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
| line_mean
float64 0.5
100
| line_max
int64 1
1k
| alpha_frac
float64 0.25
1
| autogenerated
bool 1
class |
---|---|---|---|---|---|---|---|---|---|
module.exports = {
PayloadSources: {
SERVER_ACTION: "SERVER_ACTION"
}
};
| 27AE60/entrapped | client/src/constants/app_constants.js | JavaScript | mit | 81 | 15.2 | 34 | 0.62963 | false |
// Type definitions for Electron v0.36.3
// Project: http://electron.atom.io/
// Definitions by: jedmao <https://github.com/jedmao/>, rhysd <https://rhysd.github.io>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module Electron {
/**
* This class is used to represent an image.
*/
class NativeImage {
/**
* Creates an empty NativeImage instance.
*/
static createEmpty(): NativeImage;
/**
* Creates a new NativeImage instance from file located at path.
*/
static createFromPath(path: string): NativeImage;
/**
* Creates a new NativeImage instance from buffer.
* @param scaleFactor 1.0 by default.
*/
static createFromBuffer(buffer: Buffer, scaleFactor?: number): NativeImage;
/**
* Creates a new NativeImage instance from dataURL
*/
static createFromDataURL(dataURL: string): NativeImage;
/**
* @returns Buffer Contains the image's PNG encoded data.
*/
toPng(): Buffer;
/**
* @returns Buffer Contains the image's JPEG encoded data.
*/
toJpeg(quality: number): Buffer;
/**
* @returns string The data URL of the image.
*/
toDataURL(): string;
/**
* @returns boolean Whether the image is empty.
*/
isEmpty(): boolean;
/**
* @returns {} The size of the image.
*/
getSize(): any;
/**
* Marks the image as template image.
*/
setTemplateImage(option: boolean): void;
/**
* Returns a boolean whether the image is a template image.
*/
isTemplateImage(): boolean;
}
module Clipboard {
/**
* @returns The contents of the clipboard as a NativeImage.
*/
function readImage(type?: string): NativeImage;
/**
* Writes the image into the clipboard.
*/
function writeImage(image: NativeImage, type?: string): void;
}
interface Display {
id:number;
bounds:Bounds;
workArea:Bounds;
size:Dimension;
workAreaSize:Dimension;
scaleFactor:number;
rotation:number;
touchSupport:string;
}
interface Bounds {
x:number;
y:number;
width:number;
height:number;
}
interface Dimension {
width:number;
height:number;
}
interface Point {
x:number;
y:number;
}
class Screen implements NodeJS.EventEmitter {
addListener(event: string, listener: Function): Screen;
on(event: string, listener: Function): Screen;
once(event: string, listener: Function): Screen;
removeListener(event: string, listener: Function): Screen;
removeAllListeners(event?: string): Screen;
setMaxListeners(n: number): Screen;
getMaxListeners(): number;
listeners(event: string): Function[];
emit(event: string, ...args: any[]): boolean;
listenerCount(type: string): number;
/**
* @returns The current absolute position of the mouse pointer.
*/
getCursorScreenPoint(): Point;
/**
* @returns The primary display.
*/
getPrimaryDisplay(): Display;
/**
* @returns An array of displays that are currently available.
*/
getAllDisplays(): Display[];
/**
* @returns The display nearest the specified point.
*/
getDisplayNearestPoint(point: Point): Display;
/**
* @returns The display that most closely intersects the provided bounds.
*/
getDisplayMatching(rect: Rectangle): Display;
}
/**
* The BrowserWindow class gives you ability to create a browser window.
* You can also create a window without chrome by using Frameless Window API.
*/
class BrowserWindow implements NodeJS.EventEmitter {
addListener(event: string, listener: Function): WebContents;
on(event: string, listener: Function): WebContents;
once(event: string, listener: Function): WebContents;
removeListener(event: string, listener: Function): WebContents;
removeAllListeners(event?: string): WebContents;
setMaxListeners(n: number): WebContents;
getMaxListeners(): number;
listeners(event: string): Function[];
emit(event: string, ...args: any[]): boolean;
listenerCount(type: string): number;
constructor(options?: BrowserWindowOptions);
/**
* @returns All opened browser windows.
*/
static getAllWindows(): BrowserWindow[];
/**
* @returns The window that is focused in this application.
*/
static getFocusedWindow(): BrowserWindow;
/**
* Find a window according to the webContents it owns.
*/
static fromWebContents(webContents: WebContents): BrowserWindow;
/**
* Find a window according to its ID.
*/
static fromId(id: number): BrowserWindow;
/**
* Adds devtools extension located at path. The extension will be remembered
* so you only need to call this API once, this API is not for programming use.
* @returns The extension's name.
*/
static addDevToolsExtension(path: string): string;
/**
* Remove a devtools extension.
* @param name The name of the devtools extension to remove.
*/
static removeDevToolsExtension(name: string): void;
/**
* The WebContents object this window owns, all web page related events and
* operations would be done via it.
* Note: Users should never store this object because it may become null when
* the renderer process (web page) has crashed.
*/
webContents: WebContents;
/**
* Get the WebContents of devtools of this window.
* Note: Users should never store this object because it may become null when
* the devtools has been closed.
*/
devToolsWebContents: WebContents;
/**
* Get the unique ID of this window.
*/
id: number;
/**
* Force closing the window, the unload and beforeunload event won't be emitted
* for the web page, and close event would also not be emitted for this window,
* but it would guarantee the closed event to be emitted.
* You should only use this method when the renderer process (web page) has crashed.
*/
destroy(): void;
/**
* Try to close the window, this has the same effect with user manually clicking
* the close button of the window. The web page may cancel the close though,
* see the close event.
*/
close(): void;
/**
* Focus on the window.
*/
focus(): void;
/**
* @returns Whether the window is focused.
*/
isFocused(): boolean;
/**
* Shows and gives focus to the window.
*/
show(): void;
/**
* Shows the window but doesn't focus on it.
*/
showInactive(): void;
/**
* Hides the window.
*/
hide(): void;
/**
* @returns Whether the window is visible to the user.
*/
isVisible(): boolean;
/**
* Maximizes the window.
*/
maximize(): void;
/**
* Unmaximizes the window.
*/
unmaximize(): void;
/**
* @returns Whether the window is maximized.
*/
isMaximized(): boolean;
/**
* Minimizes the window. On some platforms the minimized window will be
* shown in the Dock.
*/
minimize(): void;
/**
* Restores the window from minimized state to its previous state.
*/
restore(): void;
/**
* @returns Whether the window is minimized.
*/
isMinimized(): boolean;
/**
* Sets whether the window should be in fullscreen mode.
*/
setFullScreen(flag: boolean): void;
/**
* @returns Whether the window is in fullscreen mode.
*/
isFullScreen(): boolean;
/**
* Resizes and moves the window to width, height, x, y.
*/
setBounds(options: Rectangle): void;
/**
* @returns The window's width, height, x and y values.
*/
getBounds(): Rectangle;
/**
* Resizes the window to width and height.
*/
setSize(width: number, height: number): void;
/**
* @returns The window's width and height.
*/
getSize(): number[];
/**
* Resizes the window's client area (e.g. the web page) to width and height.
*/
setContentSize(width: number, height: number): void;
/**
* @returns The window's client area's width and height.
*/
getContentSize(): number[];
/**
* Sets the minimum size of window to width and height.
*/
setMinimumSize(width: number, height: number): void;
/**
* @returns The window's minimum width and height.
*/
getMinimumSize(): number[];
/**
* Sets the maximum size of window to width and height.
*/
setMaximumSize(width: number, height: number): void;
/**
* @returns The window's maximum width and height.
*/
getMaximumSize(): number[];
/**
* Sets whether the window can be manually resized by user.
*/
setResizable(resizable: boolean): void;
/**
* @returns Whether the window can be manually resized by user.
*/
isResizable(): boolean;
/**
* Sets whether the window should show always on top of other windows. After
* setting this, the window is still a normal window, not a toolbox window
* which can not be focused on.
*/
setAlwaysOnTop(flag: boolean): void;
/**
* @returns Whether the window is always on top of other windows.
*/
isAlwaysOnTop(): boolean;
/**
* Moves window to the center of the screen.
*/
center(): void;
/**
* Moves window to x and y.
*/
setPosition(x: number, y: number): void;
/**
* @returns The window's current position.
*/
getPosition(): number[];
/**
* Changes the title of native window to title.
*/
setTitle(title: string): void;
/**
* Note: The title of web page can be different from the title of the native window.
* @returns The title of the native window.
*/
getTitle(): string;
/**
* Starts or stops flashing the window to attract user's attention.
*/
flashFrame(flag: boolean): void;
/**
* Makes the window do not show in Taskbar.
*/
setSkipTaskbar(skip: boolean): void;
/**
* Enters or leaves the kiosk mode.
*/
setKiosk(flag: boolean): void;
/**
* @returns Whether the window is in kiosk mode.
*/
isKiosk(): boolean;
/**
* Sets the pathname of the file the window represents, and the icon of the
* file will show in window's title bar.
* Note: This API is available only on OS X.
*/
setRepresentedFilename(filename: string): void;
/**
* Note: This API is available only on OS X.
* @returns The pathname of the file the window represents.
*/
getRepresentedFilename(): string;
/**
* Specifies whether the window’s document has been edited, and the icon in
* title bar will become grey when set to true.
* Note: This API is available only on OS X.
*/
setDocumentEdited(edited: boolean): void;
/**
* Note: This API is available only on OS X.
* @returns Whether the window's document has been edited.
*/
isDocumentEdited(): boolean;
reloadIgnoringCache(): void;
/**
* Starts inspecting element at position (x, y).
*/
inspectElement(x: number, y: number): void;
focusOnWebView(): void;
blurWebView(): void;
/**
* Captures the snapshot of page within rect, upon completion the callback
* will be called. Omitting the rect would capture the whole visible page.
* Note: Be sure to read documents on remote buffer in remote if you are going
* to use this API in renderer process.
* @param callback Supplies the image that stores data of the snapshot.
*/
capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void;
capturePage(callback: (image: NativeImage) => void): void;
/**
* Same with webContents.print([options])
*/
print(options?: {
silent?: boolean;
printBackground?: boolean;
}): void;
/**
* Same with webContents.printToPDF([options])
*/
printToPDF(options: {
marginsType?: number;
pageSize?: string;
printBackground?: boolean;
printSelectionOnly?: boolean;
landscape?: boolean;
}, callback: (error: Error, data: Buffer) => void): void;
/**
* Same with webContents.loadURL(url).
*/
loadURL(url: string, options?: {
httpReferrer?: string;
userAgent?: string;
}): void;
/**
* Same with webContents.reload.
*/
reload(): void;
/**
* Sets the menu as the window top menu.
* Note: This API is not available on OS X.
*/
setMenu(menu: Menu): void;
/**
* Sets the progress value in the progress bar.
* On Linux platform, only supports Unity desktop environment, you need to
* specify the *.desktop file name to desktopName field in package.json.
* By default, it will assume app.getName().desktop.
* @param progress Valid range is [0, 1.0]. If < 0, the progress bar is removed.
* If greater than 0, it becomes indeterminate.
*/
setProgressBar(progress: number): void;
/**
* Sets a 16px overlay onto the current Taskbar icon, usually used to convey
* some sort of application status or to passively notify the user.
* Note: This API is only available on Windows 7 or above.
* @param overlay The icon to display on the bottom right corner of the Taskbar
* icon. If this parameter is null, the overlay is cleared
* @param description Provided to Accessibility screen readers.
*/
setOverlayIcon(overlay: NativeImage, description: string): void;
/**
* Shows pop-up dictionary that searches the selected word on the page.
* Note: This API is available only on OS X.
*/
showDefinitionForSelection(): void;
/**
* Sets whether the window menu bar should hide itself automatically. Once set
* the menu bar will only show when users press the single Alt key.
* If the menu bar is already visible, calling setAutoHideMenuBar(true) won't
* hide it immediately.
*/
setAutoHideMenuBar(hide: boolean): void;
/**
* @returns Whether menu bar automatically hides itself.
*/
isMenuBarAutoHide(): boolean;
/**
* Sets whether the menu bar should be visible. If the menu bar is auto-hide,
* users can still bring up the menu bar by pressing the single Alt key.
*/
setMenuBarVisibility(visibile: boolean): void;
/**
* @returns Whether the menu bar is visible.
*/
isMenuBarVisible(): boolean;
/**
* Sets whether the window should be visible on all workspaces.
* Note: This API does nothing on Windows.
*/
setVisibleOnAllWorkspaces(visible: boolean): void;
/**
* Note: This API always returns false on Windows.
* @returns Whether the window is visible on all workspaces.
*/
isVisibleOnAllWorkspaces(): boolean;
}
interface WebPreferences {
nodeIntegration?: boolean;
preload?: string;
session?: Session;
partition?: string;
zoomFactor?: number;
javascript?: boolean;
webSecurity?: boolean;
allowDisplayingInsecureContent?: boolean;
allowRunningInsecureContent?: boolean;
images?: boolean;
textAreasAreResizable?: boolean;
webgl?: boolean;
webaudio?: boolean;
plugins?: boolean;
experimentalFeatures?: boolean;
experimentalCanvasFeatures?: boolean;
directWrite?: boolean;
blinkFeatures?: string;
}
interface BrowserWindowOptions extends Rectangle {
useContentSize?: boolean;
center?: boolean;
minWidth?: number;
minHeight?: number;
maxWidth?: number;
maxHeight?: number;
resizable?: boolean;
alwaysOnTop?: boolean;
fullscreen?: boolean;
skipTaskbar?: boolean;
kiosk?: boolean;
title?: string;
icon?: NativeImage|string;
show?: boolean;
frame?: boolean;
acceptFirstMouse?: boolean;
disableAutoHideCursor?: boolean;
autoHideMenuBar?: boolean;
enableLargerThanScreen?: boolean;
backgroundColor?: string;
darkTheme?: boolean;
preload?: string;
transparent?: boolean;
type?: string;
titleBarStyle?: string;
webPreferences?: WebPreferences;
}
interface Rectangle {
x?: number;
y?: number;
width?: number;
height?: number;
}
/**
* A WebContents is responsible for rendering and controlling a web page.
*/
class WebContents implements NodeJS.EventEmitter {
addListener(event: string, listener: Function): WebContents;
on(event: string, listener: Function): WebContents;
once(event: string, listener: Function): WebContents;
removeListener(event: string, listener: Function): WebContents;
removeAllListeners(event?: string): WebContents;
setMaxListeners(n: number): WebContents;
getMaxListeners(): number;
listeners(event: string): Function[];
emit(event: string, ...args: any[]): boolean;
listenerCount(type: string): number;
/**
* Loads the url in the window.
* @param url Must contain the protocol prefix (e.g., the http:// or file://).
*/
loadURL(url: string, options?: {
httpReferrer?: string;
userAgent?: string;
}): void;
/**
* @returns The URL of current web page.
*/
getURL(): string;
/**
* @returns The title of web page.
*/
getTitle(): string;
/**
* @returns The favicon of the web page.
*/
getFavicon(): NativeImage;
/**
* @returns Whether web page is still loading resources.
*/
isLoading(): boolean;
/**
* @returns Whether web page is waiting for a first-response for the main
* resource of the page.
*/
isWaitingForResponse(): boolean;
/**
* Stops any pending navigation.
*/
stop(): void;
/**
* Reloads current page.
*/
reload(): void;
/**
* Reloads current page and ignores cache.
*/
reloadIgnoringCache(): void;
/**
* @returns Whether the web page can go back.
*/
canGoBack(): boolean;
/**
* @returns Whether the web page can go forward.
*/
canGoForward(): boolean;
/**
* @returns Whether the web page can go to offset.
*/
canGoToOffset(offset: number): boolean;
/**
* Makes the web page go back.
*/
goBack(): void;
/**
* Makes the web page go forward.
*/
goForward(): void;
/**
* Navigates to the specified absolute index.
*/
goToIndex(index: number): void;
/**
* Navigates to the specified offset from the "current entry".
*/
goToOffset(offset: number): void;
/**
* @returns Whether the renderer process has crashed.
*/
isCrashed(): boolean;
/**
* Overrides the user agent for this page.
*/
setUserAgent(userAgent: string): void;
/**
* Injects CSS into this page.
*/
insertCSS(css: string): void;
/**
* Evaluates code in page.
* @param code Code to evaluate.
*/
executeJavaScript(code: string): void;
/**
* Executes Edit -> Undo command in page.
*/
undo(): void;
/**
* Executes Edit -> Redo command in page.
*/
redo(): void;
/**
* Executes Edit -> Cut command in page.
*/
cut(): void;
/**
* Executes Edit -> Copy command in page.
*/
copy(): void;
/**
* Executes Edit -> Paste command in page.
*/
paste(): void;
/**
* Executes Edit -> Delete command in page.
*/
delete(): void;
/**
* Executes Edit -> Select All command in page.
*/
selectAll(): void;
/**
* Executes Edit -> Unselect command in page.
*/
unselect(): void;
/**
* Executes Edit -> Replace command in page.
*/
replace(text: string): void;
/**
* Executes Edit -> Replace Misspelling command in page.
*/
replaceMisspelling(text: string): void;
/**
* Checks if any serviceworker is registered.
*/
hasServiceWorker(callback: (hasServiceWorker: boolean) => void): void;
/**
* Unregisters any serviceworker if present.
*/
unregisterServiceWorker(callback:
/**
* @param isFulfilled Whether the JS promise is fulfilled.
*/
(isFulfilled: boolean) => void): void;
/**
*
* Prints window's web page. When silent is set to false, Electron will pick up system's default printer and default settings for printing.
* Calling window.print() in web page is equivalent to call WebContents.print({silent: false, printBackground: false}).
* Note:
* On Windows, the print API relies on pdf.dll. If your application doesn't need print feature, you can safely remove pdf.dll in saving binary size.
*/
print(options?: {
/**
* Don't ask user for print settings, defaults to false
*/
silent?: boolean;
/**
* Also prints the background color and image of the web page, defaults to false.
*/
printBackground: boolean;
}): void;
/**
* Prints windows' web page as PDF with Chromium's preview printing custom settings.
*/
printToPDF(options: {
/**
* Specify the type of margins to use. Default is 0.
* 0 - default
* 1 - none
* 2 - minimum
*/
marginsType?: number;
/**
* String - Specify page size of the generated PDF. Default is A4.
* A4
* A3
* Legal
* Letter
* Tabloid
*/
pageSize?: string;
/**
* Whether to print CSS backgrounds. Default is false.
*/
printBackground?: boolean;
/**
* Whether to print selection only. Default is false.
*/
printSelectionOnly?: boolean;
/**
* true for landscape, false for portrait. Default is false.
*/
landscape?: boolean;
},
/**
* Callback function on completed converting to PDF.
* error Error
* data Buffer - PDF file content
*/
callback: (error: Error, data: Buffer) => void): void;
/**
* Adds the specified path to DevTools workspace.
*/
addWorkSpace(path: string): void;
/**
* Removes the specified path from DevTools workspace.
*/
removeWorkSpace(path: string): void;
/**
* Opens the developer tools.
*/
openDevTools(options?: {
/**
* Opens devtools in a new window.
*/
detach?: boolean;
}): void;
/**
* Closes the developer tools.
*/
closeDevTools(): void;
/**
* Returns whether the developer tools are opened.
*/
isDevToolsOpened(): boolean;
/**
* Returns whether the developer tools are focussed.
*/
isDevToolsFocused(): boolean;
/**
* Toggle the developer tools.
*/
toggleDevTools(): void;
/**
* Starts inspecting element at position (x, y).
*/
inspectElement(x: number, y: number): void;
/**
* Send args.. to the web page via channel in asynchronous message, the web page
* can handle it by listening to the channel event of ipc module.
* Note:
* 1. The IPC message handler in web pages do not have a event parameter,
* which is different from the handlers on the main process.
* 2. There is no way to send synchronous messages from the main process
* to a renderer process, because it would be very easy to cause dead locks.
*/
send(channel: string, ...args: any[]): void;
}
/**
* The Menu class is used to create native menus that can be used as application
* menus and context menus. Each menu consists of multiple menu items, and each
* menu item can have a submenu.
*/
class Menu {
/**
* Creates a new menu.
*/
constructor();
/**
* Sets menu as the application menu on OS X. On Windows and Linux, the menu
* will be set as each window's top menu.
*/
static setApplicationMenu(menu: Menu): void;
/**
* Sends the action to the first responder of application, this is used for
* emulating default Cocoa menu behaviors, usually you would just use the
* selector property of MenuItem.
*
* Note: This method is OS X only.
*/
static sendActionToFirstResponder(action: string): void;
/**
* @param template Generally, just an array of options for constructing MenuItem.
* You can also attach other fields to element of the template, and they will
* become properties of the constructed menu items.
*/
static buildFromTemplate(template: MenuItemOptions[]): Menu;
/**
* Popups this menu as a context menu in the browserWindow. You can optionally
* provide a (x,y) coordinate to place the menu at, otherwise it will be placed
* at the current mouse cursor position.
* @param x Horizontal coordinate where the menu will be placed.
* @param y Vertical coordinate where the menu will be placed.
*/
popup(browserWindow: BrowserWindow, x?: number, y?: number): void;
/**
* Appends the menuItem to the menu.
*/
append(menuItem: MenuItem): void;
/**
* Inserts the menuItem to the pos position of the menu.
*/
insert(position: number, menuItem: MenuItem): void;
items: MenuItem[];
}
class MenuItem {
constructor(options?: MenuItemOptions);
options: MenuItemOptions;
}
interface MenuItemOptions {
/**
* Callback when the menu item is clicked.
*/
click?: Function;
/**
* Call the selector of first responder when clicked (OS X only).
*/
selector?: string;
/**
* Can be normal, separator, submenu, checkbox or radio.
*/
type?: string;
label?: string;
sublabel?: string;
/**
* An accelerator is string that represents a keyboard shortcut, it can contain
* multiple modifiers and key codes, combined by the + character.
*
* Examples:
* Command+A
* Ctrl+Shift+Z
*
* Platform notice: On Linux and Windows, the Command key would not have any effect,
* you can use CommandOrControl which represents Command on OS X and Control on
* Linux and Windows to define some accelerators.
*
* Available modifiers:
* Command (or Cmd for short)
* Control (or Ctrl for short)
* CommandOrControl (or CmdOrCtrl for short)
* Alt
* Shift
*
* Available key codes:
* 0 to 9
* A to Z
* F1 to F24
* Punctuations like ~, !, @, #, $, etc.
* Plus
* Space
* Backspace
* Delete
* Insert
* Return (or Enter as alias)
* Up, Down, Left and Right
* Home and End
* PageUp and PageDown
* Escape (or Esc for short)
* VolumeUp, VolumeDown and VolumeMute
* MediaNextTrack, MediaPreviousTrack, MediaStop and MediaPlayPause
*/
accelerator?: string;
/**
* In Electron for the APIs that take images, you can pass either file paths
* or NativeImage instances. When passing null, an empty image will be used.
*/
icon?: NativeImage|string;
enabled?: boolean;
visible?: boolean;
checked?: boolean;
/**
* Should be specified for submenu type menu item, when it's specified the
* type: 'submenu' can be omitted for the menu item
*/
submenu?: Menu|MenuItemOptions[];
/**
* Unique within a single menu. If defined then it can be used as a reference
* to this item by the position attribute.
*/
id?: string;
/**
* This field allows fine-grained definition of the specific location within
* a given menu.
*/
position?: string;
/**
* Define the action of the menu item, when specified the click property will be ignored
*/
role?: string;
}
class BrowserWindowProxy {
/**
* Removes focus from the child window.
*/
blur(): void;
/**
* Forcefully closes the child window without calling its unload event.
*/
close(): void;
/**
* Set to true after the child window gets closed.
*/
closed: boolean;
/**
* Evaluates the code in the child window.
*/
eval(code: string): void;
/**
* Focuses the child window (brings the window to front).
*/
focus(): void;
/**
* Sends a message to the child window with the specified origin or * for no origin preference.
* In addition to these methods, the child window implements window.opener object with no
* properties and a single method.
*/
postMessage(message: string, targetOrigin: string): void;
}
class App implements NodeJS.EventEmitter {
addListener(event: string, listener: Function): App;
on(event: string, listener: Function): App;
once(event: string, listener: Function): App;
removeListener(event: string, listener: Function): App;
removeAllListeners(event?: string): App;
setMaxListeners(n: number): App;
getMaxListeners(): number;
listeners(event: string): Function[];
emit(event: string, ...args: any[]): boolean;
listenerCount(type: string): number;
/**
* Try to close all windows. The before-quit event will first be emitted.
* If all windows are successfully closed, the will-quit event will be emitted
* and by default the application would be terminated.
*
* This method guarantees all beforeunload and unload handlers are correctly
* executed. It is possible that a window cancels the quitting by returning
* false in beforeunload handler.
*/
quit(): void;
/**
* Quit the application directly, it will not try to close all windows so
* cleanup code will not run.
*/
terminate(): void;
/**
* Returns the current application directory.
*/
getAppPath(): string;
/**
* @param name One of: home, appData, userData, cache, userCache, temp, userDesktop, exe, module
* @returns The path to a special directory or file associated with name.
* On failure an Error would throw.
*/
getPath(name: string): string;
/**
* Overrides the path to a special directory or file associated with name.
* If the path specifies a directory that does not exist, the directory will
* be created by this method. On failure an Error would throw.
*
* You can only override paths of names defined in app.getPath.
*
* By default web pages' cookies and caches will be stored under userData
* directory, if you want to change this location, you have to override the
* userData path before the ready event of app module gets emitted.
*/
setPath(name: string, path: string): void;
/**
* @returns The version of loaded application, if no version is found in
* application's package.json, the version of current bundle or executable.
*/
getVersion(): string;
/**
*
* @returns The current application's name, the name in package.json would be used.
* Usually the name field of package.json is a short lowercased name, according to
* the spec of npm modules. So usually you should also specify a productName field,
* which is your application's full capitalized name, and it will be preferred over
* name by Electron.
*/
getName(): string;
/**
* @returns The current application locale.
**/
getLocale(): string;
/**
* Resolves the proxy information for url, the callback would be called with
* callback(proxy) when the request is done.
*/
resolveProxy(url: string, callback: Function): void;
/**
* Adds path to recent documents list.
*
* This list is managed by the system, on Windows you can visit the list from
* task bar, and on Mac you can visit it from dock menu.
*/
addRecentDocument(path: string): void;
/**
* Clears the recent documents list.
*/
clearRecentDocuments(): void;
/**
* Adds tasks to the Tasks category of JumpList on Windows.
*
* Note: This API is only available on Windows.
*/
setUserTasks(tasks: Task[]): void;
dock: Dock;
commandLine: CommandLine;
/**
* This method makes your application a Single Instance Application instead of allowing
* multiple instances of your app to run, this will ensure that only a single instance
* of your app is running, and other instances signal this instance and exit.
*/
makeSingleInstance(callback: (args: string[], workingDirectory: string) => boolean): boolean;
setAppUserModelId(id: string): void;
}
interface CommandLine {
/**
* Append a switch [with optional value] to Chromium's command line.
*
* Note: This will not affect process.argv, and is mainly used by developers
* to control some low-level Chromium behaviors.
*/
appendSwitch(_switch: string, value?: string|number): void;
/**
* Append an argument to Chromium's command line. The argument will quoted properly.
*
* Note: This will not affect process.argv.
*/
appendArgument(value: any): void;
}
interface Dock {
/**
* When critical is passed, the dock icon will bounce until either the
* application becomes active or the request is canceled.
*
* When informational is passed, the dock icon will bounce for one second.
* The request, though, remains active until either the application becomes
* active or the request is canceled.
*
* Note: This API is only available on Mac.
* @param type Can be critical or informational, the default is informational.
* @returns An ID representing the request
*/
bounce(type?: string): number;
/**
* Cancel the bounce of id.
*
* Note: This API is only available on Mac.
*/
cancelBounce(id: number): void;
/**
* Sets the string to be displayed in the dock’s badging area.
*
* Note: This API is only available on Mac.
*/
setBadge(text: string): void;
/**
* Returns the badge string of the dock.
*
* Note: This API is only available on Mac.
*/
getBadge(): string;
/**
* Hides the dock icon.
*
* Note: This API is only available on Mac.
*/
hide(): void;
/**
* Shows the dock icon.
*
* Note: This API is only available on Mac.
*/
show(): void;
/**
* Sets the application dock menu.
*
* Note: This API is only available on Mac.
*/
setMenu(menu: Menu): void;
/**
* Sets the image associated with this dock icon.
*
* Note: This API is only available on Mac.
*/
setIcon(icon: NativeImage | string): void;
}
interface Task {
/**
* Path of the program to execute, usually you should specify process.execPath
* which opens current program.
*/
program: string;
/**
* The arguments of command line when program is executed.
*/
arguments: string;
/**
* The string to be displayed in a JumpList.
*/
title: string;
/**
* Description of this task.
*/
description?: string;
/**
* The absolute path to an icon to be displayed in a JumpList, it can be
* arbitrary resource file that contains an icon, usually you can specify
* process.execPath to show the icon of the program.
*/
iconPath: string;
/**
* The icon index in the icon file. If an icon file consists of two or more
* icons, set this value to identify the icon. If an icon file consists of
* one icon, this value is 0.
*/
iconIndex?: number;
commandLine?: CommandLine;
dock?: Dock;
}
class AutoUpdater implements NodeJS.EventEmitter {
addListener(event: string, listener: Function): AutoUpdater;
on(event: string, listener: Function): AutoUpdater;
once(event: string, listener: Function): AutoUpdater;
removeListener(event: string, listener: Function): AutoUpdater;
removeAllListeners(event?: string): AutoUpdater;
setMaxListeners(n: number): AutoUpdater;
getMaxListeners(): number;
listeners(event: string): Function[];
emit(event: string, ...args: any[]): boolean;
listenerCount(type: string): number;
/**
* Set the url and initialize the auto updater.
* The url cannot be changed once it is set.
*/
setFeedURL(url: string): void;
/**
* Ask the server whether there is an update, you have to call setFeedURL
* before using this API
*/
checkForUpdates(): any;
}
module Dialog {
/**
* @param callback If supplied, the API call will be asynchronous.
* @returns On success, returns an array of file paths chosen by the user,
* otherwise returns undefined.
*/
export function showOpenDialog(
browserWindow?: BrowserWindow,
options?: OpenDialogOptions,
callback?: (fileNames: string[]) => void
): string[];
export function showOpenDialog(
options?: OpenDialogOptions,
callback?: (fileNames: string[]) => void
): string[];
interface OpenDialogOptions {
title?: string;
defaultPath?: string;
/**
* File types that can be displayed or selected.
*/
filters?: {
name: string;
extensions: string[];
}[];
/**
* Contains which features the dialog should use, can contain openFile,
* openDirectory, multiSelections and createDirectory
*/
properties?: string|string[];
}
interface SaveDialogOptions {
title?: string;
defaultPath?: string;
/**
* File types that can be displayed, see dialog.showOpenDialog for an example.
*/
filters?: {
name: string;
extensions: string[];
}[];
}
/**
* @param browserWindow
* @param options
* @param callback If supplied, the API call will be asynchronous.
* @returns On success, returns the path of file chosen by the user, otherwise
* returns undefined.
*/
export function showSaveDialog(browserWindow?: BrowserWindow, options?: SaveDialogOptions, callback?: (fileName: string) => void): string;
/**
* Shows a message box. It will block until the message box is closed. It returns .
* @param callback If supplied, the API call will be asynchronous.
* @returns The index of the clicked button.
*/
export function showMessageBox(
browserWindow?: BrowserWindow,
options?: ShowMessageBoxOptions,
callback?: (response: any) => void
): number;
export function showMessageBox(
options: ShowMessageBoxOptions,
callback?: (response: any) => void
): number;
export interface ShowMessageBoxOptions {
/**
* Can be "none", "info" or "warning".
*/
type?: string;
/**
* Texts for buttons.
*/
buttons?: string[];
/**
* Title of the message box (some platforms will not show it).
*/
title?: string;
/**
* Contents of the message box.
*/
message?: string;
/**
* Extra information of the message.
*/
detail?: string;
icon?: NativeImage;
noLink?: boolean;
cancelId?: number;
}
}
class Tray implements NodeJS.EventEmitter {
addListener(event: string, listener: Function): Tray;
on(event: string, listener: Function): Tray;
once(event: string, listener: Function): Tray;
removeListener(event: string, listener: Function): Tray;
removeAllListeners(event?: string): Tray;
setMaxListeners(n: number): Tray;
getMaxListeners(): number;
listeners(event: string): Function[];
emit(event: string, ...args: any[]): boolean;
listenerCount(type: string): number;
/**
* Creates a new tray icon associated with the image.
*/
constructor(image: NativeImage|string);
/**
* Destroys the tray icon immediately.
*/
destroy(): void;
/**
* Sets the image associated with this tray icon.
*/
setImage(image: NativeImage|string): void;
/**
* Sets the image associated with this tray icon when pressed.
*/
setPressedImage(image: NativeImage): void;
/**
* Sets the hover text for this tray icon.
*/
setToolTip(toolTip: string): void;
/**
* Sets the title displayed aside of the tray icon in the status bar.
* Note: This is only implemented on OS X.
*/
setTitle(title: string): void;
/**
* Sets whether the tray icon is highlighted when it is clicked.
* Note: This is only implemented on OS X.
*/
setHighlightMode(highlight: boolean): void;
/**
* Displays a tray balloon.
* Note: This is only implemented on Windows.
*/
displayBalloon(options?: {
icon?: NativeImage;
title?: string;
content?: string;
}): void;
/**
* Sets the context menu for this icon.
*/
setContextMenu(menu: Menu): void;
}
interface Clipboard {
/**
* @returns The contents of the clipboard as plain text.
*/
readText(type?: string): string;
/**
* Writes the text into the clipboard as plain text.
*/
writeText(text: string, type?: string): void;
/**
* @returns The contents of the clipboard as a NativeImage.
*/
readImage: typeof Electron.Clipboard.readImage;
/**
* Writes the image into the clipboard.
*/
writeImage: typeof Electron.Clipboard.writeImage;
/**
* Clears everything in clipboard.
*/
clear(type?: string): void;
/**
* Note: This API is experimental and could be removed in future.
* @returns Whether the clipboard has data in the specified format.
*/
has(format: string, type?: string): boolean;
/**
* Reads the data in the clipboard of the specified format.
* Note: This API is experimental and could be removed in future.
*/
read(format: string, type?: string): any;
}
interface CrashReporterStartOptions {
/**
* Default: Electron
*/
productName?: string;
companyName: string;
/**
* URL that crash reports would be sent to as POST.
*/
submitURL: string;
/**
* Send the crash report without user interaction.
* Default: true.
*/
autoSubmit?: boolean;
/**
* Default: false.
*/
ignoreSystemCrashHandler?: boolean;
/**
* An object you can define which content will be send along with the report.
* Only string properties are send correctly.
* Nested objects are not supported.
*/
extra?: {[prop: string]: string};
}
interface CrashReporterPayload extends Object {
/**
* E.g., "electron-crash-service".
*/
rept: string;
/**
* The version of Electron.
*/
ver: string;
/**
* E.g., "win32".
*/
platform: string;
/**
* E.g., "renderer".
*/
process_type: string;
ptime: number;
/**
* The version in package.json.
*/
_version: string;
/**
* The product name in the crashReporter options object.
*/
_productName: string;
/**
* Name of the underlying product. In this case, Electron.
*/
prod: string;
/**
* The company name in the crashReporter options object.
*/
_companyName: string;
/**
* The crashreporter as a file.
*/
upload_file_minidump: File;
}
interface CrashReporter {
start(options: CrashReporterStartOptions): void;
/**
* @returns The date and ID of the last crash report. When there was no crash report
* sent or the crash reporter is not started, null will be returned.
*/
getLastCrashReport(): CrashReporterPayload;
}
interface Shell {
/**
* Show the given file in a file manager. If possible, select the file.
*/
showItemInFolder(fullPath: string): void;
/**
* Open the given file in the desktop's default manner.
*/
openItem(fullPath: string): void;
/**
* Open the given external protocol URL in the desktop's default manner
* (e.g., mailto: URLs in the default mail user agent).
*/
openExternal(url: string): void;
/**
* Move the given file to trash and returns boolean status for the operation.
*/
moveItemToTrash(fullPath: string): void;
/**
* Play the beep sound.
*/
beep(): void;
}
// Type definitions for renderer process
export class IpcRenderer implements NodeJS.EventEmitter {
addListener(event: string, listener: Function): IpcRenderer;
on(event: string, listener: Function): IpcRenderer;
once(event: string, listener: Function): IpcRenderer;
removeListener(event: string, listener: Function): IpcRenderer;
removeAllListeners(event?: string): IpcRenderer;
setMaxListeners(n: number): IpcRenderer;
getMaxListeners(): number;
listeners(event: string): Function[];
emit(event: string, ...args: any[]): boolean;
listenerCount(type: string): number;
/**
* Send ...args to the renderer via channel in asynchronous message, the main
* process can handle it by listening to the channel event of ipc module.
*/
send(channel: string, ...args: any[]): void;
/**
* Send ...args to the renderer via channel in synchronous message, and returns
* the result sent from main process. The main process can handle it by listening
* to the channel event of ipc module, and returns by setting event.returnValue.
* Note: Usually developers should never use this API, since sending synchronous
* message would block the whole renderer process.
* @returns The result sent from the main process.
*/
sendSync(channel: string, ...args: any[]): string;
/**
* Like ipc.send but the message will be sent to the host page instead of the main process.
* This is mainly used by the page in <webview> to communicate with host page.
*/
sendToHost(channel: string, ...args: any[]): void;
}
class IPCMain implements NodeJS.EventEmitter {
addListener(event: string, listener: Function): IPCMain;
once(event: string, listener: Function): IPCMain;
removeListener(event: string, listener: Function): IPCMain;
removeAllListeners(event?: string): IPCMain;
setMaxListeners(n: number): IPCMain;
getMaxListeners(): number;
listeners(event: string): Function[];
emit(event: string, ...args: any[]): boolean;
listenerCount(type: string): number;
on(event: string, listener: (event: IPCMainEvent, ...args: any[]) => any): IPCMain;
}
interface IPCMainEvent {
returnValue?: any;
sender: WebContents;
}
interface Remote extends CommonElectron {
/**
* @returns The object returned by require(module) in the main process.
*/
require(module: string): any;
/**
* @returns The BrowserWindow object which this web page belongs to.
*/
getCurrentWindow(): BrowserWindow;
/**
* @returns The global variable of name (e.g. global[name]) in the main process.
*/
getGlobal(name: string): any;
/**
* Returns the process object in the main process. This is the same as
* remote.getGlobal('process'), but gets cached.
*/
process: NodeJS.Process;
}
interface WebFrame {
/**
* Changes the zoom factor to the specified factor, zoom factor is
* zoom percent / 100, so 300% = 3.0.
*/
setZoomFactor(factor: number): void;
/**
* @returns The current zoom factor.
*/
getZoomFactor(): number;
/**
* Changes the zoom level to the specified level, 0 is "original size", and each
* increment above or below represents zooming 20% larger or smaller to default
* limits of 300% and 50% of original size, respectively.
*/
setZoomLevel(level: number): void;
/**
* @returns The current zoom level.
*/
getZoomLevel(): number;
/**
* Sets a provider for spell checking in input fields and text areas.
*/
setSpellCheckProvider(language: string, autoCorrectWord: boolean, provider: {
/**
* @returns Whether the word passed is correctly spelled.
*/
spellCheck: (text: string) => boolean;
}): void;
/**
* Sets the scheme as secure scheme. Secure schemes do not trigger mixed content
* warnings. For example, https and data are secure schemes because they cannot be
* corrupted by active network attackers.
*/
registerURLSchemeAsSecure(scheme: string): void;
/**
* Inserts text to the focused element.
*/
insertText(text: string): void;
/**
* Evaluates `code` in page.
* In the browser window some HTML APIs like `requestFullScreen` can only be
* invoked by a gesture from the user. Setting `userGesture` to `true` will remove
* this limitation.
*/
executeJavaScript(code: string, userGesture?: boolean): void;
}
// Type definitions for main process
interface ContentTracing {
/**
* Get a set of category groups. The category groups can change as new code paths are reached.
* @param callback Called once all child processes have acked to the getCategories request.
*/
getCategories(callback: (categoryGroups: any[]) => void): void;
/**
* Start recording on all processes. Recording begins immediately locally, and asynchronously
* on child processes as soon as they receive the EnableRecording request.
* @param categoryFilter A filter to control what category groups should be traced.
* A filter can have an optional "-" prefix to exclude category groups that contain
* a matching category. Having both included and excluded category patterns in the
* same list would not be supported.
* @param options controls what kind of tracing is enabled, it could be a OR-ed
* combination of tracing.DEFAULT_OPTIONS, tracing.ENABLE_SYSTRACE, tracing.ENABLE_SAMPLING
* and tracing.RECORD_CONTINUOUSLY.
* @param callback Called once all child processes have acked to the startRecording request.
*/
startRecording(categoryFilter: string, options: number, callback: Function): void;
/**
* Stop recording on all processes. Child processes typically are caching trace data and
* only rarely flush and send trace data back to the main process. That is because it may
* be an expensive operation to send the trace data over IPC, and we would like to avoid
* much runtime overhead of tracing. So, to end tracing, we must asynchronously ask all
* child processes to flush any pending trace data.
* @param resultFilePath Trace data will be written into this file if it is not empty,
* or into a temporary file.
* @param callback Called once all child processes have acked to the stopRecording request.
*/
stopRecording(resultFilePath: string, callback:
/**
* @param filePath A file that contains the traced data.
*/
(filePath: string) => void
): void;
/**
* Start monitoring on all processes. Monitoring begins immediately locally, and asynchronously
* on child processes as soon as they receive the startMonitoring request.
* @param callback Called once all child processes have acked to the startMonitoring request.
*/
startMonitoring(categoryFilter: string, options: number, callback: Function): void;
/**
* Stop monitoring on all processes.
* @param callback Called once all child processes have acked to the stopMonitoring request.
*/
stopMonitoring(callback: Function): void;
/**
* Get the current monitoring traced data. Child processes typically are caching trace data
* and only rarely flush and send trace data back to the main process. That is because it may
* be an expensive operation to send the trace data over IPC, and we would like to avoid much
* runtime overhead of tracing. So, to end tracing, we must asynchronously ask all child
* processes to flush any pending trace data.
* @param callback Called once all child processes have acked to the captureMonitoringSnapshot request.
*/
captureMonitoringSnapshot(resultFilePath: string, callback:
/**
* @param filePath A file that contains the traced data
* @returns {}
*/
(filePath: string) => void
): void;
/**
* Get the maximum across processes of trace buffer percent full state.
* @param callback Called when the TraceBufferUsage value is determined.
*/
getTraceBufferUsage(callback: Function): void;
/**
* @param callback Called every time the given event occurs on any process.
*/
setWatchEvent(categoryName: string, eventName: string, callback: Function): void;
/**
* Cancel the watch event. If tracing is enabled, this may race with the watch event callback.
*/
cancelWatchEvent(): void;
DEFAULT_OPTIONS: number;
ENABLE_SYSTRACE: number;
ENABLE_SAMPLING: number;
RECORD_CONTINUOUSLY: number;
}
interface Dialog {
/**
* @param callback If supplied, the API call will be asynchronous.
* @returns On success, returns an array of file paths chosen by the user,
* otherwise returns undefined.
*/
showOpenDialog: typeof Electron.Dialog.showOpenDialog;
/**
* @param callback If supplied, the API call will be asynchronous.
* @returns On success, returns the path of file chosen by the user, otherwise
* returns undefined.
*/
showSaveDialog: typeof Electron.Dialog.showSaveDialog;
/**
* Shows a message box. It will block until the message box is closed. It returns .
* @param callback If supplied, the API call will be asynchronous.
* @returns The index of the clicked button.
*/
showMessageBox: typeof Electron.Dialog.showMessageBox;
/**
* Runs a modal dialog that shows an error message. This API can be called safely
* before the ready event of app module emits, it is usually used to report errors
* in early stage of startup.
*/
showErrorBox(title: string, content: string): void;
}
interface GlobalShortcut {
/**
* Registers a global shortcut of accelerator.
* @param accelerator Represents a keyboard shortcut. It can contain modifiers
* and key codes, combined by the "+" character.
* @param callback Called when the registered shortcut is pressed by the user.
* @returns {}
*/
register(accelerator: string, callback: Function): void;
/**
* @param accelerator Represents a keyboard shortcut. It can contain modifiers
* and key codes, combined by the "+" character.
* @returns Whether the accelerator is registered.
*/
isRegistered(accelerator: string): boolean;
/**
* Unregisters the global shortcut of keycode.
* @param accelerator Represents a keyboard shortcut. It can contain modifiers
* and key codes, combined by the "+" character.
*/
unregister(accelerator: string): void;
/**
* Unregisters all the global shortcuts.
*/
unregisterAll(): void;
}
class RequestFileJob {
/**
* Create a request job which would query a file of path and set corresponding mime types.
*/
constructor(path: string);
}
class RequestStringJob {
/**
* Create a request job which sends a string as response.
*/
constructor(options?: {
/**
* Default is "text/plain".
*/
mimeType?: string;
/**
* Default is "UTF-8".
*/
charset?: string;
data?: string;
});
}
class RequestBufferJob {
/**
* Create a request job which accepts a buffer and sends a string as response.
*/
constructor(options?: {
/**
* Default is "application/octet-stream".
*/
mimeType?: string;
/**
* Default is "UTF-8".
*/
encoding?: string;
data?: Buffer;
});
}
interface Protocol {
registerProtocol(scheme: string, handler: (request: any) => void): void;
unregisterProtocol(scheme: string): void;
isHandledProtocol(scheme: string): boolean;
interceptProtocol(scheme: string, handler: (request: any) => void): void;
uninterceptProtocol(scheme: string): void;
RequestFileJob: typeof RequestFileJob;
RequestStringJob: typeof RequestStringJob;
RequestBufferJob: typeof RequestBufferJob;
}
interface PowerSaveBlocker {
start(type: string): number;
stop(id: number): void;
isStarted(id: number): boolean;
}
interface ClearStorageDataOptions {
origin?: string;
storages?: string[];
quotas?: string[];
}
interface NetworkEmulationOptions {
offline?: boolean;
latency?: number;
downloadThroughput?: number;
uploadThroughput?: number;
}
interface CertificateVerifyProc {
(hostname: string, cert: any, callback: (accepted: boolean) => any): any;
}
class Session {
static fromPartition(partition: string): Session;
static defaultSession: Session;
cookies: any;
clearCache(callback: Function): void;
clearStorageData(callback: Function): void;
clearStorageData(options: ClearStorageDataOptions, callback: Function): void;
flushStorageData(): void;
setProxy(config: string, callback: Function): void;
resolveProxy(url: URL, callback: (proxy: any) => any): void;
setDownloadPath(path: string): void;
enableNetworkEmulation(options: NetworkEmulationOptions): void;
disableNetworkEmulation(): void;
setCertificateVerifyProc(proc: CertificateVerifyProc): void;
webRequest: any;
}
interface CommonElectron {
clipboard: Electron.Clipboard;
crashReporter: Electron.CrashReporter;
nativeImage: typeof Electron.NativeImage;
shell: Electron.Shell;
app: Electron.App;
autoUpdater: Electron.AutoUpdater;
BrowserWindow: typeof Electron.BrowserWindow;
contentTracing: Electron.ContentTracing;
dialog: Electron.Dialog;
ipcMain: Electron.IPCMain;
globalShortcut: Electron.GlobalShortcut;
Menu: typeof Electron.Menu;
MenuItem: typeof Electron.MenuItem;
powerMonitor: NodeJS.EventEmitter;
powerSaveBlocker: Electron.PowerSaveBlocker;
protocol: Electron.Protocol;
screen: Electron.Screen;
session: Electron.Session;
Tray: typeof Electron.Tray;
hideInternalModules(): void;
}
interface DesktopCapturerOptions {
types?: string[];
thumbnailSize?: {
width: number;
height: number;
};
}
interface DesktopCapturerSource {
id: string;
name: string;
thumbnail: NativeImage;
}
interface DesktopCapturer {
getSources(options: any, callback: (error: Error, sources: DesktopCapturerSource[]) => any): void;
}
interface ElectronMainAndRenderer extends CommonElectron {
desktopCapturer: Electron.DesktopCapturer;
ipcRenderer: Electron.IpcRenderer;
remote: Electron.Remote;
webFrame: Electron.WebFrame;
}
}
interface Window {
/**
* Creates a new window.
* @returns An instance of BrowserWindowProxy class.
*/
open(url: string, frameName?: string, features?: string): Electron.BrowserWindowProxy;
}
interface File {
/**
* Exposes the real path of the filesystem.
*/
path: string;
}
declare module 'electron' {
var electron: Electron.ElectronMainAndRenderer;
export = electron;
}
interface NodeRequireFunction {
(moduleName: 'electron'): Electron.ElectronMainAndRenderer;
}
| robert396/elec-ang-tsc-boilerplate | typings/github-electron/github-electron.d.ts | TypeScript | mit | 56,083 | 28.515263 | 152 | 0.676688 | false |
Copyright 2014 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
#cast-volume-controller
This element represents the volume bars in the [CastVideos-chrome-material](https://github.com/googlecast/CastVideos-chrome-material) sample.
It's used in both `cast-player-bar` and `cast-controller-element` as the volume controller.
It fires an event to [`cast-manager`](https://github.com/googlecast/cast-manager-polymer) when volume is changed and its rendering is bound to the `volume` property.
##Setup
Use [Bower](http://bower.io/) to include the cast-volume-controller in your web app. The following
command will add the cast-volume-controller and it's dependencies to your project.
bower install --save googlecast/cast-volume-controller-polymer
##Integration
You'll need to first include
[Polymer](https://www.polymer-project.org/).
###Including the element
In your html include the element
<link rel="import"
href="bower_components/cast-volume-controller-polymer/cast-volume-controller.html">
Add the element to your HTML and bid the `volume` parameter.
<cast-volume-controller volume="[[ volume ]]"></cast-volume-controller>
| lyndeniece/tunestm | dist/bower_components/cast-volume-controller-polymer/README.md | Markdown | mit | 1,682 | 41.05 | 165 | 0.765161 | false |
// +build !nopq
package main
// including pq
import _ "github.com/lib/pq"
func init() {
drivers = append(drivers, "pq")
}
| abourget/goose | cmd/goose/pq.go | GO | mit | 126 | 11.6 | 32 | 0.642857 | false |
using System;
using System.Windows;
using System.Windows.Media.Media3D;
namespace Surfaces
{
public abstract class Surface : ModelVisual3D
{
public Surface()
{
Content = _content;
_content.Geometry = CreateMesh();
}
public static PropertyHolder<Material, Surface> MaterialProperty =
new PropertyHolder<Material, Surface>("Material", null, OnMaterialChanged);
public static PropertyHolder<Material, Surface> BackMaterialProperty =
new PropertyHolder<Material, Surface>("BackMaterial", null, OnBackMaterialChanged);
public static PropertyHolder<bool, Surface> VisibleProperty =
new PropertyHolder<bool, Surface>("Visible", true, OnVisibleChanged);
public Material Material
{
get { return MaterialProperty.Get(this); }
set { MaterialProperty.Set(this, value); }
}
public Material BackMaterial
{
get { return BackMaterialProperty.Get(this); }
set { BackMaterialProperty.Set(this, value); }
}
public bool Visible
{
get { return VisibleProperty.Get(this); }
set { VisibleProperty.Set(this, value); }
}
private static void OnMaterialChanged(Object sender, DependencyPropertyChangedEventArgs e)
{
((Surface)sender).OnMaterialChanged();
}
private static void OnBackMaterialChanged(Object sender, DependencyPropertyChangedEventArgs e)
{
((Surface)sender).OnBackMaterialChanged();
}
private static void OnVisibleChanged(Object sender, DependencyPropertyChangedEventArgs e)
{
((Surface)sender).OnVisibleChanged();
}
protected static void OnGeometryChanged(Object sender, DependencyPropertyChangedEventArgs e)
{
((Surface)sender).OnGeometryChanged();
}
private void OnMaterialChanged()
{
SetContentMaterial();
}
private void OnBackMaterialChanged()
{
SetContentBackMaterial();
}
private void OnVisibleChanged()
{
SetContentMaterial();
SetContentBackMaterial();
}
private void SetContentMaterial()
{
_content.Material = Visible ? Material : null;
}
private void SetContentBackMaterial()
{
_content.BackMaterial = Visible ? BackMaterial : null;
}
private void OnGeometryChanged()
{
_content.Geometry = CreateMesh();
}
protected abstract Geometry3D CreateMesh();
private readonly GeometryModel3D _content = new GeometryModel3D();
}
}
| dushka-dragoeva/TelerikSeson2016 | Programing C#/High-Quality-Code-Part-Two/02. Code-Tuning-and-Optimization/SolarSystem/Surface.cs | C# | mit | 2,789 | 27.752577 | 102 | 0.603801 | false |
/*-------------------------------------------------------------------------------------
*
* Copyright (c) Microsoft Corporation
*
*-------------------------------------------------------------------------------------*/
/* this ALWAYS GENERATED file contains the definitions for the interfaces */
/* File created by MIDL compiler version 8.01.0622 */
/* @@MIDL_FILE_HEADING( ) */
/* verify that the <rpcndr.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCNDR_H_VERSION__
#define __REQUIRED_RPCNDR_H_VERSION__ 475
#endif
/* verify that the <rpcsal.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCSAL_H_VERSION__
#define __REQUIRED_RPCSAL_H_VERSION__ 100
#endif
#include "rpc.h"
#include "rpcndr.h"
#ifndef __RPCNDR_H_VERSION__
#error this stub requires an updated version of <rpcndr.h>
#endif /* __RPCNDR_H_VERSION__ */
#ifndef COM_NO_WINDOWS_H
#include "windows.h"
#include "ole2.h"
#endif /*COM_NO_WINDOWS_H*/
#ifndef __d3d11_2_h__
#define __d3d11_2_h__
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
/* Forward Declarations */
#ifndef __ID3D11DeviceContext2_FWD_DEFINED__
#define __ID3D11DeviceContext2_FWD_DEFINED__
typedef interface ID3D11DeviceContext2 ID3D11DeviceContext2;
#endif /* __ID3D11DeviceContext2_FWD_DEFINED__ */
#ifndef __ID3D11Device2_FWD_DEFINED__
#define __ID3D11Device2_FWD_DEFINED__
typedef interface ID3D11Device2 ID3D11Device2;
#endif /* __ID3D11Device2_FWD_DEFINED__ */
/* header files for imported files */
#include "oaidl.h"
#include "ocidl.h"
#include "dxgi1_3.h"
#include "d3dcommon.h"
#include "d3d11_1.h"
#ifdef __cplusplus
extern "C"{
#endif
/* interface __MIDL_itf_d3d11_2_0000_0000 */
/* [local] */
#ifdef __cplusplus
}
#endif
#include "d3d11_1.h" //
#ifdef __cplusplus
extern "C"{
#endif
typedef struct D3D11_TILED_RESOURCE_COORDINATE
{
UINT X;
UINT Y;
UINT Z;
UINT Subresource;
} D3D11_TILED_RESOURCE_COORDINATE;
typedef struct D3D11_TILE_REGION_SIZE
{
UINT NumTiles;
BOOL bUseBox;
UINT Width;
UINT16 Height;
UINT16 Depth;
} D3D11_TILE_REGION_SIZE;
typedef
enum D3D11_TILE_MAPPING_FLAG
{
D3D11_TILE_MAPPING_NO_OVERWRITE = 0x1
} D3D11_TILE_MAPPING_FLAG;
typedef
enum D3D11_TILE_RANGE_FLAG
{
D3D11_TILE_RANGE_NULL = 0x1,
D3D11_TILE_RANGE_SKIP = 0x2,
D3D11_TILE_RANGE_REUSE_SINGLE_TILE = 0x4
} D3D11_TILE_RANGE_FLAG;
typedef struct D3D11_SUBRESOURCE_TILING
{
UINT WidthInTiles;
UINT16 HeightInTiles;
UINT16 DepthInTiles;
UINT StartTileIndexInOverallResource;
} D3D11_SUBRESOURCE_TILING;
#define D3D11_PACKED_TILE ( 0xffffffff )
typedef struct D3D11_TILE_SHAPE
{
UINT WidthInTexels;
UINT HeightInTexels;
UINT DepthInTexels;
} D3D11_TILE_SHAPE;
typedef struct D3D11_PACKED_MIP_DESC
{
UINT8 NumStandardMips;
UINT8 NumPackedMips;
UINT NumTilesForPackedMips;
UINT StartTileIndexInOverallResource;
} D3D11_PACKED_MIP_DESC;
typedef
enum D3D11_CHECK_MULTISAMPLE_QUALITY_LEVELS_FLAG
{
D3D11_CHECK_MULTISAMPLE_QUALITY_LEVELS_TILED_RESOURCE = 0x1
} D3D11_CHECK_MULTISAMPLE_QUALITY_LEVELS_FLAG;
typedef
enum D3D11_TILE_COPY_FLAG
{
D3D11_TILE_COPY_NO_OVERWRITE = 0x1,
D3D11_TILE_COPY_LINEAR_BUFFER_TO_SWIZZLED_TILED_RESOURCE = 0x2,
D3D11_TILE_COPY_SWIZZLED_TILED_RESOURCE_TO_LINEAR_BUFFER = 0x4
} D3D11_TILE_COPY_FLAG;
extern RPC_IF_HANDLE __MIDL_itf_d3d11_2_0000_0000_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_d3d11_2_0000_0000_v0_0_s_ifspec;
#ifndef __ID3D11DeviceContext2_INTERFACE_DEFINED__
#define __ID3D11DeviceContext2_INTERFACE_DEFINED__
/* interface ID3D11DeviceContext2 */
/* [unique][local][object][uuid] */
EXTERN_C const IID IID_ID3D11DeviceContext2;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("420d5b32-b90c-4da4-bef0-359f6a24a83a")
ID3D11DeviceContext2 : public ID3D11DeviceContext1
{
public:
virtual HRESULT STDMETHODCALLTYPE UpdateTileMappings(
/* [annotation] */
_In_ ID3D11Resource *pTiledResource,
/* [annotation] */
_In_ UINT NumTiledResourceRegions,
/* [annotation] */
_In_reads_opt_(NumTiledResourceRegions) const D3D11_TILED_RESOURCE_COORDINATE *pTiledResourceRegionStartCoordinates,
/* [annotation] */
_In_reads_opt_(NumTiledResourceRegions) const D3D11_TILE_REGION_SIZE *pTiledResourceRegionSizes,
/* [annotation] */
_In_opt_ ID3D11Buffer *pTilePool,
/* [annotation] */
_In_ UINT NumRanges,
/* [annotation] */
_In_reads_opt_(NumRanges) const UINT *pRangeFlags,
/* [annotation] */
_In_reads_opt_(NumRanges) const UINT *pTilePoolStartOffsets,
/* [annotation] */
_In_reads_opt_(NumRanges) const UINT *pRangeTileCounts,
/* [annotation] */
_In_ UINT Flags) = 0;
virtual HRESULT STDMETHODCALLTYPE CopyTileMappings(
/* [annotation] */
_In_ ID3D11Resource *pDestTiledResource,
/* [annotation] */
_In_ const D3D11_TILED_RESOURCE_COORDINATE *pDestRegionStartCoordinate,
/* [annotation] */
_In_ ID3D11Resource *pSourceTiledResource,
/* [annotation] */
_In_ const D3D11_TILED_RESOURCE_COORDINATE *pSourceRegionStartCoordinate,
/* [annotation] */
_In_ const D3D11_TILE_REGION_SIZE *pTileRegionSize,
/* [annotation] */
_In_ UINT Flags) = 0;
virtual void STDMETHODCALLTYPE CopyTiles(
/* [annotation] */
_In_ ID3D11Resource *pTiledResource,
/* [annotation] */
_In_ const D3D11_TILED_RESOURCE_COORDINATE *pTileRegionStartCoordinate,
/* [annotation] */
_In_ const D3D11_TILE_REGION_SIZE *pTileRegionSize,
/* [annotation] */
_In_ ID3D11Buffer *pBuffer,
/* [annotation] */
_In_ UINT64 BufferStartOffsetInBytes,
/* [annotation] */
_In_ UINT Flags) = 0;
virtual void STDMETHODCALLTYPE UpdateTiles(
/* [annotation] */
_In_ ID3D11Resource *pDestTiledResource,
/* [annotation] */
_In_ const D3D11_TILED_RESOURCE_COORDINATE *pDestTileRegionStartCoordinate,
/* [annotation] */
_In_ const D3D11_TILE_REGION_SIZE *pDestTileRegionSize,
/* [annotation] */
_In_ const void *pSourceTileData,
/* [annotation] */
_In_ UINT Flags) = 0;
virtual HRESULT STDMETHODCALLTYPE ResizeTilePool(
/* [annotation] */
_In_ ID3D11Buffer *pTilePool,
/* [annotation] */
_In_ UINT64 NewSizeInBytes) = 0;
virtual void STDMETHODCALLTYPE TiledResourceBarrier(
/* [annotation] */
_In_opt_ ID3D11DeviceChild *pTiledResourceOrViewAccessBeforeBarrier,
/* [annotation] */
_In_opt_ ID3D11DeviceChild *pTiledResourceOrViewAccessAfterBarrier) = 0;
virtual BOOL STDMETHODCALLTYPE IsAnnotationEnabled( void) = 0;
virtual void STDMETHODCALLTYPE SetMarkerInt(
/* [annotation] */
_In_ LPCWSTR pLabel,
INT Data) = 0;
virtual void STDMETHODCALLTYPE BeginEventInt(
/* [annotation] */
_In_ LPCWSTR pLabel,
INT Data) = 0;
virtual void STDMETHODCALLTYPE EndEvent( void) = 0;
};
#else /* C style interface */
typedef struct ID3D11DeviceContext2Vtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
ID3D11DeviceContext2 * This,
/* [in] */ REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
ID3D11DeviceContext2 * This);
ULONG ( STDMETHODCALLTYPE *Release )(
ID3D11DeviceContext2 * This);
void ( STDMETHODCALLTYPE *GetDevice )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_Outptr_ ID3D11Device **ppDevice);
HRESULT ( STDMETHODCALLTYPE *GetPrivateData )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ REFGUID guid,
/* [annotation] */
_Inout_ UINT *pDataSize,
/* [annotation] */
_Out_writes_bytes_opt_( *pDataSize ) void *pData);
HRESULT ( STDMETHODCALLTYPE *SetPrivateData )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ REFGUID guid,
/* [annotation] */
_In_ UINT DataSize,
/* [annotation] */
_In_reads_bytes_opt_( DataSize ) const void *pData);
HRESULT ( STDMETHODCALLTYPE *SetPrivateDataInterface )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ REFGUID guid,
/* [annotation] */
_In_opt_ const IUnknown *pData);
void ( STDMETHODCALLTYPE *VSSetConstantBuffers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) ID3D11Buffer *const *ppConstantBuffers);
void ( STDMETHODCALLTYPE *PSSetShaderResources )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot ) UINT NumViews,
/* [annotation] */
_In_reads_opt_(NumViews) ID3D11ShaderResourceView *const *ppShaderResourceViews);
void ( STDMETHODCALLTYPE *PSSetShader )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_opt_ ID3D11PixelShader *pPixelShader,
/* [annotation] */
_In_reads_opt_(NumClassInstances) ID3D11ClassInstance *const *ppClassInstances,
UINT NumClassInstances);
void ( STDMETHODCALLTYPE *PSSetSamplers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot ) UINT NumSamplers,
/* [annotation] */
_In_reads_opt_(NumSamplers) ID3D11SamplerState *const *ppSamplers);
void ( STDMETHODCALLTYPE *VSSetShader )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_opt_ ID3D11VertexShader *pVertexShader,
/* [annotation] */
_In_reads_opt_(NumClassInstances) ID3D11ClassInstance *const *ppClassInstances,
UINT NumClassInstances);
void ( STDMETHODCALLTYPE *DrawIndexed )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ UINT IndexCount,
/* [annotation] */
_In_ UINT StartIndexLocation,
/* [annotation] */
_In_ INT BaseVertexLocation);
void ( STDMETHODCALLTYPE *Draw )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ UINT VertexCount,
/* [annotation] */
_In_ UINT StartVertexLocation);
HRESULT ( STDMETHODCALLTYPE *Map )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Resource *pResource,
/* [annotation] */
_In_ UINT Subresource,
/* [annotation] */
_In_ D3D11_MAP MapType,
/* [annotation] */
_In_ UINT MapFlags,
/* [annotation] */
_Out_opt_ D3D11_MAPPED_SUBRESOURCE *pMappedResource);
void ( STDMETHODCALLTYPE *Unmap )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Resource *pResource,
/* [annotation] */
_In_ UINT Subresource);
void ( STDMETHODCALLTYPE *PSSetConstantBuffers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) ID3D11Buffer *const *ppConstantBuffers);
void ( STDMETHODCALLTYPE *IASetInputLayout )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_opt_ ID3D11InputLayout *pInputLayout);
void ( STDMETHODCALLTYPE *IASetVertexBuffers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) ID3D11Buffer *const *ppVertexBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) const UINT *pStrides,
/* [annotation] */
_In_reads_opt_(NumBuffers) const UINT *pOffsets);
void ( STDMETHODCALLTYPE *IASetIndexBuffer )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_opt_ ID3D11Buffer *pIndexBuffer,
/* [annotation] */
_In_ DXGI_FORMAT Format,
/* [annotation] */
_In_ UINT Offset);
void ( STDMETHODCALLTYPE *DrawIndexedInstanced )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ UINT IndexCountPerInstance,
/* [annotation] */
_In_ UINT InstanceCount,
/* [annotation] */
_In_ UINT StartIndexLocation,
/* [annotation] */
_In_ INT BaseVertexLocation,
/* [annotation] */
_In_ UINT StartInstanceLocation);
void ( STDMETHODCALLTYPE *DrawInstanced )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ UINT VertexCountPerInstance,
/* [annotation] */
_In_ UINT InstanceCount,
/* [annotation] */
_In_ UINT StartVertexLocation,
/* [annotation] */
_In_ UINT StartInstanceLocation);
void ( STDMETHODCALLTYPE *GSSetConstantBuffers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) ID3D11Buffer *const *ppConstantBuffers);
void ( STDMETHODCALLTYPE *GSSetShader )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_opt_ ID3D11GeometryShader *pShader,
/* [annotation] */
_In_reads_opt_(NumClassInstances) ID3D11ClassInstance *const *ppClassInstances,
UINT NumClassInstances);
void ( STDMETHODCALLTYPE *IASetPrimitiveTopology )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ D3D11_PRIMITIVE_TOPOLOGY Topology);
void ( STDMETHODCALLTYPE *VSSetShaderResources )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot ) UINT NumViews,
/* [annotation] */
_In_reads_opt_(NumViews) ID3D11ShaderResourceView *const *ppShaderResourceViews);
void ( STDMETHODCALLTYPE *VSSetSamplers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot ) UINT NumSamplers,
/* [annotation] */
_In_reads_opt_(NumSamplers) ID3D11SamplerState *const *ppSamplers);
void ( STDMETHODCALLTYPE *Begin )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Asynchronous *pAsync);
void ( STDMETHODCALLTYPE *End )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Asynchronous *pAsync);
HRESULT ( STDMETHODCALLTYPE *GetData )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Asynchronous *pAsync,
/* [annotation] */
_Out_writes_bytes_opt_( DataSize ) void *pData,
/* [annotation] */
_In_ UINT DataSize,
/* [annotation] */
_In_ UINT GetDataFlags);
void ( STDMETHODCALLTYPE *SetPredication )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_opt_ ID3D11Predicate *pPredicate,
/* [annotation] */
_In_ BOOL PredicateValue);
void ( STDMETHODCALLTYPE *GSSetShaderResources )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot ) UINT NumViews,
/* [annotation] */
_In_reads_opt_(NumViews) ID3D11ShaderResourceView *const *ppShaderResourceViews);
void ( STDMETHODCALLTYPE *GSSetSamplers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot ) UINT NumSamplers,
/* [annotation] */
_In_reads_opt_(NumSamplers) ID3D11SamplerState *const *ppSamplers);
void ( STDMETHODCALLTYPE *OMSetRenderTargets )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT ) UINT NumViews,
/* [annotation] */
_In_reads_opt_(NumViews) ID3D11RenderTargetView *const *ppRenderTargetViews,
/* [annotation] */
_In_opt_ ID3D11DepthStencilView *pDepthStencilView);
void ( STDMETHODCALLTYPE *OMSetRenderTargetsAndUnorderedAccessViews )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ UINT NumRTVs,
/* [annotation] */
_In_reads_opt_(NumRTVs) ID3D11RenderTargetView *const *ppRenderTargetViews,
/* [annotation] */
_In_opt_ ID3D11DepthStencilView *pDepthStencilView,
/* [annotation] */
_In_range_( 0, D3D11_1_UAV_SLOT_COUNT - 1 ) UINT UAVStartSlot,
/* [annotation] */
_In_ UINT NumUAVs,
/* [annotation] */
_In_reads_opt_(NumUAVs) ID3D11UnorderedAccessView *const *ppUnorderedAccessViews,
/* [annotation] */
_In_reads_opt_(NumUAVs) const UINT *pUAVInitialCounts);
void ( STDMETHODCALLTYPE *OMSetBlendState )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_opt_ ID3D11BlendState *pBlendState,
/* [annotation] */
_In_opt_ const FLOAT BlendFactor[ 4 ],
/* [annotation] */
_In_ UINT SampleMask);
void ( STDMETHODCALLTYPE *OMSetDepthStencilState )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_opt_ ID3D11DepthStencilState *pDepthStencilState,
/* [annotation] */
_In_ UINT StencilRef);
void ( STDMETHODCALLTYPE *SOSetTargets )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_SO_BUFFER_SLOT_COUNT) UINT NumBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) ID3D11Buffer *const *ppSOTargets,
/* [annotation] */
_In_reads_opt_(NumBuffers) const UINT *pOffsets);
void ( STDMETHODCALLTYPE *DrawAuto )(
ID3D11DeviceContext2 * This);
void ( STDMETHODCALLTYPE *DrawIndexedInstancedIndirect )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Buffer *pBufferForArgs,
/* [annotation] */
_In_ UINT AlignedByteOffsetForArgs);
void ( STDMETHODCALLTYPE *DrawInstancedIndirect )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Buffer *pBufferForArgs,
/* [annotation] */
_In_ UINT AlignedByteOffsetForArgs);
void ( STDMETHODCALLTYPE *Dispatch )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ UINT ThreadGroupCountX,
/* [annotation] */
_In_ UINT ThreadGroupCountY,
/* [annotation] */
_In_ UINT ThreadGroupCountZ);
void ( STDMETHODCALLTYPE *DispatchIndirect )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Buffer *pBufferForArgs,
/* [annotation] */
_In_ UINT AlignedByteOffsetForArgs);
void ( STDMETHODCALLTYPE *RSSetState )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_opt_ ID3D11RasterizerState *pRasterizerState);
void ( STDMETHODCALLTYPE *RSSetViewports )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_(0, D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) UINT NumViewports,
/* [annotation] */
_In_reads_opt_(NumViewports) const D3D11_VIEWPORT *pViewports);
void ( STDMETHODCALLTYPE *RSSetScissorRects )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_(0, D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) UINT NumRects,
/* [annotation] */
_In_reads_opt_(NumRects) const D3D11_RECT *pRects);
void ( STDMETHODCALLTYPE *CopySubresourceRegion )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Resource *pDstResource,
/* [annotation] */
_In_ UINT DstSubresource,
/* [annotation] */
_In_ UINT DstX,
/* [annotation] */
_In_ UINT DstY,
/* [annotation] */
_In_ UINT DstZ,
/* [annotation] */
_In_ ID3D11Resource *pSrcResource,
/* [annotation] */
_In_ UINT SrcSubresource,
/* [annotation] */
_In_opt_ const D3D11_BOX *pSrcBox);
void ( STDMETHODCALLTYPE *CopyResource )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Resource *pDstResource,
/* [annotation] */
_In_ ID3D11Resource *pSrcResource);
void ( STDMETHODCALLTYPE *UpdateSubresource )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Resource *pDstResource,
/* [annotation] */
_In_ UINT DstSubresource,
/* [annotation] */
_In_opt_ const D3D11_BOX *pDstBox,
/* [annotation] */
_In_ const void *pSrcData,
/* [annotation] */
_In_ UINT SrcRowPitch,
/* [annotation] */
_In_ UINT SrcDepthPitch);
void ( STDMETHODCALLTYPE *CopyStructureCount )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Buffer *pDstBuffer,
/* [annotation] */
_In_ UINT DstAlignedByteOffset,
/* [annotation] */
_In_ ID3D11UnorderedAccessView *pSrcView);
void ( STDMETHODCALLTYPE *ClearRenderTargetView )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11RenderTargetView *pRenderTargetView,
/* [annotation] */
_In_ const FLOAT ColorRGBA[ 4 ]);
void ( STDMETHODCALLTYPE *ClearUnorderedAccessViewUint )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11UnorderedAccessView *pUnorderedAccessView,
/* [annotation] */
_In_ const UINT Values[ 4 ]);
void ( STDMETHODCALLTYPE *ClearUnorderedAccessViewFloat )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11UnorderedAccessView *pUnorderedAccessView,
/* [annotation] */
_In_ const FLOAT Values[ 4 ]);
void ( STDMETHODCALLTYPE *ClearDepthStencilView )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11DepthStencilView *pDepthStencilView,
/* [annotation] */
_In_ UINT ClearFlags,
/* [annotation] */
_In_ FLOAT Depth,
/* [annotation] */
_In_ UINT8 Stencil);
void ( STDMETHODCALLTYPE *GenerateMips )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11ShaderResourceView *pShaderResourceView);
void ( STDMETHODCALLTYPE *SetResourceMinLOD )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Resource *pResource,
FLOAT MinLOD);
FLOAT ( STDMETHODCALLTYPE *GetResourceMinLOD )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Resource *pResource);
void ( STDMETHODCALLTYPE *ResolveSubresource )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Resource *pDstResource,
/* [annotation] */
_In_ UINT DstSubresource,
/* [annotation] */
_In_ ID3D11Resource *pSrcResource,
/* [annotation] */
_In_ UINT SrcSubresource,
/* [annotation] */
_In_ DXGI_FORMAT Format);
void ( STDMETHODCALLTYPE *ExecuteCommandList )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11CommandList *pCommandList,
BOOL RestoreContextState);
void ( STDMETHODCALLTYPE *HSSetShaderResources )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot ) UINT NumViews,
/* [annotation] */
_In_reads_opt_(NumViews) ID3D11ShaderResourceView *const *ppShaderResourceViews);
void ( STDMETHODCALLTYPE *HSSetShader )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_opt_ ID3D11HullShader *pHullShader,
/* [annotation] */
_In_reads_opt_(NumClassInstances) ID3D11ClassInstance *const *ppClassInstances,
UINT NumClassInstances);
void ( STDMETHODCALLTYPE *HSSetSamplers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot ) UINT NumSamplers,
/* [annotation] */
_In_reads_opt_(NumSamplers) ID3D11SamplerState *const *ppSamplers);
void ( STDMETHODCALLTYPE *HSSetConstantBuffers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) ID3D11Buffer *const *ppConstantBuffers);
void ( STDMETHODCALLTYPE *DSSetShaderResources )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot ) UINT NumViews,
/* [annotation] */
_In_reads_opt_(NumViews) ID3D11ShaderResourceView *const *ppShaderResourceViews);
void ( STDMETHODCALLTYPE *DSSetShader )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_opt_ ID3D11DomainShader *pDomainShader,
/* [annotation] */
_In_reads_opt_(NumClassInstances) ID3D11ClassInstance *const *ppClassInstances,
UINT NumClassInstances);
void ( STDMETHODCALLTYPE *DSSetSamplers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot ) UINT NumSamplers,
/* [annotation] */
_In_reads_opt_(NumSamplers) ID3D11SamplerState *const *ppSamplers);
void ( STDMETHODCALLTYPE *DSSetConstantBuffers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) ID3D11Buffer *const *ppConstantBuffers);
void ( STDMETHODCALLTYPE *CSSetShaderResources )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot ) UINT NumViews,
/* [annotation] */
_In_reads_opt_(NumViews) ID3D11ShaderResourceView *const *ppShaderResourceViews);
void ( STDMETHODCALLTYPE *CSSetUnorderedAccessViews )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_1_UAV_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_1_UAV_SLOT_COUNT - StartSlot ) UINT NumUAVs,
/* [annotation] */
_In_reads_opt_(NumUAVs) ID3D11UnorderedAccessView *const *ppUnorderedAccessViews,
/* [annotation] */
_In_reads_opt_(NumUAVs) const UINT *pUAVInitialCounts);
void ( STDMETHODCALLTYPE *CSSetShader )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_opt_ ID3D11ComputeShader *pComputeShader,
/* [annotation] */
_In_reads_opt_(NumClassInstances) ID3D11ClassInstance *const *ppClassInstances,
UINT NumClassInstances);
void ( STDMETHODCALLTYPE *CSSetSamplers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot ) UINT NumSamplers,
/* [annotation] */
_In_reads_opt_(NumSamplers) ID3D11SamplerState *const *ppSamplers);
void ( STDMETHODCALLTYPE *CSSetConstantBuffers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) ID3D11Buffer *const *ppConstantBuffers);
void ( STDMETHODCALLTYPE *VSGetConstantBuffers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) ID3D11Buffer **ppConstantBuffers);
void ( STDMETHODCALLTYPE *PSGetShaderResources )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot ) UINT NumViews,
/* [annotation] */
_Out_writes_opt_(NumViews) ID3D11ShaderResourceView **ppShaderResourceViews);
void ( STDMETHODCALLTYPE *PSGetShader )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_Outptr_result_maybenull_ ID3D11PixelShader **ppPixelShader,
/* [annotation] */
_Out_writes_opt_(*pNumClassInstances) ID3D11ClassInstance **ppClassInstances,
/* [annotation] */
_Inout_opt_ UINT *pNumClassInstances);
void ( STDMETHODCALLTYPE *PSGetSamplers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot ) UINT NumSamplers,
/* [annotation] */
_Out_writes_opt_(NumSamplers) ID3D11SamplerState **ppSamplers);
void ( STDMETHODCALLTYPE *VSGetShader )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_Outptr_result_maybenull_ ID3D11VertexShader **ppVertexShader,
/* [annotation] */
_Out_writes_opt_(*pNumClassInstances) ID3D11ClassInstance **ppClassInstances,
/* [annotation] */
_Inout_opt_ UINT *pNumClassInstances);
void ( STDMETHODCALLTYPE *PSGetConstantBuffers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) ID3D11Buffer **ppConstantBuffers);
void ( STDMETHODCALLTYPE *IAGetInputLayout )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_Outptr_result_maybenull_ ID3D11InputLayout **ppInputLayout);
void ( STDMETHODCALLTYPE *IAGetVertexBuffers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) ID3D11Buffer **ppVertexBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) UINT *pStrides,
/* [annotation] */
_Out_writes_opt_(NumBuffers) UINT *pOffsets);
void ( STDMETHODCALLTYPE *IAGetIndexBuffer )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_Outptr_opt_result_maybenull_ ID3D11Buffer **pIndexBuffer,
/* [annotation] */
_Out_opt_ DXGI_FORMAT *Format,
/* [annotation] */
_Out_opt_ UINT *Offset);
void ( STDMETHODCALLTYPE *GSGetConstantBuffers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) ID3D11Buffer **ppConstantBuffers);
void ( STDMETHODCALLTYPE *GSGetShader )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_Outptr_result_maybenull_ ID3D11GeometryShader **ppGeometryShader,
/* [annotation] */
_Out_writes_opt_(*pNumClassInstances) ID3D11ClassInstance **ppClassInstances,
/* [annotation] */
_Inout_opt_ UINT *pNumClassInstances);
void ( STDMETHODCALLTYPE *IAGetPrimitiveTopology )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_Out_ D3D11_PRIMITIVE_TOPOLOGY *pTopology);
void ( STDMETHODCALLTYPE *VSGetShaderResources )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot ) UINT NumViews,
/* [annotation] */
_Out_writes_opt_(NumViews) ID3D11ShaderResourceView **ppShaderResourceViews);
void ( STDMETHODCALLTYPE *VSGetSamplers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot ) UINT NumSamplers,
/* [annotation] */
_Out_writes_opt_(NumSamplers) ID3D11SamplerState **ppSamplers);
void ( STDMETHODCALLTYPE *GetPredication )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_Outptr_opt_result_maybenull_ ID3D11Predicate **ppPredicate,
/* [annotation] */
_Out_opt_ BOOL *pPredicateValue);
void ( STDMETHODCALLTYPE *GSGetShaderResources )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot ) UINT NumViews,
/* [annotation] */
_Out_writes_opt_(NumViews) ID3D11ShaderResourceView **ppShaderResourceViews);
void ( STDMETHODCALLTYPE *GSGetSamplers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot ) UINT NumSamplers,
/* [annotation] */
_Out_writes_opt_(NumSamplers) ID3D11SamplerState **ppSamplers);
void ( STDMETHODCALLTYPE *OMGetRenderTargets )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT ) UINT NumViews,
/* [annotation] */
_Out_writes_opt_(NumViews) ID3D11RenderTargetView **ppRenderTargetViews,
/* [annotation] */
_Outptr_opt_result_maybenull_ ID3D11DepthStencilView **ppDepthStencilView);
void ( STDMETHODCALLTYPE *OMGetRenderTargetsAndUnorderedAccessViews )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT ) UINT NumRTVs,
/* [annotation] */
_Out_writes_opt_(NumRTVs) ID3D11RenderTargetView **ppRenderTargetViews,
/* [annotation] */
_Outptr_opt_result_maybenull_ ID3D11DepthStencilView **ppDepthStencilView,
/* [annotation] */
_In_range_( 0, D3D11_PS_CS_UAV_REGISTER_COUNT - 1 ) UINT UAVStartSlot,
/* [annotation] */
_In_range_( 0, D3D11_PS_CS_UAV_REGISTER_COUNT - UAVStartSlot ) UINT NumUAVs,
/* [annotation] */
_Out_writes_opt_(NumUAVs) ID3D11UnorderedAccessView **ppUnorderedAccessViews);
void ( STDMETHODCALLTYPE *OMGetBlendState )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_Outptr_opt_result_maybenull_ ID3D11BlendState **ppBlendState,
/* [annotation] */
_Out_opt_ FLOAT BlendFactor[ 4 ],
/* [annotation] */
_Out_opt_ UINT *pSampleMask);
void ( STDMETHODCALLTYPE *OMGetDepthStencilState )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_Outptr_opt_result_maybenull_ ID3D11DepthStencilState **ppDepthStencilState,
/* [annotation] */
_Out_opt_ UINT *pStencilRef);
void ( STDMETHODCALLTYPE *SOGetTargets )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_SO_BUFFER_SLOT_COUNT ) UINT NumBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) ID3D11Buffer **ppSOTargets);
void ( STDMETHODCALLTYPE *RSGetState )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_Outptr_result_maybenull_ ID3D11RasterizerState **ppRasterizerState);
void ( STDMETHODCALLTYPE *RSGetViewports )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_Inout_ /*_range(0, D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE )*/ UINT *pNumViewports,
/* [annotation] */
_Out_writes_opt_(*pNumViewports) D3D11_VIEWPORT *pViewports);
void ( STDMETHODCALLTYPE *RSGetScissorRects )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_Inout_ /*_range(0, D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE )*/ UINT *pNumRects,
/* [annotation] */
_Out_writes_opt_(*pNumRects) D3D11_RECT *pRects);
void ( STDMETHODCALLTYPE *HSGetShaderResources )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot ) UINT NumViews,
/* [annotation] */
_Out_writes_opt_(NumViews) ID3D11ShaderResourceView **ppShaderResourceViews);
void ( STDMETHODCALLTYPE *HSGetShader )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_Outptr_result_maybenull_ ID3D11HullShader **ppHullShader,
/* [annotation] */
_Out_writes_opt_(*pNumClassInstances) ID3D11ClassInstance **ppClassInstances,
/* [annotation] */
_Inout_opt_ UINT *pNumClassInstances);
void ( STDMETHODCALLTYPE *HSGetSamplers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot ) UINT NumSamplers,
/* [annotation] */
_Out_writes_opt_(NumSamplers) ID3D11SamplerState **ppSamplers);
void ( STDMETHODCALLTYPE *HSGetConstantBuffers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) ID3D11Buffer **ppConstantBuffers);
void ( STDMETHODCALLTYPE *DSGetShaderResources )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot ) UINT NumViews,
/* [annotation] */
_Out_writes_opt_(NumViews) ID3D11ShaderResourceView **ppShaderResourceViews);
void ( STDMETHODCALLTYPE *DSGetShader )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_Outptr_result_maybenull_ ID3D11DomainShader **ppDomainShader,
/* [annotation] */
_Out_writes_opt_(*pNumClassInstances) ID3D11ClassInstance **ppClassInstances,
/* [annotation] */
_Inout_opt_ UINT *pNumClassInstances);
void ( STDMETHODCALLTYPE *DSGetSamplers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot ) UINT NumSamplers,
/* [annotation] */
_Out_writes_opt_(NumSamplers) ID3D11SamplerState **ppSamplers);
void ( STDMETHODCALLTYPE *DSGetConstantBuffers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) ID3D11Buffer **ppConstantBuffers);
void ( STDMETHODCALLTYPE *CSGetShaderResources )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - StartSlot ) UINT NumViews,
/* [annotation] */
_Out_writes_opt_(NumViews) ID3D11ShaderResourceView **ppShaderResourceViews);
void ( STDMETHODCALLTYPE *CSGetUnorderedAccessViews )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_1_UAV_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_1_UAV_SLOT_COUNT - StartSlot ) UINT NumUAVs,
/* [annotation] */
_Out_writes_opt_(NumUAVs) ID3D11UnorderedAccessView **ppUnorderedAccessViews);
void ( STDMETHODCALLTYPE *CSGetShader )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_Outptr_result_maybenull_ ID3D11ComputeShader **ppComputeShader,
/* [annotation] */
_Out_writes_opt_(*pNumClassInstances) ID3D11ClassInstance **ppClassInstances,
/* [annotation] */
_Inout_opt_ UINT *pNumClassInstances);
void ( STDMETHODCALLTYPE *CSGetSamplers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - StartSlot ) UINT NumSamplers,
/* [annotation] */
_Out_writes_opt_(NumSamplers) ID3D11SamplerState **ppSamplers);
void ( STDMETHODCALLTYPE *CSGetConstantBuffers )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) ID3D11Buffer **ppConstantBuffers);
void ( STDMETHODCALLTYPE *ClearState )(
ID3D11DeviceContext2 * This);
void ( STDMETHODCALLTYPE *Flush )(
ID3D11DeviceContext2 * This);
D3D11_DEVICE_CONTEXT_TYPE ( STDMETHODCALLTYPE *GetType )(
ID3D11DeviceContext2 * This);
UINT ( STDMETHODCALLTYPE *GetContextFlags )(
ID3D11DeviceContext2 * This);
HRESULT ( STDMETHODCALLTYPE *FinishCommandList )(
ID3D11DeviceContext2 * This,
BOOL RestoreDeferredContextState,
/* [annotation] */
_COM_Outptr_opt_ ID3D11CommandList **ppCommandList);
void ( STDMETHODCALLTYPE *CopySubresourceRegion1 )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Resource *pDstResource,
/* [annotation] */
_In_ UINT DstSubresource,
/* [annotation] */
_In_ UINT DstX,
/* [annotation] */
_In_ UINT DstY,
/* [annotation] */
_In_ UINT DstZ,
/* [annotation] */
_In_ ID3D11Resource *pSrcResource,
/* [annotation] */
_In_ UINT SrcSubresource,
/* [annotation] */
_In_opt_ const D3D11_BOX *pSrcBox,
/* [annotation] */
_In_ UINT CopyFlags);
void ( STDMETHODCALLTYPE *UpdateSubresource1 )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Resource *pDstResource,
/* [annotation] */
_In_ UINT DstSubresource,
/* [annotation] */
_In_opt_ const D3D11_BOX *pDstBox,
/* [annotation] */
_In_ const void *pSrcData,
/* [annotation] */
_In_ UINT SrcRowPitch,
/* [annotation] */
_In_ UINT SrcDepthPitch,
/* [annotation] */
_In_ UINT CopyFlags);
void ( STDMETHODCALLTYPE *DiscardResource )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Resource *pResource);
void ( STDMETHODCALLTYPE *DiscardView )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11View *pResourceView);
void ( STDMETHODCALLTYPE *VSSetConstantBuffers1 )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) ID3D11Buffer *const *ppConstantBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) const UINT *pFirstConstant,
/* [annotation] */
_In_reads_opt_(NumBuffers) const UINT *pNumConstants);
void ( STDMETHODCALLTYPE *HSSetConstantBuffers1 )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) ID3D11Buffer *const *ppConstantBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) const UINT *pFirstConstant,
/* [annotation] */
_In_reads_opt_(NumBuffers) const UINT *pNumConstants);
void ( STDMETHODCALLTYPE *DSSetConstantBuffers1 )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) ID3D11Buffer *const *ppConstantBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) const UINT *pFirstConstant,
/* [annotation] */
_In_reads_opt_(NumBuffers) const UINT *pNumConstants);
void ( STDMETHODCALLTYPE *GSSetConstantBuffers1 )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) ID3D11Buffer *const *ppConstantBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) const UINT *pFirstConstant,
/* [annotation] */
_In_reads_opt_(NumBuffers) const UINT *pNumConstants);
void ( STDMETHODCALLTYPE *PSSetConstantBuffers1 )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) ID3D11Buffer *const *ppConstantBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) const UINT *pFirstConstant,
/* [annotation] */
_In_reads_opt_(NumBuffers) const UINT *pNumConstants);
void ( STDMETHODCALLTYPE *CSSetConstantBuffers1 )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) ID3D11Buffer *const *ppConstantBuffers,
/* [annotation] */
_In_reads_opt_(NumBuffers) const UINT *pFirstConstant,
/* [annotation] */
_In_reads_opt_(NumBuffers) const UINT *pNumConstants);
void ( STDMETHODCALLTYPE *VSGetConstantBuffers1 )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) ID3D11Buffer **ppConstantBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) UINT *pFirstConstant,
/* [annotation] */
_Out_writes_opt_(NumBuffers) UINT *pNumConstants);
void ( STDMETHODCALLTYPE *HSGetConstantBuffers1 )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) ID3D11Buffer **ppConstantBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) UINT *pFirstConstant,
/* [annotation] */
_Out_writes_opt_(NumBuffers) UINT *pNumConstants);
void ( STDMETHODCALLTYPE *DSGetConstantBuffers1 )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) ID3D11Buffer **ppConstantBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) UINT *pFirstConstant,
/* [annotation] */
_Out_writes_opt_(NumBuffers) UINT *pNumConstants);
void ( STDMETHODCALLTYPE *GSGetConstantBuffers1 )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) ID3D11Buffer **ppConstantBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) UINT *pFirstConstant,
/* [annotation] */
_Out_writes_opt_(NumBuffers) UINT *pNumConstants);
void ( STDMETHODCALLTYPE *PSGetConstantBuffers1 )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) ID3D11Buffer **ppConstantBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) UINT *pFirstConstant,
/* [annotation] */
_Out_writes_opt_(NumBuffers) UINT *pNumConstants);
void ( STDMETHODCALLTYPE *CSGetConstantBuffers1 )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1 ) UINT StartSlot,
/* [annotation] */
_In_range_( 0, D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - StartSlot ) UINT NumBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) ID3D11Buffer **ppConstantBuffers,
/* [annotation] */
_Out_writes_opt_(NumBuffers) UINT *pFirstConstant,
/* [annotation] */
_Out_writes_opt_(NumBuffers) UINT *pNumConstants);
void ( STDMETHODCALLTYPE *SwapDeviceContextState )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3DDeviceContextState *pState,
/* [annotation] */
_Outptr_opt_ ID3DDeviceContextState **ppPreviousState);
void ( STDMETHODCALLTYPE *ClearView )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11View *pView,
/* [annotation] */
_In_ const FLOAT Color[ 4 ],
/* [annotation] */
_In_reads_opt_(NumRects) const D3D11_RECT *pRect,
UINT NumRects);
void ( STDMETHODCALLTYPE *DiscardView1 )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11View *pResourceView,
/* [annotation] */
_In_reads_opt_(NumRects) const D3D11_RECT *pRects,
UINT NumRects);
HRESULT ( STDMETHODCALLTYPE *UpdateTileMappings )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Resource *pTiledResource,
/* [annotation] */
_In_ UINT NumTiledResourceRegions,
/* [annotation] */
_In_reads_opt_(NumTiledResourceRegions) const D3D11_TILED_RESOURCE_COORDINATE *pTiledResourceRegionStartCoordinates,
/* [annotation] */
_In_reads_opt_(NumTiledResourceRegions) const D3D11_TILE_REGION_SIZE *pTiledResourceRegionSizes,
/* [annotation] */
_In_opt_ ID3D11Buffer *pTilePool,
/* [annotation] */
_In_ UINT NumRanges,
/* [annotation] */
_In_reads_opt_(NumRanges) const UINT *pRangeFlags,
/* [annotation] */
_In_reads_opt_(NumRanges) const UINT *pTilePoolStartOffsets,
/* [annotation] */
_In_reads_opt_(NumRanges) const UINT *pRangeTileCounts,
/* [annotation] */
_In_ UINT Flags);
HRESULT ( STDMETHODCALLTYPE *CopyTileMappings )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Resource *pDestTiledResource,
/* [annotation] */
_In_ const D3D11_TILED_RESOURCE_COORDINATE *pDestRegionStartCoordinate,
/* [annotation] */
_In_ ID3D11Resource *pSourceTiledResource,
/* [annotation] */
_In_ const D3D11_TILED_RESOURCE_COORDINATE *pSourceRegionStartCoordinate,
/* [annotation] */
_In_ const D3D11_TILE_REGION_SIZE *pTileRegionSize,
/* [annotation] */
_In_ UINT Flags);
void ( STDMETHODCALLTYPE *CopyTiles )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Resource *pTiledResource,
/* [annotation] */
_In_ const D3D11_TILED_RESOURCE_COORDINATE *pTileRegionStartCoordinate,
/* [annotation] */
_In_ const D3D11_TILE_REGION_SIZE *pTileRegionSize,
/* [annotation] */
_In_ ID3D11Buffer *pBuffer,
/* [annotation] */
_In_ UINT64 BufferStartOffsetInBytes,
/* [annotation] */
_In_ UINT Flags);
void ( STDMETHODCALLTYPE *UpdateTiles )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Resource *pDestTiledResource,
/* [annotation] */
_In_ const D3D11_TILED_RESOURCE_COORDINATE *pDestTileRegionStartCoordinate,
/* [annotation] */
_In_ const D3D11_TILE_REGION_SIZE *pDestTileRegionSize,
/* [annotation] */
_In_ const void *pSourceTileData,
/* [annotation] */
_In_ UINT Flags);
HRESULT ( STDMETHODCALLTYPE *ResizeTilePool )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ ID3D11Buffer *pTilePool,
/* [annotation] */
_In_ UINT64 NewSizeInBytes);
void ( STDMETHODCALLTYPE *TiledResourceBarrier )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_opt_ ID3D11DeviceChild *pTiledResourceOrViewAccessBeforeBarrier,
/* [annotation] */
_In_opt_ ID3D11DeviceChild *pTiledResourceOrViewAccessAfterBarrier);
BOOL ( STDMETHODCALLTYPE *IsAnnotationEnabled )(
ID3D11DeviceContext2 * This);
void ( STDMETHODCALLTYPE *SetMarkerInt )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ LPCWSTR pLabel,
INT Data);
void ( STDMETHODCALLTYPE *BeginEventInt )(
ID3D11DeviceContext2 * This,
/* [annotation] */
_In_ LPCWSTR pLabel,
INT Data);
void ( STDMETHODCALLTYPE *EndEvent )(
ID3D11DeviceContext2 * This);
END_INTERFACE
} ID3D11DeviceContext2Vtbl;
interface ID3D11DeviceContext2
{
CONST_VTBL struct ID3D11DeviceContext2Vtbl *lpVtbl;
};
#ifdef COBJMACROS
#define ID3D11DeviceContext2_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define ID3D11DeviceContext2_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define ID3D11DeviceContext2_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define ID3D11DeviceContext2_GetDevice(This,ppDevice) \
( (This)->lpVtbl -> GetDevice(This,ppDevice) )
#define ID3D11DeviceContext2_GetPrivateData(This,guid,pDataSize,pData) \
( (This)->lpVtbl -> GetPrivateData(This,guid,pDataSize,pData) )
#define ID3D11DeviceContext2_SetPrivateData(This,guid,DataSize,pData) \
( (This)->lpVtbl -> SetPrivateData(This,guid,DataSize,pData) )
#define ID3D11DeviceContext2_SetPrivateDataInterface(This,guid,pData) \
( (This)->lpVtbl -> SetPrivateDataInterface(This,guid,pData) )
#define ID3D11DeviceContext2_VSSetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) \
( (This)->lpVtbl -> VSSetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) )
#define ID3D11DeviceContext2_PSSetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) \
( (This)->lpVtbl -> PSSetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) )
#define ID3D11DeviceContext2_PSSetShader(This,pPixelShader,ppClassInstances,NumClassInstances) \
( (This)->lpVtbl -> PSSetShader(This,pPixelShader,ppClassInstances,NumClassInstances) )
#define ID3D11DeviceContext2_PSSetSamplers(This,StartSlot,NumSamplers,ppSamplers) \
( (This)->lpVtbl -> PSSetSamplers(This,StartSlot,NumSamplers,ppSamplers) )
#define ID3D11DeviceContext2_VSSetShader(This,pVertexShader,ppClassInstances,NumClassInstances) \
( (This)->lpVtbl -> VSSetShader(This,pVertexShader,ppClassInstances,NumClassInstances) )
#define ID3D11DeviceContext2_DrawIndexed(This,IndexCount,StartIndexLocation,BaseVertexLocation) \
( (This)->lpVtbl -> DrawIndexed(This,IndexCount,StartIndexLocation,BaseVertexLocation) )
#define ID3D11DeviceContext2_Draw(This,VertexCount,StartVertexLocation) \
( (This)->lpVtbl -> Draw(This,VertexCount,StartVertexLocation) )
#define ID3D11DeviceContext2_Map(This,pResource,Subresource,MapType,MapFlags,pMappedResource) \
( (This)->lpVtbl -> Map(This,pResource,Subresource,MapType,MapFlags,pMappedResource) )
#define ID3D11DeviceContext2_Unmap(This,pResource,Subresource) \
( (This)->lpVtbl -> Unmap(This,pResource,Subresource) )
#define ID3D11DeviceContext2_PSSetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) \
( (This)->lpVtbl -> PSSetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) )
#define ID3D11DeviceContext2_IASetInputLayout(This,pInputLayout) \
( (This)->lpVtbl -> IASetInputLayout(This,pInputLayout) )
#define ID3D11DeviceContext2_IASetVertexBuffers(This,StartSlot,NumBuffers,ppVertexBuffers,pStrides,pOffsets) \
( (This)->lpVtbl -> IASetVertexBuffers(This,StartSlot,NumBuffers,ppVertexBuffers,pStrides,pOffsets) )
#define ID3D11DeviceContext2_IASetIndexBuffer(This,pIndexBuffer,Format,Offset) \
( (This)->lpVtbl -> IASetIndexBuffer(This,pIndexBuffer,Format,Offset) )
#define ID3D11DeviceContext2_DrawIndexedInstanced(This,IndexCountPerInstance,InstanceCount,StartIndexLocation,BaseVertexLocation,StartInstanceLocation) \
( (This)->lpVtbl -> DrawIndexedInstanced(This,IndexCountPerInstance,InstanceCount,StartIndexLocation,BaseVertexLocation,StartInstanceLocation) )
#define ID3D11DeviceContext2_DrawInstanced(This,VertexCountPerInstance,InstanceCount,StartVertexLocation,StartInstanceLocation) \
( (This)->lpVtbl -> DrawInstanced(This,VertexCountPerInstance,InstanceCount,StartVertexLocation,StartInstanceLocation) )
#define ID3D11DeviceContext2_GSSetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) \
( (This)->lpVtbl -> GSSetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) )
#define ID3D11DeviceContext2_GSSetShader(This,pShader,ppClassInstances,NumClassInstances) \
( (This)->lpVtbl -> GSSetShader(This,pShader,ppClassInstances,NumClassInstances) )
#define ID3D11DeviceContext2_IASetPrimitiveTopology(This,Topology) \
( (This)->lpVtbl -> IASetPrimitiveTopology(This,Topology) )
#define ID3D11DeviceContext2_VSSetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) \
( (This)->lpVtbl -> VSSetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) )
#define ID3D11DeviceContext2_VSSetSamplers(This,StartSlot,NumSamplers,ppSamplers) \
( (This)->lpVtbl -> VSSetSamplers(This,StartSlot,NumSamplers,ppSamplers) )
#define ID3D11DeviceContext2_Begin(This,pAsync) \
( (This)->lpVtbl -> Begin(This,pAsync) )
#define ID3D11DeviceContext2_End(This,pAsync) \
( (This)->lpVtbl -> End(This,pAsync) )
#define ID3D11DeviceContext2_GetData(This,pAsync,pData,DataSize,GetDataFlags) \
( (This)->lpVtbl -> GetData(This,pAsync,pData,DataSize,GetDataFlags) )
#define ID3D11DeviceContext2_SetPredication(This,pPredicate,PredicateValue) \
( (This)->lpVtbl -> SetPredication(This,pPredicate,PredicateValue) )
#define ID3D11DeviceContext2_GSSetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) \
( (This)->lpVtbl -> GSSetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) )
#define ID3D11DeviceContext2_GSSetSamplers(This,StartSlot,NumSamplers,ppSamplers) \
( (This)->lpVtbl -> GSSetSamplers(This,StartSlot,NumSamplers,ppSamplers) )
#define ID3D11DeviceContext2_OMSetRenderTargets(This,NumViews,ppRenderTargetViews,pDepthStencilView) \
( (This)->lpVtbl -> OMSetRenderTargets(This,NumViews,ppRenderTargetViews,pDepthStencilView) )
#define ID3D11DeviceContext2_OMSetRenderTargetsAndUnorderedAccessViews(This,NumRTVs,ppRenderTargetViews,pDepthStencilView,UAVStartSlot,NumUAVs,ppUnorderedAccessViews,pUAVInitialCounts) \
( (This)->lpVtbl -> OMSetRenderTargetsAndUnorderedAccessViews(This,NumRTVs,ppRenderTargetViews,pDepthStencilView,UAVStartSlot,NumUAVs,ppUnorderedAccessViews,pUAVInitialCounts) )
#define ID3D11DeviceContext2_OMSetBlendState(This,pBlendState,BlendFactor,SampleMask) \
( (This)->lpVtbl -> OMSetBlendState(This,pBlendState,BlendFactor,SampleMask) )
#define ID3D11DeviceContext2_OMSetDepthStencilState(This,pDepthStencilState,StencilRef) \
( (This)->lpVtbl -> OMSetDepthStencilState(This,pDepthStencilState,StencilRef) )
#define ID3D11DeviceContext2_SOSetTargets(This,NumBuffers,ppSOTargets,pOffsets) \
( (This)->lpVtbl -> SOSetTargets(This,NumBuffers,ppSOTargets,pOffsets) )
#define ID3D11DeviceContext2_DrawAuto(This) \
( (This)->lpVtbl -> DrawAuto(This) )
#define ID3D11DeviceContext2_DrawIndexedInstancedIndirect(This,pBufferForArgs,AlignedByteOffsetForArgs) \
( (This)->lpVtbl -> DrawIndexedInstancedIndirect(This,pBufferForArgs,AlignedByteOffsetForArgs) )
#define ID3D11DeviceContext2_DrawInstancedIndirect(This,pBufferForArgs,AlignedByteOffsetForArgs) \
( (This)->lpVtbl -> DrawInstancedIndirect(This,pBufferForArgs,AlignedByteOffsetForArgs) )
#define ID3D11DeviceContext2_Dispatch(This,ThreadGroupCountX,ThreadGroupCountY,ThreadGroupCountZ) \
( (This)->lpVtbl -> Dispatch(This,ThreadGroupCountX,ThreadGroupCountY,ThreadGroupCountZ) )
#define ID3D11DeviceContext2_DispatchIndirect(This,pBufferForArgs,AlignedByteOffsetForArgs) \
( (This)->lpVtbl -> DispatchIndirect(This,pBufferForArgs,AlignedByteOffsetForArgs) )
#define ID3D11DeviceContext2_RSSetState(This,pRasterizerState) \
( (This)->lpVtbl -> RSSetState(This,pRasterizerState) )
#define ID3D11DeviceContext2_RSSetViewports(This,NumViewports,pViewports) \
( (This)->lpVtbl -> RSSetViewports(This,NumViewports,pViewports) )
#define ID3D11DeviceContext2_RSSetScissorRects(This,NumRects,pRects) \
( (This)->lpVtbl -> RSSetScissorRects(This,NumRects,pRects) )
#define ID3D11DeviceContext2_CopySubresourceRegion(This,pDstResource,DstSubresource,DstX,DstY,DstZ,pSrcResource,SrcSubresource,pSrcBox) \
( (This)->lpVtbl -> CopySubresourceRegion(This,pDstResource,DstSubresource,DstX,DstY,DstZ,pSrcResource,SrcSubresource,pSrcBox) )
#define ID3D11DeviceContext2_CopyResource(This,pDstResource,pSrcResource) \
( (This)->lpVtbl -> CopyResource(This,pDstResource,pSrcResource) )
#define ID3D11DeviceContext2_UpdateSubresource(This,pDstResource,DstSubresource,pDstBox,pSrcData,SrcRowPitch,SrcDepthPitch) \
( (This)->lpVtbl -> UpdateSubresource(This,pDstResource,DstSubresource,pDstBox,pSrcData,SrcRowPitch,SrcDepthPitch) )
#define ID3D11DeviceContext2_CopyStructureCount(This,pDstBuffer,DstAlignedByteOffset,pSrcView) \
( (This)->lpVtbl -> CopyStructureCount(This,pDstBuffer,DstAlignedByteOffset,pSrcView) )
#define ID3D11DeviceContext2_ClearRenderTargetView(This,pRenderTargetView,ColorRGBA) \
( (This)->lpVtbl -> ClearRenderTargetView(This,pRenderTargetView,ColorRGBA) )
#define ID3D11DeviceContext2_ClearUnorderedAccessViewUint(This,pUnorderedAccessView,Values) \
( (This)->lpVtbl -> ClearUnorderedAccessViewUint(This,pUnorderedAccessView,Values) )
#define ID3D11DeviceContext2_ClearUnorderedAccessViewFloat(This,pUnorderedAccessView,Values) \
( (This)->lpVtbl -> ClearUnorderedAccessViewFloat(This,pUnorderedAccessView,Values) )
#define ID3D11DeviceContext2_ClearDepthStencilView(This,pDepthStencilView,ClearFlags,Depth,Stencil) \
( (This)->lpVtbl -> ClearDepthStencilView(This,pDepthStencilView,ClearFlags,Depth,Stencil) )
#define ID3D11DeviceContext2_GenerateMips(This,pShaderResourceView) \
( (This)->lpVtbl -> GenerateMips(This,pShaderResourceView) )
#define ID3D11DeviceContext2_SetResourceMinLOD(This,pResource,MinLOD) \
( (This)->lpVtbl -> SetResourceMinLOD(This,pResource,MinLOD) )
#define ID3D11DeviceContext2_GetResourceMinLOD(This,pResource) \
( (This)->lpVtbl -> GetResourceMinLOD(This,pResource) )
#define ID3D11DeviceContext2_ResolveSubresource(This,pDstResource,DstSubresource,pSrcResource,SrcSubresource,Format) \
( (This)->lpVtbl -> ResolveSubresource(This,pDstResource,DstSubresource,pSrcResource,SrcSubresource,Format) )
#define ID3D11DeviceContext2_ExecuteCommandList(This,pCommandList,RestoreContextState) \
( (This)->lpVtbl -> ExecuteCommandList(This,pCommandList,RestoreContextState) )
#define ID3D11DeviceContext2_HSSetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) \
( (This)->lpVtbl -> HSSetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) )
#define ID3D11DeviceContext2_HSSetShader(This,pHullShader,ppClassInstances,NumClassInstances) \
( (This)->lpVtbl -> HSSetShader(This,pHullShader,ppClassInstances,NumClassInstances) )
#define ID3D11DeviceContext2_HSSetSamplers(This,StartSlot,NumSamplers,ppSamplers) \
( (This)->lpVtbl -> HSSetSamplers(This,StartSlot,NumSamplers,ppSamplers) )
#define ID3D11DeviceContext2_HSSetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) \
( (This)->lpVtbl -> HSSetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) )
#define ID3D11DeviceContext2_DSSetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) \
( (This)->lpVtbl -> DSSetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) )
#define ID3D11DeviceContext2_DSSetShader(This,pDomainShader,ppClassInstances,NumClassInstances) \
( (This)->lpVtbl -> DSSetShader(This,pDomainShader,ppClassInstances,NumClassInstances) )
#define ID3D11DeviceContext2_DSSetSamplers(This,StartSlot,NumSamplers,ppSamplers) \
( (This)->lpVtbl -> DSSetSamplers(This,StartSlot,NumSamplers,ppSamplers) )
#define ID3D11DeviceContext2_DSSetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) \
( (This)->lpVtbl -> DSSetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) )
#define ID3D11DeviceContext2_CSSetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) \
( (This)->lpVtbl -> CSSetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) )
#define ID3D11DeviceContext2_CSSetUnorderedAccessViews(This,StartSlot,NumUAVs,ppUnorderedAccessViews,pUAVInitialCounts) \
( (This)->lpVtbl -> CSSetUnorderedAccessViews(This,StartSlot,NumUAVs,ppUnorderedAccessViews,pUAVInitialCounts) )
#define ID3D11DeviceContext2_CSSetShader(This,pComputeShader,ppClassInstances,NumClassInstances) \
( (This)->lpVtbl -> CSSetShader(This,pComputeShader,ppClassInstances,NumClassInstances) )
#define ID3D11DeviceContext2_CSSetSamplers(This,StartSlot,NumSamplers,ppSamplers) \
( (This)->lpVtbl -> CSSetSamplers(This,StartSlot,NumSamplers,ppSamplers) )
#define ID3D11DeviceContext2_CSSetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) \
( (This)->lpVtbl -> CSSetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) )
#define ID3D11DeviceContext2_VSGetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) \
( (This)->lpVtbl -> VSGetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) )
#define ID3D11DeviceContext2_PSGetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) \
( (This)->lpVtbl -> PSGetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) )
#define ID3D11DeviceContext2_PSGetShader(This,ppPixelShader,ppClassInstances,pNumClassInstances) \
( (This)->lpVtbl -> PSGetShader(This,ppPixelShader,ppClassInstances,pNumClassInstances) )
#define ID3D11DeviceContext2_PSGetSamplers(This,StartSlot,NumSamplers,ppSamplers) \
( (This)->lpVtbl -> PSGetSamplers(This,StartSlot,NumSamplers,ppSamplers) )
#define ID3D11DeviceContext2_VSGetShader(This,ppVertexShader,ppClassInstances,pNumClassInstances) \
( (This)->lpVtbl -> VSGetShader(This,ppVertexShader,ppClassInstances,pNumClassInstances) )
#define ID3D11DeviceContext2_PSGetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) \
( (This)->lpVtbl -> PSGetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) )
#define ID3D11DeviceContext2_IAGetInputLayout(This,ppInputLayout) \
( (This)->lpVtbl -> IAGetInputLayout(This,ppInputLayout) )
#define ID3D11DeviceContext2_IAGetVertexBuffers(This,StartSlot,NumBuffers,ppVertexBuffers,pStrides,pOffsets) \
( (This)->lpVtbl -> IAGetVertexBuffers(This,StartSlot,NumBuffers,ppVertexBuffers,pStrides,pOffsets) )
#define ID3D11DeviceContext2_IAGetIndexBuffer(This,pIndexBuffer,Format,Offset) \
( (This)->lpVtbl -> IAGetIndexBuffer(This,pIndexBuffer,Format,Offset) )
#define ID3D11DeviceContext2_GSGetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) \
( (This)->lpVtbl -> GSGetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) )
#define ID3D11DeviceContext2_GSGetShader(This,ppGeometryShader,ppClassInstances,pNumClassInstances) \
( (This)->lpVtbl -> GSGetShader(This,ppGeometryShader,ppClassInstances,pNumClassInstances) )
#define ID3D11DeviceContext2_IAGetPrimitiveTopology(This,pTopology) \
( (This)->lpVtbl -> IAGetPrimitiveTopology(This,pTopology) )
#define ID3D11DeviceContext2_VSGetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) \
( (This)->lpVtbl -> VSGetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) )
#define ID3D11DeviceContext2_VSGetSamplers(This,StartSlot,NumSamplers,ppSamplers) \
( (This)->lpVtbl -> VSGetSamplers(This,StartSlot,NumSamplers,ppSamplers) )
#define ID3D11DeviceContext2_GetPredication(This,ppPredicate,pPredicateValue) \
( (This)->lpVtbl -> GetPredication(This,ppPredicate,pPredicateValue) )
#define ID3D11DeviceContext2_GSGetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) \
( (This)->lpVtbl -> GSGetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) )
#define ID3D11DeviceContext2_GSGetSamplers(This,StartSlot,NumSamplers,ppSamplers) \
( (This)->lpVtbl -> GSGetSamplers(This,StartSlot,NumSamplers,ppSamplers) )
#define ID3D11DeviceContext2_OMGetRenderTargets(This,NumViews,ppRenderTargetViews,ppDepthStencilView) \
( (This)->lpVtbl -> OMGetRenderTargets(This,NumViews,ppRenderTargetViews,ppDepthStencilView) )
#define ID3D11DeviceContext2_OMGetRenderTargetsAndUnorderedAccessViews(This,NumRTVs,ppRenderTargetViews,ppDepthStencilView,UAVStartSlot,NumUAVs,ppUnorderedAccessViews) \
( (This)->lpVtbl -> OMGetRenderTargetsAndUnorderedAccessViews(This,NumRTVs,ppRenderTargetViews,ppDepthStencilView,UAVStartSlot,NumUAVs,ppUnorderedAccessViews) )
#define ID3D11DeviceContext2_OMGetBlendState(This,ppBlendState,BlendFactor,pSampleMask) \
( (This)->lpVtbl -> OMGetBlendState(This,ppBlendState,BlendFactor,pSampleMask) )
#define ID3D11DeviceContext2_OMGetDepthStencilState(This,ppDepthStencilState,pStencilRef) \
( (This)->lpVtbl -> OMGetDepthStencilState(This,ppDepthStencilState,pStencilRef) )
#define ID3D11DeviceContext2_SOGetTargets(This,NumBuffers,ppSOTargets) \
( (This)->lpVtbl -> SOGetTargets(This,NumBuffers,ppSOTargets) )
#define ID3D11DeviceContext2_RSGetState(This,ppRasterizerState) \
( (This)->lpVtbl -> RSGetState(This,ppRasterizerState) )
#define ID3D11DeviceContext2_RSGetViewports(This,pNumViewports,pViewports) \
( (This)->lpVtbl -> RSGetViewports(This,pNumViewports,pViewports) )
#define ID3D11DeviceContext2_RSGetScissorRects(This,pNumRects,pRects) \
( (This)->lpVtbl -> RSGetScissorRects(This,pNumRects,pRects) )
#define ID3D11DeviceContext2_HSGetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) \
( (This)->lpVtbl -> HSGetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) )
#define ID3D11DeviceContext2_HSGetShader(This,ppHullShader,ppClassInstances,pNumClassInstances) \
( (This)->lpVtbl -> HSGetShader(This,ppHullShader,ppClassInstances,pNumClassInstances) )
#define ID3D11DeviceContext2_HSGetSamplers(This,StartSlot,NumSamplers,ppSamplers) \
( (This)->lpVtbl -> HSGetSamplers(This,StartSlot,NumSamplers,ppSamplers) )
#define ID3D11DeviceContext2_HSGetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) \
( (This)->lpVtbl -> HSGetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) )
#define ID3D11DeviceContext2_DSGetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) \
( (This)->lpVtbl -> DSGetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) )
#define ID3D11DeviceContext2_DSGetShader(This,ppDomainShader,ppClassInstances,pNumClassInstances) \
( (This)->lpVtbl -> DSGetShader(This,ppDomainShader,ppClassInstances,pNumClassInstances) )
#define ID3D11DeviceContext2_DSGetSamplers(This,StartSlot,NumSamplers,ppSamplers) \
( (This)->lpVtbl -> DSGetSamplers(This,StartSlot,NumSamplers,ppSamplers) )
#define ID3D11DeviceContext2_DSGetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) \
( (This)->lpVtbl -> DSGetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) )
#define ID3D11DeviceContext2_CSGetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) \
( (This)->lpVtbl -> CSGetShaderResources(This,StartSlot,NumViews,ppShaderResourceViews) )
#define ID3D11DeviceContext2_CSGetUnorderedAccessViews(This,StartSlot,NumUAVs,ppUnorderedAccessViews) \
( (This)->lpVtbl -> CSGetUnorderedAccessViews(This,StartSlot,NumUAVs,ppUnorderedAccessViews) )
#define ID3D11DeviceContext2_CSGetShader(This,ppComputeShader,ppClassInstances,pNumClassInstances) \
( (This)->lpVtbl -> CSGetShader(This,ppComputeShader,ppClassInstances,pNumClassInstances) )
#define ID3D11DeviceContext2_CSGetSamplers(This,StartSlot,NumSamplers,ppSamplers) \
( (This)->lpVtbl -> CSGetSamplers(This,StartSlot,NumSamplers,ppSamplers) )
#define ID3D11DeviceContext2_CSGetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) \
( (This)->lpVtbl -> CSGetConstantBuffers(This,StartSlot,NumBuffers,ppConstantBuffers) )
#define ID3D11DeviceContext2_ClearState(This) \
( (This)->lpVtbl -> ClearState(This) )
#define ID3D11DeviceContext2_Flush(This) \
( (This)->lpVtbl -> Flush(This) )
#define ID3D11DeviceContext2_GetType(This) \
( (This)->lpVtbl -> GetType(This) )
#define ID3D11DeviceContext2_GetContextFlags(This) \
( (This)->lpVtbl -> GetContextFlags(This) )
#define ID3D11DeviceContext2_FinishCommandList(This,RestoreDeferredContextState,ppCommandList) \
( (This)->lpVtbl -> FinishCommandList(This,RestoreDeferredContextState,ppCommandList) )
#define ID3D11DeviceContext2_CopySubresourceRegion1(This,pDstResource,DstSubresource,DstX,DstY,DstZ,pSrcResource,SrcSubresource,pSrcBox,CopyFlags) \
( (This)->lpVtbl -> CopySubresourceRegion1(This,pDstResource,DstSubresource,DstX,DstY,DstZ,pSrcResource,SrcSubresource,pSrcBox,CopyFlags) )
#define ID3D11DeviceContext2_UpdateSubresource1(This,pDstResource,DstSubresource,pDstBox,pSrcData,SrcRowPitch,SrcDepthPitch,CopyFlags) \
( (This)->lpVtbl -> UpdateSubresource1(This,pDstResource,DstSubresource,pDstBox,pSrcData,SrcRowPitch,SrcDepthPitch,CopyFlags) )
#define ID3D11DeviceContext2_DiscardResource(This,pResource) \
( (This)->lpVtbl -> DiscardResource(This,pResource) )
#define ID3D11DeviceContext2_DiscardView(This,pResourceView) \
( (This)->lpVtbl -> DiscardView(This,pResourceView) )
#define ID3D11DeviceContext2_VSSetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) \
( (This)->lpVtbl -> VSSetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) )
#define ID3D11DeviceContext2_HSSetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) \
( (This)->lpVtbl -> HSSetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) )
#define ID3D11DeviceContext2_DSSetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) \
( (This)->lpVtbl -> DSSetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) )
#define ID3D11DeviceContext2_GSSetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) \
( (This)->lpVtbl -> GSSetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) )
#define ID3D11DeviceContext2_PSSetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) \
( (This)->lpVtbl -> PSSetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) )
#define ID3D11DeviceContext2_CSSetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) \
( (This)->lpVtbl -> CSSetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) )
#define ID3D11DeviceContext2_VSGetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) \
( (This)->lpVtbl -> VSGetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) )
#define ID3D11DeviceContext2_HSGetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) \
( (This)->lpVtbl -> HSGetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) )
#define ID3D11DeviceContext2_DSGetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) \
( (This)->lpVtbl -> DSGetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) )
#define ID3D11DeviceContext2_GSGetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) \
( (This)->lpVtbl -> GSGetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) )
#define ID3D11DeviceContext2_PSGetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) \
( (This)->lpVtbl -> PSGetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) )
#define ID3D11DeviceContext2_CSGetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) \
( (This)->lpVtbl -> CSGetConstantBuffers1(This,StartSlot,NumBuffers,ppConstantBuffers,pFirstConstant,pNumConstants) )
#define ID3D11DeviceContext2_SwapDeviceContextState(This,pState,ppPreviousState) \
( (This)->lpVtbl -> SwapDeviceContextState(This,pState,ppPreviousState) )
#define ID3D11DeviceContext2_ClearView(This,pView,Color,pRect,NumRects) \
( (This)->lpVtbl -> ClearView(This,pView,Color,pRect,NumRects) )
#define ID3D11DeviceContext2_DiscardView1(This,pResourceView,pRects,NumRects) \
( (This)->lpVtbl -> DiscardView1(This,pResourceView,pRects,NumRects) )
#define ID3D11DeviceContext2_UpdateTileMappings(This,pTiledResource,NumTiledResourceRegions,pTiledResourceRegionStartCoordinates,pTiledResourceRegionSizes,pTilePool,NumRanges,pRangeFlags,pTilePoolStartOffsets,pRangeTileCounts,Flags) \
( (This)->lpVtbl -> UpdateTileMappings(This,pTiledResource,NumTiledResourceRegions,pTiledResourceRegionStartCoordinates,pTiledResourceRegionSizes,pTilePool,NumRanges,pRangeFlags,pTilePoolStartOffsets,pRangeTileCounts,Flags) )
#define ID3D11DeviceContext2_CopyTileMappings(This,pDestTiledResource,pDestRegionStartCoordinate,pSourceTiledResource,pSourceRegionStartCoordinate,pTileRegionSize,Flags) \
( (This)->lpVtbl -> CopyTileMappings(This,pDestTiledResource,pDestRegionStartCoordinate,pSourceTiledResource,pSourceRegionStartCoordinate,pTileRegionSize,Flags) )
#define ID3D11DeviceContext2_CopyTiles(This,pTiledResource,pTileRegionStartCoordinate,pTileRegionSize,pBuffer,BufferStartOffsetInBytes,Flags) \
( (This)->lpVtbl -> CopyTiles(This,pTiledResource,pTileRegionStartCoordinate,pTileRegionSize,pBuffer,BufferStartOffsetInBytes,Flags) )
#define ID3D11DeviceContext2_UpdateTiles(This,pDestTiledResource,pDestTileRegionStartCoordinate,pDestTileRegionSize,pSourceTileData,Flags) \
( (This)->lpVtbl -> UpdateTiles(This,pDestTiledResource,pDestTileRegionStartCoordinate,pDestTileRegionSize,pSourceTileData,Flags) )
#define ID3D11DeviceContext2_ResizeTilePool(This,pTilePool,NewSizeInBytes) \
( (This)->lpVtbl -> ResizeTilePool(This,pTilePool,NewSizeInBytes) )
#define ID3D11DeviceContext2_TiledResourceBarrier(This,pTiledResourceOrViewAccessBeforeBarrier,pTiledResourceOrViewAccessAfterBarrier) \
( (This)->lpVtbl -> TiledResourceBarrier(This,pTiledResourceOrViewAccessBeforeBarrier,pTiledResourceOrViewAccessAfterBarrier) )
#define ID3D11DeviceContext2_IsAnnotationEnabled(This) \
( (This)->lpVtbl -> IsAnnotationEnabled(This) )
#define ID3D11DeviceContext2_SetMarkerInt(This,pLabel,Data) \
( (This)->lpVtbl -> SetMarkerInt(This,pLabel,Data) )
#define ID3D11DeviceContext2_BeginEventInt(This,pLabel,Data) \
( (This)->lpVtbl -> BeginEventInt(This,pLabel,Data) )
#define ID3D11DeviceContext2_EndEvent(This) \
( (This)->lpVtbl -> EndEvent(This) )
#endif /* COBJMACROS */
#endif /* C style interface */
#endif /* __ID3D11DeviceContext2_INTERFACE_DEFINED__ */
#ifndef __ID3D11Device2_INTERFACE_DEFINED__
#define __ID3D11Device2_INTERFACE_DEFINED__
/* interface ID3D11Device2 */
/* [unique][local][object][uuid] */
EXTERN_C const IID IID_ID3D11Device2;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("9d06dffa-d1e5-4d07-83a8-1bb123f2f841")
ID3D11Device2 : public ID3D11Device1
{
public:
virtual void STDMETHODCALLTYPE GetImmediateContext2(
/* [annotation] */
_Outptr_ ID3D11DeviceContext2 **ppImmediateContext) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateDeferredContext2(
UINT ContextFlags,
/* [annotation] */
_COM_Outptr_opt_ ID3D11DeviceContext2 **ppDeferredContext) = 0;
virtual void STDMETHODCALLTYPE GetResourceTiling(
/* [annotation] */
_In_ ID3D11Resource *pTiledResource,
/* [annotation] */
_Out_opt_ UINT *pNumTilesForEntireResource,
/* [annotation] */
_Out_opt_ D3D11_PACKED_MIP_DESC *pPackedMipDesc,
/* [annotation] */
_Out_opt_ D3D11_TILE_SHAPE *pStandardTileShapeForNonPackedMips,
/* [annotation] */
_Inout_opt_ UINT *pNumSubresourceTilings,
/* [annotation] */
_In_ UINT FirstSubresourceTilingToGet,
/* [annotation] */
_Out_writes_(*pNumSubresourceTilings) D3D11_SUBRESOURCE_TILING *pSubresourceTilingsForNonPackedMips) = 0;
virtual HRESULT STDMETHODCALLTYPE CheckMultisampleQualityLevels1(
/* [annotation] */
_In_ DXGI_FORMAT Format,
/* [annotation] */
_In_ UINT SampleCount,
/* [annotation] */
_In_ UINT Flags,
/* [annotation] */
_Out_ UINT *pNumQualityLevels) = 0;
};
#else /* C style interface */
typedef struct ID3D11Device2Vtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
ID3D11Device2 * This,
/* [in] */ REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
ID3D11Device2 * This);
ULONG ( STDMETHODCALLTYPE *Release )(
ID3D11Device2 * This);
HRESULT ( STDMETHODCALLTYPE *CreateBuffer )(
ID3D11Device2 * This,
/* [annotation] */
_In_ const D3D11_BUFFER_DESC *pDesc,
/* [annotation] */
_In_opt_ const D3D11_SUBRESOURCE_DATA *pInitialData,
/* [annotation] */
_COM_Outptr_opt_ ID3D11Buffer **ppBuffer);
HRESULT ( STDMETHODCALLTYPE *CreateTexture1D )(
ID3D11Device2 * This,
/* [annotation] */
_In_ const D3D11_TEXTURE1D_DESC *pDesc,
/* [annotation] */
_In_reads_opt_(_Inexpressible_(pDesc->MipLevels * pDesc->ArraySize)) const D3D11_SUBRESOURCE_DATA *pInitialData,
/* [annotation] */
_COM_Outptr_opt_ ID3D11Texture1D **ppTexture1D);
HRESULT ( STDMETHODCALLTYPE *CreateTexture2D )(
ID3D11Device2 * This,
/* [annotation] */
_In_ const D3D11_TEXTURE2D_DESC *pDesc,
/* [annotation] */
_In_reads_opt_(_Inexpressible_(pDesc->MipLevels * pDesc->ArraySize)) const D3D11_SUBRESOURCE_DATA *pInitialData,
/* [annotation] */
_COM_Outptr_opt_ ID3D11Texture2D **ppTexture2D);
HRESULT ( STDMETHODCALLTYPE *CreateTexture3D )(
ID3D11Device2 * This,
/* [annotation] */
_In_ const D3D11_TEXTURE3D_DESC *pDesc,
/* [annotation] */
_In_reads_opt_(_Inexpressible_(pDesc->MipLevels)) const D3D11_SUBRESOURCE_DATA *pInitialData,
/* [annotation] */
_COM_Outptr_opt_ ID3D11Texture3D **ppTexture3D);
HRESULT ( STDMETHODCALLTYPE *CreateShaderResourceView )(
ID3D11Device2 * This,
/* [annotation] */
_In_ ID3D11Resource *pResource,
/* [annotation] */
_In_opt_ const D3D11_SHADER_RESOURCE_VIEW_DESC *pDesc,
/* [annotation] */
_COM_Outptr_opt_ ID3D11ShaderResourceView **ppSRView);
HRESULT ( STDMETHODCALLTYPE *CreateUnorderedAccessView )(
ID3D11Device2 * This,
/* [annotation] */
_In_ ID3D11Resource *pResource,
/* [annotation] */
_In_opt_ const D3D11_UNORDERED_ACCESS_VIEW_DESC *pDesc,
/* [annotation] */
_COM_Outptr_opt_ ID3D11UnorderedAccessView **ppUAView);
HRESULT ( STDMETHODCALLTYPE *CreateRenderTargetView )(
ID3D11Device2 * This,
/* [annotation] */
_In_ ID3D11Resource *pResource,
/* [annotation] */
_In_opt_ const D3D11_RENDER_TARGET_VIEW_DESC *pDesc,
/* [annotation] */
_COM_Outptr_opt_ ID3D11RenderTargetView **ppRTView);
HRESULT ( STDMETHODCALLTYPE *CreateDepthStencilView )(
ID3D11Device2 * This,
/* [annotation] */
_In_ ID3D11Resource *pResource,
/* [annotation] */
_In_opt_ const D3D11_DEPTH_STENCIL_VIEW_DESC *pDesc,
/* [annotation] */
_COM_Outptr_opt_ ID3D11DepthStencilView **ppDepthStencilView);
HRESULT ( STDMETHODCALLTYPE *CreateInputLayout )(
ID3D11Device2 * This,
/* [annotation] */
_In_reads_(NumElements) const D3D11_INPUT_ELEMENT_DESC *pInputElementDescs,
/* [annotation] */
_In_range_( 0, D3D11_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT ) UINT NumElements,
/* [annotation] */
_In_reads_(BytecodeLength) const void *pShaderBytecodeWithInputSignature,
/* [annotation] */
_In_ SIZE_T BytecodeLength,
/* [annotation] */
_COM_Outptr_opt_ ID3D11InputLayout **ppInputLayout);
HRESULT ( STDMETHODCALLTYPE *CreateVertexShader )(
ID3D11Device2 * This,
/* [annotation] */
_In_reads_(BytecodeLength) const void *pShaderBytecode,
/* [annotation] */
_In_ SIZE_T BytecodeLength,
/* [annotation] */
_In_opt_ ID3D11ClassLinkage *pClassLinkage,
/* [annotation] */
_COM_Outptr_opt_ ID3D11VertexShader **ppVertexShader);
HRESULT ( STDMETHODCALLTYPE *CreateGeometryShader )(
ID3D11Device2 * This,
/* [annotation] */
_In_reads_(BytecodeLength) const void *pShaderBytecode,
/* [annotation] */
_In_ SIZE_T BytecodeLength,
/* [annotation] */
_In_opt_ ID3D11ClassLinkage *pClassLinkage,
/* [annotation] */
_COM_Outptr_opt_ ID3D11GeometryShader **ppGeometryShader);
HRESULT ( STDMETHODCALLTYPE *CreateGeometryShaderWithStreamOutput )(
ID3D11Device2 * This,
/* [annotation] */
_In_reads_(BytecodeLength) const void *pShaderBytecode,
/* [annotation] */
_In_ SIZE_T BytecodeLength,
/* [annotation] */
_In_reads_opt_(NumEntries) const D3D11_SO_DECLARATION_ENTRY *pSODeclaration,
/* [annotation] */
_In_range_( 0, D3D11_SO_STREAM_COUNT * D3D11_SO_OUTPUT_COMPONENT_COUNT ) UINT NumEntries,
/* [annotation] */
_In_reads_opt_(NumStrides) const UINT *pBufferStrides,
/* [annotation] */
_In_range_( 0, D3D11_SO_BUFFER_SLOT_COUNT ) UINT NumStrides,
/* [annotation] */
_In_ UINT RasterizedStream,
/* [annotation] */
_In_opt_ ID3D11ClassLinkage *pClassLinkage,
/* [annotation] */
_COM_Outptr_opt_ ID3D11GeometryShader **ppGeometryShader);
HRESULT ( STDMETHODCALLTYPE *CreatePixelShader )(
ID3D11Device2 * This,
/* [annotation] */
_In_reads_(BytecodeLength) const void *pShaderBytecode,
/* [annotation] */
_In_ SIZE_T BytecodeLength,
/* [annotation] */
_In_opt_ ID3D11ClassLinkage *pClassLinkage,
/* [annotation] */
_COM_Outptr_opt_ ID3D11PixelShader **ppPixelShader);
HRESULT ( STDMETHODCALLTYPE *CreateHullShader )(
ID3D11Device2 * This,
/* [annotation] */
_In_reads_(BytecodeLength) const void *pShaderBytecode,
/* [annotation] */
_In_ SIZE_T BytecodeLength,
/* [annotation] */
_In_opt_ ID3D11ClassLinkage *pClassLinkage,
/* [annotation] */
_COM_Outptr_opt_ ID3D11HullShader **ppHullShader);
HRESULT ( STDMETHODCALLTYPE *CreateDomainShader )(
ID3D11Device2 * This,
/* [annotation] */
_In_reads_(BytecodeLength) const void *pShaderBytecode,
/* [annotation] */
_In_ SIZE_T BytecodeLength,
/* [annotation] */
_In_opt_ ID3D11ClassLinkage *pClassLinkage,
/* [annotation] */
_COM_Outptr_opt_ ID3D11DomainShader **ppDomainShader);
HRESULT ( STDMETHODCALLTYPE *CreateComputeShader )(
ID3D11Device2 * This,
/* [annotation] */
_In_reads_(BytecodeLength) const void *pShaderBytecode,
/* [annotation] */
_In_ SIZE_T BytecodeLength,
/* [annotation] */
_In_opt_ ID3D11ClassLinkage *pClassLinkage,
/* [annotation] */
_COM_Outptr_opt_ ID3D11ComputeShader **ppComputeShader);
HRESULT ( STDMETHODCALLTYPE *CreateClassLinkage )(
ID3D11Device2 * This,
/* [annotation] */
_COM_Outptr_ ID3D11ClassLinkage **ppLinkage);
HRESULT ( STDMETHODCALLTYPE *CreateBlendState )(
ID3D11Device2 * This,
/* [annotation] */
_In_ const D3D11_BLEND_DESC *pBlendStateDesc,
/* [annotation] */
_COM_Outptr_opt_ ID3D11BlendState **ppBlendState);
HRESULT ( STDMETHODCALLTYPE *CreateDepthStencilState )(
ID3D11Device2 * This,
/* [annotation] */
_In_ const D3D11_DEPTH_STENCIL_DESC *pDepthStencilDesc,
/* [annotation] */
_COM_Outptr_opt_ ID3D11DepthStencilState **ppDepthStencilState);
HRESULT ( STDMETHODCALLTYPE *CreateRasterizerState )(
ID3D11Device2 * This,
/* [annotation] */
_In_ const D3D11_RASTERIZER_DESC *pRasterizerDesc,
/* [annotation] */
_COM_Outptr_opt_ ID3D11RasterizerState **ppRasterizerState);
HRESULT ( STDMETHODCALLTYPE *CreateSamplerState )(
ID3D11Device2 * This,
/* [annotation] */
_In_ const D3D11_SAMPLER_DESC *pSamplerDesc,
/* [annotation] */
_COM_Outptr_opt_ ID3D11SamplerState **ppSamplerState);
HRESULT ( STDMETHODCALLTYPE *CreateQuery )(
ID3D11Device2 * This,
/* [annotation] */
_In_ const D3D11_QUERY_DESC *pQueryDesc,
/* [annotation] */
_COM_Outptr_opt_ ID3D11Query **ppQuery);
HRESULT ( STDMETHODCALLTYPE *CreatePredicate )(
ID3D11Device2 * This,
/* [annotation] */
_In_ const D3D11_QUERY_DESC *pPredicateDesc,
/* [annotation] */
_COM_Outptr_opt_ ID3D11Predicate **ppPredicate);
HRESULT ( STDMETHODCALLTYPE *CreateCounter )(
ID3D11Device2 * This,
/* [annotation] */
_In_ const D3D11_COUNTER_DESC *pCounterDesc,
/* [annotation] */
_COM_Outptr_opt_ ID3D11Counter **ppCounter);
HRESULT ( STDMETHODCALLTYPE *CreateDeferredContext )(
ID3D11Device2 * This,
UINT ContextFlags,
/* [annotation] */
_COM_Outptr_opt_ ID3D11DeviceContext **ppDeferredContext);
HRESULT ( STDMETHODCALLTYPE *OpenSharedResource )(
ID3D11Device2 * This,
/* [annotation] */
_In_ HANDLE hResource,
/* [annotation] */
_In_ REFIID ReturnedInterface,
/* [annotation] */
_COM_Outptr_opt_ void **ppResource);
HRESULT ( STDMETHODCALLTYPE *CheckFormatSupport )(
ID3D11Device2 * This,
/* [annotation] */
_In_ DXGI_FORMAT Format,
/* [annotation] */
_Out_ UINT *pFormatSupport);
HRESULT ( STDMETHODCALLTYPE *CheckMultisampleQualityLevels )(
ID3D11Device2 * This,
/* [annotation] */
_In_ DXGI_FORMAT Format,
/* [annotation] */
_In_ UINT SampleCount,
/* [annotation] */
_Out_ UINT *pNumQualityLevels);
void ( STDMETHODCALLTYPE *CheckCounterInfo )(
ID3D11Device2 * This,
/* [annotation] */
_Out_ D3D11_COUNTER_INFO *pCounterInfo);
HRESULT ( STDMETHODCALLTYPE *CheckCounter )(
ID3D11Device2 * This,
/* [annotation] */
_In_ const D3D11_COUNTER_DESC *pDesc,
/* [annotation] */
_Out_ D3D11_COUNTER_TYPE *pType,
/* [annotation] */
_Out_ UINT *pActiveCounters,
/* [annotation] */
_Out_writes_opt_(*pNameLength) LPSTR szName,
/* [annotation] */
_Inout_opt_ UINT *pNameLength,
/* [annotation] */
_Out_writes_opt_(*pUnitsLength) LPSTR szUnits,
/* [annotation] */
_Inout_opt_ UINT *pUnitsLength,
/* [annotation] */
_Out_writes_opt_(*pDescriptionLength) LPSTR szDescription,
/* [annotation] */
_Inout_opt_ UINT *pDescriptionLength);
HRESULT ( STDMETHODCALLTYPE *CheckFeatureSupport )(
ID3D11Device2 * This,
D3D11_FEATURE Feature,
/* [annotation] */
_Out_writes_bytes_(FeatureSupportDataSize) void *pFeatureSupportData,
UINT FeatureSupportDataSize);
HRESULT ( STDMETHODCALLTYPE *GetPrivateData )(
ID3D11Device2 * This,
/* [annotation] */
_In_ REFGUID guid,
/* [annotation] */
_Inout_ UINT *pDataSize,
/* [annotation] */
_Out_writes_bytes_opt_(*pDataSize) void *pData);
HRESULT ( STDMETHODCALLTYPE *SetPrivateData )(
ID3D11Device2 * This,
/* [annotation] */
_In_ REFGUID guid,
/* [annotation] */
_In_ UINT DataSize,
/* [annotation] */
_In_reads_bytes_opt_(DataSize) const void *pData);
HRESULT ( STDMETHODCALLTYPE *SetPrivateDataInterface )(
ID3D11Device2 * This,
/* [annotation] */
_In_ REFGUID guid,
/* [annotation] */
_In_opt_ const IUnknown *pData);
D3D_FEATURE_LEVEL ( STDMETHODCALLTYPE *GetFeatureLevel )(
ID3D11Device2 * This);
UINT ( STDMETHODCALLTYPE *GetCreationFlags )(
ID3D11Device2 * This);
HRESULT ( STDMETHODCALLTYPE *GetDeviceRemovedReason )(
ID3D11Device2 * This);
void ( STDMETHODCALLTYPE *GetImmediateContext )(
ID3D11Device2 * This,
/* [annotation] */
_Outptr_ ID3D11DeviceContext **ppImmediateContext);
HRESULT ( STDMETHODCALLTYPE *SetExceptionMode )(
ID3D11Device2 * This,
UINT RaiseFlags);
UINT ( STDMETHODCALLTYPE *GetExceptionMode )(
ID3D11Device2 * This);
void ( STDMETHODCALLTYPE *GetImmediateContext1 )(
ID3D11Device2 * This,
/* [annotation] */
_Outptr_ ID3D11DeviceContext1 **ppImmediateContext);
HRESULT ( STDMETHODCALLTYPE *CreateDeferredContext1 )(
ID3D11Device2 * This,
UINT ContextFlags,
/* [annotation] */
_COM_Outptr_opt_ ID3D11DeviceContext1 **ppDeferredContext);
HRESULT ( STDMETHODCALLTYPE *CreateBlendState1 )(
ID3D11Device2 * This,
/* [annotation] */
_In_ const D3D11_BLEND_DESC1 *pBlendStateDesc,
/* [annotation] */
_COM_Outptr_opt_ ID3D11BlendState1 **ppBlendState);
HRESULT ( STDMETHODCALLTYPE *CreateRasterizerState1 )(
ID3D11Device2 * This,
/* [annotation] */
_In_ const D3D11_RASTERIZER_DESC1 *pRasterizerDesc,
/* [annotation] */
_COM_Outptr_opt_ ID3D11RasterizerState1 **ppRasterizerState);
HRESULT ( STDMETHODCALLTYPE *CreateDeviceContextState )(
ID3D11Device2 * This,
UINT Flags,
/* [annotation] */
_In_reads_( FeatureLevels ) const D3D_FEATURE_LEVEL *pFeatureLevels,
UINT FeatureLevels,
UINT SDKVersion,
REFIID EmulatedInterface,
/* [annotation] */
_Out_opt_ D3D_FEATURE_LEVEL *pChosenFeatureLevel,
/* [annotation] */
_Out_opt_ ID3DDeviceContextState **ppContextState);
HRESULT ( STDMETHODCALLTYPE *OpenSharedResource1 )(
ID3D11Device2 * This,
/* [annotation] */
_In_ HANDLE hResource,
/* [annotation] */
_In_ REFIID returnedInterface,
/* [annotation] */
_COM_Outptr_ void **ppResource);
HRESULT ( STDMETHODCALLTYPE *OpenSharedResourceByName )(
ID3D11Device2 * This,
/* [annotation] */
_In_ LPCWSTR lpName,
/* [annotation] */
_In_ DWORD dwDesiredAccess,
/* [annotation] */
_In_ REFIID returnedInterface,
/* [annotation] */
_COM_Outptr_ void **ppResource);
void ( STDMETHODCALLTYPE *GetImmediateContext2 )(
ID3D11Device2 * This,
/* [annotation] */
_Outptr_ ID3D11DeviceContext2 **ppImmediateContext);
HRESULT ( STDMETHODCALLTYPE *CreateDeferredContext2 )(
ID3D11Device2 * This,
UINT ContextFlags,
/* [annotation] */
_COM_Outptr_opt_ ID3D11DeviceContext2 **ppDeferredContext);
void ( STDMETHODCALLTYPE *GetResourceTiling )(
ID3D11Device2 * This,
/* [annotation] */
_In_ ID3D11Resource *pTiledResource,
/* [annotation] */
_Out_opt_ UINT *pNumTilesForEntireResource,
/* [annotation] */
_Out_opt_ D3D11_PACKED_MIP_DESC *pPackedMipDesc,
/* [annotation] */
_Out_opt_ D3D11_TILE_SHAPE *pStandardTileShapeForNonPackedMips,
/* [annotation] */
_Inout_opt_ UINT *pNumSubresourceTilings,
/* [annotation] */
_In_ UINT FirstSubresourceTilingToGet,
/* [annotation] */
_Out_writes_(*pNumSubresourceTilings) D3D11_SUBRESOURCE_TILING *pSubresourceTilingsForNonPackedMips);
HRESULT ( STDMETHODCALLTYPE *CheckMultisampleQualityLevels1 )(
ID3D11Device2 * This,
/* [annotation] */
_In_ DXGI_FORMAT Format,
/* [annotation] */
_In_ UINT SampleCount,
/* [annotation] */
_In_ UINT Flags,
/* [annotation] */
_Out_ UINT *pNumQualityLevels);
END_INTERFACE
} ID3D11Device2Vtbl;
interface ID3D11Device2
{
CONST_VTBL struct ID3D11Device2Vtbl *lpVtbl;
};
#ifdef COBJMACROS
#define ID3D11Device2_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define ID3D11Device2_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define ID3D11Device2_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define ID3D11Device2_CreateBuffer(This,pDesc,pInitialData,ppBuffer) \
( (This)->lpVtbl -> CreateBuffer(This,pDesc,pInitialData,ppBuffer) )
#define ID3D11Device2_CreateTexture1D(This,pDesc,pInitialData,ppTexture1D) \
( (This)->lpVtbl -> CreateTexture1D(This,pDesc,pInitialData,ppTexture1D) )
#define ID3D11Device2_CreateTexture2D(This,pDesc,pInitialData,ppTexture2D) \
( (This)->lpVtbl -> CreateTexture2D(This,pDesc,pInitialData,ppTexture2D) )
#define ID3D11Device2_CreateTexture3D(This,pDesc,pInitialData,ppTexture3D) \
( (This)->lpVtbl -> CreateTexture3D(This,pDesc,pInitialData,ppTexture3D) )
#define ID3D11Device2_CreateShaderResourceView(This,pResource,pDesc,ppSRView) \
( (This)->lpVtbl -> CreateShaderResourceView(This,pResource,pDesc,ppSRView) )
#define ID3D11Device2_CreateUnorderedAccessView(This,pResource,pDesc,ppUAView) \
( (This)->lpVtbl -> CreateUnorderedAccessView(This,pResource,pDesc,ppUAView) )
#define ID3D11Device2_CreateRenderTargetView(This,pResource,pDesc,ppRTView) \
( (This)->lpVtbl -> CreateRenderTargetView(This,pResource,pDesc,ppRTView) )
#define ID3D11Device2_CreateDepthStencilView(This,pResource,pDesc,ppDepthStencilView) \
( (This)->lpVtbl -> CreateDepthStencilView(This,pResource,pDesc,ppDepthStencilView) )
#define ID3D11Device2_CreateInputLayout(This,pInputElementDescs,NumElements,pShaderBytecodeWithInputSignature,BytecodeLength,ppInputLayout) \
( (This)->lpVtbl -> CreateInputLayout(This,pInputElementDescs,NumElements,pShaderBytecodeWithInputSignature,BytecodeLength,ppInputLayout) )
#define ID3D11Device2_CreateVertexShader(This,pShaderBytecode,BytecodeLength,pClassLinkage,ppVertexShader) \
( (This)->lpVtbl -> CreateVertexShader(This,pShaderBytecode,BytecodeLength,pClassLinkage,ppVertexShader) )
#define ID3D11Device2_CreateGeometryShader(This,pShaderBytecode,BytecodeLength,pClassLinkage,ppGeometryShader) \
( (This)->lpVtbl -> CreateGeometryShader(This,pShaderBytecode,BytecodeLength,pClassLinkage,ppGeometryShader) )
#define ID3D11Device2_CreateGeometryShaderWithStreamOutput(This,pShaderBytecode,BytecodeLength,pSODeclaration,NumEntries,pBufferStrides,NumStrides,RasterizedStream,pClassLinkage,ppGeometryShader) \
( (This)->lpVtbl -> CreateGeometryShaderWithStreamOutput(This,pShaderBytecode,BytecodeLength,pSODeclaration,NumEntries,pBufferStrides,NumStrides,RasterizedStream,pClassLinkage,ppGeometryShader) )
#define ID3D11Device2_CreatePixelShader(This,pShaderBytecode,BytecodeLength,pClassLinkage,ppPixelShader) \
( (This)->lpVtbl -> CreatePixelShader(This,pShaderBytecode,BytecodeLength,pClassLinkage,ppPixelShader) )
#define ID3D11Device2_CreateHullShader(This,pShaderBytecode,BytecodeLength,pClassLinkage,ppHullShader) \
( (This)->lpVtbl -> CreateHullShader(This,pShaderBytecode,BytecodeLength,pClassLinkage,ppHullShader) )
#define ID3D11Device2_CreateDomainShader(This,pShaderBytecode,BytecodeLength,pClassLinkage,ppDomainShader) \
( (This)->lpVtbl -> CreateDomainShader(This,pShaderBytecode,BytecodeLength,pClassLinkage,ppDomainShader) )
#define ID3D11Device2_CreateComputeShader(This,pShaderBytecode,BytecodeLength,pClassLinkage,ppComputeShader) \
( (This)->lpVtbl -> CreateComputeShader(This,pShaderBytecode,BytecodeLength,pClassLinkage,ppComputeShader) )
#define ID3D11Device2_CreateClassLinkage(This,ppLinkage) \
( (This)->lpVtbl -> CreateClassLinkage(This,ppLinkage) )
#define ID3D11Device2_CreateBlendState(This,pBlendStateDesc,ppBlendState) \
( (This)->lpVtbl -> CreateBlendState(This,pBlendStateDesc,ppBlendState) )
#define ID3D11Device2_CreateDepthStencilState(This,pDepthStencilDesc,ppDepthStencilState) \
( (This)->lpVtbl -> CreateDepthStencilState(This,pDepthStencilDesc,ppDepthStencilState) )
#define ID3D11Device2_CreateRasterizerState(This,pRasterizerDesc,ppRasterizerState) \
( (This)->lpVtbl -> CreateRasterizerState(This,pRasterizerDesc,ppRasterizerState) )
#define ID3D11Device2_CreateSamplerState(This,pSamplerDesc,ppSamplerState) \
( (This)->lpVtbl -> CreateSamplerState(This,pSamplerDesc,ppSamplerState) )
#define ID3D11Device2_CreateQuery(This,pQueryDesc,ppQuery) \
( (This)->lpVtbl -> CreateQuery(This,pQueryDesc,ppQuery) )
#define ID3D11Device2_CreatePredicate(This,pPredicateDesc,ppPredicate) \
( (This)->lpVtbl -> CreatePredicate(This,pPredicateDesc,ppPredicate) )
#define ID3D11Device2_CreateCounter(This,pCounterDesc,ppCounter) \
( (This)->lpVtbl -> CreateCounter(This,pCounterDesc,ppCounter) )
#define ID3D11Device2_CreateDeferredContext(This,ContextFlags,ppDeferredContext) \
( (This)->lpVtbl -> CreateDeferredContext(This,ContextFlags,ppDeferredContext) )
#define ID3D11Device2_OpenSharedResource(This,hResource,ReturnedInterface,ppResource) \
( (This)->lpVtbl -> OpenSharedResource(This,hResource,ReturnedInterface,ppResource) )
#define ID3D11Device2_CheckFormatSupport(This,Format,pFormatSupport) \
( (This)->lpVtbl -> CheckFormatSupport(This,Format,pFormatSupport) )
#define ID3D11Device2_CheckMultisampleQualityLevels(This,Format,SampleCount,pNumQualityLevels) \
( (This)->lpVtbl -> CheckMultisampleQualityLevels(This,Format,SampleCount,pNumQualityLevels) )
#define ID3D11Device2_CheckCounterInfo(This,pCounterInfo) \
( (This)->lpVtbl -> CheckCounterInfo(This,pCounterInfo) )
#define ID3D11Device2_CheckCounter(This,pDesc,pType,pActiveCounters,szName,pNameLength,szUnits,pUnitsLength,szDescription,pDescriptionLength) \
( (This)->lpVtbl -> CheckCounter(This,pDesc,pType,pActiveCounters,szName,pNameLength,szUnits,pUnitsLength,szDescription,pDescriptionLength) )
#define ID3D11Device2_CheckFeatureSupport(This,Feature,pFeatureSupportData,FeatureSupportDataSize) \
( (This)->lpVtbl -> CheckFeatureSupport(This,Feature,pFeatureSupportData,FeatureSupportDataSize) )
#define ID3D11Device2_GetPrivateData(This,guid,pDataSize,pData) \
( (This)->lpVtbl -> GetPrivateData(This,guid,pDataSize,pData) )
#define ID3D11Device2_SetPrivateData(This,guid,DataSize,pData) \
( (This)->lpVtbl -> SetPrivateData(This,guid,DataSize,pData) )
#define ID3D11Device2_SetPrivateDataInterface(This,guid,pData) \
( (This)->lpVtbl -> SetPrivateDataInterface(This,guid,pData) )
#define ID3D11Device2_GetFeatureLevel(This) \
( (This)->lpVtbl -> GetFeatureLevel(This) )
#define ID3D11Device2_GetCreationFlags(This) \
( (This)->lpVtbl -> GetCreationFlags(This) )
#define ID3D11Device2_GetDeviceRemovedReason(This) \
( (This)->lpVtbl -> GetDeviceRemovedReason(This) )
#define ID3D11Device2_GetImmediateContext(This,ppImmediateContext) \
( (This)->lpVtbl -> GetImmediateContext(This,ppImmediateContext) )
#define ID3D11Device2_SetExceptionMode(This,RaiseFlags) \
( (This)->lpVtbl -> SetExceptionMode(This,RaiseFlags) )
#define ID3D11Device2_GetExceptionMode(This) \
( (This)->lpVtbl -> GetExceptionMode(This) )
#define ID3D11Device2_GetImmediateContext1(This,ppImmediateContext) \
( (This)->lpVtbl -> GetImmediateContext1(This,ppImmediateContext) )
#define ID3D11Device2_CreateDeferredContext1(This,ContextFlags,ppDeferredContext) \
( (This)->lpVtbl -> CreateDeferredContext1(This,ContextFlags,ppDeferredContext) )
#define ID3D11Device2_CreateBlendState1(This,pBlendStateDesc,ppBlendState) \
( (This)->lpVtbl -> CreateBlendState1(This,pBlendStateDesc,ppBlendState) )
#define ID3D11Device2_CreateRasterizerState1(This,pRasterizerDesc,ppRasterizerState) \
( (This)->lpVtbl -> CreateRasterizerState1(This,pRasterizerDesc,ppRasterizerState) )
#define ID3D11Device2_CreateDeviceContextState(This,Flags,pFeatureLevels,FeatureLevels,SDKVersion,EmulatedInterface,pChosenFeatureLevel,ppContextState) \
( (This)->lpVtbl -> CreateDeviceContextState(This,Flags,pFeatureLevels,FeatureLevels,SDKVersion,EmulatedInterface,pChosenFeatureLevel,ppContextState) )
#define ID3D11Device2_OpenSharedResource1(This,hResource,returnedInterface,ppResource) \
( (This)->lpVtbl -> OpenSharedResource1(This,hResource,returnedInterface,ppResource) )
#define ID3D11Device2_OpenSharedResourceByName(This,lpName,dwDesiredAccess,returnedInterface,ppResource) \
( (This)->lpVtbl -> OpenSharedResourceByName(This,lpName,dwDesiredAccess,returnedInterface,ppResource) )
#define ID3D11Device2_GetImmediateContext2(This,ppImmediateContext) \
( (This)->lpVtbl -> GetImmediateContext2(This,ppImmediateContext) )
#define ID3D11Device2_CreateDeferredContext2(This,ContextFlags,ppDeferredContext) \
( (This)->lpVtbl -> CreateDeferredContext2(This,ContextFlags,ppDeferredContext) )
#define ID3D11Device2_GetResourceTiling(This,pTiledResource,pNumTilesForEntireResource,pPackedMipDesc,pStandardTileShapeForNonPackedMips,pNumSubresourceTilings,FirstSubresourceTilingToGet,pSubresourceTilingsForNonPackedMips) \
( (This)->lpVtbl -> GetResourceTiling(This,pTiledResource,pNumTilesForEntireResource,pPackedMipDesc,pStandardTileShapeForNonPackedMips,pNumSubresourceTilings,FirstSubresourceTilingToGet,pSubresourceTilingsForNonPackedMips) )
#define ID3D11Device2_CheckMultisampleQualityLevels1(This,Format,SampleCount,Flags,pNumQualityLevels) \
( (This)->lpVtbl -> CheckMultisampleQualityLevels1(This,Format,SampleCount,Flags,pNumQualityLevels) )
#endif /* COBJMACROS */
#endif /* C style interface */
#endif /* __ID3D11Device2_INTERFACE_DEFINED__ */
/* interface __MIDL_itf_d3d11_2_0000_0002 */
/* [local] */
DEFINE_GUID(IID_ID3D11DeviceContext2,0x420d5b32,0xb90c,0x4da4,0xbe,0xf0,0x35,0x9f,0x6a,0x24,0xa8,0x3a);
DEFINE_GUID(IID_ID3D11Device2,0x9d06dffa,0xd1e5,0x4d07,0x83,0xa8,0x1b,0xb1,0x23,0xf2,0xf8,0x41);
extern RPC_IF_HANDLE __MIDL_itf_d3d11_2_0000_0002_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_d3d11_2_0000_0002_v0_0_s_ifspec;
/* Additional Prototypes for ALL interfaces */
/* end of Additional Prototypes */
#ifdef __cplusplus
}
#endif
#endif
| gongminmin/UniversalDXSDK | Include/d3d11_2.h | C | mit | 124,211 | 44.649026 | 234 | 0.625879 | false |
/****************************************************************************************
Copyright (C) 2014 Autodesk, Inc.
All rights reserved.
Use of this software is subject to the terms of the Autodesk license agreement
provided at the time of installation or download, or which otherwise accompanies
this software in either electronic or hard copy form.
****************************************************************************************/
//! \file fbxconstraintutils.h
#ifndef _FBXSDK_SCENE_CONSTRAINT_UTILS_H_
#define _FBXSDK_SCENE_CONSTRAINT_UTILS_H_
#include <fbxsdk/fbxsdk_def.h>
#include <fbxsdk/fbxsdk_nsbegin.h>
class FbxNode;
/** Utility class for constraints
*\nosubgrouping
*/
class FBXSDK_DLL FbxConstraintUtils
{
public:
/** Test if the given node is Single Chain IK Effector.
* \param pNode The given node
* \return \c true if it is, \c false otherwise.
*/
static bool IsNodeSingleChainIKEffector(FbxNode* pNode);
};
#include <fbxsdk/fbxsdk_nsend.h>
#endif /* _FBXSDK_SCENE_CONSTRAINT_UTILS_H_ */
| ericrieper/ofxFBX | libs/fbxsdk_2015.1/include/fbxsdk/scene/constraint/fbxconstraintutils.h | C | mit | 1,085 | 28.324324 | 89 | 0.597235 | false |
/*
* grunt-connect-proxy
* https://github.com/drewzboto/grunt-connect-proxy
*
* Copyright (c) 2013 Drewz
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
var proxySnippet = require("./lib/utils.js").proxyRequest;
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'lib/*.js',
'<%= nodeunit.tests %>'
],
options: {
jshintrc: '.jshintrc'
}
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tmp']
},
// Configuration to be run (and then tested).
connect: {
options: {
port: 9000,
// change this to '0.0.0.0' to access the server from outside
hostname: 'localhost'
},
proxies:
[
{
context: '/defaults',
host: 'www.defaults.com'
},
{
context: '/full',
host: 'www.full.com',
port: 8080,
https: true,
xforward: true,
rewrite: {
'^/full': '/anothercontext'
},
headers: {
"X-Proxied-Header": "added"
},
ws: true
},
{
context: '/context/test',
host: 'www.anothercontext.com',
rewrite: {
'^/context': '/anothercontext',
'test': 'testing'
}
},
{
context: '/invalidrewrite',
host: 'www.invalidrewrite.com',
rewrite: {
'^/undefined': undefined,
'^/notstring': 13,
'^/in': '/thisis'
}
},
{
context: '/missinghost'
},
{
host: 'www.missingcontext.com'
},
{
context: ['/array1','/array2'],
host: 'www.defaults.com'
},
{
context: '/rewrite',
host: 'www.yetanothercontext.com',
rewrite: {
'^(/)rewrite': function(match, p1) {
return p1;
}
}
}
],
server2: {
proxies: [
{
context: '/',
host: 'www.server2.com'
}
]
},
server3: {
appendProxies: false,
proxies: [
{
context: '/server3',
host: 'www.server3.com',
port: 8080,
}
]
},
request: {
options: {
middleware: function (connect, options) {
return [require('./lib/utils').proxyRequest];
}
},
proxies: [
{
context: '/request',
host: 'localhost',
port: 8080,
headers: {
"x-proxied-header": "added"
}
},
{
context: '/hideHeaders',
host: 'localhost',
port: 8081,
hideHeaders: ['x-hidden-header-1', 'X-HiDdEn-HeAdEr-2']
}
]
}
},
// Unit tests.
nodeunit: {
tests: 'test/connect_proxy_test.js',
server2: 'test/server2_proxy_test.js',
server3: 'test/server3_proxy_test.js',
utils: 'test/utils_test.js',
request: 'test/request_test.js',
hideHeaders: 'test/hide_headers_test.js'
}
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', [
'clean',
'nodeunit:utils',
'configureProxies',
'nodeunit:tests',
'configureProxies:server2',
'nodeunit:server2',
'configureProxies:server3',
'nodeunit:server3',
'configureProxies:request',
'connect:request',
'nodeunit:request',
'nodeunit:hideHeaders'
]);
// specifically test that option inheritance works for multi-level config
grunt.registerTask('test-inheritance', [
'clean',
'configureProxies:server2',
'nodeunit:server2'
]);
// By default, lint and run all tests.
grunt.registerTask('default', ['jshint', 'test']);
};
| Backline/grunt-connect-proxy | Gruntfile.js | JavaScript | mit | 4,665 | 23.552632 | 78 | 0.466881 | false |
-- TABLE
CREATE TABLE IF NOT EXISTS `bx_market_subproducts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`initiator` int(11) NOT NULL,
`content` int(11) NOT NULL,
`added` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `initiator` (`initiator`,`content`),
KEY `content` (`content`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- FORMS
UPDATE `sys_form_inputs` SET `editable`='1' WHERE `object`='bx_market' AND `name` IN ('allow_view_to', 'allow_purchase_to', 'allow_comment_to', 'allow_vote_to');
DELETE FROM `sys_form_inputs` WHERE `object`='bx_market' AND `name` IN ('subentries');
INSERT INTO `sys_form_inputs`(`object`, `module`, `name`, `value`, `values`, `checked`, `type`, `caption_system`, `caption`, `info`, `required`, `collapsed`, `html`, `attrs`, `attrs_tr`, `attrs_wrapper`, `checker_func`, `checker_params`, `checker_error`, `db_pass`, `db_params`, `editable`, `deletable`) VALUES
('bx_market', 'bx_market', 'subentries', '', '', 0, 'custom', '_bx_market_form_entry_input_sys_subentries', '_bx_market_form_entry_input_subentries', '_bx_market_form_entry_input_subentries_inf', 0, 0, 0, '', '', '', '', '', '', '', '', 1, 0);
DELETE FROM `sys_form_display_inputs` WHERE `display_name` IN ('bx_market_entry_add', 'bx_market_entry_edit');
INSERT INTO `sys_form_display_inputs`(`display_name`, `input_name`, `visible_for_levels`, `active`, `order`) VALUES
('bx_market_entry_add', 'title', 2147483647, 1, 1),
('bx_market_entry_add', 'name', 2147483647, 1, 2),
('bx_market_entry_add', 'cat', 2147483647, 1, 3),
('bx_market_entry_add', 'text', 2147483647, 1, 4),
('bx_market_entry_add', 'pictures', 2147483647, 1, 5),
('bx_market_entry_add', 'files', 2147483647, 1, 6),
('bx_market_entry_add', 'header_beg_single', 2147483647, 1, 7),
('bx_market_entry_add', 'warning_single', 2147483647, 1, 8),
('bx_market_entry_add', 'price_single', 2147483647, 1, 9),
('bx_market_entry_add', 'header_end_single', 2147483647, 1, 10),
('bx_market_entry_add', 'header_beg_recurring', 2147483647, 1, 11),
('bx_market_entry_add', 'warning_recurring', 2147483647, 1, 12),
('bx_market_entry_add', 'duration_recurring', 2147483647, 1, 13),
('bx_market_entry_add', 'price_recurring', 2147483647, 1, 14),
('bx_market_entry_add', 'trial_recurring', 2147483647, 1, 15),
('bx_market_entry_add', 'header_end_recurring', 2147483647, 1, 16),
('bx_market_entry_add', 'header_beg_privacy', 2147483647, 1, 17),
('bx_market_entry_add', 'allow_view_to', 2147483647, 1, 18),
('bx_market_entry_add', 'allow_purchase_to', 2147483647, 1, 19),
('bx_market_entry_add', 'allow_comment_to', 2147483647, 1, 20),
('bx_market_entry_add', 'allow_vote_to', 2147483647, 1, 21),
('bx_market_entry_add', 'header_end_privacy', 2147483647, 1, 22),
('bx_market_entry_add', 'notes', 2147483647, 1, 23),
('bx_market_entry_add', 'location', 2147483647, 1, 24),
('bx_market_entry_add', 'subentries', 2147483647, 1, 25),
('bx_market_entry_add', 'do_publish', 2147483647, 1, 26),
('bx_market_entry_edit', 'title', 2147483647, 1, 1),
('bx_market_entry_edit', 'name', 2147483647, 1, 2),
('bx_market_entry_edit', 'cat', 2147483647, 1, 3),
('bx_market_entry_edit', 'text', 2147483647, 1, 4),
('bx_market_entry_edit', 'pictures', 2147483647, 1, 5),
('bx_market_entry_edit', 'files', 2147483647, 1, 6),
('bx_market_entry_edit', 'header_beg_single', 2147483647, 1, 7),
('bx_market_entry_edit', 'warning_single', 2147483647, 1, 8),
('bx_market_entry_edit', 'price_single', 2147483647, 1, 9),
('bx_market_entry_edit', 'header_end_single', 2147483647, 1, 10),
('bx_market_entry_edit', 'header_beg_recurring', 2147483647, 1, 11),
('bx_market_entry_edit', 'warning_recurring', 2147483647, 1, 12),
('bx_market_entry_edit', 'duration_recurring', 2147483647, 1, 13),
('bx_market_entry_edit', 'price_recurring', 2147483647, 1, 14),
('bx_market_entry_edit', 'trial_recurring', 2147483647, 1, 15),
('bx_market_entry_edit', 'header_end_recurring', 2147483647, 1, 16),
('bx_market_entry_edit', 'header_beg_privacy', 2147483647, 1, 17),
('bx_market_entry_edit', 'allow_view_to', 2147483647, 1, 18),
('bx_market_entry_edit', 'allow_purchase_to', 2147483647, 1, 19),
('bx_market_entry_edit', 'allow_comment_to', 2147483647, 1, 20),
('bx_market_entry_edit', 'allow_vote_to', 2147483647, 1, 21),
('bx_market_entry_edit', 'header_end_privacy', 2147483647, 1, 22),
('bx_market_entry_edit', 'notes', 2147483647, 1, 23),
('bx_market_entry_edit', 'location', 2147483647, 1, 24),
('bx_market_entry_edit', 'subentries', 2147483647, 1, 25),
('bx_market_entry_edit', 'do_submit', 2147483647, 1, 26);
-- COMMENTS
UPDATE `sys_objects_cmts` SET `Module`='bx_market' WHERE `Name`='bx_market';
| camperjz/trident | modules/boonex/market/updates/9.0.4_9.0.5/install/sql/install.sql | SQL | mit | 4,626 | 56.825 | 311 | 0.666018 | false |
/**
* \file
*
* \brief USB configuration file for CDC application
*
* Copyright (c) 2014 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* 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. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
/**
* Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a>
*/
#ifndef _CONF_USB_H_
#define _CONF_USB_H_
#include <compiler.h>
/**
* USB Device Configuration
* @{
*/
/* ! Device definition */
#define USB_DEVICE_VENDOR_ID USB_VID_ATMEL
#define USB_DEVICE_PRODUCT_ID USB_PID_ATMEL_ASF_CDC
#define USB_DEVICE_MAJOR_VERSION 1
#define USB_DEVICE_MINOR_VERSION 0
#define USB_DEVICE_POWER 100
#define USB_DEVICE_MANUFACTURE_NAME "ATMEL ASF"
#define USB_DEVICE_PRODUCT_NAME "CDC"
#define USB_DEVICE_ATTR \
(USB_CONFIG_ATTR_SELF_POWERED)
/* (USB_CONFIG_ATTR_BUS_POWERED) */
/* (USB_CONFIG_ATTR_REMOTE_WAKEUP|USB_CONFIG_ATTR_SELF_POWERED) */
/* (USB_CONFIG_ATTR_REMOTE_WAKEUP|USB_CONFIG_ATTR_BUS_POWERED) */
/**
* Device speeds support
* Low speed not supported by CDC
* @{
*/
/* ! To authorize the High speed */
#if (UC3A3 || UC3A4)
/* #define USB_DEVICE_HS_SUPPORT */
#endif
/* @} */
#define USB_ENABLE
/**
* USB Device Callbacks definitions
* @{
*/
#define UDC_VBUS_EVENT(b_vbus_high)
#define UDC_SOF_EVENT()
#define UDC_SUSPEND_EVENT()
#define UDC_RESUME_EVENT()
/* @} */
/* @} */
/**
* USB Interface Configuration
* @{
*/
/**
* Configuration of CDC interface
* @{
*/
/* ! Interface callback definition */
#define UDI_CDC_ENABLE_EXT(port) main_cdc_enable(port)
#define UDI_CDC_DISABLE_EXT(port) main_cdc_disable(port)
#define UDI_CDC_RX_NOTIFY(port) usb_rx_notify()
#define UDI_CDC_SET_CODING_EXT(port, cfg)
#define UDI_CDC_SET_DTR_EXT(port, set) dtr_cb(set)
#define UDI_CDC_SET_RTS_EXT(port, set)
bool main_cdc_enable(uint8_t port);
/*! \brief Called by CDC interface
* Callback running when USB Host disable cdc interface
*/
void main_cdc_disable(uint8_t port);
/* ! Default configuration of communication port */
#define UDI_CDC_DEFAULT_RATE 115200
#define UDI_CDC_DEFAULT_STOPBITS CDC_STOP_BITS_1
#define UDI_CDC_DEFAULT_PARITY CDC_PAR_NONE
#define UDI_CDC_DEFAULT_DATABITS 8
/* @} */
/* @} */
/**
* USB Device Driver Configuration
* @{
*/
/* @} */
/* ! The includes of classes and other headers must be done at the end of this
* file to avoid compile error */
#include <udi_cdc_conf.h>
#include "sio2host.h"
#endif /* _CONF_USB_H_ */
| femtoio/femto-usb-blink-example | blinky/blinky/asf-3.21.0/thirdparty/wireless/avr2102_rf4control/apps/zrc/terminal_tgt/at32uc3a3256s_rz600_at86rf231/conf_usb.h | C | mit | 4,137 | 28.55 | 90 | 0.686971 | false |
package org.knowm.xchange.loyalbit.service;
import java.io.IOException;
import javax.crypto.Mac;
import javax.ws.rs.FormParam;
import org.knowm.xchange.service.BaseParamsDigest;
import net.iharder.Base64;
import si.mazi.rescu.RestInvocation;
public class LoyalbitDigest extends BaseParamsDigest {
private final String clientId;
private final byte[] apiKey;
private LoyalbitDigest(String secretKeyHex, String clientId, String apiKeyHex) throws IOException {
super(secretKeyHex.getBytes(), HMAC_SHA_256);
this.clientId = clientId;
this.apiKey = apiKeyHex.getBytes();
}
public static LoyalbitDigest createInstance(String secretKeyBase64, String clientId, String apiKey) {
try {
return secretKeyBase64 == null ? null : new LoyalbitDigest(secretKeyBase64, clientId, apiKey);
} catch (IOException e) {
throw new IllegalArgumentException("Error parsing API key or secret", e);
}
}
@Override
public String digestParams(RestInvocation restInvocation) {
Mac mac256 = getMac();
mac256.update(restInvocation.getInvocationUrl().getBytes());
mac256.update(restInvocation.getParamValue(FormParam.class, "nonce").toString().getBytes());
mac256.update(clientId.getBytes());
mac256.update(apiKey);
return Base64.encodeBytes(mac256.doFinal());
}
} | stevenuray/XChange | xchange-loyalbit/src/main/java/org/knowm/xchange/loyalbit/service/LoyalbitDigest.java | Java | mit | 1,316 | 30.357143 | 103 | 0.74924 | false |
using System;
using Xamarin.Forms.CustomAttributes;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Xamarin.Forms.Internals;
#if UITEST
using Xamarin.UITest;
using NUnit.Framework;
#endif
namespace Xamarin.Forms.Controls
{
[Preserve (AllMembers = true)]
[Issue (IssueTracker.Bugzilla, 27350, "Binding throws Null Pointer Exception when Updating Tab")]
public class Bugzilla27350 : TestContentPage // or TestMasterDetailPage, etc ...
{
protected override void Init ()
{
var btn = new Button { Text = "next main" };
btn.Clicked += async (object sender, EventArgs e) => await Navigation.PushAsync (new MainPage1 ());
Content = btn;
}
class RecipeViewModel
{
public Recipe Recipe { get; set; }
public ObservableCollection<RecipeGroup> RecipeGroups { get; set; }
#pragma warning disable 1998 // considered for removal
public async Task LoadRecipesAsync ()
#pragma warning restore 1998
{
var groups = new ObservableCollection<RecipeGroup> ();
groups.Add (new RecipeGroup { Title = "Teste 1" });
groups.Add (new RecipeGroup { Title = "Teste 2" });
groups.Add (new RecipeGroup { Title = "Teste 3" });
groups.Add (new RecipeGroup { Title = "Teste 4" });
groups.Add (new RecipeGroup { Title = "Teste 5" });
groups.Add (new RecipeGroup { Title = "Teste 6" });
groups.Add (new RecipeGroup { Title = "Teste 4" });
groups.Add (new RecipeGroup { Title = "Teste 5" });
groups.Add (new RecipeGroup { Title = "Teste 6" });
RecipeGroups = groups;
}
}
class Recipe
{
public string ID { get; set; }
public string Title { get; set; }
public string Subtitle { get; set; }
public string Description { get; set; }
public string ImagePath { get; set; }
public string TileImagePath { get; set; }
public int PrepTime { get; set; }
public string Directions { get; set; }
public List<string> Ingredients { get; set; }
}
class RecipeGroup : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged (string caller)
{
var handler = PropertyChanged;
if (handler != null) {
handler (this, new PropertyChangedEventArgs (caller));
}
}
public string ID { get; set; }
public string Title {
get{ return _title; }
set {
_title = value;
OnPropertyChanged ("Title");
}
}
string _title;
public string Subtitle { get; set; }
public string ImagePath { get; set; }
public string GroupImagePath { get; set; }
public string Description { get; set; }
public List<Recipe> Recipes { get; set; }
}
class MainPage1 : TabbedPage
{
public MainPage1 ()
{
ItemTemplate = new DataTemplate (() => {
var page = new ContentPage ();
page.SetBinding (TitleProperty, new Binding ("Title"));
var btn = new Button { Text = "change", Command = new Command (() => {
(page.BindingContext as RecipeGroup).Title = "we changed";
})
};
var btn1 = new Button { Text = "null", Command = new Command (() => {
(page.BindingContext as RecipeGroup).Title = null;
})
};
page.Content = new StackLayout { Children = { btn, btn1 } };
return page;
});
SetBinding (ItemsSourceProperty, new Binding ("RecipeGroups"));
}
protected override async void OnAppearing ()
{
base.OnAppearing ();
if (BindingContext == null)
BindingContext = await GetRecipeViewModelAsync ();
}
RecipeViewModel _rvm;
public async Task<RecipeViewModel> GetRecipeViewModelAsync ()
{
if (_rvm == null) {
_rvm = new RecipeViewModel ();
} else {
_rvm.RecipeGroups.Clear ();
}
await _rvm.LoadRecipesAsync ();
return _rvm;
}
}
}
}
| Hitcents/Xamarin.Forms | Xamarin.Forms.Controls.Issues/Xamarin.Forms.Controls.Issues.Shared/Bugzilla27350.cs | C# | mit | 3,844 | 24.111111 | 102 | 0.648621 | false |
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Gitlab::Middleware::ReleaseEnv do
let(:inner_app) { double(:app, call: 'yay') }
let(:app) { described_class.new(inner_app) }
let(:env) { { 'action_controller.instance' => 'something' } }
describe '#call' do
it 'calls the app and clears the env' do
result = app.call(env)
expect(result).to eq('yay')
expect(env).to be_empty
end
end
end
| mmkassem/gitlabhq | spec/lib/gitlab/middleware/release_env_spec.rb | Ruby | mit | 442 | 23.555556 | 63 | 0.642534 | false |
package org.jenkinsci.plugins.github.status.sources;
import hudson.model.Run;
import hudson.model.TaskListener;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kohsuke.github.GHRepository;
import org.mockito.Answers;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import java.io.PrintStream;
import java.util.List;
import static com.jayway.restassured.RestAssured.when;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class ManuallyEnteredRepositorySourceTest {
@Mock(answer = Answers.RETURNS_MOCKS)
private Run run;
@Mock(answer = Answers.RETURNS_MOCKS)
private TaskListener listener;
@Mock(answer = Answers.RETURNS_MOCKS)
private PrintStream logger;
@Test
public void nullName() {
ManuallyEnteredRepositorySource instance = Mockito.spy(new ManuallyEnteredRepositorySource("https://github.com/jenkinsci/jenkins"));
doReturn(null).when(instance).createName(Matchers.anyString());
doReturn(logger).when(listener).getLogger();
List<GHRepository> repos = instance.repos(run, listener);
assertThat("size", repos, hasSize(0));
verify(listener).getLogger();
verify(logger).printf(eq("Unable to match %s with a GitHub repository.%n"), eq("https://github.com/jenkinsci/jenkins"));
}
}
| ouaibsky/github-plugin | src/test/java/org/jenkinsci/plugins/github/status/sources/ManuallyEnteredRepositorySourceTest.java | Java | mit | 1,607 | 34.711111 | 140 | 0.761045 | false |
#include "lua_cocos2dx_experimental_video_auto.hpp"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#include "UIVideoPlayer.h"
#include "tolua_fix.h"
#include "LuaBasicConversions.h"
int lua_cocos2dx_experimental_video_VideoPlayer_getFileName(lua_State* tolua_S)
{
int argc = 0;
cocos2d::experimental::ui::VideoPlayer* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"ccexp.VideoPlayer",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::experimental::ui::VideoPlayer*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_experimental_video_VideoPlayer_getFileName'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_experimental_video_VideoPlayer_getFileName'", nullptr);
return 0;
}
const std::string& ret = cobj->getFileName();
tolua_pushcppstring(tolua_S,ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccexp.VideoPlayer:getFileName",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_experimental_video_VideoPlayer_getFileName'.",&tolua_err);
#endif
return 0;
}
int lua_cocos2dx_experimental_video_VideoPlayer_getURL(lua_State* tolua_S)
{
int argc = 0;
cocos2d::experimental::ui::VideoPlayer* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"ccexp.VideoPlayer",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::experimental::ui::VideoPlayer*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_experimental_video_VideoPlayer_getURL'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_experimental_video_VideoPlayer_getURL'", nullptr);
return 0;
}
const std::string& ret = cobj->getURL();
tolua_pushcppstring(tolua_S,ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccexp.VideoPlayer:getURL",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_experimental_video_VideoPlayer_getURL'.",&tolua_err);
#endif
return 0;
}
int lua_cocos2dx_experimental_video_VideoPlayer_play(lua_State* tolua_S)
{
int argc = 0;
cocos2d::experimental::ui::VideoPlayer* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"ccexp.VideoPlayer",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::experimental::ui::VideoPlayer*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_experimental_video_VideoPlayer_play'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_experimental_video_VideoPlayer_play'", nullptr);
return 0;
}
cobj->play();
lua_settop(tolua_S, 1);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccexp.VideoPlayer:play",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_experimental_video_VideoPlayer_play'.",&tolua_err);
#endif
return 0;
}
int lua_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled(lua_State* tolua_S)
{
int argc = 0;
cocos2d::experimental::ui::VideoPlayer* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"ccexp.VideoPlayer",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::experimental::ui::VideoPlayer*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
bool arg0;
ok &= luaval_to_boolean(tolua_S, 2,&arg0, "ccexp.VideoPlayer:setKeepAspectRatioEnabled");
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled'", nullptr);
return 0;
}
cobj->setKeepAspectRatioEnabled(arg0);
lua_settop(tolua_S, 1);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccexp.VideoPlayer:setKeepAspectRatioEnabled",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled'.",&tolua_err);
#endif
return 0;
}
int lua_cocos2dx_experimental_video_VideoPlayer_stop(lua_State* tolua_S)
{
int argc = 0;
cocos2d::experimental::ui::VideoPlayer* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"ccexp.VideoPlayer",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::experimental::ui::VideoPlayer*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_experimental_video_VideoPlayer_stop'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_experimental_video_VideoPlayer_stop'", nullptr);
return 0;
}
cobj->stop();
lua_settop(tolua_S, 1);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccexp.VideoPlayer:stop",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_experimental_video_VideoPlayer_stop'.",&tolua_err);
#endif
return 0;
}
int lua_cocos2dx_experimental_video_VideoPlayer_setFullScreenEnabled(lua_State* tolua_S)
{
int argc = 0;
cocos2d::experimental::ui::VideoPlayer* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"ccexp.VideoPlayer",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::experimental::ui::VideoPlayer*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_experimental_video_VideoPlayer_setFullScreenEnabled'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
bool arg0;
ok &= luaval_to_boolean(tolua_S, 2,&arg0, "ccexp.VideoPlayer:setFullScreenEnabled");
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_experimental_video_VideoPlayer_setFullScreenEnabled'", nullptr);
return 0;
}
cobj->setFullScreenEnabled(arg0);
lua_settop(tolua_S, 1);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccexp.VideoPlayer:setFullScreenEnabled",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_experimental_video_VideoPlayer_setFullScreenEnabled'.",&tolua_err);
#endif
return 0;
}
int lua_cocos2dx_experimental_video_VideoPlayer_setFileName(lua_State* tolua_S)
{
int argc = 0;
cocos2d::experimental::ui::VideoPlayer* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"ccexp.VideoPlayer",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::experimental::ui::VideoPlayer*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_experimental_video_VideoPlayer_setFileName'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
std::string arg0;
ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccexp.VideoPlayer:setFileName");
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_experimental_video_VideoPlayer_setFileName'", nullptr);
return 0;
}
cobj->setFileName(arg0);
lua_settop(tolua_S, 1);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccexp.VideoPlayer:setFileName",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_experimental_video_VideoPlayer_setFileName'.",&tolua_err);
#endif
return 0;
}
int lua_cocos2dx_experimental_video_VideoPlayer_setURL(lua_State* tolua_S)
{
int argc = 0;
cocos2d::experimental::ui::VideoPlayer* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"ccexp.VideoPlayer",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::experimental::ui::VideoPlayer*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_experimental_video_VideoPlayer_setURL'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
std::string arg0;
ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccexp.VideoPlayer:setURL");
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_experimental_video_VideoPlayer_setURL'", nullptr);
return 0;
}
cobj->setURL(arg0);
lua_settop(tolua_S, 1);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccexp.VideoPlayer:setURL",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_experimental_video_VideoPlayer_setURL'.",&tolua_err);
#endif
return 0;
}
int lua_cocos2dx_experimental_video_VideoPlayer_isKeepAspectRatioEnabled(lua_State* tolua_S)
{
int argc = 0;
cocos2d::experimental::ui::VideoPlayer* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"ccexp.VideoPlayer",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::experimental::ui::VideoPlayer*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_experimental_video_VideoPlayer_isKeepAspectRatioEnabled'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_experimental_video_VideoPlayer_isKeepAspectRatioEnabled'", nullptr);
return 0;
}
bool ret = cobj->isKeepAspectRatioEnabled();
tolua_pushboolean(tolua_S,(bool)ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccexp.VideoPlayer:isKeepAspectRatioEnabled",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_experimental_video_VideoPlayer_isKeepAspectRatioEnabled'.",&tolua_err);
#endif
return 0;
}
int lua_cocos2dx_experimental_video_VideoPlayer_onPlayEvent(lua_State* tolua_S)
{
int argc = 0;
cocos2d::experimental::ui::VideoPlayer* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"ccexp.VideoPlayer",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::experimental::ui::VideoPlayer*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_experimental_video_VideoPlayer_onPlayEvent'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
int arg0;
ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccexp.VideoPlayer:onPlayEvent");
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_experimental_video_VideoPlayer_onPlayEvent'", nullptr);
return 0;
}
cobj->onPlayEvent(arg0);
lua_settop(tolua_S, 1);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccexp.VideoPlayer:onPlayEvent",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_experimental_video_VideoPlayer_onPlayEvent'.",&tolua_err);
#endif
return 0;
}
int lua_cocos2dx_experimental_video_VideoPlayer_isFullScreenEnabled(lua_State* tolua_S)
{
int argc = 0;
cocos2d::experimental::ui::VideoPlayer* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"ccexp.VideoPlayer",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::experimental::ui::VideoPlayer*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_experimental_video_VideoPlayer_isFullScreenEnabled'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_experimental_video_VideoPlayer_isFullScreenEnabled'", nullptr);
return 0;
}
bool ret = cobj->isFullScreenEnabled();
tolua_pushboolean(tolua_S,(bool)ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccexp.VideoPlayer:isFullScreenEnabled",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_experimental_video_VideoPlayer_isFullScreenEnabled'.",&tolua_err);
#endif
return 0;
}
int lua_cocos2dx_experimental_video_VideoPlayer_isPlaying(lua_State* tolua_S)
{
int argc = 0;
cocos2d::experimental::ui::VideoPlayer* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"ccexp.VideoPlayer",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::experimental::ui::VideoPlayer*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_experimental_video_VideoPlayer_isPlaying'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_experimental_video_VideoPlayer_isPlaying'", nullptr);
return 0;
}
bool ret = cobj->isPlaying();
tolua_pushboolean(tolua_S,(bool)ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccexp.VideoPlayer:isPlaying",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_experimental_video_VideoPlayer_isPlaying'.",&tolua_err);
#endif
return 0;
}
int lua_cocos2dx_experimental_video_VideoPlayer_seekTo(lua_State* tolua_S)
{
int argc = 0;
cocos2d::experimental::ui::VideoPlayer* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"ccexp.VideoPlayer",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::experimental::ui::VideoPlayer*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_experimental_video_VideoPlayer_seekTo'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
double arg0;
ok &= luaval_to_number(tolua_S, 2,&arg0, "ccexp.VideoPlayer:seekTo");
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_experimental_video_VideoPlayer_seekTo'", nullptr);
return 0;
}
cobj->seekTo(arg0);
lua_settop(tolua_S, 1);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccexp.VideoPlayer:seekTo",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_experimental_video_VideoPlayer_seekTo'.",&tolua_err);
#endif
return 0;
}
int lua_cocos2dx_experimental_video_VideoPlayer_create(lua_State* tolua_S)
{
int argc = 0;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertable(tolua_S,1,"ccexp.VideoPlayer",0,&tolua_err)) goto tolua_lerror;
#endif
argc = lua_gettop(tolua_S) - 1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_experimental_video_VideoPlayer_create'", nullptr);
return 0;
}
cocos2d::experimental::ui::VideoPlayer* ret = cocos2d::experimental::ui::VideoPlayer::create();
object_to_luaval<cocos2d::experimental::ui::VideoPlayer>(tolua_S, "ccexp.VideoPlayer",(cocos2d::experimental::ui::VideoPlayer*)ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "ccexp.VideoPlayer:create",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_experimental_video_VideoPlayer_create'.",&tolua_err);
#endif
return 0;
}
int lua_cocos2dx_experimental_video_VideoPlayer_constructor(lua_State* tolua_S)
{
int argc = 0;
cocos2d::experimental::ui::VideoPlayer* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_experimental_video_VideoPlayer_constructor'", nullptr);
return 0;
}
cobj = new cocos2d::experimental::ui::VideoPlayer();
cobj->autorelease();
int ID = (int)cobj->_ID ;
int* luaID = &cobj->_luaID ;
toluafix_pushusertype_ccobject(tolua_S, ID, luaID, (void*)cobj,"ccexp.VideoPlayer");
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccexp.VideoPlayer:VideoPlayer",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_experimental_video_VideoPlayer_constructor'.",&tolua_err);
#endif
return 0;
}
static int lua_cocos2dx_experimental_video_VideoPlayer_finalize(lua_State* tolua_S)
{
printf("luabindings: finalizing LUA object (VideoPlayer)");
return 0;
}
int lua_register_cocos2dx_experimental_video_VideoPlayer(lua_State* tolua_S)
{
tolua_usertype(tolua_S,"ccexp.VideoPlayer");
tolua_cclass(tolua_S,"VideoPlayer","ccexp.VideoPlayer","ccui.Widget",nullptr);
tolua_beginmodule(tolua_S,"VideoPlayer");
tolua_function(tolua_S,"new",lua_cocos2dx_experimental_video_VideoPlayer_constructor);
tolua_function(tolua_S,"getFileName",lua_cocos2dx_experimental_video_VideoPlayer_getFileName);
tolua_function(tolua_S,"getURL",lua_cocos2dx_experimental_video_VideoPlayer_getURL);
tolua_function(tolua_S,"play",lua_cocos2dx_experimental_video_VideoPlayer_play);
tolua_function(tolua_S,"setKeepAspectRatioEnabled",lua_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled);
tolua_function(tolua_S,"stop",lua_cocos2dx_experimental_video_VideoPlayer_stop);
tolua_function(tolua_S,"setFullScreenEnabled",lua_cocos2dx_experimental_video_VideoPlayer_setFullScreenEnabled);
tolua_function(tolua_S,"setFileName",lua_cocos2dx_experimental_video_VideoPlayer_setFileName);
tolua_function(tolua_S,"setURL",lua_cocos2dx_experimental_video_VideoPlayer_setURL);
tolua_function(tolua_S,"isKeepAspectRatioEnabled",lua_cocos2dx_experimental_video_VideoPlayer_isKeepAspectRatioEnabled);
tolua_function(tolua_S,"onPlayEvent",lua_cocos2dx_experimental_video_VideoPlayer_onPlayEvent);
tolua_function(tolua_S,"isFullScreenEnabled",lua_cocos2dx_experimental_video_VideoPlayer_isFullScreenEnabled);
tolua_function(tolua_S,"isPlaying",lua_cocos2dx_experimental_video_VideoPlayer_isPlaying);
tolua_function(tolua_S,"seekTo",lua_cocos2dx_experimental_video_VideoPlayer_seekTo);
tolua_function(tolua_S,"create", lua_cocos2dx_experimental_video_VideoPlayer_create);
tolua_endmodule(tolua_S);
std::string typeName = typeid(cocos2d::experimental::ui::VideoPlayer).name();
g_luaType[typeName] = "ccexp.VideoPlayer";
g_typeCast["VideoPlayer"] = "ccexp.VideoPlayer";
return 1;
}
TOLUA_API int register_all_cocos2dx_experimental_video(lua_State* tolua_S)
{
tolua_open(tolua_S);
tolua_module(tolua_S,"ccexp",0);
tolua_beginmodule(tolua_S,"ccexp");
lua_register_cocos2dx_experimental_video_VideoPlayer(tolua_S);
tolua_endmodule(tolua_S);
return 1;
}
#endif
| dios-game/dios-cocos | src/oslibs/cocos/cocos-src/cocos/scripting/lua-bindings/auto/lua_cocos2dx_experimental_video_auto.cpp | C++ | mit | 22,866 | 29.32626 | 146 | 0.652891 | false |
<table class="palm-divider labeled">
<tr>
<td class="left"></td>
<td class="label">
#{dividerLabel}
</td>
<td class="right"></td>
</tr>
</table>
| johannjacobsohn/Mensa-Hamburg-App | webos/mojo/app/views/menu/dividerTemplate.html | HTML | mit | 158 | 16.555556 | 36 | 0.56962 | false |
<html><!-- Created using the cpp_pretty_printer from the dlib C++ library. See http://dlib.net for updates. --><head><title>dlib C++ Library - cpu_dlib.h</title></head><body bgcolor='white'><pre>
<font color='#009900'>// Copyright (C) 2015 Davis E. King (davis@dlib.net)
</font><font color='#009900'>// License: Boost Software License See LICENSE.txt for the full license.
</font><font color='#0000FF'>#ifndef</font> DLIB_DNN_CPU_H_
<font color='#0000FF'>#define</font> DLIB_DNN_CPU_H_
<font color='#009900'>// This file contains CPU implementations of the GPU based functions in cuda_dlib.h
</font><font color='#009900'>// and cudnn_dlibapi.h
</font>
<font color='#0000FF'>#include</font> "<a style='text-decoration:none' href='tensor.h.html'>tensor.h</a>"
<font color='#0000FF'>namespace</font> dlib
<b>{</b>
<font color='#0000FF'>namespace</font> cpu
<b>{</b>
<font color='#009900'>// -----------------------------------------------------------------------------------
</font>
<font color='#0000FF'><u>void</u></font> <b><a name='multiply'></a>multiply</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'><u>bool</u></font> add_to,
tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src1,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src2
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='multiply_conv'></a>multiply_conv</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'><u>bool</u></font> add_to,
tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src1,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src2
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='add'></a>add</b><font face='Lucida Console'>(</font>
<font color='#0000FF'><u>float</u></font> beta,
tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'><u>float</u></font> alpha,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='assign_bias_gradient'></a>assign_bias_gradient</b> <font face='Lucida Console'>(</font>
tensor<font color='#5555FF'>&</font> grad,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> gradient_input
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='add'></a>add</b> <font face='Lucida Console'>(</font>
tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src1,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src2
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='assign_conv_bias_gradient'></a>assign_conv_bias_gradient</b> <font face='Lucida Console'>(</font>
tensor<font color='#5555FF'>&</font> grad,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> gradient_input
<font face='Lucida Console'>)</font>;
<font color='#009900'>// -----------------------------------------------------------------------------------
</font>
<font color='#0000FF'><u>void</u></font> <b><a name='affine_transform'></a>affine_transform</b><font face='Lucida Console'>(</font>
tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src,
<font color='#0000FF'>const</font> <font color='#0000FF'><u>float</u></font> A,
<font color='#0000FF'>const</font> <font color='#0000FF'><u>float</u></font> B
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='affine_transform'></a>affine_transform</b><font face='Lucida Console'>(</font>
tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src1,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src2,
<font color='#0000FF'>const</font> <font color='#0000FF'><u>float</u></font> A,
<font color='#0000FF'>const</font> <font color='#0000FF'><u>float</u></font> B,
<font color='#0000FF'>const</font> <font color='#0000FF'><u>float</u></font> C
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='affine_transform'></a>affine_transform</b><font face='Lucida Console'>(</font>
tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src1,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src2,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src3,
<font color='#0000FF'>const</font> <font color='#0000FF'><u>float</u></font> A,
<font color='#0000FF'>const</font> <font color='#0000FF'><u>float</u></font> B,
<font color='#0000FF'>const</font> <font color='#0000FF'><u>float</u></font> C,
<font color='#0000FF'>const</font> <font color='#0000FF'><u>float</u></font> D
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='affine_transform_range'></a>affine_transform_range</b><font face='Lucida Console'>(</font>
<font color='#0000FF'><u>size_t</u></font> begin,
<font color='#0000FF'><u>size_t</u></font> end,
tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src1,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src2,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src3,
<font color='#0000FF'>const</font> <font color='#0000FF'><u>float</u></font> A,
<font color='#0000FF'>const</font> <font color='#0000FF'><u>float</u></font> B,
<font color='#0000FF'>const</font> <font color='#0000FF'><u>float</u></font> C
<font face='Lucida Console'>)</font>;
<font color='#009900'>// -----------------------------------------------------------------------------------
</font>
<font color='#0000FF'><u>void</u></font> <b><a name='affine_transform'></a>affine_transform</b><font face='Lucida Console'>(</font>
tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> A,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> B
<font face='Lucida Console'>)</font>;
<font color='#009900'>// -----------------------------------------------------------------------------------
</font>
<font color='#0000FF'><u>void</u></font> <b><a name='affine_transform_conv'></a>affine_transform_conv</b><font face='Lucida Console'>(</font>
tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> A,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> B
<font face='Lucida Console'>)</font>;
<font color='#009900'>// -----------------------------------------------------------------------------------
</font>
<font color='#0000FF'><u>void</u></font> <b><a name='compute_adam_update'></a>compute_adam_update</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'><u>size_t</u></font> begin,
<font color='#0000FF'><u>size_t</u></font> end,
tensor<font color='#5555FF'>&</font> s,
tensor<font color='#5555FF'>&</font> m,
tensor<font color='#5555FF'>&</font> v,
<font color='#0000FF'>const</font> <font color='#0000FF'><u>float</u></font> t,
<font color='#0000FF'>const</font> <font color='#0000FF'><u>float</u></font> learning_rate,
<font color='#0000FF'>const</font> <font color='#0000FF'><u>float</u></font> weight_decay,
<font color='#0000FF'>const</font> <font color='#0000FF'><u>float</u></font> momentum1,
<font color='#0000FF'>const</font> <font color='#0000FF'><u>float</u></font> momentum2,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> params,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> params_grad
<font face='Lucida Console'>)</font>;
<font color='#009900'>// -----------------------------------------------------------------------------------
</font>
<font color='#0000FF'><u>void</u></font> <b><a name='batch_normalize_inference'></a>batch_normalize_inference</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'>const</font> <font color='#0000FF'><u>double</u></font> eps,
resizable_tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> gamma,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> beta,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> running_means,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> running_variances
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='batch_normalize'></a>batch_normalize</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'>const</font> <font color='#0000FF'><u>double</u></font> eps,
resizable_tensor<font color='#5555FF'>&</font> dest,
resizable_tensor<font color='#5555FF'>&</font> means,
resizable_tensor<font color='#5555FF'>&</font> invstds,
<font color='#0000FF'>const</font> <font color='#0000FF'><u>double</u></font> averaging_factor,
resizable_tensor<font color='#5555FF'>&</font> running_means,
resizable_tensor<font color='#5555FF'>&</font> running_variances,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> gamma,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> beta
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='batch_normalize_gradient'></a>batch_normalize_gradient</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'>const</font> <font color='#0000FF'><u>double</u></font> eps,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> gradient_input,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> means,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> invstds,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> gamma,
tensor<font color='#5555FF'>&</font> src_grad,
tensor<font color='#5555FF'>&</font> gamma_grad,
tensor<font color='#5555FF'>&</font> beta_grad
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='batch_normalize_conv_inference'></a>batch_normalize_conv_inference</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'>const</font> <font color='#0000FF'><u>double</u></font> eps,
resizable_tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> gamma,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> beta,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> running_means,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> running_variances
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='batch_normalize_conv'></a>batch_normalize_conv</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'>const</font> <font color='#0000FF'><u>double</u></font> eps,
resizable_tensor<font color='#5555FF'>&</font> dest,
resizable_tensor<font color='#5555FF'>&</font> means,
resizable_tensor<font color='#5555FF'>&</font> invstds,
<font color='#0000FF'>const</font> <font color='#0000FF'><u>double</u></font> averaging_factor,
resizable_tensor<font color='#5555FF'>&</font> running_means,
resizable_tensor<font color='#5555FF'>&</font> running_variances,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> gamma,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> beta
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='batch_normalize_conv_gradient'></a>batch_normalize_conv_gradient</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'>const</font> <font color='#0000FF'><u>double</u></font> eps,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> gradient_input,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> means,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> invstds,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> gamma,
tensor<font color='#5555FF'>&</font> src_grad,
tensor<font color='#5555FF'>&</font> gamma_grad,
tensor<font color='#5555FF'>&</font> beta_grad
<font face='Lucida Console'>)</font>;
<font color='#009900'>// -----------------------------------------------------------------------------------
</font>
<font color='#0000FF'><u>void</u></font> <b><a name='threshold'></a>threshold</b> <font face='Lucida Console'>(</font>
tensor<font color='#5555FF'>&</font> data,
<font color='#0000FF'><u>float</u></font> thresh
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='dot'></a>dot</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> a,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> b,
tensor<font color='#5555FF'>&</font> result,
<font color='#0000FF'><u>size_t</u></font> idx
<font face='Lucida Console'>)</font>;
<font color='#009900'>// -----------------------------------------------------------------------------------
</font>
<font color='#0000FF'><u>void</u></font> <b><a name='softmax'></a>softmax</b> <font face='Lucida Console'>(</font>
tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='softmax_gradient'></a>softmax_gradient</b> <font face='Lucida Console'>(</font>
tensor<font color='#5555FF'>&</font> grad,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> gradient_input
<font face='Lucida Console'>)</font>;
<font color='#009900'>// ------------------------------------------------------------------------------------
</font>
<font color='#0000FF'><u>void</u></font> <b><a name='sigmoid'></a>sigmoid</b> <font face='Lucida Console'>(</font>
tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='sigmoid_gradient'></a>sigmoid_gradient</b> <font face='Lucida Console'>(</font>
tensor<font color='#5555FF'>&</font> grad,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> gradient_input
<font face='Lucida Console'>)</font>;
<font color='#009900'>// ------------------------------------------------------------------------------------
</font>
<font color='#0000FF'><u>void</u></font> <b><a name='relu'></a>relu</b> <font face='Lucida Console'>(</font>
tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='relu_gradient'></a>relu_gradient</b> <font face='Lucida Console'>(</font>
tensor<font color='#5555FF'>&</font> grad,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> gradient_input
<font face='Lucida Console'>)</font>;
<font color='#009900'>// ----------------------------------------------------------------------------------------
</font>
<font color='#0000FF'><u>void</u></font> <b><a name='prelu'></a>prelu</b> <font face='Lucida Console'>(</font>
tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> param
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='prelu_gradient'></a>prelu_gradient</b> <font face='Lucida Console'>(</font>
tensor<font color='#5555FF'>&</font> grad,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> gradient_input,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> param,
tensor<font color='#5555FF'>&</font> params_grad
<font face='Lucida Console'>)</font>;
<font color='#009900'>// ------------------------------------------------------------------------------------
</font>
<font color='#0000FF'><u>void</u></font> <b><a name='tanh'></a>tanh</b> <font face='Lucida Console'>(</font>
tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='tanh_gradient'></a>tanh_gradient</b> <font face='Lucida Console'>(</font>
tensor<font color='#5555FF'>&</font> grad,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> gradient_input
<font face='Lucida Console'>)</font>;
<font color='#009900'>// -----------------------------------------------------------------------------------
</font>
<font color='#0000FF'>class</font> <b><a name='pooling'></a>pooling</b>
<b>{</b>
<font color='#0000FF'>public</font>:
<b><a name='pooling'></a>pooling</b><font face='Lucida Console'>(</font><font color='#0000FF'>const</font> pooling<font color='#5555FF'>&</font><font face='Lucida Console'>)</font> <font color='#5555FF'>=</font> <font color='#0000FF'>delete</font>;
pooling<font color='#5555FF'>&</font> <b><a name='operator'></a>operator</b><font color='#5555FF'>=</font><font face='Lucida Console'>(</font><font color='#0000FF'>const</font> pooling<font color='#5555FF'>&</font><font face='Lucida Console'>)</font> <font color='#5555FF'>=</font> <font color='#0000FF'>delete</font>;
<b><a name='pooling'></a>pooling</b> <font face='Lucida Console'>(</font>
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='clear'></a>clear</b><font face='Lucida Console'>(</font>
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='setup_max_pooling'></a>setup_max_pooling</b><font face='Lucida Console'>(</font>
<font color='#0000FF'><u>int</u></font> window_height,
<font color='#0000FF'><u>int</u></font> window_width,
<font color='#0000FF'><u>int</u></font> stride_y,
<font color='#0000FF'><u>int</u></font> stride_x,
<font color='#0000FF'><u>int</u></font> padding_y,
<font color='#0000FF'><u>int</u></font> padding_x
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='setup_avg_pooling'></a>setup_avg_pooling</b><font face='Lucida Console'>(</font>
<font color='#0000FF'><u>int</u></font> window_height,
<font color='#0000FF'><u>int</u></font> window_width,
<font color='#0000FF'><u>int</u></font> stride_y,
<font color='#0000FF'><u>int</u></font> stride_x,
<font color='#0000FF'><u>int</u></font> padding_y,
<font color='#0000FF'><u>int</u></font> padding_x
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>bool</u></font> <b><a name='does_max_pooling'></a>does_max_pooling</b><font face='Lucida Console'>(</font>
<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> do_max_pooling; <b>}</b>
<font color='#0000FF'><u>void</u></font> <b><a name='operator'></a>operator</b><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font face='Lucida Console'>(</font>
resizable_tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='get_gradient'></a>get_gradient</b><font face='Lucida Console'>(</font>
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> gradient_input,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src,
tensor<font color='#5555FF'>&</font> grad
<font face='Lucida Console'>)</font>;
<font color='#0000FF'>private</font>:
<font color='#0000FF'><u>int</u></font> window_height;
<font color='#0000FF'><u>int</u></font> window_width;
<font color='#0000FF'><u>int</u></font> stride_y;
<font color='#0000FF'><u>int</u></font> stride_x;
<font color='#0000FF'><u>int</u></font> padding_y;
<font color='#0000FF'><u>int</u></font> padding_x;
<font color='#0000FF'><u>bool</u></font> do_max_pooling;
<b>}</b>;
<font color='#009900'>// -----------------------------------------------------------------------------------
</font>
<font color='#0000FF'>class</font> <b><a name='tensor_conv'></a>tensor_conv</b>
<b>{</b>
<font color='#0000FF'>public</font>:
<b><a name='tensor_conv'></a>tensor_conv</b><font face='Lucida Console'>(</font><font color='#0000FF'>const</font> tensor_conv<font color='#5555FF'>&</font><font face='Lucida Console'>)</font> <font color='#5555FF'>=</font> <font color='#0000FF'>delete</font>;
tensor_conv<font color='#5555FF'>&</font> <b><a name='operator'></a>operator</b><font color='#5555FF'>=</font><font face='Lucida Console'>(</font><font color='#0000FF'>const</font> tensor_conv<font color='#5555FF'>&</font><font face='Lucida Console'>)</font> <font color='#5555FF'>=</font> <font color='#0000FF'>delete</font>;
<b><a name='tensor_conv'></a>tensor_conv</b><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <b>{</b><b>}</b>
<font color='#0000FF'><u>void</u></font> <b><a name='clear'></a>clear</b><font face='Lucida Console'>(</font>
<font face='Lucida Console'>)</font> <b>{</b><b>}</b>
<font color='#0000FF'><u>void</u></font> <b><a name='operator'></a>operator</b><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font face='Lucida Console'>(</font>
resizable_tensor<font color='#5555FF'>&</font> output,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> data,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> filters,
<font color='#0000FF'><u>int</u></font> stride_y,
<font color='#0000FF'><u>int</u></font> stride_x,
<font color='#0000FF'><u>int</u></font> padding_y,
<font color='#0000FF'><u>int</u></font> padding_x
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='get_gradient_for_data'></a>get_gradient_for_data</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> gradient_input,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> filters,
tensor<font color='#5555FF'>&</font> data_gradient
<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='get_gradient_for_filters'></a>get_gradient_for_filters</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> gradient_input,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> data,
tensor<font color='#5555FF'>&</font> filters_gradient
<font face='Lucida Console'>)</font>;
<font color='#0000FF'>private</font>:
<font color='#0000FF'><u>long</u></font> last_stride_y;
<font color='#0000FF'><u>long</u></font> last_stride_x;
<font color='#0000FF'><u>long</u></font> last_padding_y;
<font color='#0000FF'><u>long</u></font> last_padding_x;
<b>}</b>;
<font color='#009900'>// -----------------------------------------------------------------------------------
</font>
<font color='#0000FF'><u>void</u></font> <b><a name='copy_tensor'></a>copy_tensor</b><font face='Lucida Console'>(</font>
tensor<font color='#5555FF'>&</font> dest,
<font color='#0000FF'><u>size_t</u></font> dest_k_offset,
<font color='#0000FF'>const</font> tensor<font color='#5555FF'>&</font> src,
<font color='#0000FF'><u>size_t</u></font> src_k_offset,
<font color='#0000FF'><u>size_t</u></font> count_k
<font face='Lucida Console'>)</font>;
<font color='#009900'>// -----------------------------------------------------------------------------------
</font>
<b>}</b>
<b>}</b>
<font color='#0000FF'>#ifdef</font> NO_MAKEFILE
<font color='#0000FF'>#include</font> "<a style='text-decoration:none' href='cpu_dlib.cpp.html'>cpu_dlib.cpp</a>"
<font color='#0000FF'>#endif</font>
<font color='#0000FF'>#endif</font> <font color='#009900'>// DLIB_DNN_CPU_H_
</font>
</pre></body></html> | ruby-dlib/ruby-dlib | ext/dlib-19.4/docs/dlib/dnn/cpu_dlib.h.html | HTML | mit | 29,388 | 70.506083 | 346 | 0.554478 | false |
# encoding: UTF-8
#
# see the blogger API spec at http://www.blogger.com/developers/api/1_docs/
# note that the method signatures are subtly different to metaWeblog, they
# are not identical. take care to ensure you handle the different semantics
# properly if you want to support blogger API too, to get maximum compatibility.
#
module Blog
class Blog < ActionWebService::Struct
member :url, :string
member :blogid, :string
member :blogName, :string
end
class User < ActionWebService::Struct
member :nickname, :string
member :userid, :string
member :url, :string
member :email, :string
member :lastname, :string
member :firstname, :string
end
end
#
# blogger
#
class BloggerAPI < ActionWebService::API::Base
inflect_names false
api_method :newPost, :returns => [:string], :expects => [
{:appkey=>:string},
{:blogid=>:string},
{:username=>:string},
{:password=>:string},
{:content=>:string},
{:publish=>:bool}
]
api_method :editPost, :returns => [:bool], :expects => [
{:appkey=>:string},
{:postid=>:string},
{:username=>:string},
{:password=>:string},
{:content=>:string},
{:publish=>:bool}
]
api_method :getUsersBlogs, :returns => [[Blog::Blog]], :expects => [
{:appkey=>:string},
{:username=>:string},
{:password=>:string}
]
api_method :getUserInfo, :returns => [Blog::User], :expects => [
{:appkey=>:string},
{:username=>:string},
{:password=>:string}
]
end
| clevertechru/actionwebservice | examples/metaWeblog/apis/blogger_api.rb | Ruby | mit | 1,525 | 24 | 80 | 0.625574 | false |
var dir_e9a7d251fba6bade57fa7234e0d8499e =
[
[ "robotis_manipulator.cpp", "robotis__manipulator_8cpp.html", null ],
[ "robotis_manipulator_common.cpp", "robotis__manipulator__common_8cpp.html", null ],
[ "robotis_manipulator_log.cpp", "robotis__manipulator__log_8cpp.html", null ],
[ "robotis_manipulator_manager.cpp", "robotis__manipulator__manager_8cpp.html", null ],
[ "robotis_manipulator_math.cpp", "robotis__manipulator__math_8cpp.html", null ],
[ "robotis_manipulator_trajectory_generator.cpp", "robotis__manipulator__trajectory__generator_8cpp.html", null ]
]; | ROBOTIS-GIT/emanual | docs/en/software/robotis_manipulator_libs/doxygen/html/dir_e9a7d251fba6bade57fa7234e0d8499e.js | JavaScript | mit | 592 | 64.888889 | 117 | 0.712838 | false |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Exponential Integral Ei</title>
<link rel="stylesheet" href="../../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.77.1">
<link rel="home" href="../../../index.html" title="Math Toolkit">
<link rel="up" href="../expint.html" title="Exponential Integrals">
<link rel="prev" href="expint_n.html" title="Exponential Integral En">
<link rel="next" href="../powers.html" title="Logs, Powers, Roots and Exponentials">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="expint_n.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../expint.html"><img src="../../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../powers.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="math_toolkit.special.expint.expint_i"></a><a class="link" href="expint_i.html" title="Exponential Integral Ei">Exponential Integral
Ei</a>
</h4></div></div></div>
<h5>
<a name="math_toolkit.special.expint.expint_i.h0"></a>
<span class="phrase"><a name="math_toolkit.special.expint.expint_i.synopsis"></a></span><a class="link" href="expint_i.html#math_toolkit.special.expint.expint_i.synopsis">Synopsis</a>
</h5>
<p>
</p>
<pre class="programlisting"><span class="preprocessor">#include</span> <span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">math</span><span class="special">/</span><span class="identifier">special_functions</span><span class="special">/</span><span class="identifier">expint</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span>
</pre>
<p>
</p>
<pre class="programlisting"><span class="keyword">namespace</span> <span class="identifier">boost</span><span class="special">{</span> <span class="keyword">namespace</span> <span class="identifier">math</span><span class="special">{</span>
<span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">T</span><span class="special">></span>
<a class="link" href="../../main_overview/result_type.html" title="Calculation of the Type of the Result"><span class="emphasis"><em>calculated-result-type</em></span></a> <span class="identifier">expint</span><span class="special">(</span><span class="identifier">T</span> <span class="identifier">z</span><span class="special">);</span>
<span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">T</span><span class="special">,</span> <span class="keyword">class</span> <a class="link" href="../../policy.html" title="Policies">Policy</a><span class="special">></span>
<a class="link" href="../../main_overview/result_type.html" title="Calculation of the Type of the Result"><span class="emphasis"><em>calculated-result-type</em></span></a> <span class="identifier">expint</span><span class="special">(</span><span class="identifier">T</span> <span class="identifier">z</span><span class="special">,</span> <span class="keyword">const</span> <a class="link" href="../../policy.html" title="Policies">Policy</a><span class="special">&);</span>
<span class="special">}}</span> <span class="comment">// namespaces</span>
</pre>
<p>
The return type of these functions is computed using the <a class="link" href="../../main_overview/result_type.html" title="Calculation of the Type of the Result"><span class="emphasis"><em>result
type calculation rules</em></span></a>: the return type is <code class="computeroutput"><span class="keyword">double</span></code> if T is an integer type, and T otherwise.
</p>
<p>
The final <a class="link" href="../../policy.html" title="Policies">Policy</a> argument is
optional and can be used to control the behaviour of the function: how
it handles errors, what level of precision to use etc. Refer to the <a class="link" href="../../policy.html" title="Policies">policy documentation for more details</a>.
</p>
<h5>
<a name="math_toolkit.special.expint.expint_i.h1"></a>
<span class="phrase"><a name="math_toolkit.special.expint.expint_i.description"></a></span><a class="link" href="expint_i.html#math_toolkit.special.expint.expint_i.description">Description</a>
</h5>
<pre class="programlisting"><span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">T</span><span class="special">></span>
<a class="link" href="../../main_overview/result_type.html" title="Calculation of the Type of the Result"><span class="emphasis"><em>calculated-result-type</em></span></a> <span class="identifier">expint</span><span class="special">(</span><span class="identifier">T</span> <span class="identifier">z</span><span class="special">);</span>
<span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">T</span><span class="special">,</span> <span class="keyword">class</span> <a class="link" href="../../policy.html" title="Policies">Policy</a><span class="special">></span>
<a class="link" href="../../main_overview/result_type.html" title="Calculation of the Type of the Result"><span class="emphasis"><em>calculated-result-type</em></span></a> <span class="identifier">expint</span><span class="special">(</span><span class="identifier">T</span> <span class="identifier">z</span><span class="special">,</span> <span class="keyword">const</span> <a class="link" href="../../policy.html" title="Policies">Policy</a><span class="special">&);</span>
</pre>
<p>
Returns the <a href="http://mathworld.wolfram.com/ExponentialIntegral.html" target="_top">exponential
integral</a> of z:
</p>
<p>
<span class="inlinemediaobject"><img src="../../../../equations/expint_i_1.png"></span>
</p>
<p>
<span class="inlinemediaobject"><img src="../../../../graphs/expint_i.png" align="middle"></span>
</p>
<h5>
<a name="math_toolkit.special.expint.expint_i.h2"></a>
<span class="phrase"><a name="math_toolkit.special.expint.expint_i.accuracy"></a></span><a class="link" href="expint_i.html#math_toolkit.special.expint.expint_i.accuracy">Accuracy</a>
</h5>
<p>
The following table shows the peak errors (in units of epsilon) found on
various platforms with various floating point types, along with comparisons
to Cody's SPECFUN implementation and the <a href="http://www.gnu.org/software/gsl/" target="_top">GSL-1.9</a>
library. Unless otherwise specified any floating point type that is narrower
than the one shown will have <a class="link" href="../../backgrounders/relative_error.html#zero_error">effectively zero
error</a>.
</p>
<div class="table">
<a name="math_toolkit.special.expint.expint_i.errors_in_the_function_expint_z_"></a><p class="title"><b>Table 50. Errors In the Function expint(z)</b></p>
<div class="table-contents"><table class="table" summary="Errors In the Function expint(z)">
<colgroup>
<col>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Significand Size
</p>
</th>
<th>
<p>
Platform and Compiler
</p>
</th>
<th>
<p>
Error
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
53
</p>
</td>
<td>
<p>
Win32, Visual C++ 8
</p>
</td>
<td>
<p>
Peak=2.4 Mean=0.6
</p>
<p>
GSL Peak=8.9 Mean=0.7
</p>
<p>
SPECFUN (Cody) Peak=2.5 Mean=0.6
</p>
</td>
</tr>
<tr>
<td>
<p>
64
</p>
</td>
<td>
<p>
RedHat Linux IA_EM64, gcc-4.1
</p>
</td>
<td>
<p>
Peak=5.1 Mean=0.8
</p>
</td>
</tr>
<tr>
<td>
<p>
64
</p>
</td>
<td>
<p>
Redhat Linux IA64, gcc-4.1
</p>
</td>
<td>
<p>
Peak=5.0 Mean=0.8
</p>
</td>
</tr>
<tr>
<td>
<p>
113
</p>
</td>
<td>
<p>
HPUX IA64, aCC A.06.06
</p>
</td>
<td>
<p>
Peak=1.9 Mean=0.63
</p>
</td>
</tr>
</tbody>
</table></div>
</div>
<br class="table-break"><p>
It should be noted that all three libraries tested above offer sub-epsilon
precision over most of their range.
</p>
<p>
GSL has the greatest difficulty near the positive root of En, while Cody's
SPECFUN along with this implementation increase their error rates very
slightly over the range [4,6].
</p>
<h5>
<a name="math_toolkit.special.expint.expint_i.h3"></a>
<span class="phrase"><a name="math_toolkit.special.expint.expint_i.testing"></a></span><a class="link" href="expint_i.html#math_toolkit.special.expint.expint_i.testing">Testing</a>
</h5>
<p>
The tests for these functions come in two parts: basic sanity checks use
spot values calculated using <a href="http://functions.wolfram.com/webMathematica/FunctionEvaluation.jsp?name=ExpIntegralEi" target="_top">Mathworld's
online evaluator</a>, while accuracy checks use high-precision test
values calculated at 1000-bit precision with <a href="http://shoup.net/ntl/doc/RR.txt" target="_top">NTL::RR</a>
and this implementation. Note that the generic and type-specific versions
of these functions use differing implementations internally, so this gives
us reasonably independent test data. Using our test data to test other
"known good" implementations also provides an additional sanity
check.
</p>
<h5>
<a name="math_toolkit.special.expint.expint_i.h4"></a>
<span class="phrase"><a name="math_toolkit.special.expint.expint_i.implementation"></a></span><a class="link" href="expint_i.html#math_toolkit.special.expint.expint_i.implementation">Implementation</a>
</h5>
<p>
For x < 0 this function just calls <a class="link" href="expint_n.html" title="Exponential Integral En">zeta</a>(1,
-x): which in turn is implemented in terms of rational approximations when
the type of x has 113 or fewer bits of precision.
</p>
<p>
For x > 0 the generic version is implemented using the infinte series:
</p>
<p>
<span class="inlinemediaobject"><img src="../../../../equations/expint_i_2.png"></span>
</p>
<p>
However, when the precision of the argument type is known at compile time
and is 113 bits or less, then rational approximations <a class="link" href="../../backgrounders/implementation.html#math_toolkit.backgrounders.implementation.rational_approximations_used">devised
by JM</a> are used.
</p>
<p>
For 0 < z < 6 a root-preserving approximation of the form:
</p>
<p>
<span class="inlinemediaobject"><img src="../../../../equations/expint_i_3.png"></span>
</p>
<p>
is used, where z<sub>0</sub> is the positive root of the function, and R(z/3 - 1) is
a minimax rational approximation rescaled so that it is evaluated over
[-1,1]. Note that while the rational approximation over [0,6] converges
rapidly to the minimax solution it is rather ill-conditioned in practice.
Cody and Thacher <a href="#ftn.math_toolkit.special.expint.expint_i.f0" class="footnote"><sup class="footnote"><a name="math_toolkit.special.expint.expint_i.f0"></a>[5]</sup></a> experienced the same issue and converted the polynomials into
Chebeshev form to ensure stable computation. By experiment we found that
the polynomials are just as stable in polynomial as Chebyshev form, <span class="emphasis"><em>provided</em></span>
they are computed over the interval [-1,1].
</p>
<p>
Over the a series of intervals [a,b] and [b,INF] the rational approximation
takes the form:
</p>
<p>
<span class="inlinemediaobject"><img src="../../../../equations/expint_i_4.png"></span>
</p>
<p>
where <span class="emphasis"><em>c</em></span> is a constant, and R(t) is a minimax solution
optimised for low absolute error compared to <span class="emphasis"><em>c</em></span>. Variable
<span class="emphasis"><em>t</em></span> is <code class="computeroutput"><span class="number">1</span><span class="special">/</span><span class="identifier">z</span></code> when
the range in infinite and <code class="computeroutput"><span class="number">2</span><span class="identifier">z</span><span class="special">/(</span><span class="identifier">b</span><span class="special">-</span><span class="identifier">a</span><span class="special">)</span>
<span class="special">-</span> <span class="special">(</span><span class="number">2</span><span class="identifier">a</span><span class="special">/(</span><span class="identifier">b</span><span class="special">-</span><span class="identifier">a</span><span class="special">)</span> <span class="special">+</span> <span class="number">1</span><span class="special">)</span></code> otherwise: this has the effect of scaling
z to the interval [-1,1]. As before rational approximations over arbitrary
intervals were found to be ill-conditioned: Cody and Thacher solved this
issue by converting the polynomials to their J-Fraction equivalent. However,
as long as the interval of evaluation was [-1,1] and the number of terms
carefully chosen, it was found that the polynomials <span class="emphasis"><em>could</em></span>
be evaluated to suitable precision: error rates are typically 2 to 3 epsilon
which is comparible to the error rate that Cody and Thacher achieved using
J-Fractions, but marginally more efficient given that fewer divisions are
involved.
</p>
<div class="footnotes">
<br><hr style="width:100; align:left;">
<div id="ftn.math_toolkit.special.expint.expint_i.f0" class="footnote"><p><a href="#math_toolkit.special.expint.expint_i.f0" class="para"><sup class="para">[5] </sup></a>
W. J. Cody and H. C. Thacher, Jr., Rational Chebyshev approximations
for the exponential integral E<sub>1</sub>(x), Math. Comp. 22 (1968), 641-649, and
W. J. Cody and H. C. Thacher, Jr., Chebyshev approximations for the exponential
integral Ei(x), Math. Comp. 23 (1969), 289-303.
</p></div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2006-2010, 2012 John Maddock, Paul A. Bristow, Hubert Holin, Xiaogang
Zhang, Bruno Lalande, Johan Råde, Gautam Sewani, Thijs van den Berg and Benjamin
Sobotta<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="expint_n.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../expint.html"><img src="../../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../powers.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| mxrrow/zaicoin | src/deps/boost/libs/math/doc/sf_and_dist/html/math_toolkit/special/expint/expint_i.html | HTML | mit | 17,697 | 57.599338 | 477 | 0.603549 | false |
<?php
return array (
'<strong>About</strong> this user' => '<strong>À propos</strong> de cet utilisateur',
);
| ProfilerTeam/Profiler | protected/modules_core/user/messages/fr/views_profile_about.php | PHP | mit | 113 | 27 | 87 | 0.660714 | false |
using System.Runtime.InteropServices;
namespace LibGit2Sharp.Core
{
[StructLayout(LayoutKind.Sequential)]
internal class GitPushOptions
{
public int Version = 1;
public int PackbuilderDegreeOfParallelism;
public GitRemoteCallbacks RemoteCallbacks;
public GitProxyOptions ProxyOptions;
public GitStrArrayManaged CustomHeaders;
}
}
| PKRoma/libgit2sharp | LibGit2Sharp/Core/GitPushOptions.cs | C# | mit | 390 | 26.714286 | 50 | 0.726804 | false |
(function(){
'use strict';
angular.module('gridshore.c3js.dynamic', [
'ui.router'
]);
})();
(function(){
'use strict';
angular.module('gridshore.c3js.dynamic')
.config(routeConfig);
routeConfig.$inject = ['$stateProvider'];
function routeConfig($stateProvider) {
$stateProvider
.state('dynamic', {
url: '/dynamic',
templateUrl: 'assets/js/dynamic/dynamic.tpl.html',
controller: 'DynamicCtrl',
controllerAs: 'vm'
});
}
})();
(function(){
'use strict';
angular.module('gridshore.c3js.dynamic')
.controller('DynamicCtrl', DynamicCtrl);
DynamicCtrl.$inject = ['$interval','dateFilter'];
function DynamicCtrl($interval, dateFilter) {
var vm = this;
vm.generateData = generateData;
vm.datapoints = [];
vm.datacolumns = [{"id": "top-1", "type": "line", "name": "Top one"},
{"id": "top-2", "type": "spline", "name": "Top two"}];
vm.datax = {"id": "x"};
function generateData() {
$interval(function () {
loadData(function (data) {
if (vm.datapoints.length > 10) {
vm.datapoints.shift();
}
vm.datapoints.push(data);
});
}, 1000, 10);
}
function loadData (callback) {
var aDate = dateFilter(new Date(),'yyyy-MM-dd hh:mm:ss');
callback({"x": aDate, "top-1": randomNumber(), "top-2": randomNumber()});
}
function randomNumber() {
return Math.floor((Math.random() * 200) + 1);
}
}
})(); | MGautier/security-sensor | trunk/version-1-0/webapp/secproject/secapp/static/bower_components/c3-angular/examples/assets/js/dynamic/dynamic.js | JavaScript | mit | 1,727 | 28.288136 | 85 | 0.492183 | false |
import sys
import antlr3
from SymtabTestLexer import SymtabTestLexer
from SymtabTestParser import SymtabTestParser
cStream = antlr3.StringStream(open(sys.argv[1]).read())
lexer = SymtabTestLexer(cStream)
tStream = antlr3.CommonTokenStream(lexer)
parser = SymtabTestParser(tStream)
parser.prog()
| JaDogg/__py_playground | reference/examples-v3/Python/scopes/scopes.py | Python | mit | 296 | 28.6 | 55 | 0.827703 | false |
///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2006-11-13
// Updated : 2011-01-26
// Licence : This source is under MIT License
// File : glm/setup.hpp
///////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef glm_setup
#define glm_setup
///////////////////////////////////////////////////////////////////////////////////////////////////
// Version
#define GLM_VERSION 92
#define GLM_VERSION_MAJOR 0
#define GLM_VERSION_MINOR 9
#define GLM_VERSION_PATCH 2
#define GLM_VERSION_REVISION 3
///////////////////////////////////////////////////////////////////////////////////////////////////
// Compiler
// User defines: GLM_FORCE_COMPILER_UNKNOWN
// TODO ? __llvm__
#define GLM_COMPILER_UNKNOWN 0x00000000
// Visual C++ defines
#define GLM_COMPILER_VC 0x01000000
#define GLM_COMPILER_VC2 0x01000010
#define GLM_COMPILER_VC4 0x01000020
#define GLM_COMPILER_VC5 0x01000030
#define GLM_COMPILER_VC6 0x01000040
#define GLM_COMPILER_VC2002 0x01000050
#define GLM_COMPILER_VC2003 0x01000060
#define GLM_COMPILER_VC2005 0x01000070
#define GLM_COMPILER_VC2008 0x01000080
#define GLM_COMPILER_VC2010 0x01000090
#define GLM_COMPILER_VC2011 0x010000A0
// GCC defines
#define GLM_COMPILER_GCC 0x02000000
#define GLM_COMPILER_GCC_LLVM 0x02000001
#define GLM_COMPILER_GCC_CLANG 0x02000002
#define GLM_COMPILER_GCC30 0x02000010
#define GLM_COMPILER_GCC31 0x02000020
#define GLM_COMPILER_GCC32 0x02000030
#define GLM_COMPILER_GCC33 0x02000040
#define GLM_COMPILER_GCC34 0x02000050
#define GLM_COMPILER_GCC35 0x02000060
#define GLM_COMPILER_GCC40 0x02000070
#define GLM_COMPILER_GCC41 0x02000080
#define GLM_COMPILER_GCC42 0x02000090
#define GLM_COMPILER_GCC43 0x020000A0
#define GLM_COMPILER_GCC44 0x020000B0
#define GLM_COMPILER_GCC45 0x020000C0
#define GLM_COMPILER_GCC46 0x020000D0
#define GLM_COMPILER_GCC47 0x020000E0
#define GLM_COMPILER_GCC48 0x020000F0
#define GLM_COMPILER_GCC49 0x02000100
#define GLM_COMPILER_GCC50 0x02000200
// G++ command line to display defined
// echo "" | g++ -E -dM -x c++ - | sort
// Borland C++ defines. How to identify BC?
#define GLM_COMPILER_BC 0x04000000
#define GLM_COMPILER_BCB4 0x04000100
#define GLM_COMPILER_BCB5 0x04000200
#define GLM_COMPILER_BCB6 0x04000300
//#define GLM_COMPILER_BCBX 0x04000400 // What's the version value?
#define GLM_COMPILER_BCB2009 0x04000500
// CodeWarrior
#define GLM_COMPILER_CODEWARRIOR 0x08000000
// CUDA
#define GLM_COMPILER_CUDA 0x10000000
#define GLM_COMPILER_CUDA30 0x10000010
#define GLM_COMPILER_CUDA31 0x10000020
#define GLM_COMPILER_CUDA32 0x10000030
#define GLM_COMPILER_CUDA40 0x10000040
// Clang
#define GLM_COMPILER_CLANG 0x20000000
#define GLM_COMPILER_CLANG26 0x20000010
#define GLM_COMPILER_CLANG27 0x20000020
#define GLM_COMPILER_CLANG28 0x20000030
#define GLM_COMPILER_CLANG29 0x20000040
// LLVM GCC
#define GLM_COMPILER_LLVM_GCC 0x40000000
// Build model
#define GLM_MODEL_32 0x00000010
#define GLM_MODEL_64 0x00000020
// Force generic C++ compiler
#ifdef GLM_FORCE_COMPILER_UNKNOWN
# define GLM_COMPILER GLM_COMPILER_UNKNOWN
// CUDA
#elif defined(__CUDACC__)
# define GLM_COMPILER GLM_COMPILER_CUDA
// Visual C++
#elif defined(_MSC_VER)
# if _MSC_VER == 900
# define GLM_COMPILER GLM_COMPILER_VC2
# elif _MSC_VER == 1000
# define GLM_COMPILER GLM_COMPILER_VC4
# elif _MSC_VER == 1100
# define GLM_COMPILER GLM_COMPILER_VC5
# elif _MSC_VER == 1200
# define GLM_COMPILER GLM_COMPILER_VC6
# elif _MSC_VER == 1300
# define GLM_COMPILER GLM_COMPILER_VC2002
# elif _MSC_VER == 1310
# define GLM_COMPILER GLM_COMPILER_VC2003
# elif _MSC_VER == 1400
# define GLM_COMPILER GLM_COMPILER_VC2005
# elif _MSC_VER == 1500
# define GLM_COMPILER GLM_COMPILER_VC2008
# elif _MSC_VER == 1600
# define GLM_COMPILER GLM_COMPILER_VC2010
# elif _MSC_VER == 1700
# define GLM_COMPILER GLM_COMPILER_VC2011
# else//_MSC_VER
# define GLM_COMPILER GLM_COMPILER_VC
# endif//_MSC_VER
// G++
#elif defined(__GNUC__) || defined(__llvm__) || defined(__clang__)
# if defined (__llvm__)
# define GLM_COMPILER_GCC_EXTRA GLM_COMPILER_GCC_LLVM
# elif defined (__clang__)
# define GLM_COMPILER_GCC_EXTRA GLM_COMPILER_GCC_CLANG
# else
# define GLM_COMPILER_GCC_EXTRA 0
# endif
#
# if (__GNUC__ == 3) && (__GNUC_MINOR__ == 2)
# define GLM_COMPILER GLM_COMPILER_GCC32
# elif (__GNUC__ == 3) && (__GNUC_MINOR__ == 3)
# define GLM_COMPILER GLM_COMPILER_GCC33
# elif (__GNUC__ == 3) && (__GNUC_MINOR__ == 4)
# define GLM_COMPILER GLM_COMPILER_GCC34
# elif (__GNUC__ == 3) && (__GNUC_MINOR__ == 5)
# define GLM_COMPILER GLM_COMPILER_GCC35
# elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 0)
# define GLM_COMPILER (GLM_COMPILER_GCC40 | GLM_COMPILER_GCC_EXTRA)
# elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 1)
# define GLM_COMPILER (GLM_COMPILER_GCC41 | GLM_COMPILER_GCC_EXTRA)
# elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 2)
# define GLM_COMPILER (GLM_COMPILER_GCC42 | GLM_COMPILER_GCC_EXTRA)
# elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 3)
# define GLM_COMPILER (GLM_COMPILER_GCC43 | GLM_COMPILER_GCC_EXTRA)
# elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 4)
# define GLM_COMPILER (GLM_COMPILER_GCC44 | GLM_COMPILER_GCC_EXTRA)
# elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 5)
# define GLM_COMPILER (GLM_COMPILER_GCC45 | GLM_COMPILER_GCC_EXTRA)
# elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 6)
# define GLM_COMPILER (GLM_COMPILER_GCC46 | GLM_COMPILER_GCC_EXTRA)
# elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 7)
# define GLM_COMPILER (GLM_COMPILER_GCC47 | GLM_COMPILER_GCC_EXTRA)
# elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 8)
# define GLM_COMPILER (GLM_COMPILER_GCC48 | GLM_COMPILER_GCC_EXTRA)
# elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 9)
# define GLM_COMPILER (GLM_COMPILER_GCC49 | GLM_COMPILER_GCC_EXTRA)
# elif (__GNUC__ == 5) && (__GNUC_MINOR__ == 0)
# define GLM_COMPILER (GLM_COMPILER_GCC50 | GLM_COMPILER_GCC_EXTRA)
# else
# define GLM_COMPILER (GLM_COMPILER_GCC | GLM_COMPILER_GCC_EXTRA)
# endif
// Borland C++
#elif defined(_BORLANDC_)
# if defined(VER125)
# define GLM_COMPILER GLM_COMPILER_BCB4
# elif defined(VER130)
# define GLM_COMPILER GLM_COMPILER_BCB5
# elif defined(VER140)
# define GLM_COMPILER GLM_COMPILER_BCB6
# elif defined(VER200)
# define GLM_COMPILER GLM_COMPILER_BCB2009
# else
# define GLM_COMPILER GLM_COMPILER_BC
# endif
// Codewarrior
#elif defined(__MWERKS__)
# define GLM_COMPILER GLM_COMPILER_CODEWARRIOR
#else
# define GLM_COMPILER GLM_COMPILER_UNKNOWN
#endif
#ifndef GLM_COMPILER
#error "GLM_COMPILER undefined, your compiler may not be supported by GLM. Add #define GLM_COMPILER 0 to ignore this message."
#endif//GLM_COMPILER
// Report compiler detection
#if(defined(GLM_MESSAGES) && !defined(GLM_MESSAGE_COMPILER_DISPLAYED))
# define GLM_MESSAGE_COMPILER_DISPLAYED
# if(GLM_COMPILER & GLM_COMPILER_CUDA)
# pragma message("GLM: CUDA compiler detected")
# elif(GLM_COMPILER & GLM_COMPILER_VC)
# pragma message("GLM: Visual C++ compiler detected")
# elif(GLM_COMPILER & GLM_COMPILER_CLANG)
# pragma message("GLM: Clang compiler detected")
# elif(GLM_COMPILER & GLM_COMPILER_LLVM_GCC)
# pragma message("GLM: LLVM GCC compiler detected")
# elif(GLM_COMPILER & GLM_COMPILER_GCC)
# if(GLM_COMPILER == GLM_COMPILER_GCC_LLVM)
# pragma message("GLM: LLVM GCC compiler detected")
# elif(GLM_COMPILER == GLM_COMPILER_GCC_CLANG)
# pragma message("GLM: CLANG compiler detected")
# else
# pragma message("GLM: GCC compiler detected")
# endif
# elif(GLM_COMPILER & GLM_COMPILER_BC)
# pragma message("GLM: Borland compiler detected but not supported")
# elif(GLM_COMPILER & GLM_COMPILER_CODEWARRIOR)
# pragma message("GLM: Codewarrior compiler detected but not supported")
# else
# pragma message("GLM: Compiler not detected")
# endif
#endif//GLM_MESSAGE
/////////////////
// Build model //
#if(GLM_COMPILER & GLM_COMPILER_VC)
# if defined(_M_X64)
# define GLM_MODEL GLM_MODEL_64
# else
# define GLM_MODEL GLM_MODEL_32
# endif//_M_X64
#elif(GLM_COMPILER & GLM_COMPILER_GCC)
# if(defined(__WORDSIZE) && (__WORDSIZE == 64)) || defined(__arch64__) || defined(__LP64__) || defined(__x86_64__)
# define GLM_MODEL GLM_MODEL_64
# else
# define GLM_MODEL GLM_MODEL_32
# endif//
#else
# define GLM_MODEL GLM_MODEL_32
#endif//
#if(!defined(GLM_MODEL) && GLM_COMPILER != 0)
#error "GLM_MODEL undefined, your compiler may not be supported by GLM. Add #define GLM_MODEL 0 to ignore this message."
#endif//GLM_MODEL
#if(defined(GLM_MESSAGES) && !defined(GLM_MESSAGE_MODEL_DISPLAYED))
# define GLM_MESSAGE_MODEL_DISPLAYED
# if(GLM_MODEL == GLM_MODEL_64)
# pragma message("GLM: 64 bits model")
# elif(GLM_MODEL == GLM_MODEL_32)
# pragma message("GLM: 32 bits model")
# endif//GLM_MODEL
#endif//GLM_MESSAGE
/////////////////
// C++ Version //
// User defines: GLM_FORCE_CXX98
#define GLM_LANG_CXX 0
#define GLM_LANG_CXX98 1
#define GLM_LANG_CXX0X 2
#define GLM_LANG_CXXMS 3
#define GLM_LANG_CXXGNU 4
#if(defined(GLM_FORCE_CXX98))
# define GLM_LANG GLM_LANG_CXX98
#elif(((GLM_COMPILER & GLM_COMPILER_GCC) == GLM_COMPILER_GCC) && defined(__GXX_EXPERIMENTAL_CXX0X__)) // -std=c++0x or -std=gnu++0x
# define GLM_LANG GLM_LANG_CXX0X
#elif(GLM_COMPILER == GLM_COMPILER_VC2010) //_MSC_EXTENSIONS for MS language extensions
# define GLM_LANG GLM_LANG_CXX0X
#elif(((GLM_COMPILER & GLM_COMPILER_GCC) == GLM_COMPILER_GCC) && defined(__STRICT_ANSI__))
# define GLM_LANG GLM_LANG_CXX98
#elif(((GLM_COMPILER & GLM_COMPILER_VC) == GLM_COMPILER_VC) && !defined(_MSC_EXTENSIONS))
# define GLM_LANG GLM_LANG_CXX98
#else
# define GLM_LANG GLM_LANG_CXX
#endif
#if(defined(GLM_MESSAGES) && !defined(GLM_MESSAGE_LANG_DISPLAYED))
# define GLM_MESSAGE_LANG_DISPLAYED
# if(GLM_LANG == GLM_LANG_CXX98)
# pragma message("GLM: C++98")
# elif(GLM_LANG == GLM_LANG_CXX0X)
# pragma message("GLM: C++0x")
# endif//GLM_MODEL
#endif//GLM_MESSAGE
/////////////////
// Platform
// User defines: GLM_FORCE_PURE GLM_FORCE_SSE2 GLM_FORCE_AVX
#define GLM_ARCH_PURE 0x0000 //(0x0000)
#define GLM_ARCH_SSE2 0x0001 //(0x0001)
#define GLM_ARCH_SSE3 0x0003 //(0x0002 | GLM_ARCH_SSE2)
#define GLM_ARCH_AVX 0x0007 //(0x0004 | GLM_ARCH_SSE3 | GLM_ARCH_SSE2)
#if(defined(GLM_FORCE_PURE))
# define GLM_ARCH GLM_ARCH_PURE
#elif(defined(GLM_FORCE_AVX))
# define GLM_ARCH GLM_ARCH_AVX
#elif(defined(GLM_FORCE_SSE3))
# define GLM_ARCH GLM_ARCH_SSE3
#elif(defined(GLM_FORCE_SSE2))
# define GLM_ARCH GLM_ARCH_SSE2
#elif((GLM_COMPILER & GLM_COMPILER_VC) && (defined(_M_IX86) || defined(_M_X64)))
# if(defined(_M_CEE_PURE))
# define GLM_ARCH GLM_ARCH_PURE
# elif(GLM_COMPILER >= GLM_COMPILER_VC2010)
# if(_MSC_FULL_VER >= 160031118) //160031118: VC2010 SP1 beta full version
# define GLM_ARCH GLM_ARCH_AVX //GLM_ARCH_AVX (Require SP1)
# else
# define GLM_ARCH GLM_ARCH_SSE3
# endif
# elif(GLM_COMPILER >= GLM_COMPILER_VC2008)
# define GLM_ARCH GLM_ARCH_SSE3
# elif(GLM_COMPILER >= GLM_COMPILER_VC2005)
# define GLM_ARCH GLM_ARCH_SSE2
# else
# define GLM_ARCH GLM_ARCH_PURE
# endif
#elif(GLM_COMPILER & GLM_COMPILER_LLVM_GCC)
# if(defined(__AVX__))
# define GLM_ARCH GLM_ARCH_AVX
# elif(defined(__SSE3__))
# define GLM_ARCH GLM_ARCH_SSE3
# elif(defined(__SSE2__))
# define GLM_ARCH GLM_ARCH_SSE2
# else
# define GLM_ARCH GLM_ARCH_PURE
# endif
#elif((GLM_COMPILER & GLM_COMPILER_GCC) && (defined(__i386__) || defined(__x86_64__)))
# if(defined(__AVX__))
# define GLM_ARCH GLM_ARCH_AVX
# elif(defined(__SSE3__))
# define GLM_ARCH GLM_ARCH_SSE3
# elif(defined(__SSE2__))
# define GLM_ARCH GLM_ARCH_SSE2
# else
# define GLM_ARCH GLM_ARCH_PURE
# endif
#else
# define GLM_ARCH GLM_ARCH_PURE
#endif
#if(GLM_ARCH != GLM_ARCH_PURE)
#if((GLM_ARCH & GLM_ARCH_AVX) == GLM_ARCH_AVX)
# include <immintrin.h>
#endif//GLM_ARCH
#if((GLM_ARCH & GLM_ARCH_SSE3) == GLM_ARCH_SSE3)
# include <pmmintrin.h>
#endif//GLM_ARCH
#if((GLM_ARCH & GLM_ARCH_SSE2) == GLM_ARCH_SSE2)
# include <emmintrin.h>
#endif//GLM_ARCH
#endif//(GLM_ARCH != GLM_ARCH_PURE)
#if(defined(GLM_MESSAGES) && !defined(GLM_MESSAGE_ARCH_DISPLAYED))
# define GLM_MESSAGE_ARCH_DISPLAYED
# if(GLM_ARCH == GLM_ARCH_PURE)
# pragma message("GLM: Platform independent")
# elif(GLM_ARCH == GLM_ARCH_SSE2)
# pragma message("GLM: SSE2 build platform")
# elif(GLM_ARCH == GLM_ARCH_SSE3)
# pragma message("GLM: SSE3 build platform")
# elif(GLM_ARCH == GLM_ARCH_AVX)
# pragma message("GLM: AVX build platform")
# endif//GLM_ARCH
#endif//GLM_MESSAGE
///////////////////////////////////////////////////////////////////////////////////////////////////
// Components
//#define GLM_FORCE_ONLY_XYZW
#define GLM_COMPONENT_GLSL_NAMES 0
#define GLM_COMPONENT_ONLY_XYZW 1 // To disable multiple vector component names access.
#define GLM_COMPONENT_MS_EXT 2 // To use anonymous union to provide multiple component names access for class valType. Visual C++ only.
#ifndef GLM_FORCE_ONLY_XYZW
# if((GLM_COMPILER & GLM_COMPILER_VC) && defined(_MSC_EXTENSIONS))
# define GLM_COMPONENT GLM_COMPONENT_MS_EXT
# else
# define GLM_COMPONENT GLM_COMPONENT_GLSL_NAMES
# endif
#else
# define GLM_COMPONENT GLM_COMPONENT_ONLY_XYZW
#endif
#if((GLM_COMPONENT == GLM_COMPONENT_MS_EXT) && !(GLM_COMPILER & GLM_COMPILER_VC))
# error "GLM_COMPONENT value is GLM_COMPONENT_MS_EXT but this is not allowed with the current compiler."
#endif
#if(defined(GLM_MESSAGES) && !defined(GLM_MESSAGE_COMPONENT_DISPLAYED))
# define GLM_MESSAGE_COMPONENT_DISPLAYED
# if(GLM_COMPONENT == GLM_COMPONENT_GLSL_NAMES)
# pragma message("GLM: GLSL multiple vector component names")
# elif(GLM_COMPONENT == GLM_COMPONENT_ONLY_XYZW)
# pragma message("GLM: x,y,z,w vector component names only")
# elif(GLM_COMPONENT == GLM_COMPONENT_MS_EXT)
# pragma message("GLM: Multiple vector component names through Visual C++ language extensions")
# else
# error "GLM_COMPONENT value unknown"
# endif//GLM_MESSAGE_COMPONENT_DISPLAYED
#endif//GLM_MESSAGE
///////////////////////////////////////////////////////////////////////////////////////////////////
// Static assert
#if(GLM_LANG == GLM_LANG_CXX0X)
# define GLM_STATIC_ASSERT(x, message) static_assert(x, message)
#elif(defined(BOOST_STATIC_ASSERT))
# define GLM_STATIC_ASSERT(x, message) BOOST_STATIC_ASSERT(x)
#elif(GLM_COMPILER & GLM_COMPILER_VC)
# define GLM_STATIC_ASSERT(x, message) typedef char __CASSERT__##__LINE__[(x) ? 1 : -1]
#else
# define GLM_STATIC_ASSERT(x, message)
# define GLM_STATIC_ASSERT_NULL
#endif//GLM_LANG
///////////////////////////////////////////////////////////////////////////////////////////////////
// Qualifiers
// User defines: GLM_FORCE_INLINE GLM_FORCE_CUDA
#if(defined(GLM_FORCE_CUDA) || (GLM_COMPILER & GLM_COMPILER_CUDA))
# define GLM_CUDA_FUNC_DEF __device__ __host__
# define GLM_CUDA_FUNC_DECL __device__ __host__
#else
# define GLM_CUDA_FUNC_DEF
# define GLM_CUDA_FUNC_DECL
#endif
#if GLM_COMPILER & GLM_COMPILER_GCC
#define GLM_VAR_USED __attribute__ ((unused))
#else
#define GLM_VAR_USED
#endif
#if(defined(GLM_FORCE_INLINE))
# if((GLM_COMPILER & GLM_COMPILER_VC) && (GLM_COMPILER >= GLM_COMPILER_VC2005))
# define GLM_INLINE __forceinline
# elif((GLM_COMPILER & GLM_COMPILER_GCC) && (GLM_COMPILER >= GLM_COMPILER_GCC34))
# define GLM_INLINE __attribute__((always_inline))
# else
# define GLM_INLINE inline
# endif//GLM_COMPILER
#else
# define GLM_INLINE inline
#endif//defined(GLM_FORCE_INLINE)
#define GLM_FUNC_DECL GLM_CUDA_FUNC_DECL
#define GLM_FUNC_QUALIFIER GLM_CUDA_FUNC_DEF GLM_INLINE
///////////////////////////////////////////////////////////////////////////////////////////////////
// Swizzle operators
// User defines: GLM_SWIZZLE_XYZW GLM_SWIZZLE_RGBA GLM_SWIZZLE_STQP GLM_SWIZZLE
#if(defined(GLM_MESSAGES) && !defined(GLM_MESSAGE_SWIZZLE_DISPLAYED))
# define GLM_MESSAGE_SWIZZLE_DISPLAYED
# if(defined(GLM_SWIZZLE))
# pragma message("GLM: Full swizzling operator enabled")
# elif(!defined(GLM_SWIZZLE_XYZW) && !defined(GLM_SWIZZLE_RGBA) && !defined(GLM_SWIZZLE_STQP) && !defined(GLM_SWIZZLE))
# pragma message("GLM: No swizzling operator enabled")
# else
# pragma message("GLM: Partial swizzling operator enabled")
# endif
#endif//GLM_MESSAGE
#endif//glm_setup
| kiwaiii/pbc | src/external/glm-0.9.2.4/glm/core/setup.hpp | C++ | mit | 16,530 | 33.4375 | 138 | 0.662916 | false |
#include "../headers/user_modes.inc"
#include "../headers/BoardMapping.h"
#define g_bCommandReceived g_kFlag,5 ; H-Command received
#define aliasAlrmByte g_summaryDataArray+11 ; áàéò îòêàçîâ
#define aliasStateByte g_summaryDataArray+10 ; áàéò ñîñòîÿíèÿ
; Data
extern g_summaryDataArray
extern g_kFlag
; Code
extern eeprom_Read;(?/?)
extern eeprom_CheckState;(?/?)
extern eeprom_Save;(?/?)
extern dac_SetChannalA;(?/?)
extern dac_SetChannalB;(?/?)
extern dac_SetChannalC;(?/?)
extern dac_SetChannalD;(?/?)
extern lib_corrWordBeforLoadDAC;(DAL, DAH/fsr0+0+1)
; Data
global g_LAShiftValue, g_HAShiftValue, D4BL, D4BH, ILIM, DAL, DAH
; Óæå ïîòåíöèàëüíî îïàñíûå
global g_recievedCmd
global g_ownI2CAddress ; áåçëèêèå íàçâàíèÿ è åùå è ñ îøèáêîé
; Code
global sdr_LockAndShiftOff;(?/?)
global sdr_Init;(?/?)
global sdr_Exec;(?/?)
mydata_i2c idata_acs
g_recievedCmd res 1 ;Lava-Lava command
tmp res 1
DAL res 1 ;for DAC'S registers
DAH res 1
DAA res 1 ;g_ownI2CAddress for D4
Temp_DAL res 1
Temp_DAH res 1
temp_DA res 1
g_LAShiftValue res 1 ;D4 SM1-Value X5
g_HAShiftValue res 1
D4BL res 1 ;D4 SM2-Value X6
D4BH res 1
ILIM res 1
bitts res 1
ctc res 1 ;arifmetic Counter
g_ownI2CAddress res 1
cta res 1
coeff res 1
;bit0-5 -ìàêñ (ãðóáûé) øàã ðåã ñìåù (ðåçåðâ)
;bit7 - ôëàã: H-âêë "ãðóáî" øàã ðåã/L- "òî÷íî" øàã ðåã
Obj_I2C code
; èíèöèàëèçàöèÿ ÷åãî?
sdr_Init;(?/?)
;ìàêñ øàã ðåã ñìåù (ðåçåðâ) çäåñü íå óñòàíàâëèâàåòñÿ
;bit7 = L "òî÷íî" ðåã.
movlw b'00100000'
movwf coeff
; îïðåäåëÿåì ñâîé àäðåñ?
call _sdr_GetOwnAddr;(void/void)
; I2C initialisation
call _sdc_InitI2CExcange;(void/void)
; Óñòàíàâëèâèòü ïîðîã ïî òîêó
call dac_SetChannalA;(?/?)
; Óñòàíîâèòü ïîðîã ïî íàïðÿæåíèþ ÌÈÏ
call dac_SetChannalD;(?/?)
rcall sdr_LockAndShiftOff;(?/?)
call _sdr_ShiftOff;(?/?)
return
;
_sdr_GetOwnAddr;(void/void)
#ifdef MODE_OLD
movlw 0x72
btfsc PORTB,0
#endif
#ifdef MODE_NEW_033
movlw 0x72
btfsc PORTB,2
#endif
movlw 0x78
btfsc PORTB,3
movlw 0x76
btfsc PORTB,4
movlw 0x74
movwf g_ownI2CAddress
return
_sdc_InitI2CExcange;(void/void)
bcf SSPCON1,SSPEN
clrf SSPCON2
bcf PIR1,SSPIF
; load slave address
movff g_ownI2CAddress,SSPADD ;g_ownI2CAddress
movlw b'00000000'
movwf SSPSTAT
movlw b'00000000'
movlw b'00110110' ;slave
movwf SSPCON1
return
; Äåêîäèðóåò ïðèíÿòóþ îò ïëàòû óïðàâëåíèÿ êîììàíäó
sdr_Exec;(?/?)
; êîììàíäó ïðèíÿëè - ñáðîñèëè ôëàã
bcf g_bCommandReceived
movf g_recievedCmd,w ; ÷èòàåì êîììàíäó
btfsc STATUS,Z
return
addlw -1
btfsc STATUS,Z
goto _Minus ;0x01
addlw -1
btfsc STATUS,Z
goto _Plus ;0x02
addlw -1
btfsc STATUS,Z
goto _ON ;0x03
addlw -1
btfsc STATUS,Z
goto sdr_LockAndShiftOff;(?/?) ;0x04
addlw -1
btfsc STATUS,Z
goto _D4AMinus ;0x05
addlw -1
btfsc STATUS,Z
goto _D4APlus ;0x06
addlw -1
btfsc STATUS,Z
goto _D4BMinus ;0x07
addlw -1
btfsc STATUS,Z
goto _D4BPlus ;0x08
addlw -1
; êîììàíäà ñîõðàíåíèÿ íàñòðîåê ïðèõîäèò èçâíå
btfsc STATUS,Z
goto _CurrentLimitSave ;0x09
addlw -1
btfsc STATUS,Z
goto _ShiftOneSave ;0x0A
addlw -1
btfsc STATUS,Z
goto _ShiftTwoSave ;0x0B
addlw -1
btfsc STATUS,Z
goto _S1Rest ;0x0C
addlw -1
btfsc STATUS,Z
goto _S2Rest ;0x0D
addlw -1
btfsc STATUS,Z
goto _ResAlr ;0x0E
addlw -1
btfsc STATUS,Z
goto _D4APlusxK ;0x0F øàã 1õ32
addlw -1
btfsc STATUS,Z
goto _D4AMinusxK ;0x10 øàã 1õ32
addlw -1
btfsc STATUS,Z
goto _D4BPlusxK ;0x11 øàã 1õ32
addlw -1
btfsc STATUS,Z
goto _D4BMinusxK ;0x12 øàã 1õ32
addlw -1
btfsc STATUS,Z
goto _ONxK ;0x13 âêë øàã 1õ32 ("ãðóáî")
addlw -1
btfsc STATUS,Z
goto _OFFxK ;0x14 âûêë øàã 1õ32 ("òî÷íî")
return
; Èíòåðôåéñíàÿ
_sdr_ShiftOff;(?/?)
bsf g_bLockAtt_leg, 0 ;VT2,4 open
return
; ×òî-òî çàêðûâàåòñÿ
sdr_LockAndShiftOff;(?/?)
bsf g_bLockAtt_leg,0 ; VT2,4 open
call _clearShift;(?/?) ; ñáðîñ ñìåùåíèÿ
bcf aliasStateByte,0
return
;
_Open:
_ON:
movf aliasAlrmByte,w
andlw b'00011111' ;bit4- àâàð Ò ! íå âêëþ÷àåì
btfss STATUS,Z
return
call _loadShiftA;(?/?)
call _loadShiftB;(?/?)
DelayUs 20 ;+++1803
bcf g_bLockAtt_leg,0 ;VT2,4 close -îòïóñòèëè àòò.
bsf aliasStateByte,0
return
_Plus
movf ILIM,w
iorlw 0xF0
movwf tmp
incf tmp,w
btfsc STATUS,Z
return
movwf ILIM
goto _PMout
_Minus
movf ILIM
btfsc STATUS,Z
return
decf ILIM,f
_PMout
bcf CVRCON,0
bcf CVRCON,1
bcf CVRCON,2
bcf CVRCON,3
movf ILIM,w
iorwf CVRCON,f
return
_S1Rest
movlw 0x16
call eeprom_Read;(?/?)
movwf g_LAShiftValue
movlw 0x17
call eeprom_Read;(?/?)
movwf g_HAShiftValue
nop
call _loadShiftA;(?/?)
return
_S2Rest
movlw 0x18
call eeprom_Read;(?/?)
movwf D4BL
movlw 0x19
call eeprom_Read;(?/?)
movwf D4BH
nop
call _loadShiftB;(?/?)
return
_ResAlr
clrf aliasAlrmByte ;ñáðîñèëè áàéò îòêàçîâ
;ñáðîñèëè òðèããåð I?
#ifdef MODE_4U
bsf PORTA,7
nop ;ñáðîñèëè òðèããåð
bcf PORTA,7
#endif
#ifdef MODE_3U
bcf PORTA,7
nop ;ñáðîñèëè òðèããåð I
bsf PORTA,7
#endif
#ifdef MODE_3U_NEW_ALU ;+091110
bcf PORTC,7
nop ;ñáðîñèëè òðèããåð U
bsf PORTC,7
#endif
;ñáðîñèëè óäåðæàíèå â ñîñò "îòêë" êàíàëà ìèï
#ifdef MODE_NEW_033
bsf PORTB,5 ;reset OFF2
bsf PORTC,2 ;reset OFF1
#endif
#ifdef MODE_4U
movlw b'00000111' ;âêëþ÷åíèå òàéìåðà äëÿ ïðîâåðêè äóãè
movwf T2CON,0
bcf PIR1,TMR2IF
bsf PIE1,TMR2IE
#endif
bsf PIE2,CMIE
return
_D4PlusX
movlw 0x20 ;1x32ðàçà
movwf ctc
_PlusX
call _D4Plus
dcfsnz ctc,f
return
bra _PlusX
_D4Plus
movff DAL,Temp_DAL
incfsz Temp_DAL,f ;DAL is 0xFF?
bra _PlusL ;No!, 8bit plus is possible
btfss bitts,0 ;8bit?
bra _Plus8c ;yes for time!!!!!!!!!
movf DAH,w ;16bit op
iorlw 0xF0 ;bits 0-3 set
movwf Temp_DAH
incfsz Temp_DAH,f
bra _PlusH
bra _Plus16c ;For Test!!!!!!!
return
_Plus8c
bcf g_kFlag,3
return
_Plus16c
bcf g_kFlag,4
return
_PlusL
movff Temp_DAL,DAL
return
_PlusH
clrf DAL
movf Temp_DAH,w
andlw 0x0F ;bits 0-3 clear
movwf DAH
return
_D4MinusX
movlw 0x20 ;1X32ðàçà
movwf ctc
_MinusX
call _D4Minus
dcfsnz ctc,f
return
bra _MinusX
_D4Minus
movf DAL
btfsc STATUS,Z
bra _MinusH
decf DAL,f
bra _Finomat
_MinusH
btfss bitts,0 ;8bit?
bra _Minus8c ;For test!!!
movf DAH ;16bit op
btfsc STATUS,Z
bra _Minus16c
decf DAH,f
movlw 0xFF
movwf DAL
_Finomat
return
_Minus8c
bsf g_kFlag,3
return
_Minus16c
bsf g_kFlag,4
return
; òþíåð ñìåùåíèÿ
_D4APlus
movff g_HAShiftValue,DAH
movff g_LAShiftValue,DAL
bsf bitts,0 ;16bit set
btfss aliasStateByte,0 ;ñìåùåíèå ïîäàíî?
call _D4PlusX ;íåò, ìîæåì äåëàòü "ãðóáî" ðåã
btfsc coeff,7 ;|ïðè èñïîëüç êîììàíä _ONxK/_OFFxK | ; "ãðóáî" ðåãóëèðîâêà (øàã =1õÊ)bit7=H ?
call _D4PlusX ;|ïðè èñïîëüç êîììàíä _ONxK/_OFFxK | ; äà, áûëà êîìàíäà (øàã =1õÊ), ìîæåì äåëàòü "ãðóáî" ðåã
call _D4Plus
movff DAH,g_HAShiftValue
movff DAL,g_LAShiftValue
btfsc aliasStateByte,0 ;íåò ñìåùåíèÿ
call _loadShiftA;(?/?)
nop
return
_D4AMinus
movff g_HAShiftValue,DAH
movff g_LAShiftValue,DAL
bsf bitts,0 ;16bit set
btfss aliasStateByte,0
call _D4MinusX ;
btfsc coeff,7 ;|ïðè èñïîëüç êîììàíä _ONxK/_OFFxK | ; "ãðóáî" ðåãóëèðîâêà (øàã =1õÊ)bit7=H ?
call _D4MinusX ;|ïðè èñïîëüç êîììàíä _ONxK/_OFFxK | ; äà, áûëà êîìàíäà (øàã =1õÊ), ìîæåì äåëàòü "ãðóáî" ðåã
call _D4Minus
movff DAH,g_HAShiftValue
movff DAL,g_LAShiftValue
btfsc aliasStateByte,0 ;íåò ñìåùåíèÿ
call _loadShiftA;(?/?)
nop
return
; òþíåð ñìåùåíèÿ
_D4BPlus
movff D4BH,DAH
movff D4BL,DAL
bsf bitts,0 ;16bit set
btfss aliasStateByte,0
call _D4PlusX ;
btfsc coeff,7 ;|ïðè èñïîëüç êîììàíä _ONxK/_OFFxK | ; "ãðóáî" ðåãóëèðîâêà (øàã =1õÊ)bit7=H ?
call _D4PlusX ;|ïðè èñïîëüç êîììàíä _ONxK/_OFFxK | ; äà, áûëà êîìàíäà (øàã =1õÊ), ìîæåì äåëàòü "ãðóáî" ðåã
call _D4Plus
movff DAH,D4BH
movff DAL,D4BL
btfsc aliasStateByte,0 ;íåò ñìåùåíèÿ
call _loadShiftB;(?/?)
nop
return
_D4BMinus
movff D4BH,DAH
movff D4BL,DAL
bsf bitts,0 ;16bit set
btfss aliasStateByte,0
call _D4MinusX ;
btfsc coeff,7 ;|ïðè èñïîëüç êîììàíä _ONxK/_OFFxK | ; "ãðóáî" ðåãóëèðîâêà (øàã =1õÊ)bit7=H ?
call _D4MinusX ;|ïðè èñïîëüç êîììàíä _ONxK/_OFFxK | ; äà, áûëà êîìàíäà (øàã =1õÊ), ìîæåì äåëàòü "ãðóáî" ðåã
call _D4Minus
movff DAH,D4BH
movff DAL,D4BL
btfsc aliasStateByte,0 ;íåò ñìåùåíèÿ
call _loadShiftB;(?/?)
nop
return
; ñìåùåíèÿ
_loadShiftA;(?/?) ; ìíîãî ãäå âûçûâàåòñÿ
movff g_LAShiftValue,DAL
movff g_HAShiftValue,DAH
call lib_corrWordBeforLoadDAC;(DAL, DAH/fsr0+0+1)
goto dac_SetChannalB;(?/?)
_loadShiftB;(?/?)
movff D4BL,DAL
movff D4BH,DAH
call lib_corrWordBeforLoadDAC;(DAL, DAH/fsr0+0+1)
goto dac_SetChannalC;(?/?) ; ññûëêà çà ïðåäåëàìè ìîäóëÿ, à âûçûâàåòñÿ.
_clearShift;(?/?)
clrf DAL
clrf DAH
lfsr 0,DAL
call dac_SetChannalB;(?/?)
lfsr 0,DAL
goto dac_SetChannalC;(?/?)
; ñìåùåíèÿ
;
_D4APlusxK
movff g_HAShiftValue,DAH
movff g_LAShiftValue,DAL
bsf bitts,0 ;16bit set
#ifdef MODE_4U
btfss aliasStateByte,0
call _D4PlusX
#endif
#ifdef MODE_3U
call _D4PlusX
#endif
movff DAH,g_HAShiftValue
movff DAL,g_LAShiftValue
btfsc aliasStateByte,0 ;íåò ñìåùåíèÿ
call _loadShiftA;(?/?)
nop
return
_D4AMinusxK
movff g_HAShiftValue,DAH
movff g_LAShiftValue,DAL
bsf bitts,0 ;16bit set
#ifdef MODE_4U
btfss aliasStateByte,0
call _D4MinusX ;_Minus_xK
#else
#ifdef MODE_3U
call _D4MinusX
#else
;[Error]
#endif
#endif
movff DAH,g_HAShiftValue
movff DAL,g_LAShiftValue
btfsc aliasStateByte,0 ;íåò ñìåùåíèÿ
call _loadShiftA;(?/?)
nop
return
;;
_D4BPlusxK
movff D4BH,DAH
movff D4BL,DAL
bsf bitts,0 ;16bit set
#ifdef MODE_4U
btfss aliasStateByte,0
call _D4PlusX ;_D4Plus_xK
#else
#ifdef MODE_3U
call _D4PlusX
#else
;[Error]
#endif
#endif
movff DAH,D4BH
movff DAL,D4BL
btfsc aliasStateByte,0 ;íåò ñìåùåíèÿ
call _loadShiftB;(?/?)
nop
return
;;
_D4BMinusxK
movff D4BH,DAH
movff D4BL,DAL
bsf bitts,0 ;16bit set
#ifdef MODE_4U
btfss aliasStateByte,0
call _D4MinusX
#endif
#ifdef MODE_3U
call _D4MinusX
#endif
movff DAH,D4BH
movff DAL,D4BL
btfsc aliasStateByte,0 ;íåò ñìåùåíèÿ
call _loadShiftB;(?/?)
nop
return
; îáðàáîò÷èê
_OFFxK
bcf coeff,7 ; "òî÷íî" ðåãóëèðîâêà (øàã =1)
bcf g_summaryDataArray+10,3 ;
return
_ONxK
bsf coeff,7 ; "ãðóáî" ðåãóëèðîâêà (øàã =1õÊ)
bsf g_summaryDataArray+10,3
return
;; Îïåðàöèè ñ EEPROM
; ñîõðàíåíèå íàñòðîåê
_CurrentLimitSave
call eeprom_CheckState;(?/?)
movlw 0x15
movwf EEADR
movf ILIM
movwf EEDATA
call eeprom_Save;(?/?)
return
_ShiftOneSave
call eeprom_CheckState;(?/?)
movlw 0x16
movwf EEADR
movff g_LAShiftValue,EEDATA
call eeprom_Save;(?/?)
call eeprom_CheckState;(?/?)
movlw 0x17
movwf EEADR
movlw b'00001111' ;ìàñêà äëÿ çàùèòû g_HAShiftValue îò ïðåâûøåíèÿ ìàêñ ðàçðåø ÷èñëîâîãî çíà÷åíèÿ
andwf g_HAShiftValue
movff g_HAShiftValue,EEDATA
call eeprom_Save;(?/?)
nop
return
_ShiftTwoSave
call eeprom_CheckState;(?/?)
movlw 0x18
movwf EEADR
movff D4BL,EEDATA
call eeprom_Save;(?/?)
call eeprom_CheckState;(?/?)
movlw 0x19
movwf EEADR
movlw b'00001111' ;ìàñêà äëÿ çàùèòû g_HAShiftValue îò ïðåâûøåíèÿ ìàêñ ðàçðåø ÷èñëîâîãî çíà÷åíèÿ
andwf D4BH
movff D4BH,EEDATA
call eeprom_Save;(?/?)
nop
return
;ñîõðàíåíèå íàñòðîåê
end
| zaqwes8811/micro-apps | matlab_ext/code-miners/projects/prepro/test-data/pb/scheduler.asm | Assembly | mit | 11,224 | 17.4 | 109 | 0.702423 | false |
<?php
return array (
'Group not found!' => 'Groep niet gevonden!',
);
| ProfilerTeam/Profiler | protected/modules_core/admin/messages/nl/controllers_GroupController.php | PHP | mit | 72 | 17 | 47 | 0.611111 | false |
exports = module.exports = History;
function History (state, executionTime) {
this.state = state;
this.executionTime = executionTime;
}
| gurbano/fuzzy-octo-location | public/libs/garageserver.io/lib/entities/history.js | JavaScript | mit | 145 | 23.166667 | 41 | 0.717241 | false |
<?php
class CaisseSortiesManager{
//attributes
private $_db;
//constructor
public function __construct($db){
$this->_db = $db;
}
//CRUD operations
public function add(CaisseSorties $sortie){
$query = $this->_db->prepare(
'INSERT INTO t_caisse_sorties (montant, designation, dateOperation, destination, utilisateur)
VALUES (:montant, :designation, :dateOperation, :destination, :utilisateur)')
or die(print_r($this->_db->errorInfo()));
$query->bindValue(':montant', $sortie->montant());
$query->bindValue(':designation', $sortie->designation());
$query->bindValue(':destination', $sortie->destination());
$query->bindValue(':dateOperation', $sortie->dateOperation());
$query->bindValue(':utilisateur', $sortie->utilisateur());
$query->execute();
$query->closeCursor();
}
public function update(CaisseSorties $sortie){
$query = $this->_db->prepare('
UPDATE t_caisse_sorties SET montant=:montant, designation=:designation,
dateOperation=:dateOperation, destination=:destination, utilisateur=:utilisateur WHERE id=:idEntrees')
or die(print_r($this->_db->errorInfo()));
$query->bindValue(':idEntrees', $sortie->id());
$query->bindValue(':montant', $sortie->montant());
$query->bindValue(':designation', $sortie->designation());
$query->bindValue(':destination', $sortie->destination());
$query->bindValue(':dateOperation', $sortie->dateOperation());
$query->bindValue(':utilisateur', $sortie->utilisateur());
$query->execute();
$query->closeCursor();
}
public function delete($idSortie){
$query = $this->_db->prepare('DELETE FROM t_caisse_sorties WHERE id=:idSortie')
or die(print_r($this->_db->errorInfo()));;
$query->bindValue(':idSortie', $idSortie);
$query->execute();
$query->closeCursor();
}
public function getCaisseSortiesByLimits($begin, $end){
$CaisseSorties = array();
$query = $this->_db->query('SELECT * FROM t_caisse_sorties ORDER BY id DESC LIMIT '.$begin.', '.$end)
or die(print_r($this->_db->errorInfo()));
while($data = $query->fetch(PDO::FETCH_ASSOC)){
$CaisseSorties[] = new CaisseSorties($data);
}
$query->closeCursor();
return $CaisseSorties;
}
public function getCaisseSorties(){
$CaisseSorties = array();
$query = $this->_db->query('SELECT * FROM t_caisse_sorties ORDER BY id DESC')
or die(print_r($this->_db->errorInfo()));
while($data = $query->fetch(PDO::FETCH_ASSOC)){
$CaisseSorties[] = new CaisseSorties($data);
}
$query->closeCursor();
return $CaisseSorties;
}
public function getCaisseSortiesBureauByLimits($begin, $end){
$CaisseSorties = array();
$query = $this->_db->query('SELECT * FROM t_caisse_sorties WHERE destination="Bureau" ORDER BY id DESC LIMIT '.$begin.', '.$end)
or die(print_r($this->_db->errorInfo()));
while($data = $query->fetch(PDO::FETCH_ASSOC)){
$CaisseSorties[] = new CaisseSorties($data);
}
$query->closeCursor();
return $CaisseSorties;
}
public function getCaisseSortiesBureau(){
$CaisseSorties = array();
$query = $this->_db->query('SELECT * FROM t_caisse_sorties WHERE destination="Bureau" ORDER BY id DESC')
or die(print_r($this->_db->errorInfo()));
while($data = $query->fetch(PDO::FETCH_ASSOC)){
$CaisseSorties[] = new CaisseSorties($data);
}
$query->closeCursor();
return $CaisseSorties;
}
public function getCaisseSortiesProjetByLimits($idProjet, $begin, $end){
$CaisseSorties = array();
$query = $this->_db->prepare('SELECT * FROM t_caisse_sorties WHERE destination=:idProjet ORDER BY id DESC LIMIT '.$begin.', '.$end)
or die(print_r($this->_db->errorInfo()));
$query->bindValue(':idProjet', $idProjet);
$query->execute();
while($data = $query->fetch(PDO::FETCH_ASSOC)){
$CaisseSorties[] = new CaisseSorties($data);
}
$query->closeCursor();
return $CaisseSorties;
}
public function getCaisseSortiesProjet($idProjet){
$CaisseSorties = array();
$query = $this->_db->prepare('SELECT * FROM t_caisse_sorties WHERE destination=:idProjet ORDER BY id DESC')
or die(print_r($this->_db->errorInfo()));
$query->bindValue(':idProjet', $idProjet);
$query->execute();
while($data = $query->fetch(PDO::FETCH_ASSOC)){
$CaisseSorties[] = new CaisseSorties($data);
}
$query->closeCursor();
return $CaisseSorties;
}
public function getDestinations(){
$destinations = array();
$query = $this->_db->query('SELECT DISTINCT destination FROM t_caisse_sorties')
or die(print_r($this->_db->errorInfo()));
while($data = $query->fetch(PDO::FETCH_ASSOC)){
$destinations[] = $data['destination'];
}
$query->closeCursor();
return $destinations;
}
public function getCaisseSortiesNumber(){
$query = $this->_db->query('SELECT COUNT(*) AS numberSorties FROM t_caisse_sorties')
or die(print_r($this->_db->errorInfo()));
$data = $query->fetch(PDO::FETCH_ASSOC);
$query->closeCursor();
return $data['numberSorties'];
}
public function getCaisseSortiesNumberBureau(){
$query = $this->_db->query('SELECT COUNT(*) AS numberSorties FROM t_caisse_sorties WHERE destination="Bureau"')
or die(print_r($this->_db->errorInfo()));
$data = $query->fetch(PDO::FETCH_ASSOC);
$query->closeCursor();
return $data['numberSorties'];
}
public function getCaisseSortiesNumberProjet($idProjet){
$query = $this->_db->prepare('SELECT COUNT(*) AS numberSorties FROM t_caisse_sorties WHERE destination=:idProjet')
or die(print_r($this->_db->errorInfo()));
$query->bindValue(':idProjet', $idProjet);
$query->execute();
$data = $query->fetch(PDO::FETCH_ASSOC);
$query->closeCursor();
return $data['numberSorties'];
}
public function getTotalCaisseSorties(){
$query = $this->_db->query('SELECT SUM(montant) AS total FROM t_caisse_sorties');
$data = $query->fetch(PDO::FETCH_ASSOC);
$total = $data['total'];
return $total;
}
public function getTotalCaisseSortiesBureau(){
$query = $this->_db->query('SELECT SUM(montant) AS total FROM t_caisse_sorties WHERE destination="Bureau"');
$data = $query->fetch(PDO::FETCH_ASSOC);
$total = $data['total'];
return $total;
}
public function getTotalCaisseSortiesProjet($idProjet){
$query = $this->_db->prepare('SELECT SUM(montant) AS total FROM t_caisse_sorties WHERE destination=:idProjet');
$query->bindValue(':idProjet', $idProjet);
$query->execute();
$data = $query->fetch(PDO::FETCH_ASSOC);
$total = $data['total'];
return $total;
}
public function getLastId(){
$query = $this->_db->query('SELECT id AS last_id FROM t_caisse_sorties ORDER BY id DESC LIMIT 0, 1');
$data = $query->fetch(PDO::FETCH_ASSOC);
$id = $data['last_id'];
return $id;
}
}
| aassou/Annahda | www/model/CaisseSortiesManager.php | PHP | mit | 7,099 | 37.79235 | 139 | 0.629103 | false |
package hudson.plugins.git.extensions.impl;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.Test;
public class PruneStaleBranchTest {
@Test
public void equalsContract() {
EqualsVerifier.forClass(PruneStaleBranch.class)
.usingGetClass()
.verify();
}
}
| jenkinsci/git-plugin | src/test/java/hudson/plugins/git/extensions/impl/PruneStaleBranchTest.java | Java | mit | 321 | 21.928571 | 55 | 0.672897 | false |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("QuanLyThuVien")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hewlett-Packard")]
[assembly: AssemblyProduct("QuanLyThuVien")]
[assembly: AssemblyCopyright("Copyright © Hewlett-Packard 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9231c47e-3af2-4cd7-9e00-acb379c34811")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| Tw0Pig/Quanlythuvien | QuanLyThuVienn-Version2/QuanLyThuVien/Properties/AssemblyInfo.cs | C# | mit | 1,432 | 38.694444 | 84 | 0.749475 | false |
/* $NetBSD: SYS.h,v 1.8 2003/08/07 16:42:02 agc Exp $ */
/*-
* Copyright (c) 1990 The Regents of the University of California.
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* 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 BY THE REGENTS 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 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.
*
* from: @(#)SYS.h 5.5 (Berkeley) 5/7/91
* $FreeBSD$
*/
#include <machine/asm.h>
#include <sys/syscall.h>
#include <machine/swi.h>
#define SYSTRAP(x) \
mov ip, r7; \
ldr r7, =SYS_ ## x; \
swi 0; \
mov r7, ip
#define CERROR _C_LABEL(cerror)
#define CURBRK _C_LABEL(curbrk)
#define _SYSCALL_NOERROR(x) \
ENTRY(__CONCAT(__sys_, x)); \
.weak _C_LABEL(x); \
.set _C_LABEL(x), _C_LABEL(__CONCAT(__sys_,x)); \
.weak _C_LABEL(__CONCAT(_,x)); \
.set _C_LABEL(__CONCAT(_,x)),_C_LABEL(__CONCAT(__sys_,x)); \
SYSTRAP(x)
#define _SYSCALL(x) \
_SYSCALL_NOERROR(x); \
it cs; \
bcs PIC_SYM(CERROR, PLT)
#define SYSCALL(x) \
_SYSCALL(x)
#define PSEUDO(x) \
ENTRY(__CONCAT(__sys_, x)); \
.weak _C_LABEL(__CONCAT(_,x)); \
.set _C_LABEL(__CONCAT(_,x)),_C_LABEL(__CONCAT(__sys_,x)); \
SYSTRAP(x); \
it cs; \
bcs PIC_SYM(CERROR, PLT); \
RET
#define RSYSCALL(x) \
_SYSCALL(x); \
RET
.globl CERROR
| kishoredbn/barrelfish | lib/libc/arm/SYS.h | C | mit | 2,755 | 33.4375 | 77 | 0.666425 | false |
Please use [pull requests](https://github.com/airbnb/enzyme/pull/new/master) to add your organization and/or project to this document!
Organizations
----------
- [Airbnb](https://github.com/airbnb)
- [Pinterest](https://github.com/pinterest)
- [Product Hunt](https://github.com/producthunt)
- [Walmart Labs](https://github.com/walmartlabs)
Projects
----------
- [Rheostat](https://github.com/airbnb/rheostat)
- [React Boilerplate](https://github.com/mxstbr/react-boilerplate/tree/v3.0.0)
| ajames72/MovieDBReact | node_modules/enzyme/INTHEWILD.md | Markdown | mit | 496 | 37.153846 | 134 | 0.71371 | false |
<div class="form-group" ng-class="{{classList}}" ng-form="fg_{{$id}}">
<abm-transclude-slot></abm-transclude-slot>
<div ng-show="showErrors" ng-messages="this['fg_'+$id].$error" ng-messages-multiple>
<div ng-if="errorMessagesInclude" ng-messages-include="{{errorMessagesInclude}}"></div>
<div ng-repeat="(key,value) in errorMessageMap">
<!-- use ng-message-exp for a message whose key is given by an expression -->
<div ng-message-exp="key" class="help-block">{{value}}</div>
</div>
</div>
</div>
| eregnier/checkme | static/bower_components/angular-bootstrap-material/src/templates/form-group.html | HTML | mit | 527 | 51.7 | 91 | 0.652751 | false |
'use strict';
// Use applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('chats'); | willPHales/cb | public/modules/chats/chats.client.module.js | JavaScript | mit | 128 | 31.25 | 63 | 0.8125 | false |
/*!
* Start Bootstrap - 4 Col Portfolio HTML Template (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
h4
{
color:white;
}
body {
background: #281525 url('background.jpg') no-repeat center center fixed ;
padding-top: 70px; /* Required padding for .navbar-fixed-top. Remove if using .navbar-static-top. Change if height of navigation changes. */
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size:cover;
}
.portfolio-item {
margin-bottom: 25px;
}
footer {
margin: 50px 0;
} | CoderGirl42/GalacticSoft | portfolio/item/css/galacticsoft.css | CSS | mit | 645 | 23.846154 | 144 | 0.703876 | false |
<?php defined('BX_DOL') or die('hack attempt');
/**
* Copyright (c) UNA, Inc - https://una.io
* MIT License - https://opensource.org/licenses/MIT
*
* @defgroup BaseProfile Base classes for profile modules
* @ingroup UnaModules
*
* @{
*/
class BxBaseModProfileInstaller extends BxBaseModGeneralInstaller
{
protected $_sParamRelations;
protected $_sParamDefaultProfileType;
function __construct($aConfig)
{
parent::__construct($aConfig);
$this->_sParamRelations = 'sys_relations';
$this->_sParamDefaultProfileType = 'sys_account_default_profile_type';
}
function enable($aParams)
{
$aResult = parent::enable($aParams);
if(BxDolService::call($this->_aConfig['name'], 'act_as_profile') !== true)
return $aResult;
if($aResult['result'] && getParam($this->_sParamDefaultProfileType) == '')
setParam($this->_sParamDefaultProfileType, $this->_aConfig['name']);
return $aResult;
}
function disable($aParams)
{
$aResult = parent::disable($aParams);
if(BxDolService::call($this->_aConfig['name'], 'act_as_profile') !== true)
return $aResult;
$sName = $this->_aConfig['name'];
if($aResult['result'] && getParam($this->_sParamDefaultProfileType) == $sName)
setParam($this->_sParamDefaultProfileType, '');
if($aResult['result']) {
$sDiv = ',';
$sRelations = getParam($this->_sParamRelations);
if(!empty($sRelations) && strpos($sRelations, $sName) !== false) {
$aRelations = explode($sDiv, $sRelations);
foreach($aRelations as $iIndex => $sValue)
if(strpos($sValue, $sName) !== false)
unset($aRelations[$iIndex]);
setParam($this->_sParamRelations, implode($sDiv, $aRelations));
}
}
if ($aResult['result']) { // disabling was successful
// TODO: switch accounts context which active profiles belong to this module
}
return $aResult;
}
}
/** @} */
| unaio/una | upgrade/files/9.0.1-10.0.0.B1/files/modules/base/profile/classes/BxBaseModProfileInstaller.php | PHP | mit | 2,125 | 30.25 | 88 | 0.576471 | false |
//@flow
const a = require('../a')
let x : number = a;
| mroch/flow | tests/dir_coverage/folder/d.js | JavaScript | mit | 55 | 12.75 | 25 | 0.527273 | false |
"""
make_gamesheets.py
~~~~~~~~~~~~~~~~~~
Read in the CSV in '../data/season2015.csv' and
write out excel files with the whole season of game sheets.
If you want to use your own formatting, the documentation for
openpyxl is here: http://openpyxl.readthedocs.org/
"""
from __future__ import print_function
import os
import openpyxl
import pandas as pd
# Change the path if your file is not here.
input_file = os.path.join('data', 'nfl_season2015.csv')
output_file = os.path.join('excel_files', 'sheets2015.xlsx')
# Default for Pandas is to draw a border around the header columns.
# Explicitly turn that off.
pd.core.format.header_style = None
# Fill colors for conditional formatting
def make_fill(color):
try:
return openpyxl.styles.PatternFill(
start_color=color, end_color=color, fill_type='solid')
except AttributeError:
fill = openpyxl.styles.Fill()
fill.start_color.index = color
fill.end_color.index = color
fill.fill_type = 'solid'
return fill
fills = dict(
red = make_fill('FFFFCCCC'),
yellow = make_fill('FFFFFFDD'),
green = make_fill('FFCCFFCC')
)
def add_conditional_fill(sheet, cell_range, color='yellow', formula=None):
try:
sheet.conditional_formatting.add(cell_range, {
'type': 'expression',
'dxf': {'fill': fills[color]},
'formula': [formula],
'stopIfTrue': '1'
})
except AttributeError:
dxfid = sheet.conditional_formatting.addDxfStyle(
sheet.parent, None, None, fills[color])
sheet.conditional_formatting.addCustomRule(cell_range, {
'type': 'expression',
#'dxf': {'fill': fills[color]},
'dxfId': dxfid,
'formula': [formula],
'stopIfTrue': '1'
})
# rows and columns to skip
skip_rows = 7
skip_cols = 1
# Change the path if your file is not here.
print("Reading schedule from {}...".format(input_file))
season = pd.read_csv(input_file)
# Add blank columns for convenience
season['winhome'] = ''
season['spacer'] = ''
season['winaway'] = ''
# Open an excel workbook and write to it.
with pd.ExcelWriter(output_file, engine='openpyxl') as workbook:
for week, games in season.groupby('week'):
gametable = games[['dayofweek', 'homeTeam', 'winhome', 'spacer', 'awayTeam', 'winaway']]
nrow, ncol = gametable.shape
sheet_name='Week {}'.format(week)
gametable.to_excel(workbook,
sheet_name=sheet_name,
index=False, # don't show the row numbers
header=['Day', 'Home', 'Win', '', 'Away', 'Win'], # alternative column names
startrow=skip_rows,
startcol=skip_cols)
sheet = workbook.sheets[sheet_name]
# Add instructions
sheet['A1'] = "Week {} (Sunday is {})".format(week, games[games['dayofweek']=='Sunday']['date'].iloc[0])
sheet['A2'] = ("Mark the 'Win' column for each team you think "
"will win. Winning sheet has the most correct.")
sheet['A4'] = "Name:"
sheet['B4'] = "<<your name>>"
sheet['A5'] = "Tiebreaker *:"
sheet['B5'] = "<<winning guess is closest to the total combined points in the final game>>"
sheet['A{}'.format(nrow + skip_rows + 1)] = "Tiebreaker game *"
# Set column widths
col_widths = zip('ABCDEFG', (18, 9, 20, 5, 10, 20, 5))
for col, width in col_widths:
sheet.column_dimensions[col].width = width
# Bold and center the headers
cell = col + str(skip_rows + 1)
try:
sheet[cell].font = openpyxl.styles.Font(bold=True)
sheet[cell].alignment = openpyxl.styles.Alignment(horizontal = 'center')
except TypeError:
sheet[cell].style.font = openpyxl.styles.fonts.Font()
sheet[cell].style.font.bold = True
sheet[cell].style.alignment = openpyxl.styles.alignment.Alignment()
sheet[cell].style.alignment.horizontal = openpyxl.styles.alignment.Alignment.HORIZONTAL_CENTER
# Right align specific cells
right_align = ('A4', 'A5', 'A{}'.format(nrow + skip_rows + 1))
for cell in right_align:
try:
sheet[cell].alignment = openpyxl.styles.Alignment(horizontal = 'right')
except TypeError:
sheet[cell].style.alignment = openpyxl.styles.alignment.Alignment()
sheet[cell].style.alignment_style = openpyxl.styles.alignment.Alignment.HORIZONTAL_RIGHT
# Create formatting rules to ensure sheet is correctly filled
homecol, awaycol = 'D', 'G'
for row in range(skip_rows + 2, skip_rows + 2 + nrow):
cell_range = "{startcol}{row}:{endcol}{row}".format(
startcol=chr(ord('A') + skip_cols),
endcol=chr(ord('A') + skip_cols + ncol - 1),
row=row)
# Yellow if unfilled
add_conditional_fill(sheet, cell_range, color='yellow', formula=
'and(ISBLANK(${homecol}${row}), ISBLANK(${awaycol}${row}))'.format(
homecol=homecol, awaycol=awaycol, row=row)
)
# Red if both teams picked
add_conditional_fill(sheet, cell_range, color='red', formula=
'and(not(ISBLANK(${homecol}${row})), not(ISBLANK(${awaycol}${row})))'.format(
homecol=homecol, awaycol=awaycol, row=row)
)
# Green if just one team picked
add_conditional_fill(sheet, cell_range, color='green', formula=(
'or(and(not(ISBLANK(${homecol}${row})), ISBLANK(${awaycol}${row})), '
'and(ISBLANK(${homecol}${row}), not(ISBLANK(${awaycol}${row}))))' ).format(
homecol=homecol, awaycol=awaycol, row=row)
)
# finished.
print("Finished.")
print("Output file is at {}.\n".format(output_file))
| nkhuyu/office-nfl-pool | extra_code/make_gamesheets.py | Python | mit | 6,062 | 40.238095 | 112 | 0.580172 | false |
<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
* This library provides server-side processing for DataTables for jQuery.
* It is compatible with DataTables v1.10 and above (hopefuly).
* Written for and tested on CodeIgniter 3.0.
*
* See
* @link https://next.datatables.net
* @link https://next.datatables.net/examples/server_side/
*
* You may find a visually compatible with Bootstrap 3 integration for DataTables at:
* @link http://startbootstrap.com/sb-admin-v2
* @link https://github.com/IronSummitMedia/startbootstrap/tree/master/templates/sb-admin-v2
*
* Here is the original integration with Bootstrap:
* https://github.com/DataTables/Plugins/tree/master/integration/bootstrap
*
* For table responsiveness with server-side processing the following plugin is needed:
* @link https://github.com/Comanche/datatables-responsive
*
* @author Ivan Tcholakov <ivantcholakov@gmail.com>, 2014-2015
* @license The MIT License, http://opensource.org/licenses/MIT
*/
// Usage Example:
/*
<?php defined('BASEPATH') OR exit('No direct script access allowed.');
class Data_tables_ajax_controller extends Base_Ajax_Controller {
public function __construct() {
parent::__construct();
$this->load
->library('datatable')
->model('users')
;
}
public function index() {
$this->output->set_header('Content-Type: application/json; charset=utf-8');
$columns = array(
array(
'db' => 'id',
'dt' => 'id',
'exact_match' => true // An instruction to the individual filter, it forces WHERE instead of LIKE clause.
),
array(
'db' => 'username',
'dt' => 'username'
),
array(
'db' => 'email',
'dt' => 'email'
),
array(
'db' => 'first_name',
'dt' => 'first_name'
),
array(
'db' => 'last_name',
'dt' => 'last_name'
),
// An example about using expressions:
array(
'db' => 'name',
'expression' => "CONCAT(first_name, ' ', last_name)",
'dt' => 'name'
),
);
$this->output->set_output(
$this->datatable
->set_columns($columns)
->from($this->users) // Using a custom model that extends Core_Model.
//->from('users', 'id') // Using CodeIgniter's Query Builder.
->generate()
);
}
}
*/
class Datatable {
protected $ci;
protected $request;
protected $db;
protected $primary_key;
protected $columns;
protected $has_order;
protected $has_filter;
public function __construct() {
$this->ci =& get_instance();
$this->clear();
}
// An empty method that keeps chaining, the parameter does the desired operation as a side-effect.
public function that($expression = NULL) {
return $this;
}
public function generate($as_json = true) {
$this->set_filters();
$db = clone $this->db;
$recordsTotal = $db->count_all_results();
$this->set_limit()->set_order();
$select = $this->pluck($this->columns, 'db');
$expressions = $this->pluck($this->columns, 'expression');
if (!empty($select)) {
$i = 0;
foreach ($select as $key => $field) {
if (trim($field) != '') {
if (isset($expressions[$i])) {
$select[$key] = $expressions[$i].' AS '.$this->db()->protect_identifiers($field);
} else {
$select[$key] = $this->db()->protect_identifiers($field);
}
} else {
// TODO: Remove this permanently.
//$select[$key] = 'NULL';
}
$i++;
}
$select = implode(', ', $select);
$this->select($select, false);
}
if ($this->is_custom_model()) {
$data = $this->db->as_array()->find();
} else {
$data = $this->db->get()->result_array();
}
// Ivan: Strange, the table works fine when $recordsFiltered = $recordsTotal
$recordsFiltered = $recordsTotal;
$result = array(
'draw' => isset($this->request['draw']) ? (int) $this->request['draw'] : 0,
'recordsTotal' => $recordsTotal,
'recordsFiltered' => $recordsFiltered,
'data' => $this->data_output($data)
);
$this->clear();
if ($as_json) {
return json_encode($result);
}
return $result;
}
// If not set, the default request is get_instance()->input->post().
public function set_request($request) {
if (is_array($request)) {
$this->request = $request;
}
return $this;
}
public function set_columns($columns) {
if (!is_array($columns)) {
return $this;
}
$this->columns = $columns;
return $this;
}
public function from($from, $primary_key = null, $db = null) {
// Check whether a custom model is to be used.
if (is_object($from)) {
if ($this->is_custom_model($from, true)) {
// $front is a model that extends our custom Core_Model.
// See https://github.com/ivantcholakov/codeigniter-base-model
$this->db = $from;
$this->primary_key = $this->db->primary_key();
} else {
// Wrong object type has been passed, abort.
$this->clear();
}
return $this;
}
// The normal Query builder has been chosen here.
// Set the Query Builder.
if (is_object($db)) {
$this->db = $db;
}
// Set the table and the primary key.
if (is_object($this->db)) {
$this->db->from($from);
if ($primary_key !== null) {
$this->primary_key = $primary_key;
}
} else {
// The Query Builder is missing, abort.
$this->clear();
}
return $this;
}
// Checks whether ordering has been requested.
public function has_order() {
if (isset($this->has_order)) {
return $this->has_order;
}
if (isset($this->request['order']) && count($this->request['order'])) {
$dtColumns = $this->pluck($this->columns, 'dt');
for ($i = 0, $ien = count($this->request['order']); $i < $ien; $i++) {
// Convert the column index into the column data property.
$columnIdx = intval($this->request['order'][$i]['column']);
$requestColumn = $this->request['columns'][$columnIdx];
$columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $this->columns[$columnIdx];
$has_db_prop = isset($column['db']) && $column['db'] != '';
if ($has_db_prop && isset($requestColumn['orderable']) && $requestColumn['orderable'] == 'true') {
$this->has_order = true;
return true;
}
}
}
$this->has_order = false;
return false;
}
// Checks whether global filter or at least one indivifual filter
// has been requested.
public function has_filter() {
if (isset($this->has_filter)) {
return $this->has_filter;
}
$dtColumns = $this->pluck($this->columns, 'dt');
if (isset($this->request['columns']) && isset($this->request['search'])
&& isset($this->request['search']['value']) && $this->request['search']['value'] != '') {
$str = $this->request['search']['value'];
for ($i = 0, $ien = count($this->request['columns']); $i < $ien; $i++) {
$requestColumn = $this->request['columns'][$i];
$columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $this->columns[$columnIdx];
$has_db_prop = isset($column['db']) && $column['db'] != '';
if ($has_db_prop && isset($requestColumn['searchable']) && $requestColumn['searchable'] == 'true') {
$this->has_filter = true;
return true;
}
}
}
// Individual column filtering
if (isset($this->request['columns'])) {
for ($i = 0, $ien = count($this->request['columns']); $i < $ien; $i++) {
$requestColumn = $this->request['columns'][$i];
$columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $this->columns[$columnIdx];
$str = isset($requestColumn['search']['value']) ? $requestColumn['search']['value'] : '';
$has_db_prop = isset($column['db']) && $column['db'] != '';
if ($has_db_prop && isset($requestColumn['searchable']) && $requestColumn['searchable'] == 'true' && $str != '') {
$this->has_filter = true;
return true;
}
}
}
$this->has_filter = false;
return false;
}
// Model/query builder method wrappers.
//--------------------------------------------------------------------------
public function with_deleted() {
if ($this->is_custom_model()) {
$this->db->with_deleted();
} else {
die('DB::with_deleted() is not supported. Use a custom model.');
}
return $this;
}
public function only_deleted() {
if ($this->is_custom_model()) {
$this->db->only_deleted();
} else {
die('DB::only_deleted() is not supported. Use a custom model.');
}
return $this;
}
public function order_by($criteria, $order = '', $escape = NULL) {
$this->db->order_by($criteria, $order, $escape);
return $this;
}
public function limit($limit, $offset = FALSE) {
$this->db->limit($limit, $offset);
return $this;
}
public function offset($offset) {
$this->db->offset($offset);
return $this;
}
public function select($select = '*', $escape = NULL) {
$this->db->select($select, $escape);
return $this;
}
public function distinct($val = TRUE) {
$this->db->distinct($val);
return $this;
}
public function join($table, $cond, $type = '', $escape = NULL) {
$this->db->join($table, $cond, $type, $escape);
return $this;
}
public function escape($str) {
return $this->db->escape($str);
}
public function escape_like_str($str) {
return $this->db->escape_like_str($str);
}
public function escape_str($str, $like = FALSE) {
return $this->db->escape_str($str, $like);
}
public function where($key, $value = NULL, $escape = NULL) {
$this->db->where($key, $value, $escape);
return $this;
}
public function or_where($key, $value = NULL, $escape = NULL) {
$this->db->or_where($key, $value, $escape);
return $this;
}
public function where_in($key = NULL, $values = NULL, $escape = NULL) {
$this->db->where_in($key, $values, $escape);
return $this;
}
public function or_where_in($key = NULL, $values = NULL, $escape = NULL) {
$this->db->or_where_in($key, $values, $escape);
return $this;
}
public function where_not_in($key = NULL, $values = NULL, $escape = NULL) {
$this->db->where_not_in($key, $values, $escape);
return $this;
}
public function or_where_not_in($key = NULL, $values = NULL, $escape = NULL) {
$this->db->or_where_not_in($key, $values, $escape);
return $this;
}
public function like($field, $match = '', $side = 'both', $escape = NULL) {
$this->db->like($field, $match, $side, $escape);
return $this;
}
public function not_like($field, $match = '', $side = 'both', $escape = NULL) {
$this->db->not_like($field, $match, $side, $escape);
return $this;
}
public function or_like($field, $match = '', $side = 'both', $escape = NULL) {
$this->db->or_like($field, $match, $side, $escape);
return $this;
}
public function or_not_like($field, $match = '', $side = 'both', $escape = NULL) {
$this->db->or_not_like($field, $match, $side, $escape);
return $this;
}
public function group_start($not = '', $type = 'AND ') {
$this->db->group_start($not, $type);
return $this;
}
public function or_group_start() {
$this->db->or_group_start();
return $this;
}
public function not_group_start() {
$this->db->not_group_start();
return $this;
}
public function or_not_group_start() {
$this->db->or_not_group_start();
return $this;
}
public function group_end() {
$this->db->group_end();
return $this;
}
public function group_by($by, $escape = NULL) {
$this->db->group_by($by, $escape);
return $this;
}
public function having($key, $value = NULL, $escape = NULL) {
$this->db->having($key, $value, $escape);
return $this;
}
public function or_having($key, $value = NULL, $escape = NULL) {
$this->db->having($key, $value, $escape);
return $this;
}
// Protected methods
//--------------------------------------------------------------------------
protected function clear() {
$this->set_request($this->ci->input->post());
if (isset($this->ci->db) && is_object($this->ci->db)) {
$this->db = $this->ci->db;
} else {
$this->db = null;
}
$this->primary_key = 'id';
$this->columns = null;
}
protected function set_limit() {
if (isset($this->request['start']) && $this->request['length'] != -1) {
$this
->offset((int) $this->request['start'])
->limit((int) $this->request['length']);
}
return $this;
}
protected function set_order() {
if (isset($this->request['order']) && count($this->request['order'])) {
$dtColumns = $this->pluck($this->columns, 'dt');
for ($i = 0, $ien = count($this->request['order']); $i < $ien; $i++) {
// Convert the column index into the column data property.
$columnIdx = intval($this->request['order'][$i]['column']);
$requestColumn = $this->request['columns'][$columnIdx];
$columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $this->columns[$columnIdx];
$has_db_prop = isset($column['db']) && $column['db'] != '';
if ($has_db_prop && isset($requestColumn['orderable']) && $requestColumn['orderable'] == 'true') {
$dir = $this->request['order'][$i]['dir'] === 'asc' ? 'asc' : 'desc';
$this->order_by($column['db'], $dir);
}
}
}
return $this;
}
protected function set_filters() {
$dtColumns = $this->pluck($this->columns, 'dt');
if (isset($this->request['columns']) && isset($this->request['search'])
&& isset($this->request['search']['value']) && $this->request['search']['value'] != '') {
$this->group_start();
$str = $this->request['search']['value'];
$c = 0;
for ($i = 0, $ien = count($this->request['columns']); $i < $ien; $i++) {
$requestColumn = $this->request['columns'][$i];
$columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $this->columns[$columnIdx];
$has_db_prop = isset($column['db']) && $column['db'] != '';
if ($has_db_prop && isset($requestColumn['searchable']) && $requestColumn['searchable'] == 'true') {
$has_expression_prop = isset($column['expression']) && $column['expression'] != '';
if ($c == 0) {
if ($has_expression_prop) {
//$this->like('('.$column['expression'].')', $str);
$this->like($column['expression'], $str);
} else {
$this->like($column['db'], $str);
}
} else {
if ($has_expression_prop) {
//$this->or_like('('.$column['expression'].')', $str);
$this->or_like($column['expression'], $str);
} else {
$this->or_like($column['db'], $str);
}
}
$c++;
}
}
$this->group_end();
}
// Individual column filtering
if (isset($this->request['columns'])) {
for ($i = 0, $ien = count($this->request['columns']); $i < $ien; $i++) {
$requestColumn = $this->request['columns'][$i];
$columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $this->columns[$columnIdx];
$str = isset($requestColumn['search']['value']) ? $requestColumn['search']['value'] : '';
$has_db_prop = isset($column['db']) && $column['db'] != '';
if ($has_db_prop && isset($requestColumn['searchable']) && $requestColumn['searchable'] == 'true' && $str != '') {
$has_expression_prop = isset($column['expression']) && $column['expression'] != '';
$exact_match = !empty($column['exact_match']);
if ($has_expression_prop) {
if ($exact_match) {
//$this->where('('.$column['expression'].') =', $str);
$this->where($column['expression'].' =', $str);
} else {
//$this->like('('.$column['expression'].')', $str);
$this->like($column['expression'], $str);
}
} else {
if ($exact_match) {
$this->where($column['db'], $str);
} else {
$this->like($column['db'], $str);
}
}
}
}
}
return $this;
}
protected function data_output (& $data) {
$out = array();
for ($i = 0, $ien = count($data); $i < $ien; $i++) {
$row = array();
for ($j = 0, $jen = count($this->columns); $j < $jen; $j++) {
$column = & $this->columns[$j];
$has_db_prop = isset($column['db']) && $column['db'] != '';
// Is there a formatter? (closures/lambda functions and array($object, 'method') callables)
$formatter = isset($column['formatter']) ? (is_callable($column['formatter']) ? $column['formatter'] : null) : null;
if (isset($formatter)) {
$row[$column['dt']] = is_array($formatter)
? $formatter[0]->{$formatter[1]}($has_db_prop ? $data[$i][$column['db']] : null, $data[$i])
: $formatter($has_db_prop ? $data[$i][$column['db']] : null, $data[$i]);
} else {
if (isset($column['dt'])) {
$row[$column['dt']] = $has_db_prop ? $data[$i][$column['db']] : null;
}
}
}
$out[] = $row;
}
return $out;
}
/**
* Pull a particular property from each assoc. array in a numeric array,
* returning and array of the property values from each item.
*
* @param array $a Array to get data from
* @param string $prop Property to read
* @return array Array of property values
*/
protected function pluck($a, $prop) {
$out = array();
for ($i = 0, $len = count($a); $i < $len; $i++) {
$has_prop = isset($a[$i][$prop]) && $a[$i][$prop] != '';
if ($has_prop) {
$out[] = $a[$i][$prop];
} else {
$out[] = null;
}
}
return $out;
}
protected function is_custom_model($object = null, $strict_check = false) {
if (!is_object($object)) {
if ($strict_check) {
return false;
}
$object = $this->db;
if (!is_object($object)) {
return false;
}
}
return @ is_a($object, 'Core_Model');
}
protected function db() {
return $this->is_custom_model() ? $this->db->database() : $this->db;
}
}
| demenvil/starter-public-edition-4 | platform/common/libraries/Datatable.php | PHP | mit | 21,655 | 26.376738 | 132 | 0.467513 | false |
/*
* 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:
*
* * 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.
*/
WebInspector = {};
WebInspector.UIString = function(s) { return s; };
importScripts("BinarySearch.js");
importScripts("HeapSnapshot.js");
importScripts("HeapSnapshotWorkerDispatcher.js");
importScripts("PartialQuickSort.js");
function postMessageWrapper(message)
{
postMessage(message);
}
var dispatcher = new WebInspector.HeapSnapshotWorkerDispatcher(this, postMessageWrapper);
addEventListener("message", dispatcher.dispatchMessage.bind(dispatcher), false);
| NetEase/pomelo-admin-web | public/front/HeapSnapshotWorker.js | JavaScript | mit | 2,031 | 44.133333 | 89 | 0.772526 | false |
//
// CVModel.h
// COLLADAViewer
//
#import <Foundation/Foundation.h>
@class CVMesh;
@interface CVModel : NSObject
@property (strong, nonatomic, readonly) CVMesh
*mesh;
@property (copy, nonatomic, readwrite) NSString
*name;
@property (copy, nonatomic, readonly) NSString
*axisAlignedBoundingBox;
@property (strong, nonatomic, readonly) NSNumber
*numberOfVertices;
@property (strong, nonatomic, readonly) NSDictionary
*plistRepresentation;
- (id)initWithName:(NSString *)aName
mesh:(CVMesh *)aMesh
indexOfFirstCommand:(NSUInteger)aFirstIndex
numberOfCommands:(NSUInteger)count;
- (id)initWithPlistRepresentation:(NSDictionary *)aDictionary
mesh:(CVMesh *)aMesh;
- (void)draw;
- (void)drawNormalsLength:(GLfloat)lineLength;
@end
| awalin/opengl-es-on-ios-examples | ch07_EXAMPLES/COLLADAViewer/COLLADAViewer/CVModel.h | C | mit | 764 | 22.151515 | 61 | 0.747382 | false |
/*!
* ui-grid - v4.8.1 - 2019-06-27
* Copyright (c) 2019 ; License: MIT
*/
.ui-grid {
border: 1px solid #d4d4d4;
box-sizing: content-box;
-webkit-border-radius: 0px;
-moz-border-radius: 0px;
border-radius: 0px;
-webkit-transform: translateZ(0);
-moz-transform: translateZ(0);
-o-transform: translateZ(0);
-ms-transform: translateZ(0);
transform: translateZ(0);
}
.ui-grid-vertical-bar {
position: absolute;
right: 0;
width: 0;
}
.ui-grid-header-cell:not(:last-child) .ui-grid-vertical-bar,
.ui-grid-cell:not(:last-child) .ui-grid-vertical-bar {
width: 1px;
}
.ui-grid-scrollbar-placeholder {
background-color: transparent;
}
.ui-grid-header-cell:not(:last-child) .ui-grid-vertical-bar {
background-color: #d4d4d4;
}
.ui-grid-cell:not(:last-child) .ui-grid-vertical-bar {
background-color: #d4d4d4;
}
.ui-grid-header-cell:last-child .ui-grid-vertical-bar {
right: -1px;
width: 1px;
background-color: #d4d4d4;
}
.ui-grid-clearfix:before,
.ui-grid-clearfix:after {
content: "";
display: table;
}
.ui-grid-clearfix:after {
clear: both;
}
.ui-grid-invisible {
visibility: hidden;
}
.ui-grid-contents-wrapper {
position: relative;
height: 100%;
width: 100%;
}
.ui-grid-sr-only {
position: absolute;
width: 1px;
height: 1px;
margin: -1px;
padding: 0;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0;
}
.ui-grid-icon-button {
background-color: transparent;
border: none;
padding: 0;
}
.clickable {
cursor: pointer;
}
.ui-grid-top-panel-background {
background-color: #f3f3f3;
}
.ui-grid-header {
border-bottom: 1px solid #d4d4d4;
box-sizing: border-box;
}
.ui-grid-top-panel {
position: relative;
overflow: hidden;
font-weight: bold;
background-color: #f3f3f3;
-webkit-border-top-right-radius: -1px;
-webkit-border-bottom-right-radius: 0;
-webkit-border-bottom-left-radius: 0;
-webkit-border-top-left-radius: -1px;
-moz-border-radius-topright: -1px;
-moz-border-radius-bottomright: 0;
-moz-border-radius-bottomleft: 0;
-moz-border-radius-topleft: -1px;
border-top-right-radius: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
border-top-left-radius: -1px;
-moz-background-clip: padding-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
}
.ui-grid-header-viewport {
overflow: hidden;
}
.ui-grid-header-canvas:before,
.ui-grid-header-canvas:after {
content: "";
display: -ms-flexbox;
display: flex;
line-height: 0;
}
.ui-grid-header-canvas:after {
clear: both;
}
.ui-grid-header-cell-wrapper {
position: relative;
display: -ms-flexbox;
display: flex;
box-sizing: border-box;
height: 100%;
width: 100%;
}
.ui-grid-header-cell-row {
display: -ms-flexbox;
display: flex;
-ms-flex-direction: row;
flex-direction: row;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
}
.ui-grid-header-cell {
position: relative;
box-sizing: border-box;
background-color: inherit;
border-right: 1px solid;
border-color: #d4d4d4;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
width: 0;
}
.ui-grid-header-cell:last-child {
border-right: 0;
}
.ui-grid-header-cell .sortable {
cursor: pointer;
}
.ui-grid-header-cell .ui-grid-sort-priority-number {
margin-left: -8px;
}
/* Fixes IE word-wrap if needed on header cells */
.ui-grid-header-cell > div {
-ms-flex-basis: 100%;
flex-basis: 100%;
}
.ui-grid-header .ui-grid-vertical-bar {
top: 0;
bottom: 0;
}
.ui-grid-column-menu-button {
position: absolute;
right: 1px;
top: 0;
}
.ui-grid-column-menu-button .ui-grid-icon-angle-down {
vertical-align: sub;
}
.ui-grid-header-cell-last-col .ui-grid-cell-contents,
.ui-grid-header-cell-last-col .ui-grid-filter-container,
.ui-grid-header-cell-last-col .ui-grid-column-menu-button,
.ui-grid-header-cell-last-col + .ui-grid-column-resizer.right {
margin-right: 13px;
}
.ui-grid-render-container-right .ui-grid-header-cell-last-col .ui-grid-cell-contents,
.ui-grid-render-container-right .ui-grid-header-cell-last-col .ui-grid-filter-container,
.ui-grid-render-container-right .ui-grid-header-cell-last-col .ui-grid-column-menu-button,
.ui-grid-render-container-right .ui-grid-header-cell-last-col + .ui-grid-column-resizer.right {
margin-right: 28px;
}
.ui-grid-column-menu {
position: absolute;
}
/* Slide up/down animations */
.ui-grid-column-menu .ui-grid-menu .ui-grid-menu-mid.ng-hide-add,
.ui-grid-column-menu .ui-grid-menu .ui-grid-menu-mid.ng-hide-remove {
-webkit-transition: all 0.04s linear;
-moz-transition: all 0.04s linear;
-o-transition: all 0.04s linear;
transition: all 0.04s linear;
display: block !important;
}
.ui-grid-column-menu .ui-grid-menu .ui-grid-menu-mid.ng-hide-add.ng-hide-add-active,
.ui-grid-column-menu .ui-grid-menu .ui-grid-menu-mid.ng-hide-remove {
-webkit-transform: translateY(-100%);
-moz-transform: translateY(-100%);
-o-transform: translateY(-100%);
-ms-transform: translateY(-100%);
transform: translateY(-100%);
}
.ui-grid-column-menu .ui-grid-menu .ui-grid-menu-mid.ng-hide-add,
.ui-grid-column-menu .ui-grid-menu .ui-grid-menu-mid.ng-hide-remove.ng-hide-remove-active {
-webkit-transform: translateY(0);
-moz-transform: translateY(0);
-o-transform: translateY(0);
-ms-transform: translateY(0);
transform: translateY(0);
}
/* Slide up/down animations */
.ui-grid-menu-button .ui-grid-menu .ui-grid-menu-mid.ng-hide-add,
.ui-grid-menu-button .ui-grid-menu .ui-grid-menu-mid.ng-hide-remove {
-webkit-transition: all 0.04s linear;
-moz-transition: all 0.04s linear;
-o-transition: all 0.04s linear;
transition: all 0.04s linear;
display: block !important;
}
.ui-grid-menu-button .ui-grid-menu .ui-grid-menu-mid.ng-hide-add.ng-hide-add-active,
.ui-grid-menu-button .ui-grid-menu .ui-grid-menu-mid.ng-hide-remove {
-webkit-transform: translateY(-100%);
-moz-transform: translateY(-100%);
-o-transform: translateY(-100%);
-ms-transform: translateY(-100%);
transform: translateY(-100%);
}
.ui-grid-menu-button .ui-grid-menu .ui-grid-menu-mid.ng-hide-add,
.ui-grid-menu-button .ui-grid-menu .ui-grid-menu-mid.ng-hide-remove.ng-hide-remove-active {
-webkit-transform: translateY(0);
-moz-transform: translateY(0);
-o-transform: translateY(0);
-ms-transform: translateY(0);
transform: translateY(0);
}
.ui-grid-filter-container {
padding: 4px 10px;
position: relative;
}
.ui-grid-filter-container .ui-grid-filter-button {
position: absolute;
top: 0;
bottom: 0;
right: 0;
}
.ui-grid-filter-container .ui-grid-filter-button [class^="ui-grid-icon"] {
position: absolute;
top: 50%;
line-height: 32px;
margin-top: -16px;
right: 10px;
opacity: 0.66;
}
.ui-grid-filter-container .ui-grid-filter-button [class^="ui-grid-icon"]:hover {
opacity: 1;
}
.ui-grid-filter-container .ui-grid-filter-button-select {
position: absolute;
top: 0;
bottom: 0;
right: 0;
}
.ui-grid-filter-container .ui-grid-filter-button-select [class^="ui-grid-icon"] {
position: absolute;
top: 50%;
line-height: 32px;
margin-top: -16px;
right: 0px;
opacity: 0.66;
}
.ui-grid-filter-container .ui-grid-filter-button-select [class^="ui-grid-icon"]:hover {
opacity: 1;
}
input[type="text"].ui-grid-filter-input {
box-sizing: border-box;
padding: 0 18px 0 0;
margin: 0;
width: 100%;
border: 1px solid #d4d4d4;
-webkit-border-top-right-radius: 0px;
-webkit-border-bottom-right-radius: 0;
-webkit-border-bottom-left-radius: 0;
-webkit-border-top-left-radius: 0;
-moz-border-radius-topright: 0px;
-moz-border-radius-bottomright: 0;
-moz-border-radius-bottomleft: 0;
-moz-border-radius-topleft: 0;
border-top-right-radius: 0px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
border-top-left-radius: 0;
-moz-background-clip: padding-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
}
input[type="text"].ui-grid-filter-input:hover {
border: 1px solid #d4d4d4;
}
select.ui-grid-filter-select {
padding: 0;
margin: 0;
border: 0;
width: 90%;
border: 1px solid #d4d4d4;
-webkit-border-top-right-radius: 0px;
-webkit-border-bottom-right-radius: 0;
-webkit-border-bottom-left-radius: 0;
-webkit-border-top-left-radius: 0;
-moz-border-radius-topright: 0px;
-moz-border-radius-bottomright: 0;
-moz-border-radius-bottomleft: 0;
-moz-border-radius-topleft: 0;
border-top-right-radius: 0px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
border-top-left-radius: 0;
-moz-background-clip: padding-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
}
select.ui-grid-filter-select:hover {
border: 1px solid #d4d4d4;
}
.ui-grid-filter-cancel-button-hidden select.ui-grid-filter-select {
width: 100%;
}
.ui-grid-render-container {
position: inherit;
-webkit-border-top-right-radius: 0;
-webkit-border-bottom-right-radius: 0px;
-webkit-border-bottom-left-radius: 0px;
-webkit-border-top-left-radius: 0;
-moz-border-radius-topright: 0;
-moz-border-radius-bottomright: 0px;
-moz-border-radius-bottomleft: 0px;
-moz-border-radius-topleft: 0;
border-top-right-radius: 0;
border-bottom-right-radius: 0px;
border-bottom-left-radius: 0px;
border-top-left-radius: 0;
-moz-background-clip: padding-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
}
.ui-grid-render-container:focus {
outline: none;
}
.ui-grid-viewport {
min-height: 20px;
position: relative;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
}
.ui-grid-viewport:focus {
outline: none !important;
}
.ui-grid-canvas {
position: relative;
padding-top: 1px;
}
.ui-grid-row {
clear: both;
}
.ui-grid-row:nth-child(odd) .ui-grid-cell {
background-color: #fdfdfd;
}
.ui-grid-row:nth-child(even) .ui-grid-cell {
background-color: #f3f3f3;
}
.ui-grid-row:last-child .ui-grid-cell {
border-bottom-color: #d4d4d4;
border-bottom-style: solid;
}
.ui-grid-row:hover > [ui-grid-row] > .ui-grid-cell:hover .ui-grid-cell,
.ui-grid-row:nth-child(odd):hover .ui-grid-cell,
.ui-grid-row:nth-child(even):hover .ui-grid-cell {
background-color: #d5eaee;
}
.ui-grid-no-row-overlay {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: 10%;
background-color: #f3f3f3;
-webkit-border-top-right-radius: 0px;
-webkit-border-bottom-right-radius: 0;
-webkit-border-bottom-left-radius: 0;
-webkit-border-top-left-radius: 0;
-moz-border-radius-topright: 0px;
-moz-border-radius-bottomright: 0;
-moz-border-radius-bottomleft: 0;
-moz-border-radius-topleft: 0;
border-top-right-radius: 0px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
border-top-left-radius: 0;
-moz-background-clip: padding-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #d4d4d4;
font-size: 2em;
text-align: center;
}
.ui-grid-no-row-overlay > * {
position: absolute;
display: table;
margin: auto 0;
width: 100%;
top: 0;
bottom: 0;
left: 0;
right: 0;
opacity: 0.66;
}
.ui-grid-cell {
overflow: hidden;
float: left;
background-color: inherit;
border-right: 1px solid;
border-color: #d4d4d4;
box-sizing: border-box;
}
.ui-grid-cell:last-child {
border-right: 0;
}
.ui-grid-cell-contents {
padding: 5px;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
white-space: nowrap;
-ms-text-overflow: ellipsis;
-o-text-overflow: ellipsis;
text-overflow: ellipsis;
overflow: hidden;
height: 100%;
}
.ui-grid-cell-contents-hidden {
visibility: hidden;
width: 0;
height: 0;
display: none;
}
.ui-grid-row .ui-grid-cell.ui-grid-row-header-cell {
background-color: #F0F0EE;
border-bottom: solid 1px #d4d4d4;
}
.ui-grid-cell-empty {
display: inline-block;
width: 10px;
height: 10px;
}
.ui-grid-footer-info {
padding: 5px 10px;
}
.ui-grid-footer-panel-background {
background-color: #f3f3f3;
}
.ui-grid-footer-panel {
position: relative;
border-bottom: 1px solid #d4d4d4;
border-top: 1px solid #d4d4d4;
overflow: hidden;
font-weight: bold;
background-color: #f3f3f3;
-webkit-border-top-right-radius: -1px;
-webkit-border-bottom-right-radius: 0;
-webkit-border-bottom-left-radius: 0;
-webkit-border-top-left-radius: -1px;
-moz-border-radius-topright: -1px;
-moz-border-radius-bottomright: 0;
-moz-border-radius-bottomleft: 0;
-moz-border-radius-topleft: -1px;
border-top-right-radius: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
border-top-left-radius: -1px;
-moz-background-clip: padding-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
}
.ui-grid-grid-footer {
float: left;
width: 100%;
}
.ui-grid-footer-viewport,
.ui-grid-footer-canvas {
display: flex;
flex: 1 1 auto;
height: 100%;
}
.ui-grid-footer-viewport {
overflow: hidden;
}
.ui-grid-footer-canvas {
position: relative;
}
.ui-grid-footer-canvas:before,
.ui-grid-footer-canvas:after {
content: "";
display: table;
line-height: 0;
}
.ui-grid-footer-canvas:after {
clear: both;
}
.ui-grid-footer-cell-wrapper {
position: relative;
display: table;
box-sizing: border-box;
height: 100%;
}
.ui-grid-footer-cell-row {
display: table-row;
}
.ui-grid-footer-cell {
overflow: hidden;
background-color: inherit;
border-right: 1px solid;
border-color: #d4d4d4;
box-sizing: border-box;
display: table-cell;
}
.ui-grid-footer-cell:last-child {
border-right: 0;
}
.ui-grid-menu-button {
z-index: 2;
position: absolute;
right: 0;
top: 0;
background: #f3f3f3;
border: 0;
border-left: 1px solid #d4d4d4;
border-bottom: 1px solid #d4d4d4;
cursor: pointer;
height: 32px;
font-weight: normal;
}
.ui-grid-menu-button .ui-grid-icon-container {
margin-top: 5px;
margin-left: 2px;
}
.ui-grid-menu-button .ui-grid-menu {
right: 0;
}
.ui-grid-menu-button .ui-grid-menu .ui-grid-menu-mid {
overflow: scroll;
}
.ui-grid-menu {
overflow: hidden;
max-width: 320px;
z-index: 2;
position: absolute;
right: 100%;
padding: 0 10px 20px 10px;
cursor: pointer;
box-sizing: border-box;
}
.ui-grid-menu-item {
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ui-grid-menu .ui-grid-menu-inner {
background: #fff;
border: 1px solid #d4d4d4;
position: relative;
white-space: nowrap;
-webkit-border-radius: 0px;
-moz-border-radius: 0px;
border-radius: 0px;
}
.ui-grid-menu .ui-grid-menu-inner ul {
margin: 0;
padding: 0;
list-style-type: none;
}
.ui-grid-menu .ui-grid-menu-inner ul li {
padding: 0;
}
.ui-grid-menu .ui-grid-menu-inner ul li .ui-grid-menu-item {
color: #000;
min-width: 100%;
padding: 8px;
text-align: left;
background: transparent;
border: none;
cursor: default;
}
.ui-grid-menu .ui-grid-menu-inner ul li button.ui-grid-menu-item {
cursor: pointer;
}
.ui-grid-menu .ui-grid-menu-inner ul li button.ui-grid-menu-item:hover,
.ui-grid-menu .ui-grid-menu-inner ul li button.ui-grid-menu-item:focus {
background-color: #b3c4c7;
}
.ui-grid-menu .ui-grid-menu-inner ul li button.ui-grid-menu-item.ui-grid-menu-item-active {
background-color: #9cb2b6;
}
.ui-grid-menu .ui-grid-menu-inner ul li:not(:last-child) > .ui-grid-menu-item {
border-bottom: 1px solid #d4d4d4;
}
.ui-grid-sortarrow {
right: 5px;
position: absolute;
width: 20px;
top: 0;
bottom: 0;
background-position: center;
}
.ui-grid-sortarrow.down {
-webkit-transform: rotate(180deg);
-moz-transform: rotate(180deg);
-o-transform: rotate(180deg);
-ms-transform: rotate(180deg);
transform: rotate(180deg);
}
@font-face {
font-family: 'ui-grid';
src: url('fonts/ui-grid.eot');
src: url('fonts/ui-grid.eot#iefix') format('embedded-opentype'), url('fonts/ui-grid.woff') format('woff'), url('fonts/ui-grid.ttf') format('truetype'), url('fonts/ui-grid.svg?#ui-grid') format('svg');
font-weight: normal;
font-style: normal;
}
/* Chrome hack: SVG is rendered more smooth in Windozze. 100% magic, uncomment if you need it. */
/* Note, that will break hinting! In other OS-es font will be not as sharp as it could be */
/*
@media screen and (-webkit-min-device-pixel-ratio:0) {
@font-face {
font-family: 'ui-grid';
src: url('@{font-path}ui-grid.svg?12312827#ui-grid') format('svg');
}
}
*/
[class^="ui-grid-icon"]:before,
[class*=" ui-grid-icon"]:before {
font-family: "ui-grid";
font-style: normal;
font-weight: normal;
speak: none;
display: inline-block;
text-decoration: inherit;
width: 1em;
margin-right: 0.2em;
text-align: center;
/* opacity: .8; */
/* For safety - reset parent styles, that can break glyph codes*/
font-variant: normal;
text-transform: none;
/* fix buttons height, for twitter bootstrap */
line-height: 1em;
/* Animation center compensation - margins should be symmetric */
/* remove if not needed */
margin-left: 0.2em;
/* you can be more comfortable with increased icons size */
/* font-size: 120%; */
/* Uncomment for 3D effect */
/* text-shadow: 1px 1px 1px rgba(127, 127, 127, 0.3); */
}
.ui-grid-icon-blank::before {
width: 1em;
content: ' ';
}
.ui-grid-icon-plus-squared:before {
content: '\c350';
}
.ui-grid-icon-minus-squared:before {
content: '\c351';
}
.ui-grid-icon-search:before {
content: '\c352';
}
.ui-grid-icon-cancel:before {
content: '\c353';
}
.ui-grid-icon-info-circled:before {
content: '\c354';
}
.ui-grid-icon-lock:before {
content: '\c355';
}
.ui-grid-icon-lock-open:before {
content: '\c356';
}
.ui-grid-icon-pencil:before {
content: '\c357';
}
.ui-grid-icon-down-dir:before {
content: '\c358';
}
.ui-grid-icon-up-dir:before {
content: '\c359';
}
.ui-grid-icon-left-dir:before {
content: '\c35a';
}
.ui-grid-icon-right-dir:before {
content: '\c35b';
}
.ui-grid-icon-left-open:before {
content: '\c35c';
}
.ui-grid-icon-right-open:before {
content: '\c35d';
}
.ui-grid-icon-angle-down:before {
content: '\c35e';
}
.ui-grid-icon-filter:before {
content: '\c35f';
}
.ui-grid-icon-sort-alt-up:before {
content: '\c360';
}
.ui-grid-icon-sort-alt-down:before {
content: '\c361';
}
.ui-grid-icon-ok:before {
content: '\c362';
}
.ui-grid-icon-menu:before {
content: '\c363';
}
.ui-grid-icon-indent-left:before {
content: '\e800';
}
.ui-grid-icon-indent-right:before {
content: '\e801';
}
.ui-grid-icon-spin5:before {
content: '\ea61';
}
/*
* RTL Styles
*/
.ui-grid[dir=rtl] .ui-grid-header-cell,
.ui-grid[dir=rtl] .ui-grid-footer-cell,
.ui-grid[dir=rtl] .ui-grid-cell {
float: right !important;
}
.ui-grid[dir=rtl] .ui-grid-column-menu-button {
position: absolute;
left: 1px;
top: 0;
right: inherit;
}
.ui-grid[dir=rtl] .ui-grid-cell:first-child,
.ui-grid[dir=rtl] .ui-grid-header-cell:first-child,
.ui-grid[dir=rtl] .ui-grid-footer-cell:first-child {
border-right: 0;
}
.ui-grid[dir=rtl] .ui-grid-cell:last-child,
.ui-grid[dir=rtl] .ui-grid-header-cell:last-child {
border-right: 1px solid #d4d4d4;
border-left: 0;
}
.ui-grid[dir=rtl] .ui-grid-header-cell:first-child .ui-grid-vertical-bar,
.ui-grid[dir=rtl] .ui-grid-footer-cell:first-child .ui-grid-vertical-bar,
.ui-grid[dir=rtl] .ui-grid-cell:first-child .ui-grid-vertical-bar {
width: 0;
}
.ui-grid[dir=rtl] .ui-grid-menu-button {
z-index: 2;
position: absolute;
left: 0;
right: auto;
background: #f3f3f3;
border: 1px solid #d4d4d4;
cursor: pointer;
min-height: 27px;
font-weight: normal;
}
.ui-grid[dir=rtl] .ui-grid-menu-button .ui-grid-menu {
left: 0;
right: auto;
}
.ui-grid[dir=rtl] .ui-grid-filter-container .ui-grid-filter-button {
right: initial;
left: 0;
}
.ui-grid[dir=rtl] .ui-grid-filter-container .ui-grid-filter-button [class^="ui-grid-icon"] {
right: initial;
left: 10px;
}
/*
Animation example, for spinners
*/
.ui-grid-animate-spin {
-moz-animation: ui-grid-spin 2s infinite linear;
-o-animation: ui-grid-spin 2s infinite linear;
-webkit-animation: ui-grid-spin 2s infinite linear;
animation: ui-grid-spin 2s infinite linear;
display: inline-block;
}
@-moz-keyframes ui-grid-spin {
0% {
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-moz-transform: rotate(359deg);
-o-transform: rotate(359deg);
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@-webkit-keyframes ui-grid-spin {
0% {
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-moz-transform: rotate(359deg);
-o-transform: rotate(359deg);
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@-o-keyframes ui-grid-spin {
0% {
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-moz-transform: rotate(359deg);
-o-transform: rotate(359deg);
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@-ms-keyframes ui-grid-spin {
0% {
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-moz-transform: rotate(359deg);
-o-transform: rotate(359deg);
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@keyframes ui-grid-spin {
0% {
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-moz-transform: rotate(359deg);
-o-transform: rotate(359deg);
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
.ui-grid-cell-focus {
outline: 0;
background-color: #b3c4c7;
}
.ui-grid-focuser {
position: absolute;
left: 0;
top: 0;
z-index: -1;
width: 100%;
height: 100%;
}
.ui-grid-focuser:focus {
border-color: #66afe9;
outline: 0;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);
}
.ui-grid-offscreen {
display: block;
position: absolute;
left: -10000px;
top: -10000px;
clip: rect(0px, 0px, 0px, 0px);
}
.ui-grid-cell input {
border-radius: inherit;
padding: 0;
width: 100%;
color: inherit;
height: auto;
font: inherit;
outline: none;
}
.ui-grid-cell input:focus {
color: inherit;
outline: none;
}
.ui-grid-cell input[type="checkbox"] {
margin: 9px 0 0 6px;
width: auto;
}
.ui-grid-cell input.ng-invalid {
border: 1px solid #fc8f8f;
}
.ui-grid-cell input.ng-valid {
border: 1px solid #d4d4d4;
}
.ui-grid-viewport .ui-grid-empty-base-layer-container {
position: absolute;
overflow: hidden;
pointer-events: none;
z-index: -1;
}
.expandableRow .ui-grid-row:nth-child(odd) .ui-grid-cell {
background-color: #fdfdfd;
}
.expandableRow .ui-grid-row:nth-child(even) .ui-grid-cell {
background-color: #f3f3f3;
}
.ui-grid-cell.ui-grid-disable-selection.ui-grid-row-header-cell {
pointer-events: none;
}
.ui-grid-expandable-buttons-cell i {
pointer-events: all;
}
.scrollFiller {
float: left;
border: 1px solid #d4d4d4;
}
.ui-grid-tree-header-row {
font-weight: bold !important;
}
.movingColumn {
position: absolute;
top: 0;
border: 1px solid #d4d4d4;
box-shadow: inset 0 0 14px rgba(0, 0, 0, 0.2);
}
.movingColumn .ui-grid-icon-angle-down {
display: none;
}
/* This file contains variable declarations (do not remove this line) */
/*-- VARIABLES (DO NOT REMOVE THESE COMMENTS) --*/
/**
* @section Grid styles
*/
/**
* @section Header styles
*/
/** @description Colors for header gradient */
/**
* @section Grid body styles
*/
/** @description Colors used for row alternation */
/**
* @section Grid Menu colors
*/
/**
* @section Sort arrow colors
*/
/**
* @section Scrollbar styles
*/
/**
* @section font library path
*/
/*-- END VARIABLES (DO NOT REMOVE THESE COMMENTS) --*/
/*---------------------------------------------------
LESS Elements 0.9
---------------------------------------------------
A set of useful LESS mixins
More info at: http://lesselements.com
---------------------------------------------------*/
.ui-grid-pager-panel {
display: flex;
justify-content: space-between;
align-items: center;
position: absolute;
left: 0;
bottom: 0;
width: 100%;
padding-top: 3px;
padding-bottom: 3px;
box-sizing: content-box;
}
.ui-grid-pager-container {
float: left;
}
.ui-grid-pager-control {
padding: 5px 0;
display: flex;
flex-flow: row nowrap;
align-items: center;
margin-right: 10px;
margin-left: 10px;
min-width: 135px;
float: left;
}
.ui-grid-pager-control button,
.ui-grid-pager-control span,
.ui-grid-pager-control input {
margin-right: 4px;
}
.ui-grid-pager-control button {
height: 25px;
min-width: 26px;
display: inline-block;
margin-bottom: 0;
font-weight: normal;
text-align: center;
vertical-align: middle;
touch-action: manipulation;
cursor: pointer;
background: #f3f3f3;
border: 1px solid #ccc;
white-space: nowrap;
padding: 6px 12px;
font-size: 14px;
line-height: 1.42857143;
border-radius: 4px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
color: #eee;
}
.ui-grid-pager-control button:hover {
border-color: #adadad;
text-decoration: none;
}
.ui-grid-pager-control button:focus {
border-color: #8c8c8c;
text-decoration: none;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
.ui-grid-pager-control button:active {
border-color: #adadad;
outline: 0;
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
}
.ui-grid-pager-control button:active:focus {
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
.ui-grid-pager-control button:active:hover,
.ui-grid-pager-control button:active:focus {
background-color: #c8c8c8;
border-color: #8c8c8c;
}
.ui-grid-pager-control button:hover,
.ui-grid-pager-control button:focus,
.ui-grid-pager-control button:active {
color: #eee;
background: #dadada;
}
.ui-grid-pager-control button[disabled] {
cursor: not-allowed;
opacity: 0.65;
filter: alpha(opacity=65);
-webkit-box-shadow: none;
box-shadow: none;
}
.ui-grid-pager-control button[disabled]:hover,
.ui-grid-pager-control button[disabled]:focus {
background-color: #f3f3f3;
border-color: #ccc;
}
.ui-grid-pager-control input {
display: inline;
height: 26px;
width: 50px;
vertical-align: top;
color: #555555;
background: #fff;
border: 1px solid #ccc;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
-o-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
.ui-grid-pager-control input:focus {
border-color: #66afe9;
outline: 0;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);
}
.ui-grid-pager-control input[disabled],
.ui-grid-pager-control input[readonly],
.ui-grid-pager-control input::-moz-placeholder {
opacity: 1;
}
.ui-grid-pager-control input::-moz-placeholder,
.ui-grid-pager-control input:-ms-input-placeholder,
.ui-grid-pager-control input::-webkit-input-placeholder {
color: #999;
}
.ui-grid-pager-control input::-ms-expand {
border: 0;
background-color: transparent;
}
.ui-grid-pager-control input[disabled],
.ui-grid-pager-control input[readonly] {
background-color: #eeeeee;
}
.ui-grid-pager-control input[disabled] {
cursor: not-allowed;
}
.ui-grid-pager-control .ui-grid-pager-max-pages-number {
vertical-align: bottom;
}
.ui-grid-pager-control .ui-grid-pager-max-pages-number > * {
vertical-align: bottom;
}
.ui-grid-pager-control .ui-grid-pager-max-pages-number abbr {
border-bottom: none;
text-decoration: none;
}
.ui-grid-pager-control .first-bar {
width: 10px;
border-left: 2px solid #4d4d4d;
margin-top: -6px;
height: 12px;
margin-left: -3px;
}
.ui-grid-pager-control .first-bar-rtl {
width: 10px;
border-left: 2px solid #4d4d4d;
margin-top: -6px;
height: 12px;
margin-right: -7px;
}
.ui-grid-pager-control .first-triangle {
width: 0;
height: 0;
border-style: solid;
border-width: 5px 8.7px 5px 0;
border-color: transparent #4d4d4d transparent transparent;
margin-left: 2px;
}
.ui-grid-pager-control .next-triangle {
margin-left: 1px;
}
.ui-grid-pager-control .prev-triangle {
margin-left: 0;
}
.ui-grid-pager-control .last-triangle {
width: 0;
height: 0;
border-style: solid;
border-width: 5px 0 5px 8.7px;
border-color: transparent transparent transparent #4d4d4d;
margin-left: -1px;
}
.ui-grid-pager-control .last-bar {
width: 10px;
border-left: 2px solid #4d4d4d;
margin-top: -6px;
height: 12px;
margin-left: 1px;
}
.ui-grid-pager-control .last-bar-rtl {
width: 10px;
border-left: 2px solid #4d4d4d;
margin-top: -6px;
height: 12px;
margin-right: -11px;
}
.ui-grid-pager-row-count-picker {
float: left;
padding: 5px 10px;
}
.ui-grid-pager-row-count-picker select {
color: #555555;
background: #fff;
border: 1px solid #ccc;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
-o-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
height: 25px;
width: 67px;
display: inline;
vertical-align: middle;
}
.ui-grid-pager-row-count-picker select:focus {
border-color: #66afe9;
outline: 0;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);
}
.ui-grid-pager-row-count-picker select[disabled],
.ui-grid-pager-row-count-picker select[readonly],
.ui-grid-pager-row-count-picker select::-moz-placeholder {
opacity: 1;
}
.ui-grid-pager-row-count-picker select::-moz-placeholder,
.ui-grid-pager-row-count-picker select:-ms-input-placeholder,
.ui-grid-pager-row-count-picker select::-webkit-input-placeholder {
color: #999;
}
.ui-grid-pager-row-count-picker select::-ms-expand {
border: 0;
background-color: transparent;
}
.ui-grid-pager-row-count-picker select[disabled],
.ui-grid-pager-row-count-picker select[readonly] {
background-color: #eeeeee;
}
.ui-grid-pager-row-count-picker select[disabled] {
cursor: not-allowed;
}
.ui-grid-pager-row-count-picker .ui-grid-pager-row-count-label {
margin-top: 3px;
}
.ui-grid-pager-count-container {
float: right;
margin-top: 4px;
min-width: 50px;
}
.ui-grid-pager-count-container .ui-grid-pager-count {
margin-right: 10px;
margin-left: 10px;
float: right;
}
.ui-grid-pager-count-container .ui-grid-pager-count abbr {
border-bottom: none;
text-decoration: none;
}
.ui-grid-pinned-container {
position: absolute;
display: inline;
top: 0;
}
.ui-grid-pinned-container.ui-grid-pinned-container-left {
float: left;
left: 0;
}
.ui-grid-pinned-container.ui-grid-pinned-container-right {
float: right;
right: 0;
}
.ui-grid-pinned-container.ui-grid-pinned-container-left .ui-grid-header-cell:last-child {
box-sizing: border-box;
border-right: 1px solid;
border-width: 1px;
border-right-color: #aeaeae;
}
.ui-grid-pinned-container.ui-grid-pinned-container-left .ui-grid-cell:last-child {
box-sizing: border-box;
border-right: 1px solid;
border-width: 1px;
border-right-color: #aeaeae;
}
.ui-grid-pinned-container.ui-grid-pinned-container-left .ui-grid-header-cell:not(:last-child) .ui-grid-vertical-bar,
.ui-grid-pinned-container .ui-grid-cell:not(:last-child) .ui-grid-vertical-bar {
width: 1px;
}
.ui-grid-pinned-container.ui-grid-pinned-container-left .ui-grid-header-cell:not(:last-child) .ui-grid-vertical-bar {
background-color: #d4d4d4;
}
.ui-grid-pinned-container.ui-grid-pinned-container-left .ui-grid-cell:not(:last-child) .ui-grid-vertical-bar {
background-color: #aeaeae;
}
.ui-grid-pinned-container.ui-grid-pinned-container-left .ui-grid-header-cell:last-child .ui-grid-vertical-bar {
right: -1px;
width: 1px;
background-color: #aeaeae;
}
.ui-grid-pinned-container.ui-grid-pinned-container-right .ui-grid-header-cell:first-child {
box-sizing: border-box;
border-left: 1px solid;
border-width: 1px;
border-left-color: #aeaeae;
}
.ui-grid-pinned-container.ui-grid-pinned-container-right .ui-grid-cell:first-child {
box-sizing: border-box;
border-left: 1px solid;
border-width: 1px;
border-left-color: #aeaeae;
}
.ui-grid-pinned-container.ui-grid-pinned-container-right .ui-grid-header-cell:not(:first-child) .ui-grid-vertical-bar,
.ui-grid-pinned-container .ui-grid-cell:not(:first-child) .ui-grid-vertical-bar {
width: 1px;
}
.ui-grid-pinned-container.ui-grid-pinned-container-right .ui-grid-header-cell:not(:first-child) .ui-grid-vertical-bar {
background-color: #d4d4d4;
}
.ui-grid-pinned-container.ui-grid-pinned-container-right .ui-grid-cell:not(:last-child) .ui-grid-vertical-bar {
background-color: #aeaeae;
}
.ui-grid-pinned-container.ui-grid-pinned-container-first .ui-grid-header-cell:first-child .ui-grid-vertical-bar {
left: -1px;
width: 1px;
background-color: #aeaeae;
}
.ui-grid-column-resizer {
top: 0;
bottom: 0;
width: 5px;
position: absolute;
cursor: col-resize;
}
.ui-grid-column-resizer.left {
left: 0;
}
.ui-grid-column-resizer.right {
right: 0;
}
.ui-grid-header-cell:last-child .ui-grid-column-resizer.right {
border-right: 1px solid #d4d4d4;
}
.ui-grid[dir=rtl] .ui-grid-header-cell:last-child .ui-grid-column-resizer.right {
border-right: 0;
}
.ui-grid[dir=rtl] .ui-grid-header-cell:last-child .ui-grid-column-resizer.left {
border-left: 1px solid #d4d4d4;
}
.ui-grid.column-resizing {
cursor: col-resize;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.ui-grid.column-resizing .ui-grid-resize-overlay {
position: absolute;
top: 0;
height: 100%;
width: 1px;
background-color: #aeaeae;
}
.ui-grid-row-saving .ui-grid-cell {
color: #848484 !important;
}
.ui-grid-row-dirty .ui-grid-cell {
color: #610B38;
}
.ui-grid-row-error .ui-grid-cell {
color: #FF0000 !important;
}
.ui-grid-row.ui-grid-row-selected > [ui-grid-row] > .ui-grid-cell {
background-color: #C9DDE1;
}
.ui-grid-disable-selection {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
cursor: default;
}
.ui-grid-selection-row-header-buttons {
display: flex;
align-items: center;
height: 100%;
cursor: pointer;
}
.ui-grid-selection-row-header-buttons::before {
opacity: 0.1;
}
.ui-grid-selection-row-header-buttons.ui-grid-row-selected::before,
.ui-grid-selection-row-header-buttons.ui-grid-all-selected::before {
opacity: 1;
}
.ui-grid-tree-row-header-buttons.ui-grid-tree-header {
cursor: pointer;
opacity: 1;
}
.ui-grid-tree-header-row {
font-weight: bold !important;
}
.ui-grid-tree-header-row .ui-grid-cell.ui-grid-disable-selection.ui-grid-row-header-cell {
pointer-events: all;
}
.ui-grid-cell-contents.invalid {
border: 1px solid #fc8f8f;
}
| extend1994/cdnjs | ajax/libs/angular-ui-grid/4.8.1/ui-grid.css | CSS | mit | 35,855 | 24.339223 | 202 | 0.682053 | false |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>value_ref</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.JSON">
<link rel="up" href="../ref.html" title="This Page Intentionally Left Blank 2/2">
<link rel="prev" href="boost__json__value_from_tag.html" title="value_from_tag">
<link rel="next" href="boost__json__value_ref/value_ref.html" title="value_ref::value_ref">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="boost__json__value_from_tag.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../ref.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="boost__json__value_ref/value_ref.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="json.ref.boost__json__value_ref"></a><a class="link" href="boost__json__value_ref.html" title="value_ref">value_ref</a>
</h4></div></div></div>
<p>
The type used in initializer lists.
</p>
<h5>
<a name="json.ref.boost__json__value_ref.h0"></a>
<span class="phrase"><a name="json.ref.boost__json__value_ref.synopsis"></a></span><a class="link" href="boost__json__value_ref.html#json.ref.boost__json__value_ref.synopsis">Synopsis</a>
</h5>
<p>
Defined in header <code class="literal"><<a href="https://github.com/cppalliance/json/blob/master/include/boost/json/value_ref.hpp" target="_top">boost/json/value_ref.hpp</a>></code>
</p>
<pre class="programlisting"><span class="keyword">class</span> <span class="identifier">value_ref</span>
</pre>
<h5>
<a name="json.ref.boost__json__value_ref.h1"></a>
<span class="phrase"><a name="json.ref.boost__json__value_ref.member_functions"></a></span><a class="link" href="boost__json__value_ref.html#json.ref.boost__json__value_ref.member_functions">Member
Functions</a>
</h5>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Name
</p>
</th>
<th>
<p>
Description
</p>
</th>
</tr></thead>
<tbody><tr>
<td>
<p>
<span class="bold"><strong><a class="link" href="boost__json__value_ref/value_ref.html" title="value_ref::value_ref">value_ref</a> <span class="silver">[constructor]</span></strong></span>
</p>
</td>
<td>
<p>
Constructor.
</p>
</td>
</tr></tbody>
</table></div>
<h5>
<a name="json.ref.boost__json__value_ref.h2"></a>
<span class="phrase"><a name="json.ref.boost__json__value_ref.description"></a></span><a class="link" href="boost__json__value_ref.html#json.ref.boost__json__value_ref.description">Description</a>
</h5>
<p>
This type is used in initializer lists for lazy construction of and assignment
to the container types <a class="link" href="boost__json__value.html" title="value"><code class="computeroutput"><span class="identifier">value</span></code></a>, <a class="link" href="boost__json__array.html" title="array"><code class="computeroutput"><span class="identifier">array</span></code></a>, and <a class="link" href="boost__json__object.html" title="object"><code class="computeroutput"><span class="identifier">object</span></code></a>. The two types of initializer
lists used are:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
<code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">initializer_list</span><span class="special"><</span>
<span class="identifier">value_ref</span> <span class="special">></span></code>
for constructing or assigning a <a class="link" href="boost__json__value.html" title="value"><code class="computeroutput"><span class="identifier">value</span></code></a> or <a class="link" href="boost__json__array.html" title="array"><code class="computeroutput"><span class="identifier">array</span></code></a>, and
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">initializer_list</span><span class="special"><</span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span>
<span class="identifier">string_view</span><span class="special">,</span>
<span class="identifier">value_ref</span> <span class="special">></span>
<span class="special">></span></code> for constructing or assigning
an <a class="link" href="boost__json__object.html" title="object"><code class="computeroutput"><span class="identifier">object</span></code></a>.
</li>
</ul></div>
<p>
A <code class="computeroutput"><span class="identifier">value_ref</span></code> uses reference
semantics. Creation of the actual container from the initializer list is
lazily deferred until the list is used. This means that the <a class="link" href="boost__json__memory_resource.html" title="memory_resource"><code class="computeroutput"><span class="identifier">memory_resource</span></code></a> used to construct
a container can be specified after the point where the initializer list is
specified.
</p>
<h5>
<a name="json.ref.boost__json__value_ref.h3"></a>
<span class="phrase"><a name="json.ref.boost__json__value_ref.example"></a></span><a class="link" href="boost__json__value_ref.html#json.ref.boost__json__value_ref.example">Example</a>
</h5>
<p>
This example demonstrates how a user-defined type containing a JSON value
can be constructed from an initializer list:
</p>
<pre class="programlisting"><span class="keyword">class</span> <span class="identifier">my_type</span>
<span class="special">{</span>
<span class="identifier">value</span> <span class="identifier">jv_</span><span class="special">;</span>
<span class="keyword">public</span><span class="special">:</span>
<span class="identifier">my_type</span><span class="special">(</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">initializer_list</span><span class="special"><</span> <span class="identifier">value_ref</span> <span class="special">></span> <span class="identifier">init</span> <span class="special">)</span>
<span class="special">:</span> <span class="identifier">jv_</span><span class="special">(</span><span class="identifier">init</span><span class="special">)</span>
<span class="special">{</span>
<span class="special">}</span>
<span class="special">};</span>
</pre>
<h5>
<a name="json.ref.boost__json__value_ref.h4"></a>
<span class="phrase"><a name="json.ref.boost__json__value_ref.remarks"></a></span><a class="link" href="boost__json__value_ref.html#json.ref.boost__json__value_ref.remarks">Remarks</a>
</h5>
<p>
Never declare a variable of type <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">initializer_list</span></code>
except in function parameter lists, otherwise the behavior may be undefined.
</p>
<h5>
<a name="json.ref.boost__json__value_ref.h5"></a>
<span class="phrase"><a name="json.ref.boost__json__value_ref.see_also"></a></span><a class="link" href="boost__json__value_ref.html#json.ref.boost__json__value_ref.see_also">See
Also</a>
</h5>
<p>
<a class="link" href="boost__json__value.html" title="value"><code class="computeroutput"><span class="identifier">value</span></code></a>,
<a class="link" href="boost__json__array.html" title="array"><code class="computeroutput"><span class="identifier">array</span></code></a>,
<a class="link" href="boost__json__object.html" title="object"><code class="computeroutput"><span class="identifier">object</span></code></a>
</p>
<p>
Convenience header <code class="literal"><<a href="https://github.com/cppalliance/json/blob/master/include/boost/json.hpp" target="_top">boost/json.hpp</a>></code>
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2019, 2020 Vinnie Falco<br>Copyright © 2020 Krystian Stasiowski<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="boost__json__value_from_tag.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../ref.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="boost__json__value_ref/value_ref.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| davehorton/drachtio-server | deps/boost_1_77_0/libs/json/doc/html/json/ref/boost__json__value_ref.html | HTML | mit | 10,474 | 64.024845 | 486 | 0.630719 | false |
package magick
// #include <magick/api.h>
import "C"
// When encoding an output image, the colorspaces RGB, CMYK, and GRAY
// may be specified. The CMYK option is only applicable when writing
// TIFF, JPEG, and Adobe Photoshop bitmap (PSD) files.
type Colorspace C.ColorspaceType
const (
RGB Colorspace = C.RGBColorspace // Red, Green, Blue colorspace.
GRAY Colorspace = C.GRAYColorspace // Similar to Luma (Y) according to ITU-R 601
TRANSPARENT Colorspace = C.TransparentColorspace // RGB which preserves the matte while quantizing colors.
OHTA Colorspace = C.OHTAColorspace
XYZ Colorspace = C.XYZColorspace // CIE XYZ
YCC Colorspace = C.YCCColorspace // Kodak PhotoCD PhotoYCC
YIQ Colorspace = C.YIQColorspace
YPBPR Colorspace = C.YPbPrColorspace
YUV Colorspace = C.YUVColorspace // YUV colorspace as used for computer video.
CMYK Colorspace = C.CMYKColorspace // Cyan, Magenta, Yellow, Black colorspace.
SRGB Colorspace = C.sRGBColorspace // Kodak PhotoCD sRGB
HSL Colorspace = C.HSLColorspace // Hue, saturation, luminosity
HWB Colorspace = C.HWBColorspace // Hue, whiteness, blackness
LAB Colorspace = C.LABColorspace // ITU LAB
REC_601_LUMA Colorspace = C.Rec601LumaColorspace // Luma (Y) according to ITU-R 601
REC_601_YCBCR Colorspace = C.Rec601YCbCrColorspace // YCbCr according to ITU-R 601
REC_709_LUMA Colorspace = C.Rec709LumaColorspace // Luma (Y) according to ITU-R 709
REC_709_YCBCR Colorspace = C.Rec709YCbCrColorspace // YCbCr according to ITU-R 709
)
// Colorspace returns the image colorspace.
func (im *Image) Colorspace() Colorspace {
return Colorspace(im.image.colorspace)
}
// SetColorspace changes the image colorspace. Note
// that this only changes how the pixels are interpreted.
// If you want to transform the image to another colorspace
// use TransformColorspace().
func (im *Image) SetColorspace(cs Colorspace) {
im.image.colorspace = C.ColorspaceType(cs)
}
// TransformColorspace returns a new image by covnerting the original to
// the given colorspace while also changing the pixels to represent the
// same image in the new colorspace.
func (im *Image) TransformColorspace(cs Colorspace) (*Image, error) {
clone, err := im.Clone()
if err != nil {
return nil, err
}
if err := clone.ToColorspace(cs); err != nil {
return nil, err
}
return clone, nil
}
// ToColorspace changes the image colorspace in place.
func (im *Image) ToColorspace(cs Colorspace) error {
_, err := im.transformColorspace(cs)
return err
}
| zuriu/magick | colorspace.go | GO | mit | 2,675 | 41.460317 | 109 | 0.700561 | false |
# Fixes
* [wpmlst-1503] Fixed issue with strings not getting imported from .mo files when their value was the same but the context was different
* [wpmlst-1498] Resolved exception with WPDb errors when two identical Widget titles existed
* [wpmlst-1496] Fixed themes string counters in Theme Plugin Localization screen
* [wpmlst-1334] Increased the allowed string size in the database (from text to longtext)
* [wpmlst-1257] Fixed initialization priority in String Translation for better compatibility with third party plugins and themes | mandino/hotelmilosantabarbara.com | wp-content/plugins/wpml-string-translation/changelog/2.6.2.md | Markdown | mit | 537 | 88.666667 | 136 | 0.808194 | false |
<div class="doc-content">
<header class="api-profile-header" >
<h2 class="md-display-1" >{{currentDoc.name}} API Documentation</h2>
</header>
<div layout="row" class="api-options-bar with-icon"></div>
<div class="api-profile-description">
<p>The <code><md-content></code> directive is a container element useful for scrollable content. It achieves
this by setting the CSS <code>overflow</code> property to <code>auto</code> so that content can properly scroll.</p>
<p>In general, <code><md-content></code> components are not designed to be nested inside one another. If
possible, it is better to make them siblings. This often results in a better user experience as
having nested scrollbars may confuse the user.</p>
<h2 id="troubleshooting">Troubleshooting</h2>
<p>In some cases, you may wish to apply the <code>md-no-momentum</code> class to ensure that Safari's
momentum scrolling is disabled. Momentum scrolling can cause flickering issues while scrolling
SVG icons and some other components.</p>
</div>
<div>
<section class="api-section">
<h2 id="Usage">Usage</h2>
<p>Add the <code>[layout-padding]</code> attribute to make the content padded.</p>
<hljs lang="html">
<md-content layout-padding>
Lorem ipsum dolor sit amet, ne quod novum mei.
</md-content>
</hljs>
</section>
</div>
</div>
| angular/code.material.angularjs.org | 1.1.0-rc4/partials/api/material.components.content/directive/mdContent.html | HTML | mit | 1,377 | 24.5 | 116 | 0.707335 | false |
/**
* Module dependencies
*/
var _ = require('lodash');
var util = require('util');
var factory = require('./factory');
var normalize = require('./normalize');
var redirect = require('./redirect');
var wildcard = require('./wildcard');
var constants = require('./constants');
/**
* `switchback`
*
* Switching utility which builds and returns a handler which is capable
* calling one of several callbacks.
*
* @param {Object|Function} callback
* - a switchback definition obj or a standard 1|2-ary node callback function.
* @param {Object} [defaultHandlers]
* - '*': supply a special callback for when none of the other handlers match
* - a string can be supplied, e.g. {'invalid': 'error'}, to "forward" one handler to another
* - otherwise a function should be supplied, e.g. { 'error': res.serverError }
* @param {Object} [callbackContext]
* - optional `this` context for callbacks
*/
var switchback = function ( callback, defaultHandlers, callbackContext ) {
var Switchback = factory(callbackContext);
// Normalize `callback` to a switchback definition object.
callback = normalize.callback(callback);
// Attach specified handlers
_.extend(Switchback, callback);
// Supply a handful of default handlers to provide better error messages.
var getWildcardCaseHandler = function ( caseName, err ) {
return function unknownCase ( /* ... */ ) {
var args = Array.prototype.slice.call(arguments);
err = (args[0] ? util.inspect(args[0])+' ' : '') + (err ? '('+(err||'')+')' : '');
if ( _.isObject(defaultHandlers) && _.isFunction(defaultHandlers['*']) ) {
return defaultHandlers['*'](err);
}
else throw new Error(err);
};
};
// redirect any handler defaults specified as strings
if (_.isObject(defaultHandlers)) {
defaultHandlers = _.mapValues(defaultHandlers, function (handler, name) {
if (_.isFunction(handler)) return handler;
// Closure which will resolve redirected handler
return function () {
var runtimeHandler = handler;
var runtimeArgs = Array.prototype.slice.call(arguments);
var runtimeCtx = callbackContext || this;
// Track previous handler to make usage error messages more useful.
var prevHandler;
// No more than 5 "redirects" allowed (prevents never-ending loop)
var MAX_FORWARDS = 5;
var numIterations = 0;
do {
prevHandler = runtimeHandler;
runtimeHandler = Switchback[runtimeHandler];
// console.log('redirecting '+name+' to "'+prevHandler +'"-- got ' + runtimeHandler);
numIterations++;
}
while ( _.isString(runtimeHandler) && numIterations <= MAX_FORWARDS);
if (numIterations > MAX_FORWARDS) {
throw new Error('Default handlers object ('+util.inspect(defaultHandlers)+') has a cyclic redirect.');
}
// Redirects to unknown handler
if (!_.isFunction(runtimeHandler)) {
runtimeHandler = getWildcardCaseHandler(runtimeHandler, '`' + name + '` case triggered, but no handler was implemented.');
}
// Invoke final runtime function
runtimeHandler.apply(runtimeCtx, runtimeArgs);
};
});
}
_.defaults(Switchback, defaultHandlers, {
success: getWildcardCaseHandler('success', '`success` case triggered, but no handler was implemented.'),
error: getWildcardCaseHandler('error', '`error` case triggered, but no handler was implemented.'),
invalid: getWildcardCaseHandler('invalid', '`invalid` case triggered, but no handler was implemented.')
});
return Switchback;
};
/**
* `isSwitchback`
*
* @param {*} something
* @return {Boolean} [whether `something` is a valid switchback instance]
*/
switchback.isSwitchback = function (something) {
return _.isObject(something) && something[constants.telltale.key] === constants.telltale.value;
};
module.exports = switchback;
| rasata/Iphone-Powered | node_modules/sails/node_modules/sails-util/node_modules/node-switchback/lib/index.js | JavaScript | mit | 3,815 | 32.173913 | 127 | 0.682569 | false |
This is a command plug-in for notifying/“pinging” web services of
new posts and pages on your live site.
**Warning:** Only run this command when there is actually new content on the
production site. Excessive or “false” pings when there are no
updates will get the site blacklisted with the ping services.
### Usage:
nikola ping
| getnikola/plugins | v7/ping/README.md | Markdown | mit | 344 | 32.6 | 76 | 0.761905 | false |
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
/**
* Copyright (c) 2014,Egret-Labs.org
* 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 the Egret-Labs.org 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 EGRET-LABS.ORG 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 EGRET-LABS.ORG AND 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.
*/
var egret;
(function (egret) {
var ProgressEvent = (function (_super) {
__extends(ProgressEvent, _super);
/**
* @method egret.ProgressEvent#constructor
* @param type {string}
* @param bubbles {boolean}
* @param cancelable {boolean}
* @param bytesLoaded {number}
* @param bytesTotal {number}
*/
function ProgressEvent(type, bubbles, cancelable, bytesLoaded, bytesTotal) {
if (bubbles === void 0) { bubbles = false; }
if (cancelable === void 0) { cancelable = false; }
if (bytesLoaded === void 0) { bytesLoaded = 0; }
if (bytesTotal === void 0) { bytesTotal = 0; }
_super.call(this, type, bubbles, cancelable);
this.bytesLoaded = bytesLoaded;
this.bytesTotal = bytesTotal;
}
/**
* 使用指定的EventDispatcher对象来抛出Event事件对象。抛出的对象将会缓存在对象池上,供下次循环复用。
* @method egret.ProgressEvent.dispatchIOErrorEvent
* @param target {egret.IEventDispatcher}
*/
ProgressEvent.dispatchProgressEvent = function (target, type, bytesLoaded, bytesTotal) {
if (bytesLoaded === void 0) { bytesLoaded = 0; }
if (bytesTotal === void 0) { bytesTotal = 0; }
egret.Event._dispatchByTarget(ProgressEvent, target, type, { "bytesLoaded": bytesLoaded, "bytesTotal": bytesTotal });
};
/**
* @constant {string} egret.ProgressEvent.PROGRESS
*/
ProgressEvent.PROGRESS = "progress";
/**
* @constant {string} egret.ProgressEvent.SOCKET_DATA
*/
ProgressEvent.SOCKET_DATA = "socketData";
return ProgressEvent;
})(egret.Event);
egret.ProgressEvent = ProgressEvent;
ProgressEvent.prototype.__class__ = "egret.ProgressEvent";
})(egret || (egret = {}));
| sunzhaoping/fastmsg | snowpear/libs/core/egret/events/ProgressEvent.js | JavaScript | mit | 3,742 | 47.236842 | 129 | 0.654119 | false |
<table class="table table-striped table-bordered table-hover table-condensed DataTable">
<thead>
<th>Name</th>
<th class="hidden-xs">Email</th>
<th class="hidden-xs">Skype</th>
<th class="hidden-xs">Mobile Number</th>
<th>
<span class="hidden-xs">date of interview</span>
<span class="visible-xs-block"><i class="glyphicon-calendar glyphicon"></i></span>
</th>
<th style="min-width:115px;"></th>
</thead>
<?php $output = $page_protect->get_applicant_list(NULL);
$resume_icon='';
for($x=0;$x!=$output['count'][0];$x++){
if($output[$x]['resume'] =='') {
$resume_icon='';
}
else {
$resume_icon='<a href="../'.$output[$x]['resume'].'" class="btn btn-xs btn-info"><i class="glyphicon-cloud-download glyphicon"></i></a>';
}
echo'
<tr>
<td>'.$output[$x]['last_name'].' '.$output[$x]['first_name'].'</td>
<td class="hidden-xs">'.$output[$x]['email'].'</td>
<td class="hidden-xs">'.$output[$x]['skype'].'</td>
<td class="hidden-xs">'.$output[$x]['mobile'].'</td>
<td>'.$output[$x]['interviewdate'].'</td>
<td>
<a href="#myModalViewAccount'. $output[$x]['applicant_id'].'" class="btn btn-xs btn-info" data-toggle="modal" data-backdrop="static"><i class="glyphicon-search glyphicon"></i></a>
<a href="#myModalViewBookings'. $output[$x]['applicant_id'].'" class="btn btn-xs btn-info" data-toggle="modal" data-backdrop="static"><i class="glyphicon-calendar glyphicon"></i></a>
<a href="applicant_profile.php?AppId='.$output[$x]['applicant_id'].'&t=3A" class="btn btn-xs btn-info" data-toggle="modal" data-backdrop="static"><i class="glyphicon-edit glyphicon"></i></a>
'.$resume_icon.'
<a href="#myModalDeleteAccount'. $output[$x]['applicant_id'].'" class="btn btn-xs btn-info" data-toggle="modal" data-backdrop="static"><i class="glyphicon-trash glyphicon"></i></a>
</td>
</tr>
<div id="myModalViewAccount'. $output[$x]['applicant_id'].'" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 id="myModalLabel">'. $output[$x]['first_name'].' '.$output[$x]['last_name'].'</h4>
</div>
<div class="modal-body">
<p style="vertical-align:top;">Email: '.$output[$x]['email'].'
</p>
<p style="vertical-align:top;">Skype ID: '.$output[$x]['skype'].'
</p>
</div>
<div class="modal-footer">
<a href="applicant_profile.php?AppId='.$output[$x]['applicant_id'].'&t=3A" ><button class="btn">View</button></a>
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</div>
</div>
</div>
<div id="myModalViewBookings'. $output[$x]['applicant_id'].'" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 id="myModalLabel">'. $output[$x]['first_name'].' '.$output[$x]['last_name'].'</h4>
</div>
<div class="modal-body">
<h4>Schedule Applicant for training:</h4>'.$output[$x]['training_date'].'
<form action="'.$_SERVER['PHP_SELF'].'?t=3A" method="post">
<input type="hidden" name="app_id" value="'.$output[$x]['applicant_id'].'" />
Select Time: <select name="hh" class="dropdown-toggle">
';
for($y=1;$y!=13;$y++)
{
echo'<option value="'.$y.'">'.$y.'</option>';
}
echo'</select> :
<select name="mm" class="dropdown-toggle">
<option value="00">00</option>
';
for($y=15;$y!=60;$y+=15)
{
echo'<option value="'.$y.'">'.$y.'</option>';
}
echo'</select>
<select name="set">
<option value="am">am</a>
<option value="pm">pm</a>
</select>
<br><br>
Select date:
<input type="text" class="datepickerto" name="training_date"/>
</div>
<div class="modal-footer">
<button class="btn" name="train_sched" type="submit" ><i class=" glyphicon-ok-sign"> </i> Save</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
</form>
</div>
</div>
</div>
</div>
<div id="myModalDeleteAccount'. $output[$x]['applicant_id'].'" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 id="myModalLabel">'. $output[$x]['first_name'].' '.$output[$x]['last_name'].'</h4>
</div>
<div class="modal-body">
<p style="vertical-align:top;">Email: '.$output[$x]['email'].'
</p>
<p style="vertical-align:top;">Skype ID: '.$output[$x]['skype'].'
</p>
</div>
<div class="modal-footer">
<form action="'.$_SERVER['PHP_SELF'].'?t=3A&" method="POST" />
<a href="applicant_profile.php?AppId='.$output[$x]['applicant_id'].'&t=3A" ><button class="btn"><i class=" glyphicon-search"> </i> View</button></a>
<input type="hidden" class="btn" name="id" value="'.$output[$x]['applicant_id'].'" />
<button type="submit" class="btn" name="delete" ><i class=" glyphicon-remove"> </i> Delete</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
</form>
</div>
</div>
</div>
</div>';
}
?>
</table> | filipinotutor/public_html | includes/utilities/tables/_applicant_account_table.php | PHP | mit | 5,816 | 41.772059 | 196 | 0.579436 | false |
const globalActionsTypes = {
MODULE_PARAMETERS_LOADED: "MODULE_PARAMETERS_LOADED"
};
export default globalActionsTypes; | dnnsoftware/Dnn.Platform | DNN Platform/Modules/ResourceManager/ResourceManager.Web/app/action types/globalActionsTypes.js | JavaScript | mit | 124 | 24 | 56 | 0.790323 | false |
/**
* San
* Copyright 2016 Baidu Inc. All rights reserved.
*
* @file 主文件
* @author errorrik(errorrik@gmail.com)
* otakustay(otakustay@gmail.com)
* junmer(junmer@foxmail.com)
*/
(function (root) {
// 人工调整打包代码顺序,通过注释手工写一些依赖
// // require('./util/empty');
// // require('./util/extend');
// // require('./util/inherits');
// // require('./util/each');
// // require('./util/contains');
// // require('./util/bind');
// // require('./browser/on');
// // require('./browser/un');
// // require('./browser/svg-tags');
// // require('./browser/create-el');
// // require('./browser/remove-el');
// // require('./util/guid');
// // require('./util/next-tick');
// // require('./browser/ie');
// // require('./browser/ie-old-than-9');
// // require('./util/indexed-list');
// // require('./browser/auto-close-tags');
// // require('./util/data-types.js');
// // require('./util/create-data-types-checker.js');
// // require('./parser/walker');
// // require('./parser/create-a-node');
// // require('./parser/parse-template');
// // require('./runtime/change-expr-compare');
// // require('./runtime/data-change-type');
// // require('./runtime/data');
// // require('./runtime/escape-html');
// // require('./runtime/default-filters');
// // require('./runtime/binary-op');
// // require('./runtime/eval-expr');
// // require('./view/life-cycle');
// // require('./view/gen-stump-html');
// // require('./view/create-text');
// // require('./view/get-prop-handler');
// // require('./view/is-data-change-by-element');
// // require('./view/event-declaration-listener');
// // require('./view/gen-element-start-html');
// // require('./view/gen-element-end-html');
// // require('./view/gen-element-childs-html');
// // require('./view/create-node');
// // require('./parser/parse-anode-from-el');
// // require('./view/from-el-init-childs');
/**
* @file 空函数
* @author errorrik(errorrik@gmail.com)
*/
/**
* 啥都不干
*/
function empty() {}
// exports = module.exports = empty;
/**
* @file 属性拷贝
* @author errorrik(errorrik@gmail.com)
*/
/**
* 对象属性拷贝
*
* @param {Object} target 目标对象
* @param {Object} source 源对象
* @return {Object} 返回目标对象
*/
function extend(target, source) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key];
}
}
return target;
}
// exports = module.exports = extend;
/**
* @file 构建类之间的继承关系
* @author errorrik(errorrik@gmail.com)
*/
// var extend = require('./extend');
/**
* 构建类之间的继承关系
*
* @param {Function} subClass 子类函数
* @param {Function} superClass 父类函数
*/
function inherits(subClass, superClass) {
/* jshint -W054 */
var subClassProto = subClass.prototype;
var F = new Function();
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
extend(subClass.prototype, subClassProto);
/* jshint +W054 */
}
// exports = module.exports = inherits;
/**
* @file bind函数
* @author errorrik(errorrik@gmail.com)
*/
/**
* Function.prototype.bind 方法的兼容性封装
*
* @param {Function} func 要bind的函数
* @param {Object} thisArg this指向对象
* @param {...*} args 预设的初始参数
* @return {Function}
*/
function bind(func, thisArg) {
var nativeBind = Function.prototype.bind;
var slice = Array.prototype.slice;
if (nativeBind && func.bind === nativeBind) {
return nativeBind.apply(func, slice.call(arguments, 1));
}
var args = slice.call(arguments, 2);
return function () {
return func.apply(thisArg, args.concat(slice.call(arguments)));
};
}
// exports = module.exports = bind;
/**
* @file 遍历数组
* @author errorrik(errorrik@gmail.com)
*/
// var bind = require('./bind');
/**
* 遍历数组集合
*
* @param {Array} array 数组源
* @param {function(Any,number):boolean} iterator 遍历函数
* @param {Object=} thisArg this指向对象
*/
function each(array, iterator, thisArg) {
if (array && array.length > 0) {
if (thisArg) {
iterator = bind(iterator, thisArg);
}
for (var i = 0, l = array.length; i < l; i++) {
if (iterator(array[i], i) === false) {
break;
}
}
}
}
// exports = module.exports = each;
/**
* @file 判断数组中是否包含某项
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('./each');
/**
* 判断数组中是否包含某项
*
* @param {Array} array 数组
* @param {*} value 包含的项
* @return {boolean}
*/
function contains(array, value) {
var result = false;
each(array, function (item) {
result = item === value;
return !result;
});
return result;
}
// exports = module.exports = contains;
/**
* @file DOM 事件挂载
* @author errorrik(errorrik@gmail.com)
*/
/**
* DOM 事件挂载
*
* @inner
* @param {HTMLElement} el DOM元素
* @param {string} eventName 事件名
* @param {Function} listener 监听函数
*/
function on(el, eventName, listener) {
if (el.addEventListener) {
el.addEventListener(eventName, listener, false);
}
else {
el.attachEvent('on' + eventName, listener);
}
}
// exports = module.exports = on;
/**
* @file DOM 事件卸载
* @author errorrik(errorrik@gmail.com)
*/
/**
* DOM 事件卸载
*
* @inner
* @param {HTMLElement} el DOM元素
* @param {string} eventName 事件名
* @param {Function} listener 监听函数
*/
function un(el, eventName, listener) {
if (el.addEventListener) {
el.removeEventListener(eventName, listener, false);
}
else {
el.detachEvent('on' + eventName, listener);
}
}
// exports = module.exports = un;
/**
* @file SVG标签表
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
/**
* svgTags
*
* @see https://www.w3.org/TR/SVG/svgdtd.html 只取常用
* @type {Object}
*/
var svgTags = {};
each((''
// structure
+ 'svg,g,defs,desc,metadata,symbol,use,'
// image & shape
+ 'image,path,rect,circle,line,ellipse,polyline,polygon,'
// text
+ 'text,tspan,tref,textpath,'
// other
+ 'marker,pattern,clippath,mask,filter,cursor,view,animate,'
// font
+ 'font,font-face,glyph,missing-glyph'
).split(','),
function (key) {
svgTags[key] = 1;
}
);
// exports = module.exports = svgTags;
/**
* @file DOM创建
* @author errorrik(errorrik@gmail.com)
*/
// var svgTags = require('./svg-tags');
/**
* 创建 DOM 元素
*
* @param {string} tagName tagName
* @return {HTMLElement}
*/
function createEl(tagName) {
if (svgTags[tagName]) {
return document.createElementNS('http://www.w3.org/2000/svg', tagName);
}
return document.createElement(tagName);
}
// exports = module.exports = createEl;
/**
* @file 移除DOM
* @author errorrik(errorrik@gmail.com)
*/
/**
* 将 DOM 从页面中移除
*
* @param {HTMLElement} el DOM元素
*/
function removeEl(el) {
if (el && el.parentNode) {
el.parentNode.removeChild(el);
}
}
// exports = module.exports = removeEl;
/**
* @file 生成唯一id
* @author errorrik(errorrik@gmail.com)
*/
/**
* 唯一id的起始值
*
* @inner
* @type {number}
*/
var guidIndex = 1;
/**
* 获取唯一id
*
* @inner
* @return {string} 唯一id
*/
function guid() {
return '_san_' + (guidIndex++);
}
// exports = module.exports = guid;
/**
* @file 在下一个时间周期运行任务
* @author errorrik(errorrik@gmail.com)
*/
// var bind = require('./bind');
// var each = require('./each');
/**
* 下一个周期要执行的任务列表
*
* @inner
* @type {Array}
*/
var nextTasks = [];
/**
* 执行下一个周期任务的函数
*
* @inner
* @type {Function}
*/
var nextHandler;
/**
* 在下一个时间周期运行任务
*
* @inner
* @param {Function} fn 要运行的任务函数
* @param {Object=} thisArg this指向对象
*/
function nextTick(fn, thisArg) {
if (thisArg) {
fn = bind(fn, thisArg);
}
nextTasks.push(fn);
if (nextHandler) {
return;
}
nextHandler = function () {
var tasks = nextTasks.slice(0);
nextTasks = [];
nextHandler = null;
each(tasks, function (task) {
task();
});
};
if (typeof MutationObserver === 'function') {
var num = 1;
var observer = new MutationObserver(nextHandler);
var text = document.createTextNode(num);
observer.observe(text, {
characterData: true
});
text.data = ++num;
}
else if (typeof setImmediate === 'function') {
setImmediate(nextHandler);
}
else {
setTimeout(nextHandler, 0);
}
}
// exports = module.exports = nextTick;
/**
* @file ie版本号
* @author errorrik(errorrik@gmail.com)
*/
/**
* 从userAgent中ie版本号的匹配信息
*
* @type {Array}
*/
var ieVersionMatch = typeof navigator !== 'undefined'
&& navigator.userAgent.match(/msie\s*([0-9]+)/i);
/**
* ie版本号,非ie时为0
*
* @type {number}
*/
var ie = ieVersionMatch ? ieVersionMatch[1] - 0 : 0;
// exports = module.exports = ie;
/**
* @file 是否 IE 并且小于 9
* @author errorrik(errorrik@gmail.com)
*/
// var ie = require('./ie');
// HACK: IE8下,设置innerHTML时如果以script开头,script会被自动滤掉
// 为了保证script的stump存在,前面加个零宽特殊字符
// IE8下,innerHTML还不支持custom element,所以需要用div替代,不用createElement
/**
* 是否 IE 并且小于 9
*/
var ieOldThan9 = ie && ie < 9;
// exports = module.exports = ieOldThan9;
/**
* @file 索引列表
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('./each');
/**
* 索引列表,能根据 item 中的 name 进行索引
*
* @class
*/
function IndexedList() {
this.raw = [];
this.index = {};
}
/**
* 在列表末尾添加 item
*
* @inner
* @param {Object} item 要添加的对象
*/
IndexedList.prototype.push = function (item) {
// #[begin] error
// if (!item.name) {
// throw new Error('[SAN ERROR] Miss "name" property');
// }
// #[end]
if (!this.index[item.name]) {
this.raw.push(item);
this.index[item.name] = item;
}
};
/**
* 根据 name 获取 item
*
* @inner
* @param {string} name name
* @return {Object}
*/
IndexedList.prototype.get = function (name) {
return this.index[name];
};
/**
* 遍历 items
*
* @inner
* @param {function(*,Number):boolean} iterator 遍历函数
* @param {Object} thisArg 遍历函数运行的this环境
*/
IndexedList.prototype.each = function (iterator, thisArg) {
each(this.raw, iterator, thisArg);
};
/**
* 根据 name 移除 item
*
* @inner
* @param {string} name name
*/
IndexedList.prototype.remove = function (name) {
this.index[name] = null;
var len = this.raw.length;
while (len--) {
if (this.raw[len].name === name) {
this.raw.splice(len, 1);
break;
}
}
};
/**
* 连接另外一个 IndexedList,返回一个新的 IndexedList
*
* @inner
* @param {IndexedList} other 要连接的IndexedList
* @return {IndexedList}
*/
IndexedList.prototype.concat = function (other) {
var result = new IndexedList();
each(this.raw.concat(other.raw), function (item) {
result.push(item);
});
return result;
};
// exports = module.exports = IndexedList;
/**
* @file 自闭合标签表
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
/**
* 自闭合标签列表
*
* @type {Object}
*/
var autoCloseTags = {};
each(
'area,base,br,col,embed,hr,img,input,keygen,param,source,track,wbr'.split(','),
function (key) {
autoCloseTags[key] = 1;
}
);
// exports = module.exports = autoCloseTags;
/**
* @file data types
* @author leon <ludafa@outlook.com>
*/
// var bind = require('./bind');
// var empty = require('./empty');
// var extend = require('./extend');
// #[begin] error
// var ANONYMOUS_CLASS_NAME = '<<anonymous>>';
//
// /**
// * 获取精确的类型
// *
// * @NOTE 如果 obj 是一个 DOMElement,我们会返回 `element`;
// *
// * @param {*} obj 目标
// * @return {string}
// */
// function getDataType(obj) {
//
// if (obj && obj.nodeType === 1) {
// return 'element';
// }
//
// return Object.prototype.toString
// .call(obj)
// .slice(8, -1)
// .toLowerCase();
// }
// #[end]
/**
* 创建链式的数据类型校验器
*
* @param {Function} validate 真正的校验器
* @return {Function}
*/
function createChainableChecker(validate) {
var chainedChecker = function () {};
chainedChecker.isRequired = empty;
// 只在 error 功能启用时才有实际上的 dataTypes 检测
// #[begin] error
// var checkType = function (isRequired, data, dataName, componentName, fullDataName) {
//
// var dataValue = data[dataName];
// var dataType = getDataType(dataValue);
//
// componentName = componentName || ANONYMOUS_CLASS_NAME;
//
// // 如果是 null 或 undefined,那么要提前返回啦
// if (dataValue == null) {
// // 是 required 就报错
// if (isRequired) {
// throw new Error('[SAN ERROR] '
// + 'The `' + dataName + '` '
// + 'is marked as required in `' + componentName + '`, '
// + 'but its value is ' + dataType
// );
// }
// // 不是 required,那就是 ok 的
// return;
// }
//
// validate(data, dataName, componentName, fullDataName);
//
// };
//
// chainedChecker = bind(checkType, null, false);
// chainedChecker.isRequired = bind(checkType, null, true);
// #[end]
return chainedChecker;
}
// #[begin] error
// /**
// * 生成主要类型数据校验器
// *
// * @param {string} type 主类型
// * @return {Function}
// */
// function createPrimaryTypeChecker(type) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// var dataValue = data[dataName];
// var dataType = getDataType(dataValue);
//
// if (dataType !== type) {
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + fullDataName + '` of type'
// + '(' + dataType + ' supplied to ' + componentName + ', '
// + 'expected ' + type + ')'
// );
// }
//
// });
//
// }
//
//
//
// /**
// * 生成 arrayOf 校验器
// *
// * @param {Function} arrayItemChecker 数组中每项数据的校验器
// * @return {Function}
// */
// function createArrayOfChecker(arrayItemChecker) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// if (typeof arrayItemChecker !== 'function') {
// throw new Error('[SAN ERROR] '
// + 'Data `' + dataName + '` of `' + componentName + '` has invalid '
// + 'DataType notation inside `arrayOf`, expected `function`'
// );
// }
//
// var dataValue = data[dataName];
// var dataType = getDataType(dataValue);
//
// if (dataType !== 'array') {
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + fullDataName + '` of type'
// + '(' + dataType + ' supplied to ' + componentName + ', '
// + 'expected array)'
// );
// }
//
// for (var i = 0, len = dataValue.length; i < len; i++) {
// arrayItemChecker(dataValue, i, componentName, fullDataName + '[' + i + ']');
// }
//
// });
//
// }
//
// /**
// * 生成 instanceOf 检测器
// *
// * @param {Function|Class} expectedClass 期待的类
// * @return {Function}
// */
// function createInstanceOfChecker(expectedClass) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// var dataValue = data[dataName];
//
// if (dataValue instanceof expectedClass) {
// return;
// }
//
// var dataValueClassName = dataValue.constructor && dataValue.constructor.name
// ? dataValue.constructor.name
// : ANONYMOUS_CLASS_NAME;
//
// var expectedClassName = expectedClass.name || ANONYMOUS_CLASS_NAME;
//
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + fullDataName + '` of type'
// + '(' + dataValueClassName + ' supplied to ' + componentName + ', '
// + 'expected instance of ' + expectedClassName + ')'
// );
//
//
// });
//
// }
//
// /**
// * 生成 shape 校验器
// *
// * @param {Object} shapeTypes shape 校验规则
// * @return {Function}
// */
// function createShapeChecker(shapeTypes) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// if (getDataType(shapeTypes) !== 'object') {
// throw new Error('[SAN ERROR] '
// + 'Data `' + fullDataName + '` of `' + componentName + '` has invalid '
// + 'DataType notation inside `shape`, expected `object`'
// );
// }
//
// var dataValue = data[dataName];
// var dataType = getDataType(dataValue);
//
// if (dataType !== 'object') {
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + fullDataName + '` of type'
// + '(' + dataType + ' supplied to ' + componentName + ', '
// + 'expected object)'
// );
// }
//
// for (var shapeKeyName in shapeTypes) {
// if (shapeTypes.hasOwnProperty(shapeKeyName)) {
// var checker = shapeTypes[shapeKeyName];
// if (typeof checker === 'function') {
// checker(dataValue, shapeKeyName, componentName, fullDataName + '.' + shapeKeyName);
// }
// }
// }
//
// });
//
// }
//
// /**
// * 生成 oneOf 校验器
// *
// * @param {Array} expectedEnumValues 期待的枚举值
// * @return {Function}
// */
// function createOneOfChecker(expectedEnumValues) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// if (getDataType(expectedEnumValues) !== 'array') {
// throw new Error('[SAN ERROR] '
// + 'Data `' + fullDataName + '` of `' + componentName + '` has invalid '
// + 'DataType notation inside `oneOf`, array is expected.'
// );
// }
//
// var dataValue = data[dataName];
//
// for (var i = 0, len = expectedEnumValues.length; i < len; i++) {
// if (dataValue === expectedEnumValues[i]) {
// return;
// }
// }
//
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + fullDataName + '` of value'
// + '(`' + dataValue + '` supplied to ' + componentName + ', '
// + 'expected one of ' + expectedEnumValues.join(',') + ')'
// );
//
// });
//
// }
//
// /**
// * 生成 oneOfType 校验器
// *
// * @param {Array<Function>} expectedEnumOfTypeValues 期待的枚举类型
// * @return {Function}
// */
// function createOneOfTypeChecker(expectedEnumOfTypeValues) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// if (getDataType(expectedEnumOfTypeValues) !== 'array') {
// throw new Error('[SAN ERROR] '
// + 'Data `' + dataName + '` of `' + componentName + '` has invalid '
// + 'DataType notation inside `oneOf`, array is expected.'
// );
// }
//
// var dataValue = data[dataName];
//
// for (var i = 0, len = expectedEnumOfTypeValues.length; i < len; i++) {
//
// var checker = expectedEnumOfTypeValues[i];
//
// if (typeof checker !== 'function') {
// continue;
// }
//
// try {
// checker(data, dataName, componentName, fullDataName);
// // 如果 checker 完成校验没报错,那就返回了
// return;
// }
// catch (e) {
// // 如果有错误,那么应该把错误吞掉
// }
//
// }
//
// // 所有的可接受 type 都失败了,才丢一个异常
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + dataName + '` of value'
// + '(`' + dataValue + '` supplied to ' + componentName + ')'
// );
//
// });
//
// }
//
// /**
// * 生成 objectOf 校验器
// *
// * @param {Function} typeChecker 对象属性值校验器
// * @return {Function}
// */
// function createObjectOfChecker(typeChecker) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// if (typeof typeChecker !== 'function') {
// throw new Error('[SAN ERROR] '
// + 'Data `' + dataName + '` of `' + componentName + '` has invalid '
// + 'DataType notation inside `objectOf`, expected function'
// );
// }
//
// var dataValue = data[dataName];
// var dataType = getDataType(dataValue);
//
// if (dataType !== 'object') {
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + dataName + '` of type'
// + '(' + dataType + ' supplied to ' + componentName + ', '
// + 'expected object)'
// );
// }
//
// for (var dataKeyName in dataValue) {
// if (dataValue.hasOwnProperty(dataKeyName)) {
// typeChecker(
// dataValue,
// dataKeyName,
// componentName,
// fullDataName + '.' + dataKeyName
// );
// }
// }
//
//
// });
//
// }
//
// /**
// * 生成 exact 校验器
// *
// * @param {Object} shapeTypes object 形态定义
// * @return {Function}
// */
// function createExactChecker(shapeTypes) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName, secret) {
//
// if (getDataType(shapeTypes) !== 'object') {
// throw new Error('[SAN ERROR] '
// + 'Data `' + dataName + '` of `' + componentName + '` has invalid '
// + 'DataType notation inside `exact`'
// );
// }
//
// var dataValue = data[dataName];
// var dataValueType = getDataType(dataValue);
//
// if (dataValueType !== 'object') {
// throw new Error('[SAN ERROR] '
// + 'Invalid data `' + fullDataName + '` of type `' + dataValueType + '`'
// + '(supplied to ' + componentName + ', expected `object`)'
// );
// }
//
// var allKeys = {};
//
// // 先合入 shapeTypes
// extend(allKeys, shapeTypes);
// // 再合入 dataValue
// extend(allKeys, dataValue);
// // 保证 allKeys 的类型正确
//
// for (var key in allKeys) {
// if (allKeys.hasOwnProperty(key)) {
// var checker = shapeTypes[key];
//
// // dataValue 中有一个多余的数据项
// if (!checker) {
// throw new Error('[SAN ERROR] '
// + 'Invalid data `' + fullDataName + '` key `' + key + '` '
// + 'supplied to `' + componentName + '`. '
// + '(`' + key + '` is not defined in `DataTypes.exact`)'
// );
// }
//
// if (!(key in dataValue)) {
// throw new Error('[SAN ERROR] '
// + 'Invalid data `' + fullDataName + '` key `' + key + '` '
// + 'supplied to `' + componentName + '`. '
// + '(`' + key + '` is marked `required` in `DataTypes.exact`)'
// );
// }
//
// checker(
// dataValue,
// key,
// componentName,
// fullDataName + '.' + key,
// secret
// );
//
// }
// }
//
// });
//
// }
// #[end]
/* eslint-disable fecs-valid-var-jsdoc */
var DataTypes = {
array: createChainableChecker(empty),
object: createChainableChecker(empty),
func: createChainableChecker(empty),
string: createChainableChecker(empty),
number: createChainableChecker(empty),
bool: createChainableChecker(empty),
symbol: createChainableChecker(empty),
any: createChainableChecker,
arrayOf: createChainableChecker,
instanceOf: createChainableChecker,
shape: createChainableChecker,
oneOf: createChainableChecker,
oneOfType: createChainableChecker,
objectOf: createChainableChecker,
exact: createChainableChecker
};
// #[begin] error
// DataTypes = {
//
// any: createChainableChecker(empty),
//
// // 类型检测
// array: createPrimaryTypeChecker('array'),
// object: createPrimaryTypeChecker('object'),
// func: createPrimaryTypeChecker('function'),
// string: createPrimaryTypeChecker('string'),
// number: createPrimaryTypeChecker('number'),
// bool: createPrimaryTypeChecker('boolean'),
// symbol: createPrimaryTypeChecker('symbol'),
//
// // 复合类型检测
// arrayOf: createArrayOfChecker,
// instanceOf: createInstanceOfChecker,
// shape: createShapeChecker,
// oneOf: createOneOfChecker,
// oneOfType: createOneOfTypeChecker,
// objectOf: createObjectOfChecker,
// exact: createExactChecker
//
// };
// /* eslint-enable fecs-valid-var-jsdoc */
// #[end]
// module.exports = DataTypes;
/**
* @file 创建数据检测函数
* @author leon<ludafa@outlook.com>
*/
// #[begin] error
//
// /**
// * 创建数据检测函数
// *
// * @param {Object} dataTypes 数据格式
// * @param {string} componentName 组件名
// * @return {Function}
// */
// function createDataTypesChecker(dataTypes, componentName) {
//
// /**
// * 校验 data 是否满足 data types 的格式
// *
// * @param {*} data 数据
// */
// return function (data) {
//
// for (var dataTypeName in dataTypes) {
//
// if (dataTypes.hasOwnProperty(dataTypeName)) {
//
// var dataTypeChecker = dataTypes[dataTypeName];
//
// if (typeof dataTypeChecker !== 'function') {
// throw new Error('[SAN ERROR] '
// + componentName + ':' + dataTypeName + ' is invalid; '
// + 'it must be a function, usually from san.DataTypes'
// );
// }
//
// dataTypeChecker(
// data,
// dataTypeName,
// componentName,
// dataTypeName
// );
//
//
// }
// }
//
// };
//
// }
//
// #[end]
// module.exports = createDataTypesChecker;
/**
* @file 字符串源码读取类
* @author errorrik(errorrik@gmail.com)
*/
/**
* 字符串源码读取类,用于模板字符串解析过程
*
* @class
* @param {string} source 要读取的字符串
*/
function Walker(source) {
this.source = source;
this.len = this.source.length;
this.index = 0;
}
/**
* 获取当前字符码
*
* @return {number}
*/
Walker.prototype.currentCode = function () {
return this.charCode(this.index);
};
/**
* 截取字符串片段
*
* @param {number} start 起始位置
* @param {number} end 结束位置
* @return {string}
*/
Walker.prototype.cut = function (start, end) {
return this.source.slice(start, end);
};
/**
* 向前读取字符
*
* @param {number} distance 读取字符数
*/
Walker.prototype.go = function (distance) {
this.index += distance;
};
/**
* 读取下一个字符,返回下一个字符的 code
*
* @return {number}
*/
Walker.prototype.nextCode = function () {
this.go(1);
return this.currentCode();
};
/**
* 获取相应位置字符的 code
*
* @param {number} index 字符位置
* @return {number}
*/
Walker.prototype.charCode = function (index) {
return this.source.charCodeAt(index);
};
/**
* 向前读取字符,直到遇到指定字符再停止
*
* @param {number=} charCode 指定字符的code
* @return {boolean} 当指定字符时,返回是否碰到指定的字符
*/
Walker.prototype.goUntil = function (charCode) {
var code;
while (this.index < this.len && (code = this.currentCode())) {
switch (code) {
case 32:
case 9:
this.index++;
break;
default:
if (code === charCode) {
this.index++;
return 1;
}
return;
}
}
};
/**
* 向前读取符合规则的字符片段,并返回规则匹配结果
*
* @param {RegExp} reg 字符片段的正则表达式
* @return {Array}
*/
Walker.prototype.match = function (reg) {
reg.lastIndex = this.index;
var match = reg.exec(this.source);
if (match) {
this.index = reg.lastIndex;
}
return match;
};
// exports = module.exports = Walker;
/**
* @file 表达式类型
* @author errorrik(errorrik@gmail.com)
*/
/**
* 表达式类型
*
* @const
* @type {Object}
*/
var ExprType = {
STRING: 1,
NUMBER: 2,
BOOL: 3,
ACCESSOR: 4,
INTERP: 5,
CALL: 6,
TEXT: 7,
BINARY: 8,
UNARY: 9,
TERTIARY: 10
};
// exports = module.exports = ExprType;
/**
* @file 读取字符串
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
/**
* 读取字符串
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readString(walker) {
var startCode = walker.currentCode();
var startIndex = walker.index;
var charCode;
walkLoop: while ((charCode = walker.nextCode())) {
switch (charCode) {
case 92: // \
walker.go(1);
break;
case startCode:
walker.go(1);
break walkLoop;
}
}
var literal = walker.cut(startIndex, walker.index);
return {
type: ExprType.STRING,
value: (new Function('return ' + literal))()
};
}
// exports = module.exports = readString;
/**
* @file 读取数字
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
/**
* 读取数字
*
* @inner
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readNumber(walker) {
var match = walker.match(/\s*(-?[0-9]+(.[0-9]+)?)/g);
return {
type: ExprType.NUMBER,
value: match[1] - 0
};
}
// exports = module.exports = readNumber;
/**
* @file 读取ident
* @author errorrik(errorrik@gmail.com)
*/
/**
* 读取ident
*
* @inner
* @param {Walker} walker 源码读取对象
* @return {string}
*/
function readIdent(walker) {
var match = walker.match(/\s*([\$0-9a-z_]+)/ig);
return match[1];
}
// exports = module.exports = readIdent;
/**
* @file 读取三元表达式
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
// var readLogicalORExpr = require('./read-logical-or-expr');
/**
* 读取三元表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readTertiaryExpr(walker) {
var conditional = readLogicalORExpr(walker);
walker.goUntil();
if (walker.currentCode() === 63) { // ?
walker.go(1);
var yesExpr = readTertiaryExpr(walker);
walker.goUntil();
if (walker.currentCode() === 58) { // :
walker.go(1);
return {
type: ExprType.TERTIARY,
segs: [
conditional,
yesExpr,
readTertiaryExpr(walker)
]
};
}
}
return conditional;
}
// exports = module.exports = readTertiaryExpr;
/**
* @file 读取访问表达式
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
// var readIdent = require('./read-ident');
// var readTertiaryExpr = require('./read-tertiary-expr');
/**
* 读取访问表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readAccessor(walker) {
var firstSeg = readIdent(walker);
switch (firstSeg) {
case 'true':
case 'false':
return {
type: ExprType.BOOL,
value: firstSeg === 'true'
};
}
var result = {
type: ExprType.ACCESSOR,
paths: [
{
type: ExprType.STRING,
value: firstSeg
}
]
};
/* eslint-disable no-constant-condition */
accessorLoop: while (1) {
/* eslint-enable no-constant-condition */
switch (walker.currentCode()) {
case 46: // .
walker.go(1);
// ident as string
result.paths.push({
type: ExprType.STRING,
value: readIdent(walker)
});
break;
case 91: // [
walker.go(1);
result.paths.push(readTertiaryExpr(walker));
walker.goUntil(93); // ]
break;
default:
break accessorLoop;
}
}
return result;
}
// exports = module.exports = readAccessor;
/**
* @file 读取括号表达式
* @author errorrik(errorrik@gmail.com)
*/
// var readTertiaryExpr = require('./read-tertiary-expr');
/**
* 读取括号表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readParenthesizedExpr(walker) {
walker.go(1);
var expr = readTertiaryExpr(walker);
walker.goUntil(41); // )
return expr;
}
// exports = module.exports = readParenthesizedExpr;
/**
* @file 读取一元表达式
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
// var readString = require('./read-string');
// var readNumber = require('./read-number');
// var readAccessor = require('./read-accessor');
// var readParenthesizedExpr = require('./read-parenthesized-expr');
/**
* 读取一元表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readUnaryExpr(walker) {
walker.goUntil();
switch (walker.currentCode()) {
case 33: // !
walker.go(1);
return {
type: ExprType.UNARY,
expr: readUnaryExpr(walker)
};
case 34: // "
case 39: // '
return readString(walker);
case 45: // number
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
return readNumber(walker);
case 40: // (
return readParenthesizedExpr(walker);
}
return readAccessor(walker);
}
// exports = module.exports = readUnaryExpr;
/**
* @file 读取乘法表达式
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
// var readUnaryExpr = require('./read-unary-expr');
/**
* 读取乘法表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readMultiplicativeExpr(walker) {
var expr = readUnaryExpr(walker);
walker.goUntil();
var code = walker.currentCode();
switch (code) {
case 37: // %
case 42: // *
case 47: // /
walker.go(1);
return {
type: ExprType.BINARY,
operator: code,
segs: [expr, readMultiplicativeExpr(walker)]
};
}
return expr;
}
// exports = module.exports = readMultiplicativeExpr;
/**
* @file 读取加法表达式
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
// var readMultiplicativeExpr = require('./read-multiplicative-expr');
/**
* 读取加法表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readAdditiveExpr(walker) {
var expr = readMultiplicativeExpr(walker);
walker.goUntil();
var code = walker.currentCode();
switch (code) {
case 43: // +
case 45: // -
walker.go(1);
return {
type: ExprType.BINARY,
operator: code,
segs: [expr, readAdditiveExpr(walker)]
};
}
return expr;
}
// exports = module.exports = readAdditiveExpr;
/**
* @file 读取关系判断表达式
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
// var readAdditiveExpr = require('./read-additive-expr');
/**
* 读取关系判断表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readRelationalExpr(walker) {
var expr = readAdditiveExpr(walker);
walker.goUntil();
var code = walker.currentCode();
switch (code) {
case 60: // <
case 62: // >
if (walker.nextCode() === 61) {
code += 61;
walker.go(1);
}
return {
type: ExprType.BINARY,
operator: code,
segs: [expr, readRelationalExpr(walker)]
};
}
return expr;
}
// exports = module.exports = readRelationalExpr;
/**
* @file 读取相等比对表达式
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
// var readRelationalExpr = require('./read-relational-expr');
/**
* 读取相等比对表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readEqualityExpr(walker) {
var expr = readRelationalExpr(walker);
walker.goUntil();
var code = walker.currentCode();
switch (code) {
case 61: // =
case 33: // !
if (walker.nextCode() === 61) {
code += 61;
if (walker.nextCode() === 61) {
code += 61;
walker.go(1);
}
return {
type: ExprType.BINARY,
operator: code,
segs: [expr, readEqualityExpr(walker)]
};
}
walker.go(-1);
}
return expr;
}
// exports = module.exports = readEqualityExpr;
/**
* @file 读取逻辑与表达式
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
// var readEqualityExpr = require('./read-equality-expr');
/**
* 读取逻辑与表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readLogicalANDExpr(walker) {
var expr = readEqualityExpr(walker);
walker.goUntil();
if (walker.currentCode() === 38) { // &
if (walker.nextCode() === 38) {
walker.go(1);
return {
type: ExprType.BINARY,
operator: 76,
segs: [expr, readLogicalANDExpr(walker)]
};
}
walker.go(-1);
}
return expr;
}
// exports = module.exports = readLogicalANDExpr;
/**
* @file 读取逻辑或表达式
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
// var readLogicalANDExpr = require('./read-logical-and-expr');
/**
* 读取逻辑或表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readLogicalORExpr(walker) {
var expr = readLogicalANDExpr(walker);
walker.goUntil();
if (walker.currentCode() === 124) { // |
if (walker.nextCode() === 124) {
walker.go(1);
return {
type: ExprType.BINARY,
operator: 248,
segs: [expr, readLogicalORExpr(walker)]
};
}
walker.go(-1);
}
return expr;
}
// exports = module.exports = readLogicalORExpr;
/**
* @file 读取调用
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
// var readIdent = require('./read-ident');
// var readTertiaryExpr = require('./read-tertiary-expr');
/**
* 读取调用
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readCall(walker) {
walker.goUntil();
var ident = readIdent(walker);
var args = [];
if (walker.goUntil(40)) { // (
while (!walker.goUntil(41)) { // )
args.push(readTertiaryExpr(walker));
walker.goUntil(44); // ,
}
}
return {
type: ExprType.CALL,
name: ident,
args: args
};
}
// exports = module.exports = readCall;
/**
* @file 解析插值替换
* @author errorrik(errorrik@gmail.com)
*/
// var Walker = require('./walker');
// var readTertiaryExpr = require('./read-tertiary-expr');
// var ExprType = require('./expr-type');
// var readCall = require('./read-call');
/**
* 解析插值替换
*
* @param {string} source 源码
* @return {Object}
*/
function parseInterp(source) {
var walker = new Walker(source);
var expr = readTertiaryExpr(walker);
var filters = [];
while (walker.goUntil(124)) { // |
filters.push(readCall(walker));
}
return {
type: ExprType.INTERP,
expr: expr,
filters: filters
};
}
// exports = module.exports = parseInterp;
/**
* @file 解析文本
* @author errorrik(errorrik@gmail.com)
*/
// var Walker = require('./walker');
// var ExprType = require('./expr-type');
// var parseInterp = require('./parse-interp');
/**
* 解析文本
*
* @param {string} source 源码
* @return {Object}
*/
function parseText(source) {
var exprStartReg = /\{\{\s*([\s\S]+?)\s*\}\}/ig;
var exprMatch;
var walker = new Walker(source);
var beforeIndex = 0;
var segs = [];
function pushStringToSeg(text) {
text && segs.push({
type: ExprType.STRING,
value: text
});
}
while ((exprMatch = walker.match(exprStartReg)) != null) {
pushStringToSeg(walker.cut(
beforeIndex,
walker.index - exprMatch[0].length
));
segs.push(parseInterp(exprMatch[1]));
beforeIndex = walker.index;
}
pushStringToSeg(walker.cut(beforeIndex));
var expr = {
type: ExprType.TEXT,
segs: segs,
raw: source
};
if (segs.length === 1 && segs[0].type === ExprType.STRING) {
expr.value = segs[0].value;
}
return expr;
}
// exports = module.exports = parseText;
/**
* @file 模板解析生成的抽象节点
* @author errorrik(errorrik@gmail.com)
*/
// var IndexedList = require('../util/indexed-list');
// var parseText = require('./parse-text');
/**
* 创建模板解析生成的抽象节点
*
* @class
* @param {Object=} options 节点参数
* @param {string=} options.tagName 标签名
* @param {ANode=} options.parent 父节点
* @param {boolean=} options.isText 是否文本节点
*/
function createANode(options) {
options = options || {};
if (options.isText) {
options.textExpr = parseText(options.text);
}
else {
options.directives = options.directives || new IndexedList();
options.props = options.props || new IndexedList();
options.events = options.events || [];
options.childs = options.childs || [];
}
return options;
}
// exports = module.exports = createANode;
/**
* @file 解析表达式
* @author errorrik(errorrik@gmail.com)
*/
// var Walker = require('./walker');
// var readTertiaryExpr = require('./read-tertiary-expr');
/**
* 解析表达式
*
* @param {string} source 源码
* @return {Object}
*/
function parseExpr(source) {
if (typeof source === 'object' && source.type) {
return source;
}
var expr = readTertiaryExpr(new Walker(source));
expr.raw = source;
return expr;
}
// exports = module.exports = parseExpr;
/**
* @file 解析调用
* @author errorrik(errorrik@gmail.com)
*/
// var Walker = require('./walker');
// var readCall = require('./read-call');
/**
* 解析调用
*
* @param {string} source 源码
* @return {Object}
*/
function parseCall(source) {
var expr = readCall(new Walker(source));
expr.raw = source;
return expr;
}
// exports = module.exports = parseCall;
/**
* @file 解析指令
* @author errorrik(errorrik@gmail.com)
*/
// var Walker = require('./walker');
// var parseExpr = require('./parse-expr');
// var parseText = require('./parse-text');
// var parseInterp = require('./parse-interp');
// var readAccessor = require('./read-accessor');
/**
* 指令解析器
*
* @inner
* @type {Object}
*/
var directiveParsers = {
'for': function (value) {
var walker = new Walker(value);
var match = walker.match(/^\s*([\$0-9a-z_]+)(\s*,\s*([\$0-9a-z_]+))?\s+in\s+/ig);
if (match) {
return {
item: parseExpr(match[1]),
index: parseExpr(match[3] || '$index'),
list: readAccessor(walker)
};
}
// #[begin] error
// throw new Error('[SAN FATAL] for syntax error: ' + value);
// #[end]
},
'ref': function (value) {
return {
value: parseText(value)
};
},
'if': function (value) {
return {
value: parseExpr(value.replace(/(^\{\{|\}\}$)/g, ''))
};
},
'elif': function (value) {
return {
value: parseExpr(value.replace(/(^\{\{|\}\}$)/g, ''))
};
},
'else': function (value) {
return {
value: 1
};
},
'html': function (value) {
return {
value: parseInterp(value)
};
}
};
/**
* 解析指令
*
* @param {ANode} aNode 抽象节点
* @param {string} name 指令名称
* @param {string} value 指令值
*/
function parseDirective(aNode, name, value) {
var parser = directiveParsers[name];
if (parser) {
var result = parser(value);
result.name = name;
result.raw = value;
aNode.directives.push(result);
}
}
// exports = module.exports = parseDirective;
/**
* @file 对属性信息进行处理
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('../parser/expr-type');
/**
* 对属性信息进行处理
* 对组件的 binds 或者特殊的属性(比如 input 的 checked)需要处理
*
* 扁平化:
* 当 text 解析只有一项时,要么就是 string,要么就是 interp
* interp 有可能是绑定到组件属性的表达式,不希望被 eval text 成 string
* 所以这里做个处理,只有一项时直接抽出来
*
* bool属性:
* 当绑定项没有值时,默认为true
*
* @param {Object} prop 属性对象
*/
function postProp(prop) {
var expr = prop.expr;
if (expr.type === ExprType.TEXT) {
switch (expr.segs.length) {
case 0:
prop.expr = {
type: ExprType.BOOL,
value: true
};
break;
case 1:
expr = prop.expr = expr.segs[0];
if (expr.type === ExprType.INTERP && expr.filters.length === 0) {
prop.expr = expr.expr;
}
}
}
}
// exports = module.exports = postProp;
/**
* @file 二元表达式操作函数
* @author errorrik(errorrik@gmail.com)
*/
/**
* 二元表达式操作函数
*
* @type {Object}
*/
var BinaryOp = {
/* eslint-disable */
37: function (a, b) {
return a % b;
},
43: function (a, b) {
return a + b;
},
45: function (a, b) {
return a - b;
},
42: function (a, b) {
return a * b;
},
47: function (a, b) {
return a / b;
},
60: function (a, b) {
return a < b;
},
62: function (a, b) {
return a > b;
},
76: function (a, b) {
return a && b;
},
94: function (a, b) {
return a != b;
},
121: function (a, b) {
return a <= b;
},
122: function (a, b) {
return a == b;
},
123: function (a, b) {
return a >= b;
},
155: function (a, b) {
return a !== b;
},
183: function (a, b) {
return a === b;
},
248: function (a, b) {
return a || b;
}
/* eslint-enable */
};
// exports = module.exports = BinaryOp;
/**
* @file HTML转义
* @author errorrik(errorrik@gmail.com)
*/
/**
* HTML Filter替换的字符实体表
*
* @const
* @inner
* @type {Object}
*/
var HTML_ENTITY = {
/* jshint ignore:start */
'&': '&',
'<': '<',
'>': '>',
'"': '"',
/* eslint-disable quotes */
"'": '''
/* eslint-enable quotes */
/* jshint ignore:end */
};
/**
* HTML Filter的替换函数
*
* @inner
* @param {string} c 替换字符
* @return {string} 替换后的HTML字符实体
*/
function htmlFilterReplacer(c) {
return HTML_ENTITY[c];
}
/**
* HTML转义
*
* @param {string} source 源串
* @return {string} 替换结果串
*/
function escapeHTML(source) {
if (source == null) {
return '';
}
return ('' + source).replace(/[&<>"']/g, htmlFilterReplacer);
}
// exports = module.exports = escapeHTML;
/**
* @file 默认filter
* @author errorrik(errorrik@gmail.com)
*/
// var escapeHTML = require('./escape-html');
/* eslint-disable fecs-camelcase */
/* eslint-disable guard-for-in */
/**
* 默认filter
*
* @const
* @type {Object}
*/
var DEFAULT_FILTERS = {
/**
* HTML转义filter
*
* @param {string} source 源串
* @return {string} 替换结果串
*/
html: escapeHTML,
/**
* URL编码filter
*
* @param {string} source 源串
* @return {string} 替换结果串
*/
url: encodeURIComponent,
/**
* 源串filter,用于在默认开启HTML转义时获取源串,不进行转义
*
* @param {string} source 源串
* @return {string} 替换结果串
*/
raw: function (source) {
return source;
},
_class: function (source) {
if (source instanceof Array) {
return source.join(' ');
}
return source;
},
_style: function (source) {
if (typeof source === 'object') {
var result = '';
for (var key in source) {
result += key + ':' + source[key] + ';';
}
return result;
}
return source;
},
_sep: function (source, sep) {
return source ? sep + source : source;
}
};
/* eslint-enable fecs-camelcase */
// exports = module.exports = DEFAULT_FILTERS;
/**
* @file 表达式计算
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('../parser/expr-type');
// var BinaryOp = require('./binary-op');
// var DEFAULT_FILTERS = require('./default-filters');
// var escapeHTML = require('./escape-html');
// var each = require('../util/each');
/**
* 计算表达式的值
*
* @param {Object} expr 表达式对象
* @param {Data} data 数据容器对象
* @param {Component=} owner 所属组件环境
* @param {boolean?} escapeInterpHtml 是否对插值进行html转义
* @return {*}
*/
function evalExpr(expr, data, owner, escapeInterpHtml) {
if (expr.value != null) {
return expr.value;
}
switch (expr.type) {
case ExprType.UNARY:
return !evalExpr(expr.expr, data, owner);
case ExprType.BINARY:
var opHandler = BinaryOp[expr.operator];
if (typeof opHandler === 'function') {
return opHandler(
evalExpr(expr.segs[0], data, owner),
evalExpr(expr.segs[1], data, owner)
);
}
return;
case ExprType.TERTIARY:
return evalExpr(
expr.segs[evalExpr(expr.segs[0], data, owner) ? 1 : 2],
data,
owner
);
case ExprType.ACCESSOR:
return data.get(expr);
case ExprType.INTERP:
var value = evalExpr(expr.expr, data, owner);
owner && each(expr.filters, function (filter) {
var filterName = filter.name;
/* eslint-disable no-use-before-define */
var filterFn = owner.filters[filterName] || DEFAULT_FILTERS[filterName];
/* eslint-enable no-use-before-define */
if (typeof filterFn === 'function') {
var args = [value];
each(filter.args, function (arg) {
args.push(evalExpr(arg, data, owner));
});
value = filterFn.apply(owner, args);
}
});
if (value == null) {
value = '';
}
return value;
case ExprType.TEXT:
var buf = '';
each(expr.segs, function (seg) {
var segValue = evalExpr(seg, data, owner);
// escape html
if (escapeInterpHtml && seg.type === ExprType.INTERP && !seg.filters[0]) {
segValue = escapeHTML(segValue);
}
buf += segValue;
});
return buf;
}
}
// exports = module.exports = evalExpr;
/**
* @file 在节点环境执行表达式
* @author errorrik(errorrik@gmail.com)
*/
// var evalExpr = require('../runtime/eval-expr');
/**
* 在节点环境执行表达式
*
* @param {Object} node 节点对象
* @param {Object} expr 表达式对象
* @param {boolean} escapeInterpHtml 是否要对插值结果进行html转义
* @return {*}
*/
function nodeEvalExpr(node, expr, escapeInterpHtml) {
return evalExpr(expr, node.scope, node.owner, escapeInterpHtml);
}
// exports = module.exports = nodeEvalExpr;
/**
* @file 节点类型
* @author errorrik(errorrik@gmail.com)
*/
/**
* 节点类型
*
* @const
* @type {Object}
*/
var NodeType = {
TEXT: 1,
IF: 2,
FOR: 3,
ELEM: 4,
CMPT: 5,
SLOT: 6
};
// exports = module.exports = NodeType;
/**
* @file 判断一个node是否组件
* @author errorrik(errorrik@gmail.com)
*/
// var NodeType = require('./node-type');
/**
* 判断一个node是否组件
*
* @param {Node} node 节点实例
* @return {boolean}
*/
function isComponent(node) {
return node && node._type === NodeType.CMPT;
}
// exports = module.exports = isComponent;
/**
* @file 获取属性处理对象
* @author errorrik(errorrik@gmail.com)
*/
// var contains = require('../util/contains');
// var empty = require('../util/empty');
// var svgTags = require('../browser/svg-tags');
// var evalExpr = require('../runtime/eval-expr');
// var nodeEvalExpr = require('./node-eval-expr');
// var isComponent = require('./is-component');
/**
* HTML 属性和 DOM 操作属性的对照表
*
* @inner
* @const
* @type {Object}
*/
var HTML_ATTR_PROP_MAP = {
'readonly': 'readOnly',
'cellpadding': 'cellPadding',
'cellspacing': 'cellSpacing',
'colspan': 'colSpan',
'rowspan': 'rowSpan',
'valign': 'vAlign',
'usemap': 'useMap',
'frameborder': 'frameBorder',
'for': 'htmlFor',
'class': 'className'
};
/**
* 默认的元素的属性设置的变换方法
*
* @inner
* @type {Object}
*/
var defaultElementPropHandler = {
attr: function (element, name, value) {
if (value) {
return ' ' + name + '="' + value + '"';
}
},
prop: function (element, name, value) {
name = HTML_ATTR_PROP_MAP[name] || name;
if (svgTags[element.tagName]) {
element.el.setAttribute(name, value);
}
else {
element.el[name] = value;
}
},
output: function (element, bindInfo, data) {
data.set(bindInfo.expr, element.el[bindInfo.name], {
target: {
id: element.id,
prop: bindInfo.name
}
});
}
};
/**
* 默认的属性设置变换方法
*
* @inner
* @type {Object}
*/
var defaultElementPropHandlers = {
style: {
attr: function (element, name, value) {
if (value) {
return ' style="' + value + '"';
}
},
prop: function (element, name, value) {
element.el.style.cssText = value;
}
},
draggable: genBoolPropHandler('draggable'),
readonly: genBoolPropHandler('readonly'),
disabled: genBoolPropHandler('disabled')
};
var checkedPropHandler = genBoolPropHandler('checked');
var analInputChecker = {
checkbox: contains,
radio: function (a, b) {
return a === b;
}
};
function analInputCheckedState(element, value, oper) {
var bindValue = element.props.get('value');
var bindType = element.props.get('type');
if (bindValue && bindType) {
var type = nodeEvalExpr(element, bindType.expr);
if (analInputChecker[type]) {
var bindChecked = element.props.get('checked');
if (!bindChecked.hintExpr) {
bindChecked.hintExpr = bindValue.expr;
}
var checkedState = analInputChecker[type](
value,
nodeEvalExpr(element, bindValue.expr)
);
switch (oper) {
case 'attr':
return checkedState ? ' checked="checked"' : '';
case 'prop':
element.el.checked = checkedState;
return;
}
}
}
return checkedPropHandler[oper](element, 'checked', value);
}
var elementPropHandlers = {
input: {
mutiple: genBoolPropHandler('mutiple'),
checked: {
attr: function (element, name, value) {
return analInputCheckedState(element, value, 'attr');
},
prop: function (element, name, value) {
analInputCheckedState(element, value, 'prop');
},
output: function (element, bindInfo, data) {
var el = element.el;
var bindType = element.props.get('type') || {};
switch (bindType.raw) {
case 'checkbox':
data[el.checked ? 'push' : 'remove'](bindInfo.expr, el.value);
break;
case 'radio':
el.checked && data.set(bindInfo.expr, el.value, {
target: {
id: element.id,
prop: bindInfo.name
}
});
break;
}
}
}
},
textarea: {
value: {
attr: empty,
prop: defaultElementPropHandler.prop,
output: defaultElementPropHandler.output
}
},
option: {
value: {
attr: function (element, name, value) {
var attrStr = ' value="' + (value || '') + '"';
var parentSelect = element.parent;
while (parentSelect) {
if (parentSelect.tagName === 'select') {
break;
}
parentSelect = parentSelect.parent;
}
if (parentSelect) {
var selectValue = null;
var prop;
var expr;
if ((prop = parentSelect.props.get('value'))
&& (expr = prop.expr)
) {
selectValue = isComponent(parentSelect)
? evalExpr(expr, parentSelect.data, parentSelect)
: nodeEvalExpr(parentSelect, expr)
|| '';
}
if (selectValue === value) {
attrStr += ' selected';
}
}
return attrStr;
},
prop: defaultElementPropHandler.prop
}
},
select: {
value: {
attr: empty,
prop: function (element, name, value) {
element.el.value = value || '';
},
output: defaultElementPropHandler.output
}
}
};
/**
* 生成 bool 类型属性绑定操作的变换方法
*
* @inner
* @param {string} attrName 属性名
* @return {Object}
*/
function genBoolPropHandler(attrName) {
var attrLiteral = ' ' + attrName;
return {
attr: function (element, name, value) {
// 因为元素的attr值必须经过html escape,否则可能有漏洞
// 所以这里直接对假值字符串形式进行处理
// NaN之类非主流的就先不考虑了
if (element.props.get(name).raw === ''
|| value && value !== 'false' && value !== '0'
) {
return attrLiteral;
}
},
prop: function (element, name, value) {
var propName = HTML_ATTR_PROP_MAP[attrName] || attrName;
element.el[propName] = !!(value && value !== 'false' && value !== '0');
}
};
}
/**
* 获取属性处理对象
*
* @param {Element} element 元素实例
* @param {string} name 属性名
* @return {Object}
*/
function getPropHandler(element, name) {
var tagPropHandlers = elementPropHandlers[element.tagName];
if (!tagPropHandlers) {
tagPropHandlers = elementPropHandlers[element.tagName] = {};
}
var propHandler = tagPropHandlers[name];
if (!propHandler) {
propHandler = defaultElementPropHandlers[name] || defaultElementPropHandler;
tagPropHandlers[name] = propHandler;
}
return propHandler;
}
// exports = module.exports = getPropHandler;
/**
* @file 解析抽象节点属性
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var parseExpr = require('./parse-expr');
// var parseCall = require('./parse-call');
// var parseText = require('./parse-text');
// var parseDirective = require('./parse-directive');
// var ExprType = require('./expr-type');
// var postProp = require('./post-prop');
// var getPropHandler = require('../view/get-prop-handler');
/**
* 解析抽象节点属性
*
* @param {ANode} aNode 抽象节点
* @param {string} name 属性名称
* @param {string} value 属性值
* @param {boolean=} ignoreNormal 是否忽略无前缀的普通属性
*/
function integrateAttr(aNode, name, value, ignoreNormal) {
if (name === 'id') {
aNode.id = value;
return;
}
var prefixIndex = name.indexOf('-');
var realName;
var prefix;
if (prefixIndex > 0) {
prefix = name.slice(0, prefixIndex);
realName = name.slice(prefixIndex + 1);
}
switch (prefix) {
case 'on':
aNode.events.push({
name: realName,
expr: parseCall(value)
});
break;
case 'san':
case 's':
parseDirective(aNode, realName, value);
break;
case 'prop':
integrateProp(aNode, realName, value);
break;
default:
if (!ignoreNormal) {
integrateProp(aNode, name, value);
}
}
}
/**
* 解析抽象节点绑定属性
*
* @inner
* @param {ANode} aNode 抽象节点
* @param {string} name 属性名称
* @param {string} value 属性值
*/
function integrateProp(aNode, name, value) {
// parse two way binding, e.g. value="{=ident=}"
var xMatch = value.match(/^\{=\s*(.*?)\s*=\}$/);
if (xMatch) {
aNode.props.push({
name: name,
expr: parseExpr(xMatch[1]),
x: 1,
raw: value
});
return;
}
// parse normal prop
var prop = {
name: name,
expr: parseText(value),
raw: value
};
if (prop.expr.value != null && !/^(template|input|textarea|select|option)$/.test(aNode.tagName)) {
prop.attr = getPropHandler(aNode, name).attr(aNode, name, value);
}
if (name === 'checked' && aNode.tagName === 'input') {
postProp(prop);
}
// 这里不能把只有一个插值的属性抽取
// 因为插值里的值可能是html片段,容易被注入
// 组件的数据绑定在组件init时做抽取
switch (prop.name) {
case 'class':
case 'style':
each(prop.expr.segs, function (seg) {
if (seg.type === ExprType.INTERP) {
seg.filters.push({
type: ExprType.CALL,
name: '_' + prop.name,
args: []
});
}
});
break;
}
aNode.props.push(prop);
}
// exports = module.exports = integrateAttr;
/**
* @file 解析模板
* @author errorrik(errorrik@gmail.com)
*/
// var createANode = require('./create-a-node');
// var Walker = require('./walker');
// var integrateAttr = require('./integrate-attr');
// var autoCloseTags = require('../browser/auto-close-tags');
/* eslint-disable fecs-max-statements */
/**
* 解析 template
*
* @param {string} source template源码
* @param {Object?} options 解析参数
* @param {string?} options.trimWhitespace 空白文本的处理策略。none|blank|all
* @return {ANode}
*/
function parseTemplate(source, options) {
options = options || {};
options.trimWhitespace = options.trimWhitespace || 'none';
var rootNode = createANode();
if (typeof source !== 'string') {
return rootNode;
}
source = source.replace(/<!--([\s\S]*?)-->/mg, '').replace(/(^\s+|\s+$)/g, '');
var walker = new Walker(source);
var tagReg = /<(\/)?([a-z0-9-]+)\s*/ig;
var attrReg = /([-:0-9a-z\(\)\[\]]+)(=(['"])([^\3]*?)\3)?\s*/ig;
var tagMatch;
var currentNode = rootNode;
var beforeLastIndex = 0;
while ((tagMatch = walker.match(tagReg)) != null) {
var tagEnd = tagMatch[1];
var tagName = tagMatch[2].toLowerCase();
pushTextNode(source.slice(
beforeLastIndex,
walker.index - tagMatch[0].length
));
// 62: >
// 47: /
if (tagEnd && walker.currentCode() === 62) {
// 满足关闭标签的条件时,关闭标签
// 向上查找到对应标签,找不到时忽略关闭
var closeTargetNode = currentNode;
while (closeTargetNode && closeTargetNode.tagName !== tagName) {
closeTargetNode = closeTargetNode.parent;
}
closeTargetNode && (currentNode = closeTargetNode.parent);
walker.go(1);
}
else if (!tagEnd) {
var aElement = createANode({
tagName: tagName,
parent: currentNode
});
var tagClose = autoCloseTags[tagName];
// 解析 attributes
/* eslint-disable no-constant-condition */
while (1) {
/* eslint-enable no-constant-condition */
var nextCharCode = walker.currentCode();
// 标签结束时跳出 attributes 读取
// 标签可能直接结束或闭合结束
if (nextCharCode === 62) {
walker.go(1);
break;
}
else if (nextCharCode === 47
&& walker.charCode(walker.index + 1) === 62
) {
walker.go(2);
tagClose = 1;
break;
}
// 读取 attribute
var attrMatch = walker.match(attrReg);
if (attrMatch) {
integrateAttr(
aElement,
attrMatch[1],
attrMatch[2] ? attrMatch[4] : ''
);
}
}
// match if directive for else/elif directive
var elseDirective = aElement.directives.get('else') || aElement.directives.get('elif');
if (elseDirective) {
var parentChildsLen = currentNode.childs.length;
while (parentChildsLen--) {
var parentChild = currentNode.childs[parentChildsLen];
if (parentChild.isText) {
currentNode.childs.splice(parentChildsLen, 1);
continue;
}
// #[begin] error
// if (!parentChild.directives.get('if')) {
// throw new Error('[SAN FATEL] else not match if.');
// }
// #[end]
parentChild.elses = parentChild.elses || [];
parentChild.elses.push(aElement);
break;
}
}
else {
if (aElement.tagName === 'tr' && currentNode.tagName === 'table') {
var tbodyNode = createANode({
tagName: 'tbody',
parent: currentNode
});
currentNode.childs.push(tbodyNode);
currentNode = tbodyNode;
aElement.parent = tbodyNode;
}
currentNode.childs.push(aElement);
}
if (!tagClose) {
currentNode = aElement;
}
}
beforeLastIndex = walker.index;
}
pushTextNode(walker.cut(beforeLastIndex));
return rootNode;
/**
* 在读取栈中添加文本节点
*
* @inner
* @param {string} text 文本内容
*/
function pushTextNode(text) {
switch (options.trimWhitespace) {
case 'blank':
if (/^\s+$/.test(text)) {
text = null;
}
break;
case 'all':
text = text.replace(/(^\s+|\s+$)/g, '');
break;
}
if (text) {
currentNode.childs.push(createANode({
isText: 1,
text: text,
parent: currentNode
}));
}
}
}
/* eslint-enable fecs-max-statements */
// exports = module.exports = parseTemplate;
/**
* @file 比较变更表达式与目标表达式之间的关系
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('../parser/expr-type');
// var evalExpr = require('./eval-expr');
// var each = require('../util/each');
/**
* 判断变更表达式与多个表达式之间的关系,0为完全没关系,1为有关系
*
* @inner
* @param {Object} changeExpr 目标表达式
* @param {Array} exprs 多个源表达式
* @param {Data} data 表达式所属数据环境
* @return {number}
*/
function changeExprCompareExprs(changeExpr, exprs, data) {
var result;
each(exprs, function (expr) {
result = changeExprCompare(changeExpr, expr, data);
return !result;
});
return result ? 1 : 0;
}
/**
* 比较变更表达式与目标表达式之间的关系,用于视图更新判断
* 视图更新需要根据其关系,做出相应的更新行为
*
* 0: 完全没关系
* 1: 变更表达式是目标表达式的母项(如a与a.b) 或 表示需要完全变化
* 2: 变更表达式是目标表达式相等
* >2: 变更表达式是目标表达式的子项,如a.b.c与a.b
*
* @param {Object} changeExpr 变更表达式
* @param {Object} expr 要比较的目标表达式
* @param {Data} data 表达式所属数据环境
* @return {number}
*/
function changeExprCompare(changeExpr, expr, data) {
switch (expr.type) {
case ExprType.ACCESSOR:
var paths = expr.paths;
var len = paths.length;
var changePaths = changeExpr.paths;
var changeLen = changePaths.length;
var result = 1;
for (var i = 0; i < len; i++) {
var pathExpr = paths[i];
if (pathExpr.type === ExprType.ACCESSOR
&& changeExprCompare(changeExpr, pathExpr, data)
) {
return 1;
}
if (result && i < changeLen
/* eslint-disable eqeqeq */
&& evalExpr(pathExpr, data) != evalExpr(changePaths[i], data)
/* eslint-enable eqeqeq */
) {
result = 0;
}
}
if (result) {
result = Math.max(1, changeLen - len + 2);
}
return result;
case ExprType.UNARY:
return changeExprCompare(changeExpr, expr.expr, data) ? 1 : 0;
case ExprType.TEXT:
case ExprType.BINARY:
case ExprType.TERTIARY:
return changeExprCompareExprs(changeExpr, expr.segs, data);
case ExprType.INTERP:
if (!changeExprCompare(changeExpr, expr.expr, data)) {
var filterResult;
each(expr.filters, function (filter) {
filterResult = changeExprCompareExprs(changeExpr, filter.args, data);
return !filterResult;
});
return filterResult ? 1 : 0;
}
return 1;
}
return 0;
}
// exports = module.exports = changeExprCompare;
/**
* @file 数据变更类型枚举
* @author errorrik(errorrik@gmail.com)
*/
/**
* 数据变更类型枚举
*
* @const
* @type {Object}
*/
var DataChangeType = {
SET: 1,
SPLICE: 2
};
// exports = module.exports = DataChangeType;
/**
* @file 数据类
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('../parser/expr-type');
// var evalExpr = require('./eval-expr');
// var DataChangeType = require('./data-change-type');
// var parseExpr = require('../parser/parse-expr');
// var each = require('../util/each');
/**
* 数据类
*
* @class
* @param {Object?} data 初始数据
* @param {Model?} parent 父级数据容器
*/
function Data(data, parent) {
this.parent = parent;
this.raw = data || {};
this.listeners = [];
}
// #[begin] error
// // 以下两个函数只在开发模式下可用,在生产模式下不存在
// /**
// * DataTypes 检测
// */
// Data.prototype.checkDataTypes = function () {
// if (this.typeChecker) {
// this.typeChecker(this.raw);
// }
// };
//
// /**
// * 设置 type checker
// *
// * @param {Function} typeChecker 类型校验器
// */
// Data.prototype.setTypeChecker = function (typeChecker) {
// this.typeChecker = typeChecker;
// };
//
// #[end]
/**
* 添加数据变更的事件监听器
*
* @param {Function} listener 监听函数
*/
Data.prototype.listen = function (listener) {
if (typeof listener === 'function') {
this.listeners.push(listener);
}
};
/**
* 移除数据变更的事件监听器
*
* @param {Function} listener 监听函数
*/
Data.prototype.unlisten = function (listener) {
var len = this.listeners.length;
while (len--) {
if (!listener || this.listeners[len] === listener) {
this.listeners.splice(len, 1);
}
}
};
/**
* 触发数据变更
*
* @param {Object} change 变更信息对象
*/
Data.prototype.fire = function (change) {
each(this.listeners, function (listener) {
listener.call(this, change);
}, this);
};
/**
* 获取数据项
*
* @param {string|Object?} expr 数据项路径
* @return {*}
*/
Data.prototype.get = function (expr) {
var value = this.raw;
if (!expr) {
return value;
}
expr = parseExpr(expr);
var paths = expr.paths;
var start = 0;
var l = paths.length;
for (; start < l; start++) {
if (paths[start].value == null) {
break;
}
}
var i = 0;
for (; value != null && i < start; i++) {
value = value[paths[i].value];
}
if (value == null && this.parent) {
value = this.parent.get({
type: ExprType.ACCESSOR,
paths: paths.slice(0, start)
});
}
for (i = start; value != null && i < l; i++) {
value = value[evalExpr(paths[i], this)];
}
return value;
};
/**
* 数据对象变更操作
*
* @inner
* @param {Object|Array} source 要变更的源数据
* @param {Array} exprPaths 属性路径
* @param {*} value 变更属性值
* @param {Data} data 对应的Data对象
* @return {*} 变更后的新数据
*/
function immutableSet(source, exprPaths, value, data) {
if (exprPaths.length === 0) {
return value;
}
var prop = evalExpr(exprPaths[0], data);
var result;
if (source instanceof Array) {
var index = +prop;
if (!isNaN(index)) {
result = source.slice(0);
result[index] = immutableSet(result[index], exprPaths.slice(1), value, data);
return result;
}
}
else if (typeof source === 'object') {
result = {};
for (var key in source) {
if (key !== prop) {
result[key] = source[key];
}
}
result[prop] = immutableSet(source[prop] || {}, exprPaths.slice(1), value, data);
return result;
}
return source;
}
/**
* 设置数据项
*
* @param {string|Object} expr 数据项路径
* @param {*} value 数据值
* @param {Object=} option 设置参数
* @param {boolean} option.silence 静默设置,不触发变更事件
*/
Data.prototype.set = function (expr, value, option) {
option = option || {};
// #[begin] error
// var exprRaw = expr;
// #[end]
expr = parseExpr(expr);
// #[begin] error
// if (expr.type !== ExprType.ACCESSOR) {
// throw new Error('[SAN ERROR] Invalid Expression in Data set: ' + exprRaw);
// }
// #[end]
if (this.get(expr) === value) {
return;
}
this.raw = immutableSet(this.raw, expr.paths, value, this);
!option.silence && this.fire({
type: DataChangeType.SET,
expr: expr,
value: value,
option: option
});
// #[begin] error
// this.checkDataTypes();
// #[end]
};
Data.prototype.splice = function (expr, args, option) {
option = option || {};
// #[begin] error
// var exprRaw = expr;
// #[end]
expr = parseExpr(expr);
// #[begin] error
// if (expr.type !== ExprType.ACCESSOR) {
// throw new Error('[SAN ERROR] Invalid Expression in Data splice: ' + exprRaw);
// }
// #[end]
var target = this.get(expr);
var returnValue = [];
if (target instanceof Array) {
var index = args[0];
if (index < 0 || index > target.length) {
return;
}
var newArray = target.slice(0);
returnValue = newArray.splice.apply(newArray, args);
this.raw = immutableSet(this.raw, expr.paths, newArray, this);
!option.silence && this.fire({
expr: expr,
type: DataChangeType.SPLICE,
index: index,
deleteCount: returnValue.length,
value: returnValue,
insertions: args.slice(2),
option: option
});
}
// #[begin] error
// this.checkDataTypes();
// #[end]
return returnValue;
};
/**
* 数组数据项push操作
*
* @param {string|Object} expr 数据项路径
* @param {*} item 要push的值
* @param {Object=} option 设置参数
* @param {boolean} option.silence 静默设置,不触发变更事件
*/
Data.prototype.push = function (expr, item, option) {
var target = this.get(expr);
if (target instanceof Array) {
this.splice(expr, [target.length, 0, item], option);
}
};
/**
* 数组数据项pop操作
*
* @param {string|Object} expr 数据项路径
* @param {Object=} option 设置参数
* @param {boolean} option.silence 静默设置,不触发变更事件
* @return {*}
*/
Data.prototype.pop = function (expr, option) {
var target = this.get(expr);
if (target instanceof Array) {
var len = target.length;
if (len) {
return this.splice(expr, [len - 1, 1], option)[0];
}
}
};
/**
* 数组数据项shift操作
*
* @param {string|Object} expr 数据项路径
* @param {Object=} option 设置参数
* @param {boolean} option.silence 静默设置,不触发变更事件
* @return {*}
*/
Data.prototype.shift = function (expr, option) {
return this.splice(expr, [0, 1], option)[0];
};
/**
* 数组数据项unshift操作
*
* @param {string|Object} expr 数据项路径
* @param {*} item 要unshift的值
* @param {Object=} option 设置参数
* @param {boolean} option.silence 静默设置,不触发变更事件
*/
Data.prototype.unshift = function (expr, item, option) {
this.splice(expr, [0, 0, item], option);
};
/**
* 数组数据项移除操作
*
* @param {string|Object} expr 数据项路径
* @param {number} index 要移除项的索引
* @param {Object=} option 设置参数
* @param {boolean} option.silence 静默设置,不触发变更事件
*/
Data.prototype.removeAt = function (expr, index, option) {
this.splice(expr, [index, 1], option);
};
/**
* 数组数据项移除操作
*
* @param {string|Object} expr 数据项路径
* @param {*} value 要移除的项
* @param {Object=} option 设置参数
* @param {boolean} option.silence 静默设置,不触发变更事件
*/
Data.prototype.remove = function (expr, value, option) {
var target = this.get(expr);
if (target instanceof Array) {
var len = target.length;
while (len--) {
if (target[len] === value) {
this.splice(expr, [len, 1], option);
break;
}
}
}
};
// exports = module.exports = Data;
/**
* @file 生命周期类
* @author errorrik(errorrik@gmail.com)
*/
/* eslint-disable fecs-valid-var-jsdoc */
/**
* 节点生命周期信息
*
* @inner
* @type {Object}
*/
var LifeCycles = {
compiled: {
compiled: 1
},
inited: {
compiled: 1,
inited: 1
},
painting: {
compiled: 1,
inited: 1,
painting: 1
},
created: {
compiled: 1,
inited: 1,
created: 1
},
attached: {
compiled: 1,
inited: 1,
created: 1,
attached: 1
},
detached: {
compiled: 1,
inited: 1,
created: 1,
detached: 1
},
disposed: {
disposed: 1
}
};
/* eslint-enable fecs-valid-var-jsdoc */
/**
* 生命周期类
*
* @class
*/
function LifeCycle() {
this.raw = {};
}
/**
* 设置生命周期
*
* @param {string} name 生命周期名称
*/
LifeCycle.prototype.set = function (name) {
var phase = LifeCycles[name];
if (phase) {
this.raw = phase;
}
};
/**
* 是否位于生命周期
*
* @param {string} name 生命周期名称
* @return {boolean}
*/
LifeCycle.prototype.is = function (name) {
return this.raw[name];
};
// exports = module.exports = LifeCycle;
/**
* @file 字符串连接时是否使用老式的兼容方案
* @author errorrik(errorrik@gmail.com)
*/
// var ie = require('./ie');
/**
* 字符串连接时是否使用老式的兼容方案
*
* @inner
* @type {boolean}
*/
var isCompatStrJoin = ie && ie < 8;
// exports = module.exports = isCompatStrJoin;
/**
* @file 往字符串连接对象中添加字符串
* @author errorrik(errorrik@gmail.com)
*/
// var isCompatStrJoin = require('../browser/is-compat-str-join');
/**
* 往字符串连接对象中添加字符串
*
* @param {Object} buf 字符串连接对象
* @param {string} str 要添加的字符串
*/
var pushStrBuffer = isCompatStrJoin
? function (buf, str) {
buf.raw[buf.length++] = str;
}
: function (buf, str) {
buf.raw += str;
};
// exports = module.exports = pushStrBuffer;
/**
* @file 创建桩的html
* @author errorrik(errorrik@gmail.com)
*/
// var pushStrBuffer = require('../runtime/push-str-buffer');
/**
* 创建桩的html
*
* @param {Node} node 节点对象
* @param {Object} buf html串存储对象
*/
function genStumpHTML(node, buf) {
pushStrBuffer(buf, '<!--san:' + node.id + '-->');
}
// exports = module.exports = genStumpHTML;
/**
* @file 初始化节点
* @author errorrik(errorrik@gmail.com)
*/
// var guid = require('../util/guid');
// var isComponent = require('./is-component');
/**
* 初始化节点
*
* @param {Object} options 初始化参数
* @param {ANode} options.aNode 抽象信息节点对象
* @param {Component=} options.owner 所属的组件对象
* @param {Object?} node 节点对象,允许为空。空时将options作为节点对象,避免重复创建
* @return {Object}
*/
function nodeInit(options, node) {
node = node || options || {};
if (node !== options) {
node.owner = options.owner;
node.parent = options.parent;
node.scope = options.scope;
node.aNode = node.aNode || options.aNode;
node.el = options.el;
}
node.parentComponent = isComponent(options.parent)
? options.parent
: options.parent && options.parent.parentComponent,
node.id = (options.el && options.el.id)
|| (options.aNode && options.aNode.id)
|| guid();
return node;
}
// exports = module.exports = nodeInit;
/**
* @file 获取节点 stump 的 comment
* @author errorrik(errorrik@gmail.com)
*/
// #[begin] error
// /**
// * 获取节点 stump 的 comment
// *
// * @param {HTMLElement} el HTML元素
// */
// function warnSetHTML(el) {
// // dont warn if not in browser runtime
// if (!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document)) {
// return;
// }
//
// // some html elements cannot set innerHTML in old ie
// // see: https://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
// if (/^(col|colgroup|frameset|style|table|tbody|tfoot|thead|tr|select)$/i.test(el.tagName)) {
// var message = '[SAN WARNING] set html for element "' + el.tagName
// + '" may cause an error in old IE';
// /* eslint-disable no-console */
// if (typeof console === 'object' && console.warn) {
// console.warn(message);
// }
// else {
// throw new Error(message);
// }
// /* eslint-enable no-console */
// }
// }
// #[end]
// exports = module.exports = warnSetHTML;
/**
* @file 判断是否结束桩
* @author errorrik(errorrik@gmail.com)
*/
// #[begin] reverse
// /**
// * 判断是否结束桩
// *
// * @param {HTMLElement|HTMLComment} target 要判断的元素
// * @param {string} type 桩类型
// * @return {boolean}
// */
// function isEndStump(target, type) {
// return target.nodeType === 8 && target.data === '/s-' + type;
// }
// #[end]
// exports = module.exports = isEndStump;
/**
* @file 创建 text 节点
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var removeEl = require('../browser/remove-el');
// var createANode = require('../parser/create-a-node');
// var ExprType = require('../parser/expr-type');
// var pushStrBuffer = require('../runtime/push-str-buffer');
// var changeExprCompare = require('../runtime/change-expr-compare');
// var nodeInit = require('./node-init');
// var NodeType = require('./node-type');
// var nodeEvalExpr = require('./node-eval-expr');
// var warnSetHTML = require('./warn-set-html');
// var isEndStump = require('./is-end-stump');
/**
* 创建 text 节点
*
* @param {Object} options 初始化参数
* @param {ANode} options.aNode 抽象信息节点对象
* @param {Component=} options.owner 所属的组件对象
* @return {Object}
*/
function createText(options) {
var node = nodeInit(options);
node._type = NodeType.TEXT;
node.dispose = textOwnDispose;
node._attachHTML = textOwnAttachHTML;
node._update = textOwnUpdate;
// #[begin] reverse
// // from el
// if (node.el) {
// node.aNode = createANode({
// isText: 1,
// text: options.stumpText
// });
//
// node.parent._pushChildANode(node.aNode);
//
// /* eslint-disable no-constant-condition */
// while (1) {
// /* eslint-enable no-constant-condition */
// var next = options.elWalker.next;
// if (isEndStump(next, 'text')) {
// options.elWalker.goNext();
// removeEl(next);
// break;
// }
//
// options.elWalker.goNext();
// }
//
// removeEl(node.el);
// node.el = null;
// }
// #[end]
node._static = node.aNode.textExpr.value;
return node;
}
/**
* 销毁 text 节点
*/
function textOwnDispose() {
this._prev = null;
this.el = null;
this.content = null;
}
/**
* attach text 节点的 html
*
* @param {Object} buf html串存储对象
*/
function textOwnAttachHTML(buf) {
this.content = nodeEvalExpr(this, this.aNode.textExpr, 1);
pushStrBuffer(buf, this.content);
}
/* eslint-disable max-depth */
/**
* 更新 text 节点的视图
*
* @param {Array} changes 数据变化信息
*/
function textOwnUpdate(changes) {
var me = this;
var len = changes ? changes.length : 0;
while (len--) {
if (changeExprCompare(changes[len].expr, this.aNode.textExpr, this.scope)) {
var text = nodeEvalExpr(this, this.aNode.textExpr, 1);
if (text !== this.content) {
this.content = text;
// 无 stump 元素,所以需要根据组件结构定位
if (!this._located) {
each(this.parent.childs, function (child, i) {
if (child === me) {
me._prev = me.parent.childs[i - 1];
return false;
}
});
this._located = 1;
}
// 两种 update 模式
// 1. 单纯的 text node
// 2. 可能是复杂的 html 结构
if (!me.updateMode) {
me.updateMode = 1;
each(this.aNode.textExpr.segs, function (seg) {
if (seg.type === ExprType.INTERP) {
each(seg.filters, function (filter) {
switch (filter.name) {
case 'html':
case 'url':
return;
}
me.updateMode = 2;
return false;
});
}
return me.updateMode < 2;
});
}
var parentEl = this.parent._getEl();
if (me.updateMode === 1) {
if (me.el) {
me.el[typeof me.el.textContent === 'string' ? 'textContent' : 'data'] = text;
}
else {
var el = me._prev && me._prev._getEl().nextSibling || parentEl.firstChild;
if (el) {
switch (el.nodeType) {
case 3:
me.el = el;
me.el[typeof me.el.textContent === 'string' ? 'textContent' : 'data'] = text;
break;
case 1:
el.insertAdjacentHTML('beforebegin', text);
break;
default:
me.el = document.createTextNode(text);
parentEl.insertBefore(me.el, el);
}
}
else {
parentEl.insertAdjacentHTML('beforeend', text);
}
}
}
else {
var insertBeforeEl = me._prev && me._prev._getEl().nextSibling || parentEl.firstChild;
var startRemoveEl = insertBeforeEl;
while (startRemoveEl && !/^_san_/.test(startRemoveEl.id)) {
insertBeforeEl = startRemoveEl.nextSibling;
removeEl(startRemoveEl);
startRemoveEl = insertBeforeEl;
}
// #[begin] error
// warnSetHTML(parentEl);
// #[end]
if (insertBeforeEl) {
insertBeforeEl.insertAdjacentHTML('beforebegin', text);
}
else if (me._prev) {
me._prev._getEl().insertAdjacentHTML('afterend', text);
}
else {
parentEl.innerHTML = text;
}
}
}
return;
}
}
}
/* eslint-enable max-depth */
// exports = module.exports = createText;
/**
* @file 判断变更是否来源于元素
* @author errorrik(errorrik@gmail.com)
*/
/**
* 判断变更是否来源于元素,来源于元素时,视图更新需要阻断
*
* @param {Object} change 变更对象
* @param {Element} element 元素
* @param {string?} propName 属性名,可选。需要精确判断是否来源于此属性时传入
* @return {boolean}
*/
function isDataChangeByElement(change, element, propName) {
var changeTarget = change.option.target;
return changeTarget && changeTarget.id === element.id
&& (!propName || changeTarget.prop === propName);
}
// exports = module.exports = isDataChangeByElement;
/**
* @file 声明式事件的监听函数
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var evalExpr = require('../runtime/eval-expr');
// var ExprType = require('../parser/expr-type');
/**
* 声明式事件的监听函数
*
* @param {Object} eventBind 绑定信息对象
* @param {boolean} isComponentEvent 是否组件自定义事件
* @param {Model} model 数据环境
* @param {Event} e 事件对象
*/
function eventDeclarationListener(eventBind, isComponentEvent, model, e) {
var args = [];
var expr = eventBind.expr;
each(expr.args, function (argExpr) {
args.push(argExpr.type === ExprType.ACCESSOR
&& argExpr.paths.length === 1
&& argExpr.paths[0].value === '$event'
? (isComponentEvent ? e : e || window.event)
: evalExpr(argExpr, model)
);
});
var method = this[expr.name];
if (typeof method === 'function') {
method.apply(this, args);
}
}
// exports = module.exports = eventDeclarationListener;
/**
* @file 生成元素标签起始的html
* @author errorrik(errorrik@gmail.com)
*/
// var evalExpr = require('../runtime/eval-expr');
// var pushStrBuffer = require('../runtime/push-str-buffer');
// var isComponent = require('./is-component');
// var getPropHandler = require('./get-prop-handler');
// var nodeEvalExpr = require('./node-eval-expr');
/**
* 生成元素标签起始的html
*
* @param {Element} element 元素
* @param {Object} buf html串存储对象
*/
function genElementStartHTML(element, buf) {
if (!element.tagName) {
return;
}
pushStrBuffer(buf, '<' + element.tagName + ' id="' + element.id + '"');
element.props.each(function (prop) {
var attr = prop.attr;
if (!attr) {
element.dynamicProps.push(prop);
var value = isComponent(element)
? evalExpr(prop.expr, element.data, element)
: nodeEvalExpr(element, prop.expr, 1);
attr = getPropHandler(element, prop.name).attr(element, prop.name, value);
}
pushStrBuffer(buf, attr || '');
});
pushStrBuffer(buf, '>');
}
// exports = module.exports = genElementStartHTML;
/**
* @file 生成元素标签结束的html
* @author errorrik(errorrik@gmail.com)
*/
// var autoCloseTags = require('../browser/auto-close-tags');
// var pushStrBuffer = require('../runtime/push-str-buffer');
/**
* 生成元素标签结束的html
*
* @inner
* @param {Element} element 元素
* @param {Object} buf html串存储对象
*/
function genElementEndHTML(element, buf) {
var tagName = element.tagName;
if (!autoCloseTags[tagName]) {
pushStrBuffer(buf, '</' + tagName + '>');
}
}
// exports = module.exports = genElementEndHTML;
/**
* @file attaching 的 element 和 component 池
完成 html fill 后执行 attached 操作,进行事件绑定等后续行为
* @author errorrik(errorrik@gmail.com)
*/
/**
* attaching 的 element 和 component 集合
*
* @inner
* @type {Array}
*/
var attachingNodes = [];
/**
* attaching 操作对象
*
* @type {Object}
*/
var attachings = {
/**
* 添加 attaching 的 element 或 component
*
* @param {Object|Component} node attaching的node
*/
add: function (node) {
attachingNodes.push(node);
},
/**
* 执行 attaching 完成行为
*/
done: function () {
for (var i = 0, l = attachingNodes.length; i < l; i++) {
var node = attachingNodes[i];
node._attached();
}
attachingNodes = [];
}
};
// exports = module.exports = attachings;
/**
* @file 解析元素自身的 ANode
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var createANode = require('./create-a-node');
// var integrateAttr = require('./integrate-attr');
// #[begin] reverse
// /**
// * 解析元素自身的 ANode
// *
// * @param {HTMLElement} el 页面元素
// * @return {ANode}
// */
// function parseANodeFromEl(el) {
// var aNode = createANode();
// aNode.tagName = el.tagName.toLowerCase();
//
// each(
// el.attributes,
// function (attr) {
// integrateAttr(aNode, attr.name, attr.value, 1);
// }
// );
//
// return aNode;
// }
// #[end]
// exports = module.exports = parseANodeFromEl;
/**
* @file 创建 element 节点
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var IndexedList = require('../util/indexed-list');
// var changeExprCompare = require('../runtime/change-expr-compare');
// var attachings = require('./attachings');
// var parseANodeFromEl = require('../parser/parse-anode-from-el');
// var fromElInitChilds = require('./from-el-init-childs');
// var isDataChangeByElement = require('./is-data-change-by-element');
// var nodeInit = require('./node-init');
// var nodeEvalExpr = require('./node-eval-expr');
// var elementUpdateChilds = require('./element-update-childs');
// var elementOwnAttachHTML = require('./element-own-attach-html');
// var elementOwnCreate = require('./element-own-create');
// var elementOwnAttach = require('./element-own-attach');
// var elementOwnDetach = require('./element-own-detach');
// var elementOwnDispose = require('./element-own-dispose');
// var elementOwnGetEl = require('./element-own-get-el');
// var elementOwnOnEl = require('./element-own-on-el');
// var elementAttached = require('./element-attached');
// var elementSetElProp = require('./element-set-el-prop');
// var elementInitProps = require('./element-init-props');
// var elementInitTagName = require('./element-init-tag-name');
// var elementOwnPushChildANode = require('./element-own-push-child-anode');
// var warnSetHTML = require('./warn-set-html');
/**
* 创建 element 节点
*
* @param {Object} options 初始化参数
* @param {ANode} options.aNode 抽象信息节点对象
* @param {Component=} options.owner 所属的组件对象
* @return {Object}
*/
function createElement(options) {
var node = nodeInit(options);
// init methods
node.attach = elementOwnAttach;
node.detach = elementOwnDetach;
node.dispose = elementOwnDispose;
node._attachHTML = elementOwnAttachHTML;
node._update = elementOwnUpdate;
node._create = elementOwnCreate;
node._attached = elementOwnAttached;
node._getEl = elementOwnGetEl;
node._toPhase = elementOwnToPhase;
node._onEl = elementOwnOnEl;
elementInitProps(node);
// #[begin] reverse
// node._pushChildANode = elementOwnPushChildANode;
//
// if (node.el) {
// node.aNode = parseANodeFromEl(node.el);
// node.parent && node.parent._pushChildANode(node.aNode);
// node.tagName = node.aNode.tagName;
//
// if (!node.aNode.directives.get('html')) {
// fromElInitChilds(node);
// }
// node.el.id = node.id;
//
// node.dynamicProps = new IndexedList();
// node.aNode.props.each(function (prop) {
// if (!prop.attr) {
// node.dynamicProps.push(prop);
// }
// });
// attachings.add(node);
// }
// #[end]
elementInitTagName(node);
node.props = node.aNode.props;
node.binds = node.aNode.binds || node.aNode.props;
node._toPhase('inited');
return node;
}
/**
* 视图更新函数
*
* @param {Array} changes 数据变化信息
*/
function elementOwnUpdate(changes) {
this._getEl();
var me = this;
this.dynamicProps.each(function (prop) {
if (prop.expr.value) {
return;
}
each(changes, function (change) {
if (!isDataChangeByElement(change, me, prop.name)
&& (
changeExprCompare(change.expr, prop.expr, me.scope)
|| prop.hintExpr && changeExprCompare(change.expr, prop.hintExpr, me.scope)
)
) {
elementSetElProp(me, prop.name, nodeEvalExpr(me, prop.expr));
return false;
}
});
});
var htmlDirective = this.aNode.directives.get('html');
if (htmlDirective) {
each(changes, function (change) {
if (changeExprCompare(change.expr, htmlDirective.value, me.scope)) {
// #[begin] error
// warnSetHTML(me.el);
// #[end]
me.el.innerHTML = nodeEvalExpr(me, htmlDirective.value);
return false;
}
});
}
else {
elementUpdateChilds(this, changes);
}
}
/**
* 执行完成attached状态的行为
*/
function elementOwnAttached() {
elementAttached(this);
}
/**
* 使节点到达相应的生命周期
*
* @param {string} name 生命周期名称
*/
function elementOwnToPhase(name) {
this.lifeCycle.set(name);
}
// exports = module.exports = createElement;
/**
* @file 创建节点的工厂方法
* @author errorrik(errorrik@gmail.com)
*/
// var isComponent = require('./is-component');
// var createText = require('./create-text');
// var createElement = require('./create-element');
// var createSlot = require('./create-slot');
// var createFor = require('./create-for');
// var createIf = require('./create-if');
/**
* 创建节点
*
* @param {ANode} aNode 抽象节点
* @param {Node} parent 父亲节点
* @param {Model=} scope 所属数据环境
* @return {Node}
*/
function createNode(aNode, parent, scope) {
var owner = isComponent(parent) ? parent : parent.owner;
scope = scope || (isComponent(parent) ? parent.data : parent.scope);
var options = {
aNode: aNode,
owner: owner,
scope: scope,
parent: parent
};
if (aNode.isText) {
return createText(options);
}
if (aNode.directives.get('if')) {
return createIf(options);
}
if (aNode.directives.get('for')) {
return createFor(options);
}
var ComponentType = owner.components[aNode.tagName];
if (ComponentType) {
options.subTag = aNode.tagName;
return new ComponentType(options);
}
if (aNode.tagName === 'slot') {
return createSlot(options);
}
return createElement(options);
}
// exports = module.exports = createNode;
/**
* @file 通过存在的 el 创建节点的工厂方法
* @author errorrik(errorrik@gmail.com)
*/
// var parseTemplate = require('../parser/parse-template');
// var parseANodeFromEl = require('../parser/parse-anode-from-el');
// var NodeType = require('./node-type');
// var isComponent = require('./is-component');
// var createText = require('./create-text');
// var createElement = require('./create-element');
// var createIf = require('./create-if');
// var createFor = require('./create-for');
// var createSlot = require('./create-slot');
// #[begin] reverse
// /**
// * 通过存在的 el 创建节点
// *
// * @param {HTMLElement} el 页面中存在的元素
// * @param {Node} parent 父亲节点
// * @param {DOMChildsWalker} elWalker 遍历元素的功能对象
// * @param {Model=} scope 所属数据环境
// * @return {Node}
// */
// function createNodeByEl(el, parent, elWalker, scope) {
// var owner = isComponent(parent) ? parent : parent.owner;
// scope = scope || (isComponent(parent) ? parent.data : parent.scope);
//
// var option = {
// owner: owner,
// scope: scope,
// parent: parent,
// el: el,
// elWalker: elWalker
// };
//
// // comment as stump
// if (el.nodeType === 8) {
// var stumpMatch = el.data.match(/^\s*s-([a-z]+)(:[\s\S]+)?$/);
//
// if (stumpMatch) {
// option.stumpText = stumpMatch[2] ? stumpMatch[2].slice(1) : '';
//
// switch (stumpMatch[1]) {
// case 'text':
// return createText(option);
//
// case 'for':
// return createFor(option);
//
// case 'slot':
// return createSlot(option);
//
// case 'if':
// return createIf(option);
//
//
// case 'else':
// case 'elif':
// createNodeByElseStump(option, stumpMatch[1]);
// return;
//
// case 'data':
// // fill component data
// var data = (new Function(
// 'return ' + option.stumpText.replace(/^[\s\n]*/, '')
// ))();
//
// /* eslint-disable guard-for-in */
// for (var key in data) {
// owner.data.set(key, data[key]);
// }
// /* eslint-enable guard-for-in */
//
// return;
// }
// }
//
// return;
// }
//
// // element as anything
// var tagName = el.tagName.toLowerCase();
// var childANode = parseANodeFromEl(el);
// option.aNode = childANode;
//
// // find component class
// var ComponentClass = null;
// if (tagName.indexOf('-') > 0) {
// ComponentClass = owner.components[tagName];
// }
//
// var componentName = el.getAttribute('s-component');
// if (componentName) {
// ComponentClass = owner.components[componentName];
// childANode.tagName = componentName;
// }
//
//
// if (childANode.directives.get('if')) {
// return createIf(option);
// }
//
// if (childANode.directives.get('else')) {
// return createNodeByElseEl(option, 'else');
// }
//
// if (childANode.directives.get('elif')) {
// return createNodeByElseEl(option, 'elif');
// }
//
//
// // as Component
// if (ComponentClass) {
// return new ComponentClass(option);
// }
//
// // as Element
// return createElement(option);
// }
//
// function createNodeByElseEl(option, type) {
// var parentChilds = option.parent.childs;
// var len = parentChilds.length;
//
// matchif: while (len--) {
// var ifNode = parentChilds[len];
// switch (ifNode._type) {
// case NodeType.TEXT:
// continue matchif;
//
// case NodeType.IF:
// if (!ifNode.aNode.elses) {
// ifNode.aNode.elses = [];
// }
// ifNode.aNode.elses.push(option.aNode);
// ifNode.elseIndex = ifNode.aNode.elses.length - 1;
//
// option.el.removeAttribute('san-' + type);
// option.el.removeAttribute('s-' + type);
//
// var elseChild = createNodeByEl(option.el, ifNode, option.elWalker);
// ifNode.childs[0] = elseChild;
// option.aNode.childs = option.aNode.childs.slice(0);
// break matchif;
// }
//
// throw new Error('[SAN FATEL] ' + type + ' not match if.');
// }
// }
//
// function createNodeByElseStump(option, type) {
// var parentChilds = option.parent.childs;
// var len = parentChilds.length;
//
// matchif: while (len--) {
// var ifNode = parentChilds[len];
// switch (ifNode._type) {
// case NodeType.TEXT:
// continue matchif;
//
// case NodeType.IF:
// if (!ifNode.aNode.elses) {
// ifNode.aNode.elses = [];
// }
//
// var elseANode;
// switch (type) {
// case 'else':
// elseANode = parseTemplate(
// option.stumpText.replace('san-else', '').replace('s-else', '')
// ).childs[0];
// elseANode.directives.push({
// value: 1,
// name: type
// });
//
// break;
//
// case 'elif':
// elseANode = parseTemplate(
// option.stumpText.replace('san-elif', 's-if').replace('s-elif', 's-if')
// ).childs[0];
//
// var ifDirective = elseANode.directives.get('if');
// elseANode.directives.remove('if');
// ifDirective.name = 'elif';
// elseANode.directives.push(ifDirective);
//
// break;
// }
//
// ifNode.aNode.elses.push(elseANode);
// break matchif;
// }
//
// throw new Error('[SAN FATEL] ' + type + ' not match if.');
// }
// }
// #[end]
// exports = module.exports = createNodeByEl;
/**
* @file 获取节点 stump 的父元素
* @author errorrik(errorrik@gmail.com)
*/
/**
* 获取节点 stump 的父元素
* if、for 节点的 el stump 是 comment node,在 IE 下还可能不存在
* 获取其父元素通常用于 el 的查找,以及视图变更的插入操作
*
* @param {Node} node 节点对象
* @return {HTMLElement}
*/
function getNodeStumpParent(node) {
if (node.el) {
return node.el.parentNode;
}
var parentNode = node.parent._getEl();
while (parentNode && parentNode.nodeType !== 1) {
parentNode = parentNode.parentNode;
}
return parentNode;
}
// exports = module.exports = getNodeStumpParent;
/**
* @file 更新元素的子元素视图
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
/**
* 更新元素的子元素视图
*
* @param {Object} element 要更新的元素
* @param {Array} changes 数据变化信息
* @param {string} slotChildsName 子slot名称
*/
function elementUpdateChilds(element, changes, slotChildsName) {
each(element.childs, function (child) {
child._update(changes);
});
each(element[slotChildsName || 'slotChilds'], function (child) {
elementUpdateChilds(child, changes);
});
}
// exports = module.exports = elementUpdateChilds;
/**
* @file 销毁释放元素的子元素
* @author errorrik(errorrik@gmail.com)
*/
/**
* 销毁释放元素的子元素
*
* @param {Object} element 元素节点
* @param {boolean} dontDetach 是否不要将节点从DOM移除
*/
function elementDisposeChilds(element, dontDetach) {
var childs = element.childs;
if (childs instanceof Array) {
var len = childs.length;
while (len--) {
childs[len].dispose(dontDetach);
}
childs.length = 0;
}
}
// exports = module.exports = elementDisposeChilds;
/**
* @file 销毁节点,清空节点上的无用成员
* @author errorrik(errorrik@gmail.com)
*/
/**
* 销毁节点
*
* @param {Object} node 节点对象
*/
function nodeDispose(node) {
node.el = null;
node.owner = null;
node.scope = null;
node.aNode = null;
node.parent = null;
node.parentComponent = null;
node.childs = null;
}
// exports = module.exports = nodeDispose;
/**
* @file 简单执行销毁节点的行为
* @author errorrik(errorrik@gmail.com)
*/
// var removeEl = require('../browser/remove-el');
// var nodeDispose = require('./node-dispose');
// var elementDisposeChilds = require('./element-dispose-childs');
/**
* 简单执行销毁节点的行为
*
* @param {boolean} dontDetach 是否不要将节点移除
*/
function nodeOwnSimpleDispose(dontDetach) {
elementDisposeChilds(this, dontDetach);
if (!dontDetach) {
removeEl(this._getEl());
}
nodeDispose(this);
}
// exports = module.exports = nodeOwnSimpleDispose;
/**
* @file 获取节点 stump 的 comment
* @author errorrik(errorrik@gmail.com)
*/
// var getNodeStumpParent = require('./get-node-stump-parent');
/**
* 获取节点 stump 的 comment
*
* @param {Node} node 节点对象
* @return {Comment}
*/
function getNodeStump(node) {
if (typeof node.el === 'undefined') {
var parentNode = getNodeStumpParent(node);
var el = parentNode.firstChild;
while (el) {
if (el.nodeType === 8
&& el.data.indexOf('san:') === 0
&& el.data.replace('san:', '') === node.id
) {
break;
}
el = el.nextSibling;
}
node.el = el;
}
return node.el;
}
// exports = module.exports = getNodeStump;
/**
* @file 获取节点对应的 stump 主元素
* @author errorrik(errorrik@gmail.com)
*/
// var getNodeStump = require('./get-node-stump');
/**
* 获取节点对应的 stump 主元素
*
* @return {Comment}
*/
function nodeOwnGetStumpEl() {
return getNodeStump(this);
}
// exports = module.exports = nodeOwnGetStumpEl;
/**
* @file 创建 if 指令元素
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var empty = require('../util/empty');
// var IndexedList = require('../util/indexed-list');
// var parseTemplate = require('../parser/parse-template');
// var createANode = require('../parser/create-a-node');
// var genStumpHTML = require('./gen-stump-html');
// var nodeInit = require('./node-init');
// var NodeType = require('./node-type');
// var nodeEvalExpr = require('./node-eval-expr');
// var createNode = require('./create-node');
// var createNodeByEl = require('./create-node-by-el');
// var getNodeStumpParent = require('./get-node-stump-parent');
// var elementUpdateChilds = require('./element-update-childs');
// var elementDisposeChilds = require('./element-dispose-childs');
// var nodeOwnSimpleDispose = require('./node-own-simple-dispose');
// var nodeOwnGetStumpEl = require('./node-own-get-stump-el');
/**
* 创建 if 指令元素
*
* @param {Object} options 初始化参数
* @return {Object}
*/
function createIf(options) {
var node = nodeInit(options);
node.childs = [];
node._type = NodeType.IF;
node.dispose = nodeOwnSimpleDispose;
node._getEl = nodeOwnGetStumpEl;
node._attachHTML = ifOwnAttachHTML;
node._update = ifOwnUpdate;
// #[begin] reverse
// node._pushChildANode = empty;
// #[end]
// #[begin] reverse
// if (options.el) {
// if (options.el.nodeType === 8) {
// var aNode = parseTemplate(options.stumpText).childs[0];
// node.aNode = aNode;
// }
// else {
// node.elseIndex = -1;
// var el = document.createComment('san:' + this.id);
// options.el.parentNode.insertBefore(el, options.el.nextSibling);
//
//
// options.el.removeAttribute('san-if');
// options.el.removeAttribute('s-if');
//
// var child = createNodeByEl(options.el, node, options.elWalker);
// node.childs[0] = child;
// node.aNode.childs = child.aNode.childs.slice(0);
//
// node.el = el;
// }
//
// node.parent._pushChildANode(node.aNode);
// }
// #[end]
node.cond = node.aNode.directives.get('if').value;
return node;
}
/**
* 创建 if 指令对应条件为 true 时对应的元素
*
* @inner
* @param {ANode} directiveANode 指令ANode
* @param {IfDirective} mainIf 主if元素
* @return {Element}
*/
function createIfDirectiveChild(directiveANode, mainIf) {
var childANode = createANode({
childs: directiveANode.childs,
props: directiveANode.props,
events: directiveANode.events,
tagName: directiveANode.tagName,
directives: (new IndexedList()).concat(directiveANode.directives)
});
childANode.directives.remove('if');
childANode.directives.remove('else');
childANode.directives.remove('elif');
return createNode(childANode, mainIf);
}
/**
* attach元素的html
*
* @param {Object} buf html串存储对象
*/
function ifOwnAttachHTML(buf) {
var me = this;
var elseIndex;
var child;
if (nodeEvalExpr(me, me.cond)) {
child = createIfDirectiveChild(me.aNode, me);
elseIndex = -1;
}
else {
each(me.aNode.elses, function (elseANode, index) {
var elif = elseANode.directives.get('elif');
if (!elif || elif && nodeEvalExpr(me, elif.value)) {
child = createIfDirectiveChild(elseANode, me);
elseIndex = index;
return false;
}
});
}
if (child) {
me.childs[0] = child;
child._attachHTML(buf);
me.elseIndex = elseIndex;
}
genStumpHTML(this, buf);
}
/**
* 视图更新函数
*
* @param {Array} changes 数据变化信息
*/
function ifOwnUpdate(changes) {
var me = this;
var childANode = me.aNode;
var elseIndex;
if (nodeEvalExpr(this, this.cond)) {
elseIndex = -1;
}
else {
each(me.aNode.elses, function (elseANode, index) {
var elif = elseANode.directives.get('elif');
if (elif && nodeEvalExpr(me, elif.value) || !elif) {
elseIndex = index;
childANode = elseANode;
return false;
}
});
}
if (elseIndex === me.elseIndex) {
elementUpdateChilds(me, changes);
}
else {
elementDisposeChilds(me);
if (typeof elseIndex !== 'undefined') {
var child = createIfDirectiveChild(childANode, me);
var parentEl = getNodeStumpParent(me);
child.attach(parentEl, me._getEl() || parentEl.firstChild);
me.childs[0] = child;
}
me.elseIndex = elseIndex;
}
}
// exports = module.exports = createIf;
/**
* @file 创建字符串连接对象,用于跨平台提高性能的字符串连接,万一不小心支持老式浏览器了呢
* @author errorrik(errorrik@gmail.com)
*/
// var isCompatStrJoin = require('../browser/is-compat-str-join');
/**
* 创建字符串连接对象
*
* @return {Object}
*/
function createStrBuffer() {
return {
raw: isCompatStrJoin ? [] : '',
length: 0
};
}
// exports = module.exports = createStrBuffer;
/**
* @file 字符串化字符串连接对象
* @author errorrik(errorrik@gmail.com)
*/
// var isCompatStrJoin = require('../browser/is-compat-str-join');
/**
* 字符串化字符串连接对象
*
* @param {Object} buf 字符串连接对象
* @return {string}
*/
var stringifyStrBuffer = isCompatStrJoin
? function (buf) {
return buf.raw.join('');
}
: function (buf) {
return buf.raw;
};
// exports = module.exports = stringifyStrBuffer;
/**
* @file 创建节点对应的 stump comment 元素
* @author errorrik(errorrik@gmail.com)
*/
/**
* 创建节点对应的 stump comment 主元素
*/
function nodeOwnCreateStump() {
this.el = this.el || document.createComment('san:' + this.id);
}
// exports = module.exports = nodeOwnCreateStump;
/**
* @file 创建 for 指令元素
* @author errorrik(errorrik@gmail.com)
*/
// var empty = require('../util/empty');
// var extend = require('../util/extend');
// var inherits = require('../util/inherits');
// var each = require('../util/each');
// var IndexedList = require('../util/indexed-list');
// var parseTemplate = require('../parser/parse-template');
// var createANode = require('../parser/create-a-node');
// var ExprType = require('../parser/expr-type');
// var parseExpr = require('../parser/parse-expr');
// var Data = require('../runtime/data');
// var DataChangeType = require('../runtime/data-change-type');
// var changeExprCompare = require('../runtime/change-expr-compare');
// var createStrBuffer = require('../runtime/create-str-buffer');
// var stringifyStrBuffer = require('../runtime/stringify-str-buffer');
// var removeEl = require('../browser/remove-el');
// var attachings = require('./attachings');
// var genStumpHTML = require('./gen-stump-html');
// var nodeInit = require('./node-init');
// var NodeType = require('./node-type');
// var nodeEvalExpr = require('./node-eval-expr');
// var createNode = require('./create-node');
// var createNodeByEl = require('./create-node-by-el');
// var isEndStump = require('./is-end-stump');
// var getNodeStumpParent = require('./get-node-stump-parent');
// var nodeOwnSimpleDispose = require('./node-own-simple-dispose');
// var nodeOwnCreateStump = require('./node-own-create-stump');
// var nodeOwnGetStumpEl = require('./node-own-get-stump-el');
// var elementDisposeChilds = require('./element-dispose-childs');
// var warnSetHTML = require('./warn-set-html');
/**
* 循环项的数据容器类
*
* @inner
* @class
* @param {Object} forElement for元素对象
* @param {*} item 当前项的数据
* @param {number} index 当前项的索引
*/
function ForItemData(forElement, item, index) {
this.parent = forElement.scope;
this.raw = {};
this.listeners = [];
this.directive = forElement.aNode.directives.get('for');
this.raw[this.directive.item.raw] = item;
this.raw[this.directive.index.raw] = index;
}
/**
* 将数据操作的表达式,转换成为对parent数据操作的表达式
* 主要是对item和index进行处理
*
* @param {Object} expr 表达式
* @return {Object}
*/
ForItemData.prototype.exprResolve = function (expr) {
var directive = this.directive;
var me = this;
function resolveItem(expr) {
if (expr.type === ExprType.ACCESSOR
&& expr.paths[0].value === directive.item.paths[0].value
) {
return {
type: ExprType.ACCESSOR,
paths: directive.list.paths.concat(
{
type: ExprType.NUMBER,
value: me.get(directive.index)
},
expr.paths.slice(1)
)
};
}
return expr;
}
expr = resolveItem(expr);
var resolvedPaths = [];
each(expr.paths, function (item) {
resolvedPaths.push(
item.type === ExprType.ACCESSOR
&& item.paths[0].value === directive.index.paths[0].value
? {
type: ExprType.NUMBER,
value: me.get(directive.index)
}
: resolveItem(item)
);
});
return {
type: ExprType.ACCESSOR,
paths: resolvedPaths
};
};
// 代理数据操作方法
inherits(ForItemData, Data);
each(
['set', 'remove', 'unshift', 'shift', 'push', 'pop', 'splice'],
function (method) {
ForItemData.prototype[method] = function (expr) {
expr = this.exprResolve(parseExpr(expr));
this.parent[method].apply(
this.parent,
[expr].concat(Array.prototype.slice.call(arguments, 1))
);
};
}
);
/**
* 创建 for 指令元素的子元素
*
* @inner
* @param {ForDirective} forElement for 指令元素对象
* @param {*} item 子元素对应数据
* @param {number} index 子元素对应序号
* @return {Element}
*/
function createForDirectiveChild(forElement, item, index) {
var itemScope = new ForItemData(forElement, item, index);
return createNode(forElement.itemANode, forElement, itemScope);
}
/**
* 创建 for 指令元素
*
* @param {Object} options 初始化参数
* @return {Object}
*/
function createFor(options) {
var node = nodeInit(options);
node.childs = [];
node._type = NodeType.FOR;
node.attach = forOwnAttach;
node.detach = forOwnDetach;
node.dispose = nodeOwnSimpleDispose;
node._attachHTML = forOwnAttachHTML;
node._update = forOwnUpdate;
node._create = nodeOwnCreateStump;
node._getEl = nodeOwnGetStumpEl;
// #[begin] reverse
// node._pushChildANode = empty;
// #[end]
var aNode = node.aNode;
// #[begin] reverse
// if (options.el) {
// aNode = parseTemplate(options.stumpText).childs[0];
// node.aNode = aNode;
//
// var index = 0;
// var directive = aNode.directives.get('for');
// var listData = nodeEvalExpr(node, directive.list) || [];
//
// /* eslint-disable no-constant-condition */
// while (1) {
// /* eslint-enable no-constant-condition */
// var next = options.elWalker.next;
// if (isEndStump(next, 'for')) {
// removeEl(options.el);
// node.el = next;
// options.elWalker.goNext();
// break;
// }
//
// var itemScope = new ForItemData(node, listData[index], index);
// var child = createNodeByEl(next, node, options.elWalker, itemScope);
// node.childs.push(child);
//
// index++;
// options.elWalker.goNext();
// }
//
// node.parent._pushChildANode(node.aNode);
// }
// #[end]
node.itemANode = createANode({
childs: aNode.childs,
props: aNode.props,
events: aNode.events,
tagName: aNode.tagName,
directives: (new IndexedList()).concat(aNode.directives)
});
node.itemANode.directives.remove('for');
return node;
}
/**
* attach元素的html
*
* @param {Object} buf html串存储对象
* @param {boolean} onlyChilds 是否只attach列表本身html,不包括stump部分
*/
function forOwnAttachHTML(buf, onlyChilds) {
var me = this;
each(
nodeEvalExpr(me, me.aNode.directives.get('for').list),
function (item, i) {
var child = createForDirectiveChild(me, item, i);
me.childs.push(child);
child._attachHTML(buf);
}
);
if (!onlyChilds) {
genStumpHTML(me, buf);
}
}
/**
* 将元素attach到页面的行为
*
* @param {HTMLElement} parentEl 要添加到的父元素
* @param {HTMLElement=} beforeEl 要添加到哪个元素之前
*/
function forOwnAttach(parentEl, beforeEl) {
this._create();
if (parentEl) {
if (beforeEl) {
parentEl.insertBefore(this.el, beforeEl);
}
else {
parentEl.appendChild(this.el);
}
}
// paint list
var el = this._getEl() || parentEl.firstChild;
var prevEl = el && el.previousSibling;
var buf = createStrBuffer();
prev: while (prevEl) {
switch (prevEl.nodeType) {
case 1:
break prev;
case 3:
if (!/^\s*$/.test(prevEl.textContent)) {
break prev;
}
removeEl(prevEl);
break;
}
prevEl = prevEl.previousSibling;
}
if (!prevEl) {
this._attachHTML(buf, 1);
// #[begin] error
// warnSetHTML(parentEl);
// #[end]
parentEl.insertAdjacentHTML('afterbegin', stringifyStrBuffer(buf));
}
else if (prevEl.nodeType === 1) {
this._attachHTML(buf, 1);
// #[begin] error
// warnSetHTML(parentEl);
// #[end]
prevEl.insertAdjacentHTML('afterend', stringifyStrBuffer(buf));
}
else {
each(
nodeEvalExpr(this, this.aNode.directives.get('for').list),
function (item, i) {
var child = createForDirectiveChild(this, item, i);
this.childs.push(child);
child.attach(parentEl, el);
},
this
);
}
attachings.done();
}
/**
* 将元素从页面上移除的行为
*/
function forOwnDetach() {
if (this.lifeCycle.is('attached')) {
elementDisposeChilds(this, true);
removeEl(this._getEl());
this.lifeCycle.set('detached');
}
}
/**
* 视图更新函数
*
* @param {Array} changes 数据变化信息
*/
function forOwnUpdate(changes) {
var childsChanges = [];
var oldChildsLen = this.childs.length;
each(this.childs, function () {
childsChanges.push([]);
});
var disposeChilds = [];
var forDirective = this.aNode.directives.get('for');
this._getEl();
var parentEl = getNodeStumpParent(this);
var parentFirstChild = parentEl.firstChild;
var parentLastChild = parentEl.lastChild;
var isOnlyParentChild =
oldChildsLen > 0 // 有孩子时
&& parentFirstChild === this.childs[0]._getEl()
&& (parentLastChild === this.el || parentLastChild === this.childs[oldChildsLen - 1]._getEl())
|| oldChildsLen === 0 // 无孩子时
&& parentFirstChild === this.el
&& parentLastChild === this.el
each(changes, function (change) {
var relation = changeExprCompare(change.expr, forDirective.list, this.scope);
if (!relation) {
// 无关时,直接传递给子元素更新,列表本身不需要动
each(childsChanges, function (childChanges) {
childChanges.push(change);
});
}
else if (relation > 2) {
// 变更表达式是list绑定表达式的子项
// 只需要对相应的子项进行更新
var changePaths = change.expr.paths;
var forLen = forDirective.list.paths.length;
change = extend({}, change);
change.expr = {
type: ExprType.ACCESSOR,
paths: forDirective.item.paths.concat(changePaths.slice(forLen + 1))
};
var changeIndex = +nodeEvalExpr(this, changePaths[forLen]);
childsChanges[changeIndex].push(change);
switch (change.type) {
case DataChangeType.SET:
Data.prototype.set.call(
this.childs[changeIndex].scope,
change.expr,
change.value,
{silence: 1}
);
break;
case DataChangeType.SPLICE:
Data.prototype.splice.call(
this.childs[changeIndex].scope,
change.expr,
[].concat(change.index, change.deleteCount, change.insertions),
{silence: 1}
);
break;
}
}
else if (change.type === DataChangeType.SET) {
// 变更表达式是list绑定表达式本身或母项的重新设值
// 此时需要更新整个列表
var oldLen = this.childs.length;
var newList = nodeEvalExpr(this, forDirective.list);
var newLen = newList.length;
// 老的比新的多的部分,标记需要dispose
if (oldLen > newLen) {
disposeChilds = disposeChilds.concat(this.childs.slice(newLen));
childsChanges.length = newLen;
this.childs.length = newLen;
}
// 整项变更
for (var i = 0; i < newLen; i++) {
childsChanges[i] = [
{
type: DataChangeType.SET,
option: change.option,
expr: {
type: ExprType.ACCESSOR,
paths: forDirective.item.paths.slice(0)
},
value: newList[i]
}
];
if (this.childs[i]) {
Data.prototype.set.call(
this.childs[i].scope,
forDirective.item,
newList[i],
{silence: 1}
);
}
else {
this.childs[i] = createForDirectiveChild(this, newList[i], i);
}
}
}
else if (relation === 2 && change.type === DataChangeType.SPLICE) {
// 变更表达式是list绑定表达式本身数组的SPLICE操作
// 此时需要删除部分项,创建部分项
var changeStart = change.index;
var deleteCount = change.deleteCount;
var indexChange = {
type: DataChangeType.SET,
option: change.option,
expr: forDirective.index
};
var insertionsLen = change.insertions.length;
if (insertionsLen !== deleteCount) {
each(this.childs, function (child, index) {
// update child index
if (index >= changeStart + deleteCount) {
childsChanges[index].push(indexChange);
Data.prototype.set.call(
child.scope,
indexChange.expr,
index - deleteCount + insertionsLen,
{silence: 1}
);
}
}, this);
}
var spliceArgs = [changeStart, deleteCount];
var childsChangesSpliceArgs = [changeStart, deleteCount];
each(change.insertions, function (insertion, index) {
spliceArgs.push(createForDirectiveChild(this, insertion, changeStart + index));
childsChangesSpliceArgs.push([]);
}, this);
disposeChilds = disposeChilds.concat(this.childs.splice.apply(this.childs, spliceArgs));
childsChanges.splice.apply(childsChanges, childsChangesSpliceArgs);
}
}, this);
var newChildsLen = this.childs.length;
// 标记 length 是否发生变化
if (newChildsLen !== oldChildsLen) {
var lengthChange = {
type: DataChangeType.SET,
option: {},
expr: {
type: ExprType.ACCESSOR,
paths: forDirective.list.paths.concat({
type: ExprType.STRING,
value: 'length'
})
}
};
each(childsChanges, function (childChanges) {
childChanges.push(lengthChange);
});
}
// 清除应该干掉的 child
var violentClear = isOnlyParentChild && newChildsLen === 0;
each(disposeChilds, function (child) {
child.dispose(violentClear);
});
if (violentClear) {
parentEl.innerHTML = '';
this.el = document.createComment('san:' + this.id);
parentEl.appendChild(this.el);
return;
}
// 对相应的项进行更新
// 如果不attached则直接创建,如果存在则调用更新函数
// var newChildBuf;
// var newChilds;
// for (var i = 0; i < newChildsLen; i++) {
// var child = this.childs[i];
// if (child.lifeCycle.is('attached')) {
// childsChanges[i].length && child._update(childsChanges[i]);
// }
// else {
// newChilds = newChilds || [];
// newChilds.push(child);
// newChildBuf = newChildBuf || createStrBuffer();
// child._attachHTML(newChildBuf);
// var nextChild = this.childs[i + 1];
// if (!nextChild || nextChild.lifeCycle.is('attached')) {
// var beforeEl = nextChild && nextChild._getEl();
// if (!beforeEl) {
// beforeEl = document.createElement('script');
// parentEl.insertBefore(beforeEl, this._getEl() || parentEl.firstChild);
// }
// beforeEl.insertAdjacentHTML('beforebegin', stringifyStrBuffer(newChildBuf));
// newChildBuf = null;
// newChilds = null;
// if (!nextChild) {
// parentEl.removeChild(beforeEl);
// }
// }
// }
// }
// 对相应的项进行更新
// 如果不attached则直接创建,如果存在则调用更新函数
if (oldChildsLen === 0 && isOnlyParentChild) {
var buf = createStrBuffer();
each(
this.childs,
function (child) {
child._attachHTML(buf);
}
);
parentEl.innerHTML = stringifyStrBuffer(buf);
this.el = document.createComment('san:' + this.id);
parentEl.appendChild(this.el);
}
else {
var attachStump = this;
while (newChildsLen--) {
var child = this.childs[newChildsLen];
if (child.lifeCycle.is('attached')) {
childsChanges[newChildsLen].length && child._update(childsChanges[newChildsLen]);
}
else {
child.attach(parentEl, attachStump._getEl() || parentEl.firstChild);
}
attachStump = child;
}
}
attachings.done();
}
// exports = module.exports = createFor;
/**
* @file 生成子元素html
* @author errorrik(errorrik@gmail.com)
*/
// var escapeHTML = require('../runtime/escape-html');
// var pushStrBuffer = require('../runtime/push-str-buffer');
// var each = require('../util/each');
// var createNode = require('./create-node');
// var nodeEvalExpr = require('./node-eval-expr');
/**
* 生成子元素html
*
* @param {Element} element 元素
* @param {Object} buf html串存储对象
*/
function genElementChildsHTML(element, buf) {
if (element.tagName === 'textarea') {
var valueProp = element.props.get('value');
if (valueProp) {
pushStrBuffer(buf, escapeHTML(nodeEvalExpr(element, valueProp.expr)));
}
}
else {
var htmlDirective = element.aNode.directives.get('html');
if (htmlDirective) {
pushStrBuffer(buf, nodeEvalExpr(element, htmlDirective.value));
}
else {
each(element.aNode.childs, function (aNodeChild) {
var child = createNode(aNodeChild, element);
if (!child._static) {
element.childs.push(child);
}
child._attachHTML(buf);
});
}
}
}
// exports = module.exports = genElementChildsHTML;
/**
* @file 添加子节点的 ANode
* @author errorrik(errorrik@gmail.com)
*/
// #[begin] reverse
// /**
// * 添加子节点的 ANode
// * 用于从 el 初始化时,需要将解析的元素抽象成 ANode,并向父级注册
// *
// * @param {ANode} aNode 抽象节点对象
// */
// function elementOwnPushChildANode(aNode) {
// this.aNode.childs.push(aNode);
// }
// #[end]
// exports = module.exports = elementOwnPushChildANode;
/**
* @file 创建 slot 元素
* @author errorrik(errorrik@gmail.com)
*/
// var empty = require('../util/empty');
// var createANode = require('../parser/create-a-node');
// var NodeType = require('./node-type');
// var isEndStump = require('./is-end-stump');
// var genElementChildsHTML = require('./gen-element-childs-html');
// var nodeInit = require('./node-init');
// var nodeDispose = require('./node-dispose');
// var createNodeByEl = require('./create-node-by-el');
// var elementDisposeChilds = require('./element-dispose-childs');
// var elementOwnPushChildANode = require('./element-own-push-child-anode');
/**
* 创建 slot 元素
*
* @param {Object} options 初始化参数
* @return {Object}
*/
function createSlot(options) {
var literalOwner = options.owner;
var aNode = createANode();
// #[begin] reverse
// if (options.el) {
// if (options.stumpText.indexOf('!') !== 0) {
// options.owner = literalOwner.owner;
// options.scope = literalOwner.scope;
// options.stumpText = options.stumpText.slice(1);
// }
// this.name = options.stumpText || '____';
// }
// else {
// #[end]
var nameBind = options.aNode.props.get('name');
this.name = nameBind ? nameBind.raw : '____';
var givenSlots = literalOwner.aNode.givenSlots;
var givenChilds = givenSlots && givenSlots[this.name];
aNode.childs = givenChilds || options.aNode.childs.slice(0);
if (givenChilds) {
options.owner = literalOwner.owner;
options.scope = literalOwner.scope;
}
// #[begin] reverse
// }
// #[end]
options.aNode = aNode;
var node = nodeInit(options);
node.childs = [];
node._type = NodeType.SLOT;
node.dispose = slotOwnDispose;
node._getEl = slotOwnGetEl;
node._attachHTML = slotOwnAttachHTML;
node._update = empty;
// #[begin] reverse
// node._pushChildANode = elementOwnPushChildANode;
// #[end]
var parent = node.parent;
while (parent) {
if (parent === node.owner) {
parent.ownSlotChilds.push(node);
break;
}
if (parent._type !== NodeType.SLOT && parent.owner === node.owner) {
parent.slotChilds.push(node);
break;
}
parent = parent.parent;
}
// #[begin] reverse
// if (options.el) {
// /* eslint-disable no-constant-condition */
// while (1) {
// /* eslint-enable no-constant-condition */
// var next = options.elWalker.next;
// if (!next || isEndStump(next, 'slot')) {
// next && options.elWalker.goNext();
// break;
// }
//
// var child = createNodeByEl(next, node, options.elWalker);
// node.childs.push(child);
// options.elWalker.goNext();
// }
//
// if (literalOwner !== node.owner) {
// literalOwner.aNode.givenSlots[node.name] = node.aNode;
// }
// }
// #[end]
return node;
}
/**
* attach元素的html
*
* @param {Object} buf html串存储对象
*/
function slotOwnAttachHTML(buf) {
genElementChildsHTML(this, buf);
}
/**
* 获取 slot 对应的主元素
* slot 是片段的管理,没有主元素,所以直接返回爹的主元素,不持有引用
*
* @return {HTMLElement}
*/
function slotOwnGetEl() {
return this.parent._getEl();
}
/**
* 销毁释放 slot
*/
function slotOwnDispose() {
elementDisposeChilds(this);
nodeDispose(this);
}
// exports = module.exports = createSlot;
/**
* @file 遍历和编译已有元素的孩子
* @author errorrik(errorrik@gmail.com)
*/
// var createNodeByEl = require('./create-node-by-el');
// #[begin] reverse
// /**
// * 元素子节点遍历操作对象
// *
// * @inner
// * @class
// * @param {HTMLElement} el 要遍历的元素
// */
// function DOMChildsWalker(el) {
// this.raw = [];
// this.index = 0;
//
// var child = el.firstChild;
// while (child) {
// switch (child.nodeType) {
// case 1:
// case 8:
// this.raw.push(child);
// }
//
// child = child.nextSibling;
// }
//
// this.current = this.raw[this.index];
// this.next = this.raw[this.index + 1];
// }
//
// /**
// * 往下走一个元素
// */
// DOMChildsWalker.prototype.goNext = function () {
// this.current = this.raw[++this.index];
// this.next = this.raw[this.index + 1];
// };
//
// /**
// * 遍历和编译已有元素的孩子
// *
// * @param {HTMLElement} element 已有元素
// */
// function fromElInitChilds(element) {
// var walker = new DOMChildsWalker(element.el);
// var current;
// while ((current = walker.current)) {
// var child = createNodeByEl(current, element, walker);
// if (child && !child._static) {
// element.childs.push(child);
// }
//
// walker.goNext();
// }
// }
// #[end]
// exports = module.exports = fromElInitChilds;
/**
* @file attach 元素的 HTML
* @author errorrik(errorrik@gmail.com)
*/
// var genElementStartHTML = require('./gen-element-start-html');
// var genElementChildsHTML = require('./gen-element-childs-html');
// var genElementEndHTML = require('./gen-element-end-html');
// var attachings = require('./attachings');
/**
* attach 元素的 HTML
*
* @param {Object} buf html串存储对象
*/
function elementOwnAttachHTML(buf) {
this.lifeCycle.set('painting');
genElementStartHTML(this, buf);
genElementChildsHTML(this, buf);
genElementEndHTML(this, buf);
attachings.add(this);
}
// exports = module.exports = elementOwnAttachHTML;
/**
* @file 创建节点对应的 HTMLElement 主元素
* @author errorrik(errorrik@gmail.com)
*/
// var createEl = require('../browser/create-el');
// var evalExpr = require('../runtime/eval-expr');
// var nodeEvalExpr = require('./node-eval-expr');
// var isComponent = require('./is-component');
// var getPropHandler = require('./get-prop-handler');
/**
* 创建节点对应的 HTMLElement 主元素
*
* @param {Object} element 元素节点
*/
function elementCreate(element) {
element.lifeCycle.set('painting');
element.el = createEl(element.tagName);
element.el.id = element.id;
element.props.each(function (prop) {
var attr = prop.attr;
if (!attr) {
element.dynamicProps.push(prop);
var value = isComponent(element)
? evalExpr(prop.expr, element.data, element)
: nodeEvalExpr(element, prop.expr, 1);
attr = getPropHandler(element, prop.name).attr(element, prop.name, value);
}
var match = /^\s+([a-z0-9_-]+)=(['"])([^\2]*)\2$/i.exec(attr);
if (match) {
element.el.setAttribute(match[1], match[3]);
}
});
}
// exports = module.exports = elementCreate;
/**
* @file 创建节点对应的 HTMLElement 主元素
* @author errorrik(errorrik@gmail.com)
*/
// var elementCreate = require('./element-create');
/**
* 创建节点对应的 HTMLElement 主元素
*/
function elementOwnCreate() {
if (!this.lifeCycle.is('created')) {
elementCreate(this);
this._toPhase('created');
}
}
// exports = module.exports = elementOwnCreate;
/**
* @file 将元素attach到页面
* @author errorrik(errorrik@gmail.com)
*/
// var createStrBuffer = require('../runtime/create-str-buffer');
// var stringifyStrBuffer = require('../runtime/stringify-str-buffer');
// var genElementChildsHTML = require('./gen-element-childs-html');
// var warnSetHTML = require('./warn-set-html');
/**
* 将元素attach到页面
*
* @param {Object} element 元素节点
* @param {HTMLElement} parentEl 要添加到的父元素
* @param {HTMLElement=} beforeEl 要添加到哪个元素之前
*/
function elementAttach(element, parentEl, beforeEl) {
element._create();
if (parentEl) {
if (beforeEl) {
parentEl.insertBefore(element.el, beforeEl);
}
else {
parentEl.appendChild(element.el);
}
}
if (!element._contentReady) {
var buf = createStrBuffer();
genElementChildsHTML(element, buf);
// html 没内容就不要设置 innerHTML了
// 这里还能避免在 IE 下 component root 为 input 等元素时设置 innerHTML 报错的问题
var html = stringifyStrBuffer(buf);
if (html) {
// #[begin] error
// warnSetHTML(element.el);
// #[end]
element.el.innerHTML = html;
}
element._contentReady = 1;
}
}
// exports = module.exports = elementAttach;
/**
* @file 将元素attach到页面
* @author errorrik(errorrik@gmail.com)
*/
// var elementAttach = require('./element-attach');
// var attachings = require('./attachings');
/**
* 将元素attach到页面
*
* @param {HTMLElement} parentEl 要添加到的父元素
* @param {HTMLElement=} beforeEl 要添加到哪个元素之前
*/
function elementOwnAttach(parentEl, beforeEl) {
if (!this.lifeCycle.is('attached')) {
elementAttach(this, parentEl, beforeEl);
attachings.add(this);
attachings.done();
this._toPhase('attached');
}
}
// exports = module.exports = elementOwnAttach;
/**
* @file 将元素从页面上移除
* @author errorrik(errorrik@gmail.com)
*/
// var removeEl = require('../browser/remove-el');
/**
* 将元素从页面上移除
*/
function elementOwnDetach() {
if (this.lifeCycle.is('attached')) {
removeEl(this._getEl());
this._toPhase('detached');
}
}
// exports = module.exports = elementOwnDetach;
/**
* @file 销毁元素节点
* @author errorrik(errorrik@gmail.com)
*/
// var elementDisposeChilds = require('./element-dispose-childs');
// var nodeDispose = require('./node-dispose');
// var un = require('../browser/un');
/**
* 销毁元素节点
*
* @param {Object} element 要销毁的元素节点
* @param {boolean} dontDetach 是否不要将节点从DOM移除
*/
function elementDispose(element, dontDetach) {
elementDisposeChilds(element, true);
/* eslint-disable guard-for-in */
// el 事件解绑
for (var key in element._elFns) {
var nameListeners = element._elFns[key];
var len = nameListeners && nameListeners.length;
while (len--) {
un(element._getEl(), key, nameListeners[len]);
}
}
element._elFns = null;
/* eslint-enable guard-for-in */
if (!dontDetach) {
element.detach();
}
else if (element._toPhase) {
element._toPhase('detached');
}
element.props = null;
element.dynamicProps = null;
element.binds = null;
element._propVals = null;
// 这里不用挨个调用 dispose 了,因为 childs 释放链会调用的
element.slotChilds = null;
nodeDispose(element);
}
// exports = module.exports = elementDispose;
/**
* @file 销毁释放元素
* @author errorrik(errorrik@gmail.com)
*/
// var elementDispose = require('./element-dispose');
/**
* 销毁释放元素
*
* @param {boolean} dontDetach 是否不要将节点移除
*/
function elementOwnDispose(dontDetach) {
if (!this.lifeCycle.is('disposed')) {
elementDispose(this, dontDetach);
this._toPhase('disposed');
}
}
// exports = module.exports = elementOwnDispose;
/**
* @file 获取节点对应的主元素
* @author errorrik(errorrik@gmail.com)
*/
/**
* 获取节点对应的主元素
*
* @return {HTMLElement}
*/
function elementOwnGetEl() {
if (!this.el) {
this.el = document.getElementById(this.id);
}
return this.el;
}
// exports = module.exports = elementOwnGetEl;
/**
* @file 为元素的 el 绑定事件
* @author errorrik(errorrik@gmail.com)
*/
// var on = require('../browser/on');
/**
* 为元素的 el 绑定事件
*
* @param {string} name 事件名
* @param {Function} listener 监听器
*/
function elementOwnOnEl(name, listener) {
if (typeof listener === 'function') {
if (!this._elFns[name]) {
this._elFns[name] = [];
}
this._elFns[name].push(listener);
on(this._getEl(), name, listener);
}
}
// exports = module.exports = elementOwnOnEl;
/**
* @file 是否浏览器环境
* @author errorrik(errorrik@gmail.com)
*/
var isBrowser = typeof window !== 'undefined';
// exports = module.exports = isBrowser;
/**
* @file 完成元素 attached 后的行为
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var bind = require('../util/bind');
// var isBrowser = require('../browser/is-browser');
// var eventDeclarationListener = require('./event-declaration-listener');
// var isComponent = require('./is-component');
// var getPropHandler = require('./get-prop-handler');
/**
* 完成元素 attached 后的行为
*
* @param {Object} element 元素节点
*/
function elementAttached(element) {
element._toPhase('created');
var data = isComponent(element) ? element.data : element.scope;
// 处理自身变化时双向绑定的逻辑
var xBinds = isComponent(element) ? element.props : element.binds;
xBinds && xBinds.each(function (bindInfo) {
if (!bindInfo.x) {
return;
}
var el = element._getEl();
function outputer() {
getPropHandler(element, bindInfo.name).output(element, bindInfo, data);
}
switch (bindInfo.name) {
case 'value':
switch (element.tagName) {
case 'input':
case 'textarea':
if (isBrowser && window.CompositionEvent) {
element._onEl('compositionstart', function () {
this.composing = 1;
});
element._onEl('compositionend', function () {
this.composing = 0;
var event = document.createEvent('HTMLEvents');
event.initEvent('input', true, true);
this.dispatchEvent(event);
});
}
element._onEl(
('oninput' in el) ? 'input' : 'propertychange',
function (e) {
if (!this.composing) {
outputer(e);
}
}
);
break;
case 'select':
element._onEl('change', outputer);
break;
}
break;
case 'checked':
switch (element.tagName) {
case 'input':
switch (el.type) {
case 'checkbox':
case 'radio':
element._onEl('click', outputer);
}
}
break;
}
});
// bind events
each(element.aNode.events, function (eventBind) {
element._onEl(
eventBind.name,
bind(
eventDeclarationListener,
isComponent(element) ? element : element.owner,
eventBind,
0,
element.data || element.scope
)
);
});
element._toPhase('attached');
}
// exports = module.exports = elementAttached;
/**
* @file 设置元素属性
* @author errorrik(errorrik@gmail.com)
*/
// var getPropHandler = require('./get-prop-handler');
/**
* 设置元素属性
*
* @param {Object} element 元素
* @param {string} name 属性名
* @param {*} value 属性值
*/
function elementSetElProp(element, name, value) {
getPropHandler(element, name).prop(element, name, value);
}
// exports = module.exports = elementSetElProp;
/**
* @file 初始化 element 节点的必须属性
* @author errorrik(errorrik@gmail.com)
*/
// var LifeCycle = require('./life-cycle');
// var IndexedList = require('../util/indexed-list');
/**
* 初始化 element 节点的必须属性
*
* @param {Object} element 节点对象
*/
function elementInitProps(element) {
element.lifeCycle = new LifeCycle();
element.childs = [];
element.slotChilds = [];
element._elFns = {};
element._propVals = {};
element.dynamicProps = new IndexedList();
}
// exports = module.exports = elementInitProps;
/**
* @file 初始化 element 节点的 tagName 处理
* @author errorrik(errorrik@gmail.com)
*/
// var ieOldThan9 = require('../browser/ie-old-than-9');
/**
* 初始化 element 节点的 tagName 处理
*
* @param {Object} node 节点对象
*/
function elementInitTagName(node) {
node.tagName = node.tagName || node.aNode.tagName || 'div';
// ie8- 不支持innerHTML输出自定义标签
if (ieOldThan9 && node.tagName.indexOf('-') > 0) {
node.tagName = 'div';
}
// ie 下,如果 option 没有 value 属性,select.value = xx 操作不会选中 option
// 所以没有设置 value 时,默认把 option 的内容作为 value
if (node.tagName === 'option'
&& !node.aNode.props.get('value')
&& node.aNode.childs[0]
) {
node.aNode.props.push({
name: 'value',
expr: node.aNode.childs[0].textExpr
});
}
}
// exports = module.exports = elementInitTagName;
/**
* @file 给 devtool 发通知消息
* @author errorrik(errorrik@gmail.com)
*/
// var isBrowser = require('../browser/is-browser');
// #[begin] devtool
// var san4devtool;
//
// /**
// * 给 devtool 发通知消息
// *
// * @param {string} name 消息名称
// * @param {*} arg 消息参数
// */
// function emitDevtool(name, arg) {
// if (isBrowser && san4devtool && san4devtool.debug && window.__san_devtool__) {
// window.__san_devtool__.emit(name, arg);
// }
// }
//
// emitDevtool.start = function (main) {
// san4devtool = main;
// emitDevtool('san', main);
// };
// #[end]
// exports = module.exports = emitDevtool;
/**
* @file 组件类
* @author errorrik(errorrik@gmail.com)
*/
// var bind = require('../util/bind');
// var each = require('../util/each');
// var extend = require('../util/extend');
// var nextTick = require('../util/next-tick');
// var emitDevtool = require('../util/emit-devtool');
// var IndexedList = require('../util/indexed-list');
// var ExprType = require('../parser/expr-type');
// var createANode = require('../parser/create-a-node');
// var parseExpr = require('../parser/parse-expr');
// var parseText = require('../parser/parse-text');
// var parseTemplate = require('../parser/parse-template');
// var parseANodeFromEl = require('../parser/parse-anode-from-el');
// var Data = require('../runtime/data');
// var DataChangeType = require('../runtime/data-change-type');
// var evalExpr = require('../runtime/eval-expr');
// var changeExprCompare = require('../runtime/change-expr-compare');
// var defineComponent = require('./define-component');
// var attachings = require('./attachings');
// var isComponent = require('./is-component');
// var isDataChangeByElement = require('./is-data-change-by-element');
// var eventDeclarationListener = require('./event-declaration-listener');
// var fromElInitChilds = require('./from-el-init-childs');
// var postComponentBinds = require('./post-component-binds');
// var camelComponentBinds = require('./camel-component-binds');
// var nodeEvalExpr = require('./node-eval-expr');
// var NodeType = require('./node-type');
// var nodeInit = require('./node-init');
// var elementInitProps = require('./element-init-props');
// var elementInitTagName = require('./element-init-tag-name');
// var elementAttached = require('./element-attached');
// var elementDispose = require('./element-dispose');
// var elementUpdateChilds = require('./element-update-childs');
// var elementSetElProp = require('./element-set-el-prop');
// var elementOwnGetEl = require('./element-own-get-el');
// var elementOwnOnEl = require('./element-own-on-el');
// var elementOwnCreate = require('./element-own-create');
// var elementOwnAttach = require('./element-own-attach');
// var elementOwnDetach = require('./element-own-detach');
// var elementOwnAttachHTML = require('./element-own-attach-html');
// var elementOwnPushChildANode = require('./element-own-push-child-anode');
// var createDataTypesChecker = require('../util/create-data-types-checker');
/* eslint-disable guard-for-in */
/**
* 组件类
*
* @class
* @param {Object} options 初始化参数
*/
function Component(options) {
elementInitProps(this);
options = options || {};
this.dataChanges = [];
this.listeners = {};
this.ownSlotChilds = [];
this.filters = this.filters || this.constructor.filters || {};
this.computed = this.computed || this.constructor.computed || {};
this.messages = this.messages || this.constructor.messages || {};
this.subTag = options.subTag;
// compile
this._compile();
var me = this;
var givenANode = options.aNode;
var protoANode = this.constructor.prototype.aNode;
if (givenANode) {
// 组件运行时传入的结构,做slot解析
var givenSlots = {};
each(givenANode.childs, function (child) {
var slotName = '____';
var slotBind = !child.isText && child.props.get('slot');
if (slotBind) {
slotName = slotBind.raw;
}
if (!givenSlots[slotName]) {
givenSlots[slotName] = [];
}
givenSlots[slotName].push(child);
});
this.aNode = createANode({
tagName: protoANode.tagName || givenANode.tagName,
givenSlots: givenSlots,
// 组件的实际结构应为template编译的结构
childs: protoANode.childs,
// 合并运行时的一些绑定和事件声明
props: protoANode.props,
binds: camelComponentBinds(givenANode.props),
events: protoANode.events,
directives: givenANode.directives
});
each(givenANode.events, function (eventBind) {
me.on(
eventBind.name,
bind(eventDeclarationListener, options.owner, eventBind, 1, options.scope),
eventBind
);
});
}
this._toPhase('compiled');
// init data
this.data = new Data(
extend(
typeof this.initData === 'function' && this.initData() || {},
options.data
)
);
nodeInit(options, this);
// #[begin] reverse
// if (this.el) {
// this.aNode = parseANodeFromEl(this.el);
// this.aNode.givenSlots = {};
// this.aNode.binds = camelComponentBinds(this.aNode.props);
// this.aNode.props = this.constructor.prototype.aNode.props;
//
// this.parent && this.parent._pushChildANode(this.aNode);
// this.tagName = this.aNode.tagName;
//
// fromElInitChilds(this);
// attachings.add(this);
// }
// #[end]
elementInitTagName(this);
this.props = this.aNode.props;
this.binds = this.aNode.binds || this.aNode.props;
postComponentBinds(this.binds);
this.scope && this.binds.each(function (bind) {
me.data.set(bind.name, nodeEvalExpr(me, bind.expr));
});
// #[begin] error
// // 在初始化 + 数据绑定后,开始数据校验
// // NOTE: 只在开发版本中进行属性校验
// var dataTypes = this.dataTypes || this.constructor.dataTypes;
// if (dataTypes) {
// var dataTypeChecker = createDataTypesChecker(
// dataTypes,
// this.subTag || this.name || this.constructor.name
// );
// this.data.setTypeChecker(dataTypeChecker);
// this.data.checkDataTypes();
// }
// #[end]
this.computedDeps = {};
for (var expr in this.computed) {
if (!this.computedDeps[expr]) {
this._calcComputed(expr);
}
}
if (!this.dataChanger) {
this.dataChanger = bind(this._dataChanger, this);
this.data.listen(this.dataChanger);
}
this._toPhase('inited');
// #[begin] reverse
// // 如果从el编译的,认为已经attach了,触发钩子
// if (this.el) {
// attachings.done();
// }
// #[end]
}
/**
* 类型标识
*
* @protected
* @type {string}
*/
Component.prototype._type = NodeType.CMPT;
/* eslint-disable operator-linebreak */
/**
* 使节点到达相应的生命周期
*
* @protected
* @param {string} name 生命周期名称
*/
Component.prototype._callHook =
Component.prototype._toPhase = function (name) {
if (this.lifeCycle.is(name)) {
return;
}
this.lifeCycle.set(name);
if (typeof this[name] === 'function') {
this[name](this);
}
// 通知devtool
// #[begin] devtool
// emitDevtool('comp-' + name, this);
// #[end]
};
/* eslint-enable operator-linebreak */
/**
* 添加事件监听器
*
* @param {string} name 事件名
* @param {Function} listener 监听器
* @param {string?} declaration 声明式
*/
Component.prototype.on = function (name, listener, declaration) {
if (typeof listener === 'function') {
if (!this.listeners[name]) {
this.listeners[name] = [];
}
this.listeners[name].push({fn: listener, declaration: declaration});
}
};
/**
* 移除事件监听器
*
* @param {string} name 事件名
* @param {Function=} listener 监听器
*/
Component.prototype.un = function (name, listener) {
var nameListeners = this.listeners[name];
var len = nameListeners && nameListeners.length;
while (len--) {
if (!listener || listener === nameListeners[len].fn) {
nameListeners.splice(len, 1);
}
}
};
/**
* 派发事件
*
* @param {string} name 事件名
* @param {Object} event 事件对象
*/
Component.prototype.fire = function (name, event) {
each(this.listeners[name], function (listener) {
listener.fn.call(this, event);
}, this);
};
/**
* 计算 computed 属性的值
*
* @private
* @param {string} computedExpr computed表达式串
*/
Component.prototype._calcComputed = function (computedExpr) {
var computedDeps = this.computedDeps[computedExpr];
if (!computedDeps) {
computedDeps = this.computedDeps[computedExpr] = {};
}
this.data.set(computedExpr, this.computed[computedExpr].call({
data: {
get: bind(function (expr) {
// #[begin] error
// if (!expr) {
// throw new Error('[SAN ERROR] call get method in computed need argument');
// }
// #[end]
if (!computedDeps[expr]) {
computedDeps[expr] = 1;
if (this.computed[expr]) {
this._calcComputed(expr);
}
this.watch(expr, function () {
this._calcComputed(computedExpr);
});
}
return this.data.get(expr);
}, this)
}
}));
};
/**
* 派发消息
* 组件可以派发消息,消息将沿着组件树向上传递,直到遇上第一个处理消息的组件
*
* @param {string} name 消息名称
* @param {*?} value 消息值
*/
Component.prototype.dispatch = function (name, value) {
var parentComponent = this.parentComponent;
while (parentComponent) {
if (typeof parentComponent.messages[name] === 'function') {
parentComponent.messages[name].call(
parentComponent,
{target: this, value: value}
);
break;
}
parentComponent = parentComponent.parentComponent;
}
};
/**
* 获取带有 san-ref 指令的子组件引用
*
* @param {string} name 子组件的引用名
* @return {Component}
*/
Component.prototype.ref = function (name) {
var refComponent;
var owner = this;
function slotChildsTraversal(childs) {
each(childs, function (slotChild) {
childsTraversal(slotChild);
return !refComponent;
});
}
function childsTraversal(element) {
slotChildsTraversal(element.slotChilds);
each(element.childs, function (child) {
if (isComponent(child)) {
var refDirective = child.aNode.directives.get('ref');
if (refDirective
&& evalExpr(refDirective.value, child.scope || owner.data, owner) === name
) {
refComponent = child;
}
slotChildsTraversal(child.slotChilds);
}
if (!refComponent && child._type !== NodeType.TEXT) {
childsTraversal(child);
}
return !refComponent;
});
}
childsTraversal(this);
slotChildsTraversal(this.ownSlotChilds);
return refComponent;
};
/* eslint-disable quotes */
var componentPropExtra = [
{name: 'class', expr: parseText("{{class | _class | _sep(' ')}}")},
{name: 'style', expr: parseText("{{style | _style | _sep(';')}}")}
];
/* eslint-enable quotes */
/**
* 模板编译行为
*
* @private
*/
Component.prototype._compile = function () {
var ComponentClass = this.constructor;
var proto = ComponentClass.prototype;
// pre define components class
if (!proto.hasOwnProperty('_cmptReady')) {
proto.components = ComponentClass.components || proto.components || {};
var components = proto.components;
for (var key in components) {
var componentClass = components[key];
if (typeof componentClass === 'object') {
components[key] = defineComponent(componentClass);
}
else if (componentClass === 'self') {
components[key] = ComponentClass;
}
}
proto._cmptReady = 1;
}
// pre compile template
if (!proto.hasOwnProperty('_compiled')) {
proto.aNode = createANode();
var tpl = ComponentClass.template || proto.template;
if (tpl) {
var aNode = parseTemplate(tpl, {
trimWhitespace: proto.trimWhitespace || ComponentClass.trimWhitespace
});
var firstChild = aNode.childs[0];
// #[begin] error
// if (aNode.childs.length !== 1 || firstChild.isText) {
// throw new Error('[SAN FATAL] template must have a root element.');
// }
// #[end]
proto.aNode = firstChild;
if (firstChild.tagName === 'template') {
firstChild.tagName = null;
}
firstChild.binds = new IndexedList();
each(componentPropExtra, function (extra) {
var prop = firstChild.props.get(extra.name);
if (prop) {
prop.expr.segs.push(extra.expr.segs[0]);
prop.expr.value = null;
prop.attr = null;
}
else {
firstChild.props.push({
name: extra.name,
expr: extra.expr
});
}
});
}
proto._compiled = 1;
}
};
/**
* 视图更新函数
*
* @param {Array?} changes 数据变化信息
*/
Component.prototype._update = function (changes) {
if (this.lifeCycle.is('disposed')) {
return;
}
var me = this;
each(changes, function (change) {
var changeExpr = change.expr;
me.binds.each(function (bindItem) {
var relation;
var setExpr = bindItem.name;
var updateExpr = bindItem.expr;
if (!isDataChangeByElement(change, me, setExpr)
&& (relation = changeExprCompare(changeExpr, updateExpr, me.scope))
) {
if (relation > 2) {
setExpr = {
type: ExprType.ACCESSOR,
paths: [{
type: ExprType.STRING,
value: setExpr
}].concat(changeExpr.paths.slice(updateExpr.paths.length))
};
updateExpr = changeExpr;
}
me.data.set(setExpr, nodeEvalExpr(me, updateExpr), {
target: {
id: me.owner.id
}
});
}
});
});
each(this.slotChilds, function (child) {
elementUpdateChilds(child, changes);
});
var dataChanges = me.dataChanges;
if (dataChanges.length) {
me.dataChanges = [];
me.props.each(function (prop) {
each(dataChanges, function (change) {
if (changeExprCompare(change.expr, prop.expr, me.data)
|| prop.hintExpr && changeExprCompare(change.expr, prop.hintExpr, me.data)
) {
elementSetElProp(
me,
prop.name,
evalExpr(prop.expr, me.data, me)
);
return false;
}
});
});
elementUpdateChilds(this, dataChanges, 'ownSlotChilds');
this._toPhase('updated');
if (me.owner) {
each(dataChanges, function (change) {
me.binds.each(function (bindItem) {
var changeExpr = change.expr;
if (bindItem.x
&& !isDataChangeByElement(change, me.owner)
&& changeExprCompare(changeExpr, parseExpr(bindItem.name), me.data)
) {
var updateScopeExpr = bindItem.expr;
if (changeExpr.paths.length > 1) {
updateScopeExpr = {
type: ExprType.ACCESSOR,
paths: bindItem.expr.paths.concat(changeExpr.paths.slice(1))
};
}
me.scope.set(
updateScopeExpr,
evalExpr(changeExpr, me.data, me),
{
target: {
id: me.id,
prop: bindItem.name
}
}
);
}
});
});
me.owner._update();
}
}
};
/**
* 组件内部监听数据变化的函数
*
* @private
* @param {Object} change 数据变化信息
*/
Component.prototype._dataChanger = function (change) {
if (this.lifeCycle.is('painting') || this.lifeCycle.is('created')) {
var len = this.dataChanges.length;
if (!len) {
nextTick(this._update, this);
}
while (len--) {
switch (changeExprCompare(change.expr, this.dataChanges[len].expr)) {
case 1:
case 2:
if (change.type === DataChangeType.SET) {
this.dataChanges.splice(len, 1);
}
}
}
this.dataChanges.push(change);
}
};
/**
* 监听组件的数据变化
*
* @param {string} dataName 变化的数据项
* @param {Function} listener 监听函数
*/
Component.prototype.watch = function (dataName, listener) {
var dataExpr = parseExpr(dataName);
this.data.listen(bind(function (change) {
if (changeExprCompare(change.expr, dataExpr, this.data)) {
listener.call(this, evalExpr(dataExpr, this.data, this), change);
}
}, this));
};
/**
* 组件销毁的行为
*
* @param {boolean} dontDetach 是否不要将节点从DOM移除
*/
Component.prototype.dispose = function (dontDetach) {
if (!this.lifeCycle.is('disposed')) {
elementDispose(this, dontDetach);
this.ownSlotChilds = null;
this.data.unlisten();
this.dataChanger = null;
this.dataChanges = null;
this.listeners = null;
this._toPhase('disposed');
}
};
/**
* 完成组件 attached 后的行为
*
* @param {Object} element 元素节点
*/
Component.prototype._attached = function () {
this._getEl();
elementAttached(this);
};
Component.prototype.attach = elementOwnAttach;
Component.prototype.detach = elementOwnDetach;
Component.prototype._attachHTML = elementOwnAttachHTML;
Component.prototype._create = elementOwnCreate;
Component.prototype._getEl = elementOwnGetEl;
Component.prototype._onEl = elementOwnOnEl;
// #[begin] reverse
// Component.prototype._pushChildANode = elementOwnPushChildANode;
// #[end]
// exports = module.exports = Component;
/**
* @file 创建组件类
* @author errorrik(errorrik@gmail.com)
*/
// var Component = require('./component');
// var inherits = require('../util/inherits');
/**
* 创建组件类
*
* @param {Object} proto 组件类的方法表
* @return {Function}
*/
function defineComponent(proto) {
// 如果传入一个不是 san component 的 constructor,直接返回不是组件构造函数
// 这种场景导致的错误 san 不予考虑
if (typeof proto === 'function') {
return proto;
}
// #[begin] error
// if (typeof proto !== 'object') {
// throw new Error('[SAN FATAL] param must be a plain object.');
// }
// #[end]
function ComponentClass(option) {
Component.call(this, option);
}
ComponentClass.prototype = proto;
inherits(ComponentClass, Component);
return ComponentClass;
}
// exports = module.exports = defineComponent;
/**
* @file 将组件的绑定信息进行后处理
* @author errorrik(errorrik@gmail.com)
*/
// var postProp = require('../parser/post-prop');
/**
* 将组件的绑定信息进行后处理
*
* 扁平化:
* 当 text 解析只有一项时,要么就是 string,要么就是 interp
* interp 有可能是绑定到组件属性的表达式,不希望被 eval text 成 string
* 所以这里做个处理,只有一项时直接抽出来
*
* bool属性:
* 当绑定项没有值时,默认为true
*
* @param {IndexedList} binds 组件绑定信息集合对象
*/
function postComponentBinds(binds) {
binds.each(function (bind) {
postProp(bind);
});
}
// exports = module.exports = postComponentBinds;
/**
* @file 把 kebab case 字符串转换成 camel case
* @author errorrik(errorrik@gmail.com)
*/
/**
* 把 kebab case 字符串转换成 camel case
*
* @param {string} source 源字符串
* @return {string}
*/
function kebab2camel(source) {
return source.replace(/-([a-z])/g, function (match, alpha) {
return alpha.toUpperCase();
});
}
// exports = module.exports = kebab2camel;
/**
* @file 将 binds 的 name 从 kebabcase 转换成 camelcase
* @author errorrik(errorrik@gmail.com)
*/
// var kebab2camel = require('../util/kebab2camel');
// var IndexedList = require('../util/indexed-list');
/**
* 将 binds 的 name 从 kebabcase 转换成 camelcase
*
* @param {IndexedList} binds binds集合
* @return {IndexedList}
*/
function camelComponentBinds(binds) {
var result = new IndexedList();
binds.each(function (bind) {
result.push({
name: kebab2camel(bind.name),
expr: bind.expr,
x: bind.x,
raw: bind.raw
});
});
return result;
}
// exports = module.exports = camelComponentBinds;
/**
* @file 把 camel case 字符串转换成 kebab case
* @author errorrik(errorrik@gmail.com)
*/
// #[begin] ssr
// /**
// * 把 camel case 字符串转换成 kebab case
// *
// * @param {string} source 源字符串
// * @return {string}
// */
// function camel2kebab(source) {
// return source.replace(/[A-Z]/g, function (match) {
// return '-' + match.toLowerCase();
// });
// }
// #[end]
// exports = module.exports = camel2kebab;
/**
* @file 编译源码的 helper 方法集合
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var ExprType = require('../parser/expr-type');
// #[begin] ssr
//
// /**
// * 编译源码的 helper 方法集合对象
// */
// var compileExprSource = {
//
// /**
// * 字符串字面化
// *
// * @param {string} source 需要字面化的字符串
// * @return {string} 字符串字面化结果
// */
// stringLiteralize: function (source) {
// return '"'
// + source
// .replace(/\x5C/g, '\\\\')
// .replace(/"/g, '\\"')
// .replace(/\x0A/g, '\\n')
// .replace(/\x09/g, '\\t')
// .replace(/\x0D/g, '\\r')
// // .replace( /\x08/g, '\\b' )
// // .replace( /\x0C/g, '\\f' )
// + '"';
// },
//
// /**
// * 生成数据访问表达式代码
// *
// * @param {Object?} accessorExpr accessor表达式对象
// * @return {string}
// */
// dataAccess: function (accessorExpr) {
// var code = 'componentCtx.data';
// if (accessorExpr) {
// each(accessorExpr.paths, function (path) {
// if (path.type === ExprType.ACCESSOR) {
// code += '[' + compileExprSource.dataAccess(path) + ']';
// return;
// }
//
// switch (typeof path.value) {
// case 'string':
// code += '.' + path.value;
// break;
//
// case 'number':
// code += '[' + path.value + ']';
// break;
// }
// });
// }
//
// return code;
// },
//
// /**
// * 生成插值代码
// *
// * @param {Object} interpExpr 插值表达式对象
// * @return {string}
// */
// interp: function (interpExpr) {
// var code = compileExprSource.expr(interpExpr.expr);
//
// each(interpExpr.filters, function (filter) {
// code = 'componentCtx.callFilter("' + filter.name + '", [' + code;
// each(filter.args, function (arg) {
// code += ', ' + compileExprSource.expr(arg);
// });
// code += '])';
// });
//
// return code;
// },
//
// /**
// * 生成文本片段代码
// *
// * @param {Object} textExpr 文本片段表达式对象
// * @return {string}
// */
// text: function (textExpr) {
// if (textExpr.segs.length === 0) {
// return '""';
// }
//
// var code = '';
//
// each(textExpr.segs, function (seg) {
// if (seg.type === ExprType.INTERP && !seg.filters[0]) {
// seg = {
// type: ExprType.INTERP,
// expr: seg.expr,
// filters: [
// {
// type: ExprType.CALL,
// name: 'html',
// args: []
// }
// ]
// };
// }
//
// var segCode = compileExprSource.expr(seg);
// code += code ? ' + ' + segCode : segCode;
// });
//
// return code;
// },
//
// /**
// * 二元表达式操作符映射表
// *
// * @type {Object}
// */
// binaryOp: {
// /* eslint-disable */
// 43: '+',
// 45: '-',
// 42: '*',
// 47: '/',
// 60: '<',
// 62: '>',
// 76: '&&',
// 94: '!=',
// 121: '<=',
// 122: '==',
// 123: '>=',
// 155: '!==',
// 183: '===',
// 248: '||'
// /* eslint-enable */
// },
//
// /**
// * 生成表达式代码
// *
// * @param {Object} expr 表达式对象
// * @return {string}
// */
// expr: function (expr) {
// switch (expr.type) {
// case ExprType.UNARY:
// return '!' + compileExprSource.expr(expr.expr);
//
// case ExprType.BINARY:
// return compileExprSource.expr(expr.segs[0])
// + compileExprSource.binaryOp[expr.operator]
// + compileExprSource.expr(expr.segs[1]);
//
// case ExprType.TERTIARY:
// return compileExprSource.expr(expr.segs[0])
// + '?' + compileExprSource.expr(expr.segs[1])
// + ':' + compileExprSource.expr(expr.segs[2]);
//
// case ExprType.STRING:
// return compileExprSource.stringLiteralize(expr.value);
//
// case ExprType.NUMBER:
// return expr.value;
//
// case ExprType.BOOL:
// return expr.value ? 'true' : 'false';
//
// case ExprType.ACCESSOR:
// return compileExprSource.dataAccess(expr);
//
// case ExprType.INTERP:
// return compileExprSource.interp(expr);
//
// case ExprType.TEXT:
// return compileExprSource.text(expr);
// }
// }
// };
// #[end]
// exports = module.exports = compileExprSource;
/**
* @file 编译源码的中间buffer类
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var compileExprSource = require('./compile-expr-source');
// #[begin] ssr
// /**
// * 编译源码的中间buffer类
// *
// * @class
// */
// function CompileSourceBuffer() {
// this.segs = [];
// }
//
// /**
// * 添加原始代码,将原封不动输出
// *
// * @param {string} code 原始代码
// */
// CompileSourceBuffer.prototype.addRaw = function (code) {
// this.segs.push({
// type: 'RAW',
// code: code
// });
// };
//
// /**
// * 添加被拼接为html的原始代码
// *
// * @param {string} code 原始代码
// */
// CompileSourceBuffer.prototype.joinRaw = function (code) {
// this.segs.push({
// type: 'JOIN_RAW',
// code: code
// });
// };
//
// /**
// * 添加renderer方法的起始源码
// */
// CompileSourceBuffer.prototype.addRendererStart = function () {
// this.addRaw('function (data, parentCtx) {');
// this.addRaw('var html = "";');
// };
//
// /**
// * 添加renderer方法的结束源码
// */
// CompileSourceBuffer.prototype.addRendererEnd = function () {
// this.addRaw('return html;');
// this.addRaw('}');
// };
//
// /**
// * 添加被拼接为html的静态字符串
// *
// * @param {string} str 被拼接的字符串
// */
// CompileSourceBuffer.prototype.joinString = function (str) {
// this.segs.push({
// str: str,
// type: 'JOIN_STRING'
// });
// };
//
// /**
// * 添加被拼接为html的数据访问
// *
// * @param {Object?} accessor 数据访问表达式对象
// */
// CompileSourceBuffer.prototype.joinDataStringify = function () {
// this.segs.push({
// type: 'JOIN_DATA_STRINGIFY'
// });
// };
//
// /**
// * 添加被拼接为html的表达式
// *
// * @param {Object} expr 表达式对象
// */
// CompileSourceBuffer.prototype.joinExpr = function (expr) {
// this.segs.push({
// expr: expr,
// type: 'JOIN_EXPR'
// });
// };
//
// /**
// * 生成编译后代码
// *
// * @return {string}
// */
// CompileSourceBuffer.prototype.toCode = function () {
// var code = [];
// var temp = '';
//
// function genStrLiteral() {
// if (temp) {
// code.push('html += ' + compileExprSource.stringLiteralize(temp) + ';');
// }
//
// temp = '';
// }
//
// each(this.segs, function (seg) {
// if (seg.type === 'JOIN_STRING') {
// temp += seg.str;
// return;
// }
//
// genStrLiteral();
// switch (seg.type) {
// case 'JOIN_DATA_STRINGIFY':
// code.push('html += stringifier.any(' + compileExprSource.dataAccess() + ');');
// break;
//
// case 'JOIN_EXPR':
// code.push('html += ' + compileExprSource.expr(seg.expr) + ';');
// break;
//
// case 'JOIN_RAW':
// code.push('html += ' + seg.code + ';');
// break;
//
// case 'RAW':
// code.push(seg.code);
// break;
//
// }
// });
//
// genStrLiteral();
//
// return code.join('\n');
// };
//
// #[end]
// exports = module.exports = CompileSourceBuffer;
/**
* @file 序列化一个ANode
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var autoCloseTags = require('../browser/auto-close-tags');
// #[begin] ssr
// /**
// * 序列化一个ANode
// *
// * @param {ANode} aNode aNode对象
// * @return {string}
// */
// function serializeANode(aNode) {
// if (aNode.isText) {
// return aNode.text;
// }
//
// var tagName = aNode.tagName;
//
// // start tag
// var str = '<' + tagName;
//
// // for directives
// var hasElse;
// aNode.directives.each(function (directive) {
// if (directive.name === 'else' || directive.name === 'if' && directive.isElse) {
// if (!hasElse) {
// str += ' s-else';
// }
// hasElse = 1;
//
// return;
// }
//
// str += ' s-' + directive.name + '="' + directive.raw + '"';
// });
//
// // for events
// each(aNode.events, function (event) {
// str += ' on-' + event.name + '="' + event.expr.raw + '"';
// });
//
// // for props
// aNode.props.each(function (prop) {
// str += ' ' + prop.name + '="' + prop.raw + '"';
// });
//
// if (autoCloseTags[tagName]) {
// str += ' />';
// }
// else {
// str += '>';
//
// // for childs
// each(aNode.childs, function (child) {
// str += serializeANode(child);
// });
//
// // close tag
// str += '</' + tagName + '>';
// }
//
// return str;
// }
// #[end]
// exports = module.exports = serializeANode;
/**
* @file 将组件编译成 render 方法的 js 源码
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var camel2kebab = require('../util/camel2kebab');
// var IndexedList = require('../util/indexed-list');
// var parseExpr = require('../parser/parse-expr');
// var createANode = require('../parser/create-a-node');
// var escapeHTML = require('../runtime/escape-html');
// var autoCloseTags = require('../browser/auto-close-tags');
// var CompileSourceBuffer = require('./compile-source-buffer');
// var compileExprSource = require('./compile-expr-source');
// var postComponentBinds = require('./post-component-binds');
// var serializeANode = require('./serialize-a-node');
// #[begin] ssr
//
// /**
// * 生成序列化时起始桩的html
// *
// * @param {string} type 桩类型标识
// * @param {string?} content 桩内的内容
// * @return {string}
// */
// function serializeStump(type, content) {
// return '<!--s-' + type + (content ? ':' + content : '') + '-->';
// }
//
// /**
// * 生成序列化时结束桩的html
// *
// * @param {string} type 桩类型标识
// * @return {string}
// */
// function serializeStumpEnd(type) {
// return '<!--/s-' + type + '-->';
// }
//
// /**
// * element 的编译方法集合对象
// *
// * @inner
// */
// var elementSourceCompiler = {
//
// /* eslint-disable max-params */
// /**
// * 编译元素标签头
// *
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {string} tagName 标签名
// * @param {IndexedList} props 属性列表
// * @param {IndexedList} binds 绑定信息列表
// * @param {Array} events 绑定事件列表
// * @param {Object} aNode 对应的抽象节点对象
// * @param {string?} extraProp 额外的属性串
// * @param {boolean?} isComponent 是否组件
// */
// tagStart: function (sourceBuffer, tagName, props, binds, events, aNode, extraProp, isComponent) {
// sourceBuffer.joinString('<' + tagName);
// sourceBuffer.joinString(extraProp || '');
//
// binds.each(function (bindInfo) {
// if (isComponent) {
// sourceBuffer.joinString(
// ' prop-' + camel2kebab(bindInfo.name)
// + (bindInfo.raw ? '="' + bindInfo.raw + '"' : '')
// );
// }
// else if (bindInfo.raw) {
// sourceBuffer.joinString(
// ' prop-' + camel2kebab(bindInfo.name) + '="' + bindInfo.raw + '"'
// );
// }
//
// });
//
// var htmlDirective = aNode.directives.get('html');
// if (htmlDirective) {
// sourceBuffer.joinString(' s-html="' + htmlDirective.raw + '"');
// }
//
// each(events, function (event) {
// sourceBuffer.joinString(' on-' + event.name + '="' + event.expr.raw + '"');
// });
//
// props.each(function (prop) {
// if (prop.name === 'value') {
// switch (tagName) {
// case 'textarea':
// return;
//
// case 'select':
// sourceBuffer.addRaw('$selectValue = '
// + compileExprSource.expr(prop.expr)
// + ' || "";'
// );
// return;
//
// case 'option':
// sourceBuffer.addRaw('$optionValue = '
// + compileExprSource.expr(prop.expr)
// + ';'
// );
// // value
// sourceBuffer.addRaw('if ($optionValue != null) {');
// sourceBuffer.joinRaw('" value=\\"" + $optionValue + "\\""');
// sourceBuffer.addRaw('}');
//
// // selected
// sourceBuffer.addRaw('if ($optionValue === $selectValue) {');
// sourceBuffer.joinString(' selected');
// sourceBuffer.addRaw('}');
// return;
// }
// }
//
// switch (prop.name) {
// case 'draggable':
// case 'readonly':
// case 'disabled':
// case 'mutiple':
// if (prop.raw === '') {
// sourceBuffer.joinString(' ' + prop.name);
// }
// else {
// sourceBuffer.joinRaw('boolAttrFilter("' + prop.name + '", '
// + compileExprSource.expr(prop.expr)
// + ')'
// );
// }
// break;
//
// case 'checked':
// if (tagName === 'input') {
// var valueProp = props.get('value');
// var valueCode = compileExprSource.expr(valueProp.expr);
//
// if (valueProp) {
// switch (props.get('type').raw) {
// case 'checkbox':
// sourceBuffer.addRaw('if (contains('
// + compileExprSource.expr(prop.expr)
// + ', '
// + valueCode
// + ')) {'
// );
// sourceBuffer.joinString(' checked');
// sourceBuffer.addRaw('}');
// break;
//
// case 'radio':
// sourceBuffer.addRaw('if ('
// + compileExprSource.expr(prop.expr)
// + ' === '
// + valueCode
// + ') {'
// );
// sourceBuffer.joinString(' checked');
// sourceBuffer.addRaw('}');
// break;
// }
// }
// }
// break;
//
// default:
// if (prop.expr.value) {
// sourceBuffer.joinString(' ' + prop.name + '="' + prop.expr.value + '"');
// }
// else {
// sourceBuffer.joinRaw('attrFilter("' + prop.name + '", '
// + compileExprSource.expr(prop.expr)
// + ')'
// );
// }
// break;
// }
// });
//
// sourceBuffer.joinString('>');
// },
// /* eslint-enable max-params */
//
// /**
// * 编译元素闭合
// *
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {string} tagName 标签名
// */
// tagEnd: function (sourceBuffer, tagName) {
// if (!autoCloseTags[tagName]) {
// sourceBuffer.joinString('</' + tagName + '>');
// }
//
// if (tagName === 'select') {
// sourceBuffer.addRaw('$selectValue = null;');
// }
//
// if (tagName === 'option') {
// sourceBuffer.addRaw('$optionValue = null;');
// }
// },
//
// /**
// * 编译元素内容
// *
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {ANode} aNode 元素的抽象节点信息
// * @param {Component} owner 所属组件实例环境
// */
// inner: function (sourceBuffer, aNode, owner) {
// // inner content
// if (aNode.tagName === 'textarea') {
// var valueProp = aNode.props.get('value');
// if (valueProp) {
// sourceBuffer.joinRaw('escapeHTML('
// + compileExprSource.expr(valueProp.expr)
// + ')'
// );
// }
//
// return;
// }
//
// var htmlDirective = aNode.directives.get('html');
// if (htmlDirective) {
// sourceBuffer.joinExpr(htmlDirective.value);
// }
// else {
// /* eslint-disable no-use-before-define */
// each(aNode.childs, function (aNodeChild) {
// sourceBuffer.addRaw(aNodeCompiler.compile(aNodeChild, sourceBuffer, owner));
// });
// /* eslint-enable no-use-before-define */
// }
// }
// };
//
// /**
// * ANode 的编译方法集合对象
// *
// * @inner
// */
// var aNodeCompiler = {
//
// /**
// * 编译节点
// *
// * @param {ANode} aNode 抽象节点
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Component} owner 所属组件实例环境
// * @param {Object} extra 编译所需的一些额外信息
// */
// compile: function (aNode, sourceBuffer, owner, extra) {
// extra = extra || {};
// var compileMethod = 'compileElement';
//
// if (aNode.isText) {
// compileMethod = 'compileText';
// }
// else if (aNode.directives.get('if')) {
// compileMethod = 'compileIf';
// }
// else if (aNode.directives.get('for')) {
// compileMethod = 'compileFor';
// }
// else if (aNode.tagName === 'slot') {
// compileMethod = 'compileSlot';
// }
// else {
// var ComponentType = owner.components[aNode.tagName];
// if (ComponentType) {
// compileMethod = 'compileComponent';
// extra.ComponentClass = ComponentType;
// }
// }
//
// aNodeCompiler[compileMethod](aNode, sourceBuffer, owner, extra);
// },
//
// /**
// * 编译文本节点
// *
// * @param {ANode} aNode 节点对象
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// */
// compileText: function (aNode, sourceBuffer) {
// var value = aNode.textExpr.value;
//
// if (value == null) {
// sourceBuffer.joinString('<!--s-text:' + aNode.text + '-->');
// sourceBuffer.joinExpr(aNode.textExpr);
// sourceBuffer.joinString('<!--/s-text-->');
// }
// else {
// sourceBuffer.joinString(value);
// }
// },
//
// /**
// * 编译 if 节点
// *
// * @param {ANode} aNode 节点对象
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Component} owner 所属组件实例环境
// */
// compileIf: function (aNode, sourceBuffer, owner) {
// sourceBuffer.addRaw('(function () {');
// sourceBuffer.addRaw('var ifIndex = null;');
//
// // for ifIndex
// var ifDirective = aNode.directives.get('if');
// sourceBuffer.addRaw('if (' + compileExprSource.expr(ifDirective.value) + ') {');
// sourceBuffer.addRaw(' ifIndex = -1;');
// sourceBuffer.addRaw('}');
// each(aNode.elses, function (elseANode, index) {
// var elifDirective = elseANode.directives.get('elif');
// if (elifDirective) {
// sourceBuffer.addRaw('else if (' + compileExprSource.expr(elifDirective.value) + ') {');
// }
// else {
// sourceBuffer.addRaw('else {');
// }
//
// sourceBuffer.addRaw(' ifIndex = ' + index + ';');
// sourceBuffer.addRaw('}');
// });
//
// // for output main if html
// sourceBuffer.addRaw('if (ifIndex === -1) {');
// sourceBuffer.addRaw(
// aNodeCompiler.compile(
// rinseANode(aNode),
// sourceBuffer,
// owner,
// {prop: ' s-if="' + escapeHTML(ifDirective.raw) + '"'}
// )
// );
// sourceBuffer.addRaw('} else {');
// sourceBuffer.joinString(serializeStump('if', serializeANode(aNode)));
// sourceBuffer.addRaw('}');
//
// // for output else html
// each(aNode.elses, function (elseANode, index) {
// var elifDirective = elseANode.directives.get('elif');
// sourceBuffer.addRaw('if (ifIndex === ' + index + ') {');
// sourceBuffer.addRaw(
// aNodeCompiler.compile(
// rinseANode(elseANode),
// sourceBuffer,
// owner,
// {
// prop: elifDirective ? ' s-elif="' + escapeHTML(elifDirective.raw) + '"' : ' s-else'
// }
// )
// );
// sourceBuffer.addRaw('} else {');
// sourceBuffer.joinString(serializeStump(elifDirective ? 'elif' : 'else', serializeANode(elseANode)));
// sourceBuffer.addRaw('}');
// });
//
// sourceBuffer.addRaw('})();');
//
// /**
// * 清洗 if aNode,返回纯净无 if 指令的 aNode
// *
// * @param {ANode} ifANode 节点对象
// * @return {ANode}
// */
// function rinseANode(ifANode) {
// var result = createANode({
// childs: ifANode.childs,
// props: ifANode.props,
// events: ifANode.events,
// tagName: ifANode.tagName,
// directives: (new IndexedList()).concat(ifANode.directives)
// });
// result.directives.remove('if');
// result.directives.remove('elif');
// result.directives.remove('else');
//
// return result;
// }
// },
//
// /**
// * 编译 for 节点
// *
// * @param {ANode} aNode 节点对象
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Component} owner 所属组件实例环境
// */
// compileFor: function (aNode, sourceBuffer, owner) {
// var forElementANode = createANode({
// childs: aNode.childs,
// props: aNode.props,
// events: aNode.events,
// tagName: aNode.tagName,
// directives: (new IndexedList()).concat(aNode.directives)
// });
// forElementANode.directives.remove('for');
//
// var forDirective = aNode.directives.get('for');
// var itemName = forDirective.item.raw;
// var indexName = forDirective.index.raw;
// var listName = compileExprSource.dataAccess(forDirective.list);
//
// // start stump
// sourceBuffer.joinString(serializeStump('for', serializeANode(aNode)));
//
// sourceBuffer.addRaw('for ('
// + 'var ' + indexName + ' = 0; '
// + indexName + ' < ' + listName + '.length; '
// + indexName + '++) {'
// );
// sourceBuffer.addRaw('componentCtx.data.' + indexName + '=' + indexName + ';');
// sourceBuffer.addRaw('componentCtx.data.' + itemName + '= ' + listName + '[' + indexName + '];');
// sourceBuffer.addRaw(
// aNodeCompiler.compile(
// forElementANode,
// sourceBuffer,
// owner
// )
// );
// sourceBuffer.addRaw('}');
//
// // stop stump
// sourceBuffer.joinString(serializeStumpEnd('for'));
// },
//
// /**
// * 编译 slot 节点
// *
// * @param {ANode} aNode 节点对象
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Component} owner 所属组件实例环境
// */
// compileSlot: function (aNode, sourceBuffer, owner) {
// var nameProp = aNode.props.get('name');
// var name = nameProp ? nameProp.raw : '____';
// var isGivenContent = 0;
// var childs = aNode.childs;
//
// if (owner.aNode.givenSlots[name]) {
// isGivenContent = 1;
// childs = owner.aNode.givenSlots[name];
// }
//
// var stumpText = (!isGivenContent ? '!' : '')
// + (nameProp ? nameProp.raw : '');
// sourceBuffer.joinString(serializeStump('slot', stumpText));
//
// if (isGivenContent) {
// sourceBuffer.addRaw('(function (componentCtx) {');
// }
//
// each(childs, function (aNodeChild) {
// sourceBuffer.addRaw(aNodeCompiler.compile(aNodeChild, sourceBuffer, owner));
// });
//
// if (isGivenContent) {
// sourceBuffer.addRaw('})(componentCtx.owner);');
// }
//
// sourceBuffer.joinString(serializeStumpEnd('slot'));
// },
//
// /**
// * 编译普通节点
// *
// * @param {ANode} aNode 节点对象
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Component} owner 所属组件实例环境
// * @param {Object} extra 编译所需的一些额外信息
// */
// compileElement: function (aNode, sourceBuffer, owner, extra) {
// extra = extra || {};
// if (aNode.tagName === 'option'
// && !aNode.props.get('value')
// && aNode.childs[0]
// ) {
// aNode.props.push({
// name: 'value',
// expr: aNode.childs[0].textExpr
// });
// }
//
// elementSourceCompiler.tagStart(
// sourceBuffer,
// aNode.tagName,
// aNode.props,
// aNode.props,
// aNode.events,
// aNode,
// extra.prop
// );
//
// elementSourceCompiler.inner(sourceBuffer, aNode, owner);
// elementSourceCompiler.tagEnd(sourceBuffer, aNode.tagName);
// },
//
// /**
// * 编译组件节点
// *
// * @param {ANode} aNode 节点对象
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Component} owner 所属组件实例环境
// * @param {Object} extra 编译所需的一些额外信息
// * @param {Function} extra.ComponentClass 对应组件类
// */
// compileComponent: function (aNode, sourceBuffer, owner, extra) {
// var ComponentClass = extra.ComponentClass;
// var component = new ComponentClass({
// aNode: aNode,
// owner: owner,
// subTag: aNode.tagName
// });
//
// var givenData = [];
//
// postComponentBinds(aNode.props);
// component.binds.each(function (prop) {
// givenData.push(
// compileExprSource.stringLiteralize(prop.name)
// + ':'
// + compileExprSource.expr(prop.expr)
// );
// });
//
// sourceBuffer.addRaw('html += (');
// sourceBuffer.addRendererStart();
// compileComponentSource(sourceBuffer, component, extra && extra.prop);
// sourceBuffer.addRendererEnd();
// sourceBuffer.addRaw(')({' + givenData.join(',\n') + '}, componentCtx);');
// }
// };
//
// /* eslint-disable guard-for-in */
//
// /**
// * 生成组件 renderer 时 ctx 对象构建的代码
// *
// * @inner
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Object} component 组件实例
// * @param {string?} extraProp 额外的属性串
// */
// function compileComponentSource(sourceBuffer, component, extraProp) {
// sourceBuffer.addRaw(genComponentContextCode(component));
// sourceBuffer.addRaw('componentCtx.owner = parentCtx;');
// sourceBuffer.addRaw('data = extend(componentCtx.data, data);');
// sourceBuffer.addRaw('for (var $i = 0; $i < componentCtx.computedNames.length; $i++) {');
// sourceBuffer.addRaw('var $computedName = componentCtx.computedNames[$i];');
// sourceBuffer.addRaw('data[$computedName] = componentCtx.computed[$computedName]();');
// sourceBuffer.addRaw('}');
//
// extraProp = extraProp || '';
// if (component.subTag) {
// extraProp += ' s-component="' + component.subTag + '"';
// }
//
// var refDirective = component.aNode.directives.get('ref');
// if (refDirective) {
// extraProp += ' s-ref="' + refDirective.value.raw + '"';
// }
//
// var eventDeclarations = [];
// for (var key in component.listeners) {
// each(component.listeners[key], function (listener) {
// if (listener.declaration) {
// eventDeclarations.push(listener.declaration);
// }
// });
// }
//
// elementSourceCompiler.tagStart(
// sourceBuffer,
// component.tagName,
// component.props,
// component.binds,
// eventDeclarations,
// component.aNode,
// extraProp,
// 1
// );
//
// if (!component.owner) {
// sourceBuffer.joinString('<!--s-data:');
// sourceBuffer.joinDataStringify();
// sourceBuffer.joinString('-->');
// }
//
// elementSourceCompiler.inner(sourceBuffer, component.aNode, component);
// elementSourceCompiler.tagEnd(sourceBuffer, component.tagName);
// }
//
// var stringifier = {
// obj: function (source) {
// var prefixComma;
// var result = '{';
//
// for (var key in source) {
// if (prefixComma) {
// result += ',';
// }
// prefixComma = 1;
//
// result += compileExprSource.stringLiteralize(key) + ':' + stringifier.any(source[key]);
// }
//
// return result + '}';
// },
//
// arr: function (source) {
// var prefixComma;
// var result = '[';
//
// each(source, function (value) {
// if (prefixComma) {
// result += ',';
// }
// prefixComma = 1;
//
// result += stringifier.any(value);
// });
//
// return result + ']';
// },
//
// str: function (source) {
// return compileExprSource.stringLiteralize(source);
// },
//
// date: function (source) {
// return 'new Date(' + source.getTime() + ')';
// },
//
// any: function (source) {
// switch (typeof source) {
// case 'string':
// return stringifier.str(source);
//
// case 'number':
// return '' + source;
//
// case 'boolean':
// return source ? 'true' : 'false';
//
// case 'object':
// if (!source) {
// return null;
// }
//
// if (source instanceof Array) {
// return stringifier.arr(source);
// }
//
// if (source instanceof Date) {
// return stringifier.date(source);
// }
//
// return stringifier.obj(source);
// }
//
// throw new Error('Cannot Stringify:' + source);
// }
// };
//
// /**
// * 生成组件 renderer 时 ctx 对象构建的代码
// *
// * @inner
// * @param {Object} component 组件实例
// * @return {string}
// */
// function genComponentContextCode(component) {
// var code = ['var componentCtx = {'];
//
// // filters
// code.push('filters: {');
// var filterCode = [];
// for (var key in component.filters) {
// var filter = component.filters[key];
//
// if (typeof filter === 'function') {
// filterCode.push(key + ': ' + filter.toString());
// }
// }
// code.push(filterCode.join(','));
// code.push('},');
//
// code.push(
// 'callFilter: function (name, args) {',
// ' var filter = this.filters[name] || DEFAULT_FILTERS[name];',
// ' if (typeof filter === "function") {',
// ' return filter.apply(this, args);',
// ' }',
// '},'
// );
//
// /* eslint-disable no-redeclare */
// // computed obj
// code.push('computed: {');
// var computedCode = [];
// for (var key in component.computed) {
// var computed = component.computed[key];
//
// if (typeof computed === 'function') {
// computedCode.push(key + ': '
// + computed.toString().replace(
// /this.data.get\(([^\)]+)\)/g,
// function (match, exprLiteral) {
// var exprStr = (new Function('return ' + exprLiteral))();
// var expr = parseExpr(exprStr);
//
// return compileExprSource.expr(expr);
// })
// );
// }
// }
// code.push(computedCode.join(','));
// code.push('},');
//
// // computed names
// code.push('computedNames: [');
// computedCode = [];
// for (var key in component.computed) {
// var computed = component.computed[key];
//
// if (typeof computed === 'function') {
// computedCode.push('"' + key + '"');
// }
// }
// code.push(computedCode.join(','));
// code.push('],');
// /* eslint-enable no-redeclare */
//
// // data
// code.push('data: ' + stringifier.any(component.data.get()) + ',');
//
// // tagName
// code.push('tagName: "' + component.tagName + '"');
// code.push('};');
//
// return code.join('\n');
// }
//
// /* eslint-enable guard-for-in */
//
// /* eslint-disable no-unused-vars */
// /* eslint-disable fecs-camelcase */
//
// /**
// * 组件编译的模板函数
// *
// * @inner
// */
// function componentCompilePreCode() {
// var $version = '3.2.5';
//
// function extend(target, source) {
// if (source) {
// Object.keys(source).forEach(function (key) {
// target[key] = source[key];
// });
// }
//
// return target;
// }
//
// function each(array, iterator) {
// if (array && array.length > 0) {
// for (var i = 0, l = array.length; i < l; i++) {
// if (iterator(array[i], i) === false) {
// break;
// }
// }
// }
// }
//
// function contains(array, value) {
// var result;
// each(array, function (item) {
// result = item === value;
// return !result;
// });
//
// return result;
// }
//
// var HTML_ENTITY = {
// /* jshint ignore:start */
// '&': '&',
// '<': '<',
// '>': '>',
// '"': '"',
// /* eslint-disable quotes */
// "'": '''
// /* eslint-enable quotes */
// /* jshint ignore:end */
// };
//
// function htmlFilterReplacer(c) {
// return HTML_ENTITY[c];
// }
//
// function escapeHTML(source) {
// if (source == null) {
// return '';
// }
//
// return String(source).replace(/[&<>"']/g, htmlFilterReplacer);
// }
//
// var DEFAULT_FILTERS = {
// html: escapeHTML,
// url: encodeURIComponent,
// raw: function (source) {
// return source;
// },
// _class: function (source) {
// if (source instanceof Array) {
// return source.join(' ');
// }
//
// return source;
// },
// _style: function (source) {
// if (typeof source === 'object') {
// var result = '';
// if (source) {
// Object.keys(source).forEach(function (key) {
// result += key + ':' + source[key] + ';';
// });
// }
//
// return result;
// }
//
// return source || '';
// },
// _sep: function (source, sep) {
// return source ? sep + source : '';
// }
// };
//
// function attrFilter(name, value) {
// if (value) {
// return ' ' + name + '="' + value + '"';
// }
//
// return '';
// }
//
// function boolAttrFilter(name, value) {
// if (value && value !== 'false' && value !== '0') {
// return ' ' + name;
// }
//
// return '';
// }
//
// function stringLiteralize(source) {
// return '"'
// + source
// .replace(/\x5C/g, '\\\\')
// .replace(/"/g, '\\"')
// .replace(/\x0A/g, '\\n')
// .replace(/\x09/g, '\\t')
// .replace(/\x0D/g, '\\r')
// + '"';
// }
//
// var stringifier = {
// obj: function (source) {
// var prefixComma;
// var result = '{';
//
// Object.keys(source).forEach(function (key) {
// if (prefixComma) {
// result += ',';
// }
// prefixComma = 1;
//
// result += stringLiteralize(key) + ':' + stringifier.any(source[key]);
// });
//
// return result + '}';
// },
//
// arr: function (source) {
// var prefixComma;
// var result = '[';
//
// each(source, function (value) {
// if (prefixComma) {
// result += ',';
// }
// prefixComma = 1;
//
// result += stringifier.any(value);
// });
//
// return result + ']';
// },
//
// str: function (source) {
// return stringLiteralize(source);
// },
//
// date: function (source) {
// return 'new Date(' + source.getTime() + ')';
// },
//
// any: function (source) {
// switch (typeof source) {
// case 'string':
// return stringifier.str(source);
//
// case 'number':
// return '' + source;
//
// case 'boolean':
// return source ? 'true' : 'false';
//
// case 'object':
// if (!source) {
// return null;
// }
//
// if (source instanceof Array) {
// return stringifier.arr(source);
// }
//
// if (source instanceof Date) {
// return stringifier.date(source);
// }
//
// return stringifier.obj(source);
// }
//
// throw new Error('Cannot Stringify:' + source);
// }
// };
// }
// /* eslint-enable no-unused-vars */
// /* eslint-enable fecs-camelcase */
//
// /**
// * 将组件编译成 render 方法的 js 源码
// *
// * @param {Function} ComponentClass 组件类
// * @return {string}
// */
// function compileJSSource(ComponentClass) {
// var sourceBuffer = new CompileSourceBuffer();
//
// sourceBuffer.addRendererStart();
// sourceBuffer.addRaw(
// componentCompilePreCode.toString()
// .split('\n')
// .slice(1)
// .join('\n')
// .replace(/\}\s*$/, '')
// );
//
// // 先初始化个实例,让模板编译成 ANode,并且能获得初始化数据
// var component = new ComponentClass();
//
// compileComponentSource(sourceBuffer, component);
// sourceBuffer.addRendererEnd();
// return sourceBuffer.toCode();
// }
// #[end]
// exports = module.exports = compileJSSource;
/* eslint-disable no-unused-vars */
// var nextTick = require('./util/next-tick');
// var inherits = require('./util/inherits');
// var parseTemplate = require('./parser/parse-template');
// var parseExpr = require('./parser/parse-expr');
// var ExprType = require('./parser/expr-type');
// var LifeCycle = require('./view/life-cycle');
// var Component = require('./view/component');
// var defineComponent = require('./view/define-component');
// var emitDevtool = require('./util/emit-devtool');
// var compileJSSource = require('./view/compile-js-source');
// var DataTypes = require('./util/data-types');
var san = {
/**
* san版本号
*
* @type {string}
*/
version: '3.2.5',
// #[begin] devtool
// /**
// * 是否开启调试。开启调试时 devtool 会工作
// *
// * @type {boolean}
// */
// debug: true,
// #[end]
// #[begin] ssr
// /**
// * 将组件类编译成 renderer 方法
// *
// * @param {Function} ComponentClass 组件类
// * @return {function(Object):string}
// */
// compileToRenderer: function (ComponentClass) {
// var renderer = ComponentClass.__ssrRenderer;
//
// if (!renderer) {
// var code = compileJSSource(ComponentClass);
// renderer = (new Function('return ' + code))();
// ComponentClass.__ssrRenderer = renderer;
// }
//
// return renderer;
// },
//
// /**
// * 将组件类编译成 renderer 方法的源文件
// *
// * @param {Function} ComponentClass 组件类
// * @return {string}
// */
// compileToSource: compileJSSource,
// #[end]
/**
* 组件基类
*
* @type {Function}
*/
Component: Component,
/**
* 创建组件类
*
* @param {Object} proto 组件类的方法表
* @return {Function}
*/
defineComponent: defineComponent,
/**
* 解析 template
*
* @inner
* @param {string} source template 源码
* @return {ANode}
*/
parseTemplate: parseTemplate,
/**
* 解析表达式
*
* @param {string} source 源码
* @return {Object}
*/
parseExpr: parseExpr,
/**
* 表达式类型枚举
*
* @const
* @type {Object}
*/
ExprType: ExprType,
/**
* 生命周期类
*
* @class
*/
LifeCycle: LifeCycle,
/**
* 在下一个更新周期运行函数
*
* @param {Function} fn 要运行的函数
*/
nextTick: nextTick,
/**
* 构建类之间的继承关系
*
* @param {Function} subClass 子类函数
* @param {Function} superClass 父类函数
*/
inherits: inherits,
/**
* DataTypes
*
* @type {Object}
*/
DataTypes: DataTypes
};
// export
if (typeof exports === 'object' && typeof module === 'object') {
// For CommonJS
exports = module.exports = san;
}
else if (typeof define === 'function' && define.amd) {
// For AMD
define('san', [], san);
}
else {
// For <script src="..."
root.san = san;
}
// #[begin] devtool
// emitDevtool.start(san);
// #[end]
})(this);
| extend1994/cdnjs | ajax/libs/san/3.2.5/san.spa.js | JavaScript | mit | 230,053 | 23.840073 | 115 | 0.514213 | false |
var searchData=
[
['isprimitivetype_2eh',['IsPrimitiveType.h',['../a00178.html',1,'']]]
];
| h-iwata/MultiplayPaint | proj.ios_mac/Photon-iOS_SDK/doc/cpp/html/search/files_7.js | JavaScript | mit | 93 | 22.25 | 71 | 0.623656 | false |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_raw_socket::async_send_to (2 of 2 overloads)</title>
<link rel="stylesheet" href="../../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../../index.html" title="Asio">
<link rel="up" href="../async_send_to.html" title="basic_raw_socket::async_send_to">
<link rel="prev" href="overload1.html" title="basic_raw_socket::async_send_to (1 of 2 overloads)">
<link rel="next" href="../at_mark.html" title="basic_raw_socket::at_mark">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr><td valign="top"><img alt="asio C++ library" width="250" height="60" src="../../../../asio.png"></td></tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload1.html"><img src="../../../../prev.png" alt="Prev"></a><a accesskey="u" href="../async_send_to.html"><img src="../../../../up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../home.png" alt="Home"></a><a accesskey="n" href="../at_mark.html"><img src="../../../../next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h5 class="title">
<a name="asio.reference.basic_raw_socket.async_send_to.overload2"></a><a class="link" href="overload2.html" title="basic_raw_socket::async_send_to (2 of 2 overloads)">basic_raw_socket::async_send_to
(2 of 2 overloads)</a>
</h5></div></div></div>
<p>
Start an asynchronous send.
</p>
<pre class="programlisting"><span class="keyword">template</span><span class="special"><</span>
<span class="keyword">typename</span> <a class="link" href="../../ConstBufferSequence.html" title="Constant buffer sequence requirements">ConstBufferSequence</a><span class="special">,</span>
<span class="keyword">typename</span> <a class="link" href="../../WriteHandler.html" title="Write handler requirements">WriteHandler</a><span class="special">></span>
<a class="link" href="../../asynchronous_operations.html#asio.reference.asynchronous_operations.return_type_of_an_initiating_function"><span class="emphasis"><em>void-or-deduced</em></span></a> <span class="identifier">async_send_to</span><span class="special">(</span>
<span class="keyword">const</span> <span class="identifier">ConstBufferSequence</span> <span class="special">&</span> <span class="identifier">buffers</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">endpoint_type</span> <span class="special">&</span> <span class="identifier">destination</span><span class="special">,</span>
<span class="identifier">socket_base</span><span class="special">::</span><span class="identifier">message_flags</span> <span class="identifier">flags</span><span class="special">,</span>
<span class="identifier">WriteHandler</span> <span class="identifier">handler</span><span class="special">);</span>
</pre>
<p>
This function is used to asynchronously send raw data to the specified
remote endpoint. The function call always returns immediately.
</p>
<h6>
<a name="asio.reference.basic_raw_socket.async_send_to.overload2.h0"></a>
<span><a name="asio.reference.basic_raw_socket.async_send_to.overload2.parameters"></a></span><a class="link" href="overload2.html#asio.reference.basic_raw_socket.async_send_to.overload2.parameters">Parameters</a>
</h6>
<div class="variablelist">
<p class="title"><b></b></p>
<dl>
<dt><span class="term">buffers</span></dt>
<dd><p>
One or more data buffers to be sent to the remote endpoint. Although
the buffers object may be copied as necessary, ownership of the
underlying memory blocks is retained by the caller, which must
guarantee that they remain valid until the handler is called.
</p></dd>
<dt><span class="term">flags</span></dt>
<dd><p>
Flags specifying how the send call is to be made.
</p></dd>
<dt><span class="term">destination</span></dt>
<dd><p>
The remote endpoint to which the data will be sent. Copies will
be made of the endpoint as required.
</p></dd>
<dt><span class="term">handler</span></dt>
<dd>
<p>
The handler to be called when the send operation completes. Copies
will be made of the handler as required. The function signature
of the handler must be:
</p>
<pre class="programlisting"><span class="keyword">void</span> <span class="identifier">handler</span><span class="special">(</span>
<span class="keyword">const</span> <span class="identifier">asio</span><span class="special">::</span><span class="identifier">error_code</span><span class="special">&</span> <span class="identifier">error</span><span class="special">,</span> <span class="comment">// Result of operation.</span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <span class="identifier">bytes_transferred</span> <span class="comment">// Number of bytes sent.</span>
<span class="special">);</span>
</pre>
<p>
Regardless of whether the asynchronous operation completes immediately
or not, the handler will not be invoked from within this function.
Invocation of the handler will be performed in a manner equivalent
to using <code class="computeroutput"><span class="identifier">asio</span><span class="special">::</span><span class="identifier">io_service</span><span class="special">::</span><span class="identifier">post</span><span class="special">()</span></code>.
</p>
</dd>
</dl>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2015 Christopher M.
Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload1.html"><img src="../../../../prev.png" alt="Prev"></a><a accesskey="u" href="../async_send_to.html"><img src="../../../../up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../home.png" alt="Home"></a><a accesskey="n" href="../at_mark.html"><img src="../../../../next.png" alt="Next"></a>
</div>
</body>
</html>
| otgaard/zap | third_party/asio/doc/asio/reference/basic_raw_socket/async_send_to/overload2.html | HTML | mit | 6,854 | 68.938776 | 356 | 0.643858 | false |
/*
* Block.h
*
* Copyright (c) 2008-2010 Apple Inc. All rights reserved.
*
* @APPLE_LLVM_LICENSE_HEADER@
*
*/
#ifndef _Block_H_
#define _Block_H_
#if !defined(BLOCK_EXPORT)
# if defined(__cplusplus)
# define BLOCK_EXPORT extern "C"
# else
# define BLOCK_EXPORT extern
# endif
#endif
#include <Availability.h>
#include <TargetConditionals.h>
#if __cplusplus
extern "C" {
#endif
// Create a heap based copy of a Block or simply add a reference to an existing one.
// This must be paired with Block_release to recover memory, even when running
// under Objective-C Garbage Collection.
BLOCK_EXPORT void *_Block_copy(const void *aBlock)
__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_2);
// Lose the reference, and if heap based and last reference, recover the memory
BLOCK_EXPORT void _Block_release(const void *aBlock)
__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_2);
// Used by the compiler. Do not call this function yourself.
BLOCK_EXPORT void _Block_object_assign(void *, const void *, const int)
__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_2);
// Used by the compiler. Do not call this function yourself.
BLOCK_EXPORT void _Block_object_dispose(const void *, const int)
__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_2);
// Used by the compiler. Do not use these variables yourself.
BLOCK_EXPORT void * _NSConcreteGlobalBlock[32]
__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_2);
BLOCK_EXPORT void * _NSConcreteStackBlock[32]
__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_2);
#if __cplusplus
}
#endif
// Type correct macros
#define Block_copy(...) ((__typeof(__VA_ARGS__))_Block_copy((const void *)(__VA_ARGS__)))
#define Block_release(...) _Block_release((const void *)(__VA_ARGS__))
#endif
| e-t-h-a-n/esdarwin | macos-10124/esdarwin-destroot-b1/usr/include/Block.h | C | mit | 1,775 | 26.734375 | 89 | 0.686761 | false |
/*
* # Semantic - Segment
* http://github.com/jlukic/semantic-ui/
*
*
* Copyright 2013 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
/*******************************
Segment
*******************************/
.ui.segment {
position: relative;
background-color: #FFFFFF;
-webkit-box-shadow: 0px 0px 0px 1px rgba(0, 0, 0, 0.1);
box-shadow: 0px 0px 0px 1px rgba(0, 0, 0, 0.1);
margin: 1em 0em;
padding: 1em;
border-radius: 5px 5px 5px 5px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
}
.ui.segment:first-child {
margin-top: 0em;
}
.ui.segment:last-child {
margin-bottom: 0em;
}
.ui.segment:after {
content: '';
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.ui.vertical.segment {
margin: 0em;
padding-left: 0em;
padding-right: 0em;
background-color: transparent;
border-radius: 0px;
-webkit-box-shadow: 0px 1px 0px rgba(0, 0, 0, 0.1);
box-shadow: 0px 1px 0px rgba(0, 0, 0, 0.1);
}
.ui.vertical.segment:first-child {
padding-top: 0em;
}
.ui.horizontal.segment {
margin: 0em;
padding-top: 0em;
padding-bottom: 0em;
background-color: transparent;
border-radius: 0px;
-webkit-box-shadow: 1px 0px 0px rgba(0, 0, 0, 0.1);
box-shadow: 1px 0px 0px rgba(0, 0, 0, 0.1);
}
.ui.horizontal.segment:first-child {
padding-left: 0em;
}
/*-------------------
Loose Coupling
--------------------*/
.ui.pointing.menu ~ .ui.attached.segment {
top: 1px;
}
.ui.page.grid.segment .ui.grid .ui.segment.column {
padding-top: 2rem;
padding-bottom: 2rem;
}
.ui.grid.segment,
.ui.grid .ui.segment.row,
.ui.grid .ui.segment.column {
border-radius: 0em;
-webkit-box-shadow: none;
box-shadow: none;
border: none;
}
/* No padding on edge content */
.ui.segment > :first-child {
margin-top: 0em;
}
.ui.segment > :last-child {
margin-bottom: 0em;
}
/*******************************
Types
*******************************/
/*-------------------
Piled
--------------------*/
.ui.piled.segment {
margin: 2em 0em;
-webkit-box-shadow: 0px 0px 1px 1px rgba(0, 0, 0, 0.15);
-ms-box-shadow: 0px 0px 1px 1px rgba(0, 0, 0, 0.15);
-o-box-shadow: 0px 0px 1px 1px rgba(0, 0, 0, 0.15);
box-shadow: 0px 0px 1px 1px rgba(0, 0, 0, 0.15);
}
.ui.piled.segment:first-child {
margin-top: 0em;
}
.ui.piled.segment:last-child {
margin-bottom: 0em;
}
.ui.piled.segment:after,
.ui.piled.segment:before {
background-color: #FFFFFF;
visibility: visible;
content: "";
display: block;
height: 100%;
left: -1px;
position: absolute;
width: 100%;
-webkit-box-shadow: 0px 0px 1px 1px rgba(0, 0, 0, 0.1);
box-shadow: 0px 0px 1px 1px rgba(0, 0, 0, 0.1);
}
.ui.piled.segment:after {
-webkit-transform: rotate(1.2deg);
-moz-transform: rotate(1.2deg);
-ms-transform: rotate(1.2deg);
transform: rotate(1.2deg);
top: 0;
z-index: -1;
}
.ui.piled.segment:before {
-webkit-transform: rotate(-1.2deg);
-moz-transform: rotate(-1.2deg);
-ms-transform: rotate(-1.2deg);
transform: rotate(-1.2deg);
top: 0;
z-index: -2;
}
/*-------------------
Stacked
--------------------*/
.ui.stacked.segment {
padding-bottom: 1.7em;
}
.ui.stacked.segment:after,
.ui.stacked.segment:before {
content: '';
position: absolute;
bottom: -3px;
left: 0%;
border-top: 1px solid rgba(0, 0, 0, 0.1);
background-color: rgba(0, 0, 0, 0.02);
width: 100%;
height: 5px;
visibility: visible;
}
.ui.stacked.segment:before {
bottom: 0px;
}
/* Inverted */
.ui.stacked.inverted.segment:after,
.ui.stacked.inverted.segment:before {
background-color: rgba(255, 255, 255, 0.1);
border-top: 1px solid rgba(255, 255, 255, 0.35);
}
/*-------------------
Circular
--------------------*/
.ui.circular.segment {
display: table-cell;
padding: 2em;
text-align: center;
vertical-align: middle;
border-radius: 500em;
}
/*-------------------
Raised
--------------------*/
.ui.raised.segment {
-webkit-box-shadow: 0px 1px 2px 1px rgba(0, 0, 0, 0.1);
box-shadow: 0px 1px 2px 1px rgba(0, 0, 0, 0.1);
}
/*******************************
States
*******************************/
.ui.disabled.segment {
opacity: 0.8;
color: #DDDDDD;
}
/*******************************
Variations
*******************************/
/*-------------------
Basic
--------------------*/
.ui.basic.segment {
position: relative;
background-color: transparent;
-webkit-box-shadow: none;
box-shadow: none;
border-radius: 0px;
}
.ui.basic.segment:first-child {
padding-top: 0em;
}
.ui.basic.segment:last-child {
padding-bottom: 0em;
}
/*-------------------
Fittted
--------------------*/
.ui.fitted.segment {
padding: 0em;
}
/*-------------------
Colors
--------------------*/
.ui.blue.segment {
border-top: 0.2em solid #6ECFF5;
}
.ui.green.segment {
border-top: 0.2em solid #A1CF64;
}
.ui.red.segment {
border-top: 0.2em solid #D95C5C;
}
.ui.orange.segment {
border-top: 0.2em solid #F05940;
}
.ui.purple.segment {
border-top: 0.2em solid #564F8A;
}
.ui.teal.segment {
border-top: 0.2em solid #00B5AD;
}
/*-------------------
Inverted Colors
--------------------*/
.ui.inverted.black.segment {
background-color: #5C6166 !important;
color: #FFFFFF !important;
}
.ui.inverted.blue.segment {
background-color: #6ECFF5 !important;
color: #FFFFFF !important;
}
.ui.inverted.green.segment {
background-color: #A1CF64 !important;
color: #FFFFFF !important;
}
.ui.inverted.red.segment {
background-color: #D95C5C !important;
color: #FFFFFF !important;
}
.ui.inverted.orange.segment {
background-color: #F05940 !important;
color: #FFFFFF !important;
}
.ui.inverted.purple.segment {
background-color: #564F8A !important;
color: #FFFFFF !important;
}
.ui.inverted.teal.segment {
background-color: #00B5AD !important;
color: #FFFFFF !important;
}
/*-------------------
Aligned
--------------------*/
.ui.left.aligned.segment {
text-align: left;
}
.ui.right.aligned.segment {
text-align: right;
}
.ui.center.aligned.segment {
text-align: center;
}
.ui.justified.segment {
text-align: justify;
-webkit-hyphens: auto;
-moz-hyphens: auto;
-ms-hyphens: auto;
hyphens: auto;
}
/*-------------------
Floated
--------------------*/
.ui.floated.segment,
.ui.left.floated.segment {
float: left;
}
.ui.right.floated.segment {
float: right;
}
/*-------------------
Inverted
--------------------*/
.ui.inverted.segment {
border: none;
-webkit-box-shadow: none;
box-shadow: none;
}
.ui.inverted.segment .segment {
color: rgba(0, 0, 0, 0.7);
}
.ui.inverted.segment .inverted.segment {
color: #FFFFFF;
}
.ui.inverted.segment,
.ui.primary.inverted.segment {
background-color: #222222;
color: #FFFFFF;
}
/*-------------------
Ordinality
--------------------*/
.ui.primary.segment {
background-color: #FFFFFF;
color: #555555;
}
.ui.secondary.segment {
background-color: #FAF9FA;
color: #777777;
}
.ui.tertiary.segment {
background-color: #EBEBEB;
color: #B0B0B0;
}
.ui.secondary.inverted.segment {
background-color: #555555;
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(rgba(255, 255, 255, 0.3)), to(rgba(255, 255, 255, 0.3)));
background-image: -webkit-linear-gradient(rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0.3) 100%);
background-image: -moz-linear-gradient(rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0.3) 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(255, 255, 255, 0.3)), to(rgba(255, 255, 255, 0.3)));
background-image: linear-gradient(rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0.3) 100%);
color: #FAFAFA;
}
.ui.tertiary.inverted.segment {
background-color: #555555;
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(rgba(255, 255, 255, 0.6)), to(rgba(255, 255, 255, 0.6)));
background-image: -webkit-linear-gradient(rgba(255, 255, 255, 0.6) 0%, rgba(255, 255, 255, 0.6) 100%);
background-image: -moz-linear-gradient(rgba(255, 255, 255, 0.6) 0%, rgba(255, 255, 255, 0.6) 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(255, 255, 255, 0.6)), to(rgba(255, 255, 255, 0.6)));
background-image: linear-gradient(rgba(255, 255, 255, 0.6) 0%, rgba(255, 255, 255, 0.6) 100%);
color: #EEEEEE;
}
/*-------------------
Attached
--------------------*/
.ui.segment.attached {
top: -1px;
bottom: -1px;
border-radius: 0px;
margin: 0em;
-webkit-box-shadow: 0px 0px 0px 1px #DDDDDD;
box-shadow: 0px 0px 0px 1px #DDDDDD;
}
.ui.top.attached.segment {
top: 0px;
bottom: -1px;
margin-top: 1em;
margin-bottom: 0em;
border-radius: 5px 5px 0px 0px;
}
.ui.segment.top.attached:first-child {
margin-top: 0em;
}
.ui.segment.bottom.attached {
top: -1px;
bottom: 0px;
margin-top: 0em;
margin-bottom: 1em;
border-radius: 0px 0px 5px 5px;
}
.ui.segment.bottom.attached:last-child {
margin-bottom: 0em;
}
.ui.stacked.segment{
width: 896px;
} | pygamebrasil/pygame-site | src/app/static/css/segment.css | CSS | mit | 9,093 | 22.931579 | 130 | 0.592544 | false |
---
description: A training for advanced development on the Auth0 platform.
---
# Training: Auth0 Advanced Topics
A training for advanced development on the Auth0 platform. Target audience is developers and solution architects.
## Duration
8 hours.
## Level
**Level 300-400**: deep dive into Auth0 platform capabilities. Course focuses on advanced topics, extensibility, performance optimizations and advanced integrations.
## Topics covered
Deep dive on architecture, extensibility points, proven practices for high performance, scalability, and high availability.
<%= include('../_includes/_contact-sales') %>
| hamzawi06/docs | articles/services/auth0-advanced.md | Markdown | mit | 623 | 26.086957 | 165 | 0.775281 | false |
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import * as React from 'react';
import PropTypes from 'prop-types';
import PopperJs from 'popper.js';
import { chainPropTypes, refType, HTMLElementType } from '@material-ui/utils';
import { useTheme } from '@material-ui/styles';
import Portal from '../Portal';
import createChainedFunction from '../utils/createChainedFunction';
import setRef from '../utils/setRef';
import useForkRef from '../utils/useForkRef';
function flipPlacement(placement, theme) {
const direction = theme && theme.direction || 'ltr';
if (direction === 'ltr') {
return placement;
}
switch (placement) {
case 'bottom-end':
return 'bottom-start';
case 'bottom-start':
return 'bottom-end';
case 'top-end':
return 'top-start';
case 'top-start':
return 'top-end';
default:
return placement;
}
}
function getAnchorEl(anchorEl) {
return typeof anchorEl === 'function' ? anchorEl() : anchorEl;
}
const useEnhancedEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
const defaultPopperOptions = {};
/**
* Poppers rely on the 3rd party library [Popper.js](https://popper.js.org/docs/v1/) for positioning.
*/
const Popper = /*#__PURE__*/React.forwardRef(function Popper(props, ref) {
const {
anchorEl,
children,
container,
disablePortal = false,
keepMounted = false,
modifiers,
open,
placement: initialPlacement = 'bottom',
popperOptions = defaultPopperOptions,
popperRef: popperRefProp,
style,
transition = false
} = props,
other = _objectWithoutPropertiesLoose(props, ["anchorEl", "children", "container", "disablePortal", "keepMounted", "modifiers", "open", "placement", "popperOptions", "popperRef", "style", "transition"]);
const tooltipRef = React.useRef(null);
const ownRef = useForkRef(tooltipRef, ref);
const popperRef = React.useRef(null);
const handlePopperRef = useForkRef(popperRef, popperRefProp);
const handlePopperRefRef = React.useRef(handlePopperRef);
useEnhancedEffect(() => {
handlePopperRefRef.current = handlePopperRef;
}, [handlePopperRef]);
React.useImperativeHandle(popperRefProp, () => popperRef.current, []);
const [exited, setExited] = React.useState(true);
const theme = useTheme();
const rtlPlacement = flipPlacement(initialPlacement, theme);
/**
* placement initialized from prop but can change during lifetime if modifiers.flip.
* modifiers.flip is essentially a flip for controlled/uncontrolled behavior
*/
const [placement, setPlacement] = React.useState(rtlPlacement);
React.useEffect(() => {
if (popperRef.current) {
popperRef.current.update();
}
});
const handleOpen = React.useCallback(() => {
if (!tooltipRef.current || !anchorEl || !open) {
return;
}
if (popperRef.current) {
popperRef.current.destroy();
handlePopperRefRef.current(null);
}
const handlePopperUpdate = data => {
setPlacement(data.placement);
};
const resolvedAnchorEl = getAnchorEl(anchorEl);
if (process.env.NODE_ENV !== 'production') {
if (resolvedAnchorEl && resolvedAnchorEl.nodeType === 1) {
const box = resolvedAnchorEl.getBoundingClientRect();
if (process.env.NODE_ENV !== 'test' && box.top === 0 && box.left === 0 && box.right === 0 && box.bottom === 0) {
console.warn(['Material-UI: The `anchorEl` prop provided to the component is invalid.', 'The anchor element should be part of the document layout.', "Make sure the element is present in the document or that it's not display none."].join('\n'));
}
}
}
const popper = new PopperJs(getAnchorEl(anchorEl), tooltipRef.current, _extends({
placement: rtlPlacement
}, popperOptions, {
modifiers: _extends({}, disablePortal ? {} : {
// It's using scrollParent by default, we can use the viewport when using a portal.
preventOverflow: {
boundariesElement: 'window'
}
}, modifiers, popperOptions.modifiers),
// We could have been using a custom modifier like react-popper is doing.
// But it seems this is the best public API for this use case.
onCreate: createChainedFunction(handlePopperUpdate, popperOptions.onCreate),
onUpdate: createChainedFunction(handlePopperUpdate, popperOptions.onUpdate)
}));
handlePopperRefRef.current(popper);
}, [anchorEl, disablePortal, modifiers, open, rtlPlacement, popperOptions]);
const handleRef = React.useCallback(node => {
setRef(ownRef, node);
handleOpen();
}, [ownRef, handleOpen]);
const handleEnter = () => {
setExited(false);
};
const handleClose = () => {
if (!popperRef.current) {
return;
}
popperRef.current.destroy();
handlePopperRefRef.current(null);
};
const handleExited = () => {
setExited(true);
handleClose();
};
React.useEffect(() => {
return () => {
handleClose();
};
}, []);
React.useEffect(() => {
if (!open && !transition) {
// Otherwise handleExited will call this.
handleClose();
}
}, [open, transition]);
if (!keepMounted && !open && (!transition || exited)) {
return null;
}
const childProps = {
placement
};
if (transition) {
childProps.TransitionProps = {
in: open,
onEnter: handleEnter,
onExited: handleExited
};
}
return /*#__PURE__*/React.createElement(Portal, {
disablePortal: disablePortal,
container: container
}, /*#__PURE__*/React.createElement("div", _extends({
ref: handleRef,
role: "tooltip"
}, other, {
style: _extends({
// Prevents scroll issue, waiting for Popper.js to add this style once initiated.
position: 'fixed',
// Fix Popper.js display issue
top: 0,
left: 0,
display: !open && keepMounted && !transition ? 'none' : null
}, style)
}), typeof children === 'function' ? children(childProps) : children));
});
process.env.NODE_ENV !== "production" ? Popper.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* A HTML element, [referenceObject](https://popper.js.org/docs/v1/#referenceObject),
* or a function that returns either.
* It's used to set the position of the popper.
* The return value will passed as the reference object of the Popper instance.
*/
anchorEl: chainPropTypes(PropTypes.oneOfType([HTMLElementType, PropTypes.object, PropTypes.func]), props => {
if (props.open) {
const resolvedAnchorEl = getAnchorEl(props.anchorEl);
if (resolvedAnchorEl && resolvedAnchorEl.nodeType === 1) {
const box = resolvedAnchorEl.getBoundingClientRect();
if (process.env.NODE_ENV !== 'test' && box.top === 0 && box.left === 0 && box.right === 0 && box.bottom === 0) {
return new Error(['Material-UI: The `anchorEl` prop provided to the component is invalid.', 'The anchor element should be part of the document layout.', "Make sure the element is present in the document or that it's not display none."].join('\n'));
}
} else if (!resolvedAnchorEl || typeof resolvedAnchorEl.clientWidth !== 'number' || typeof resolvedAnchorEl.clientHeight !== 'number' || typeof resolvedAnchorEl.getBoundingClientRect !== 'function') {
return new Error(['Material-UI: The `anchorEl` prop provided to the component is invalid.', 'It should be an HTML element instance or a referenceObject ', '(https://popper.js.org/docs/v1/#referenceObject).'].join('\n'));
}
}
return null;
}),
/**
* Popper render function or node.
*/
children: PropTypes
/* @typescript-to-proptypes-ignore */
.oneOfType([PropTypes.node, PropTypes.func]).isRequired,
/**
* A HTML element, component instance, or function that returns either.
* The `container` will have the portal children appended to it.
*
* By default, it uses the body of the top-level document object,
* so it's simply `document.body` most of the time.
*/
container: PropTypes
/* @typescript-to-proptypes-ignore */
.oneOfType([HTMLElementType, PropTypes.instanceOf(React.Component), PropTypes.func]),
/**
* The `children` will be inside the DOM hierarchy of the parent component.
*/
disablePortal: PropTypes.bool,
/**
* Always keep the children in the DOM.
* This prop can be useful in SEO situation or
* when you want to maximize the responsiveness of the Popper.
*/
keepMounted: PropTypes.bool,
/**
* Popper.js is based on a "plugin-like" architecture,
* most of its features are fully encapsulated "modifiers".
*
* A modifier is a function that is called each time Popper.js needs to
* compute the position of the popper.
* For this reason, modifiers should be very performant to avoid bottlenecks.
* To learn how to create a modifier, [read the modifiers documentation](https://popper.js.org/docs/v1/#modifiers).
*/
modifiers: PropTypes.object,
/**
* If `true`, the popper is visible.
*/
open: PropTypes.bool.isRequired,
/**
* Popper placement.
*/
placement: PropTypes.oneOf(['bottom-end', 'bottom-start', 'bottom', 'left-end', 'left-start', 'left', 'right-end', 'right-start', 'right', 'top-end', 'top-start', 'top']),
/**
* Options provided to the [`popper.js`](https://popper.js.org/docs/v1/) instance.
*/
popperOptions: PropTypes.object,
/**
* A ref that points to the used popper instance.
*/
popperRef: refType,
/**
* @ignore
*/
style: PropTypes.object,
/**
* Help supporting a react-transition-group/Transition component.
*/
transition: PropTypes.bool
} : void 0;
export default Popper; | cdnjs/cdnjs | ajax/libs/material-ui/5.0.0-alpha.4/es/Popper/Popper.js | JavaScript | mit | 10,081 | 32.719064 | 258 | 0.653209 | false |
```js
// app.js
// Intercept responses and check for anything
// unauthorized. If there is an unauthorized response,
// log the user out and redirect to the home route
Vue.http.interceptors.push({
response: function (response) {
if(response.status === 401) {
this.logout();
this.authenticated = false;
router.go('/');
}
return response;
}
});
``` | hamzawi06/docs | snippets/client-platforms/vuejs/interceptors.md | Markdown | mit | 381 | 21.470588 | 54 | 0.643045 | false |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="robots" content="noindex">
<title>File Mint/Types/DeveloperType.php</title>
<link rel="stylesheet" href="resources/style.css?e99947befd7bf673c6b43ff75e9e0f170c88a60e">
</head>
<body>
<div id="left">
<div id="menu">
<a href="index.html" title="Overview"><span>Overview</span></a>
<div id="groups">
<h3>Namespaces</h3>
<ul>
<li>
<a href="namespace-Apigee.html">
Apigee<span></span>
</a>
<ul>
<li>
<a href="namespace-Apigee.Exceptions.html">
Exceptions </a>
</li>
<li>
<a href="namespace-Apigee.ManagementAPI.html">
ManagementAPI </a>
</li>
<li>
<a href="namespace-Apigee.Mint.html">
Mint<span></span>
</a>
<ul>
<li>
<a href="namespace-Apigee.Mint.Base.html">
Base </a>
</li>
<li>
<a href="namespace-Apigee.Mint.DataStructures.html">
DataStructures </a>
</li>
<li>
<a href="namespace-Apigee.Mint.Exceptions.html">
Exceptions </a>
</li>
<li>
<a href="namespace-Apigee.Mint.Types.html">
Types </a>
</li>
</ul></li>
<li>
<a href="namespace-Apigee.SmartDocs.html">
SmartDocs<span></span>
</a>
<ul>
<li>
<a href="namespace-Apigee.SmartDocs.Security.html">
Security </a>
</li>
</ul></li>
<li>
<a href="namespace-Apigee.test.html">
test<span></span>
</a>
<ul>
<li>
<a href="namespace-Apigee.test.ManagementAPI.html">
ManagementAPI </a>
</li>
</ul></li>
<li>
<a href="namespace-Apigee.Util.html">
Util </a>
</li>
</ul></li>
</ul>
</div>
<hr>
<div id="elements">
<h3>Classes</h3>
<ul>
<li><a href="class-Apigee.Util.APIObject.html">Apigee\Util\APIObject</a></li>
<li><a href="class-Apigee.Util.CacheFactory.html">Apigee\Util\CacheFactory</a></li>
<li><a href="class-Apigee.Util.CacheManager.html">Apigee\Util\CacheManager</a></li>
<li><a href="class-Apigee.Util.DebugData.html">Apigee\Util\DebugData</a></li>
<li><a href="class-Apigee.Util.OrgConfig.html">Apigee\Util\OrgConfig</a></li>
</ul>
</div>
</div>
</div>
<div id="splitter"></div>
<div id="right">
<div id="rightInner">
<form id="search">
<input type="hidden" name="cx" value="">
<input type="hidden" name="ie" value="UTF-8">
<input type="text" name="q" class="text" placeholder="Search">
</form>
<div id="navigation">
<ul>
<li>
<a href="index.html" title="Overview"><span>Overview</span></a>
</li>
<li>
<span>Namespace</span> </li>
<li>
<a href="class-Apigee.Mint.Exceptions.MintApiException.html" title="Summary of Apigee\Mint\Exceptions\MintApiException"><span>Class</span></a>
</li>
</ul>
<ul>
</ul>
<ul>
</ul>
</div>
<pre><code><span id="1" class="l"><a href="#1"> 1: </a><span class="xlang"><?php</span>
</span><span id="2" class="l"><a href="#2"> 2: </a>
</span><span id="3" class="l"><a href="#3"> 3: </a><span class="php-keyword1">namespace</span> Apigee\Mint\Types;
</span><span id="4" class="l"><a href="#4"> 4: </a>
</span><span id="5" class="l"><a href="#5"> 5: </a><span class="php-keyword1">final</span> <span class="php-keyword1">class</span> DeveloperType <span class="php-keyword1">extends</span> Type
</span><span id="6" class="l"><a href="#6"> 6: </a>{
</span><span id="7" class="l"><a href="#7"> 7: </a> <span class="php-keyword1">const</span> TRUSTED = <span class="php-quote">'TRUSTED'</span>;
</span><span id="8" class="l"><a href="#8"> 8: </a> <span class="php-keyword1">const</span> UNTRUSTED = <span class="php-quote">'UNTRUSTED'</span>;
</span><span id="9" class="l"><a href="#9"> 9: </a>}
</span><span id="10" class="l"><a href="#10">10: </a></span></code></pre>
<div id="footer">
API documentation generated by <a href="http://apigen.org">ApiGen</a>
</div>
</div>
</div>
<script src="resources/combined.js?44e93de8fc3b749f55d0fae2da59a38c45b15f0b"></script>
<script src="elementlist.js?2d449b059bc1b466ad1426ddfe5bbce4628bf250"></script>
</body>
</html>
| apigee/edge-php-sdk | docs/source-class-Apigee.Mint.Types.DeveloperType.html | HTML | mit | 4,203 | 24.472727 | 191 | 0.581727 | false |
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _reactIs = require("react-is");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _clsx = _interopRequireDefault(require("clsx"));
var _unstyled = require("@material-ui/unstyled");
var _experimentalStyled = _interopRequireDefault(require("../styles/experimentalStyled"));
var _useThemeProps = _interopRequireDefault(require("../styles/useThemeProps"));
var _bottomNavigationClasses = require("./bottomNavigationClasses");
const overridesResolver = (props, styles) => styles.root || {};
const useUtilityClasses = styleProps => {
const {
classes
} = styleProps;
const slots = {
root: ['root']
};
return (0, _unstyled.unstable_composeClasses)(slots, _bottomNavigationClasses.getBottomNavigationUtilityClass, classes);
};
const BottomNavigationRoot = (0, _experimentalStyled.default)('div', {}, {
name: 'MuiBottomNavigation',
slot: 'Root',
overridesResolver
})(({
theme
}) => ({
/* Styles applied to the root element. */
display: 'flex',
justifyContent: 'center',
height: 56,
backgroundColor: theme.palette.background.paper
}));
const BottomNavigation = /*#__PURE__*/React.forwardRef(function BottomNavigation(inProps, ref) {
const props = (0, _useThemeProps.default)({
props: inProps,
name: 'MuiBottomNavigation'
});
const {
children,
className,
component = 'div',
onChange,
showLabels = false,
value
} = props,
other = (0, _objectWithoutPropertiesLoose2.default)(props, ["children", "className", "component", "onChange", "showLabels", "value"]);
const styleProps = (0, _extends2.default)({}, props, {
component,
showLabels
});
const classes = useUtilityClasses(styleProps);
return /*#__PURE__*/React.createElement(BottomNavigationRoot, (0, _extends2.default)({
as: component,
className: (0, _clsx.default)(classes.root, className),
ref: ref,
styleProps: styleProps
}, other), React.Children.map(children, (child, childIndex) => {
if (! /*#__PURE__*/React.isValidElement(child)) {
return null;
}
if (process.env.NODE_ENV !== 'production') {
if ((0, _reactIs.isFragment)(child)) {
console.error(["Material-UI: The BottomNavigation component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n'));
}
}
const childValue = child.props.value === undefined ? childIndex : child.props.value;
return /*#__PURE__*/React.cloneElement(child, {
selected: childValue === value,
showLabel: child.props.showLabel !== undefined ? child.props.showLabel : showLabels,
value: childValue,
onChange
});
}));
});
process.env.NODE_ENV !== "production" ? BottomNavigation.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The content of the component.
*/
children: _propTypes.default.node,
/**
* Override or extend the styles applied to the component.
*/
classes: _propTypes.default.object,
/**
* @ignore
*/
className: _propTypes.default.string,
/**
* The component used for the root node.
* Either a string to use a HTML element or a component.
*/
component: _propTypes.default.elementType,
/**
* Callback fired when the value changes.
*
* @param {object} event The event source of the callback. **Warning**: This is a generic event not a change event.
* @param {any} value We default to the index of the child.
*/
onChange: _propTypes.default.func,
/**
* If `true`, all `BottomNavigationAction`s will show their labels.
* By default, only the selected `BottomNavigationAction` will show its label.
* @default false
*/
showLabels: _propTypes.default.bool,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: _propTypes.default.object,
/**
* The value of the currently selected `BottomNavigationAction`.
*/
value: _propTypes.default.any
} : void 0;
var _default = BottomNavigation;
exports.default = _default; | cdnjs/cdnjs | ajax/libs/material-ui/5.0.0-alpha.27/node/BottomNavigation/BottomNavigation.js | JavaScript | mit | 4,828 | 30.357143 | 160 | 0.663836 | false |
/*++
/* NAME
/* smtp 3h
/* SUMMARY
/* smtp client program
/* SYNOPSIS
/* #include "smtp.h"
/* DESCRIPTION
/* .nf
/*
* System library.
*/
#include <string.h>
/*
* Utility library.
*/
#include <vstream.h>
#include <vstring.h>
#include <argv.h>
#include <htable.h>
#include <dict.h>
/*
* Global library.
*/
#include <deliver_request.h>
#include <scache.h>
#include <string_list.h>
#include <maps.h>
#include <tok822.h>
#include <dsn_buf.h>
#include <header_body_checks.h>
/*
* Postfix TLS library.
*/
#include <tls.h>
/*
* Global iterator support. This is updated by the connection-management
* loop, and contains dynamic context that appears in lookup keys for SASL
* passwords, TLS policy, cached SMTP connections, and cached TLS session
* keys.
*
* For consistency and maintainability, context that is used in more than one
* lookup key is formatted with smtp_key_format().
*/
typedef struct SMTP_ITERATOR {
/* Public members. */
VSTRING *request_nexthop; /* request nexhop or empty */
VSTRING *dest; /* current nexthop */
VSTRING *host; /* hostname or empty */
VSTRING *addr; /* printable address or empty */
unsigned port; /* network byte order or null */
struct DNS_RR *rr; /* DNS resource record or null */
struct DNS_RR *mx; /* DNS resource record or null */
/* Private members. */
VSTRING *saved_dest; /* saved current nexthop */
struct SMTP_STATE *parent; /* parent linkage */
} SMTP_ITERATOR;
#define SMTP_ITER_INIT(iter, _dest, _host, _addr, _port, state) do { \
vstring_strcpy((iter)->dest, (_dest)); \
vstring_strcpy((iter)->host, (_host)); \
vstring_strcpy((iter)->addr, (_addr)); \
(iter)->port = (_port); \
(iter)->mx = (iter)->rr = 0; \
vstring_strcpy((iter)->saved_dest, ""); \
(iter)->parent = (state); \
} while (0)
#define SMTP_ITER_CLOBBER(iter, _dest, _host, _addr) do { \
vstring_strcpy((iter)->dest, (_dest)); \
vstring_strcpy((iter)->host, (_host)); \
vstring_strcpy((iter)->addr, (_addr)); \
} while (0)
#define SMTP_ITER_SAVE_DEST(iter) do { \
vstring_strcpy((iter)->saved_dest, STR((iter)->dest)); \
} while (0)
#define SMTP_ITER_RESTORE_DEST(iter) do { \
vstring_strcpy((iter)->dest, STR((iter)->saved_dest)); \
} while (0)
/*
* TLS Policy support.
*/
#ifdef USE_TLS
typedef struct SMTP_TLS_POLICY {
int level; /* TLS enforcement level */
char *protocols; /* Acceptable SSL protocols */
char *grade; /* Cipher grade: "export", ... */
VSTRING *exclusions; /* Excluded SSL ciphers */
ARGV *matchargv; /* Cert match patterns */
DSN_BUF *why; /* Lookup error status */
TLS_DANE *dane; /* DANE TLSA digests */
} SMTP_TLS_POLICY;
/*
* smtp_tls_policy.c
*/
extern void smtp_tls_list_init(void);
extern int smtp_tls_policy_cache_query(DSN_BUF *, SMTP_TLS_POLICY *, SMTP_ITERATOR *);
extern void smtp_tls_policy_cache_flush(void);
/*
* Macros must use distinct names for local temporary variables, otherwise
* there will be bugs due to shadowing. This happened when an earlier
* version of smtp_tls_policy_dummy() invoked smtp_tls_policy_init(), but it
* could also happen without macro nesting.
*
* General principle: use all or part of the macro name in each temporary
* variable name. Then, append suffixes to the names if needed.
*/
#define smtp_tls_policy_dummy(t) do { \
SMTP_TLS_POLICY *_tls_policy_dummy_tmp = (t); \
smtp_tls_policy_init(_tls_policy_dummy_tmp, (DSN_BUF *) 0); \
_tls_policy_dummy_tmp->level = TLS_LEV_NONE; \
} while (0)
/* This macro is not part of the module external interface. */
#define smtp_tls_policy_init(t, w) do { \
SMTP_TLS_POLICY *_tls_policy_init_tmp = (t); \
_tls_policy_init_tmp->protocols = 0; \
_tls_policy_init_tmp->grade = 0; \
_tls_policy_init_tmp->exclusions = 0; \
_tls_policy_init_tmp->matchargv = 0; \
_tls_policy_init_tmp->why = (w); \
_tls_policy_init_tmp->dane = 0; \
} while (0)
#endif
/*
* State information associated with each SMTP delivery request.
* Session-specific state is stored separately.
*/
typedef struct SMTP_STATE {
int misc_flags; /* processing flags, see below */
VSTREAM *src; /* queue file stream */
const char *service; /* transport name */
DELIVER_REQUEST *request; /* envelope info, offsets */
struct SMTP_SESSION *session; /* network connection */
int status; /* delivery status */
ssize_t space_left; /* output length control */
/*
* Global iterator.
*/
SMTP_ITERATOR iterator[1]; /* Usage: state->iterator->member */
/*
* Global iterator.
*/
#ifdef USE_TLS
SMTP_TLS_POLICY tls[1]; /* Usage: state->tls->member */
#endif
/*
* Connection cache support.
*/
HTABLE *cache_used; /* cached addresses that were used */
VSTRING *dest_label; /* cached logical/physical binding */
VSTRING *dest_prop; /* binding properties, passivated */
VSTRING *endp_label; /* cached session physical endpoint */
VSTRING *endp_prop; /* endpoint properties, passivated */
/*
* Flags and counters to control the handling of mail delivery errors.
* There is some redundancy for sanity checking. At the end of an SMTP
* session all recipients should be marked one way or the other.
*/
int rcpt_left; /* recipients left over */
int rcpt_drop; /* recipients marked as drop */
int rcpt_keep; /* recipients marked as keep */
/*
* DSN Support introduced major bloat in error processing.
*/
DSN_BUF *why; /* on-the-fly formatting buffer */
} SMTP_STATE;
/*
* TODO: use the new SMTP_ITER name space.
*/
#define SET_NEXTHOP_STATE(state, nexthop) { \
vstring_strcpy((state)->iterator->request_nexthop, nexthop); \
}
#define FREE_NEXTHOP_STATE(state) { \
STR((state)->iterator->request_nexthop)[0] = 0; \
}
#define HAVE_NEXTHOP_STATE(state) (STR((state)->iterator->request_nexthop)[0] != 0)
/*
* Server features.
*/
#define SMTP_FEATURE_ESMTP (1<<0)
#define SMTP_FEATURE_8BITMIME (1<<1)
#define SMTP_FEATURE_PIPELINING (1<<2)
#define SMTP_FEATURE_SIZE (1<<3)
#define SMTP_FEATURE_STARTTLS (1<<4)
#define SMTP_FEATURE_AUTH (1<<5)
#define SMTP_FEATURE_XFORWARD_NAME (1<<7)
#define SMTP_FEATURE_XFORWARD_ADDR (1<<8)
#define SMTP_FEATURE_XFORWARD_PROTO (1<<9)
#define SMTP_FEATURE_XFORWARD_HELO (1<<10)
#define SMTP_FEATURE_XFORWARD_DOMAIN (1<<11)
#define SMTP_FEATURE_BEST_MX (1<<12) /* for next-hop or fall-back */
#define SMTP_FEATURE_RSET_REJECTED (1<<13) /* RSET probe rejected */
#define SMTP_FEATURE_FROM_CACHE (1<<14) /* cached connection */
#define SMTP_FEATURE_DSN (1<<15) /* DSN supported */
#define SMTP_FEATURE_PIX_NO_ESMTP (1<<16) /* PIX smtp fixup mode */
#define SMTP_FEATURE_PIX_DELAY_DOTCRLF (1<<17) /* PIX smtp fixup mode */
#define SMTP_FEATURE_XFORWARD_PORT (1<<18)
#define SMTP_FEATURE_EARLY_TLS_MAIL_REPLY (1<<19) /* CVE-2009-3555 */
#define SMTP_FEATURE_XFORWARD_IDENT (1<<20)
#define SMTP_FEATURE_SMTPUTF8 (1<<21) /* RFC 6531 */
/*
* Features that passivate under the endpoint.
*/
#define SMTP_FEATURE_ENDPOINT_MASK \
(~(SMTP_FEATURE_BEST_MX | SMTP_FEATURE_RSET_REJECTED \
| SMTP_FEATURE_FROM_CACHE))
/*
* Features that passivate under the logical destination.
*/
#define SMTP_FEATURE_DESTINATION_MASK (SMTP_FEATURE_BEST_MX)
/*
* Misc flags.
*/
#define SMTP_MISC_FLAG_LOOP_DETECT (1<<0)
#define SMTP_MISC_FLAG_IN_STARTTLS (1<<1)
#define SMTP_MISC_FLAG_FIRST_NEXTHOP (1<<2)
#define SMTP_MISC_FLAG_FINAL_NEXTHOP (1<<3)
#define SMTP_MISC_FLAG_FINAL_SERVER (1<<4)
#define SMTP_MISC_FLAG_CONN_LOAD (1<<5)
#define SMTP_MISC_FLAG_CONN_STORE (1<<6)
#define SMTP_MISC_FLAG_COMPLETE_SESSION (1<<7)
#define SMTP_MISC_FLAG_PREF_IPV6 (1<<8)
#define SMTP_MISC_FLAG_PREF_IPV4 (1<<9)
#define SMTP_MISC_FLAG_CONN_CACHE_MASK \
(SMTP_MISC_FLAG_CONN_LOAD | SMTP_MISC_FLAG_CONN_STORE)
/*
* smtp.c
*/
#define SMTP_HAS_DSN(why) (STR((why)->status)[0] != 0)
#define SMTP_HAS_SOFT_DSN(why) (STR((why)->status)[0] == '4')
#define SMTP_HAS_HARD_DSN(why) (STR((why)->status)[0] == '5')
#define SMTP_HAS_LOOP_DSN(why) \
(SMTP_HAS_DSN(why) && strcmp(STR((why)->status) + 1, ".4.6") == 0)
#define SMTP_SET_SOFT_DSN(why) (STR((why)->status)[0] = '4')
#define SMTP_SET_HARD_DSN(why) (STR((why)->status)[0] = '5')
extern int smtp_host_lookup_mask; /* host lookup methods to use */
#define SMTP_HOST_FLAG_DNS (1<<0)
#define SMTP_HOST_FLAG_NATIVE (1<<1)
extern int smtp_dns_support; /* dns support level */
#define SMTP_DNS_INVALID (-1) /* smtp_dns_support_level = <bogus> */
#define SMTP_DNS_DISABLED 0 /* smtp_dns_support_level = disabled */
#define SMTP_DNS_ENABLED 1 /* smtp_dns_support_level = enabled */
#define SMTP_DNS_DNSSEC 2 /* smtp_dns_support_level = dnssec */
extern SCACHE *smtp_scache; /* connection cache instance */
extern STRING_LIST *smtp_cache_dest; /* cached destinations */
extern MAPS *smtp_ehlo_dis_maps; /* ehlo keyword filter */
extern MAPS *smtp_pix_bug_maps; /* PIX workarounds */
extern MAPS *smtp_generic_maps; /* make internal address valid */
extern int smtp_ext_prop_mask; /* address externsion propagation */
extern unsigned smtp_dns_res_opt; /* DNS query flags */
#ifdef USE_TLS
extern TLS_APPL_STATE *smtp_tls_ctx; /* client-side TLS engine */
#endif
extern HBC_CHECKS *smtp_header_checks; /* limited header checks */
extern HBC_CHECKS *smtp_body_checks; /* limited body checks */
/*
* smtp_session.c
*/
typedef struct SMTP_SESSION {
VSTREAM *stream; /* network connection */
SMTP_ITERATOR *iterator; /* dest, host, addr, port */
char *namaddr; /* mail exchanger */
char *helo; /* helo response */
unsigned port; /* network byte order */
char *namaddrport; /* mail exchanger, incl. port */
VSTRING *buffer; /* I/O buffer */
VSTRING *scratch; /* scratch buffer */
VSTRING *scratch2; /* scratch buffer */
int features; /* server features */
off_t size_limit; /* server limit or unknown */
ARGV *history; /* transaction log */
int error_mask; /* error classes */
struct MIME_STATE *mime_state; /* mime state machine */
int send_proto_helo; /* XFORWARD support */
time_t expire_time; /* session reuse expiration time */
int reuse_count; /* # of times reused (for logging) */
int forbidden; /* No further I/O allowed */
#ifdef USE_SASL_AUTH
char *sasl_mechanism_list; /* server mechanism list */
char *sasl_username; /* client username */
char *sasl_passwd; /* client password */
struct XSASL_CLIENT *sasl_client; /* SASL internal state */
VSTRING *sasl_reply; /* client response */
#endif
/*
* TLS related state, don't forget to initialize in session_tls_init()!
*/
#ifdef USE_TLS
TLS_SESS_STATE *tls_context; /* TLS library session state */
char *tls_nexthop; /* Nexthop domain for cert checks */
int tls_retry_plain; /* Try plain when TLS handshake fails */
#endif
SMTP_STATE *state; /* back link */
} SMTP_SESSION;
extern SMTP_SESSION *smtp_session_alloc(VSTREAM *, SMTP_ITERATOR *, time_t, int);
extern void smtp_session_new_stream(SMTP_SESSION *, VSTREAM *, time_t, int);
extern int smtp_sess_plaintext_ok(SMTP_ITERATOR *, int);
extern void smtp_session_free(SMTP_SESSION *);
extern int smtp_session_passivate(SMTP_SESSION *, VSTRING *, VSTRING *);
extern SMTP_SESSION *smtp_session_activate(int, SMTP_ITERATOR *, VSTRING *, VSTRING *);
/*
* What's in a name?
*/
#define SMTP_HNAME(rr) (var_smtp_cname_overr ? (rr)->rname : (rr)->qname)
/*
* smtp_connect.c
*/
extern int smtp_connect(SMTP_STATE *);
/*
* smtp_proto.c
*/
extern void smtp_vrfy_init(void);
extern int smtp_helo(SMTP_STATE *);
extern int smtp_xfer(SMTP_STATE *);
extern int smtp_rset(SMTP_STATE *);
extern int smtp_quit(SMTP_STATE *);
extern HBC_CALL_BACKS smtp_hbc_callbacks[];
/*
* A connection is re-usable if session->expire_time is > 0 and the
* expiration time has not been reached. This is subtle because the timer
* can expire between sending a command and receiving the reply for that
* command.
*
* But wait, there is more! When SMTP command pipelining is enabled, there are
* two protocol loops that execute at very different times: one loop that
* generates commands, and one loop that receives replies to those commands.
* These will be called "sender loop" and "receiver loop", respectively. At
* well-defined protocol synchronization points, the sender loop pauses to
* let the receiver loop catch up.
*
* When we choose to reuse a connection, both the sender and receiver protocol
* loops end with "." (mail delivery) or "RSET" (address probe). When we
* choose not to reuse, both the sender and receiver protocol loops end with
* "QUIT". The problem is that we must make the same protocol choices in
* both the sender and receiver loops, even though those loops may execute
* at completely different times.
*
* We "freeze" the choice in the sender loop, just before we generate "." or
* "RSET". The reader loop leaves the connection cachable even if the timer
* expires by the time the response arrives. The connection cleanup code
* will call smtp_quit() for connections with an expired cache expiration
* timer.
*
* We could have made the programmer's life a lot simpler by not making a
* choice at all, and always leaving it up to the connection cleanup code to
* call smtp_quit() for connections with an expired cache expiration timer.
*
* As a general principle, neither the sender loop nor the receiver loop must
* modify the connection caching state, if that can affect the receiver
* state machine for not-yet processed replies to already-generated
* commands. This restriction does not apply when we have to exit the
* protocol loops prematurely due to e.g., timeout or connection loss, so
* that those pending replies will never be received.
*
* But wait, there is even more! Only the first good connection for a specific
* destination may be cached under both the next-hop destination name and
* the server address; connections to alternate servers must be cached under
* the server address alone. This means we must distinguish between bad
* connections and other reasons why connections cannot be cached.
*/
#define THIS_SESSION_IS_CACHED \
(!THIS_SESSION_IS_FORBIDDEN && session->expire_time > 0)
#define THIS_SESSION_IS_EXPIRED \
(THIS_SESSION_IS_CACHED \
&& (session->expire_time < vstream_ftime(session->stream) \
|| (var_smtp_reuse_count > 0 \
&& session->reuse_count >= var_smtp_reuse_count)))
#define THIS_SESSION_IS_THROTTLED \
(!THIS_SESSION_IS_FORBIDDEN && session->expire_time < 0)
#define THIS_SESSION_IS_FORBIDDEN \
(session->forbidden != 0)
/* Bring the bad news. */
#define DONT_CACHE_THIS_SESSION \
(session->expire_time = 0)
#define DONT_CACHE_THROTTLED_SESSION \
(session->expire_time = -1)
#define DONT_USE_FORBIDDEN_SESSION \
(session->forbidden = 1)
/* Initialization. */
#define USE_NEWBORN_SESSION \
(session->forbidden = 0)
#define CACHE_THIS_SESSION_UNTIL(when) \
(session->expire_time = (when))
/*
* Encapsulate the following so that we don't expose details of of
* connection management and error handling to the SMTP protocol engine.
*/
#ifdef USE_SASL_AUTH
#define HAVE_SASL_CREDENTIALS \
(var_smtp_sasl_enable \
&& *var_smtp_sasl_passwd \
&& smtp_sasl_passwd_lookup(session))
#else
#define HAVE_SASL_CREDENTIALS (0)
#endif
#define PREACTIVE_DELAY \
(session->state->request->msg_stats.active_arrival.tv_sec - \
session->state->request->msg_stats.incoming_arrival.tv_sec)
#define PLAINTEXT_FALLBACK_OK_AFTER_STARTTLS_FAILURE \
(session->tls_context == 0 \
&& state->tls->level == TLS_LEV_MAY \
&& PREACTIVE_DELAY >= var_min_backoff_time \
&& !HAVE_SASL_CREDENTIALS)
#define PLAINTEXT_FALLBACK_OK_AFTER_TLS_SESSION_FAILURE \
(session->tls_context != 0 \
&& SMTP_RCPT_LEFT(state) > SMTP_RCPT_MARK_COUNT(state) \
&& state->tls->level == TLS_LEV_MAY \
&& PREACTIVE_DELAY >= var_min_backoff_time \
&& !HAVE_SASL_CREDENTIALS)
/*
* XXX The following will not retry recipients that were deferred while the
* SMTP_MISC_FLAG_FINAL_SERVER flag was already set. This includes the case
* when TLS fails in the middle of a delivery.
*/
#define RETRY_AS_PLAINTEXT do { \
session->tls_retry_plain = 1; \
state->misc_flags &= ~SMTP_MISC_FLAG_FINAL_SERVER; \
} while (0)
/*
* smtp_chat.c
*/
typedef struct SMTP_RESP { /* server response */
int code; /* SMTP code */
const char *dsn; /* enhanced status */
char *str; /* full reply */
VSTRING *dsn_buf; /* status buffer */
VSTRING *str_buf; /* reply buffer */
} SMTP_RESP;
extern void PRINTFLIKE(2, 3) smtp_chat_cmd(SMTP_SESSION *, const char *,...);
extern DICT *smtp_chat_resp_filter;
extern SMTP_RESP *smtp_chat_resp(SMTP_SESSION *);
extern void smtp_chat_init(SMTP_SESSION *);
extern void smtp_chat_reset(SMTP_SESSION *);
extern void smtp_chat_notify(SMTP_SESSION *);
#define SMTP_RESP_FAKE(resp, _dsn) \
((resp)->code = 0, \
(resp)->dsn = (_dsn), \
(resp)->str = DSN_BY_LOCAL_MTA, \
(resp))
#define DSN_BY_LOCAL_MTA ((char *) 0) /* DSN issued by local MTA */
#define SMTP_RESP_SET_DSN(resp, _dsn) do { \
vstring_strcpy((resp)->dsn_buf, (_dsn)); \
(resp)->dsn = STR((resp)->dsn_buf); \
} while (0)
/*
* These operations implement a redundant mark-and-sweep algorithm that
* explicitly accounts for the fate of every recipient. The interface is
* documented in smtp_rcpt.c, which also implements the sweeping. The
* smtp_trouble.c module does most of the marking after failure.
*
* When a delivery fails or succeeds, take one of the following actions:
*
* - Mark the recipient as KEEP (deliver to alternate MTA) and do not update
* the delivery request status.
*
* - Mark the recipient as DROP (remove from delivery request), log whether
* delivery succeeded or failed, delete the recipient from the queue file
* and/or update defer or bounce logfiles, and update the delivery request
* status.
*
* At the end of a delivery attempt, all recipients must be marked one way or
* the other. Failure to do so will trigger a panic.
*/
#define SMTP_RCPT_STATE_KEEP 1 /* send to backup host */
#define SMTP_RCPT_STATE_DROP 2 /* remove from request */
#define SMTP_RCPT_INIT(state) do { \
(state)->rcpt_drop = (state)->rcpt_keep = 0; \
(state)->rcpt_left = state->request->rcpt_list.len; \
} while (0)
#define SMTP_RCPT_DROP(state, rcpt) do { \
(rcpt)->u.status = SMTP_RCPT_STATE_DROP; (state)->rcpt_drop++; \
} while (0)
#define SMTP_RCPT_KEEP(state, rcpt) do { \
(rcpt)->u.status = SMTP_RCPT_STATE_KEEP; (state)->rcpt_keep++; \
} while (0)
#define SMTP_RCPT_ISMARKED(rcpt) ((rcpt)->u.status != 0)
#define SMTP_RCPT_LEFT(state) (state)->rcpt_left
#define SMTP_RCPT_MARK_COUNT(state) ((state)->rcpt_drop + (state)->rcpt_keep)
extern void smtp_rcpt_cleanup(SMTP_STATE *);
extern void smtp_rcpt_done(SMTP_STATE *, SMTP_RESP *, RECIPIENT *);
/*
* smtp_trouble.c
*/
extern int smtp_sess_fail(SMTP_STATE *);
extern int PRINTFLIKE(4, 5) smtp_site_fail(SMTP_STATE *, const char *,
SMTP_RESP *, const char *,...);
extern int PRINTFLIKE(4, 5) smtp_mesg_fail(SMTP_STATE *, const char *,
SMTP_RESP *, const char *,...);
extern void PRINTFLIKE(5, 6) smtp_rcpt_fail(SMTP_STATE *, RECIPIENT *,
const char *, SMTP_RESP *,
const char *,...);
extern int smtp_stream_except(SMTP_STATE *, int, const char *);
/*
* smtp_unalias.c
*/
extern const char *smtp_unalias_name(const char *);
extern VSTRING *smtp_unalias_addr(VSTRING *, const char *);
/*
* smtp_state.c
*/
extern SMTP_STATE *smtp_state_alloc(void);
extern void smtp_state_free(SMTP_STATE *);
/*
* smtp_map11.c
*/
extern int smtp_map11_external(VSTRING *, MAPS *, int);
extern int smtp_map11_tree(TOK822 *, MAPS *, int);
extern int smtp_map11_internal(VSTRING *, MAPS *, int);
/*
* smtp_key.c
*/
char *smtp_key_prefix(VSTRING *, const char *, SMTP_ITERATOR *, int);
#define SMTP_KEY_FLAG_SERVICE (1<<0) /* service name */
#define SMTP_KEY_FLAG_SENDER (1<<1) /* sender address */
#define SMTP_KEY_FLAG_REQ_NEXTHOP (1<<2) /* request nexthop */
#define SMTP_KEY_FLAG_NEXTHOP (1<<3) /* current nexthop */
#define SMTP_KEY_FLAG_HOSTNAME (1<<4) /* remote host name */
#define SMTP_KEY_FLAG_ADDR (1<<5) /* remote address */
#define SMTP_KEY_FLAG_PORT (1<<6) /* remote port */
#define SMTP_KEY_MASK_ALL \
(SMTP_KEY_FLAG_SERVICE | SMTP_KEY_FLAG_SENDER | \
SMTP_KEY_FLAG_REQ_NEXTHOP | \
SMTP_KEY_FLAG_NEXTHOP | SMTP_KEY_FLAG_HOSTNAME | \
SMTP_KEY_FLAG_ADDR | SMTP_KEY_FLAG_PORT)
/*
* Conditional lookup-key flags for cached connections that may be
* SASL-authenticated with a per-{sender, nexthop, or hostname} credential.
* Each bit corresponds to one type of smtp_sasl_password_file lookup key,
* and is turned on only when the corresponding main.cf parameter is turned
* on.
*/
#define COND_SASL_SMTP_KEY_FLAG_SENDER \
((var_smtp_sender_auth && *var_smtp_sasl_passwd) ? \
SMTP_KEY_FLAG_SENDER : 0)
#define COND_SASL_SMTP_KEY_FLAG_NEXTHOP \
(*var_smtp_sasl_passwd ? SMTP_KEY_FLAG_NEXTHOP : 0)
#define COND_SASL_SMTP_KEY_FLAG_HOSTNAME \
(*var_smtp_sasl_passwd ? SMTP_KEY_FLAG_HOSTNAME : 0)
/*
* Connection-cache destination lookup key. The SENDER attribute is a proxy
* for sender-dependent SASL credentials (or absence thereof), and prevents
* false connection sharing when different SASL credentials may be required
* for different deliveries to the same domain and port. The SERVICE
* attribute is a proxy for all request-independent configuration details.
*/
#define SMTP_KEY_MASK_SCACHE_DEST_LABEL \
(SMTP_KEY_FLAG_SERVICE | COND_SASL_SMTP_KEY_FLAG_SENDER \
| SMTP_KEY_FLAG_REQ_NEXTHOP)
/*
* Connection-cache endpoint lookup key. The SENDER, NEXTHOP, and HOSTNAME
* attributes are proxies for SASL credentials (or absence thereof), and
* prevent false connection sharing when different SASL credentials may be
* required for different deliveries to the same IP address and port.
*/
#define SMTP_KEY_MASK_SCACHE_ENDP_LABEL \
(SMTP_KEY_FLAG_SERVICE | COND_SASL_SMTP_KEY_FLAG_SENDER \
| COND_SASL_SMTP_KEY_FLAG_NEXTHOP | COND_SASL_SMTP_KEY_FLAG_HOSTNAME \
| SMTP_KEY_FLAG_ADDR | SMTP_KEY_FLAG_PORT)
/*
* Silly little macros.
*/
#define STR(s) vstring_str(s)
#define LEN(s) VSTRING_LEN(s)
extern int smtp_mode;
#define VAR_LMTP_SMTP(x) (smtp_mode ? VAR_SMTP_##x : VAR_LMTP_##x)
#define LMTP_SMTP_SUFFIX(x) (smtp_mode ? x##_SMTP : x##_LMTP)
/* LICENSE
/* .ad
/* .fi
/* The Secure Mailer license must be distributed with this software.
/* AUTHOR(S)
/* Wietse Venema
/* IBM T.J. Watson Research
/* P.O. Box 704
/* Yorktown Heights, NY 10598, USA
/*
/* TLS support originally by:
/* Lutz Jaenicke
/* BTU Cottbus
/* Allgemeine Elektrotechnik
/* Universitaetsplatz 3-4
/* D-03044 Cottbus, Germany
/*
/* Victor Duchovni
/* Morgan Stanley
/*--*/
| Dexus/ubuntu-trusty-postfix | src/smtp/smtp.h | C | epl-1.0 | 23,293 | 32.905386 | 87 | 0.669472 | false |
/*
* Copyright 2014 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at http://www.eclipse.org/legal/epl-v10.html
*/
package io.liveoak.mongo.launcher.service;
import java.io.IOException;
import io.liveoak.mongo.launcher.MongoLauncher;
import io.liveoak.mongo.launcher.config.MongoLauncherConfigResource;
import org.jboss.logging.Logger;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
/**
* @author <a href="mailto:marko.strukelj@gmail.com">Marko Strukelj</a>
*/
public class MongoLauncherService implements Service<MongoLauncher> {
private static final Logger log = Logger.getLogger("mongo-launcher");
private final String id;
private MongoLauncher launcher;
private InjectedValue<MongoLauncherConfigResource> configResourceInjector = new InjectedValue<>();
public MongoLauncherService(String id) {
this.id = id;
}
@Override
public void start(StartContext context) throws StartException {
boolean detectRunning;
// init launcher properties
MongoLauncherConfigResource config = configResourceInjector.getValue();
switch(config.enabled()) {
case "auto":
detectRunning = true;
break;
case "true":
detectRunning = false;
break;
case "false":
log.info("MongoLauncher is explicitly disabled. Not starting mongod automatically");
return;
default:
log.warn("Not starting mongod automatically - configuration parameter 'enabled' contains invalid value: " + config.enabled());
return;
}
context.asynchronous();
launcher = new MongoLauncher();
boolean exitIfPortTaken = detectRunning;
new Thread(() -> {
try {
String host = config.host();
if (host != null) {
launcher.setHost(host);
}
int port = config.port();
if (port != 0) {
launcher.setPort(port);
}
if (launcher.serverRunning(host, port)) {
log.warn("It appears there is an existing server on port: " + port);
if (exitIfPortTaken) {
log.warn("Not starting mongod (you can change this behavior via 'enabled' property in conf/extensions/mongo-launcher.json)");
context.complete();
return;
} else {
throw new RuntimeException("Can't start mongod (port already in use)");
}
}
String val = config.mongodPath();
if (val != null) {
launcher.setMongodPath(val);
}
val = config.dbPath();
if (val != null) {
launcher.setDbPath(val);
}
val = config.logPath();
if (val != null) {
launcher.setLogPath(val);
}
val = config.pidFilePath();
if (val != null) {
launcher.setPidFilePath(val);
}
launcher.setUseSmallFiles(config.useSmallFiles());
val = config.extraArgs();
if (val != null) {
launcher.addExtraArgs(val);
}
launcher.setUseAnyMongod(config.useAnyMongod());
try {
launcher.startMongo();
while(!launcher.serverRunning(host, port)) {
try {
log.debug("Attempting to connect to MongoDB instance");
Thread.sleep(300);
} catch (InterruptedException e) {
context.failed(new StartException("Interrupted", e));
return;
}
}
log.info("Mongo started");
} catch (Throwable e) {
throw new RuntimeException("Failed to start MongoDB - Check mongo-launcher.json extension configuration file", e);
}
context.complete();
} catch (Throwable t) {
context.failed(new StartException(t));
}
}, "MongoLauncherService starter").start();
}
@Override
public void stop(StopContext context) {
try {
if (launcher != null) {
launcher.stopMongo();
}
} catch (IOException e) {
log.warn("Failed to stop MongoDB: ", e);
}
}
@Override
public MongoLauncher getValue() throws IllegalStateException, IllegalArgumentException {
return launcher;
}
public InjectedValue<MongoLauncherConfigResource> configResourceInjector() {
return this.configResourceInjector;
}
}
| ljshj/liveoak | modules/mongo-launcher/src/main/java/io/liveoak/mongo/launcher/service/MongoLauncherService.java | Java | epl-1.0 | 5,256 | 32.056604 | 149 | 0.532725 | false |
/*
* Copyright (c) 2012-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.ide.editor.synchronization;
import static org.eclipse.che.ide.api.resources.ResourceDelta.ADDED;
import static org.eclipse.che.ide.api.resources.ResourceDelta.MOVED_FROM;
import static org.eclipse.che.ide.api.resources.ResourceDelta.MOVED_TO;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.web.bindery.event.shared.EventBus;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.che.ide.api.editor.EditorPartPresenter;
import org.eclipse.che.ide.api.editor.EditorWithAutoSave;
import org.eclipse.che.ide.api.event.ActivePartChangedEvent;
import org.eclipse.che.ide.api.event.ActivePartChangedHandler;
import org.eclipse.che.ide.api.parts.EditorPartStack;
import org.eclipse.che.ide.api.parts.PartPresenter;
import org.eclipse.che.ide.api.resources.ResourceChangedEvent;
import org.eclipse.che.ide.api.resources.ResourceChangedEvent.ResourceChangedHandler;
import org.eclipse.che.ide.api.resources.ResourceDelta;
import org.eclipse.che.ide.resource.Path;
/**
* The default implementation of {@link EditorContentSynchronizer}. The synchronizer of content for
* opened files with the same {@link Path}. Used to sync the content of opened files in different
* {@link EditorPartStack}s. Note: this implementation disables autosave feature for implementations
* of {@link EditorWithAutoSave} with the same {@link Path} except active editor.
*
* @author Roman Nikitenko
*/
@Singleton
public class EditorContentSynchronizerImpl
implements EditorContentSynchronizer, ActivePartChangedHandler, ResourceChangedHandler {
final Map<Path, EditorGroupSynchronization> editorGroups;
final Provider<EditorGroupSynchronization> editorGroupSyncProvider;
@Inject
public EditorContentSynchronizerImpl(
EventBus eventBus, Provider<EditorGroupSynchronization> editorGroupSyncProvider) {
this.editorGroupSyncProvider = editorGroupSyncProvider;
this.editorGroups = new HashMap<>();
eventBus.addHandler(ActivePartChangedEvent.TYPE, this);
eventBus.addHandler(ResourceChangedEvent.getType(), this);
}
/**
* Begins to track given editor to sync its content with opened files with the same {@link Path}.
*
* @param editor editor to sync content
*/
@Override
public void trackEditor(EditorPartPresenter editor) {
Path path = editor.getEditorInput().getFile().getLocation();
if (editorGroups.containsKey(path)) {
editorGroups.get(path).addEditor(editor);
} else {
EditorGroupSynchronization group = editorGroupSyncProvider.get();
editorGroups.put(path, group);
group.addEditor(editor);
}
}
/**
* Stops to track given editor.
*
* @param editor editor to stop tracking
*/
@Override
public void unTrackEditor(EditorPartPresenter editor) {
Path path = editor.getEditorInput().getFile().getLocation();
EditorGroupSynchronization group = editorGroups.get(path);
if (group == null) {
return;
}
group.removeEditor(editor);
if (group.getSynchronizedEditors().isEmpty()) {
group.unInstall();
editorGroups.remove(path);
}
}
@Override
public void onActivePartChanged(ActivePartChangedEvent event) {
PartPresenter activePart = event.getActivePart();
if (!(activePart instanceof EditorPartPresenter)) {
return;
}
EditorPartPresenter activeEditor = (EditorPartPresenter) activePart;
Path path = activeEditor.getEditorInput().getFile().getLocation();
if (editorGroups.containsKey(path)) {
editorGroups.get(path).onActiveEditorChanged(activeEditor);
}
}
@Override
public void onResourceChanged(ResourceChangedEvent event) {
final ResourceDelta delta = event.getDelta();
if (delta.getKind() != ADDED || (delta.getFlags() & (MOVED_FROM | MOVED_TO)) == 0) {
return;
}
final Path fromPath = delta.getFromPath();
final Path toPath = delta.getToPath();
if (delta.getResource().isFile()) {
onFileChanged(fromPath, toPath);
} else {
onFolderChanged(fromPath, toPath);
}
}
private void onFileChanged(Path fromPath, Path toPath) {
final EditorGroupSynchronization group = editorGroups.remove(fromPath);
if (group != null) {
editorGroups.put(toPath, group);
}
}
private void onFolderChanged(Path fromPath, Path toPath) {
final Map<Path, EditorGroupSynchronization> newGroups = new HashMap<>(editorGroups.size());
final Iterator<Map.Entry<Path, EditorGroupSynchronization>> iterator =
editorGroups.entrySet().iterator();
while (iterator.hasNext()) {
final Map.Entry<Path, EditorGroupSynchronization> entry = iterator.next();
final Path groupPath = entry.getKey();
final EditorGroupSynchronization group = entry.getValue();
if (fromPath.isPrefixOf(groupPath)) {
final Path relPath = groupPath.removeFirstSegments(fromPath.segmentCount());
final Path newPath = toPath.append(relPath);
newGroups.put(newPath, group);
iterator.remove();
}
}
editorGroups.putAll(newGroups);
}
}
| TypeFox/che | ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/editor/synchronization/EditorContentSynchronizerImpl.java | Java | epl-1.0 | 5,522 | 35.091503 | 100 | 0.737052 | false |
/*******************************************************************************
* Copyright (c) 2005-2010 VecTrace (Zingo Andersen) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Soren Mathiasen implementation
*******************************************************************************/
package com.vectrace.MercurialEclipse.synchronize;
import org.eclipse.team.internal.ui.synchronize.IRefreshEvent;
import org.eclipse.team.internal.ui.synchronize.RefreshUserNotificationPolicy;
import org.eclipse.team.ui.synchronize.ISynchronizeParticipant;
/**
* @author Soren Mathiasen
*
*/
@SuppressWarnings("restriction")
public class MercurialRefreshUserNotificationPolicy extends RefreshUserNotificationPolicy {
/**
* @param participant
*/
public MercurialRefreshUserNotificationPolicy(ISynchronizeParticipant participant) {
super(participant);
}
/**
* @see org.eclipse.team.internal.ui.synchronize.RefreshUserNotificationPolicy#handleRefreshDone(org.eclipse.team.internal.ui.synchronize.IRefreshEvent, boolean)
*/
@Override
protected boolean handleRefreshDone(IRefreshEvent event, boolean prompt) {
// set prompt to false in order to disable on changes found dialog.
// TODO There must be a better way of doing this !
return super.handleRefreshDone(event, false);
}
}
| boa0332/mercurialeclipse | plugin/src/com/vectrace/MercurialEclipse/synchronize/MercurialRefreshUserNotificationPolicy.java | Java | epl-1.0 | 1,532 | 37.3 | 162 | 0.707572 | false |
require "rjava"
# Copyright (c) 2000, 2008 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
module Org::Eclipse::Swt::Internal::Image
module TIFFFileFormatImports #:nodoc:
class_module.module_eval {
include ::Java::Lang
include ::Org::Eclipse::Swt::Internal::Image
include ::Org::Eclipse::Swt
include ::Org::Eclipse::Swt::Graphics
include ::Java::Io
}
end
# Baseline TIFF decoder revision 6.0
# Extension T4-encoding CCITT T.4 1D
class TIFFFileFormat < TIFFFileFormatImports.const_get :FileFormat
include_class_members TIFFFileFormatImports
typesig { [LEDataInputStream] }
def is_file_format(stream)
begin
header = Array.typed(::Java::Byte).new(4) { 0 }
stream.read(header)
stream.unread(header)
if (!(header[0]).equal?(header[1]))
return false
end
if (!((header[0]).equal?(0x49) && (header[2]).equal?(42) && (header[3]).equal?(0)) && !((header[0]).equal?(0x4d) && (header[2]).equal?(0) && (header[3]).equal?(42)))
return false
end
return true
rescue JavaException => e
return false
end
end
typesig { [] }
def load_from_byte_stream
header = Array.typed(::Java::Byte).new(8) { 0 }
is_little_endian = false
images = Array.typed(ImageData).new(0) { nil }
file = TIFFRandomFileAccess.new(self.attr_input_stream)
begin
file.read(header)
if (!(header[0]).equal?(header[1]))
SWT.error(SWT::ERROR_INVALID_IMAGE)
end
if (!((header[0]).equal?(0x49) && (header[2]).equal?(42) && (header[3]).equal?(0)) && !((header[0]).equal?(0x4d) && (header[2]).equal?(0) && (header[3]).equal?(42)))
SWT.error(SWT::ERROR_INVALID_IMAGE)
end
is_little_endian = (header[0]).equal?(0x49)
offset = is_little_endian ? (header[4] & 0xff) | ((header[5] & 0xff) << 8) | ((header[6] & 0xff) << 16) | ((header[7] & 0xff) << 24) : (header[7] & 0xff) | ((header[6] & 0xff) << 8) | ((header[5] & 0xff) << 16) | ((header[4] & 0xff) << 24)
file.seek(offset)
directory = TIFFDirectory.new(file, is_little_endian, self.attr_loader)
image = directory.read
# A baseline reader is only expected to read the first directory
images = Array.typed(ImageData).new([image])
rescue IOException => e
SWT.error(SWT::ERROR_IO, e)
end
return images
end
typesig { [ImageLoader] }
def unload_into_byte_stream(loader)
# We do not currently support writing multi-page tiff,
# so we use the first image data in the loader's array.
image = loader.attr_data[0]
directory = TIFFDirectory.new(image)
begin
directory.write_to_stream(self.attr_output_stream)
rescue IOException => e
SWT.error(SWT::ERROR_IO, e)
end
end
typesig { [] }
def initialize
super()
end
private
alias_method :initialize__tifffile_format, :initialize
end
end
| neelance/swt4ruby | swt4ruby/lib/mingw32-x86_32/org/eclipse/swt/internal/image/TIFFFileFormat.rb | Ruby | epl-1.0 | 3,342 | 34.553191 | 247 | 0.605925 | false |
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Schema documentation for component AttributeType_file:/Users/ianmayo/dev/Debrief361/org.mwc.asset.core/asset_schemas/ASSET.xsd_Complex_Type</title>
<link rel="stylesheet" href="docHtml.css" type="text/css" /><script type="text/javascript">
<!--
var propertiesBoxes= new Array('properties_id568',
'properties_id576',
'properties_id581');
var facetsBoxes= new Array('facets_id581');
var usedByBoxes= new Array('usedBy_id567',
'usedBy_id581');
var sourceBoxes= new Array('source_id568',
'source_id576',
'source_id567',
'source_id581');
var instanceBoxes= new Array('instance_id576');
var annotationBoxes= new Array('annotations_id568',
'annotations_id576',
'annotations_id567',
'annotations_id581');
var attributesBoxes= new Array('attributes_id568',
'attributes_id567');
var button_prefix = 'button_';
/**
* Returns an element in the current HTML document.
*
* @param elementID Identifier of HTML element
* @return HTML element object
*/
function getElementObject(elementID) {
var elemObj = null;
if (document.getElementById) {
elemObj = document.getElementById(elementID);
}
return elemObj;
}
/**
* Switches the state of a collapseable box, e.g.
* if it's opened, it'll be closed, and vice versa.
*
* @param boxID Identifier of box
*/
function switchState(boxID) {
var boxObj = getElementObject(boxID);
var buttonObj = getElementObject(button_prefix + boxID);
if (boxObj == null || buttonObj == null) {
// Box or button not found
} else if (boxObj.style.display == "none") {
// Box is closed, so open it
openBox(boxObj, buttonObj);
} else if (boxObj.style.display == "block") {
// Box is opened, so close it
closeBox(boxObj, buttonObj);
}
}
/**
* Opens a collapseable box.
*
* @param boxObj Collapseable box
* @param buttonObj Button controlling box
*/
function openBox(boxObj, buttonObj) {
if (boxObj == null || buttonObj == null) {
// Box or button not found
} else {
// Change 'display' CSS property of box
boxObj.style.display = "block";
// Change text of button
if (boxObj.style.display == "block") {
buttonObj.src = "img/btM.gif";
}
}
}
/**
* Closes a collapseable box.
*
* @param boxObj Collapseable box
* @param buttonObj Button controlling box
*/
function closeBox(boxObj, buttonObj) {
if (boxObj == null || buttonObj == null) {
// Box or button not found
} else {
// Change 'display' CSS property of box
boxObj.style.display = "none";
// Change text of button
if (boxObj.style.display == "none") {
buttonObj.src = "img/btP.gif";
}
}
}
function switchStateForAll(buttonObj, boxList) {
if (buttonObj == null) {
// button not found
} else if (buttonObj.value == "+") {
// Expand all
expandAll(boxList);
buttonObj.value = "-";
} else if (buttonObj.value == "-") {
// Collapse all
collapseAll(boxList);
buttonObj.value = "+";
}
}
/**
* Closes all boxes in a given list.
*
* @param boxList Array of box IDs
*/
function collapseAll(boxList) {
var idx;
for (idx = 0; idx < boxList.length; idx++) {
var boxObj = getElementObject(boxList[idx]);
var buttonObj = getElementObject(button_prefix + boxList[idx]);
closeBox(boxObj, buttonObj);
}
}
/**
* Open all boxes in a given list.
*
* @param boxList Array of box IDs
*/
function expandAll(boxList) {
var idx;
for (idx = 0; idx < boxList.length; idx++) {
var boxObj = getElementObject(boxList[idx]);
var buttonObj = getElementObject(button_prefix + boxList[idx]);
openBox(boxObj, buttonObj);
}
}
/**
* Update the message presented in the title of the html page.
* - If the documentation was splited by namespace we present something like: "Documentation for namespace 'ns'"
* - If the documentation was splited by location we present somehing like: "Documentation for 'Schema.xsd'"
* - If no split we always present: "Documentation for 'MainSchema.xsd'"
*/
function updatePageTitle(message) {
top.document.title = message;
}
/**
* Finds an HTML element by its ID and makes it floatable over the normal content.
*
* @param x_displacement The difference in pixels to the right side of the window from
* the left side of the element.
* @param y_displacement The difference in pixels to the right side of the window from
* the top of the element.
*/
function findAndFloat(id, x_displacement, y_displacement){
var element = getElementObject(id);
window[id + "_obj"] = element;
if(document.layers) {
element.style = element;
}
element.current_y = y_displacement;
element.first_time = true;
element.floatElement = function(){
// It may be closed by an user action.
// Target X and Y coordinates.
var x, y;
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
x = myWidth - x_displacement;
var ns = (navigator.appName.indexOf("Netscape") != -1);
y = ns ? pageYOffset : document.documentElement && document.documentElement.scrollTop ?
document.documentElement.scrollTop : document.body.scrollTop;
y = y + y_displacement;
// The current y is the current coordinate of the floating element.
// This should be at the limit the y target coordinate.
this.current_y += (y - this.current_y)/1.25;
// Add the pixels constant after the values
// and move the element.
var px = document.layers ? "" : "px";
this.style.left = x + px;
this.style.top = this.current_y + px;
setTimeout(this.id + "_obj.floatElement()", 100);
}
element.floatElement();
return element;
}
/**
* Finds an HTML element by its ID and makes it floatable over the normal content.
*
* @param x_displacement The difference in pixels to the right side of the window from
* the left side of the element.
* @param y_displacement The difference in pixels to the right side of the window from
* the top of the element.
*/
function selectTOCGroupBy(id, isChunked, indexFileLocation, indexFileNamespace, indexFileComponent){
if (!isChunked) {
var selectIds = new Array('toc_group_by_namespace', 'toc_group_by_location', 'toc_group_by_component_type');
// Make all the tabs invisible.
for (i = 0; i < 3; i++){
var tab = getElementObject(selectIds[i]);
tab.style.display = 'none';
}
var selTab = getElementObject(id);
selTab.style.display = 'block';
} else {
if (id == 'toc_group_by_namespace') {
parent.indexFrame.location = indexFileNamespace;
} else if (id == 'toc_group_by_location') {
parent.indexFrame.location = indexFileLocation;
} else if (id == 'toc_group_by_component_type') {
parent.indexFrame.location = indexFileComponent;
}
}
}
--></script></head>
<body>
<div id="global_controls" class="globalControls" style="position:absolute;right:0;">
<table class="rt">
<tr>
<td class="rt_cornerTopLeft"></td>
<td class="rt_lineTop"></td>
<td class="rt_cornerTopRight"></td>
</tr>
<tr>
<td class="rt_lineLeft"></td>
<td class="rt_content">
<h3>Showing:</h3>
<table>
<tr>
<td><span><input type="checkbox" value="-" checked="checked"
onclick="switchStateForAll(this, annotationBoxes);"
class="control" /></span><span class="globalControlName">Annotations</span></td>
</tr>
<tr>
<td><span><input type="checkbox" value="-" checked="checked"
onclick="switchStateForAll(this, attributesBoxes);"
class="control" /></span><span class="globalControlName">Attributes </span></td>
</tr>
<tr>
<td><span><input type="checkbox" value="-" checked="checked"
onclick="switchStateForAll(this, facetsBoxes);"
class="control" /></span><span class="globalControlName">Facets </span></td>
</tr>
<tr>
<td><span><input type="checkbox" value="-" checked="checked"
onclick="switchStateForAll(this, instanceBoxes);"
class="control" /></span><span class="globalControlName">Instances</span></td>
</tr>
<tr>
<td><span><input type="checkbox" value="-" checked="checked"
onclick="switchStateForAll(this, propertiesBoxes);"
class="control" /></span><span class="globalControlName">Properties </span></td>
</tr>
<tr>
<td><span><input type="checkbox" value="-" checked="checked"
onclick="switchStateForAll(this, sourceBoxes);"
class="control" /></span><span class="globalControlName">Source</span></td>
</tr>
<tr>
<td><span><input type="checkbox" value="-" checked="checked"
onclick="switchStateForAll(this, usedByBoxes);"
class="control" /></span><span class="globalControlName">Used by </span></td>
</tr>
</table>
<div align="right"><span><input type="button"
onclick="getElementObject('global_controls').style.display = 'none';"
value="Close" /></span></div>
</td>
<td class="rt_lineRight"></td>
</tr>
<tr>
<td class="rt_cornerBottomLeft"></td>
<td class="rt_lineBottom"></td>
<td class="rt_cornerBottomRight"></td>
</tr>
</table>
</div><a id="id568"></a><div class="componentTitle">Element <span class="qname"><b><a href="ASSET_xsd_Complex_Type_AttributeType.html#id567" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component AttributeType')">AttributeType</a></b> / Range</span></div>
<table class="rt">
<tr>
<td class="rt_cornerTopLeft"></td>
<td class="rt_lineTop"></td>
<td class="rt_cornerTopRight"></td>
</tr>
<tr>
<td class="rt_lineLeft"></td>
<td class="rt_content">
<table class="component">
<tbody>
<tr>
<td class="firstColumn"><b>Namespace</b></td>
<td>No namespace</td>
</tr>
<tr>
<td class="firstColumn">
<div class="floatLeft"><b>Annotations</b></div>
<div class="floatRight"><input id="button_annotations_id568" type="image" src="img/btM.gif" value="-"
onclick="switchState('annotations_id568');"
class="control" /></div>
</td>
<td>
<div id="annotations_id568" style="display:block">
<div class="annotation">
<table style="table-layout:fixed;white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;_white-space:pre;"
class="preWrapContainer">
<tr>
<td width="100%"><pre><span class="tT">Use a range of values to specify the attribute.</span><span class="tI">
</span><span class="tT">Visible:</span><span class="tI">
</span><span class="tT">Value. Editable: Text box for value.</span></pre></td>
</tr>
</table>
</div>
</div>
</td>
</tr>
<tr>
<td class="firstColumn"><b>Type</b></td>
<td><b><a href="ASSET_xsd_Complex_Type_RangeType.html#id569" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component RangeType')">RangeType</a></b></td>
</tr>
<tr>
<td class="firstColumn"><b>Type hierarchy</b></td>
<td>
<ul>
<li><b><a href="ASSET_xsd_Complex_Type_RandomVarianceType.html#id552" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component RandomVarianceType')">RandomVarianceType</a></b><ul>
<li><b><a href="ASSET_xsd_Complex_Type_RangeType.html#id569" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component RangeType')">RangeType</a></b></li>
</ul>
</li>
</ul>
</td>
</tr>
<tr>
<td class="firstColumn">
<div class="floatLeft"><b>Properties</b></div>
<div class="floatRight"><input id="button_properties_id568" type="image" src="img/btM.gif" value="-"
onclick="switchState('properties_id568');"
class="control" /></div>
</td>
<td>
<div id="properties_id568" style="display:block">
<table class="propertiesTable">
<tr>
<td class="firstColumn">content:
</td>
<td><b>complex</b></td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td class="firstColumn">
<div class="floatLeft"><b>Attributes</b></div>
<div class="floatRight"><input id="button_attributes_id568" type="image" src="img/btM.gif" value="-"
onclick="switchState('attributes_id568');"
class="control" /></div>
</td>
<td>
<div id="attributes_id568" style="display:block">
<table class="attributesTable">
<thead>
<tr>
<th>QName</th>
<th>Type</th>
<th>Fixed</th>
<th>Default</th>
<th>Use</th>
<th>Annotation</th>
</tr>
</thead>
<tr>
<td class="firstColumn"><b><a href="ASSET_xsd_Complex_Type_RandomVarianceType.html#id553" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component RandomModel')">RandomModel</a></b></td>
<td>restriction of <b>xs:NMTOKEN</b></td>
<td></td>
<td></td>
<td>optional</td>
<td>
<div class="annotation">
<table style="table-layout:fixed;white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;_white-space:pre;"
class="preWrapContainer">
<tr>
<td width="100%"><pre><span class="tT">The model through which random permutations are</span><span class="tI">
</span><span class="tT">generated</span></pre></td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td class="firstColumn"><b><a href="ASSET_xsd_Complex_Type_RangeType.html#id574" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component format')">format</a></b></td>
<td><b><a href="ASSET_xsd_Simple_Type_validString.html#id575" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component validString')">validString</a></b></td>
<td></td>
<td></td>
<td>optional</td>
<td>
<div class="annotation">
<table style="table-layout:fixed;white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;_white-space:pre;"
class="preWrapContainer">
<tr>
<td width="100%"><pre><span class="tT">String format to use (eg 0.0 0 0.0000)</span></pre></td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td class="firstColumn"><b><a href="ASSET_xsd_Complex_Type_RangeType.html#id571" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component max')">max</a></b></td>
<td><b>xs:decimal</b></td>
<td></td>
<td></td>
<td>required</td>
<td>
<div class="annotation">
<table style="table-layout:fixed;white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;_white-space:pre;"
class="preWrapContainer">
<tr>
<td width="100%"><pre><span class="tT">Max value to use (inclusive)</span></pre></td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td class="firstColumn"><b><a href="ASSET_xsd_Complex_Type_RangeType.html#id570" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component min')">min</a></b></td>
<td><b>xs:decimal</b></td>
<td></td>
<td></td>
<td>required</td>
<td>
<div class="annotation">
<table style="table-layout:fixed;white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;_white-space:pre;"
class="preWrapContainer">
<tr>
<td width="100%"><pre><span class="tT">Min value to use (inclusive)</span></pre></td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td class="firstColumn"><b><a href="ASSET_xsd_Complex_Type_RangeType.html#id573" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component number_permutations')">number_permutations</a></b></td>
<td><b>xs:decimal</b></td>
<td></td>
<td></td>
<td>optional</td>
<td>
<div class="annotation">
<table style="table-layout:fixed;white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;_white-space:pre;"
class="preWrapContainer">
<tr>
<td width="100%"><pre><span class="tT">When calculating values within the range,</span><span class="tI">
</span><span class="tT">specifying the</span><span class="tI">
</span><span class="tT">number of permutations causes that many</span><span class="tI">
</span><span class="tT">permutations to be created.</span><span class="tI">
</span><span class="tT">Instances from this limited number of</span><span class="tI">
</span><span class="tT">permutations are selected in</span><span class="tI">
</span><span class="tT">sequence for new random scenarios.</span><span class="tI">
</span><span class="tT">When per-case analysis of scenario</span><span class="tI">
</span><span class="tT">results is used a continuously</span><span class="tI">
</span><span class="tT">random set of vlaues would prevent</span><span class="tI">
</span><span class="tT">analysis of grouped results.</span><span class="tI">
</span><span class="tT">Specifying that a restricted number of</span><span class="tI">
</span><span class="tT">permutations will be used</span><span class="tI">
</span><span class="tT">ensures that groups of matching scenarios can</span><span class="tI">
</span><span class="tT">be analysed</span><span class="tI">
</span><span class="tT">together.</span></pre></td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td class="firstColumn"><b><a href="ASSET_xsd_Complex_Type_RangeType.html#id572" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component step')">step</a></b></td>
<td><b>xs:decimal</b></td>
<td></td>
<td></td>
<td>optional</td>
<td>
<div class="annotation">
<table style="table-layout:fixed;white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;_white-space:pre;"
class="preWrapContainer">
<tr>
<td width="100%"><pre><span class="tT">Step interval to use in generating new values.</span><span class="tI">
</span><span class="tT">If omitted,</span><span class="tI">
</span><span class="tT">random values will be generated according to the</span><span class="tI">
</span><span class="tT">random model</span><span class="tI">
</span><span class="tT">specified</span></pre></td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td class="firstColumn">
<div class="floatLeft"><b>Source</b></div>
<div class="floatRight"><input id="button_source_id568" type="image" src="img/btM.gif" value="-"
onclick="switchState('source_id568');"
class="control" /></div>
</td>
<td>
<div id="source_id568" style="display:block">
<table style="table-layout:fixed;white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;_white-space:pre;"
class="preWrapContainer">
<tr>
<td width="100%"><pre><span class="tEl"><xs:element</span><span class="tAN"> name=</span><span class="tAV">"Range"</span><span class="tAN"> type=</span><span class="tAV">"RangeType"</span><span class="tEl">></span><span class="tI">
</span><span class="tEl"><xs:annotation</span><span class="tEl">></span><span class="tI">
</span><span class="tEl"><xs:documentation</span><span class="tEl">></span><span class="tT">Use a range of values to specify the attribute.
Visible:
Value. Editable: Text box for value.</span><span class="tEl"></xs:documentation></span><span class="tI">
</span><span class="tEl"></xs:annotation></span><span class="tI">
</span><span class="tEl"></xs:element></span></pre></td>
</tr>
</table>
</div>
</td>
</tr>
</tbody>
</table>
</td>
<td class="rt_lineRight"></td>
</tr>
<tr>
<td class="rt_cornerBottomLeft"></td>
<td class="rt_lineBottom"></td>
<td class="rt_cornerBottomRight"></td>
</tr>
</table><a id="id576"></a><div class="componentTitle">Element <span class="qname"><b><a href="ASSET_xsd_Complex_Type_AttributeType.html#id567" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component AttributeType')">AttributeType</a></b> / Choice</span></div>
<table class="rt">
<tr>
<td class="rt_cornerTopLeft"></td>
<td class="rt_lineTop"></td>
<td class="rt_cornerTopRight"></td>
</tr>
<tr>
<td class="rt_lineLeft"></td>
<td class="rt_content">
<table class="component">
<tbody>
<tr>
<td class="firstColumn"><b>Namespace</b></td>
<td>No namespace</td>
</tr>
<tr>
<td class="firstColumn">
<div class="floatLeft"><b>Annotations</b></div>
<div class="floatRight"><input id="button_annotations_id576" type="image" src="img/btM.gif" value="-"
onclick="switchState('annotations_id576');"
class="control" /></div>
</td>
<td>
<div id="annotations_id576" style="display:block">
<div class="annotation">
<table style="table-layout:fixed;white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;_white-space:pre;"
class="preWrapContainer">
<tr>
<td width="100%"><pre><span class="tT">Provide a list of attribute values to choose</span><span class="tI">
</span><span class="tT">from. Visible:</span><span class="tI">
</span><span class="tT">Value. Editable: Combo box of values.</span></pre></td>
</tr>
</table>
</div>
</div>
</td>
</tr>
<tr>
<td class="firstColumn"><b>Type</b></td>
<td><b><a href="ASSET_xsd_Complex_Type_ChoiceType.html#id577" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component ChoiceType')">ChoiceType</a></b></td>
</tr>
<tr>
<td class="firstColumn">
<div class="floatLeft"><b>Properties</b></div>
<div class="floatRight"><input id="button_properties_id576" type="image" src="img/btM.gif" value="-"
onclick="switchState('properties_id576');"
class="control" /></div>
</td>
<td>
<div id="properties_id576" style="display:block">
<table class="propertiesTable">
<tr>
<td class="firstColumn">content:
</td>
<td><b>complex</b></td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td class="firstColumn"><b>Model</b></td>
<td><b><a href="ASSET_xsd_Complex_Type_ChoiceType.html#id578" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component Value+')">Value+</a></b></td>
</tr>
<tr>
<td class="firstColumn"><b>Children</b></td>
<td><b><a href="ASSET_xsd_Complex_Type_ChoiceType.html#id578" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component Value')">Value</a></b></td>
</tr>
<tr>
<td class="firstColumn">
<div class="floatLeft"><b>Instance</b></div>
<div class="floatRight"><input id="button_instance_id576" type="image" src="img/btM.gif" value="-"
onclick="switchState('instance_id576');"
class="control" /></div>
</td>
<td>
<div id="instance_id576" style="display:block">
<table style="table-layout:fixed;white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;_white-space:pre;"
class="preWrapContainer">
<tr>
<td width="100%"><pre><span class="tEl"><Choice</span><span class="tEl">></span><span class="tI">
</span><span class="tEl"><Value</span><span class="tT"> </span><span class="tAN">value=</span><span class="tAV">""</span><span class="tEl">></span><span class="tT">{1,unbounded}</span><span class="tEl"></Value></span><span class="tI">
</span><span class="tEl"></Choice></span></pre></td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td class="firstColumn">
<div class="floatLeft"><b>Source</b></div>
<div class="floatRight"><input id="button_source_id576" type="image" src="img/btM.gif" value="-"
onclick="switchState('source_id576');"
class="control" /></div>
</td>
<td>
<div id="source_id576" style="display:block">
<table style="table-layout:fixed;white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;_white-space:pre;"
class="preWrapContainer">
<tr>
<td width="100%"><pre><span class="tEl"><xs:element</span><span class="tAN"> name=</span><span class="tAV">"Choice"</span><span class="tAN"> type=</span><span class="tAV">"ChoiceType"</span><span class="tEl">></span><span class="tI">
</span><span class="tEl"><xs:annotation</span><span class="tEl">></span><span class="tI">
</span><span class="tEl"><xs:documentation</span><span class="tEl">></span><span class="tT">Provide a list of attribute values to choose
from. Visible:
Value. Editable: Combo box of values.</span><span class="tEl"></xs:documentation></span><span class="tI">
</span><span class="tEl"></xs:annotation></span><span class="tI">
</span><span class="tEl"></xs:element></span></pre></td>
</tr>
</table>
</div>
</td>
</tr>
</tbody>
</table>
</td>
<td class="rt_lineRight"></td>
</tr>
<tr>
<td class="rt_cornerBottomLeft"></td>
<td class="rt_lineBottom"></td>
<td class="rt_cornerBottomRight"></td>
</tr>
</table><a id="id567"></a><div class="componentTitle">Complex Type <span class="qname">AttributeType</span></div>
<table class="rt">
<tr>
<td class="rt_cornerTopLeft"></td>
<td class="rt_lineTop"></td>
<td class="rt_cornerTopRight"></td>
</tr>
<tr>
<td class="rt_lineLeft"></td>
<td class="rt_content">
<table class="component">
<tbody>
<tr>
<td class="firstColumn"><b>Namespace</b></td>
<td>No namespace</td>
</tr>
<tr>
<td class="firstColumn">
<div class="floatLeft"><b>Annotations</b></div>
<div class="floatRight"><input id="button_annotations_id567" type="image" src="img/btM.gif" value="-"
onclick="switchState('annotations_id567');"
class="control" /></div>
</td>
<td>
<div id="annotations_id567" style="display:block">
<div class="annotation">
<table style="table-layout:fixed;white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;_white-space:pre;"
class="preWrapContainer">
<tr>
<td width="100%"><pre><span class="tT">Change the value of a single attribute.</span></pre></td>
</tr>
</table>
</div>
<div class="annotation">
<p><a href="http://asset.info/ui">http://asset.info/ui</a></p>
<table style="table-layout:fixed;white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;_white-space:pre;"
class="preWrapContainer">
<tr>
<td width="100%"><pre><span class="tT">Visible: Value. Editable:</span><span class="tI">
</span><span class="tT">None</span></pre></td>
</tr>
</table>
</div>
</div>
</td>
</tr>
<tr>
<td class="firstColumn">
<div class="floatLeft"><b>Used by</b></div>
<div class="floatRight"><input id="button_usedBy_id567" type="image" src="img/btM.gif" value="-"
onclick="switchState('usedBy_id567');"
class="control" /></div>
</td>
<td>
<div id="usedBy_id567" style="display:block">
<table class="usedByTable">
<tr>
<td class="firstColumn">Element </td>
<td><b><a href="ASSET_xsd_Complex_Type_VarianceType.html#id566" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component VarianceType/Attribute')">VarianceType/Attribute</a></b></td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td class="firstColumn"><b>Model</b></td>
<td><b><a href="ASSET_xsd_Complex_Type_AttributeType.html#id568" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component Range')">Range</a></b> | <b><a href="ASSET_xsd_Complex_Type_AttributeType.html#id576" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component Choice')">Choice</a></b></td>
</tr>
<tr>
<td class="firstColumn"><b>Children</b></td>
<td><b><a href="ASSET_xsd_Complex_Type_AttributeType.html#id576" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component Choice')">Choice</a></b>, <b><a href="ASSET_xsd_Complex_Type_AttributeType.html#id568" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component Range')">Range</a></b></td>
</tr>
<tr>
<td class="firstColumn">
<div class="floatLeft"><b>Attributes</b></div>
<div class="floatRight"><input id="button_attributes_id567" type="image" src="img/btM.gif" value="-"
onclick="switchState('attributes_id567');"
class="control" /></div>
</td>
<td>
<div id="attributes_id567" style="display:block">
<table class="attributesTable">
<thead>
<tr>
<th>QName</th>
<th>Type</th>
<th>Fixed</th>
<th>Default</th>
<th>Use</th>
<th>Annotation</th>
</tr>
</thead>
<tr>
<td class="firstColumn"><b><a href="ASSET_xsd_Complex_Type_AttributeType.html#id581" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component name')">name</a></b></td>
<td><b><a href="ASSET_xsd_Simple_Type_validString.html#id575" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component validString')">validString</a></b></td>
<td></td>
<td></td>
<td>required</td>
<td>
<div class="annotation">
<table style="table-layout:fixed;white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;_white-space:pre;"
class="preWrapContainer">
<tr>
<td width="100%"><pre><span class="tT">The attribute name of what we are changing</span></pre></td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td class="firstColumn">
<div class="floatLeft"><b>Source</b></div>
<div class="floatRight"><input id="button_source_id567" type="image" src="img/btM.gif" value="-"
onclick="switchState('source_id567');"
class="control" /></div>
</td>
<td>
<div id="source_id567" style="display:block">
<table style="table-layout:fixed;white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;_white-space:pre;"
class="preWrapContainer">
<tr>
<td width="100%"><pre><span class="tEl"><xs:complexType</span><span class="tAN"> name=</span><span class="tAV">"AttributeType"</span><span class="tEl">></span><span class="tI">
</span><span class="tEl"><xs:annotation</span><span class="tEl">></span><span class="tI">
</span><span class="tEl"><xs:documentation</span><span class="tEl">></span><span class="tT">Change the value of a single attribute.</span><span class="tEl"></xs:documentation></span><span class="tI">
</span><span class="tEl"><xs:documentation</span><span class="tAN"> source=</span><span class="tAV">"http://asset.info/ui"</span><span class="tEl">></span><span class="tT">Visible: Value. Editable:
None</span><span class="tEl"></xs:documentation></span><span class="tI">
</span><span class="tEl"></xs:annotation></span><span class="tI">
</span><span class="tEl"><xs:choice</span><span class="tEl">></span><span class="tI">
</span><span class="tEl"><xs:element</span><span class="tAN"> name=</span><span class="tAV">"Range"</span><span class="tAN"> type=</span><span class="tAV">"RangeType"</span><span class="tEl">></span><span class="tI">
</span><span class="tEl"><xs:annotation</span><span class="tEl">></span><span class="tI">
</span><span class="tEl"><xs:documentation</span><span class="tEl">></span><span class="tT">Use a range of values to specify the attribute.
Visible:
Value. Editable: Text box for value.</span><span class="tEl"></xs:documentation></span><span class="tI">
</span><span class="tEl"></xs:annotation></span><span class="tI">
</span><span class="tEl"></xs:element></span><span class="tI">
</span><span class="tEl"><xs:element</span><span class="tAN"> name=</span><span class="tAV">"Choice"</span><span class="tAN"> type=</span><span class="tAV">"ChoiceType"</span><span class="tEl">></span><span class="tI">
</span><span class="tEl"><xs:annotation</span><span class="tEl">></span><span class="tI">
</span><span class="tEl"><xs:documentation</span><span class="tEl">></span><span class="tT">Provide a list of attribute values to choose
from. Visible:
Value. Editable: Combo box of values.</span><span class="tEl"></xs:documentation></span><span class="tI">
</span><span class="tEl"></xs:annotation></span><span class="tI">
</span><span class="tEl"></xs:element></span><span class="tI">
</span><span class="tEl"></xs:choice></span><span class="tI">
</span><span class="tEl"><xs:attribute</span><span class="tAN"> name=</span><span class="tAV">"name"</span><span class="tAN"> type=</span><span class="tAV">"validString"</span><span class="tAN"> use=</span><span class="tAV">"required"</span><span class="tEl">></span><span class="tI">
</span><span class="tEl"><xs:annotation</span><span class="tEl">></span><span class="tI">
</span><span class="tEl"><xs:documentation</span><span class="tEl">></span><span class="tT">The attribute name of what we are changing</span><span class="tEl"></xs:documentation></span><span class="tI">
</span><span class="tEl"></xs:annotation></span><span class="tI">
</span><span class="tEl"></xs:attribute></span><span class="tI">
</span><span class="tEl"></xs:complexType></span></pre></td>
</tr>
</table>
</div>
</td>
</tr>
</tbody>
</table>
</td>
<td class="rt_lineRight"></td>
</tr>
<tr>
<td class="rt_cornerBottomLeft"></td>
<td class="rt_lineBottom"></td>
<td class="rt_cornerBottomRight"></td>
</tr>
</table><a id="id581"></a><div class="componentTitle">Attribute <span class="qname"><b><a href="ASSET_xsd_Complex_Type_AttributeType.html#id567" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component AttributeType')">AttributeType</a></b> / @name</span></div>
<table class="rt">
<tr>
<td class="rt_cornerTopLeft"></td>
<td class="rt_lineTop"></td>
<td class="rt_cornerTopRight"></td>
</tr>
<tr>
<td class="rt_lineLeft"></td>
<td class="rt_content">
<table class="component">
<tbody>
<tr>
<td class="firstColumn"><b>Namespace</b></td>
<td>No namespace</td>
</tr>
<tr>
<td class="firstColumn">
<div class="floatLeft"><b>Annotations</b></div>
<div class="floatRight"><input id="button_annotations_id581" type="image" src="img/btM.gif" value="-"
onclick="switchState('annotations_id581');"
class="control" /></div>
</td>
<td>
<div id="annotations_id581" style="display:block">
<div class="annotation">
<table style="table-layout:fixed;white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;_white-space:pre;"
class="preWrapContainer">
<tr>
<td width="100%"><pre><span class="tT">The attribute name of what we are changing</span></pre></td>
</tr>
</table>
</div>
</div>
</td>
</tr>
<tr>
<td class="firstColumn"><b>Type</b></td>
<td><b><a href="ASSET_xsd_Simple_Type_validString.html#id575" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component validString')">validString</a></b></td>
</tr>
<tr>
<td class="firstColumn">
<div class="floatLeft"><b>Properties</b></div>
<div class="floatRight"><input id="button_properties_id581" type="image" src="img/btM.gif" value="-"
onclick="switchState('properties_id581');"
class="control" /></div>
</td>
<td>
<div id="properties_id581" style="display:block">
<table class="propertiesTable">
<tr>
<td class="firstColumn">use:
</td>
<td><b>required</b></td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td class="firstColumn">
<div class="floatLeft"><b>Facets</b></div>
<div class="floatRight"><input id="button_facets_id581" type="image" src="img/btM.gif" value="-"
onclick="switchState('facets_id581');"
class="control" /></div>
</td>
<td>
<div id="facets_id581" style="display:block">
<table class="facetsTable">
<tr>
<td class="firstColumn">minLength</td>
<td width="30%"><b>1</b></td>
<td>
<div class="annotation"></div>
</td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td class="firstColumn">
<div class="floatLeft"><b>Used by</b></div>
<div class="floatRight"><input id="button_usedBy_id581" type="image" src="img/btM.gif" value="-"
onclick="switchState('usedBy_id581');"
class="control" /></div>
</td>
<td>
<div id="usedBy_id581" style="display:block">
<table class="usedByTable">
<tr>
<td class="firstColumn">Complex Type </td>
<td><b><a href="ASSET_xsd_Complex_Type_AttributeType.html#id567" target="mainFrame"
title="No namespace"
onclick="updatePageTitle('Schema documentation for component AttributeType')">AttributeType</a></b></td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td class="firstColumn">
<div class="floatLeft"><b>Source</b></div>
<div class="floatRight"><input id="button_source_id581" type="image" src="img/btM.gif" value="-"
onclick="switchState('source_id581');"
class="control" /></div>
</td>
<td>
<div id="source_id581" style="display:block">
<table style="table-layout:fixed;white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;_white-space:pre;"
class="preWrapContainer">
<tr>
<td width="100%"><pre><span class="tEl"><xs:attribute</span><span class="tAN"> name=</span><span class="tAV">"name"</span><span class="tAN"> type=</span><span class="tAV">"validString"</span><span class="tAN"> use=</span><span class="tAV">"required"</span><span class="tEl">></span><span class="tI">
</span><span class="tEl"><xs:annotation</span><span class="tEl">></span><span class="tI">
</span><span class="tEl"><xs:documentation</span><span class="tEl">></span><span class="tT">The attribute name of what we are changing</span><span class="tEl"></xs:documentation></span><span class="tI">
</span><span class="tEl"></xs:annotation></span><span class="tI">
</span><span class="tEl"></xs:attribute></span></pre></td>
</tr>
</table>
</div>
</td>
</tr>
</tbody>
</table>
</td>
<td class="rt_lineRight"></td>
</tr>
<tr>
<td class="rt_cornerBottomLeft"></td>
<td class="rt_lineBottom"></td>
<td class="rt_cornerBottomRight"></td>
</tr>
</table>
<div class="footer">
<hr />
<div align="center">XML Schema documentation generated by <a href="http://www.oxygenxml.com" target="_parent"><span class="oXygenLogo"><span class="redX"><</span>o<span class="redX">X</span>ygen<span class="redX">/></span></span></a><sup>®</sup> XML Editor.
</div>
</div><script type="text/javascript">
<!--
// The namespace is the selected option in the TOC combo.
// Floats the toolbar.
var globalControls = getElementObject("global_controls");
if(globalControls != null){
var browser=navigator.appName;
var version = parseFloat(navigator.appVersion.split('MSIE')[1]);
var IE6 = false;
if ((browser=="Microsoft Internet Explorer") && (version < 7)){
IE6 = true;
}
//alert (IE6 + " |V| " + version);
if(IE6){
// On IE 6 the 'fixed' property is not supported. We must use javascript.
globalControls.style.position='absolute';
// The global controls will do not exist in the TOC frame, when chunking.
findAndFloat("global_controls", 225, 30);
} else {
globalControls.style.position='fixed';
}
globalControls.style.right='0';
}
--></script></body>
</html> | alastrina123/debrief | org.mwc.asset.core/asset_schemas/doc/ASSET_xsd_Complex_Type_AttributeType.html | HTML | epl-1.0 | 62,522 | 56.570902 | 341 | 0.425153 | false |
/*
irssi-python
Copyright (C) 2006 Christopher Davis
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <Python.h>
#include <frameobject.h>
#include <string.h>
#include "pyirssi.h"
#include "pyloader.h"
#include "pyutils.h"
#include "pyscript-object.h"
/* List of loaded modules */
static PyObject *script_modules;
/* List of load paths for scripts */
static GSList *script_paths = NULL;
static PyObject *py_get_script(const char *name, int *id);
static int py_load_module(PyObject *module, const char *path);
static char *py_find_script(const char *name);
/* Add to the list of script load paths */
void pyloader_add_script_path(const char *path)
{
PyObject *ppath = PySys_GetObject("path");
if (ppath)
{
PyList_Append(ppath, PyString_FromString(path));
script_paths = g_slist_append(script_paths, g_strdup(path));
}
}
/* Loads a file into a module; it is not inserted into sys.modules */
static int py_load_module(PyObject *module, const char *path)
{
PyObject *dict, *ret, *fp;
if (PyModule_AddStringConstant(module, "__file__", (char *)path) < 0)
return 0;
dict = PyModule_GetDict(module);
if (PyDict_SetItemString(dict, "__builtins__", PyEval_GetBuiltins()) < 0)
return 0;
/* Dont use the standard library to avoid incompatabilities with
the FILE structure and Python */
fp = PyFile_FromString((char *)path, "r");
if (!fp)
return 0;
ret = PyRun_File(PyFile_AsFile(fp), path, Py_file_input, dict, dict);
Py_DECREF(fp); /* XXX: I assume that the file is closed when refs drop to zero? */
if (!ret)
return 0;
Py_DECREF(ret);
return 1;
}
/* looks up name in Irssi script directories
returns full path or NULL if not found */
static char *py_find_script(const char *name)
{
GSList *node;
char *fname;
char *path = NULL;
//XXX: what if there's another ext?
if (!file_has_ext(name, "py"))
fname = g_strdup_printf("%s.py", name);
else
fname = (char *)name;
/*XXX: use case insensitive path search? */
for (node = script_paths; node && !path; node = node->next)
{
path = g_strdup_printf("%s/%s", (char *)node->data, fname);
if (!g_file_test(path, G_FILE_TEST_IS_REGULAR))
{
g_free(path);
path = NULL;
}
}
if (fname != name)
g_free(fname);
return path;
}
/* Load a script manually using PyRun_File.
* This expects a null terminated array of strings
* (such as from g_strsplit) of the command line.
* The array needs at least one item
*/
static int py_load_script_path_argv(const char *path, char **argv)
{
PyObject *module = NULL, *script = NULL;
char *name = NULL;
name = file_get_filename(path);
module = PyModule_New(name);
g_free(name);
if (!module)
goto error;
script = pyscript_new(module, argv);
Py_DECREF(module);
if (!script)
goto error;
/* insert script obj into module dict, load file */
if (PyModule_AddObject(module, "_script", script) != 0)
goto error;
Py_INCREF(script);
if (!py_load_module(module, path))
goto error;
if (PyList_Append(script_modules, script) != 0)
goto error;
printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "loaded script %s", argv[0]);
/* PySys_WriteStdout("load %s, script -> 0x%x\n", argv[0], script); */
Py_DECREF(script);
return 1;
error:
if (PyErr_Occurred())
PyErr_Print();
printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "error loading script %s", argv[0]);
if (script)
{
/* make sure to clean up any formats, signals, commands that may have been
attached before the exception took place */
pyscript_cleanup(script);
Py_DECREF(script);
}
return 0;
}
static int py_load_script_path(const char *path)
{
int ret;
char *argv[2];
argv[0] = file_get_filename(path);
argv[1] = NULL;
if (py_get_script(argv[0], NULL) != NULL)
pyloader_unload_script(argv[0]);
ret = py_load_script_path_argv(path, argv);
g_free(argv[0]);
return ret;
}
int pyloader_load_script_argv(char **argv)
{
char *path;
int ret;
if (py_get_script(argv[0], NULL) != NULL)
pyloader_unload_script(argv[0]);
path = py_find_script(argv[0]);
if (!path)
{
printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "script %s does not exist", argv[0]);
return 0;
}
ret = py_load_script_path_argv(path, argv);
g_free(path);
return ret;
}
int pyloader_load_script(char *name)
{
char *argv[2];
argv[0] = name;
argv[1] = NULL;
return pyloader_load_script_argv(argv);
}
static PyObject *py_get_script(const char *name, int *id)
{
int i;
g_return_val_if_fail(script_modules != NULL, NULL);
for (i = 0; i < PyList_Size(script_modules); i++)
{
PyObject *script;
char *sname;
script = PyList_GET_ITEM(script_modules, i);
sname = pyscript_get_name(script);
if (sname && !strcmp(sname, name))
{
if (id)
*id = i;
return script;
}
}
return NULL;
}
int pyloader_unload_script(const char *name)
{
int id;
PyObject *script = py_get_script(name, &id);
if (!script)
{
printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "%s is not loaded", name);
return 0;
}
/* PySys_WriteStdout("unload %s, script -> 0x%x\n", name, script); */
pyscript_cleanup(script);
if (PySequence_DelItem(script_modules, id) < 0)
{
PyErr_Print();
printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "error unloading script %s", name);
return 0;
}
/* Probably a good time to call the garbage collecter to clean up reference cycles */
PyGC_Collect();
printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "unloaded script %s", name);
return 1;
}
/* Traverse stack backwards to find the nearest valid _script object in globals */
PyObject *pyloader_find_script_obj(void)
{
PyFrameObject *frame;
for (frame = PyEval_GetFrame(); frame != NULL; frame = frame->f_back)
{
PyObject *script;
g_return_val_if_fail(frame->f_globals != NULL, NULL);
script = PyDict_GetItemString(frame->f_globals, "_script");
if (script && pyscript_check(script))
{
/*
PySys_WriteStdout("Found script at %s in %s, script -> 0x%x\n",
PyString_AS_STRING(frame->f_code->co_name),
PyString_AS_STRING(frame->f_code->co_filename), script);
*/
return script;
}
}
return NULL;
}
char *pyloader_find_script_name(void)
{
PyObject *script = pyloader_find_script_obj();
if (!script)
return NULL;
return pyscript_get_name(script);
}
GSList *pyloader_list(void)
{
int i;
GSList *list = NULL;
g_return_val_if_fail(script_modules != NULL, NULL);
for (i = 0; i < PyList_Size(script_modules); i++)
{
PyObject *scr;
char *name, *file;
scr = PyList_GET_ITEM(script_modules, i);
name = pyscript_get_name(scr);
file = pyscript_get_filename(scr);
if (name && file)
{
PY_LIST_REC *rec;
rec = g_new0(PY_LIST_REC, 1);
rec->name = g_strdup(name);
rec->file = g_strdup(file);
list = g_slist_append(list, rec);
}
}
return list;
}
void pyloader_list_destroy(GSList **list)
{
GSList *node;
if (*list == NULL)
return;
for (node = *list; node != NULL; node = node->next)
{
PY_LIST_REC *rec = node->data;
g_free(rec->name);
g_free(rec->file);
g_free(rec);
}
g_slist_free(*list);
*list = NULL;
}
void pyloader_auto_load(void)
{
GSList *node;
char *autodir;
const char *name;
GDir *gd;
for (node = script_paths; node; node = node->next)
{
autodir = g_strdup_printf("%s/autorun", (char *)node->data);
gd = g_dir_open(autodir, 0, NULL);
g_free(autodir);
if (!gd)
continue;
while ((name = g_dir_read_name(gd)))
{
char *path = g_strdup_printf("%s/autorun/%s", (char*)node->data, name);
if (!strcmp(file_get_ext(name), "py"))
py_load_script_path(path);
g_free(path);
}
g_dir_close(gd);
}
}
int pyloader_init(void)
{
char *pyhome;
g_return_val_if_fail(script_paths == NULL, 0);
g_return_val_if_fail(script_modules == NULL, 0);
script_modules = PyList_New(0);
if (!script_modules)
return 0;
/* Add script location to the load path */
pyhome = g_strdup_printf("%s/scripts", get_irssi_dir());
pyloader_add_script_path(pyhome);
g_free(pyhome);
/* typically /usr/local/share/irssi/scripts */
pyloader_add_script_path(SCRIPTDIR);
return 1;
}
static void py_clear_scripts()
{
int i;
for (i = 0; i < PyList_Size(script_modules); i++)
{
PyObject *scr = PyList_GET_ITEM(script_modules, i);
pyscript_cleanup(scr);
}
Py_DECREF(script_modules);
}
void pyloader_deinit(void)
{
GSList *node;
g_return_if_fail(script_paths != NULL);
g_return_if_fail(script_modules != NULL);
for (node = script_paths; node != NULL; node = node->next)
g_free(node->data);
g_slist_free(script_paths);
script_paths = NULL;
py_clear_scripts();
}
| mdsitton/irssi-python | src/pyloader.c | C | gpl-2.0 | 10,377 | 22.855172 | 90 | 0.585911 | false |
/*
* fs/sdcardfs/inode.c
*
* Copyright (c) 2013 Samsung Electronics Co. Ltd
* Authors: Daeho Jeong, Woojoong Lee, Seunghwan Hyun,
* Sunghwan Yun, Sungjong Seo
*
* This program has been developed as a stackable file system based on
* the WrapFS which written by
*
* Copyright (c) 1998-2011 Erez Zadok
* Copyright (c) 2009 Shrikar Archak
* Copyright (c) 2003-2011 Stony Brook University
* Copyright (c) 2003-2011 The Research Foundation of SUNY
*
* This file is dual licensed. It may be redistributed and/or modified
* under the terms of the Apache 2.0 License OR version 2 of the GNU
* General Public License.
*/
#include "sdcardfs.h"
/* Do not directly use this function. Use OVERRIDE_CRED() instead. */
const struct cred * override_fsids(struct sdcardfs_sb_info* sbi)
{
struct cred * cred;
const struct cred * old_cred;
cred = prepare_creds();
if (!cred)
return NULL;
cred->fsuid = sbi->options.fs_low_uid;
cred->fsgid = sbi->options.fs_low_gid;
old_cred = override_creds(cred);
return old_cred;
}
/* Do not directly use this function, use REVERT_CRED() instead. */
void revert_fsids(const struct cred * old_cred)
{
const struct cred * cur_cred;
cur_cred = current->cred;
revert_creds(old_cred);
put_cred(cur_cred);
}
static int sdcardfs_create(struct inode *dir, struct dentry *dentry,
umode_t mode, bool want_excl)
{
int err = 0;
struct dentry *lower_dentry;
struct dentry *lower_parent_dentry = NULL;
struct path lower_path;
const struct cred *saved_cred = NULL;
if(!check_caller_access_to_name(dir, dentry->d_name.name, 1)) {
printk(KERN_INFO "%s: need to check the caller's gid in packages.list\n"
" dentry: %s, task:%s\n",
__func__, dentry->d_name.name, current->comm);
err = -EACCES;
goto out_eacces;
}
/* save current_cred and override it */
OVERRIDE_CRED(SDCARDFS_SB(dir->i_sb), saved_cred);
sdcardfs_get_lower_path(dentry, &lower_path);
lower_dentry = lower_path.dentry;
lower_parent_dentry = lock_parent(lower_dentry);
err = mnt_want_write(lower_path.mnt);
if (err)
goto out_unlock;
/* set last 16bytes of mode field to 0664 */
mode = (mode & S_IFMT) | 00664;
err = vfs_create(lower_parent_dentry->d_inode, lower_dentry, mode,
true);
if (err)
goto out;
err = sdcardfs_interpose(dentry, dir->i_sb, &lower_path);
if (err)
goto out;
fsstack_copy_attr_times(dir, sdcardfs_lower_inode(dir));
fsstack_copy_inode_size(dir, lower_parent_dentry->d_inode);
out:
mnt_drop_write(lower_path.mnt);
out_unlock:
unlock_dir(lower_parent_dentry);
sdcardfs_put_lower_path(dentry, &lower_path);
REVERT_CRED(saved_cred);
out_eacces:
return err;
}
#if 0
static int sdcardfs_link(struct dentry *old_dentry, struct inode *dir,
struct dentry *new_dentry)
{
struct dentry *lower_old_dentry;
struct dentry *lower_new_dentry;
struct dentry *lower_dir_dentry;
u64 file_size_save;
int err;
struct path lower_old_path, lower_new_path;
const struct cred *saved_cred = NULL;
OVERRIDE_CRED(SDCARDFS_SB(dir->i_sb), saved_cred);
file_size_save = i_size_read(old_dentry->d_inode);
sdcardfs_get_lower_path(old_dentry, &lower_old_path);
sdcardfs_get_lower_path(new_dentry, &lower_new_path);
lower_old_dentry = lower_old_path.dentry;
lower_new_dentry = lower_new_path.dentry;
lower_dir_dentry = lock_parent(lower_new_dentry);
err = mnt_want_write(lower_new_path.mnt);
if (err)
goto out_unlock;
err = vfs_link(lower_old_dentry, lower_dir_dentry->d_inode,
lower_new_dentry);
if (err || !lower_new_dentry->d_inode)
goto out;
err = sdcardfs_interpose(new_dentry, dir->i_sb, &lower_new_path);
if (err)
goto out;
fsstack_copy_attr_times(dir, lower_new_dentry->d_inode);
fsstack_copy_inode_size(dir, lower_new_dentry->d_inode);
set_nlink(old_dentry->d_inode,
sdcardfs_lower_inode(old_dentry->d_inode)->i_nlink);
i_size_write(new_dentry->d_inode, file_size_save);
out:
mnt_drop_write(lower_new_path.mnt);
out_unlock:
unlock_dir(lower_dir_dentry);
sdcardfs_put_lower_path(old_dentry, &lower_old_path);
sdcardfs_put_lower_path(new_dentry, &lower_new_path);
REVERT_CRED(saved_cred);
return err;
}
#endif
static int sdcardfs_unlink(struct inode *dir, struct dentry *dentry)
{
int err;
struct dentry *lower_dentry;
struct inode *lower_dir_inode = sdcardfs_lower_inode(dir);
struct dentry *lower_dir_dentry;
struct path lower_path;
const struct cred *saved_cred = NULL;
if(!check_caller_access_to_name(dir, dentry->d_name.name, 1)) {
printk(KERN_INFO "%s: need to check the caller's gid in packages.list\n"
" dentry: %s, task:%s\n",
__func__, dentry->d_name.name, current->comm);
err = -EACCES;
goto out_eacces;
}
/* save current_cred and override it */
OVERRIDE_CRED(SDCARDFS_SB(dir->i_sb), saved_cred);
sdcardfs_get_lower_path(dentry, &lower_path);
lower_dentry = lower_path.dentry;
dget(lower_dentry);
lower_dir_dentry = lock_parent(lower_dentry);
err = mnt_want_write(lower_path.mnt);
if (err)
goto out_unlock;
err = vfs_unlink(lower_dir_inode, lower_dentry);
/*
* Note: unlinking on top of NFS can cause silly-renamed files.
* Trying to delete such files results in EBUSY from NFS
* below. Silly-renamed files will get deleted by NFS later on, so
* we just need to detect them here and treat such EBUSY errors as
* if the upper file was successfully deleted.
*/
if (err == -EBUSY && lower_dentry->d_flags & DCACHE_NFSFS_RENAMED)
err = 0;
if (err)
goto out;
fsstack_copy_attr_times(dir, lower_dir_inode);
fsstack_copy_inode_size(dir, lower_dir_inode);
set_nlink(dentry->d_inode,
sdcardfs_lower_inode(dentry->d_inode)->i_nlink);
dentry->d_inode->i_ctime = dir->i_ctime;
d_drop(dentry); /* this is needed, else LTP fails (VFS won't do it) */
out:
mnt_drop_write(lower_path.mnt);
out_unlock:
unlock_dir(lower_dir_dentry);
dput(lower_dentry);
sdcardfs_put_lower_path(dentry, &lower_path);
REVERT_CRED(saved_cred);
out_eacces:
return err;
}
#if 0
static int sdcardfs_symlink(struct inode *dir, struct dentry *dentry,
const char *symname)
{
int err = 0;
struct dentry *lower_dentry;
struct dentry *lower_parent_dentry = NULL;
struct path lower_path;
const struct cred *saved_cred = NULL;
OVERRIDE_CRED(SDCARDFS_SB(dir->i_sb), saved_cred);
sdcardfs_get_lower_path(dentry, &lower_path);
lower_dentry = lower_path.dentry;
lower_parent_dentry = lock_parent(lower_dentry);
err = mnt_want_write(lower_path.mnt);
if (err)
goto out_unlock;
err = vfs_symlink(lower_parent_dentry->d_inode, lower_dentry, symname);
if (err)
goto out;
err = sdcardfs_interpose(dentry, dir->i_sb, &lower_path);
if (err)
goto out;
fsstack_copy_attr_times(dir, sdcardfs_lower_inode(dir));
fsstack_copy_inode_size(dir, lower_parent_dentry->d_inode);
out:
unlock_dir(lower_parent_dentry);
sdcardfs_put_lower_path(dentry, &lower_path);
REVERT_CRED(saved_cred);
return err;
}
#endif
static int touch(char *abs_path, mode_t mode) {
struct file *filp = filp_open(abs_path, O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW, mode);
if (IS_ERR(filp)) {
if (PTR_ERR(filp) == -EEXIST) {
return 0;
}
else {
printk(KERN_ERR "sdcardfs: failed to open(%s): %ld\n",
abs_path, PTR_ERR(filp));
return PTR_ERR(filp);
}
}
filp_close(filp, current->files);
return 0;
}
static int sdcardfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
{
int err = 0;
int make_nomedia_in_obb = 0;
struct dentry *lower_dentry;
struct dentry *lower_parent_dentry = NULL;
struct path lower_path;
const struct cred *saved_cred = NULL;
struct sdcardfs_inode_info *pi = SDCARDFS_I(dir);
char *page_buf;
char *nomedia_dir_name;
char *nomedia_fullpath;
int fullpath_namelen;
int touch_err = 0;
if(!check_caller_access_to_name(dir, dentry->d_name.name, 1)) {
printk(KERN_INFO "%s: need to check the caller's gid in packages.list\n"
" dentry: %s, task:%s\n",
__func__, dentry->d_name.name, current->comm);
err = -EACCES;
goto out_eacces;
}
/* save current_cred and override it */
OVERRIDE_CRED(SDCARDFS_SB(dir->i_sb), saved_cred);
/* check disk space */
if (!check_min_free_space(dentry, 0, 1)) {
printk(KERN_INFO "sdcardfs: No minimum free space.\n");
err = -ENOSPC;
goto out_revert;
}
/* the lower_dentry is negative here */
sdcardfs_get_lower_path(dentry, &lower_path);
lower_dentry = lower_path.dentry;
lower_parent_dentry = lock_parent(lower_dentry);
err = mnt_want_write(lower_path.mnt);
if (err)
goto out_unlock;
/* set last 16bytes of mode field to 0775 */
mode = (mode & S_IFMT) | 00775;
err = vfs_mkdir(lower_parent_dentry->d_inode, lower_dentry, mode);
if (err)
goto out;
/* if it is a local obb dentry, setup it with the base obbpath */
if(need_graft_path(dentry)) {
err = setup_obb_dentry(dentry, &lower_path);
if(err) {
/* if the sbi->obbpath is not available, the lower_path won't be
* changed by setup_obb_dentry() but the lower path is saved to
* its orig_path. this dentry will be revalidated later.
* but now, the lower_path should be NULL */
sdcardfs_put_reset_lower_path(dentry);
/* the newly created lower path which saved to its orig_path or
* the lower_path is the base obbpath.
* therefore, an additional path_get is required */
path_get(&lower_path);
} else
make_nomedia_in_obb = 1;
} else {
if (!strcasecmp(dentry->d_name.name, "obb")
&& (pi->perm == PERM_ANDROID))
make_nomedia_in_obb = 1;
}
err = sdcardfs_interpose(dentry, dir->i_sb, &lower_path);
if (err)
goto out;
fsstack_copy_attr_times(dir, sdcardfs_lower_inode(dir));
fsstack_copy_inode_size(dir, lower_parent_dentry->d_inode);
/* update number of links on parent directory */
set_nlink(dir, sdcardfs_lower_inode(dir)->i_nlink);
unlock_dir(lower_parent_dentry);
lower_parent_dentry = NULL;
/* When creating /Android/data and /Android/obb, mark them as .nomedia */
if (make_nomedia_in_obb ||
((pi->perm == PERM_ANDROID) && (!strcasecmp(dentry->d_name.name, "data")))) {
page_buf = (char *)__get_free_page(GFP_KERNEL);
if (!page_buf) {
printk(KERN_ERR "sdcardfs: failed to allocate page buf\n");
goto out;
}
nomedia_dir_name = d_absolute_path(&lower_path, page_buf, PAGE_SIZE);
if (IS_ERR(nomedia_dir_name)) {
free_page((unsigned long)page_buf);
printk(KERN_ERR "sdcardfs: failed to get .nomedia dir name\n");
goto out;
}
fullpath_namelen = page_buf + PAGE_SIZE - nomedia_dir_name - 1;
fullpath_namelen += strlen("/.nomedia");
nomedia_fullpath = kzalloc(fullpath_namelen + 1, GFP_KERNEL);
if (!nomedia_fullpath) {
free_page((unsigned long)page_buf);
printk(KERN_ERR "sdcardfs: failed to allocate .nomedia fullpath buf\n");
goto out;
}
strcpy(nomedia_fullpath, nomedia_dir_name);
free_page((unsigned long)page_buf);
strcat(nomedia_fullpath, "/.nomedia");
touch_err = touch(nomedia_fullpath, 0664);
if (touch_err) {
printk(KERN_ERR "sdcardfs: failed to touch(%s): %d\n",
nomedia_fullpath, touch_err);
kfree(nomedia_fullpath);
goto out;
}
kfree(nomedia_fullpath);
}
out:
mnt_drop_write(lower_path.mnt);
out_unlock:
if (lower_parent_dentry)
unlock_dir(lower_parent_dentry);
sdcardfs_put_lower_path(dentry, &lower_path);
out_revert:
REVERT_CRED(saved_cred);
out_eacces:
return err;
}
static int sdcardfs_rmdir(struct inode *dir, struct dentry *dentry)
{
struct dentry *lower_dentry;
struct dentry *lower_dir_dentry;
int err;
struct path lower_path;
const struct cred *saved_cred = NULL;
if(!check_caller_access_to_name(dir, dentry->d_name.name, 1)) {
printk(KERN_INFO "%s: need to check the caller's gid in packages.list\n"
" dentry: %s, task:%s\n",
__func__, dentry->d_name.name, current->comm);
err = -EACCES;
goto out_eacces;
}
/* save current_cred and override it */
OVERRIDE_CRED(SDCARDFS_SB(dir->i_sb), saved_cred);
/* sdcardfs_get_real_lower(): in case of remove an user's obb dentry
* the dentry on the original path should be deleted. */
sdcardfs_get_real_lower(dentry, &lower_path);
lower_dentry = lower_path.dentry;
lower_dir_dentry = lock_parent(lower_dentry);
err = mnt_want_write(lower_path.mnt);
if (err)
goto out_unlock;
err = vfs_rmdir(lower_dir_dentry->d_inode, lower_dentry);
if (err)
goto out;
d_drop(dentry); /* drop our dentry on success (why not VFS's job?) */
if (dentry->d_inode)
clear_nlink(dentry->d_inode);
fsstack_copy_attr_times(dir, lower_dir_dentry->d_inode);
fsstack_copy_inode_size(dir, lower_dir_dentry->d_inode);
set_nlink(dir, lower_dir_dentry->d_inode->i_nlink);
out:
mnt_drop_write(lower_path.mnt);
out_unlock:
unlock_dir(lower_dir_dentry);
sdcardfs_put_real_lower(dentry, &lower_path);
REVERT_CRED(saved_cred);
out_eacces:
return err;
}
static int sdcardfs_mknod(struct inode *dir, struct dentry *dentry,
umode_t mode, dev_t dev)
{
int err = 0;
struct dentry *lower_dentry;
struct dentry *lower_parent_dentry = NULL;
struct path lower_path;
const struct cred *saved_cred = NULL;
OVERRIDE_CRED(SDCARDFS_SB(dir->i_sb), saved_cred);
sdcardfs_get_lower_path(dentry, &lower_path);
lower_dentry = lower_path.dentry;
lower_parent_dentry = lock_parent(lower_dentry);
err = mnt_want_write(lower_path.mnt);
if (err)
goto out_unlock;
err = vfs_mknod(lower_parent_dentry->d_inode, lower_dentry, mode, dev);
if (err)
goto out;
err = sdcardfs_interpose(dentry, dir->i_sb, &lower_path);
if (err)
goto out;
fsstack_copy_attr_times(dir, sdcardfs_lower_inode(dir));
fsstack_copy_inode_size(dir, lower_parent_dentry->d_inode);
out:
mnt_drop_write(lower_path.mnt);
out_unlock:
unlock_dir(lower_parent_dentry);
sdcardfs_put_lower_path(dentry, &lower_path);
REVERT_CRED(saved_cred);
return err;
}
/*
* The locking rules in sdcardfs_rename are complex. We could use a simpler
* superblock-level name-space lock for renames and copy-ups.
*/
static int sdcardfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
int err = 0;
struct dentry *lower_old_dentry = NULL;
struct dentry *lower_new_dentry = NULL;
struct dentry *lower_old_dir_dentry = NULL;
struct dentry *lower_new_dir_dentry = NULL;
struct dentry *trap = NULL;
struct dentry *new_parent = NULL;
struct path lower_old_path, lower_new_path;
const struct cred *saved_cred = NULL;
struct sdcardfs_sb_info *sbi;
int mask = 0;
if(!check_caller_access_to_name(old_dir, old_dentry->d_name.name, 1) ||
!check_caller_access_to_name(new_dir, new_dentry->d_name.name, 1)) {
printk(KERN_INFO "%s: need to check the caller's gid in packages.list\n"
" new dentry: %s, task:%s\n",
__func__, new_dentry->d_name.name, current->comm);
err = -EACCES;
goto out_eacces;
}
/* save current_cred and override it */
OVERRIDE_CRED(SDCARDFS_SB(old_dir->i_sb), saved_cred);
sdcardfs_get_real_lower(old_dentry, &lower_old_path);
sdcardfs_get_lower_path(new_dentry, &lower_new_path);
lower_old_dentry = lower_old_path.dentry;
lower_new_dentry = lower_new_path.dentry;
lower_old_dir_dentry = dget_parent(lower_old_dentry);
lower_new_dir_dentry = dget_parent(lower_new_dentry);
trap = lock_rename(lower_old_dir_dentry, lower_new_dir_dentry);
/* source should not be ancestor of target */
if (trap == lower_old_dentry) {
err = -EINVAL;
goto out;
}
/* target should not be ancestor of source */
if (trap == lower_new_dentry) {
err = -ENOTEMPTY;
goto out;
}
err = mnt_want_write(lower_old_path.mnt);
if (err)
goto out;
err = mnt_want_write(lower_new_path.mnt);
if (err)
goto out_drop_old_write;
err = vfs_rename(lower_old_dir_dentry->d_inode, lower_old_dentry,
lower_new_dir_dentry->d_inode, lower_new_dentry);
if (err)
goto out_err;
/* Copy attrs from lower dir, but i_uid/i_gid */
sdcardfs_copy_inode_attr(new_dir, lower_new_dir_dentry->d_inode);
fsstack_copy_inode_size(new_dir, lower_new_dir_dentry->d_inode);
sbi = SDCARDFS_SB(new_dentry->d_sb);
mask = sbi->options.sdfs_mask;
fix_derived_permission(new_dir, mask);
if (new_dir != old_dir) {
sdcardfs_copy_inode_attr(old_dir, lower_old_dir_dentry->d_inode);
fsstack_copy_inode_size(old_dir, lower_old_dir_dentry->d_inode);
sbi = SDCARDFS_SB(old_dentry->d_sb);
mask = sbi->options.sdfs_mask;
fix_derived_permission(old_dir, mask);
/* update the derived permission of the old_dentry
* with its new parent
*/
new_parent = dget_parent(new_dentry);
if(new_parent) {
if(old_dentry->d_inode) {
get_derived_permission(new_parent, old_dentry);
sbi = SDCARDFS_SB(old_dentry->d_sb);
mask = sbi->options.sdfs_mask;
fix_derived_permission(old_dentry->d_inode, mask);
}
dput(new_parent);
}
}
out_err:
mnt_drop_write(lower_new_path.mnt);
out_drop_old_write:
mnt_drop_write(lower_old_path.mnt);
out:
unlock_rename(lower_old_dir_dentry, lower_new_dir_dentry);
dput(lower_old_dir_dentry);
dput(lower_new_dir_dentry);
sdcardfs_put_real_lower(old_dentry, &lower_old_path);
sdcardfs_put_lower_path(new_dentry, &lower_new_path);
REVERT_CRED(saved_cred);
out_eacces:
return err;
}
static int sdcardfs_readlink(struct dentry *dentry, char __user *buf,
int bufsiz)
{
int err;
struct dentry *lower_dentry;
struct path lower_path;
/* XXX readlink does not requires overriding credential */
sdcardfs_get_lower_path(dentry, &lower_path);
lower_dentry = lower_path.dentry;
if (!lower_dentry->d_inode->i_op ||
!lower_dentry->d_inode->i_op->readlink) {
err = -EINVAL;
goto out;
}
err = lower_dentry->d_inode->i_op->readlink(lower_dentry,
buf, bufsiz);
if (err < 0)
goto out;
fsstack_copy_attr_atime(dentry->d_inode, lower_dentry->d_inode);
out:
sdcardfs_put_lower_path(dentry, &lower_path);
return err;
}
#if 0
static void *sdcardfs_follow_link(struct dentry *dentry, struct nameidata *nd)
{
char *buf;
int len = PAGE_SIZE, err;
mm_segment_t old_fs;
/* This is freed by the put_link method assuming a successful call. */
buf = kmalloc(len, GFP_KERNEL);
if (!buf) {
buf = ERR_PTR(-ENOMEM);
goto out;
}
/* read the symlink, and then we will follow it */
old_fs = get_fs();
set_fs(KERNEL_DS);
err = sdcardfs_readlink(dentry, buf, len);
set_fs(old_fs);
if (err < 0) {
kfree(buf);
buf = ERR_PTR(err);
} else {
buf[err] = '\0';
}
out:
nd_set_link(nd, buf);
return NULL;
}
/* this @nd *IS* still used */
static void sdcardfs_put_link(struct dentry *dentry, struct nameidata *nd,
void *cookie)
{
char *buf = nd_get_link(nd);
if (!IS_ERR(buf)) /* free the char* */
kfree(buf);
}
#endif
static int sdcardfs_permission(struct inode *inode, int mask)
{
int err;
/*
* Permission check on sdcardfs inode.
* Calling process should have AID_SDCARD_RW permission
*/
err = generic_permission(inode, mask);
/* XXX
* Original sdcardfs code calls inode_permission(lower_inode,.. )
* for checking inode permission. But doing such things here seems
* duplicated work, because the functions called after this func,
* such as vfs_create, vfs_unlink, vfs_rename, and etc,
* does exactly same thing, i.e., they calls inode_permission().
* So we just let they do the things.
* If there are any security hole, just uncomment following if block.
*/
#if 0
if (!err) {
/*
* Permission check on lower_inode(=EXT4).
* we check it with AID_MEDIA_RW permission
*/
struct inode *lower_inode;
OVERRIDE_CRED(SDCARDFS_SB(inode->sb));
lower_inode = sdcardfs_lower_inode(inode);
err = inode_permission(lower_inode, mask);
REVERT_CRED();
}
#endif
return err;
}
static int sdcardfs_getattr(struct vfsmount *mnt, struct dentry *dentry,
struct kstat *stat)
{
struct dentry *lower_dentry;
struct inode *inode;
struct inode *lower_inode;
struct path lower_path;
struct dentry *parent;
struct sdcardfs_sb_info *sbi;
int mask = 0;
parent = dget_parent(dentry);
if(!check_caller_access_to_name(parent->d_inode, dentry->d_name.name, 0)) {
printk(KERN_INFO "%s: need to check the caller's gid in packages.list\n"
" dentry: %s, task:%s\n",
__func__, dentry->d_name.name, current->comm);
dput(parent);
return -EACCES;
}
dput(parent);
inode = dentry->d_inode;
sdcardfs_get_lower_path(dentry, &lower_path);
lower_dentry = lower_path.dentry;
lower_inode = sdcardfs_lower_inode(inode);
mutex_lock(&inode->i_mutex);
sdcardfs_copy_inode_attr(inode, lower_inode);
fsstack_copy_inode_size(inode, lower_inode);
/* if the dentry has been moved from other location
* so, on this stage, its derived permission must be
* rechecked from its private field.
*/
sbi = SDCARDFS_SB(dentry->d_sb);
mask = sbi->options.sdfs_mask;
fix_derived_permission(inode, mask);
mutex_unlock(&inode->i_mutex);
generic_fillattr(inode, stat);
sdcardfs_put_lower_path(dentry, &lower_path);
return 0;
}
static int sdcardfs_setattr(struct dentry *dentry, struct iattr *ia)
{
int err = 0;
struct dentry *lower_dentry;
struct inode *inode;
struct inode *lower_inode;
struct path lower_path;
struct iattr lower_ia;
struct dentry *parent;
struct sdcardfs_sb_info *sbi;
int mask = 0;
inode = dentry->d_inode;
/*
* Check if user has permission to change inode. We don't check if
* this user can change the lower inode: that should happen when
* calling notify_change on the lower inode.
*/
err = inode_change_ok(inode, ia);
/* no vfs_XXX operations required, cred overriding will be skipped. wj*/
if (!err) {
/* check the Android group ID */
parent = dget_parent(dentry);
if(!(ia->ia_valid & ATTR_CTIME) &&
!check_caller_access_to_name(parent->d_inode, dentry->d_name.name, 1)) {
printk(KERN_INFO "%s: need to check the caller's gid in packages.list\n"
" dentry: %s, task:%s\n",
__func__, dentry->d_name.name, current->comm);
err = -EACCES;
}
dput(parent);
}
if (err)
goto out_err;
sdcardfs_get_lower_path(dentry, &lower_path);
lower_dentry = lower_path.dentry;
lower_inode = sdcardfs_lower_inode(inode);
/* prepare our own lower struct iattr (with the lower file) */
memcpy(&lower_ia, ia, sizeof(lower_ia));
if (ia->ia_valid & ATTR_FILE)
lower_ia.ia_file = sdcardfs_lower_file(ia->ia_file);
lower_ia.ia_valid &= ~(ATTR_UID | ATTR_GID | ATTR_MODE);
/*
* If shrinking, first truncate upper level to cancel writing dirty
* pages beyond the new eof; and also if its' maxbytes is more
* limiting (fail with -EFBIG before making any change to the lower
* level). There is no need to vmtruncate the upper level
* afterwards in the other cases: we fsstack_copy_inode_size from
* the lower level.
*/
if (ia->ia_valid & ATTR_SIZE) {
err = inode_newsize_ok(inode, ia->ia_size);
if (err) {
goto out;
}
truncate_setsize(inode, ia->ia_size);
}
/*
* mode change is for clearing setuid/setgid bits. Allow lower fs
* to interpret this in its own way.
*/
if (lower_ia.ia_valid & (ATTR_KILL_SUID | ATTR_KILL_SGID))
lower_ia.ia_valid &= ~ATTR_MODE;
/* notify the (possibly copied-up) lower inode */
/*
* Note: we use lower_dentry->d_inode, because lower_inode may be
* unlinked (no inode->i_sb and i_ino==0. This happens if someone
* tries to open(), unlink(), then ftruncate() a file.
*/
mutex_lock(&lower_dentry->d_inode->i_mutex);
err = notify_change(lower_dentry, &lower_ia); /* note: lower_ia */
mutex_unlock(&lower_dentry->d_inode->i_mutex);
if (err)
goto out;
/* get attributes from the lower inode */
sdcardfs_copy_inode_attr(inode, lower_inode);
/* update derived permission of the upper inode */
sbi = SDCARDFS_SB(dentry->d_sb);
mask = sbi->options.sdfs_mask;
fix_derived_permission(inode, mask);
/*
* Not running fsstack_copy_inode_size(inode, lower_inode), because
* VFS should update our inode size, and notify_change on
* lower_inode should update its size.
*/
out:
sdcardfs_put_lower_path(dentry, &lower_path);
out_err:
return err;
}
const struct inode_operations sdcardfs_symlink_iops = {
.permission = sdcardfs_permission,
.setattr = sdcardfs_setattr,
.readlink = sdcardfs_readlink,
/* XXX Following operations are implemented,
* but FUSE(sdcard) or FAT does not support them
* These methods are *NOT* perfectly tested.
.put_link = sdcardfs_put_link,
.follow_link = sdcardfs_follow_link,
*/
};
const struct inode_operations sdcardfs_dir_iops = {
.create = sdcardfs_create,
.lookup = sdcardfs_lookup,
.permission = sdcardfs_permission,
.unlink = sdcardfs_unlink,
.mkdir = sdcardfs_mkdir,
.rmdir = sdcardfs_rmdir,
.rename = sdcardfs_rename,
.setattr = sdcardfs_setattr,
.getattr = sdcardfs_getattr,
.mknod = sdcardfs_mknod,
/* XXX Following operations are implemented,
* but FUSE(sdcard) or FAT does not support them
* These methods are *NOT* perfectly tested.
.symlink = sdcardfs_symlink,
*/
};
const struct inode_operations sdcardfs_main_iops = {
.permission = sdcardfs_permission,
.setattr = sdcardfs_setattr,
.getattr = sdcardfs_getattr,
};
| LG-V10/LGV10__pplus_msm8992_kernel | fs/sdcardfs/inode.c | C | gpl-2.0 | 25,231 | 27.769669 | 84 | 0.679204 | false |
/* Copyright (C) 2006 - 2008 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: Boss_Magmadar
SD%Complete: 75
SDComment: Conflag on ground nyi, fear causes issues without VMAPs
SDCategory: Molten Core
EndScriptData */
#include "precompiled.h"
#define EMOTE_FRENZY -1409001
#define SPELL_FRENZY 19451
#define SPELL_MAGMASPIT 19449 //This is actually a buff he gives himself
#define SPELL_PANIC 19408
#define SPELL_LAVABOMB 19411 //This calls a dummy server side effect that isn't implemented yet
#define SPELL_LAVABOMB_ALT 19428 //This is the spell that the lava bomb casts
struct TRINITY_DLL_DECL boss_magmadarAI : public ScriptedAI
{
boss_magmadarAI(Creature *c) : ScriptedAI(c) {}
uint32 Frenzy_Timer;
uint32 Panic_Timer;
uint32 Lavabomb_Timer;
void Reset()
{
Frenzy_Timer = 30000;
Panic_Timer = 20000;
Lavabomb_Timer = 12000;
m_creature->CastSpell(m_creature,SPELL_MAGMASPIT,true);
}
void EnterCombat(Unit *who)
{
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
//Frenzy_Timer
if (Frenzy_Timer < diff)
{
DoScriptText(EMOTE_FRENZY, m_creature);
DoCast(m_creature,SPELL_FRENZY);
Frenzy_Timer = 15000;
}else Frenzy_Timer -= diff;
//Panic_Timer
if (Panic_Timer < diff)
{
DoCast(m_creature->getVictim(),SPELL_PANIC);
Panic_Timer = 35000;
}else Panic_Timer -= diff;
//Lavabomb_Timer
if (Lavabomb_Timer < diff)
{
if( Unit* target = SelectUnit(SELECT_TARGET_RANDOM,0) )
DoCast(target,SPELL_LAVABOMB_ALT);
Lavabomb_Timer = 12000;
}else Lavabomb_Timer -= diff;
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI_boss_magmadar(Creature *_Creature)
{
return new boss_magmadarAI (_Creature);
}
void AddSC_boss_magmadar()
{
Script *newscript;
newscript = new Script;
newscript->Name="boss_magmadar";
newscript->GetAI = &GetAI_boss_magmadar;
newscript->RegisterSelf();
}
| aedansilver/Proyecto-TBC | src/bindings/scripts/scripts/zone/molten_core/boss_magmadar.cpp | C++ | gpl-2.0 | 2,994 | 28.94 | 126 | 0.632933 | false |
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javafx.binding;
import com.sun.javafx.collections.annotations.ReturnsUnmodifiableCollection;
import javafx.beans.InvalidationListenerMock;
import javafx.beans.Observable;
import javafx.beans.binding.MapBinding;
import javafx.beans.property.ReadOnlyBooleanProperty;
import javafx.beans.property.ReadOnlyIntegerProperty;
import javafx.beans.value.ChangeListenerMock;
import javafx.beans.value.ObservableValueBase;
import javafx.collections.FXCollections;
import javafx.collections.MockMapObserver;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import org.junit.Before;
import org.junit.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static javafx.collections.MockMapObserver.Call;
import static org.junit.Assert.*;
/**
*/
public class MapBindingTest {
private final static Object KEY_1 = new Object();
private final static Object KEY_2_0 = new Object();
private final static Object KEY_2_1 = new Object();
private final static Object DATA_1 = new Object();
private final static Object DATA_2_0 = new Object();
private final static Object DATA_2_1 = new Object();
private ObservableStub dependency1;
private ObservableStub dependency2;
private MapBindingImpl binding0;
private MapBindingImpl binding1;
private MapBindingImpl binding2;
private ObservableMap<Object, Object> emptyMap;
private ObservableMap<Object, Object> set1;
private ObservableMap<Object, Object> set2;
private MockMapObserver<Object, Object> listener;
@Before
public void setUp() {
dependency1 = new ObservableStub();
dependency2 = new ObservableStub();
binding0 = new MapBindingImpl();
binding1 = new MapBindingImpl(dependency1);
binding2 = new MapBindingImpl(dependency1, dependency2);
emptyMap = FXCollections.observableMap(Collections.emptyMap());
set1 = FXCollections.observableMap(Collections.singletonMap(KEY_1, DATA_1));
final Map<Object, Object> map = new HashMap<Object, Object>();
map.put(KEY_2_0, DATA_2_0);
map.put(KEY_2_1, DATA_2_1);
set2 = FXCollections.observableMap(map);
listener = new MockMapObserver<Object, Object>();
binding0.setValue(set2);
binding1.setValue(set2);
binding2.setValue(set2);
}
@Test
public void testSizeProperty() {
assertEquals(binding0, binding0.sizeProperty().getBean());
assertEquals(binding1, binding1.sizeProperty().getBean());
assertEquals(binding2, binding2.sizeProperty().getBean());
final ReadOnlyIntegerProperty size = binding1.sizeProperty();
assertEquals("size", size.getName());
assertEquals(2, size.get());
binding1.setValue(emptyMap);
dependency1.fireValueChangedEvent();
assertEquals(0, size.get());
binding1.setValue(null);
dependency1.fireValueChangedEvent();
assertEquals(0, size.get());
binding1.setValue(set1);
dependency1.fireValueChangedEvent();
assertEquals(1, size.get());
}
@Test
public void testEmptyProperty() {
assertEquals(binding0, binding0.emptyProperty().getBean());
assertEquals(binding1, binding1.emptyProperty().getBean());
assertEquals(binding2, binding2.emptyProperty().getBean());
final ReadOnlyBooleanProperty empty = binding1.emptyProperty();
assertEquals("empty", empty.getName());
assertFalse(empty.get());
binding1.setValue(emptyMap);
dependency1.fireValueChangedEvent();
assertTrue(empty.get());
binding1.setValue(null);
dependency1.fireValueChangedEvent();
assertTrue(empty.get());
binding1.setValue(set1);
dependency1.fireValueChangedEvent();
assertFalse(empty.get());
}
@Test
public void testNoDependency_MapChangeListener() {
binding0.getValue();
binding0.addListener(listener);
System.gc(); // making sure we did not not overdo weak references
assertEquals(true, binding0.isValid());
// calling getValue()
binding0.reset();
binding0.getValue();
assertEquals(0, binding0.getComputeValueCounter());
assertEquals(0, listener.getCallsNumber());
assertEquals(true, binding0.isValid());
}
@Test
public void testSingleDependency_MapChangeListener() {
binding1.getValue();
binding1.addListener(listener);
System.gc(); // making sure we did not not overdo weak references
assertEquals(true, binding1.isValid());
// fire single change event
binding1.reset();
listener.clear();
binding1.setValue(set1);
dependency1.fireValueChangedEvent();
assertEquals(1, binding1.getComputeValueCounter());
listener.assertMultipleCalls(new Call[]{new Call<Object, Object>(KEY_2_0, DATA_2_0, null), new Call<Object, Object>(KEY_2_1, DATA_2_1, null), new Call<Object, Object>(KEY_1, null, DATA_1)});
assertEquals(true, binding1.isValid());
listener.clear();
binding1.getValue();
assertEquals(0, binding1.getComputeValueCounter());
assertEquals(0, listener.getCallsNumber());
assertEquals(true, binding1.isValid());
listener.clear();
// fire single change event with same value
binding1.setValue(set1);
dependency1.fireValueChangedEvent();
assertEquals(1, binding1.getComputeValueCounter());
assertEquals(0, listener.getCallsNumber());
assertEquals(true, binding1.isValid());
listener.clear();
binding1.getValue();
assertEquals(0, binding1.getComputeValueCounter());
assertEquals(0, listener.getCallsNumber());
assertEquals(true, binding1.isValid());
listener.clear();
// fire two change events
binding1.setValue(set2);
dependency1.fireValueChangedEvent();
listener.clear();
binding1.setValue(set1);
dependency1.fireValueChangedEvent();
assertEquals(2, binding1.getComputeValueCounter());
listener.assertMultipleCalls(new Call[]{new Call<Object, Object>(KEY_2_0, DATA_2_0, null), new Call<Object, Object>(KEY_2_1, DATA_2_1, null), new Call<Object, Object>(KEY_1, null, DATA_1)});
assertEquals(true, binding1.isValid());
listener.clear();
binding1.getValue();
assertEquals(0, binding1.getComputeValueCounter());
assertEquals(0, listener.getCallsNumber());
assertEquals(true, binding1.isValid());
listener.clear();
// fire two change events with same value
binding1.setValue(set2);
dependency1.fireValueChangedEvent();
binding1.setValue(set2);
dependency1.fireValueChangedEvent();
assertEquals(2, binding1.getComputeValueCounter());
listener.assertMultipleCalls(new Call[] {new Call<Object, Object>(KEY_1, DATA_1, null), new Call<Object, Object>(KEY_2_0, null, DATA_2_0), new Call<Object, Object>(KEY_2_1, null, DATA_2_1)});
assertEquals(true, binding1.isValid());
listener.clear();
binding1.getValue();
assertEquals(0, binding1.getComputeValueCounter());
assertEquals(0, listener.getCallsNumber());
assertEquals(true, binding1.isValid());
}
@Test
public void testChangeContent_InvalidationListener() {
final InvalidationListenerMock listenerMock = new InvalidationListenerMock();
binding1.get();
binding1.addListener(listenerMock);
assertTrue(binding1.isValid());
binding1.reset();
listenerMock.reset();
set2.put(new Object(), new Object());
assertEquals(0, binding1.getComputeValueCounter());
listenerMock.check(binding1, 1);
assertTrue(binding1.isValid());
}
@Test
public void testChangeContent_ChangeListener() {
final ChangeListenerMock listenerMock = new ChangeListenerMock(null);
binding1.get();
binding1.addListener(listenerMock);
assertTrue(binding1.isValid());
binding1.reset();
listenerMock.reset();
set2.put(new Object(), new Object());
assertEquals(0, binding1.getComputeValueCounter());
listenerMock.check(binding1, set2, set2, 1);
assertTrue(binding1.isValid());
}
@Test
public void testChangeContent_MapChangeListener() {
binding1.get();
binding1.addListener(listener);
assertTrue(binding1.isValid());
final Object newKey = new Object();
final Object newData = new Object();
binding1.reset();
listener.clear();
set2.put(newKey, newData);
assertEquals(0, binding1.getComputeValueCounter());
listener.assertAdded(MockMapObserver.Tuple.tup(newKey, newData));
assertTrue(binding1.isValid());
}
public static class ObservableStub extends ObservableValueBase<Object> {
@Override public void fireValueChangedEvent() {super.fireValueChangedEvent();}
@Override
public Object getValue() {
return null;
}
}
private static class MapBindingImpl extends MapBinding<Object, Object> {
private int computeValueCounter = 0;
private ObservableMap<Object, Object> value;
public void setValue(ObservableMap<Object, Object> value) {
this.value = value;
}
public MapBindingImpl(Observable... dep) {
super.bind(dep);
}
public int getComputeValueCounter() {
final int result = computeValueCounter;
reset();
return result;
}
public void reset() {
computeValueCounter = 0;
}
@Override
public ObservableMap<Object, Object> computeValue() {
computeValueCounter++;
return value;
}
@Override @ReturnsUnmodifiableCollection
public ObservableList<?> getDependencies() {
fail("Should not reach here");
return null;
}
}
// private class MapChangeListenerMock implements MapChangeListener<Object, Object> {
//
// private Change<? extends Object> change;
// private int counter;
//
// @Override
// public void onChanged(Change<? extends Object> change) {
// this.change = change;
// counter++;
// }
//
// private void reset() {
// change = null;
// counter = 0;
// }
//
// private void checkNotCalled() {
// assertEquals(null, change);
// assertEquals(0, counter);
// reset();
// }
//
// private void check(ObservableMap<Object, Object> oldMap, ObservableMap<Object, Object> newMap, int counter) {
// assertTrue(change.next());
// assertTrue(change.wasReplaced());
// assertEquals(oldMap, change.getRemoved());
// assertEquals(newMap, change.getMap());
// assertFalse(change.next());
// assertEquals(counter, this.counter);
// reset();
// }
//
// private void check(int pos, Object newObject, int counter) {
// assertTrue(change.next());
// assertTrue(change.wasAdded());
// assertEquals(pos, change.getFrom());
// assertEquals(Collections.singletonMap(newObject), change.getAddedSubMap());
// assertFalse(change.next());
// assertEquals(counter, this.counter);
// reset();
// }
// }
}
| loveyoupeng/rt | modules/base/src/test/java/javafx/binding/MapBindingTest.java | Java | gpl-2.0 | 12,899 | 35.437853 | 199 | 0.653384 | false |
#include "stdafx.h"
#include "Emu/Cell/PPUModule.h"
#include "Emu/IdManager.h"
#include "sceNp.h"
#include "sceNp2.h"
#include "Emu/NP/np_handler.h"
#include "Emu/NP/np_contexts.h"
#include "cellSysutil.h"
LOG_CHANNEL(sceNp2);
template <>
void fmt_class_string<SceNpMatching2Error>::format(std::string& out, u64 arg)
{
format_enum(out, arg, [](auto error) {
switch (error)
{
STR_CASE(SCE_NP_MATCHING2_ERROR_OUT_OF_MEMORY);
STR_CASE(SCE_NP_MATCHING2_ERROR_ALREADY_INITIALIZED);
STR_CASE(SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED);
STR_CASE(SCE_NP_MATCHING2_ERROR_CONTEXT_MAX);
STR_CASE(SCE_NP_MATCHING2_ERROR_CONTEXT_ALREADY_EXISTS);
STR_CASE(SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_FOUND);
STR_CASE(SCE_NP_MATCHING2_ERROR_CONTEXT_ALREADY_STARTED);
STR_CASE(SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_STARTED);
STR_CASE(SCE_NP_MATCHING2_ERROR_SERVER_NOT_FOUND);
STR_CASE(SCE_NP_MATCHING2_ERROR_INVALID_ARGUMENT);
STR_CASE(SCE_NP_MATCHING2_ERROR_INVALID_CONTEXT_ID);
STR_CASE(SCE_NP_MATCHING2_ERROR_INVALID_SERVER_ID);
STR_CASE(SCE_NP_MATCHING2_ERROR_INVALID_WORLD_ID);
STR_CASE(SCE_NP_MATCHING2_ERROR_INVALID_LOBBY_ID);
STR_CASE(SCE_NP_MATCHING2_ERROR_INVALID_ROOM_ID);
STR_CASE(SCE_NP_MATCHING2_ERROR_INVALID_MEMBER_ID);
STR_CASE(SCE_NP_MATCHING2_ERROR_INVALID_ATTRIBUTE_ID);
STR_CASE(SCE_NP_MATCHING2_ERROR_INVALID_CASTTYPE);
STR_CASE(SCE_NP_MATCHING2_ERROR_INVALID_SORT_METHOD);
STR_CASE(SCE_NP_MATCHING2_ERROR_INVALID_MAX_SLOT);
STR_CASE(SCE_NP_MATCHING2_ERROR_INVALID_MATCHING_SPACE);
STR_CASE(SCE_NP_MATCHING2_ERROR_INVALID_BLOCK_KICK_FLAG);
STR_CASE(SCE_NP_MATCHING2_ERROR_INVALID_MESSAGE_TARGET);
STR_CASE(SCE_NP_MATCHING2_ERROR_RANGE_FILTER_MAX);
STR_CASE(SCE_NP_MATCHING2_ERROR_INSUFFICIENT_BUFFER);
STR_CASE(SCE_NP_MATCHING2_ERROR_DESTINATION_DISAPPEARED);
STR_CASE(SCE_NP_MATCHING2_ERROR_REQUEST_TIMEOUT);
STR_CASE(SCE_NP_MATCHING2_ERROR_INVALID_ALIGNMENT);
STR_CASE(SCE_NP_MATCHING2_ERROR_REQUEST_CB_QUEUE_OVERFLOW);
STR_CASE(SCE_NP_MATCHING2_ERROR_EVENT_CB_QUEUE_OVERFLOW);
STR_CASE(SCE_NP_MATCHING2_ERROR_MSG_CB_QUEUE_OVERFLOW);
STR_CASE(SCE_NP_MATCHING2_ERROR_CONNECTION_CLOSED_BY_SERVER);
STR_CASE(SCE_NP_MATCHING2_ERROR_SSL_VERIFY_FAILED);
STR_CASE(SCE_NP_MATCHING2_ERROR_SSL_HANDSHAKE);
STR_CASE(SCE_NP_MATCHING2_ERROR_SSL_SEND);
STR_CASE(SCE_NP_MATCHING2_ERROR_SSL_RECV);
STR_CASE(SCE_NP_MATCHING2_ERROR_JOINED_SESSION_MAX);
STR_CASE(SCE_NP_MATCHING2_ERROR_ALREADY_JOINED);
STR_CASE(SCE_NP_MATCHING2_ERROR_INVALID_SESSION_TYPE);
STR_CASE(SCE_NP_MATCHING2_ERROR_CLAN_LOBBY_NOT_EXIST);
STR_CASE(SCE_NP_MATCHING2_ERROR_NP_SIGNED_OUT);
STR_CASE(SCE_NP_MATCHING2_ERROR_CONTEXT_UNAVAILABLE);
STR_CASE(SCE_NP_MATCHING2_ERROR_SERVER_NOT_AVAILABLE);
STR_CASE(SCE_NP_MATCHING2_ERROR_NOT_ALLOWED);
STR_CASE(SCE_NP_MATCHING2_ERROR_ABORTED);
STR_CASE(SCE_NP_MATCHING2_ERROR_REQUEST_NOT_FOUND);
STR_CASE(SCE_NP_MATCHING2_ERROR_SESSION_DESTROYED);
STR_CASE(SCE_NP_MATCHING2_ERROR_CONTEXT_STOPPED);
STR_CASE(SCE_NP_MATCHING2_ERROR_INVALID_REQUEST_PARAMETER);
STR_CASE(SCE_NP_MATCHING2_ERROR_NOT_NP_SIGN_IN);
STR_CASE(SCE_NP_MATCHING2_ERROR_ROOM_NOT_FOUND);
STR_CASE(SCE_NP_MATCHING2_ERROR_ROOM_MEMBER_NOT_FOUND);
STR_CASE(SCE_NP_MATCHING2_ERROR_LOBBY_NOT_FOUND);
STR_CASE(SCE_NP_MATCHING2_ERROR_LOBBY_MEMBER_NOT_FOUND);
STR_CASE(SCE_NP_MATCHING2_ERROR_EVENT_DATA_NOT_FOUND);
STR_CASE(SCE_NP_MATCHING2_ERROR_KEEPALIVE_TIMEOUT);
STR_CASE(SCE_NP_MATCHING2_ERROR_TIMEOUT_TOO_SHORT);
STR_CASE(SCE_NP_MATCHING2_ERROR_TIMEDOUT);
STR_CASE(SCE_NP_MATCHING2_ERROR_CREATE_HEAP);
STR_CASE(SCE_NP_MATCHING2_ERROR_INVALID_ATTRIBUTE_SIZE);
STR_CASE(SCE_NP_MATCHING2_ERROR_CANNOT_ABORT);
STR_CASE(SCE_NP_MATCHING2_RESOLVER_ERROR_NO_DNS_SERVER);
STR_CASE(SCE_NP_MATCHING2_RESOLVER_ERROR_INVALID_PACKET);
STR_CASE(SCE_NP_MATCHING2_RESOLVER_ERROR_TIMEOUT);
STR_CASE(SCE_NP_MATCHING2_RESOLVER_ERROR_NO_RECORD);
STR_CASE(SCE_NP_MATCHING2_RESOLVER_ERROR_RES_PACKET_FORMAT);
STR_CASE(SCE_NP_MATCHING2_RESOLVER_ERROR_RES_SERVER_FAILURE);
STR_CASE(SCE_NP_MATCHING2_RESOLVER_ERROR_NO_HOST);
STR_CASE(SCE_NP_MATCHING2_RESOLVER_ERROR_RES_NOT_IMPLEMENTED);
STR_CASE(SCE_NP_MATCHING2_RESOLVER_ERROR_RES_SERVER_REFUSED);
STR_CASE(SCE_NP_MATCHING2_RESOLVER_ERROR_RESP_TRUNCATED);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_BAD_REQUEST);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_SERVICE_UNAVAILABLE);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_BUSY);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_END_OF_SERVICE);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_INTERNAL_SERVER_ERROR);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_PLAYER_BANNED);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_FORBIDDEN);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_BLOCKED);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_UNSUPPORTED_NP_ENV);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_INVALID_TICKET);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_INVALID_SIGNATURE);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_EXPIRED_TICKET);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_ENTITLEMENT_REQUIRED);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_NO_SUCH_CONTEXT);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_CLOSED);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_NO_SUCH_TITLE);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_NO_SUCH_WORLD);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_NO_SUCH_LOBBY);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_NO_SUCH_ROOM);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_NO_SUCH_LOBBY_INSTANCE);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_NO_SUCH_ROOM_INSTANCE);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_PASSWORD_MISMATCH);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_LOBBY_FULL);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_ROOM_FULL);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_GROUP_FULL);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_NO_SUCH_USER);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_TITLE_PASSPHRASE_MISMATCH);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_DUPLICATE_LOBBY);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_DUPLICATE_ROOM);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_NO_JOIN_GROUP_LABEL);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_NO_SUCH_GROUP);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_NO_PASSWORD);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_MAX_OVER_SLOT_GROUP);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_MAX_OVER_PASSWORD_MASK);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_DUPLICATE_GROUP_LABEL);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_REQUEST_OVERFLOW);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_ALREADY_JOINED);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_NAT_TYPE_MISMATCH);
STR_CASE(SCE_NP_MATCHING2_SERVER_ERROR_ROOM_INCONSISTENCY);
// STR_CASE(SCE_NP_MATCHING2_NET_ERRNO_BASE);
// STR_CASE(SCE_NP_MATCHING2_NET_H_ERRNO_BASE);
}
return unknown;
});
}
template <>
void fmt_class_string<SceNpOauthError>::format(std::string& out, u64 arg)
{
format_enum(out, arg, [](auto error) {
switch (error)
{
STR_CASE(SCE_NP_OAUTH_ERROR_UNKNOWN);
STR_CASE(SCE_NP_OAUTH_ERROR_ALREADY_INITIALIZED);
STR_CASE(SCE_NP_OAUTH_ERROR_NOT_INITIALIZED);
STR_CASE(SCE_NP_OAUTH_ERROR_INVALID_ARGUMENT);
STR_CASE(SCE_NP_OAUTH_ERROR_OUT_OF_MEMORY);
STR_CASE(SCE_NP_OAUTH_ERROR_OUT_OF_BUFFER);
STR_CASE(SCE_NP_OAUTH_ERROR_BAD_RESPONSE);
STR_CASE(SCE_NP_OAUTH_ERROR_ABORTED);
STR_CASE(SCE_NP_OAUTH_ERROR_SIGNED_OUT);
STR_CASE(SCE_NP_OAUTH_ERROR_REQUEST_NOT_FOUND);
STR_CASE(SCE_NP_OAUTH_ERROR_SSL_ERR_CN_CHECK);
STR_CASE(SCE_NP_OAUTH_ERROR_SSL_ERR_UNKNOWN_CA);
STR_CASE(SCE_NP_OAUTH_ERROR_SSL_ERR_NOT_AFTER_CHECK);
STR_CASE(SCE_NP_OAUTH_ERROR_SSL_ERR_NOT_BEFORE_CHECK);
STR_CASE(SCE_NP_OAUTH_ERROR_SSL_ERR_INVALID_CERT);
STR_CASE(SCE_NP_OAUTH_ERROR_SSL_ERR_INTERNAL);
STR_CASE(SCE_NP_OAUTH_ERROR_REQUEST_MAX);
STR_CASE(SCE_NP_OAUTH_SERVER_ERROR_BANNED_CONSOLE);
STR_CASE(SCE_NP_OAUTH_SERVER_ERROR_INVALID_LOGIN);
STR_CASE(SCE_NP_OAUTH_SERVER_ERROR_INACTIVE_ACCOUNT);
STR_CASE(SCE_NP_OAUTH_SERVER_ERROR_SUSPENDED_ACCOUNT);
STR_CASE(SCE_NP_OAUTH_SERVER_ERROR_SUSPENDED_DEVICE);
STR_CASE(SCE_NP_OAUTH_SERVER_ERROR_PASSWORD_EXPIRED);
STR_CASE(SCE_NP_OAUTH_SERVER_ERROR_TOSUA_MUST_BE_RE_ACCEPTED);
STR_CASE(SCE_NP_OAUTH_SERVER_ERROR_TOSUA_MUST_BE_RE_ACCEPTED_FOR_SUBACCOUNT);
STR_CASE(SCE_NP_OAUTH_SERVER_ERROR_BANNED_ACCOUNT);
STR_CASE(SCE_NP_OAUTH_SERVER_ERROR_SERVICE_END);
STR_CASE(SCE_NP_OAUTH_SERVER_ERROR_SERVICE_UNAVAILABLE);
}
return unknown;
});
}
error_code sceNpMatching2Init2(u64 stackSize, s32 priority, vm::ptr<SceNpMatching2UtilityInitParam> param);
error_code sceNpMatching2Term(ppu_thread& ppu);
error_code sceNpMatching2Term2();
error_code generic_match2_error_check(const named_thread<np::np_handler>& nph, SceNpMatching2ContextId ctxId, vm::cptr<void> reqParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
if (!reqParam || !assignedReqId)
{
return SCE_NP_MATCHING2_ERROR_INVALID_ARGUMENT;
}
if (!ctxId)
{
return SCE_NP_MATCHING2_ERROR_INVALID_CONTEXT_ID;
}
if (!check_match2_context(ctxId))
{
return SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_FOUND;
}
return CELL_OK;
}
error_code sceNp2Init(u32 poolsize, vm::ptr<void> poolptr)
{
sceNp2.warning("sceNp2Init(poolsize=0x%x, poolptr=*0x%x)", poolsize, poolptr);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
{
std::lock_guard lock(nph.mutex_status);
if (nph.is_NP2_init)
{
return SCE_NP_ERROR_ALREADY_INITIALIZED;
}
}
const u32 result = std::bit_cast<u32>(sceNpInit(poolsize, poolptr));
if (result && result != SCE_NP_ERROR_ALREADY_INITIALIZED)
{
return result;
}
nph.is_NP2_init = true;
return CELL_OK;
}
error_code sceNpMatching2Init(u32 stackSize, s32 priority)
{
sceNp2.todo("sceNpMatching2Init(stackSize=0x%x, priority=%d)", stackSize, priority);
return sceNpMatching2Init2(stackSize, priority, vm::null); // > SDK 2.4.0
}
error_code sceNpMatching2Init2(u64 stackSize, s32 priority, vm::ptr<SceNpMatching2UtilityInitParam> param)
{
sceNp2.todo("sceNpMatching2Init2(stackSize=0x%x, priority=%d, param=*0x%x)", stackSize, priority, param);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_init)
{
return SCE_NP_ERROR_NOT_INITIALIZED;
}
if (nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_ALREADY_INITIALIZED;
}
// TODO:
// 1. Create an internal thread
// 2. Create heap area to be used by the NP matching 2 utility
// 3. Set maximum lengths for the event data queues in the system
nph.is_NP2_Match2_init = true;
return CELL_OK;
}
error_code sceNp2Term(ppu_thread& ppu)
{
sceNp2.warning("sceNp2Term()");
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
{
std::lock_guard lock(nph.mutex_status);
if (!nph.is_NP2_init)
{
return SCE_NP_ERROR_NOT_INITIALIZED;
}
}
// TODO: does this return on error_code ?
sceNpMatching2Term(ppu);
// cellSysutilUnregisterCallbackDispatcher();
sceNpTerm();
nph.is_NP2_init = false;
return CELL_OK;
}
error_code sceNpMatching2Term(ppu_thread&)
{
sceNp2.warning("sceNpMatching2Term()");
return sceNpMatching2Term2(); // > SDK 2.4.0
}
error_code sceNpMatching2Term2()
{
sceNp2.warning("sceNpMatching2Term2()");
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
{
std::lock_guard lock(nph.mutex_status);
if (!nph.is_NP2_init)
{
return SCE_NP_ERROR_NOT_INITIALIZED;
}
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
nph.is_NP2_Match2_init = false;
}
// TODO: for all contexts: sceNpMatching2DestroyContext
return CELL_OK;
}
error_code sceNpMatching2DestroyContext(SceNpMatching2ContextId ctxId)
{
sceNp2.todo("sceNpMatching2DestroyContext(ctxId=%d)", ctxId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
if (!destroy_match2_context(ctxId))
return SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_FOUND;
return CELL_OK;
}
error_code sceNpMatching2LeaveLobby(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2LeaveLobbyRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.todo("sceNpMatching2LeaveLobby(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
return CELL_OK;
}
error_code sceNpMatching2RegisterLobbyMessageCallback(SceNpMatching2ContextId ctxId, vm::ptr<SceNpMatching2LobbyMessageCallback> cbFunc, vm::ptr<void> cbFuncArg)
{
sceNp2.todo("sceNpMatching2RegisterLobbyMessageCallback(ctxId=%d, cbFunc=*0x%x, cbFuncArg=*0x%x)", ctxId, cbFunc, cbFuncArg);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
return CELL_OK;
}
error_code sceNpMatching2GetWorldInfoList(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2GetWorldInfoListRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.warning("sceNpMatching2GetWorldInfoList(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
if (reqParam->serverId == 0)
{
return SCE_NP_MATCHING2_ERROR_INVALID_SERVER_ID;
}
*assignedReqId = nph.get_world_list(ctxId, optParam, reqParam->serverId);
return CELL_OK;
}
error_code sceNpMatching2RegisterLobbyEventCallback(SceNpMatching2ContextId ctxId, vm::ptr<SceNpMatching2LobbyEventCallback> cbFunc, vm::ptr<void> cbFuncArg)
{
sceNp2.todo("sceNpMatching2RegisterLobbyEventCallback(ctxId=%d, cbFunc=*0x%x, cbFuncArg=*0x%x)", ctxId, cbFunc, cbFuncArg);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
return CELL_OK;
}
error_code sceNpMatching2GetLobbyMemberDataInternalList(SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2GetLobbyMemberDataInternalListRequest> reqParam,
vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.todo("sceNpMatching2GetLobbyMemberDataInternalList(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
return CELL_OK;
}
error_code sceNpMatching2SearchRoom(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2SearchRoomRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.warning("sceNpMatching2SearchRoom(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
*assignedReqId = nph.search_room(ctxId, optParam, reqParam.get_ptr());
return CELL_OK;
}
error_code sceNpMatching2SignalingGetConnectionStatus(
SceNpMatching2ContextId ctxId, SceNpMatching2RoomId roomId, SceNpMatching2RoomMemberId memberId, vm::ptr<int> connStatus, vm::ptr<np_in_addr> peerAddr, vm::ptr<np_in_port_t> peerPort)
{
sceNp2.warning("sceNpMatching2SignalingGetConnectionStatus(ctxId=%d, roomId=%d, memberId=%d, connStatus=*0x%x, peerAddr=*0x%x, peerPort=*0x%x)", ctxId, roomId, memberId, connStatus, peerAddr, peerPort);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
if (!connStatus)
{
return SCE_NP_MATCHING2_ERROR_INVALID_ARGUMENT;
}
auto& sigh = g_fxo->get<named_thread<signaling_handler>>();
const auto si = sigh.get_sig2_infos(roomId, memberId);
*connStatus = si.connStatus;
if (peerAddr)
{
(*peerAddr).np_s_addr = si.addr; // infos.addr is already BE
}
if (peerPort)
{
*peerPort = si.port;
}
return CELL_OK;
}
error_code sceNpMatching2SetUserInfo(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2SetUserInfoRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.todo("sceNpMatching2SetUserInfo(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
return CELL_OK;
}
error_code sceNpMatching2GetClanLobbyId(SceNpMatching2ContextId ctxId, SceNpClanId clanId, vm::ptr<SceNpMatching2LobbyId> lobbyId)
{
sceNp2.todo("sceNpMatching2GetClanLobbyId(ctxId=%d, clanId=%d, lobbyId=*0x%x)", ctxId, clanId, lobbyId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
return CELL_OK;
}
error_code sceNpMatching2GetLobbyMemberDataInternal(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2GetLobbyMemberDataInternalRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.todo("sceNpMatching2GetLobbyMemberDataInternal(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
return CELL_OK;
}
error_code sceNpMatching2ContextStart(SceNpMatching2ContextId ctxId)
{
sceNp2.warning("sceNpMatching2ContextStart(ctxId=%d)", ctxId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
const auto ctx = get_match2_context(ctxId);
if (!ctx)
return SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_FOUND;
if (ctx->context_callback)
{
sysutil_register_cb([=](ppu_thread& cb_ppu) -> s32
{
ctx->context_callback(cb_ppu, ctxId, SCE_NP_MATCHING2_CONTEXT_EVENT_Start, SCE_NP_MATCHING2_EVENT_CAUSE_CONTEXT_ACTION, 0, ctx->context_callback_param);
return 0;
});
}
return CELL_OK;
}
error_code sceNpMatching2CreateServerContext(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2CreateServerContextRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.warning("sceNpMatching2CreateServerContext(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
if (reqParam->serverId == 0)
{
return SCE_NP_MATCHING2_ERROR_INVALID_SERVER_ID;
}
*assignedReqId = nph.create_server_context(ctxId, optParam, reqParam->serverId);
return CELL_OK;
}
error_code sceNpMatching2GetMemoryInfo(vm::ptr<SceNpMatching2MemoryInfo> memInfo) // TODO
{
sceNp2.todo("sceNpMatching2GetMemoryInfo(memInfo=*0x%x)", memInfo);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
return CELL_OK;
}
error_code sceNpMatching2LeaveRoom(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2LeaveRoomRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.warning("sceNpMatching2LeaveRoom(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
*assignedReqId = nph.leave_room(ctxId, optParam, reqParam.get_ptr());
return CELL_OK;
}
error_code sceNpMatching2SetRoomDataExternal(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2SetRoomDataExternalRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.warning("sceNpMatching2SetRoomDataExternal(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
*assignedReqId = nph.set_roomdata_external(ctxId, optParam, reqParam.get_ptr());
return CELL_OK;
}
error_code sceNpMatching2SignalingGetConnectionInfo(
SceNpMatching2ContextId ctxId, SceNpMatching2RoomId roomId, SceNpMatching2RoomMemberId memberId, s32 code, vm::ptr<SceNpSignalingConnectionInfo> connInfo)
{
sceNp2.warning("sceNpMatching2SignalingGetConnectionInfo(ctxId=%d, roomId=%d, memberId=%d, code=%d, connInfo=*0x%x)", ctxId, roomId, memberId, code, connInfo);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
switch (code)
{
case SCE_NP_SIGNALING_CONN_INFO_RTT:
{
connInfo->rtt = 20000; // HACK
break;
}
case SCE_NP_SIGNALING_CONN_INFO_BANDWIDTH:
{
connInfo->bandwidth = 10'000'000; // 10 MBPS HACK
break;
}
case SCE_NP_SIGNALING_CONN_INFO_PEER_NPID:
{
// TODO: need an update to whole signaling as matching2 signaling ignores npids atm
sceNp2.fatal("sceNpMatching2SignalingGetConnectionInfo Unimplemented SCE_NP_SIGNALING_CONN_INFO_PEER_NPID");
break;
}
case SCE_NP_SIGNALING_CONN_INFO_PEER_ADDRESS:
{
auto& sigh = g_fxo->get<named_thread<signaling_handler>>();
const auto si = sigh.get_sig2_infos(roomId, memberId);
connInfo->address.port = std::bit_cast<u16, be_t<u16>>(si.port);
connInfo->address.addr.np_s_addr = si.addr;
break;
}
case SCE_NP_SIGNALING_CONN_INFO_MAPPED_ADDRESS:
{
auto& sigh = g_fxo->get<named_thread<signaling_handler>>();
const auto si = sigh.get_sig2_infos(roomId, memberId);
connInfo->address.port = std::bit_cast<u16, be_t<u16>>(si.mapped_port);
connInfo->address.addr.np_s_addr = si.mapped_addr;
break;
}
case SCE_NP_SIGNALING_CONN_INFO_PACKET_LOSS:
{
connInfo->packet_loss = 1; // HACK
break;
}
default:
{
sceNp2.fatal("sceNpMatching2SignalingGetConnectionInfo Unimplemented code: %d", code);
return CELL_OK;
}
}
return CELL_OK;
}
error_code sceNpMatching2SendRoomMessage(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2SendRoomMessageRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.warning("sceNpMatching2SendRoomMessage(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
*assignedReqId = nph.send_room_message(ctxId, optParam, reqParam.get_ptr());
return CELL_OK;
}
error_code sceNpMatching2JoinLobby(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2JoinLobbyRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.todo("sceNpMatching2JoinLobby(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
return CELL_OK;
}
error_code sceNpMatching2GetRoomMemberDataExternalList(SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2GetRoomMemberDataExternalListRequest> reqParam,
vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.todo("sceNpMatching2GetRoomMemberDataExternalList(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
return CELL_OK;
}
error_code sceNpMatching2AbortRequest(SceNpMatching2ContextId ctxId, SceNpMatching2RequestId reqId)
{
sceNp2.todo("sceNpMatching2AbortRequest(ctxId=%d, reqId=%d)", ctxId, reqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
return CELL_OK;
}
error_code sceNpMatching2GetServerInfo(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2GetServerInfoRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.warning("sceNpMatching2GetServerInfo(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
*assignedReqId = nph.get_server_status(ctxId, optParam, reqParam->serverId);
return CELL_OK;
}
error_code sceNpMatching2GetEventData(SceNpMatching2ContextId ctxId, SceNpMatching2EventKey eventKey, vm::ptr<void> buf, u64 bufLen)
{
sceNp2.notice("sceNpMatching2GetEventData(ctxId=%d, eventKey=%d, buf=*0x%x, bufLen=%d)", ctxId, eventKey, buf, bufLen);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
if (!buf)
{
return SCE_NP_MATCHING2_ERROR_INVALID_ARGUMENT;
}
return not_an_error(nph.get_match2_event(eventKey, buf.addr(), bufLen));
}
error_code sceNpMatching2GetRoomSlotInfoLocal(SceNpMatching2ContextId ctxId, const SceNpMatching2RoomId roomId, vm::ptr<SceNpMatching2RoomSlotInfo> roomSlotInfo)
{
sceNp2.notice("sceNpMatching2GetRoomSlotInfoLocal(ctxId=%d, roomId=%d, roomSlotInfo=*0x%x)", ctxId, roomId, roomSlotInfo);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
if (!ctxId)
{
return SCE_NP_MATCHING2_ERROR_INVALID_CONTEXT_ID;
}
if (!roomId)
{
return SCE_NP_MATCHING2_ERROR_INVALID_ROOM_ID;
}
if (!check_match2_context(ctxId))
{
return SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_FOUND;
}
const auto [error, slots] = nph.local_get_room_slots(roomId);
if (error)
{
return error;
}
memcpy(roomSlotInfo.get_ptr(), &slots.value(), sizeof(SceNpMatching2RoomSlotInfo));
return CELL_OK;
}
error_code sceNpMatching2SendLobbyChatMessage(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2SendLobbyChatMessageRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.todo("sceNpMatching2SendLobbyChatMessage(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
return CELL_OK;
}
error_code sceNpMatching2AbortContextStart(SceNpMatching2ContextId ctxId)
{
sceNp2.todo("sceNpMatching2AbortContextStart(ctxId=%d)", ctxId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
return CELL_OK;
}
error_code sceNpMatching2GetRoomMemberIdListLocal(SceNpMatching2ContextId ctxId, SceNpMatching2RoomId roomId, s32 sortMethod, vm::ptr<SceNpMatching2RoomMemberId> memberId, u32 memberIdNum)
{
sceNp2.notice("sceNpMatching2GetRoomMemberIdListLocal(ctxId=%d, roomId=%d, sortMethod=%d, memberId=*0x%x, memberIdNum=%d)", ctxId, roomId, sortMethod, memberId, memberIdNum);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
if (!ctxId)
{
return SCE_NP_MATCHING2_ERROR_INVALID_CONTEXT_ID;
}
if (!roomId)
{
return SCE_NP_MATCHING2_ERROR_INVALID_ROOM_ID;
}
if (sortMethod != SCE_NP_MATCHING2_SORT_METHOD_JOIN_DATE && sortMethod != SCE_NP_MATCHING2_SORT_METHOD_SLOT_NUMBER)
{
return SCE_NP_MATCHING2_ERROR_INVALID_SORT_METHOD;
}
if (!check_match2_context(ctxId))
{
return SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_FOUND;
}
const auto [error, vec_memberids] = nph.local_get_room_memberids(roomId, sortMethod);
if (error)
{
return error;
}
u32 num_members = std::min(memberIdNum, static_cast<u32>(vec_memberids.size()));
for (u32 i = 0; i < num_members; i++)
{
memberId[i] = vec_memberids[i];
}
return not_an_error(num_members);
}
error_code sceNpMatching2JoinRoom(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2JoinRoomRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.warning("sceNpMatching2JoinRoom(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
*assignedReqId = nph.join_room(ctxId, optParam, reqParam.get_ptr());
return CELL_OK;
}
error_code sceNpMatching2GetRoomMemberDataInternalLocal(SceNpMatching2ContextId ctxId, SceNpMatching2RoomId roomId, SceNpMatching2RoomMemberId memberId, vm::cptr<SceNpMatching2AttributeId> attrId,
u32 attrIdNum, vm::ptr<SceNpMatching2RoomMemberDataInternal> member, vm::ptr<char> buf, u64 bufLen)
{
sceNp2.warning("sceNpMatching2GetRoomMemberDataInternalLocal(ctxId=%d, roomId=%d, memberId=%d, attrId=*0x%x, attrIdNum=%d, member=*0x%x, buf=*0x%x, bufLen=%d)", ctxId, roomId, memberId, attrId,
attrIdNum, member, buf, bufLen);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
if (!ctxId)
{
return SCE_NP_MATCHING2_ERROR_INVALID_CONTEXT_ID;
}
if (!roomId)
{
return SCE_NP_MATCHING2_ERROR_INVALID_ROOM_ID;
}
if (!memberId)
{
return SCE_NP_MATCHING2_ERROR_INVALID_MEMBER_ID;
}
std::vector<SceNpMatching2AttributeId> binattrs_list;
for (u32 i = 0; i < attrIdNum; i++)
{
if (attrId[i] < SCE_NP_MATCHING2_ROOMMEMBER_BIN_ATTR_INTERNAL_1_ID || attrId[i] >= SCE_NP_MATCHING2_USER_BIN_ATTR_1_ID)
{
return SCE_NP_MATCHING2_ERROR_INVALID_ATTRIBUTE_ID;
}
binattrs_list.push_back(attrId[i]);
}
if (!check_match2_context(ctxId))
{
return SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_FOUND;
}
return nph.local_get_room_member_data(roomId, memberId, binattrs_list, member ? member.get_ptr() : nullptr, buf.addr(), bufLen);
}
error_code sceNpMatching2GetCbQueueInfo(SceNpMatching2ContextId ctxId, vm::ptr<SceNpMatching2CbQueueInfo> queueInfo)
{
sceNp2.todo("sceNpMatching2GetCbQueueInfo(ctxId=%d, queueInfo=*0x%x)", ctxId, queueInfo);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
return CELL_OK;
}
error_code sceNpMatching2KickoutRoomMember(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2KickoutRoomMemberRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.todo("sceNpMatching2KickoutRoomMember(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
return CELL_OK;
}
error_code sceNpMatching2ContextStartAsync(SceNpMatching2ContextId ctxId, u32 timeout)
{
sceNp2.warning("sceNpMatching2ContextStartAsync(ctxId=%d, timeout=%d)", ctxId, timeout);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
if (!ctxId)
{
return SCE_NP_MATCHING2_ERROR_INVALID_CONTEXT_ID;
}
const auto ctx = get_match2_context(ctxId);
if (!ctx)
return SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_FOUND;
if (ctx->context_callback)
{
sysutil_register_cb([=](ppu_thread& cb_ppu) -> s32
{
ctx->context_callback(cb_ppu, ctxId, SCE_NP_MATCHING2_CONTEXT_EVENT_Start, SCE_NP_MATCHING2_EVENT_CAUSE_CONTEXT_ACTION, 0, ctx->context_callback_param);
return 0;
});
}
return CELL_OK;
}
error_code sceNpMatching2SetSignalingOptParam(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2SetSignalingOptParamRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.todo("sceNpMatching2SetSignalingOptParam(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
return CELL_OK;
}
error_code sceNpMatching2RegisterContextCallback(SceNpMatching2ContextId ctxId, vm::ptr<SceNpMatching2ContextCallback> cbFunc, vm::ptr<void> cbFuncArg)
{
sceNp2.warning("sceNpMatching2RegisterContextCallback(ctxId=%d, cbFunc=*0x%x, cbFuncArg=*0x%x)", ctxId, cbFunc, cbFuncArg);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
if (!ctxId)
{
return SCE_NP_MATCHING2_ERROR_INVALID_CONTEXT_ID;
}
const auto ctx = get_match2_context(ctxId);
if (!ctx)
return SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_FOUND;
ctx->context_callback = cbFunc;
ctx->context_callback_param = cbFuncArg;
return CELL_OK;
}
error_code sceNpMatching2SendRoomChatMessage(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2SendRoomChatMessageRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.todo("sceNpMatching2SendRoomChatMessage(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
return CELL_OK;
}
error_code sceNpMatching2SetRoomDataInternal(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2SetRoomDataInternalRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.warning("sceNpMatching2SetRoomDataInternal(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
*assignedReqId = nph.set_roomdata_internal(ctxId, optParam, reqParam.get_ptr());
return CELL_OK;
}
error_code sceNpMatching2GetRoomDataInternal(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2GetRoomDataInternalRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.warning("sceNpMatching2GetRoomDataInternal(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
*assignedReqId = nph.get_roomdata_internal(ctxId, optParam, reqParam.get_ptr());
return CELL_OK;
}
error_code sceNpMatching2SignalingGetPingInfo(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2SignalingGetPingInfoRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.warning("sceNpMatching2SignalingGetPingInfo(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
*assignedReqId = nph.get_ping_info(ctxId, optParam, reqParam.get_ptr());
return CELL_OK;
}
error_code sceNpMatching2GetServerIdListLocal(SceNpMatching2ContextId ctxId, vm::ptr<SceNpMatching2ServerId> serverId, u32 serverIdNum)
{
sceNp2.notice("sceNpMatching2GetServerIdListLocal(ctxId=%d, serverId=*0x%x, serverIdNum=%d)", ctxId, serverId, serverIdNum);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
if (!check_match2_context(ctxId))
{
return SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_FOUND;
}
const auto slist = nph.get_match2_server_list(ctxId);
u32 num_servs = std::min(static_cast<u32>(slist.size()), serverIdNum);
if (serverId)
{
for (u32 i = 0; i < num_servs; i++)
{
serverId[i] = slist[i];
}
}
return not_an_error(static_cast<s32>(slist.size()));
}
error_code sceNpUtilBuildCdnUrl(vm::cptr<char> url, vm::ptr<char> buf, u64 bufSize, vm::ptr<u64> required, vm::ptr<void> option)
{
sceNp2.todo("sceNpUtilBuildCdnUrl(url=%s, buf=*0x%x, bufSize=%d, required=*0x%x, option=*0x%x)", url, buf, bufSize, required, option);
if (!url || option) // option check at least until fw 4.71
{
// TODO: check url for '?'
return SCE_NP_UTIL_ERROR_INVALID_ARGUMENT;
}
// if (offline)
//{
// return SCE_NP_ERROR_OFFLINE;
//}
return CELL_OK;
}
error_code sceNpMatching2GrantRoomOwner(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2GrantRoomOwnerRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.todo("sceNpMatching2GrantRoomOwner(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
return CELL_OK;
}
error_code sceNpMatching2CreateContext(
vm::cptr<SceNpId> npId, vm::cptr<SceNpCommunicationId> commId, vm::cptr<SceNpCommunicationPassphrase> passPhrase, vm::ptr<SceNpMatching2ContextId> ctxId, s32 option)
{
sceNp2.warning("sceNpMatching2CreateContext(npId=*0x%x, commId=*0x%x(%s), passPhrase=*0x%x, ctxId=*0x%x, option=%d)", npId, commId, commId ? commId->data : "", ctxId, option);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
if (!npId || !commId || !passPhrase || !ctxId)
{
return SCE_NP_MATCHING2_ERROR_INVALID_ARGUMENT;
}
*ctxId = create_match2_context(commId, passPhrase);
return CELL_OK;
}
error_code sceNpMatching2GetSignalingOptParamLocal(SceNpMatching2ContextId ctxId, SceNpMatching2RoomId roomId, vm::ptr<SceNpMatching2SignalingOptParam> signalingOptParam)
{
sceNp2.todo("sceNpMatching2GetSignalingOptParamLocal(ctxId=%d, roomId=%d, signalingOptParam=*0x%x)", ctxId, roomId, signalingOptParam);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
return CELL_OK;
}
error_code sceNpMatching2RegisterSignalingCallback(SceNpMatching2ContextId ctxId, vm::ptr<SceNpMatching2SignalingCallback> cbFunc, vm::ptr<void> cbFuncArg)
{
sceNp2.notice("sceNpMatching2RegisterSignalingCallback(ctxId=%d, cbFunc=*0x%x, cbFuncArg=*0x%x)", ctxId, cbFunc, cbFuncArg);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
auto& sigh = g_fxo->get<named_thread<signaling_handler>>();
sigh.set_sig2_cb(ctxId, cbFunc, cbFuncArg);
return CELL_OK;
}
error_code sceNpMatching2ClearEventData(SceNpMatching2ContextId ctxId, SceNpMatching2EventKey eventKey)
{
sceNp2.todo("sceNpMatching2ClearEventData(ctxId=%d, eventKey=%d)", ctxId, eventKey);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
return CELL_OK;
}
error_code sceNpMatching2GetUserInfoList(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2GetUserInfoListRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.todo("sceNpMatching2GetUserInfoList(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
return CELL_OK;
}
error_code sceNpMatching2GetRoomMemberDataInternal(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2GetRoomMemberDataInternalRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.todo("sceNpMatching2GetRoomMemberDataInternal(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
return CELL_OK;
}
error_code sceNpMatching2SetRoomMemberDataInternal(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2SetRoomMemberDataInternalRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.warning("sceNpMatching2SetRoomMemberDataInternal(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
*assignedReqId = nph.set_roommemberdata_internal(ctxId, optParam, reqParam.get_ptr());
return CELL_OK;
}
error_code sceNpMatching2JoinProhibitiveRoom(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2JoinProhibitiveRoomRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.warning("sceNpMatching2JoinProhibitiveRoom(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
// TODO: add blocked users
*assignedReqId = nph.join_room(ctxId, optParam, &reqParam->joinParam);
return CELL_OK;
}
error_code sceNpMatching2SignalingSetCtxOpt(SceNpMatching2ContextId ctxId, s32 optname, s32 optval)
{
sceNp2.todo("sceNpMatching2SignalingSetCtxOpt(ctxId=%d, optname=%d, optval=%d)", ctxId, optname, optval);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
return CELL_OK;
}
error_code sceNpMatching2DeleteServerContext(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2DeleteServerContextRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.warning("sceNpMatching2DeleteServerContext(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
if (reqParam->serverId == 0)
{
return SCE_NP_MATCHING2_ERROR_INVALID_SERVER_ID;
}
*assignedReqId = nph.delete_server_context(ctxId, optParam, reqParam->serverId);
return CELL_OK;
}
error_code sceNpMatching2SetDefaultRequestOptParam(SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2RequestOptParam> optParam)
{
sceNp2.warning("sceNpMatching2SetDefaultRequestOptParam(ctxId=%d, optParam=*0x%x)", ctxId, optParam);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
if (!optParam)
{
return SCE_NP_MATCHING2_ERROR_INVALID_ARGUMENT;
}
const auto ctx = get_match2_context(ctxId);
if (!ctx)
return SCE_NP_MATCHING2_ERROR_INVALID_CONTEXT_ID;
memcpy(&ctx->default_match2_optparam, optParam.get_ptr(), sizeof(SceNpMatching2RequestOptParam));
return CELL_OK;
}
error_code sceNpMatching2RegisterRoomEventCallback(SceNpMatching2ContextId ctxId, vm::ptr<SceNpMatching2RoomEventCallback> cbFunc, vm::ptr<void> cbFuncArg)
{
sceNp2.todo("sceNpMatching2RegisterRoomEventCallback(ctxId=%d, cbFunc=*0x%x, cbFuncArg=*0x%x)", ctxId, cbFunc, cbFuncArg);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
nph.room_event_cb = cbFunc;
nph.room_event_cb_ctx = ctxId;
nph.room_event_cb_arg = cbFuncArg;
return CELL_OK;
}
error_code sceNpMatching2GetRoomPasswordLocal(SceNpMatching2ContextId ctxId, SceNpMatching2RoomId roomId, vm::ptr<b8> withPassword, vm::ptr<SceNpMatching2SessionPassword> roomPassword)
{
sceNp2.notice("sceNpMatching2GetRoomPasswordLocal(ctxId=%d, roomId=%d, withPassword=*0x%x, roomPassword=*0x%x)", ctxId, roomId, withPassword, roomPassword);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
if (!ctxId)
{
return SCE_NP_MATCHING2_ERROR_INVALID_CONTEXT_ID;
}
if (!roomId)
{
return SCE_NP_MATCHING2_ERROR_INVALID_ROOM_ID;
}
if (!check_match2_context(ctxId))
{
return SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_FOUND;
}
const auto [error, password] = nph.local_get_room_password(roomId);
if (error)
{
return error;
}
if (password)
{
*withPassword = true;
memcpy(roomPassword.get_ptr(), &*password, sizeof(SceNpMatching2SessionPassword));
}
else
{
*withPassword = false;
}
return CELL_OK;
}
error_code sceNpMatching2GetRoomDataExternalList(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2GetRoomDataExternalListRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.warning("sceNpMatching2GetRoomDataExternalList(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
*assignedReqId = nph.get_roomdata_external_list(ctxId, optParam, reqParam.get_ptr());
return CELL_OK;
}
error_code sceNpMatching2CreateJoinRoom(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2CreateJoinRoomRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.warning("sceNpMatching2CreateJoinRoom(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
*assignedReqId = nph.create_join_room(ctxId, optParam, reqParam.get_ptr());
return CELL_OK;
}
error_code sceNpMatching2SignalingGetCtxOpt(SceNpMatching2ContextId ctxId, s32 optname, vm::ptr<s32> optval)
{
sceNp2.todo("sceNpMatching2SignalingGetCtxOpt(ctxId=%d, optname=%d, optval=*0x%x)", ctxId, optname, optval);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
return CELL_OK;
}
error_code sceNpMatching2GetLobbyInfoList(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2GetLobbyInfoListRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.todo("sceNpMatching2GetLobbyInfoList(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
return CELL_OK;
}
error_code sceNpMatching2GetLobbyMemberIdListLocal(
SceNpMatching2ContextId ctxId, SceNpMatching2LobbyId lobbyId, vm::ptr<SceNpMatching2LobbyMemberId> memberId, u32 memberIdNum, vm::ptr<SceNpMatching2LobbyMemberId> me)
{
sceNp2.todo("sceNpMatching2GetLobbyMemberIdListLocal(ctxId=%d, lobbyId=%d, memberId=*0x%x, memberIdNum=%d, me=*0x%x)", ctxId, lobbyId, memberId, memberIdNum, me);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
return CELL_OK;
}
error_code sceNpMatching2SendLobbyInvitation(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2SendLobbyInvitationRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.todo("sceNpMatching2SendLobbyInvitation(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
return CELL_OK;
}
error_code sceNpMatching2ContextStop(SceNpMatching2ContextId ctxId)
{
sceNp2.todo("sceNpMatching2ContextStop(ctxId=%d)", ctxId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
const auto ctx = get_match2_context(ctxId);
if (!ctx)
{
return SCE_NP_MATCHING2_ERROR_INVALID_CONTEXT_ID;
}
if (ctx->context_callback)
{
sysutil_register_cb([=](ppu_thread& cb_ppu) -> s32
{
ctx->context_callback(cb_ppu, ctxId, SCE_NP_MATCHING2_CONTEXT_EVENT_Stop, SCE_NP_MATCHING2_EVENT_CAUSE_CONTEXT_ACTION, 0, ctx->context_callback_param);
return 0;
});
}
return CELL_OK;
}
error_code sceNpMatching2SetLobbyMemberDataInternal(
SceNpMatching2ContextId ctxId, vm::cptr<SceNpMatching2SetLobbyMemberDataInternalRequest> reqParam, vm::cptr<SceNpMatching2RequestOptParam> optParam, vm::ptr<SceNpMatching2RequestId> assignedReqId)
{
sceNp2.todo("sceNpMatching2SetLobbyMemberDataInternal(ctxId=%d, reqParam=*0x%x, optParam=*0x%x, assignedReqId=*0x%x)", ctxId, reqParam, optParam, assignedReqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (auto res = generic_match2_error_check(nph, ctxId, reqParam, assignedReqId); res != CELL_OK)
{
return res;
}
return CELL_OK;
}
error_code sceNpMatching2RegisterRoomMessageCallback(SceNpMatching2ContextId ctxId, vm::ptr<SceNpMatching2RoomMessageCallback> cbFunc, vm::ptr<void> cbFuncArg)
{
sceNp2.todo("sceNpMatching2RegisterRoomMessageCallback(ctxId=%d, cbFunc=*0x%x, cbFuncArg=*0x%x)", ctxId, cbFunc, cbFuncArg);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
nph.room_msg_cb = cbFunc;
nph.room_msg_cb_ctx = ctxId;
nph.room_msg_cb_arg = cbFuncArg;
return CELL_OK;
}
error_code sceNpMatching2SignalingCancelPeerNetInfo(SceNpMatching2ContextId ctxId, SceNpMatching2SignalingRequestId reqId)
{
sceNp2.todo("sceNpMatching2SignalingCancelPeerNetInfo(ctxId=%d, reqId=%d)", ctxId, reqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
return CELL_OK;
}
error_code sceNpMatching2SignalingGetLocalNetInfo(vm::ptr<SceNpMatching2SignalingNetInfo> netinfo)
{
sceNp2.todo("sceNpMatching2SignalingGetLocalNetInfo(netinfo=*0x%x)", netinfo);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
if (!netinfo)
{
// TODO: check netinfo->size
return SCE_NP_MATCHING2_ERROR_INVALID_ARGUMENT;
}
return CELL_OK;
}
error_code sceNpMatching2SignalingGetPeerNetInfo(SceNpMatching2ContextId ctxId, SceNpMatching2RoomId roomId, SceNpMatching2RoomMemberId roomMemberId, vm::ptr<SceNpMatching2SignalingRequestId> reqId)
{
sceNp2.todo("sceNpMatching2SignalingGetPeerNetInfo(ctxId=%d, roomId=%d, roomMemberId=%d, reqId=*0x%x)", ctxId, roomId, roomMemberId, reqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
if (!reqId)
{
return SCE_NP_MATCHING2_ERROR_INVALID_ARGUMENT;
}
return CELL_OK;
}
error_code sceNpMatching2SignalingGetPeerNetInfoResult(SceNpMatching2ContextId ctxId, SceNpMatching2SignalingRequestId reqId, vm::ptr<SceNpMatching2SignalingNetInfo> netinfo)
{
sceNp2.todo("sceNpMatching2SignalingGetPeerNetInfoResult(ctxId=%d, reqId=%d, netinfo=*0x%x)", ctxId, reqId, netinfo);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP2_Match2_init)
{
return SCE_NP_MATCHING2_ERROR_NOT_INITIALIZED;
}
if (!netinfo)
{
// TODO: check netinfo->size
return SCE_NP_MATCHING2_ERROR_INVALID_ARGUMENT;
}
return CELL_OK;
}
error_code sceNpAuthOAuthInit()
{
sceNp2.todo("sceNpAuthOAuthInit()");
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (nph.is_NP_Auth_init)
{
return SCE_NP_OAUTH_ERROR_ALREADY_INITIALIZED;
}
nph.is_NP_Auth_init = true;
return CELL_OK;
}
error_code sceNpAuthOAuthTerm()
{
sceNp2.todo("sceNpAuthOAuthTerm()");
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
// TODO: check if this might throw SCE_NP_OAUTH_ERROR_NOT_INITIALIZED
nph.is_NP_Auth_init = false;
return CELL_OK;
}
error_code sceNpAuthCreateOAuthRequest()
{
sceNp2.todo("sceNpAuthCreateOAuthRequest()");
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP_Auth_init)
{
return SCE_NP_OAUTH_ERROR_NOT_INITIALIZED;
}
return CELL_OK;
}
error_code sceNpAuthDeleteOAuthRequest(SceNpAuthOAuthRequestId reqId)
{
sceNp2.todo("sceNpAuthDeleteOAuthRequest(reqId=%d)", reqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP_Auth_init)
{
return SCE_NP_OAUTH_ERROR_NOT_INITIALIZED;
}
return CELL_OK;
}
error_code sceNpAuthAbortOAuthRequest(SceNpAuthOAuthRequestId reqId)
{
sceNp2.todo("sceNpAuthAbortOAuthRequest(reqId=%d)", reqId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP_Auth_init)
{
return SCE_NP_OAUTH_ERROR_NOT_INITIALIZED;
}
return CELL_OK;
}
error_code sceNpAuthGetAuthorizationCode(SceNpAuthOAuthRequestId reqId, vm::cptr<SceNpAuthGetAuthorizationCodeParameter> param, vm::ptr<SceNpAuthorizationCode> authCode, vm::ptr<s32> issuerId)
{
sceNp2.todo("sceNpAuthGetAuthorizationCode(reqId=%d, param=*0x%x, authCode=*0x%x, issuerId=%d)", reqId, param, authCode, issuerId);
auto& nph = g_fxo->get<named_thread<np::np_handler>>();
if (!nph.is_NP_Auth_init)
{
return SCE_NP_OAUTH_ERROR_NOT_INITIALIZED;
}
return CELL_OK;
}
error_code sceNpAuthGetAuthorizationCode2()
{
UNIMPLEMENTED_FUNC(sceNp2);
return CELL_OK;
}
DECLARE(ppu_module_manager::sceNp2)
("sceNp2", []() {
REG_FUNC(sceNp2, sceNpMatching2DestroyContext);
REG_FUNC(sceNp2, sceNpMatching2LeaveLobby);
REG_FUNC(sceNp2, sceNpMatching2RegisterLobbyMessageCallback);
REG_FUNC(sceNp2, sceNpMatching2GetWorldInfoList);
REG_FUNC(sceNp2, sceNpMatching2RegisterLobbyEventCallback);
REG_FUNC(sceNp2, sceNpMatching2GetLobbyMemberDataInternalList);
REG_FUNC(sceNp2, sceNpMatching2SearchRoom);
REG_FUNC(sceNp2, sceNpMatching2SignalingGetConnectionStatus);
REG_FUNC(sceNp2, sceNpMatching2SetUserInfo);
REG_FUNC(sceNp2, sceNpMatching2GetClanLobbyId);
REG_FUNC(sceNp2, sceNpMatching2GetLobbyMemberDataInternal);
REG_FUNC(sceNp2, sceNpMatching2ContextStart);
REG_FUNC(sceNp2, sceNpMatching2CreateServerContext);
REG_FUNC(sceNp2, sceNpMatching2GetMemoryInfo);
REG_FUNC(sceNp2, sceNpMatching2LeaveRoom);
REG_FUNC(sceNp2, sceNpMatching2SetRoomDataExternal);
REG_FUNC(sceNp2, sceNpMatching2Term2);
REG_FUNC(sceNp2, sceNpMatching2SignalingGetConnectionInfo);
REG_FUNC(sceNp2, sceNpMatching2SendRoomMessage);
REG_FUNC(sceNp2, sceNpMatching2JoinLobby);
REG_FUNC(sceNp2, sceNpMatching2GetRoomMemberDataExternalList);
REG_FUNC(sceNp2, sceNpMatching2AbortRequest);
REG_FUNC(sceNp2, sceNpMatching2Term);
REG_FUNC(sceNp2, sceNpMatching2GetServerInfo);
REG_FUNC(sceNp2, sceNpMatching2GetEventData);
REG_FUNC(sceNp2, sceNpMatching2GetRoomSlotInfoLocal);
REG_FUNC(sceNp2, sceNpMatching2SendLobbyChatMessage);
REG_FUNC(sceNp2, sceNpMatching2Init);
REG_FUNC(sceNp2, sceNp2Init);
REG_FUNC(sceNp2, sceNpMatching2AbortContextStart);
REG_FUNC(sceNp2, sceNpMatching2GetRoomMemberIdListLocal);
REG_FUNC(sceNp2, sceNpMatching2JoinRoom);
REG_FUNC(sceNp2, sceNpMatching2GetRoomMemberDataInternalLocal);
REG_FUNC(sceNp2, sceNpMatching2GetCbQueueInfo);
REG_FUNC(sceNp2, sceNpMatching2KickoutRoomMember);
REG_FUNC(sceNp2, sceNpMatching2ContextStartAsync);
REG_FUNC(sceNp2, sceNpMatching2SetSignalingOptParam);
REG_FUNC(sceNp2, sceNpMatching2RegisterContextCallback);
REG_FUNC(sceNp2, sceNpMatching2SendRoomChatMessage);
REG_FUNC(sceNp2, sceNpMatching2SetRoomDataInternal);
REG_FUNC(sceNp2, sceNpMatching2GetRoomDataInternal);
REG_FUNC(sceNp2, sceNpMatching2SignalingGetPingInfo);
REG_FUNC(sceNp2, sceNpMatching2GetServerIdListLocal);
REG_FUNC(sceNp2, sceNpUtilBuildCdnUrl);
REG_FUNC(sceNp2, sceNpMatching2GrantRoomOwner);
REG_FUNC(sceNp2, sceNpMatching2CreateContext);
REG_FUNC(sceNp2, sceNpMatching2GetSignalingOptParamLocal);
REG_FUNC(sceNp2, sceNpMatching2RegisterSignalingCallback);
REG_FUNC(sceNp2, sceNpMatching2ClearEventData);
REG_FUNC(sceNp2, sceNp2Term);
REG_FUNC(sceNp2, sceNpMatching2GetUserInfoList);
REG_FUNC(sceNp2, sceNpMatching2GetRoomMemberDataInternal);
REG_FUNC(sceNp2, sceNpMatching2SetRoomMemberDataInternal);
REG_FUNC(sceNp2, sceNpMatching2JoinProhibitiveRoom);
REG_FUNC(sceNp2, sceNpMatching2SignalingSetCtxOpt);
REG_FUNC(sceNp2, sceNpMatching2DeleteServerContext);
REG_FUNC(sceNp2, sceNpMatching2SetDefaultRequestOptParam);
REG_FUNC(sceNp2, sceNpMatching2RegisterRoomEventCallback);
REG_FUNC(sceNp2, sceNpMatching2GetRoomPasswordLocal);
REG_FUNC(sceNp2, sceNpMatching2GetRoomDataExternalList);
REG_FUNC(sceNp2, sceNpMatching2CreateJoinRoom);
REG_FUNC(sceNp2, sceNpMatching2SignalingGetCtxOpt);
REG_FUNC(sceNp2, sceNpMatching2GetLobbyInfoList);
REG_FUNC(sceNp2, sceNpMatching2GetLobbyMemberIdListLocal);
REG_FUNC(sceNp2, sceNpMatching2SendLobbyInvitation);
REG_FUNC(sceNp2, sceNpMatching2ContextStop);
REG_FUNC(sceNp2, sceNpMatching2Init2);
REG_FUNC(sceNp2, sceNpMatching2SetLobbyMemberDataInternal);
REG_FUNC(sceNp2, sceNpMatching2RegisterRoomMessageCallback);
REG_FUNC(sceNp2, sceNpMatching2SignalingCancelPeerNetInfo);
REG_FUNC(sceNp2, sceNpMatching2SignalingGetLocalNetInfo);
REG_FUNC(sceNp2, sceNpMatching2SignalingGetPeerNetInfo);
REG_FUNC(sceNp2, sceNpMatching2SignalingGetPeerNetInfoResult);
REG_FUNC(sceNp2, sceNpAuthOAuthInit);
REG_FUNC(sceNp2, sceNpAuthOAuthTerm);
REG_FUNC(sceNp2, sceNpAuthCreateOAuthRequest);
REG_FUNC(sceNp2, sceNpAuthDeleteOAuthRequest);
REG_FUNC(sceNp2, sceNpAuthAbortOAuthRequest);
REG_FUNC(sceNp2, sceNpAuthGetAuthorizationCode);
REG_FUNC(sceNp2, sceNpAuthGetAuthorizationCode2);
});
| RPCS3/rpcs3 | rpcs3/Emu/Cell/Modules/sceNp2.cpp | C++ | gpl-2.0 | 60,635 | 32.574197 | 203 | 0.749897 | false |
<?php
/**
* @version $Id: default.php 15358 2010-03-13 12:31:20Z infograf768 $
* @package Joomla.Site
* @subpackage com_mailto
* @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// no direct access
defined('_JEXEC') or die;
?>
<div style="padding: 10px;">
<div style="text-align:right">
<a href="javascript: void window.close()">
<?php echo JText::_('COM_MAILTO_CLOSE_WINDOW'); ?> <?php echo JHTML::_('image','mailto/close-x.png', NULL, array('border' => 0), true); ?></a>
</div>
<h2>
<?php echo JText::_('COM_MAILTO_EMAIL_SENT'); ?>
</h2>
</div>
| 3den/J-MediaGalleries | components/com_mailto/views/sent/tmpl/default.php | PHP | gpl-2.0 | 681 | 29.954545 | 145 | 0.643172 | false |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* 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 license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Api
* @copyright Copyright (c) 2006-2014 X.commerce, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Wsdl base config
*
* @category Mage
* @package Mage_Api
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_Api_Model_Wsdl_Config_Base extends Varien_Simplexml_Config
{
protected $_handler = '';
/**
* @var Varien_Object
*/
protected $_wsdlVariables = null;
protected $_loadedFiles = array();
public function __construct($sourceData=null)
{
$this->_elementClass = 'Mage_Api_Model_Wsdl_Config_Element';
// remove wsdl parameter from query
$queryParams = Mage::app()->getRequest()->getQuery();
unset($queryParams['wsdl']);
// set up default WSDL template variables
$this->_wsdlVariables = new Varien_Object(
array(
'name' => 'Magento',
'url' => htmlspecialchars(Mage::getUrl('*/*/*', array('_query' => $queryParams)))
)
);
parent::__construct($sourceData);
}
/**
* Set handler
*
* @param string $handler
* @return Mage_Api_Model_Wsdl_Config_Base
*/
public function setHandler($handler)
{
$this->_handler = $handler;
return $this;
}
/**
* Get handler
*
* @return string
*/
public function getHandler()
{
return $this->_handler;
}
/**
* Processing file data
*
* @param string $text
* @return string
*/
public function processFileData($text)
{
/** @var $template Mage_Core_Model_Email_Template_Filter */
$template = Mage::getModel('core/email_template_filter');
$this->_wsdlVariables->setHandler($this->getHandler());
$template->setVariables(array('wsdl'=>$this->_wsdlVariables));
return $template->filter($text);
}
public function addLoadedFile($file)
{
if (!in_array($file, $this->_loadedFiles)) {
$this->_loadedFiles[] = $file;
}
return $this;
}
public function loadFile($file)
{
if (in_array($file, $this->_loadedFiles)) {
return false;
}
$res = parent::loadFile($file);
if ($res) {
$this->addLoadedFile($file);
}
return $this;
}
/**
* Set variable to be used in WSDL template processing
*
* @param string $key Varible key
* @param string $value Variable value
* @return Mage_Api_Model_Wsdl_Config_Base
*/
public function setWsdlVariable($key, $value)
{
$this->_wsdlVariables->setData($key, $value);
return $this;
}
}
| T0MM0R/magento | web/app/code/core/Mage/Api/Model/Wsdl/Config/Base.php | PHP | gpl-2.0 | 3,547 | 25.080882 | 98 | 0.588666 | false |
/*
* Core MDSS framebuffer driver.
*
* Copyright (C) 2007 Google Incorporated
* Copyright (c) 2008-2015, The Linux Foundation. All rights reserved.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#define pr_fmt(fmt) "%s: " fmt, __func__
#include <linux/bootmem.h>
#include <linux/console.h>
#include <linux/debugfs.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/kernel.h>
#include <linux/leds.h>
#include <linux/memory.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/msm_mdp.h>
#include <linux/proc_fs.h>
#include <linux/pm_runtime.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/uaccess.h>
#include <linux/version.h>
#include <linux/vmalloc.h>
#include <linux/sync.h>
#include <linux/sw_sync.h>
#include <linux/file.h>
#include <linux/memory_alloc.h>
#include <linux/kthread.h>
#include <linux/of_address.h>
#include <mach/board.h>
#include <mach/memory.h>
#include <mach/iommu.h>
#include <mach/iommu_domains.h>
#include <mach/msm_memtypes.h>
#include "mdss_fb.h"
#include "mdss_mdp_splash_logo.h"
#include "mdss_mdp.h"
#ifdef CONFIG_FB_MSM_TRIPLE_BUFFER
#define MDSS_FB_NUM 3
#else
#define MDSS_FB_NUM 2
#endif
#define MAX_FBI_LIST 32
static struct fb_info *fbi_list[MAX_FBI_LIST];
static int fbi_list_index;
struct sys_panelinfo panelinfo = {NULL, NULL, NULL};
static u32 mdss_fb_pseudo_palette[16] = {
0x00000000, 0xffffffff, 0xffffffff, 0xffffffff,
0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff
};
static struct msm_mdp_interface *mdp_instance;
static int mdss_fb_register(struct msm_fb_data_type *mfd);
static int mdss_fb_open(struct fb_info *info, int user);
static int mdss_fb_release(struct fb_info *info, int user);
static int mdss_fb_release_all(struct fb_info *info, bool release_all);
static int mdss_fb_pan_display(struct fb_var_screeninfo *var,
struct fb_info *info);
static int mdss_fb_check_var(struct fb_var_screeninfo *var,
struct fb_info *info);
static int mdss_fb_set_par(struct fb_info *info);
static int mdss_fb_blank(int blank_mode, struct fb_info *info);
static int mdss_fb_suspend_sub(struct msm_fb_data_type *mfd);
static int mdss_fb_ioctl(struct fb_info *info, unsigned int cmd,
unsigned long arg);
static int mdss_fb_fbmem_ion_mmap(struct fb_info *info,
struct vm_area_struct *vma);
static void mdss_fb_release_fences(struct msm_fb_data_type *mfd);
static int __mdss_fb_sync_buf_done_callback(struct notifier_block *p,
unsigned long val, void *data);
static int __mdss_fb_display_thread(void *data);
static int mdss_fb_pan_idle(struct msm_fb_data_type *mfd);
static int mdss_fb_send_panel_event(struct msm_fb_data_type *mfd,
int event, void *arg);
static void mdss_fb_set_mdp_sync_pt_threshold(struct msm_fb_data_type *mfd);
void mdss_fb_no_update_notify_timer_cb(unsigned long data)
{
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)data;
if (!mfd) {
pr_err("%s mfd NULL\n", __func__);
return;
}
mfd->no_update.value = NOTIFY_TYPE_NO_UPDATE;
complete(&mfd->no_update.comp);
}
void mdss_fb_bl_update_notify(struct msm_fb_data_type *mfd)
{
if (!mfd) {
pr_err("%s mfd NULL\n", __func__);
return;
}
mutex_lock(&mfd->update.lock);
if (mfd->update.ref_count > 0) {
mutex_unlock(&mfd->update.lock);
mfd->update.value = NOTIFY_TYPE_BL_UPDATE;
complete(&mfd->update.comp);
mutex_lock(&mfd->update.lock);
}
mutex_unlock(&mfd->update.lock);
mutex_lock(&mfd->no_update.lock);
if (mfd->no_update.ref_count > 0) {
mutex_unlock(&mfd->no_update.lock);
mfd->no_update.value = NOTIFY_TYPE_BL_UPDATE;
complete(&mfd->no_update.comp);
mutex_lock(&mfd->no_update.lock);
}
mutex_unlock(&mfd->no_update.lock);
}
static int mdss_fb_notify_update(struct msm_fb_data_type *mfd,
unsigned long *argp)
{
int ret;
unsigned long notify = 0x0, to_user = 0x0;
ret = copy_from_user(¬ify, argp, sizeof(unsigned long));
if (ret) {
pr_err("%s:ioctl failed\n", __func__);
return ret;
}
if (notify > NOTIFY_UPDATE_POWER_OFF)
return -EINVAL;
if (mfd->update.is_suspend) {
to_user = NOTIFY_TYPE_SUSPEND;
mfd->update.is_suspend = 0;
ret = 1;
} else if (notify == NOTIFY_UPDATE_START) {
INIT_COMPLETION(mfd->update.comp);
mutex_lock(&mfd->update.lock);
mfd->update.ref_count++;
mutex_unlock(&mfd->update.lock);
ret = wait_for_completion_interruptible_timeout(
&mfd->update.comp, 4 * HZ);
mutex_lock(&mfd->update.lock);
mfd->update.ref_count--;
mutex_unlock(&mfd->update.lock);
to_user = (unsigned int)mfd->update.value;
if (mfd->update.type == NOTIFY_TYPE_SUSPEND) {
to_user = (unsigned int)mfd->update.type;
ret = 1;
}
} else if (notify == NOTIFY_UPDATE_STOP) {
INIT_COMPLETION(mfd->no_update.comp);
mutex_lock(&mfd->no_update.lock);
mfd->no_update.ref_count++;
mutex_unlock(&mfd->no_update.lock);
ret = wait_for_completion_interruptible_timeout(
&mfd->no_update.comp, 4 * HZ);
mutex_lock(&mfd->no_update.lock);
mfd->no_update.ref_count--;
mutex_unlock(&mfd->no_update.lock);
to_user = (unsigned int)mfd->no_update.value;
} else {
if (mfd->panel_power_on) {
INIT_COMPLETION(mfd->power_off_comp);
ret = wait_for_completion_interruptible_timeout(
&mfd->power_off_comp, 1 * HZ);
}
}
if (ret == 0)
ret = -ETIMEDOUT;
else if (ret > 0)
ret = copy_to_user(argp, &to_user, sizeof(unsigned long));
return ret;
}
static int lcd_backlight_registered;
static void mdss_fb_set_bl_brightness(struct led_classdev *led_cdev,
enum led_brightness value)
{
struct msm_fb_data_type *mfd = dev_get_drvdata(led_cdev->dev->parent);
int bl_lvl;
if (value > mfd->panel_info->brightness_max)
value = mfd->panel_info->brightness_max;
/* This maps android backlight level 0 to 255 into
driver backlight level 0 to bl_max with rounding */
MDSS_BRIGHT_TO_BL(bl_lvl, value, mfd->panel_info->bl_max,
mfd->panel_info->brightness_max);
if (!bl_lvl && value)
bl_lvl = 1;
if (!IS_CALIB_MODE_BL(mfd) && (!mfd->ext_bl_ctrl || !value ||
!mfd->bl_level)) {
mutex_lock(&mfd->bl_lock);
mdss_fb_set_backlight(mfd, bl_lvl);
mutex_unlock(&mfd->bl_lock);
}
}
static struct led_classdev backlight_led = {
.name = "lcd-backlight",
.brightness = MDSS_MAX_BL_BRIGHTNESS,
.brightness_set = mdss_fb_set_bl_brightness,
};
static ssize_t mdss_fb_get_type(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t ret = 0;
struct fb_info *fbi = dev_get_drvdata(dev);
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)fbi->par;
switch (mfd->panel.type) {
case NO_PANEL:
ret = snprintf(buf, PAGE_SIZE, "no panel\n");
break;
case HDMI_PANEL:
ret = snprintf(buf, PAGE_SIZE, "hdmi panel\n");
break;
case LVDS_PANEL:
ret = snprintf(buf, PAGE_SIZE, "lvds panel\n");
break;
case DTV_PANEL:
ret = snprintf(buf, PAGE_SIZE, "dtv panel\n");
break;
case MIPI_VIDEO_PANEL:
ret = snprintf(buf, PAGE_SIZE, "mipi dsi video panel\n");
break;
case MIPI_CMD_PANEL:
ret = snprintf(buf, PAGE_SIZE, "mipi dsi cmd panel\n");
break;
case WRITEBACK_PANEL:
ret = snprintf(buf, PAGE_SIZE, "writeback panel\n");
break;
case EDP_PANEL:
ret = snprintf(buf, PAGE_SIZE, "edp panel\n");
break;
default:
ret = snprintf(buf, PAGE_SIZE, "unknown panel\n");
break;
}
return ret;
}
static void mdss_fb_parse_dt(struct msm_fb_data_type *mfd)
{
u32 data[2] = {0};
u32 panel_xres;
struct platform_device *pdev = mfd->pdev;
of_property_read_u32_array(pdev->dev.of_node,
"qcom,mdss-fb-split", data, 2);
panel_xres = mfd->panel_info->xres;
if (data[0] && data[1]) {
if (mfd->split_display)
panel_xres *= 2;
if (panel_xres == data[0] + data[1]) {
mfd->split_fb_left = data[0];
mfd->split_fb_right = data[1];
}
} else {
if (mfd->split_display)
mfd->split_fb_left = mfd->split_fb_right = panel_xres;
else
mfd->split_fb_left = mfd->split_fb_right = 0;
}
pr_info("split framebuffer left=%d right=%d\n",
mfd->split_fb_left, mfd->split_fb_right);
}
static int pcc_r = 32768, pcc_g = 32768, pcc_b = 32768;
static ssize_t mdss_get_rgb(struct device *dev,
struct device_attribute *attr, char *buf)
{
u32 copyback = 0;
struct mdp_pcc_cfg_data pcc_cfg;
memset(&pcc_cfg, 0, sizeof(struct mdp_pcc_cfg_data));
pcc_cfg.block = MDP_LOGICAL_BLOCK_DISP_0;
pcc_cfg.ops = MDP_PP_OPS_READ;
mdss_mdp_pcc_config(&pcc_cfg, ©back);
/* We disable pcc when using default values and reg
* are zeroed on pp resume, so ignore empty values.
*/
if (pcc_cfg.r.r && pcc_cfg.g.g && pcc_cfg.b.b) {
pcc_r = pcc_cfg.r.r;
pcc_g = pcc_cfg.g.g;
pcc_b = pcc_cfg.b.b;
}
return scnprintf(buf, PAGE_SIZE, "%d %d %d\n", pcc_r, pcc_g, pcc_b);
}
/**
* simple color temperature interface using polynomial color correction
*
* input values are r/g/b adjustments from 0-32768 representing 0 -> 1
*
* example adjustment @ 3500K:
* 1.0000 / 0.5515 / 0.2520 = 32768 / 25828 / 17347
*
* reference chart:
* http://www.vendian.org/mncharity/dir3/blackbody/UnstableURLs/bbr_color.html
*/
static ssize_t mdss_set_rgb(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
uint32_t r = 0, g = 0, b = 0;
struct mdp_pcc_cfg_data pcc_cfg;
u32 copyback = 0;
if (count > 19)
return -EINVAL;
sscanf(buf, "%d %d %d", &r, &g, &b);
if (r < 0 || r > 32768)
return -EINVAL;
if (g < 0 || g > 32768)
return -EINVAL;
if (b < 0 || b > 32768)
return -EINVAL;
pr_info("%s: r=%d g=%d b=%d", __func__, r, g, b);
memset(&pcc_cfg, 0, sizeof(struct mdp_pcc_cfg_data));
pcc_cfg.block = MDP_LOGICAL_BLOCK_DISP_0;
if (r == 32768 && g == 32768 && b == 32768)
pcc_cfg.ops = MDP_PP_OPS_DISABLE;
else
pcc_cfg.ops = MDP_PP_OPS_ENABLE;
pcc_cfg.ops |= MDP_PP_OPS_WRITE;
pcc_cfg.r.r = r;
pcc_cfg.g.g = g;
pcc_cfg.b.b = b;
if (mdss_mdp_pcc_config(&pcc_cfg, ©back) == 0) {
pcc_r = r;
pcc_g = g;
pcc_b = b;
return count;
}
return -EINVAL;
}
static ssize_t mdss_fb_get_split(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t ret = 0;
struct fb_info *fbi = dev_get_drvdata(dev);
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)fbi->par;
ret = snprintf(buf, PAGE_SIZE, "%d %d\n",
mfd->split_fb_left, mfd->split_fb_right);
return ret;
}
static ssize_t mdss_mdp_show_blank_event(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct fb_info *fbi = dev_get_drvdata(dev);
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)fbi->par;
int ret;
pr_debug("fb%d panel_power_on = %d\n", mfd->index,
mfd->quickdraw_in_progress ? 0 : mfd->panel_power_on);
ret = scnprintf(buf, PAGE_SIZE, "panel_power_on = %d\n",
mfd->quickdraw_in_progress ? 0 : mfd->panel_power_on);
return ret;
}
static void __mdss_fb_idle_notify_work(struct work_struct *work)
{
struct delayed_work *dw = to_delayed_work(work);
struct msm_fb_data_type *mfd = container_of(dw, struct msm_fb_data_type,
idle_notify_work);
/* Notify idle-ness here */
pr_debug("Idle timeout %dms expired!\n", mfd->idle_time);
sysfs_notify(&mfd->fbi->dev->kobj, NULL, "idle_notify");
}
static ssize_t mdss_fb_get_idle_time(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct fb_info *fbi = dev_get_drvdata(dev);
struct msm_fb_data_type *mfd = fbi->par;
int ret;
ret = scnprintf(buf, PAGE_SIZE, "%d", mfd->idle_time);
return ret;
}
static ssize_t mdss_fb_set_idle_time(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct fb_info *fbi = dev_get_drvdata(dev);
struct msm_fb_data_type *mfd = fbi->par;
int rc = 0;
int idle_time = 0;
rc = kstrtoint(buf, 10, &idle_time);
if (rc) {
pr_err("kstrtoint failed. rc=%d\n", rc);
return rc;
}
pr_debug("Idle time = %d\n", idle_time);
mfd->idle_time = idle_time;
return count;
}
static ssize_t mdss_fb_get_idle_notify(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct fb_info *fbi = dev_get_drvdata(dev);
struct msm_fb_data_type *mfd = fbi->par;
int ret;
ret = scnprintf(buf, PAGE_SIZE, "%s",
work_busy(&mfd->idle_notify_work.work) ? "no" : "yes");
return ret;
}
static ssize_t mdss_fb_get_panel_info(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct fb_info *fbi = dev_get_drvdata(dev);
struct msm_fb_data_type *mfd = fbi->par;
struct mdss_panel_info *pinfo = mfd->panel_info;
int ret;
ret = scnprintf(buf, PAGE_SIZE,
"pu_en=%d\nxstart=%d\nwalign=%d\nystart=%d\nhalign=%d\n"
"min_w=%d\nmin_h=%d\ndyn_fps_en=%d\nmin_fps=%d\n"
"max_fps=%d\n",
pinfo->partial_update_enabled, pinfo->xstart_pix_align,
pinfo->width_pix_align, pinfo->ystart_pix_align,
pinfo->height_pix_align, pinfo->min_width,
pinfo->min_height, pinfo->dynamic_fps,
pinfo->min_fps, pinfo->max_fps);
return ret;
}
/*
* mdss_fb_lpm_enable() - Function to Control LowPowerMode
* @mfd: Framebuffer data structure for display
* @mode: Enabled/Disable LowPowerMode
* 1: Enter into LowPowerMode
* 0: Exit from LowPowerMode
*
* This Function dynamically switches to and from LowPowerMode
* based on the argument @mode.
*/
static int mdss_fb_lpm_enable(struct msm_fb_data_type *mfd, int mode)
{
int ret = 0;
u32 bl_lvl = 0;
struct mdss_panel_info *pinfo = NULL;
struct mdss_panel_data *pdata;
if (!mfd || !mfd->panel_info)
return -EINVAL;
pinfo = mfd->panel_info;
if (!pinfo->mipi.dynamic_switch_enabled) {
pr_warn("Panel does not support dynamic switch!\n");
return 0;
}
if (mode == pinfo->mipi.mode) {
pr_debug("Already in requested mode!\n");
return 0;
}
pdata = dev_get_platdata(&mfd->pdev->dev);
pr_debug("Enter mode: %d\n", mode);
pdata->panel_info.dynamic_switch_pending = true;
mutex_lock(&mfd->bl_lock);
bl_lvl = mfd->bl_level;
mdss_fb_set_backlight(mfd, 0);
mutex_unlock(&mfd->bl_lock);
lock_fb_info(mfd->fbi);
ret = mdss_fb_blank_sub(FB_BLANK_POWERDOWN, mfd->fbi,
mfd->op_enable);
if (ret) {
pr_err("can't turn off display!\n");
unlock_fb_info(mfd->fbi);
return ret;
}
mfd->op_enable = false;
ret = mfd->mdp.configure_panel(mfd, mode);
mdss_fb_set_mdp_sync_pt_threshold(mfd);
mfd->op_enable = true;
ret = mdss_fb_blank_sub(FB_BLANK_UNBLANK, mfd->fbi,
mfd->op_enable);
if (ret) {
pr_err("can't turn on display!\n");
unlock_fb_info(mfd->fbi);
return ret;
}
unlock_fb_info(mfd->fbi);
mutex_lock(&mfd->bl_lock);
mfd->bl_updated = true;
mdss_fb_set_backlight(mfd, bl_lvl);
mutex_unlock(&mfd->bl_lock);
pdata->panel_info.dynamic_switch_pending = false;
pdata->panel_info.is_lpm_mode = mode ? 1 : 0;
if (ret) {
pr_err("can't turn on display!\n");
return ret;
}
pr_debug("Exit mode: %d\n", mode);
return 0;
}
static DEVICE_ATTR(msm_fb_type, S_IRUGO, mdss_fb_get_type, NULL);
static DEVICE_ATTR(msm_fb_split, S_IRUGO, mdss_fb_get_split, NULL);
static DEVICE_ATTR(show_blank_event, S_IRUGO, mdss_mdp_show_blank_event, NULL);
static DEVICE_ATTR(idle_time, S_IRUGO | S_IWUSR | S_IWGRP,
mdss_fb_get_idle_time, mdss_fb_set_idle_time);
static DEVICE_ATTR(idle_notify, S_IRUGO, mdss_fb_get_idle_notify, NULL);
static DEVICE_ATTR(msm_fb_panel_info, S_IRUGO, mdss_fb_get_panel_info, NULL);
static DEVICE_ATTR(rgb, S_IRUGO | S_IWUSR | S_IWGRP, mdss_get_rgb, mdss_set_rgb);
static struct attribute *mdss_fb_attrs[] = {
&dev_attr_msm_fb_type.attr,
&dev_attr_msm_fb_split.attr,
&dev_attr_show_blank_event.attr,
&dev_attr_idle_time.attr,
&dev_attr_idle_notify.attr,
&dev_attr_msm_fb_panel_info.attr,
&dev_attr_rgb.attr,
NULL,
};
static struct attribute_group mdss_fb_attr_group = {
.attrs = mdss_fb_attrs,
};
static ssize_t panel_name_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", panelinfo.panel_name);
}
static ssize_t panel_ver_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "0x%016llx\n", *panelinfo.panel_ver);
}
static ssize_t panel_supplier_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", panelinfo.panel_supplier);
}
static ssize_t panel_man_id_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
u32 panel_ver = (u32)(*panelinfo.panel_ver);
return snprintf(buf, PAGE_SIZE, "0x%02x\n", panel_ver & 0xff);
}
static ssize_t panel_controller_ver_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
u32 panel_ver = (u32)(*panelinfo.panel_ver);
return snprintf(buf, PAGE_SIZE, "0x%02x\n", (panel_ver & 0xff00) >> 8);
}
static ssize_t panel_controller_drv_ver_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
u32 panel_ver = (u32)(*panelinfo.panel_ver);
return snprintf(buf, PAGE_SIZE, "0x%02x\n",
(panel_ver & 0xff0000) >> 16);
}
static DEVICE_ATTR(panel_name, S_IRUGO,
panel_name_show, NULL);
static DEVICE_ATTR(panel_ver, S_IRUGO,
panel_ver_show, NULL);
static DEVICE_ATTR(panel_supplier, S_IRUGO,
panel_supplier_show, NULL);
static DEVICE_ATTR(man_id, S_IRUGO,
panel_man_id_show, NULL);
static DEVICE_ATTR(controller_ver, S_IRUGO,
panel_controller_ver_show, NULL);
static DEVICE_ATTR(controller_drv_ver, S_IRUGO,
panel_controller_drv_ver_show, NULL);
static struct attribute *panel_id_attrs[] = {
&dev_attr_panel_name.attr,
&dev_attr_panel_ver.attr,
&dev_attr_panel_supplier.attr,
&dev_attr_man_id.attr,
&dev_attr_controller_ver.attr,
&dev_attr_controller_drv_ver.attr,
NULL,
};
static struct attribute_group panel_id_attr_group = {
.attrs = panel_id_attrs,
};
static int mdss_fb_create_sysfs(struct msm_fb_data_type *mfd)
{
int rc;
rc = sysfs_create_group(&mfd->fbi->dev->kobj, &mdss_fb_attr_group);
if (rc) {
pr_err("sysfs group creation failed, rc=%d\n", rc);
goto err;
}
rc = sysfs_create_group(&mfd->fbi->dev->kobj, &panel_id_attr_group);
if (rc)
pr_err("panel id group creation failed, rc=%d\n", rc);
err:
return rc;
}
static void mdss_fb_remove_sysfs(struct msm_fb_data_type *mfd)
{
sysfs_remove_group(&mfd->fbi->dev->kobj, &mdss_fb_attr_group);
}
static void mdss_fb_shutdown(struct platform_device *pdev)
{
struct msm_fb_data_type *mfd = platform_get_drvdata(pdev);
mfd->shutdown_pending = true;
lock_fb_info(mfd->fbi);
if (lcd_backlight_registered)
mdss_fb_set_bl_brightness(&backlight_led, 0);
mdss_fb_release_all(mfd->fbi, true);
unlock_fb_info(mfd->fbi);
}
static int mdss_fb_probe(struct platform_device *pdev)
{
struct msm_fb_data_type *mfd = NULL;
struct mdss_panel_data *pdata;
struct fb_info *fbi;
int rc;
if (fbi_list_index >= MAX_FBI_LIST)
return -ENOMEM;
pdata = dev_get_platdata(&pdev->dev);
if (!pdata)
return -EPROBE_DEFER;
/*
* alloc framebuffer info + par data
*/
fbi = framebuffer_alloc(sizeof(struct msm_fb_data_type), NULL);
if (fbi == NULL) {
pr_err("can't allocate framebuffer info data!\n");
return -ENOMEM;
}
mfd = (struct msm_fb_data_type *)fbi->par;
pdata->mfd = mfd;
mfd->key = MFD_KEY;
mfd->fbi = fbi;
mfd->panel_info = &pdata->panel_info;
mfd->panel.type = pdata->panel_info.type;
mfd->panel.id = mfd->index;
mfd->fb_page = MDSS_FB_NUM;
mfd->index = fbi_list_index;
mfd->mdp_fb_page_protection = MDP_FB_PAGE_PROTECTION_WRITECOMBINE;
mfd->ext_ad_ctrl = -1;
mfd->bl_level = 0;
mfd->bl_level_prev_scaled = 0;
mfd->bl_scale = 1024;
mfd->bl_min_lvl = 30;
mfd->ad_bl_level = 0;
mfd->fb_imgType = MDP_RGBA_8888;
mfd->pdev = pdev;
if (pdata->next)
mfd->split_display = true;
mfd->mdp = *mdp_instance;
INIT_LIST_HEAD(&mfd->proc_list);
mutex_init(&mfd->bl_lock);
fbi_list[fbi_list_index++] = fbi;
platform_set_drvdata(pdev, mfd);
rc = mdss_fb_register(mfd);
if (rc)
return rc;
if (mfd->mdp.init_fnc) {
rc = mfd->mdp.init_fnc(mfd);
if (rc) {
pr_err("init_fnc failed\n");
return rc;
}
}
rc = pm_runtime_set_active(mfd->fbi->dev);
if (rc < 0)
pr_err("pm_runtime: fail to set active.\n");
pm_runtime_enable(mfd->fbi->dev);
/* android supports only one lcd-backlight/lcd for now */
if (!lcd_backlight_registered) {
backlight_led.brightness = mfd->panel_info->brightness_max;
backlight_led.max_brightness = mfd->panel_info->brightness_max;
if (led_classdev_register(&pdev->dev, &backlight_led))
pr_err("led_classdev_register failed\n");
else
lcd_backlight_registered = 1;
}
mdss_fb_create_sysfs(mfd);
mdss_fb_send_panel_event(mfd, MDSS_EVENT_FB_REGISTERED, fbi);
mfd->mdp_sync_pt_data.fence_name = "mdp-fence";
if (mfd->mdp_sync_pt_data.timeline == NULL) {
char timeline_name[16];
snprintf(timeline_name, sizeof(timeline_name),
"mdss_fb_%d", mfd->index);
mfd->mdp_sync_pt_data.timeline =
sw_sync_timeline_create(timeline_name);
if (mfd->mdp_sync_pt_data.timeline == NULL) {
pr_err("cannot create release fence time line\n");
return -ENOMEM;
}
mfd->mdp_sync_pt_data.notifier.notifier_call =
__mdss_fb_sync_buf_done_callback;
}
mdss_fb_set_mdp_sync_pt_threshold(mfd);
if (mfd->mdp.splash_init_fnc)
mfd->mdp.splash_init_fnc(mfd);
INIT_DELAYED_WORK(&mfd->idle_notify_work, __mdss_fb_idle_notify_work);
mfd->quickdraw_in_progress = false;
mfd->quickdraw_reset_panel = false;
if (mfd->panel_info->cont_splash_feature_on) {
mfd->bl_level_scaled = mfd->panel_info->bl_max;
mfd->bl_updated = true;
}
return rc;
}
static void mdss_fb_set_mdp_sync_pt_threshold(struct msm_fb_data_type *mfd)
{
if (!mfd)
return;
switch (mfd->panel.type) {
case WRITEBACK_PANEL:
mfd->mdp_sync_pt_data.threshold = 1;
mfd->mdp_sync_pt_data.retire_threshold = 0;
break;
case MIPI_CMD_PANEL:
mfd->mdp_sync_pt_data.threshold = 1;
mfd->mdp_sync_pt_data.retire_threshold = 1;
break;
default:
mfd->mdp_sync_pt_data.threshold = 2;
mfd->mdp_sync_pt_data.retire_threshold = 0;
break;
}
}
static int mdss_fb_remove(struct platform_device *pdev)
{
struct msm_fb_data_type *mfd;
mfd = (struct msm_fb_data_type *)platform_get_drvdata(pdev);
if (!mfd)
return -ENODEV;
mdss_fb_remove_sysfs(mfd);
pm_runtime_disable(mfd->fbi->dev);
if (mfd->key != MFD_KEY)
return -EINVAL;
if (mdss_fb_suspend_sub(mfd))
pr_err("msm_fb_remove: can't stop the device %d\n",
mfd->index);
/* remove /dev/fb* */
unregister_framebuffer(mfd->fbi);
if (lcd_backlight_registered) {
lcd_backlight_registered = 0;
led_classdev_unregister(&backlight_led);
}
return 0;
}
static int mdss_fb_send_panel_event(struct msm_fb_data_type *mfd,
int event, void *arg)
{
struct mdss_panel_data *pdata;
pdata = dev_get_platdata(&mfd->pdev->dev);
if (!pdata) {
pr_err("no panel connected\n");
return -ENODEV;
}
pr_debug("sending event=%d for fb%d\n", event, mfd->index);
if (pdata->event_handler)
return pdata->event_handler(pdata, event, arg);
return 0;
}
static int mdss_fb_suspend_sub(struct msm_fb_data_type *mfd)
{
int ret = 0;
if ((!mfd) || (mfd->key != MFD_KEY))
return 0;
pr_debug("mdss_fb suspend index=%d\n", mfd->index);
mdss_fb_pan_idle(mfd);
ret = mdss_fb_send_panel_event(mfd, MDSS_EVENT_SUSPEND, NULL);
if (ret) {
pr_warn("unable to suspend fb%d (%d)\n", mfd->index, ret);
return ret;
}
mfd->suspend.op_enable = mfd->op_enable;
mfd->suspend.panel_power_on = mfd->panel_power_on;
if (mfd->op_enable) {
ret = mdss_fb_blank_sub(FB_BLANK_POWERDOWN, mfd->fbi,
mfd->suspend.op_enable);
if (ret) {
pr_warn("can't turn off display!\n");
return ret;
}
mfd->op_enable = false;
fb_set_suspend(mfd->fbi, FBINFO_STATE_SUSPENDED);
}
return 0;
}
static int mdss_fb_resume_sub(struct msm_fb_data_type *mfd)
{
int ret = 0;
if ((!mfd) || (mfd->key != MFD_KEY))
return 0;
INIT_COMPLETION(mfd->power_set_comp);
mfd->is_power_setting = true;
pr_debug("mdss_fb resume index=%d\n", mfd->index);
mdss_fb_pan_idle(mfd);
ret = mdss_fb_send_panel_event(mfd, MDSS_EVENT_RESUME, NULL);
if (ret) {
pr_warn("unable to resume fb%d (%d)\n", mfd->index, ret);
return ret;
}
/* resume state var recover */
mfd->op_enable = mfd->suspend.op_enable;
if (mfd->suspend.panel_power_on) {
ret = mdss_fb_blank_sub(FB_BLANK_UNBLANK, mfd->fbi,
mfd->op_enable);
if (ret)
pr_warn("can't turn on display!\n");
else
fb_set_suspend(mfd->fbi, FBINFO_STATE_RUNNING);
}
mfd->is_power_setting = false;
complete_all(&mfd->power_set_comp);
return ret;
}
#if defined(CONFIG_PM) && !defined(CONFIG_PM_SLEEP)
static int mdss_fb_suspend(struct platform_device *pdev, pm_message_t state)
{
struct msm_fb_data_type *mfd = platform_get_drvdata(pdev);
if (!mfd)
return -ENODEV;
dev_dbg(&pdev->dev, "display suspend\n");
return mdss_fb_suspend_sub(mfd);
}
static int mdss_fb_resume(struct platform_device *pdev)
{
struct msm_fb_data_type *mfd = platform_get_drvdata(pdev);
if (!mfd)
return -ENODEV;
dev_dbg(&pdev->dev, "display resume\n");
return mdss_fb_resume_sub(mfd);
}
#else
#define mdss_fb_suspend NULL
#define mdss_fb_resume NULL
#endif
#ifdef CONFIG_PM_SLEEP
static int mdss_fb_pm_suspend(struct device *dev)
{
struct msm_fb_data_type *mfd = dev_get_drvdata(dev);
if (!mfd)
return -ENODEV;
dev_dbg(dev, "display pm suspend\n");
return mdss_fb_suspend_sub(mfd);
}
static int mdss_fb_pm_resume(struct device *dev)
{
struct msm_fb_data_type *mfd = dev_get_drvdata(dev);
if (!mfd)
return -ENODEV;
dev_dbg(dev, "display pm resume\n");
return mdss_fb_resume_sub(mfd);
}
#endif
static const struct dev_pm_ops mdss_fb_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(mdss_fb_pm_suspend, mdss_fb_pm_resume)
};
static const struct of_device_id mdss_fb_dt_match[] = {
{ .compatible = "qcom,mdss-fb",},
{}
};
EXPORT_COMPAT("qcom,mdss-fb");
static struct platform_driver mdss_fb_driver = {
.probe = mdss_fb_probe,
.remove = mdss_fb_remove,
.suspend = mdss_fb_suspend,
.resume = mdss_fb_resume,
.shutdown = mdss_fb_shutdown,
.driver = {
.name = "mdss_fb",
.of_match_table = mdss_fb_dt_match,
.pm = &mdss_fb_pm_ops,
},
};
static void mdss_fb_scale_bl(struct msm_fb_data_type *mfd, u32 *bl_lvl)
{
u32 temp = *bl_lvl;
pr_debug("input = %d, scale = %d", temp, mfd->bl_scale);
if (temp >= mfd->bl_min_lvl) {
if (temp > mfd->panel_info->bl_max) {
pr_warn("%s: invalid bl level\n",
__func__);
temp = mfd->panel_info->bl_max;
}
if (mfd->bl_scale > 1024) {
pr_warn("%s: invalid bl scale\n",
__func__);
mfd->bl_scale = 1024;
}
/*
* bl_scale is the numerator of
* scaling fraction (x/1024)
*/
temp = (temp * mfd->bl_scale) / 1024;
/*if less than minimum level, use min level*/
if (temp < mfd->bl_min_lvl)
temp = mfd->bl_min_lvl;
}
pr_debug("output = %d", temp);
(*bl_lvl) = temp;
}
/* must call this function from within mfd->bl_lock */
void mdss_fb_set_backlight(struct msm_fb_data_type *mfd, u32 bkl_lvl)
{
struct mdss_panel_data *pdata;
u32 temp = bkl_lvl;
bool bl_notify_needed = false;
if ((((!mfd->panel_power_on && mfd->dcm_state != DCM_ENTER)
|| !mfd->bl_updated) && !IS_CALIB_MODE_BL(mfd)) ||
mfd->panel_info->cont_splash_enabled) {
mfd->unset_bl_level = bkl_lvl;
return;
} else {
mfd->unset_bl_level = 0;
}
pdata = dev_get_platdata(&mfd->pdev->dev);
if ((pdata) && (pdata->set_backlight)) {
if (mfd->mdp.ad_calc_bl)
(*mfd->mdp.ad_calc_bl)(mfd, temp, &temp,
&bl_notify_needed);
if (bl_notify_needed)
mdss_fb_bl_update_notify(mfd);
mfd->bl_level_prev_scaled = mfd->bl_level_scaled;
if (!IS_CALIB_MODE_BL(mfd))
mdss_fb_scale_bl(mfd, &temp);
/*
* Even though backlight has been scaled, want to show that
* backlight has been set to bkl_lvl to those that read from
* sysfs node. Thus, need to set bl_level even if it appears
* the backlight has already been set to the level it is at,
* as well as setting bl_level to bkl_lvl even though the
* backlight has been set to the scaled value.
*/
if (mfd->bl_level_scaled == temp) {
mfd->bl_level = bkl_lvl;
} else {
pr_debug("backlight sent to panel :%d\n", temp);
pdata->set_backlight(pdata, temp);
mfd->bl_level = bkl_lvl;
mfd->bl_level_scaled = temp;
}
}
}
void mdss_fb_update_backlight(struct msm_fb_data_type *mfd)
{
struct mdss_panel_data *pdata;
u32 temp;
bool bl_notify = false;
if (mfd->unset_bl_level) {
mutex_lock(&mfd->bl_lock);
if (!mfd->bl_updated) {
pdata = dev_get_platdata(&mfd->pdev->dev);
if ((pdata) && (pdata->set_backlight)) {
mfd->bl_level = mfd->unset_bl_level;
temp = mfd->bl_level;
if (mfd->mdp.ad_calc_bl)
(*mfd->mdp.ad_calc_bl)(mfd, temp, &temp,
&bl_notify);
if (bl_notify)
mdss_fb_bl_update_notify(mfd);
pdata->set_backlight(pdata, temp);
mfd->bl_level_scaled = mfd->unset_bl_level;
mfd->bl_updated = 1;
}
}
mutex_unlock(&mfd->bl_lock);
}
}
int mdss_fb_blank_sub(int blank_mode, struct fb_info *info, int op_enable)
{
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par;
struct mdss_panel_data *pdata;
int ret = 0;
if (!op_enable && !mfd->quickdraw_in_progress)
return -EPERM;
if (mfd->dcm_state == DCM_ENTER)
return -EPERM;
pdata = dev_get_platdata(&mfd->pdev->dev);
switch (blank_mode) {
case FB_BLANK_UNBLANK:
if (!mfd->panel_power_on && mfd->mdp.on_fnc) {
int panel_dead = mfd->panel_info->panel_dead;
ret = mfd->mdp.on_fnc(mfd);
if (ret == 0) {
mfd->panel_power_on = true;
if (panel_dead &&
mfd->panel_info->bklt_ctrl == BL_DCS_CMD &&
pdata) {
mutex_lock(&mfd->bl_lock);
pdata->set_backlight(pdata,
mfd->bl_level);
mutex_unlock(&mfd->bl_lock);
}
if (panel_dead)
mfd->panel_info->panel_dead = false;
}
mutex_lock(&mfd->update.lock);
mfd->update.type = NOTIFY_TYPE_UPDATE;
mfd->update.is_suspend = 0;
mutex_unlock(&mfd->update.lock);
/* Start the work thread to signal idle time */
if (mfd->idle_time)
schedule_delayed_work(&mfd->idle_notify_work,
msecs_to_jiffies(mfd->idle_time));
}
mutex_lock(&mfd->bl_lock);
if (!mfd->bl_updated) {
mfd->bl_updated = 1;
mdss_fb_set_backlight(mfd, mfd->bl_level_prev_scaled);
}
mutex_unlock(&mfd->bl_lock);
break;
case FB_BLANK_VSYNC_SUSPEND:
case FB_BLANK_HSYNC_SUSPEND:
case FB_BLANK_NORMAL:
case FB_BLANK_POWERDOWN:
default:
if (mfd->panel_power_on && mfd->mdp.off_fnc) {
int curr_pwr_state;
mutex_lock(&mfd->update.lock);
mfd->update.type = NOTIFY_TYPE_SUSPEND;
mfd->update.is_suspend = 1;
mutex_unlock(&mfd->update.lock);
complete(&mfd->update.comp);
del_timer(&mfd->no_update.timer);
mfd->no_update.value = NOTIFY_TYPE_SUSPEND;
complete(&mfd->no_update.comp);
mfd->op_enable = false;
curr_pwr_state = mfd->panel_power_on;
mutex_lock(&mfd->bl_lock);
mdss_fb_set_backlight(mfd, 0);
mfd->panel_power_on = false;
mfd->bl_updated = 0;
mutex_unlock(&mfd->bl_lock);
if (mfd->shutdown_pending &&
mfd->panel_info->bl_shutdown_delay)
usleep_range(mfd->panel_info->bl_shutdown_delay
* 1000,
mfd->panel_info->bl_shutdown_delay
* 1000);
ret = mfd->mdp.off_fnc(mfd);
if (ret)
mfd->panel_power_on = curr_pwr_state;
else
mdss_fb_release_fences(mfd);
mfd->op_enable = true;
complete(&mfd->power_off_comp);
}
break;
}
if (!mfd->quickdraw_in_progress) {
/* Notify listeners */
sysfs_notify(&mfd->fbi->dev->kobj, NULL, "show_blank_event");
}
return ret;
}
static int mdss_fb_blank(int blank_mode, struct fb_info *info)
{
struct mdss_panel_data *pdata;
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par;
int panel_dead = mfd->panel_info->panel_dead;
int ret;
mdss_fb_pan_idle(mfd);
if (mfd->op_enable == 0) {
if (blank_mode == FB_BLANK_UNBLANK)
mfd->suspend.panel_power_on = true;
else
mfd->suspend.panel_power_on = false;
return 0;
}
pr_debug("mode: %d\n", blank_mode);
pdata = dev_get_platdata(&mfd->pdev->dev);
if (pdata->panel_info.is_lpm_mode &&
blank_mode == FB_BLANK_UNBLANK) {
pr_debug("panel is in lpm mode\n");
mfd->mdp.configure_panel(mfd, 0);
mdss_fb_set_mdp_sync_pt_threshold(mfd);
pdata->panel_info.is_lpm_mode = false;
}
ret = mdss_fb_blank_sub(blank_mode, info, mfd->op_enable);
if (blank_mode == FB_BLANK_UNBLANK && !panel_dead &&
mfd->panel_info->panel_dead) {
pr_err("%s: Panel is dead, attempt recovery\n", __func__);
mdss_fb_blank_sub(FB_BLANK_NORMAL, info, 1);
mdss_fb_blank_sub(FB_BLANK_UNBLANK, info, 1);
}
return ret;
}
static inline int mdss_fb_create_ion_client(struct msm_fb_data_type *mfd)
{
mfd->fb_ion_client = msm_ion_client_create(-1 , "mdss_fb_iclient");
if (IS_ERR_OR_NULL(mfd->fb_ion_client)) {
pr_err("Err:client not created, val %d\n",
PTR_RET(mfd->fb_ion_client));
mfd->fb_ion_client = NULL;
return PTR_RET(mfd->fb_ion_client);
}
return 0;
}
void mdss_fb_free_fb_ion_memory(struct msm_fb_data_type *mfd)
{
if (!mfd) {
pr_err("no mfd\n");
return;
}
if (!mfd->fbi->screen_base)
return;
if (!mfd->fb_ion_client || !mfd->fb_ion_handle) {
pr_err("invalid input parameters for fb%d\n", mfd->index);
return;
}
mfd->fbi->screen_base = NULL;
mfd->fbi->fix.smem_start = 0;
ion_unmap_kernel(mfd->fb_ion_client, mfd->fb_ion_handle);
if (mfd->mdp.fb_mem_get_iommu_domain) {
ion_unmap_iommu(mfd->fb_ion_client, mfd->fb_ion_handle,
mfd->mdp.fb_mem_get_iommu_domain(), 0);
}
ion_free(mfd->fb_ion_client, mfd->fb_ion_handle);
mfd->fb_ion_handle = NULL;
}
int mdss_fb_alloc_fb_ion_memory(struct msm_fb_data_type *mfd, size_t fb_size)
{
unsigned long buf_size;
int rc;
void *vaddr;
if (!mfd) {
pr_err("Invalid input param - no mfd");
return -EINVAL;
}
if (!mfd->fb_ion_client) {
rc = mdss_fb_create_ion_client(mfd);
if (rc < 0) {
pr_err("fb ion client couldn't be created - %d\n", rc);
return rc;
}
}
pr_debug("size for mmap = %zu", fb_size);
mfd->fb_ion_handle = ion_alloc(mfd->fb_ion_client, fb_size, SZ_4K,
ION_HEAP(ION_SYSTEM_HEAP_ID), 0);
if (IS_ERR_OR_NULL(mfd->fb_ion_handle)) {
pr_err("unable to alloc fbmem from ion - %ld\n",
PTR_ERR(mfd->fb_ion_handle));
return PTR_ERR(mfd->fb_ion_handle);
}
if (mfd->mdp.fb_mem_get_iommu_domain) {
rc = ion_map_iommu(mfd->fb_ion_client, mfd->fb_ion_handle,
mfd->mdp.fb_mem_get_iommu_domain(), 0, SZ_4K, 0,
&mfd->iova, &buf_size, 0, 0);
if (rc) {
pr_err("Cannot map fb_mem to IOMMU. rc=%d\n", rc);
goto fb_mmap_failed;
}
} else {
pr_err("No IOMMU Domain");
rc = -EINVAL;
goto fb_mmap_failed;
}
vaddr = ion_map_kernel(mfd->fb_ion_client, mfd->fb_ion_handle);
if (IS_ERR_OR_NULL(vaddr)) {
pr_err("ION memory mapping failed - %ld\n", PTR_ERR(vaddr));
rc = PTR_ERR(vaddr);
if (mfd->mdp.fb_mem_get_iommu_domain) {
ion_unmap_iommu(mfd->fb_ion_client, mfd->fb_ion_handle,
mfd->mdp.fb_mem_get_iommu_domain(), 0);
}
goto fb_mmap_failed;
}
pr_debug("alloc 0x%zuB vaddr = %p (%pa iova) for fb%d\n", fb_size,
vaddr, &mfd->iova, mfd->index);
mfd->fbi->screen_base = (char *) vaddr;
mfd->fbi->fix.smem_start = (unsigned int) mfd->iova;
mfd->fbi->fix.smem_len = fb_size;
return rc;
fb_mmap_failed:
ion_free(mfd->fb_ion_client, mfd->fb_ion_handle);
return rc;
}
/**
* mdss_fb_fbmem_ion_mmap() - Custom fb mmap() function for MSM driver.
*
* @info - Framebuffer info.
* @vma - VM area which is part of the process virtual memory.
*
* This framebuffer mmap function differs from standard mmap() function by
* allowing for customized page-protection and dynamically allocate framebuffer
* memory from system heap and map to iommu virtual address.
*
* Return: virtual address is returned through vma
*/
static int mdss_fb_fbmem_ion_mmap(struct fb_info *info,
struct vm_area_struct *vma)
{
int rc = 0;
size_t req_size, fb_size;
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par;
struct sg_table *table;
unsigned long addr = vma->vm_start;
unsigned long offset = vma->vm_pgoff * PAGE_SIZE;
struct scatterlist *sg;
unsigned int i;
struct page *page;
if (!mfd || !mfd->pdev || !mfd->pdev->dev.of_node) {
pr_err("Invalid device node\n");
return -ENODEV;
}
req_size = vma->vm_end - vma->vm_start;
fb_size = mfd->fbi->fix.smem_len;
if (req_size > fb_size) {
pr_warn("requested map is greater than framebuffer");
return -EOVERFLOW;
}
if (!mfd->fbi->screen_base) {
rc = mdss_fb_alloc_fb_ion_memory(mfd, fb_size);
if (rc < 0) {
pr_err("fb mmap failed!!!!");
return rc;
}
}
table = ion_sg_table(mfd->fb_ion_client, mfd->fb_ion_handle);
if (IS_ERR(table)) {
pr_err("Unable to get sg_table from ion:%ld\n", PTR_ERR(table));
mfd->fbi->screen_base = NULL;
return PTR_ERR(table);
} else if (!table) {
pr_err("sg_list is NULL\n");
mfd->fbi->screen_base = NULL;
return -EINVAL;
}
page = sg_page(table->sgl);
if (page) {
for_each_sg(table->sgl, sg, table->nents, i) {
unsigned long remainder = vma->vm_end - addr;
unsigned long len = sg->length;
page = sg_page(sg);
if (offset >= sg->length) {
offset -= sg->length;
continue;
} else if (offset) {
page += offset / PAGE_SIZE;
len = sg->length - offset;
offset = 0;
}
len = min(len, remainder);
if (mfd->mdp_fb_page_protection ==
MDP_FB_PAGE_PROTECTION_WRITECOMBINE)
vma->vm_page_prot =
pgprot_writecombine(vma->vm_page_prot);
pr_debug("vma=%p, addr=%x len=%ld",
vma, (unsigned int)addr, len);
pr_cont("vm_start=%x vm_end=%x vm_page_prot=%ld\n",
(unsigned int)vma->vm_start,
(unsigned int)vma->vm_end,
(unsigned long int)vma->vm_page_prot);
io_remap_pfn_range(vma, addr, page_to_pfn(page), len,
vma->vm_page_prot);
addr += len;
if (addr >= vma->vm_end)
break;
}
} else {
pr_err("PAGE is null\n");
mdss_fb_free_fb_ion_memory(mfd);
return -ENOMEM;
}
return rc;
}
/*
* mdss_fb_physical_mmap() - Custom fb mmap() function for MSM driver.
*
* @info - Framebuffer info.
* @vma - VM area which is part of the process virtual memory.
*
* This framebuffer mmap function differs from standard mmap() function as
* map to framebuffer memory from the CMA memory which is allocated during
* bootup.
*
* Return: virtual address is returned through vma
*/
static int mdss_fb_physical_mmap(struct fb_info *info,
struct vm_area_struct *vma)
{
/* Get frame buffer memory range. */
unsigned long start = info->fix.smem_start;
u32 len = PAGE_ALIGN((start & ~PAGE_MASK) + info->fix.smem_len);
unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par;
if (!start) {
pr_warn("No framebuffer memory is allocated\n");
return -ENOMEM;
}
/* Set VM flags. */
start &= PAGE_MASK;
if ((vma->vm_end <= vma->vm_start) ||
(off >= len) ||
((vma->vm_end - vma->vm_start) > (len - off)))
return -EINVAL;
off += start;
if (off < start)
return -EINVAL;
vma->vm_pgoff = off >> PAGE_SHIFT;
/* This is an IO map - tell maydump to skip this VMA */
vma->vm_flags |= VM_IO;
if (mfd->mdp_fb_page_protection == MDP_FB_PAGE_PROTECTION_WRITECOMBINE)
vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot);
/* Remap the frame buffer I/O range */
if (io_remap_pfn_range(vma, vma->vm_start, off >> PAGE_SHIFT,
vma->vm_end - vma->vm_start,
vma->vm_page_prot))
return -EAGAIN;
return 0;
}
static int mdss_fb_mmap(struct fb_info *info, struct vm_area_struct *vma)
{
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par;
int rc = 0;
if (!info->fix.smem_start && !mfd->fb_ion_handle)
rc = mdss_fb_fbmem_ion_mmap(info, vma);
else
rc = mdss_fb_physical_mmap(info, vma);
if (rc < 0)
pr_err("fb mmap failed with rc = %d", rc);
return rc;
}
static struct fb_ops mdss_fb_ops = {
.owner = THIS_MODULE,
.fb_open = mdss_fb_open,
.fb_release = mdss_fb_release,
.fb_check_var = mdss_fb_check_var, /* vinfo check */
.fb_set_par = mdss_fb_set_par, /* set the video mode */
.fb_blank = mdss_fb_blank, /* blank display */
.fb_pan_display = mdss_fb_pan_display, /* pan display */
.fb_ioctl = mdss_fb_ioctl, /* perform fb specific ioctl */
.fb_mmap = mdss_fb_mmap,
};
static int mdss_fb_alloc_fbmem_iommu(struct msm_fb_data_type *mfd, int dom)
{
void *virt = NULL;
phys_addr_t phys = 0;
size_t size = 0;
struct platform_device *pdev = mfd->pdev;
int rc = 0;
struct device_node *fbmem_pnode = NULL;
if (!pdev || !pdev->dev.of_node) {
pr_err("Invalid device node\n");
return -ENODEV;
}
fbmem_pnode = of_parse_phandle(pdev->dev.of_node,
"linux,contiguous-region", 0);
if (!fbmem_pnode) {
pr_debug("fbmem is not reserved for %s\n", pdev->name);
mfd->fbi->screen_base = NULL;
mfd->fbi->fix.smem_start = 0;
return 0;
} else {
const u32 *addr;
u64 len;
addr = of_get_address(fbmem_pnode, 0, &len, NULL);
if (!addr) {
pr_err("fbmem size is not specified\n");
of_node_put(fbmem_pnode);
return -EINVAL;
}
size = (size_t)len;
of_node_put(fbmem_pnode);
}
pr_debug("%s frame buffer reserve_size=0x%zx\n", __func__, size);
if (size < PAGE_ALIGN(mfd->fbi->fix.line_length *
mfd->fbi->var.yres_virtual))
pr_warn("reserve size is smaller than framebuffer size\n");
virt = dma_alloc_coherent(&pdev->dev, size, &phys, GFP_KERNEL);
if (!virt) {
pr_err("unable to alloc fbmem size=%zx\n", size);
return -ENOMEM;
}
rc = msm_iommu_map_contig_buffer(phys, dom, 0, size, SZ_4K, 0,
&mfd->iova);
if (rc)
pr_warn("Cannot map fb_mem %pa to IOMMU. rc=%d\n", &phys, rc);
pr_debug("alloc 0x%zxB @ (%pa phys) (0x%p virt) (%pa iova) for fb%d\n",
size, &phys, virt, &mfd->iova, mfd->index);
mfd->fbi->screen_base = virt;
mfd->fbi->fix.smem_start = phys;
mfd->fbi->fix.smem_len = size;
return 0;
}
static int mdss_fb_alloc_fbmem(struct msm_fb_data_type *mfd)
{
if (mfd->mdp.fb_mem_alloc_fnc) {
return mfd->mdp.fb_mem_alloc_fnc(mfd);
} else if (mfd->mdp.fb_mem_get_iommu_domain) {
int dom = mfd->mdp.fb_mem_get_iommu_domain();
if (dom >= 0)
return mdss_fb_alloc_fbmem_iommu(mfd, dom);
else
return -ENOMEM;
} else {
pr_err("no fb memory allocator function defined\n");
return -ENOMEM;
}
}
static int mdss_fb_register(struct msm_fb_data_type *mfd)
{
int ret = -ENODEV;
int bpp;
struct mdss_panel_info *panel_info = mfd->panel_info;
struct fb_info *fbi = mfd->fbi;
struct fb_fix_screeninfo *fix;
struct fb_var_screeninfo *var;
int *id;
/*
* fb info initialization
*/
fix = &fbi->fix;
var = &fbi->var;
fix->type_aux = 0; /* if type == FB_TYPE_INTERLEAVED_PLANES */
fix->visual = FB_VISUAL_TRUECOLOR; /* True Color */
fix->ywrapstep = 0; /* No support */
fix->mmio_start = 0; /* No MMIO Address */
fix->mmio_len = 0; /* No MMIO Address */
fix->accel = FB_ACCEL_NONE;/* FB_ACCEL_MSM needes to be added in fb.h */
var->xoffset = 0, /* Offset from virtual to visible */
var->yoffset = 0, /* resolution */
var->grayscale = 0, /* No graylevels */
var->nonstd = 0, /* standard pixel format */
var->activate = FB_ACTIVATE_VBL, /* activate it at vsync */
var->height = -1, /* height of picture in mm */
var->width = -1, /* width of picture in mm */
var->accel_flags = 0, /* acceleration flags */
var->sync = 0, /* see FB_SYNC_* */
var->rotate = 0, /* angle we rotate counter clockwise */
mfd->op_enable = false;
/* Set undefined column alignments to single pixel alignment */
if (panel_info->col_align == 0)
panel_info->col_align = 1;
switch (mfd->fb_imgType) {
case MDP_RGB_565:
fix->type = FB_TYPE_PACKED_PIXELS;
fix->xpanstep = 1;
fix->ypanstep = 1;
var->vmode = FB_VMODE_NONINTERLACED;
var->blue.offset = 0;
var->green.offset = 5;
var->red.offset = 11;
var->blue.length = 5;
var->green.length = 6;
var->red.length = 5;
var->blue.msb_right = 0;
var->green.msb_right = 0;
var->red.msb_right = 0;
var->transp.offset = 0;
var->transp.length = 0;
bpp = 2;
break;
case MDP_RGB_888:
fix->type = FB_TYPE_PACKED_PIXELS;
fix->xpanstep = 1;
fix->ypanstep = 1;
var->vmode = FB_VMODE_NONINTERLACED;
var->blue.offset = 0;
var->green.offset = 8;
var->red.offset = 16;
var->blue.length = 8;
var->green.length = 8;
var->red.length = 8;
var->blue.msb_right = 0;
var->green.msb_right = 0;
var->red.msb_right = 0;
var->transp.offset = 0;
var->transp.length = 0;
bpp = 3;
break;
case MDP_ARGB_8888:
fix->type = FB_TYPE_PACKED_PIXELS;
fix->xpanstep = 1;
fix->ypanstep = 1;
var->vmode = FB_VMODE_NONINTERLACED;
var->blue.offset = 0;
var->green.offset = 8;
var->red.offset = 16;
var->blue.length = 8;
var->green.length = 8;
var->red.length = 8;
var->blue.msb_right = 0;
var->green.msb_right = 0;
var->red.msb_right = 0;
var->transp.offset = 24;
var->transp.length = 8;
bpp = 4;
break;
case MDP_RGBA_8888:
fix->type = FB_TYPE_PACKED_PIXELS;
fix->xpanstep = 1;
fix->ypanstep = 1;
var->vmode = FB_VMODE_NONINTERLACED;
var->blue.offset = 8;
var->green.offset = 16;
var->red.offset = 24;
var->blue.length = 8;
var->green.length = 8;
var->red.length = 8;
var->blue.msb_right = 0;
var->green.msb_right = 0;
var->red.msb_right = 0;
var->transp.offset = 0;
var->transp.length = 8;
bpp = 4;
break;
case MDP_YCRYCB_H2V1:
fix->type = FB_TYPE_INTERLEAVED_PLANES;
fix->xpanstep = 2;
fix->ypanstep = 1;
var->vmode = FB_VMODE_NONINTERLACED;
/* how about R/G/B offset? */
var->blue.offset = 0;
var->green.offset = 5;
var->red.offset = 11;
var->blue.length = 5;
var->green.length = 6;
var->red.length = 5;
var->blue.msb_right = 0;
var->green.msb_right = 0;
var->red.msb_right = 0;
var->transp.offset = 0;
var->transp.length = 0;
bpp = 2;
break;
default:
pr_err("msm_fb_init: fb %d unkown image type!\n",
mfd->index);
return ret;
}
var->xres = panel_info->xres;
if (mfd->split_display)
var->xres *= 2;
fix->type = panel_info->is_3d_panel;
if (mfd->mdp.fb_stride)
fix->line_length = mfd->mdp.fb_stride(mfd->index, var->xres,
bpp);
else
fix->line_length = var->xres * bpp;
var->yres = panel_info->yres;
if (panel_info->physical_width)
var->width = panel_info->physical_width;
if (panel_info->physical_height)
var->height = panel_info->physical_height;
var->xres_virtual = var->xres;
var->yres_virtual = panel_info->yres * mfd->fb_page;
var->bits_per_pixel = bpp * 8; /* FrameBuffer color depth */
var->upper_margin = panel_info->lcdc.v_back_porch;
var->lower_margin = panel_info->lcdc.v_front_porch;
var->vsync_len = panel_info->lcdc.v_pulse_width;
var->left_margin = panel_info->lcdc.h_back_porch;
var->right_margin = panel_info->lcdc.h_front_porch;
var->hsync_len = panel_info->lcdc.h_pulse_width;
var->pixclock = panel_info->clk_rate / 1000;
/*
* Populate smem length here for uspace to get the
* Framebuffer size when FBIO_FSCREENINFO ioctl is
* called.
*/
fix->smem_len = PAGE_ALIGN(fix->line_length * var->yres) * mfd->fb_page;
/* id field for fb app */
id = (int *)&mfd->panel;
snprintf(fix->id, sizeof(fix->id), "mdssfb_%x", (u32) *id);
fbi->fbops = &mdss_fb_ops;
fbi->flags = FBINFO_FLAG_DEFAULT;
fbi->pseudo_palette = mdss_fb_pseudo_palette;
mfd->ref_cnt = 0;
mfd->panel_power_on = false;
mfd->dcm_state = DCM_UNINIT;
mdss_fb_parse_dt(mfd);
if (mdss_fb_alloc_fbmem(mfd))
pr_warn("unable to allocate fb memory in fb register\n");
mfd->op_enable = true;
mutex_init(&mfd->update.lock);
mutex_init(&mfd->no_update.lock);
mutex_init(&mfd->mdp_sync_pt_data.sync_mutex);
atomic_set(&mfd->mdp_sync_pt_data.commit_cnt, 0);
atomic_set(&mfd->commits_pending, 0);
atomic_set(&mfd->ioctl_ref_cnt, 0);
atomic_set(&mfd->kickoff_pending, 0);
init_timer(&mfd->no_update.timer);
mfd->no_update.timer.function = mdss_fb_no_update_notify_timer_cb;
mfd->no_update.timer.data = (unsigned long)mfd;
mfd->update.ref_count = 0;
mfd->no_update.ref_count = 0;
init_completion(&mfd->update.comp);
init_completion(&mfd->no_update.comp);
init_completion(&mfd->power_off_comp);
init_completion(&mfd->power_set_comp);
init_waitqueue_head(&mfd->commit_wait_q);
init_waitqueue_head(&mfd->idle_wait_q);
init_waitqueue_head(&mfd->ioctl_q);
init_waitqueue_head(&mfd->kickoff_wait_q);
ret = fb_alloc_cmap(&fbi->cmap, 256, 0);
if (ret)
pr_err("fb_alloc_cmap() failed!\n");
if (register_framebuffer(fbi) < 0) {
fb_dealloc_cmap(&fbi->cmap);
mfd->op_enable = false;
return -EPERM;
}
pr_info("FrameBuffer[%d] %dx%d registered successfully!\n", mfd->index,
fbi->var.xres, fbi->var.yres);
return 0;
}
static int mdss_fb_open(struct fb_info *info, int user)
{
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par;
struct mdss_fb_proc_info *pinfo = NULL;
int result;
int pid = current->tgid;
struct task_struct *task = current->group_leader;
if (mfd->shutdown_pending) {
pr_err("Shutdown pending. Aborting operation. Request from pid:%d name=%s\n",
pid, task->comm);
return -EPERM;
}
list_for_each_entry(pinfo, &mfd->proc_list, list) {
if (pinfo->pid == pid)
break;
}
if ((pinfo == NULL) || (pinfo->pid != pid)) {
pinfo = kmalloc(sizeof(*pinfo), GFP_KERNEL);
if (!pinfo) {
pr_err("unable to alloc process info\n");
return -ENOMEM;
}
pinfo->pid = pid;
pinfo->ref_cnt = 0;
list_add(&pinfo->list, &mfd->proc_list);
pr_debug("new process entry pid=%d\n", pinfo->pid);
}
result = pm_runtime_get_sync(info->dev);
if (result < 0) {
pr_err("pm_runtime: fail to wake up\n");
goto pm_error;
}
if (!mfd->ref_cnt) {
mfd->disp_thread = kthread_run(__mdss_fb_display_thread, mfd,
"mdss_fb%d", mfd->index);
if (IS_ERR(mfd->disp_thread)) {
pr_err("unable to start display thread %d\n",
mfd->index);
result = PTR_ERR(mfd->disp_thread);
mfd->disp_thread = NULL;
goto thread_error;
}
result = mdss_fb_blank_sub(FB_BLANK_UNBLANK, info,
mfd->op_enable);
if (result) {
pr_err("can't turn on fb%d! rc=%d\n", mfd->index,
result);
goto blank_error;
}
}
pinfo->ref_cnt++;
mfd->ref_cnt++;
return 0;
blank_error:
kthread_stop(mfd->disp_thread);
mfd->disp_thread = NULL;
thread_error:
if (pinfo && !pinfo->ref_cnt) {
list_del(&pinfo->list);
kfree(pinfo);
}
pm_runtime_put(info->dev);
pm_error:
return result;
}
static int mdss_fb_release_all(struct fb_info *info, bool release_all)
{
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par;
struct mdss_fb_proc_info *pinfo = NULL, *temp_pinfo = NULL;
int ret = 0, ad_ret = 0;
int pid = current->tgid;
bool unknown_pid = true, release_needed = false;
struct task_struct *task = current->group_leader;
struct mdss_panel_data *pdata;
if (!mfd->ref_cnt) {
pr_info("try to close unopened fb %d! from %s\n", mfd->index,
task->comm);
return -EINVAL;
}
if (!wait_event_timeout(mfd->ioctl_q,
!atomic_read(&mfd->ioctl_ref_cnt) || !release_all,
msecs_to_jiffies(1000)))
pr_warn("fb%d ioctl could not finish. waited 1 sec.\n",
mfd->index);
mdss_fb_pan_idle(mfd);
pr_debug("release_all = %s\n", release_all ? "true" : "false");
list_for_each_entry_safe(pinfo, temp_pinfo, &mfd->proc_list, list) {
if (!release_all && (pinfo->pid != pid))
continue;
unknown_pid = false;
pr_debug("found process %s pid=%d mfd->ref=%d pinfo->ref=%d\n",
task->comm, mfd->ref_cnt, pinfo->pid, pinfo->ref_cnt);
do {
if (mfd->ref_cnt < pinfo->ref_cnt)
pr_warn("WARN:mfd->ref=%d < pinfo->ref=%d\n",
mfd->ref_cnt, pinfo->ref_cnt);
else
mfd->ref_cnt--;
pinfo->ref_cnt--;
pm_runtime_put(info->dev);
} while (release_all && pinfo->ref_cnt);
if (release_all && mfd->disp_thread) {
kthread_stop(mfd->disp_thread);
mfd->disp_thread = NULL;
}
if (pinfo->ref_cnt == 0) {
list_del(&pinfo->list);
kfree(pinfo);
release_needed = !release_all;
}
if (!release_all)
break;
}
if (release_needed) {
pr_debug("known process %s pid=%d mfd->ref=%d\n",
task->comm, pid, mfd->ref_cnt);
if (mfd->mdp.release_fnc) {
ret = mfd->mdp.release_fnc(mfd, false);
if (ret)
pr_err("error releasing fb%d pid=%d\n",
mfd->index, pid);
}
} else if (unknown_pid || release_all) {
pr_warn("unknown process %s pid=%d mfd->ref=%d\n",
task->comm, pid, mfd->ref_cnt);
if (mfd->ref_cnt)
mfd->ref_cnt--;
if (mfd->mdp.release_fnc) {
ret = mfd->mdp.release_fnc(mfd, true);
if (ret)
pr_err("error fb%d release process %s pid=%d\n",
mfd->index, task->comm, pid);
}
}
if (!mfd->ref_cnt) {
if (mfd->disp_thread) {
kthread_stop(mfd->disp_thread);
mfd->disp_thread = NULL;
}
/*
* Turn off back light of video panel to make possible artifacts
* caused by blank/unblank invisible.
*/
pdata = dev_get_platdata(&mfd->pdev->dev);
if (pdata && pdata->set_backlight &&
mfd->panel_info->type == MIPI_VIDEO_PANEL) {
mutex_lock(&mfd->bl_lock);
if (mfd->bl_level_scaled != 0)
pdata->set_backlight(pdata, 0);
mutex_unlock(&mfd->bl_lock);
}
ret = mdss_fb_blank_sub(FB_BLANK_POWERDOWN, info,
mfd->op_enable);
if (ret) {
pr_err("can't turn off fb%d! rc=%d process %s pid=%d\n",
mfd->index, ret, task->comm, pid);
return ret;
}
mutex_lock(&mfd->bl_lock);
if (!mfd->unset_bl_level)
mfd->unset_bl_level = mfd->bl_level_scaled;
mutex_unlock(&mfd->bl_lock);
if (mfd->mdp.release_fnc) {
ret = mfd->mdp.release_fnc(mfd, true);
if (ret)
pr_err("error fb%d release process %s pid=%d\n",
mfd->index, task->comm, pid);
}
if (mfd->fb_ion_handle)
mdss_fb_free_fb_ion_memory(mfd);
if (mfd->mdp.ad_shutdown_cleanup) {
ad_ret = (*mfd->mdp.ad_shutdown_cleanup)(mfd);
if (ad_ret)
pr_err("AD shutdown cleanup failed ret = %d\n",
ad_ret);
}
atomic_set(&mfd->ioctl_ref_cnt, 0);
}
return ret;
}
static int mdss_fb_release(struct fb_info *info, int user)
{
return mdss_fb_release_all(info, false);
}
static void mdss_fb_power_setting_idle(struct msm_fb_data_type *mfd)
{
int ret;
if (mfd->is_power_setting) {
ret = wait_for_completion_timeout(
&mfd->power_set_comp,
msecs_to_jiffies(WAIT_DISP_OP_TIMEOUT));
if (ret < 0)
ret = -ERESTARTSYS;
else if (!ret)
pr_err("%s wait for power_set_comp timeout %d %d",
__func__, ret, mfd->is_power_setting);
if (ret <= 0) {
mfd->is_power_setting = false;
complete_all(&mfd->power_set_comp);
}
}
}
void mdss_fb_wait_for_fence(struct msm_sync_pt_data *sync_pt_data)
{
struct sync_fence *fences[MDP_MAX_FENCE_FD];
int fence_cnt;
int i, ret = 0;
pr_debug("%s: wait for fences\n", sync_pt_data->fence_name);
mutex_lock(&sync_pt_data->sync_mutex);
/*
* Assuming that acq_fen_cnt is sanitized in bufsync ioctl
* to check for sync_pt_data->acq_fen_cnt) <= MDP_MAX_FENCE_FD
*/
fence_cnt = sync_pt_data->acq_fen_cnt;
sync_pt_data->acq_fen_cnt = 0;
if (fence_cnt)
memcpy(fences, sync_pt_data->acq_fen,
fence_cnt * sizeof(struct sync_fence *));
mutex_unlock(&sync_pt_data->sync_mutex);
/* buf sync */
for (i = 0; i < fence_cnt && !ret; i++) {
ret = sync_fence_wait(fences[i],
WAIT_FENCE_FIRST_TIMEOUT);
if (ret == -ETIME) {
pr_warn("%s: sync_fence_wait timed out! ",
sync_pt_data->fence_name);
pr_cont("Waiting %ld more seconds\n",
WAIT_FENCE_FINAL_TIMEOUT/MSEC_PER_SEC);
ret = sync_fence_wait(fences[i],
WAIT_FENCE_FINAL_TIMEOUT);
}
sync_fence_put(fences[i]);
}
if (ret < 0) {
pr_err("%s: sync_fence_wait failed! ret = %x\n",
sync_pt_data->fence_name, ret);
for (; i < fence_cnt; i++)
sync_fence_put(fences[i]);
}
}
/**
* mdss_fb_signal_timeline() - signal a single release fence
* @sync_pt_data: Sync point data structure for the timeline which
* should be signaled.
*
* This is called after a frame has been pushed to display. This signals the
* timeline to release the fences associated with this frame.
*/
void mdss_fb_signal_timeline(struct msm_sync_pt_data *sync_pt_data)
{
mutex_lock(&sync_pt_data->sync_mutex);
if (atomic_add_unless(&sync_pt_data->commit_cnt, -1, 0) &&
sync_pt_data->timeline) {
sw_sync_timeline_inc(sync_pt_data->timeline, 1);
sync_pt_data->timeline_value++;
pr_debug("%s: buffer signaled! timeline val=%d remaining=%d\n",
sync_pt_data->fence_name, sync_pt_data->timeline_value,
atomic_read(&sync_pt_data->commit_cnt));
} else {
pr_debug("%s timeline signaled without commits val=%d\n",
sync_pt_data->fence_name, sync_pt_data->timeline_value);
}
mutex_unlock(&sync_pt_data->sync_mutex);
}
/**
* mdss_fb_release_fences() - signal all pending release fences
* @mfd: Framebuffer data structure for display
*
* Release all currently pending release fences, including those that are in
* the process to be commited.
*
* Note: this should only be called during close or suspend sequence.
*/
static void mdss_fb_release_fences(struct msm_fb_data_type *mfd)
{
struct msm_sync_pt_data *sync_pt_data = &mfd->mdp_sync_pt_data;
int val;
mutex_lock(&sync_pt_data->sync_mutex);
if (sync_pt_data->timeline) {
val = sync_pt_data->threshold +
atomic_read(&sync_pt_data->commit_cnt);
sw_sync_timeline_inc(sync_pt_data->timeline, val);
sync_pt_data->timeline_value += val;
atomic_set(&sync_pt_data->commit_cnt, 0);
}
mutex_unlock(&sync_pt_data->sync_mutex);
}
/**
* __mdss_fb_sync_buf_done_callback() - process async display events
* @p: Notifier block registered for async events.
* @event: Event enum to identify the event.
* @data: Optional argument provided with the event.
*
* See enum mdp_notify_event for events handled.
*/
static int __mdss_fb_sync_buf_done_callback(struct notifier_block *p,
unsigned long event, void *data)
{
struct msm_sync_pt_data *sync_pt_data;
struct msm_fb_data_type *mfd;
sync_pt_data = container_of(p, struct msm_sync_pt_data, notifier);
mfd = container_of(sync_pt_data, struct msm_fb_data_type,
mdp_sync_pt_data);
switch (event) {
case MDP_NOTIFY_FRAME_BEGIN:
if (mfd->idle_time) {
cancel_delayed_work_sync(&mfd->idle_notify_work);
schedule_delayed_work(&mfd->idle_notify_work,
msecs_to_jiffies(mfd->idle_time));
}
break;
case MDP_NOTIFY_FRAME_READY:
if (sync_pt_data->async_wait_fences)
mdss_fb_wait_for_fence(sync_pt_data);
break;
case MDP_NOTIFY_FRAME_FLUSHED:
pr_debug("%s: frame flushed\n", sync_pt_data->fence_name);
sync_pt_data->flushed = true;
break;
case MDP_NOTIFY_FRAME_TIMEOUT:
pr_err("%s: frame timeout\n", sync_pt_data->fence_name);
mdss_fb_signal_timeline(sync_pt_data);
break;
case MDP_NOTIFY_FRAME_DONE:
pr_debug("%s: frame done\n", sync_pt_data->fence_name);
mdss_fb_signal_timeline(sync_pt_data);
break;
}
return NOTIFY_OK;
}
/**
* mdss_fb_pan_idle() - wait for panel programming to be idle
* @mfd: Framebuffer data structure for display
*
* Wait for any pending programming to be done if in the process of programming
* hardware configuration. After this function returns it is safe to perform
* software updates for next frame.
*/
static int mdss_fb_pan_idle(struct msm_fb_data_type *mfd)
{
int ret = 0;
ret = wait_event_timeout(mfd->idle_wait_q,
(!atomic_read(&mfd->commits_pending) ||
mfd->shutdown_pending),
msecs_to_jiffies(WAIT_DISP_OP_TIMEOUT));
if (!ret) {
pr_err("wait for idle timeout %d pending=%d\n",
ret, atomic_read(&mfd->commits_pending));
mdss_fb_signal_timeline(&mfd->mdp_sync_pt_data);
} else if (mfd->shutdown_pending) {
pr_debug("Shutdown signalled\n");
return -EPERM;
}
return 0;
}
static int mdss_fb_wait_for_kickoff(struct msm_fb_data_type *mfd)
{
int ret = 0;
ret = wait_event_timeout(mfd->kickoff_wait_q,
(!atomic_read(&mfd->kickoff_pending) ||
mfd->shutdown_pending),
msecs_to_jiffies(WAIT_DISP_OP_TIMEOUT / 2));
if (!ret) {
pr_err("wait for kickoff timeout %d pending=%d\n",
ret, atomic_read(&mfd->kickoff_pending));
} else if (mfd->shutdown_pending) {
pr_debug("Shutdown signalled\n");
return -EPERM;
}
return 0;
}
int mdss_fb_pan_display_ex(struct fb_info *info,
struct mdp_display_commit *disp_commit)
{
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par;
struct fb_var_screeninfo *var = &disp_commit->var;
u32 wait_for_finish = disp_commit->wait_for_finish;
int ret = 0;
if (!mfd || (!mfd->op_enable && !mfd->quickdraw_in_progress))
return -EPERM;
if ((!mfd->panel_power_on) && !((mfd->dcm_state == DCM_ENTER) &&
(mfd->panel.type == MIPI_CMD_PANEL)))
return -EPERM;
if (var->xoffset > (info->var.xres_virtual - info->var.xres))
return -EINVAL;
if (var->yoffset > (info->var.yres_virtual - info->var.yres))
return -EINVAL;
ret = mdss_fb_pan_idle(mfd);
if (ret) {
pr_err("Shutdown pending. Aborting operation\n");
return ret;
}
mutex_lock(&mfd->mdp_sync_pt_data.sync_mutex);
if (info->fix.xpanstep)
info->var.xoffset =
(var->xoffset / info->fix.xpanstep) * info->fix.xpanstep;
if (info->fix.ypanstep)
info->var.yoffset =
(var->yoffset / info->fix.ypanstep) * info->fix.ypanstep;
mfd->msm_fb_backup.info = *info;
mfd->msm_fb_backup.disp_commit = *disp_commit;
atomic_inc(&mfd->mdp_sync_pt_data.commit_cnt);
atomic_inc(&mfd->commits_pending);
atomic_inc(&mfd->kickoff_pending);
wake_up_all(&mfd->commit_wait_q);
mutex_unlock(&mfd->mdp_sync_pt_data.sync_mutex);
if (wait_for_finish)
mdss_fb_pan_idle(mfd);
return ret;
}
static int mdss_fb_pan_display(struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct mdp_display_commit disp_commit;
memset(&disp_commit, 0, sizeof(disp_commit));
disp_commit.wait_for_finish = true;
memcpy(&disp_commit.var, var, sizeof(struct fb_var_screeninfo));
return mdss_fb_pan_display_ex(info, &disp_commit);
}
static int mdss_fb_pan_display_sub(struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par;
if (!mfd->op_enable)
return -EPERM;
if ((!mfd->panel_power_on) && !((mfd->dcm_state == DCM_ENTER) &&
(mfd->panel.type == MIPI_CMD_PANEL)))
return -EPERM;
if (var->xoffset > (info->var.xres_virtual - info->var.xres))
return -EINVAL;
if (var->yoffset > (info->var.yres_virtual - info->var.yres))
return -EINVAL;
if (info->fix.xpanstep)
info->var.xoffset =
(var->xoffset / info->fix.xpanstep) * info->fix.xpanstep;
if (info->fix.ypanstep)
info->var.yoffset =
(var->yoffset / info->fix.ypanstep) * info->fix.ypanstep;
if (mfd->mdp.dma_fnc)
mfd->mdp.dma_fnc(mfd);
else
pr_warn("dma function not set for panel type=%d\n",
mfd->panel.type);
return 0;
}
static void mdss_fb_var_to_panelinfo(struct fb_var_screeninfo *var,
struct mdss_panel_info *pinfo)
{
pinfo->xres = var->xres;
pinfo->yres = var->yres;
pinfo->lcdc.v_front_porch = var->lower_margin;
pinfo->lcdc.v_back_porch = var->upper_margin;
pinfo->lcdc.v_pulse_width = var->vsync_len;
pinfo->lcdc.h_front_porch = var->right_margin;
pinfo->lcdc.h_back_porch = var->left_margin;
pinfo->lcdc.h_pulse_width = var->hsync_len;
pinfo->clk_rate = var->pixclock;
}
/**
* __mdss_fb_perform_commit() - process a frame to display
* @mfd: Framebuffer data structure for display
*
* Processes all layers and buffers programmed and ensures all pending release
* fences are signaled once the buffer is transfered to display.
*/
static int __mdss_fb_perform_commit(struct msm_fb_data_type *mfd)
{
struct msm_sync_pt_data *sync_pt_data = &mfd->mdp_sync_pt_data;
struct msm_fb_backup_type *fb_backup = &mfd->msm_fb_backup;
int ret = -ENOSYS;
if (!sync_pt_data->async_wait_fences)
mdss_fb_wait_for_fence(sync_pt_data);
sync_pt_data->flushed = false;
if (fb_backup->disp_commit.flags & MDP_DISPLAY_COMMIT_OVERLAY) {
if (mfd->mdp.kickoff_fnc)
ret = mfd->mdp.kickoff_fnc(mfd,
&fb_backup->disp_commit);
else
pr_warn("no kickoff function setup for fb%d\n",
mfd->index);
} else {
ret = mdss_fb_pan_display_sub(&fb_backup->disp_commit.var,
&fb_backup->info);
if (ret)
pr_err("pan display failed %x on fb%d\n", ret,
mfd->index);
atomic_set(&mfd->kickoff_pending, 0);
wake_up_all(&mfd->kickoff_wait_q);
}
if (!ret)
mdss_fb_update_backlight(mfd);
if (IS_ERR_VALUE(ret) || !sync_pt_data->flushed)
mdss_fb_signal_timeline(sync_pt_data);
return ret;
}
static int __mdss_fb_display_thread(void *data)
{
struct msm_fb_data_type *mfd = data;
int ret;
struct sched_param param;
param.sched_priority = 16;
ret = sched_setscheduler(current, SCHED_FIFO, ¶m);
if (ret)
pr_warn("set priority failed for fb%d display thread\n",
mfd->index);
while (1) {
wait_event(mfd->commit_wait_q,
(atomic_read(&mfd->commits_pending) ||
kthread_should_stop()));
if (kthread_should_stop())
break;
ret = __mdss_fb_perform_commit(mfd);
atomic_dec(&mfd->commits_pending);
wake_up_all(&mfd->idle_wait_q);
}
atomic_set(&mfd->commits_pending, 0);
atomic_set(&mfd->kickoff_pending, 0);
wake_up_all(&mfd->idle_wait_q);
return ret;
}
static int mdss_fb_check_var(struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par;
if (var->rotate != FB_ROTATE_UR)
return -EINVAL;
if (var->grayscale != info->var.grayscale)
return -EINVAL;
switch (var->bits_per_pixel) {
case 16:
if ((var->green.offset != 5) ||
!((var->blue.offset == 11)
|| (var->blue.offset == 0)) ||
!((var->red.offset == 11)
|| (var->red.offset == 0)) ||
(var->blue.length != 5) ||
(var->green.length != 6) ||
(var->red.length != 5) ||
(var->blue.msb_right != 0) ||
(var->green.msb_right != 0) ||
(var->red.msb_right != 0) ||
(var->transp.offset != 0) ||
(var->transp.length != 0))
return -EINVAL;
break;
case 24:
if ((var->blue.offset != 0) ||
(var->green.offset != 8) ||
(var->red.offset != 16) ||
(var->blue.length != 8) ||
(var->green.length != 8) ||
(var->red.length != 8) ||
(var->blue.msb_right != 0) ||
(var->green.msb_right != 0) ||
(var->red.msb_right != 0) ||
!(((var->transp.offset == 0) &&
(var->transp.length == 0)) ||
((var->transp.offset == 24) &&
(var->transp.length == 8))))
return -EINVAL;
break;
case 32:
/* Figure out if the user meant RGBA or ARGB
and verify the position of the RGB components */
if (var->transp.offset == 24) {
if ((var->blue.offset != 0) ||
(var->green.offset != 8) ||
(var->red.offset != 16))
return -EINVAL;
} else if (var->transp.offset == 0) {
if ((var->blue.offset != 8) ||
(var->green.offset != 16) ||
(var->red.offset != 24))
return -EINVAL;
} else
return -EINVAL;
/* Check the common values for both RGBA and ARGB */
if ((var->blue.length != 8) ||
(var->green.length != 8) ||
(var->red.length != 8) ||
(var->transp.length != 8) ||
(var->blue.msb_right != 0) ||
(var->green.msb_right != 0) ||
(var->red.msb_right != 0))
return -EINVAL;
break;
default:
return -EINVAL;
}
if ((var->xres_virtual <= 0) || (var->yres_virtual <= 0))
return -EINVAL;
if (info->fix.smem_start) {
u32 len = var->xres_virtual * var->yres_virtual *
(var->bits_per_pixel / 8);
if (len > info->fix.smem_len)
return -EINVAL;
}
if ((var->xres == 0) || (var->yres == 0))
return -EINVAL;
if (var->xoffset > (var->xres_virtual - var->xres))
return -EINVAL;
if (var->yoffset > (var->yres_virtual - var->yres))
return -EINVAL;
if (mfd->panel_info) {
struct mdss_panel_info panel_info;
int rc;
memcpy(&panel_info, mfd->panel_info, sizeof(panel_info));
mdss_fb_var_to_panelinfo(var, &panel_info);
rc = mdss_fb_send_panel_event(mfd, MDSS_EVENT_CHECK_PARAMS,
&panel_info);
if (IS_ERR_VALUE(rc))
return rc;
mfd->panel_reconfig = rc;
}
return 0;
}
static int mdss_fb_set_par(struct fb_info *info)
{
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par;
struct fb_var_screeninfo *var = &info->var;
int old_imgType;
int ret = 0;
ret = mdss_fb_pan_idle(mfd);
if (ret) {
pr_err("Shutdown pending. Aborting operation\n");
return ret;
}
old_imgType = mfd->fb_imgType;
switch (var->bits_per_pixel) {
case 16:
if (var->red.offset == 0)
mfd->fb_imgType = MDP_BGR_565;
else
mfd->fb_imgType = MDP_RGB_565;
break;
case 24:
if ((var->transp.offset == 0) && (var->transp.length == 0))
mfd->fb_imgType = MDP_RGB_888;
else if ((var->transp.offset == 24) &&
(var->transp.length == 8)) {
mfd->fb_imgType = MDP_ARGB_8888;
info->var.bits_per_pixel = 32;
}
break;
case 32:
if (var->transp.offset == 24)
mfd->fb_imgType = MDP_ARGB_8888;
else
mfd->fb_imgType = MDP_RGBA_8888;
break;
default:
return -EINVAL;
}
if (mfd->mdp.fb_stride)
mfd->fbi->fix.line_length = mfd->mdp.fb_stride(mfd->index,
var->xres,
var->bits_per_pixel / 8);
else
mfd->fbi->fix.line_length = var->xres * var->bits_per_pixel / 8;
mfd->fbi->fix.smem_len = mfd->fbi->fix.line_length *
mfd->fbi->var.yres_virtual;
if (mfd->panel_reconfig || (mfd->fb_imgType != old_imgType)) {
mdss_fb_blank_sub(FB_BLANK_POWERDOWN, info, mfd->op_enable);
mdss_fb_var_to_panelinfo(var, mfd->panel_info);
mdss_fb_blank_sub(FB_BLANK_UNBLANK, info, mfd->op_enable);
mfd->panel_reconfig = false;
}
return ret;
}
int mdss_fb_dcm(struct msm_fb_data_type *mfd, int req_state)
{
int ret = 0;
if (req_state == mfd->dcm_state) {
pr_warn("Already in correct DCM/DTM state");
return ret;
}
switch (req_state) {
case DCM_UNBLANK:
if (mfd->dcm_state == DCM_UNINIT &&
!mfd->panel_power_on && mfd->mdp.on_fnc) {
ret = mfd->mdp.on_fnc(mfd);
if (ret == 0) {
mfd->panel_power_on = true;
mfd->dcm_state = DCM_UNBLANK;
}
}
break;
case DCM_ENTER:
if (mfd->dcm_state == DCM_UNBLANK) {
/*
* Keep unblank path available for only
* DCM operation
*/
mfd->panel_power_on = false;
mfd->dcm_state = DCM_ENTER;
}
break;
case DCM_EXIT:
if (mfd->dcm_state == DCM_ENTER) {
/* Release the unblank path for exit */
mfd->panel_power_on = true;
mfd->dcm_state = DCM_EXIT;
}
break;
case DCM_BLANK:
if ((mfd->dcm_state == DCM_EXIT ||
mfd->dcm_state == DCM_UNBLANK) &&
mfd->panel_power_on && mfd->mdp.off_fnc) {
ret = mfd->mdp.off_fnc(mfd);
if (ret == 0) {
mfd->panel_power_on = false;
mfd->dcm_state = DCM_UNINIT;
}
}
break;
case DTM_ENTER:
if (mfd->dcm_state == DCM_UNINIT)
mfd->dcm_state = DTM_ENTER;
break;
case DTM_EXIT:
if (mfd->dcm_state == DTM_ENTER)
mfd->dcm_state = DCM_UNINIT;
break;
}
return ret;
}
static int mdss_fb_cursor(struct fb_info *info, void __user *p)
{
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par;
struct fb_cursor cursor;
int ret;
if (!mfd->mdp.cursor_update)
return -ENODEV;
ret = copy_from_user(&cursor, p, sizeof(cursor));
if (ret)
return ret;
return mfd->mdp.cursor_update(mfd, &cursor);
}
static int mdss_fb_set_lut(struct fb_info *info, void __user *p)
{
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par;
struct fb_cmap cmap;
int ret;
if (!mfd->mdp.lut_update)
return -ENODEV;
ret = copy_from_user(&cmap, p, sizeof(cmap));
if (ret)
return ret;
mfd->mdp.lut_update(mfd, &cmap);
return 0;
}
/**
* mdss_fb_sync_get_fence() - get fence from timeline
* @timeline: Timeline to create the fence on
* @fence_name: Name of the fence that will be created for debugging
* @val: Timeline value at which the fence will be signaled
*
* Function returns a fence on the timeline given with the name provided.
* The fence created will be signaled when the timeline is advanced.
*/
struct sync_fence *mdss_fb_sync_get_fence(struct sw_sync_timeline *timeline,
const char *fence_name, int val)
{
struct sync_pt *sync_pt;
struct sync_fence *fence;
pr_debug("%s: buf sync fence timeline=%d\n", fence_name, val);
sync_pt = sw_sync_pt_create(timeline, val);
if (sync_pt == NULL) {
pr_err("%s: cannot create sync point\n", fence_name);
return NULL;
}
/* create fence */
fence = sync_fence_create(fence_name, sync_pt);
if (fence == NULL) {
sync_pt_free(sync_pt);
pr_err("%s: cannot create fence\n", fence_name);
return NULL;
}
return fence;
}
static int mdss_fb_handle_buf_sync_ioctl(struct msm_sync_pt_data *sync_pt_data,
struct mdp_buf_sync *buf_sync)
{
int i, ret = 0;
int acq_fen_fd[MDP_MAX_FENCE_FD];
struct sync_fence *fence, *rel_fence, *retire_fence;
int rel_fen_fd;
int retire_fen_fd;
int val;
if ((buf_sync->acq_fen_fd_cnt > MDP_MAX_FENCE_FD) ||
(sync_pt_data->timeline == NULL))
return -EINVAL;
if (buf_sync->acq_fen_fd_cnt)
ret = copy_from_user(acq_fen_fd, buf_sync->acq_fen_fd,
buf_sync->acq_fen_fd_cnt * sizeof(int));
if (ret) {
pr_err("%s: copy_from_user failed", sync_pt_data->fence_name);
return ret;
}
if (sync_pt_data->acq_fen_cnt) {
pr_warn("%s: currently %d fences active. waiting...\n",
sync_pt_data->fence_name,
sync_pt_data->acq_fen_cnt);
mdss_fb_wait_for_fence(sync_pt_data);
}
mutex_lock(&sync_pt_data->sync_mutex);
for (i = 0; i < buf_sync->acq_fen_fd_cnt; i++) {
fence = sync_fence_fdget(acq_fen_fd[i]);
if (fence == NULL) {
pr_err("%s: null fence! i=%d fd=%d\n",
sync_pt_data->fence_name, i,
acq_fen_fd[i]);
ret = -EINVAL;
break;
}
sync_pt_data->acq_fen[i] = fence;
}
sync_pt_data->acq_fen_cnt = i;
if (ret)
goto buf_sync_err_1;
val = sync_pt_data->timeline_value + sync_pt_data->threshold +
atomic_read(&sync_pt_data->commit_cnt);
/* Set release fence */
rel_fence = mdss_fb_sync_get_fence(sync_pt_data->timeline,
sync_pt_data->fence_name, val);
if (IS_ERR_OR_NULL(rel_fence)) {
pr_err("%s: unable to retrieve release fence\n",
sync_pt_data->fence_name);
ret = rel_fence ? PTR_ERR(rel_fence) : -ENOMEM;
goto buf_sync_err_1;
}
/* create fd */
rel_fen_fd = get_unused_fd_flags(0);
if (rel_fen_fd < 0) {
pr_err("%s: get_unused_fd_flags failed\n",
sync_pt_data->fence_name);
ret = -EIO;
goto buf_sync_err_2;
}
sync_fence_install(rel_fence, rel_fen_fd);
ret = copy_to_user(buf_sync->rel_fen_fd, &rel_fen_fd, sizeof(int));
if (ret) {
pr_err("%s: copy_to_user failed\n", sync_pt_data->fence_name);
goto buf_sync_err_3;
}
if (!(buf_sync->flags & MDP_BUF_SYNC_FLAG_RETIRE_FENCE))
goto skip_retire_fence;
if (sync_pt_data->get_retire_fence)
retire_fence = sync_pt_data->get_retire_fence(sync_pt_data);
else
retire_fence = NULL;
if (IS_ERR_OR_NULL(retire_fence)) {
val += sync_pt_data->retire_threshold;
retire_fence = mdss_fb_sync_get_fence(
sync_pt_data->timeline, "mdp-retire", val);
}
if (IS_ERR_OR_NULL(retire_fence)) {
pr_err("%s: unable to retrieve retire fence\n",
sync_pt_data->fence_name);
ret = retire_fence ? PTR_ERR(rel_fence) : -ENOMEM;
goto buf_sync_err_3;
}
retire_fen_fd = get_unused_fd_flags(0);
if (retire_fen_fd < 0) {
pr_err("%s: get_unused_fd_flags failed for retire fence\n",
sync_pt_data->fence_name);
ret = -EIO;
sync_fence_put(retire_fence);
goto buf_sync_err_3;
}
sync_fence_install(retire_fence, retire_fen_fd);
ret = copy_to_user(buf_sync->retire_fen_fd, &retire_fen_fd,
sizeof(int));
if (ret) {
pr_err("%s: copy_to_user failed for retire fence\n",
sync_pt_data->fence_name);
put_unused_fd(retire_fen_fd);
sync_fence_put(retire_fence);
goto buf_sync_err_3;
}
skip_retire_fence:
mutex_unlock(&sync_pt_data->sync_mutex);
if (buf_sync->flags & MDP_BUF_SYNC_FLAG_WAIT)
mdss_fb_wait_for_fence(sync_pt_data);
return ret;
buf_sync_err_3:
put_unused_fd(rel_fen_fd);
buf_sync_err_2:
sync_fence_put(rel_fence);
buf_sync_err_1:
for (i = 0; i < sync_pt_data->acq_fen_cnt; i++)
sync_fence_put(sync_pt_data->acq_fen[i]);
sync_pt_data->acq_fen_cnt = 0;
mutex_unlock(&sync_pt_data->sync_mutex);
return ret;
}
static int mdss_fb_display_commit(struct fb_info *info,
unsigned long *argp)
{
int ret;
struct mdp_display_commit disp_commit;
ret = copy_from_user(&disp_commit, argp,
sizeof(disp_commit));
if (ret) {
pr_err("%s:copy_from_user failed", __func__);
return ret;
}
ret = mdss_fb_pan_display_ex(info, &disp_commit);
return ret;
}
static int __ioctl_wait_idle(struct msm_fb_data_type *mfd, u32 cmd)
{
int ret = 0;
if (mfd->wait_for_kickoff &&
((cmd == MSMFB_OVERLAY_PREPARE) ||
(cmd == MSMFB_BUFFER_SYNC) ||
(cmd == MSMFB_OVERLAY_SET))) {
ret = mdss_fb_wait_for_kickoff(mfd);
} else if ((cmd != MSMFB_VSYNC_CTRL) &&
(cmd != MSMFB_OVERLAY_VSYNC_CTRL) &&
(cmd != MSMFB_ASYNC_BLIT) &&
(cmd != MSMFB_BLIT) &&
(cmd != MSMFB_NOTIFY_UPDATE) &&
(cmd != MSMFB_OVERLAY_PREPARE)) {
ret = mdss_fb_pan_idle(mfd);
}
if (ret)
pr_debug("Shutdown pending. Aborting operation %x\n", cmd);
return ret;
}
static int mdss_fb_ioctl(struct fb_info *info, unsigned int cmd,
unsigned long arg)
{
struct msm_fb_data_type *mfd;
void __user *argp = (void __user *)arg;
struct mdp_page_protection fb_page_protection;
int ret = -ENOSYS;
struct mdp_buf_sync buf_sync;
struct msm_sync_pt_data *sync_pt_data = NULL;
unsigned int dsi_mode = 0;
if (!info || !info->par)
return -EINVAL;
mfd = (struct msm_fb_data_type *)info->par;
if (!mfd)
return -EINVAL;
if (mfd->shutdown_pending)
return -EPERM;
atomic_inc(&mfd->ioctl_ref_cnt);
mdss_fb_power_setting_idle(mfd);
ret = __ioctl_wait_idle(mfd, cmd);
if (ret)
goto exit;
switch (cmd) {
case MSMFB_CURSOR:
ret = mdss_fb_cursor(info, argp);
break;
case MSMFB_SET_LUT:
ret = mdss_fb_set_lut(info, argp);
break;
case MSMFB_GET_PAGE_PROTECTION:
fb_page_protection.page_protection =
mfd->mdp_fb_page_protection;
ret = copy_to_user(argp, &fb_page_protection,
sizeof(fb_page_protection));
if (ret)
goto exit;
break;
case MSMFB_BUFFER_SYNC:
ret = copy_from_user(&buf_sync, argp, sizeof(buf_sync));
if (ret)
goto exit;
if ((!mfd->op_enable) || (!mfd->panel_power_on)) {
ret = -EPERM;
goto exit;
}
if (mfd->mdp.get_sync_fnc)
sync_pt_data = mfd->mdp.get_sync_fnc(mfd, &buf_sync);
if (!sync_pt_data)
sync_pt_data = &mfd->mdp_sync_pt_data;
ret = mdss_fb_handle_buf_sync_ioctl(sync_pt_data, &buf_sync);
if (!ret)
ret = copy_to_user(argp, &buf_sync, sizeof(buf_sync));
break;
case MSMFB_NOTIFY_UPDATE:
ret = mdss_fb_notify_update(mfd, argp);
break;
case MSMFB_DISPLAY_COMMIT:
ret = mdss_fb_display_commit(info, argp);
break;
case MSMFB_LPM_ENABLE:
ret = copy_from_user(&dsi_mode, argp, sizeof(dsi_mode));
if (ret) {
pr_err("%s: MSMFB_LPM_ENABLE ioctl failed\n", __func__);
goto exit;
}
ret = mdss_fb_lpm_enable(mfd, dsi_mode);
break;
default:
if (mfd->mdp.ioctl_handler)
ret = mfd->mdp.ioctl_handler(mfd, cmd, argp);
break;
}
if (ret == -ENOSYS)
pr_err("unsupported ioctl (%x)\n", cmd);
exit:
if (!atomic_dec_return(&mfd->ioctl_ref_cnt))
wake_up_all(&mfd->ioctl_q);
return ret;
}
struct fb_info *msm_fb_get_writeback_fb(void)
{
int c = 0;
for (c = 0; c < fbi_list_index; ++c) {
struct msm_fb_data_type *mfd;
mfd = (struct msm_fb_data_type *)fbi_list[c]->par;
if (mfd->panel.type == WRITEBACK_PANEL)
return fbi_list[c];
}
return NULL;
}
EXPORT_SYMBOL(msm_fb_get_writeback_fb);
static int mdss_fb_register_extra_panel(struct platform_device *pdev,
struct mdss_panel_data *pdata)
{
struct mdss_panel_data *fb_pdata;
fb_pdata = dev_get_platdata(&pdev->dev);
if (!fb_pdata) {
pr_err("framebuffer device %s contains invalid panel data\n",
dev_name(&pdev->dev));
return -EINVAL;
}
if (fb_pdata->next) {
pr_err("split panel already setup for framebuffer device %s\n",
dev_name(&pdev->dev));
return -EEXIST;
}
fb_pdata->next = pdata;
return 0;
}
int mdss_register_panel(struct platform_device *pdev,
struct mdss_panel_data *pdata)
{
struct platform_device *fb_pdev, *mdss_pdev;
struct device_node *node;
int rc = 0;
bool master_panel = true;
if (!pdev || !pdev->dev.of_node) {
pr_err("Invalid device node\n");
return -ENODEV;
}
if (!mdp_instance) {
pr_err("mdss mdp resource not initialized yet\n");
return -EPROBE_DEFER;
}
node = of_parse_phandle(pdev->dev.of_node, "qcom,mdss-fb-map", 0);
if (!node) {
pr_err("Unable to find fb node for device: %s\n",
pdev->name);
return -ENODEV;
}
mdss_pdev = of_find_device_by_node(node->parent);
if (!mdss_pdev) {
pr_err("Unable to find mdss for node: %s\n", node->full_name);
rc = -ENODEV;
goto mdss_notfound;
}
fb_pdev = of_find_device_by_node(node);
if (fb_pdev) {
rc = mdss_fb_register_extra_panel(fb_pdev, pdata);
if (rc == 0)
master_panel = false;
} else {
pr_info("adding framebuffer device %s\n", dev_name(&pdev->dev));
fb_pdev = of_platform_device_create(node, NULL,
&mdss_pdev->dev);
if (fb_pdev)
fb_pdev->dev.platform_data = pdata;
}
if (master_panel && mdp_instance->panel_register_done)
mdp_instance->panel_register_done(pdata);
mdss_notfound:
of_node_put(node);
return rc;
}
EXPORT_SYMBOL(mdss_register_panel);
int mdss_fb_register_mdp_instance(struct msm_mdp_interface *mdp)
{
if (mdp_instance) {
pr_err("multiple MDP instance registration");
return -EINVAL;
}
mdp_instance = mdp;
return 0;
}
EXPORT_SYMBOL(mdss_fb_register_mdp_instance);
int mdss_fb_get_phys_info(unsigned long *start, unsigned long *len, int fb_num)
{
struct fb_info *info;
struct msm_fb_data_type *mfd;
if (fb_num >= MAX_FBI_LIST)
return -EINVAL;
info = fbi_list[fb_num];
if (!info)
return -ENOENT;
mfd = (struct msm_fb_data_type *)info->par;
if (!mfd)
return -ENODEV;
if (mfd->iova)
*start = mfd->iova;
else
*start = info->fix.smem_start;
*len = info->fix.smem_len;
return 0;
}
EXPORT_SYMBOL(mdss_fb_get_phys_info);
int __init mdss_fb_init(void)
{
int rc = -ENODEV;
if (platform_driver_register(&mdss_fb_driver))
return rc;
return 0;
}
module_init(mdss_fb_init);
| RenderBroken/msm8974_motox2014_render_kernel | drivers/video/msm/mdss/mdss_fb.c | C | gpl-2.0 | 82,534 | 24.687519 | 81 | 0.646085 | false |
<?php
/**
* Base class for columns containing action links for items.
*
* @since 2.2.6
*/
abstract class CPAC_Column_Actions extends CPAC_Column {
/**
* Get a list of action links for an item (e.g. post) ID.
*
* @since 2.2.6
*
* @param int $item_id Item ID to get the list of actions for.
* @return array List of actions ([action name] => [action link]).
*/
abstract public function get_actions( $item_id );
/**
* @see CPAC_Column::init()
* @since 2.2.6
*/
public function init() {
parent::init();
// Properties
$this->properties['type'] = 'column-actions';
$this->properties['label'] = __( 'Actions', 'cpac' );
// Options
$this->options['use_icons'] = false;
}
/**
* @see CPAC_Column::get_value()
* @since 2.2.6
*/
public function get_value( $post_id ) {
$actions = $this->get_raw_value( $post_id );
if ( ! empty( $this->options->use_icons ) ) {
return implode( '', $this->convert_actions_to_icons( $actions ) );
}
return implode( ' | ', $actions );
}
/**
* @see CPAC_Column::get_value()
* @since 2.2.6
*/
public function get_raw_value( $post_id ) {
/**
* Filter the action links for the actions column
*
* @since 2.2.9
*
* @param array List of actions ([action name] => [action link]).
* @param CPAC_Column_Actions $column_instance Column object.
*/
return apply_filters( 'cac/column/actions/action_links', $this->get_actions( $post_id ), $this );
}
/**
* @see CPAC_Column::display_settings()
* @since 2.2.6
*/
public function display_settings() {
parent::display_settings();
$this->display_field_use_icons();
}
/**
* Display the settings field for using icons instead of text links.
*
* @since 2.2.6
*/
public function display_field_use_icons() {
?>
<tr class="column_editing">
<?php $this->label_view( __( 'Use icons?', 'cpac' ), __( 'Use icons instead of text for displaying the actions.', 'cpac' ), 'use_icons' ); ?>
<td class="input">
<label for="<?php $this->attr_id( 'use_icons' ); ?>-yes">
<input type="radio" value="1" name="<?php $this->attr_name( 'use_icons' ); ?>" id="<?php $this->attr_id( 'use_icons' ); ?>-yes"<?php checked( $this->options->use_icons, '1' ); ?> />
<?php _e( 'Yes'); ?>
</label>
<label for="<?php $this->attr_id( 'use_icons' ); ?>-no">
<input type="radio" value="" name="<?php $this->attr_name( 'use_icons' ); ?>" id="<?php $this->attr_id( 'use_icons' ); ?>-no"<?php checked( $this->options->use_icons, '' ); ?> />
<?php _e( 'No'); ?>
</label>
</td>
</tr>
<?php
}
/**
* Convert items from a list of action links to icons (if they have an icon).
*
* @since 2.2.6
*
* @param array $actions List of actions ([action name] => [action link]).
* @return array List of actions ([action name] => [action icon link]).
*/
public function convert_actions_to_icons( $actions ) {
$icons = $this->get_actions_icons();
foreach ( $actions as $action => $link ) {
if ( isset( $icons[ $action ] ) ) {
// Add mandatory "class" HTML attribute
if ( strpos( $link, 'class=' ) === false ) {
$link = str_replace( '<a ', '<a class="" ', $link );
}
// Add icon and tooltip classes
$link = preg_replace( '/class=["\'](.*?)["\']/', 'class="$1 cpac-tip button cpac-button-action dashicons hide-content dashicons-' . $icons[ $action ] . '"', $link, 1 );
// Add tooltip title
$link = preg_replace_callback( '/>(.*?)<\/a>/', array( $this, 'add_link_tooltip' ), $link );
$actions[ $action ] = $link;
}
}
return $actions;
}
/**
* Add the tooltip data attribute to the link
* Callback for preg_replace_callback
*
* @since 2.2.6.1
*
* @param array $matches Matches information from preg_replace_callback
* @return string Link part with tooltip attribute
*/
public function add_link_tooltip( $matches ) {
return ' data-tip="' . esc_attr( $matches[1] ) . '">' . $matches[1] . '</a>';
}
/**
* Get a list of action names and their corresponding dashicons.
*
* @since 2.2.6
*
* @return array List of actions and icons ([action] => [dashicon]).
*/
public function get_actions_icons() {
return array(
'edit' => 'edit',
'trash' => 'trash',
'delete' => 'trash',
'untrash' => 'undo',
'view' => 'visibility',
'inline hide-if-no-js' => 'welcome-write-blog'
);
}
} | Click3X/000276_Friendshop | wp-content/plugins/codepress-admin-columns/classes/column/actions.php | PHP | gpl-2.0 | 4,538 | 25.349398 | 186 | 0.559498 | false |
/* Copyright (c) 2011-2014, 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.
*/
#ifndef _SLIM_MSM_H
#define _SLIM_MSM_H
#include <linux/irq.h>
#include <linux/kthread.h>
#include <soc/qcom/msm_qmi_interface.h>
#include <soc/qcom/subsystem_notif.h>
#include <linux/ipc_logging.h>
#define SLIM_MSGQ_BUF_LEN 40
#define MSM_TX_BUFS 32
#define SLIM_USR_MC_GENERIC_ACK 0x25
#define SLIM_USR_MC_MASTER_CAPABILITY 0x0
#define SLIM_USR_MC_REPORT_SATELLITE 0x1
#define SLIM_USR_MC_ADDR_QUERY 0xD
#define SLIM_USR_MC_ADDR_REPLY 0xE
#define SLIM_USR_MC_DEFINE_CHAN 0x20
#define SLIM_USR_MC_DEF_ACT_CHAN 0x21
#define SLIM_USR_MC_CHAN_CTRL 0x23
#define SLIM_USR_MC_RECONFIG_NOW 0x24
#define SLIM_USR_MC_REQ_BW 0x28
#define SLIM_USR_MC_CONNECT_SRC 0x2C
#define SLIM_USR_MC_CONNECT_SINK 0x2D
#define SLIM_USR_MC_DISCONNECT_PORT 0x2E
#define SLIM_USR_MC_REPEAT_CHANGE_VALUE 0x0
#define MSM_SLIM_VE_MAX_MAP_ADDR 0xFFF
#define SLIM_MAX_VE_SLC_BYTES 16
#define MSM_SLIM_AUTOSUSPEND MSEC_PER_SEC
#define MSM_SLIM_DESC_NUM 32
#define MSM_SLIM_PERF_SUMM_THRESHOLD 0x8000
#define MSM_SLIM_NPORTS 24
#define MSM_SLIM_NCHANS 32
#define QC_MFGID_LSB 0x2
#define QC_MFGID_MSB 0x17
#define QC_CHIPID_SL 0x10
#define QC_DEVID_SAT1 0x3
#define QC_DEVID_SAT2 0x4
#define QC_DEVID_PGD 0x5
#define SLIM_MSG_ASM_FIRST_WORD(l, mt, mc, dt, ad) \
((l) | ((mt) << 5) | ((mc) << 8) | ((dt) << 15) | ((ad) << 16))
#define INIT_MX_RETRIES 10
#define DEF_RETRY_MS 10
#define MSM_CONCUR_MSG 8
#define SAT_CONCUR_MSG 8
#define DEF_WATERMARK (8 << 1)
#define DEF_ALIGN 0
#define DEF_PACK (1 << 6)
#define ENABLE_PORT 1
#define DEF_BLKSZ 0
#define DEF_TRANSZ 0
#define SAT_MAGIC_LSB 0xD9
#define SAT_MAGIC_MSB 0xC5
#define SAT_MSG_VER 0x1
#define SAT_MSG_PROT 0x1
#define MSM_SAT_SUCCSS 0x20
#define MSM_MAX_NSATS 2
#define MSM_MAX_SATCH 32
#define SLIMBUS_QMI_SVC_ID 0x0301
#define SLIMBUS_QMI_SVC_V1 1
#define SLIMBUS_QMI_INS_ID 0
#define PGD_THIS_EE(r, v) ((v) ? PGD_THIS_EE_V2(r) : PGD_THIS_EE_V1(r))
#define PGD_PORT(r, p, v) ((v) ? PGD_PORT_V2(r, p) : PGD_PORT_V1(r, p))
#define CFG_PORT(r, v) ((v) ? CFG_PORT_V2(r) : CFG_PORT_V1(r))
#define PGD_THIS_EE_V2(r) (dev->base + (r ## _V2) + (dev->ee * 0x1000))
#define PGD_PORT_V2(r, p) (dev->base + (r ## _V2) + ((p) * 0x1000))
#define CFG_PORT_V2(r) ((r ## _V2))
enum comp_reg_v2 {
COMP_CFG_V2 = 4,
COMP_TRUST_CFG_V2 = 0x3000,
};
enum pgd_reg_v2 {
PGD_CFG_V2 = 0x800,
PGD_STAT_V2 = 0x804,
PGD_INT_EN_V2 = 0x810,
PGD_INT_STAT_V2 = 0x814,
PGD_INT_CLR_V2 = 0x818,
PGD_OWN_EEn_V2 = 0x300C,
PGD_PORT_INT_EN_EEn_V2 = 0x5000,
PGD_PORT_INT_ST_EEn_V2 = 0x5004,
PGD_PORT_INT_CL_EEn_V2 = 0x5008,
PGD_PORT_CFGn_V2 = 0x14000,
PGD_PORT_STATn_V2 = 0x14004,
PGD_PORT_PARAMn_V2 = 0x14008,
PGD_PORT_BLKn_V2 = 0x1400C,
PGD_PORT_TRANn_V2 = 0x14010,
PGD_PORT_MCHANn_V2 = 0x14014,
PGD_PORT_PSHPLLn_V2 = 0x14018,
PGD_PORT_PC_CFGn_V2 = 0x8000,
PGD_PORT_PC_VALn_V2 = 0x8004,
PGD_PORT_PC_VFR_TSn_V2 = 0x8008,
PGD_PORT_PC_VFR_STn_V2 = 0x800C,
PGD_PORT_PC_VFR_CLn_V2 = 0x8010,
PGD_IE_STAT_V2 = 0x820,
PGD_VE_STAT_V2 = 0x830,
};
#define PGD_THIS_EE_V1(r) (dev->base + (r ## _V1) + (dev->ee * 16))
#define PGD_PORT_V1(r, p) (dev->base + (r ## _V1) + ((p) * 32))
#define CFG_PORT_V1(r) ((r ## _V1))
enum comp_reg_v1 {
COMP_CFG_V1 = 0,
COMP_TRUST_CFG_V1 = 0x14,
};
enum pgd_reg_v1 {
PGD_CFG_V1 = 0x1000,
PGD_STAT_V1 = 0x1004,
PGD_INT_EN_V1 = 0x1010,
PGD_INT_STAT_V1 = 0x1014,
PGD_INT_CLR_V1 = 0x1018,
PGD_OWN_EEn_V1 = 0x1020,
PGD_PORT_INT_EN_EEn_V1 = 0x1030,
PGD_PORT_INT_ST_EEn_V1 = 0x1034,
PGD_PORT_INT_CL_EEn_V1 = 0x1038,
PGD_PORT_CFGn_V1 = 0x1080,
PGD_PORT_STATn_V1 = 0x1084,
PGD_PORT_PARAMn_V1 = 0x1088,
PGD_PORT_BLKn_V1 = 0x108C,
PGD_PORT_TRANn_V1 = 0x1090,
PGD_PORT_MCHANn_V1 = 0x1094,
PGD_PORT_PSHPLLn_V1 = 0x1098,
PGD_PORT_PC_CFGn_V1 = 0x1600,
PGD_PORT_PC_VALn_V1 = 0x1604,
PGD_PORT_PC_VFR_TSn_V1 = 0x1608,
PGD_PORT_PC_VFR_STn_V1 = 0x160C,
PGD_PORT_PC_VFR_CLn_V1 = 0x1610,
PGD_IE_STAT_V1 = 0x1700,
PGD_VE_STAT_V1 = 0x1710,
};
enum msm_slim_port_status {
MSM_PORT_OVERFLOW = 1 << 2,
MSM_PORT_UNDERFLOW = 1 << 3,
MSM_PORT_DISCONNECT = 1 << 19,
};
enum msm_ctrl_state {
MSM_CTRL_AWAKE,
MSM_CTRL_IDLE,
MSM_CTRL_ASLEEP,
MSM_CTRL_DOWN,
};
enum msm_slim_msgq {
MSM_MSGQ_DISABLED,
MSM_MSGQ_RESET,
MSM_MSGQ_ENABLED,
MSM_MSGQ_DOWN,
};
struct msm_slim_sps_bam {
unsigned long hdl;
void __iomem *base;
int irq;
};
struct msm_slim_endp {
struct sps_pipe *sps;
struct sps_connect config;
struct sps_register_event event;
struct sps_mem_buffer buf;
bool connected;
int port_b;
};
struct msm_slim_qmi {
struct qmi_handle *handle;
struct task_struct *task;
struct task_struct *slave_thread;
struct completion slave_notify;
struct kthread_work kwork;
struct kthread_worker kworker;
struct completion qmi_comp;
struct notifier_block nb;
struct work_struct ssr_down;
struct work_struct ssr_up;
};
struct msm_slim_ss {
struct notifier_block nb;
void *ssr;
enum msm_ctrl_state state;
};
struct msm_slim_pdata {
u32 apps_pipes;
u32 eapc;
};
struct msm_slim_ctrl {
struct slim_controller ctrl;
struct slim_framer framer;
struct device *dev;
void __iomem *base;
struct resource *slew_mem;
struct resource *bam_mem;
u32 curr_bw;
u8 msg_cnt;
u32 tx_buf[10];
u8 rx_msgs[MSM_CONCUR_MSG][SLIM_MSGQ_BUF_LEN];
int tx_tail;
int tx_head;
spinlock_t rx_lock;
int head;
int tail;
int irq;
int err;
int ee;
struct completion **wr_comp;
struct msm_slim_sat *satd[MSM_MAX_NSATS];
struct msm_slim_endp *pipes;
struct msm_slim_sps_bam bam;
struct msm_slim_endp tx_msgq;
struct msm_slim_endp rx_msgq;
struct completion rx_msgq_notify;
struct task_struct *rx_msgq_thread;
struct clk *rclk;
struct clk *hclk;
struct mutex tx_lock;
struct mutex tx_buf_lock;
u8 pgdla;
enum msm_slim_msgq use_rx_msgqs;
enum msm_slim_msgq use_tx_msgqs;
int port_nums;
struct completion reconf;
bool reconf_busy;
bool chan_active;
enum msm_ctrl_state state;
struct completion ctrl_up;
int nsats;
u32 ver;
struct msm_slim_qmi qmi;
struct msm_slim_pdata pdata;
struct msm_slim_ss ext_mdm;
struct msm_slim_ss dsp;
int default_ipc_log_mask;
int ipc_log_mask;
bool sysfs_created;
void *ipc_slimbus_log;
};
struct msm_sat_chan {
u8 chan;
u16 chanh;
int req_rem;
int req_def;
bool reconf;
};
struct msm_slim_sat {
struct slim_device satcl;
struct msm_slim_ctrl *dev;
struct workqueue_struct *wq;
struct work_struct wd;
u8 sat_msgs[SAT_CONCUR_MSG][40];
struct msm_sat_chan *satch;
u8 nsatch;
bool sent_capability;
bool pending_reconf;
bool pending_capability;
int shead;
int stail;
spinlock_t lock;
};
enum rsc_grp {
EE_MGR_RSC_GRP = 1 << 10,
EE_NGD_2 = 2 << 6,
EE_NGD_1 = 0,
};
#define IPC_SLIMBUS_LOG_PAGES 5
enum {
FATAL_LEV = 0U,
ERR_LEV = 1U,
WARN_LEV = 2U,
INFO_LEV = 3U,
DBG_LEV = 4U,
};
#define SLIM_DBG(dev, x...) do { \
pr_debug(x); \
if (dev->ipc_slimbus_log && dev->ipc_log_mask >= DBG_LEV) { \
ipc_log_string(dev->ipc_slimbus_log, x); \
} \
} while (0)
#define SLIM_INFO(dev, x...) do { \
pr_debug(x); \
if (dev->ipc_slimbus_log && dev->ipc_log_mask >= INFO_LEV) {\
ipc_log_string(dev->ipc_slimbus_log, x); \
} \
} while (0)
#define SLIM_WARN(dev, x...) do { \
pr_warn(x); \
if (dev->ipc_slimbus_log && dev->ipc_log_mask >= WARN_LEV) \
ipc_log_string(dev->ipc_slimbus_log, x); \
} while (0)
#define SLIM_ERR(dev, x...) do { \
pr_err(x); \
if (dev->ipc_slimbus_log && dev->ipc_log_mask >= ERR_LEV) { \
ipc_log_string(dev->ipc_slimbus_log, x); \
dev->default_ipc_log_mask = dev->ipc_log_mask; \
dev->ipc_log_mask = FATAL_LEV; \
} \
} while (0)
#define SLIM_RST_LOGLVL(dev) { \
dev->ipc_log_mask = dev->default_ipc_log_mask; \
}
int msm_slim_rx_enqueue(struct msm_slim_ctrl *dev, u32 *buf, u8 len);
int msm_slim_rx_dequeue(struct msm_slim_ctrl *dev, u8 *buf);
int msm_slim_get_ctrl(struct msm_slim_ctrl *dev);
void msm_slim_put_ctrl(struct msm_slim_ctrl *dev);
irqreturn_t msm_slim_port_irq_handler(struct msm_slim_ctrl *dev, u32 pstat);
int msm_slim_init_endpoint(struct msm_slim_ctrl *dev, struct msm_slim_endp *ep);
void msm_slim_free_endpoint(struct msm_slim_endp *ep);
void msm_hw_set_port(struct msm_slim_ctrl *dev, u8 pn);
int msm_alloc_port(struct slim_controller *ctrl, u8 pn);
void msm_dealloc_port(struct slim_controller *ctrl, u8 pn);
int msm_slim_connect_pipe_port(struct msm_slim_ctrl *dev, u8 pn);
enum slim_port_err msm_slim_port_xfer_status(struct slim_controller *ctr,
u8 pn, phys_addr_t *done_buf, u32 *done_len);
int msm_slim_port_xfer(struct slim_controller *ctrl, u8 pn, phys_addr_t iobuf,
u32 len, struct completion *comp);
int msm_send_msg_buf(struct msm_slim_ctrl *dev, u32 *buf, u8 len, u32 tx_reg);
u32 *msm_get_msg_buf(struct msm_slim_ctrl *dev, int len,
struct completion *comp);
u32 *msm_slim_manage_tx_msgq(struct msm_slim_ctrl *dev, bool getbuf,
struct completion *comp);
int msm_slim_rx_msgq_get(struct msm_slim_ctrl *dev, u32 *data, int offset);
int msm_slim_sps_init(struct msm_slim_ctrl *dev, struct resource *bam_mem,
u32 pipe_reg, bool remote);
void msm_slim_sps_exit(struct msm_slim_ctrl *dev, bool dereg);
int msm_slim_connect_endp(struct msm_slim_ctrl *dev,
struct msm_slim_endp *endpoint,
struct completion *notify);
void msm_slim_disconnect_endp(struct msm_slim_ctrl *dev,
struct msm_slim_endp *endpoint,
enum msm_slim_msgq *msgq_flag);
void msm_slim_qmi_exit(struct msm_slim_ctrl *dev);
int msm_slim_qmi_init(struct msm_slim_ctrl *dev, bool apps_is_master);
int msm_slim_qmi_power_request(struct msm_slim_ctrl *dev, bool active);
int msm_slim_qmi_check_framer_request(struct msm_slim_ctrl *dev);
#endif
| Bigcountry907/kernel_htc_a32eul | drivers/slimbus/slim-msm.h | C | gpl-2.0 | 10,205 | 25.997354 | 80 | 0.682901 | false |
//--------------------------------------------------------
// Función que valida que no se incluyan comillas simples
// en los textos ya que dañana la consulta SQL
//--------------------------------------------------------
function ue_validarcomillas(valor)
{
val = valor.value;
longitud = val.length;
texto = "";
textocompleto = "";
for(r=0;r<=longitud;r++)
{
texto = valor.value.substring(r,r+1);
if((texto != "'")&&(texto != '"')&&(texto != "\\"))
{
textocompleto += texto;
}
}
valor.value=textocompleto;
}
//--------------------------------------------------------
// Función que valida que solo se incluyan números en los textos
//--------------------------------------------------------
function ue_validarnumero(valor)
{
val = valor.value;
longitud = val.length;
texto = "";
textocompleto = "";
for(r=0;r<=longitud;r++)
{
texto = valor.value.substring(r,r+1);
if((texto=="0")||(texto=="1")||(texto=="2")||(texto=="3")||(texto=="4")||(texto=="5")||(texto=="6")||(texto=="7")||(texto=="8")||(texto=="9"))
{
textocompleto += texto;
}
}
valor.value=textocompleto;
}
//--------------------------------------------------------
// Función que valida que el texto no esté vacio
//--------------------------------------------------------
function ue_validarvacio(valor)
{
var texto;
while(''+valor.charAt(0)==' ')
{
valor=valor.substring(1,valor.length)
}
texto = valor;
return texto;
}
//--------------------------------------------------------
// Función que rellena un campo con ceros a la izquierda
//--------------------------------------------------------
function ue_rellenarcampo(valor,maxlon)
{
var total;
var auxiliar;
var longitud;
var index;
total=0;
auxiliar=valor.value;
longitud=valor.value.length;
total=maxlon-longitud;
if (total < maxlon)
{
for (index=0;index<total;index++)
{
auxiliar="0"+auxiliar;
}
valor.value = auxiliar;
}
}
//--------------------------------------------------------
// Función que formatea un número
//--------------------------------------------------------
function ue_formatonumero(fld, milSep, decSep, e)
{
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;
if (fld.readOnly==true) return false;
if (whichCode == 13) return true; // Enter
if (whichCode == 8) return true; // Return
if (whichCode == 127) return true; // Suprimir
key = String.fromCharCode(whichCode); // Get key value from key code
if (strCheck.indexOf(key) == -1) return false; // Not a valid key
len = fld.value.length;
for(i = 0; i < len; i++)
if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
aux = '';
for(; i < len; i++)
if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
aux += key;
len = aux.length;
if (len == 0) fld.value = '';
if (len == 1) fld.value = '0'+ decSep + '0' + aux;
if (len == 2) fld.value = '0'+ decSep + aux;
if (len > 2) {
aux2 = '';
for (j = 0, i = len - 3; i >= 0; i--) {
if (j == 3) {
aux2 += milSep;
j = 0;
}
aux2 += aux.charAt(i);
j++;
}
fld.value = '';
len2 = aux2.length;
for (i = len2 - 1; i >= 0; i--)
fld.value += aux2.charAt(i);
fld.value += decSep + aux.substr(len - 2, len);
}
return false;
}
//--------------------------------------------------------
// Función que verifica que la fecha no tenga letras
//--------------------------------------------------------
function ue_validarfecha(valor)
{
var texto;
if ((valor=="dd/mm/aaaa")||(valor=="")||(valor=="01/01/1900"))
{
texto="1900-01-01";
}
else
{
texto = valor;
}
return texto;
}
//--------------------------------------------------------
// Función que valida que solo se incluyan números(1234567890),guiones(-) y Espacios en blanco
//--------------------------------------------------------
function ue_validartelefono(valor)
{
val = valor.value;
longitud = val.length;
texto = "";
textocompleto = "";
for(r=0;r<=longitud;r++)
{
texto = valor.value.substring(r,r+1);
if((texto=="0")||(texto=="1")||(texto=="2")||(texto=="3")||(texto=="4")||(texto=="5")||(texto=="6")||(texto=="7")||
(texto=="8")||(texto=="9")||(texto=="-")||(texto==" ")||(texto=="(")||(texto==")"))
{
textocompleto += texto;
}
}
valor.value=textocompleto;
}
//--------------------------------------------------------
// Función que le da formato a la fecha
//--------------------------------------------------------
function ue_formatofecha(d,sep,pat,nums)
{
if(d.valant != d.value)
{
val = d.value
largo = val.length
val = val.split(sep)
val2 = ''
for(r=0;r<val.length;r++)
{
val2 += val[r]
}
if(nums)
{
for(z=0;z<val2.length;z++)
{
if(isNaN(val2.charAt(z)))
{
letra = new RegExp(val2.charAt(z),"g")
val2 = val2.replace(letra,"")
}
}
}
val = ''
val3 = new Array()
for(s=0; s<pat.length; s++)
{
val3[s] = val2.substring(0,pat[s])
val2 = val2.substr(pat[s])
}
for(q=0;q<val3.length; q++)
{
if(q ==0)
{
val = val3[q]
}
else
{
if(val3[q] != "")
{
val += sep + val3[q]
}
}
}
d.value = val
d.valant = val
}
}
//--------------------------------------------------------
// Función que valida el correo electrónico
//--------------------------------------------------------
function ue_validarcorreo(obj)
{
//expresion regular
var filtro=/^[A-Za-z][A-Za-z0-9_]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;
if (obj.length==0)
{
return true;
}
else
{
if(filtro.test(obj)==false)
{
alert("Email No Válido.");
return false;
}
else
{
return true;
}
}
}
//--------------------------------------------------------
// Función que verifica que la fecha 2 sea mayor que la fecha 1
//--------------------------------------------------------
function ue_comparar_fechas(fecha1,fecha2)
{
vali=false;
dia1 = fecha1.substr(0,2);
mes1 = fecha1.substr(3,2);
ano1 = fecha1.substr(6,4);
dia2 = fecha2.substr(0,2);
mes2 = fecha2.substr(3,2);
ano2 = fecha2.substr(6,4);
if (ano1 < ano2)
{
vali = true;
}
else
{
if (ano1 == ano2)
{
if (mes1 < mes2)
{
vali = true;
}
else
{
if (mes1 == mes2)
{
if (dia1 <= dia2)
{
vali = true;
}
}
}
}
}
return vali;
}
//--------------------------------------------------------
// Función que Instancia el objeto ajax
//--------------------------------------------------------
function objetoAjax()
{
var xmlhttp=false;
try
{
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(E)
{
xmlhttp = false;
}
}
if(!xmlhttp && typeof XMLHttpRequest!='undefined')
{
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
//--------------------------------------------------------
// Función que llena unos objeto ocultos para el orden de las consultas de los catálogos
//--------------------------------------------------------
function ue_orden(campo)
{
f=document.formulario;
if(f.campoorden.value==campo)
{
if(f.orden.value=="ASC")
{
f.orden.value="DESC";
}
else
{
f.orden.value="ASC";
}
}
else
{
f.campoorden.value=campo;
f.orden.value="ASC";
}
ue_search();
}
//--------------------------------------------------------
// Función que convierte los montos para poder hacer calculos
//--------------------------------------------------------
function ue_formato_calculo(monto)
{
while(monto.indexOf('.')>0)
{//Elimino todos los puntos o separadores de miles
monto=monto.replace(".","");
}
monto=monto.replace(",",".");
return monto;
}
//--------------------------------------------------------
// Función que actualiza el total de las filas de un campo local
//--------------------------------------------------------
function ue_calcular_total_fila_local(campo)
{
existe=true;
li_i=1;
while(existe)
{
existe=document.getElementById(campo+li_i);
if(existe!=null)
{
li_i=li_i+1;
}
else
{
existe=false;
li_i=li_i-1;
}
}
return li_i
}
//--------------------------------------------------------
// Función que actualiza el total de las filas de un campo de un pagina opener
//--------------------------------------------------------
function ue_calcular_total_fila_opener(campo)
{
existe=true;
li_i=1;
while(existe)
{
existe=opener.document.getElementById(campo+li_i);
if(existe!=null)
{
li_i=li_i+1;
}
else
{
existe=false;
li_i=li_i-1;
}
}
return li_i
}
//--------------------------------------------------------
// Función que verifica si la tecla es enter y llama al metodo ue_search de los catálogos
//--------------------------------------------------------
function ue_mostrar(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13)
{
ue_search();
return false;
}
else
return true
}
//--------------------------------------------------------
// Función que verifica si un campo esta vacio y de ser asi lo mando a ese campo
//--------------------------------------------------------
function ue_validarcampo(campo,mensaje,foco)
{
valido=true;
if(campo=="")
{
alert(mensaje);
foco.focus();
valido=false;
}
return valido;
}
function redondear(cantidad, decimales)
{
var cantidad = parseFloat(cantidad);
var decimales = parseFloat(decimales);
decimales = (!decimales ? 2 : decimales);
primera=Math.round(cantidad * Math.pow(10, decimales+1)) / Math.pow(10, decimales+1);
return Math.round(primera * Math.pow(10, decimales)) / Math.pow(10, decimales);
} | ArrozAlba/huayra | cfg/spg/js/funcion_cfg.js | JavaScript | gpl-2.0 | 10,385 | 21.93318 | 144 | 0.451131 | false |
package edu.stanford.nlp.process;
import java.io.Reader;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.ling.HasWord;
import edu.stanford.nlp.objectbank.TokenizerFactory;
import edu.stanford.nlp.process.WordSegmenter;
/** A tokenizer that works by calling a WordSegmenter.
* This is used for Chinese and Arabic.
*
* @author Galen Andrew
* @author Spence Green
*/
public class WordSegmentingTokenizer extends AbstractTokenizer<HasWord> {
private Iterator<HasWord> wordIter;
private Tokenizer<CoreLabel> tok;
private WordSegmenter wordSegmenter;
public WordSegmentingTokenizer(WordSegmenter segmenter, Reader r) {
this(segmenter, WhitespaceTokenizer.newCoreLabelWhitespaceTokenizer(r));
}
public WordSegmentingTokenizer(WordSegmenter segmenter, Tokenizer<CoreLabel> tokenizer) {
wordSegmenter = segmenter;
tok = tokenizer;
}
@Override
protected HasWord getNext() {
while (wordIter == null || ! wordIter.hasNext()) {
if ( ! tok.hasNext()) {
return null;
}
String s = tok.next().word();
if (s == null) {
return null;
}
List<HasWord> se = wordSegmenter.segment(s);
wordIter = se.iterator();
}
return wordIter.next();
}
public static TokenizerFactory<HasWord> factory(WordSegmenter wordSegmenter) {
return new WordSegmentingTokenizerFactory(wordSegmenter);
}
private static class WordSegmentingTokenizerFactory implements TokenizerFactory<HasWord>, Serializable {
private static final long serialVersionUID = -4697961121607489828L;
private WordSegmenter segmenter;
public WordSegmentingTokenizerFactory(WordSegmenter wordSegmenter) {
segmenter = wordSegmenter;
}
public Iterator<HasWord> getIterator(Reader r) {
return getTokenizer(r);
}
public Tokenizer<HasWord> getTokenizer(Reader r) {
return new WordSegmentingTokenizer(segmenter, r);
}
public Tokenizer<HasWord> getTokenizer(Reader r, String extraOptions) {
setOptions(extraOptions);
return getTokenizer(r);
}
public void setOptions(String options) {}
}
}
| simplyianm/stanford-corenlp | src/main/java/edu/stanford/nlp/process/WordSegmentingTokenizer.java | Java | gpl-2.0 | 2,222 | 27.487179 | 106 | 0.721422 | false |
<?php
/**
* @package Helix3 Framework
* @author L.THEME http://www.ltheme.com
* @copyright Copyright (c) 2010 - 2015 L.THEME
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or Later
*/
//no direct accees
defined ('_JEXEC') or die('resticted aceess');
class Helix3FeatureLogo {
private $helix3;
public $position;
public function __construct( $helix3 ){
$this->helix3 = $helix3;
$this->position = $this->helix3->getParam('logo_position', 'logo');
}
public function renderFeature() {
//Retina Image
if( $this->helix3->getParam('logo_type') == 'image' ) {
jimport('joomla.image.image');
if( $this->helix3->getParam('logo_image') ) {
$path = JPATH_ROOT . '/' . $this->helix3->getParam('logo_image');
} else {
$path = JPATH_ROOT . '/templates/' . $this->helix3->getTemplate() . '/images/presets/' . $this->helix3->Preset() . '/logo.png';
}
if(file_exists($path)) {
$image = new JImage( $path );
$width = $image->getWidth();
$height = $image->getHeight();
} else {
$width = '';
$height = '';
}
}
$html = '';
$custom_logo_class = '';
$sitename = JFactory::getApplication()->get('sitename');
if( $this->helix3->getParam('mobile_logo') ) {
$custom_logo_class = ' hidden-xs';
}
$html .= '<a class="logo" href="' . JURI::base(true) . '/">';
if( $this->helix3->getParam('logo_type') == 'image' ) {
if( $this->helix3->getParam('logo_image') ) {
$html .= '<h1>';
$html .= '<img class="sp-default-logo'. $custom_logo_class .'" src="' . $this->helix3->getParam('logo_image') . '" alt="'. $sitename .'">';
if( $this->helix3->getParam('logo_image_2x') ) {
$html .= '<img class="sp-retina-logo'. $custom_logo_class .'" src="' . $this->helix3->getParam('logo_image_2x') . '" alt="'. $sitename .'" width="' . $width . '" height="' . $height . '">';
}
if( $this->helix3->getParam('mobile_logo') ) {
$html .= '<img class="sp-default-logo visible-xs" src="' . $this->helix3->getParam('mobile_logo') . '" alt="'. $sitename .'">';
}
$html .= '</h1>';
} else {
$html .= '<h1>';
$html .= '<img class="sp-default-logo'. $custom_logo_class .'" src="' . $this->helix3->getTemplateUri() . '/images/presets/' . $this->helix3->Preset() . '/logo.png" alt="'. $sitename .'">';
$html .= '<img class="sp-retina-logo'. $custom_logo_class .'" src="' . $this->helix3->getTemplateUri() . '/images/presets/' . $this->helix3->Preset() . '/logo@2x.png" alt="'. $sitename .'" width="' . $width . '" height="' . $height . '">';
if( $this->helix3->getParam('mobile_logo') ) {
$html .= '<img class="sp-default-logo visible-xs" src="' . $this->helix3->getParam('mobile_logo') . '" alt="'. $sitename .'">';
}
$html .= '</h1>';
}
} else {
if( $this->helix3->getParam('logo_text') ) {
$html .= '<h1>' . $this->helix3->getParam('logo_text') . '</h1>';
} else {
$html .= '<h1>' . $sitename . '</h1>';
}
if( $this->helix3->getParam('logo_slogan') ) {
$html .= '<p class="logo-slogan">' . $this->helix3->getParam('logo_slogan') . '</p>';
}
}
$html .= '</a>';
return $html;
}
} | Caojunkai/arcticfox | tmp/travel/features/logo.php | PHP | gpl-2.0 | 3,157 | 31.895833 | 243 | 0.554007 | false |
/* { dg-do run } */
/* { dg-options "-O2 -mavx512bw -DAVX512BW" } */
/* { dg-require-effective-target avx512bw } */
#include "avx512f-helper.h"
#define SIZE (AVX512F_LEN / 8)
#include "avx512f-mask-type.h"
void
CALC (unsigned char *src1, unsigned char *src2,
unsigned char *dst)
{
int i;
for (i = 0; i < SIZE; i++)
dst[i] = src1[i] < src2[i] ? src1[i] : src2[i];
}
void
TEST (void)
{
int i;
UNION_TYPE (AVX512F_LEN, i_b) src1, src2, res1, res2, res3;
MASK_TYPE mask = MASK_VALUE;
unsigned char res_ref[SIZE];
for (i = 0; i < SIZE; i++)
{
src1.a[i] = i * i;
src2.a[i] = i + 20;
res2.a[i] = DEFAULT_VALUE;
}
res1.x = INTRINSIC (_min_epu8) (src1.x, src2.x);
res2.x = INTRINSIC (_mask_min_epu8) (res2.x, mask, src1.x, src2.x);
res3.x = INTRINSIC (_maskz_min_epu8) (mask, src1.x, src2.x);
CALC (src1.a, src2.a, res_ref);
if (UNION_CHECK (AVX512F_LEN, i_b) (res1, res_ref))
abort ();
MASK_MERGE (i_b) (res_ref, mask, SIZE);
if (UNION_CHECK (AVX512F_LEN, i_b) (res2, res_ref))
abort ();
MASK_ZERO (i_b) (res_ref, mask, SIZE);
if (UNION_CHECK (AVX512F_LEN, i_b) (res3, res_ref))
abort ();
}
| mageec/mageec-gcc | gcc/testsuite/gcc.target/i386/avx512bw-vpminub-2.c | C | gpl-2.0 | 1,175 | 21.596154 | 69 | 0.573617 | false |
/* Copyright (C) 2008 Curtis Gedak
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "../include/Dialog_FileSystem_Label.h"
namespace GParted
{
Dialog_FileSystem_Label::Dialog_FileSystem_Label( const Partition & partition )
{
this ->set_resizable( false ) ;
this ->set_has_separator( false ) ;
this ->set_size_request( 300, 80 ) ;
/* TO TRANSLATORS: dialog title, looks like Set file system label on /dev/hda3 */
this->set_title( String::ucompose( _("Set file system label on %1"), partition.get_path() ) );
{
int top = 0, bottom = 1;
//Create table to hold Label and entry box
Gtk::Table* table(manage(new Gtk::Table()));
table->set_border_width(5);
table->set_col_spacings(10);
get_vbox()->pack_start(*table, Gtk::PACK_SHRINK);
table->attach(*Utils::mk_label("<b>" + Glib::ustring(_("Label:")) + "</b>"),
0, 1,
top, bottom,
Gtk::FILL);
//Create Text entry box
entry = manage(new Gtk::Entry());
entry->set_max_length( Utils::get_filesystem_label_maxlength( partition.filesystem ) ) ;
entry->set_width_chars(20);
entry->set_activates_default(true);
entry->set_text(partition.get_filesystem_label());
entry->select_region(0, entry ->get_text_length());
//Add entry box to table
table->attach(*entry,
1, 2,
top++, bottom++,
Gtk::FILL);
}
this ->add_button( Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL ) ;
this ->add_button( Gtk::Stock::OK, Gtk::RESPONSE_OK ) ;
this ->set_default_response( Gtk::RESPONSE_OK ) ;
this ->show_all_children() ;
}
Dialog_FileSystem_Label::~Dialog_FileSystem_Label()
{
}
Glib::ustring Dialog_FileSystem_Label::get_new_label()
{
return Utils::trim( Glib::ustring( entry ->get_text() ) );
}
} //GParted
| nodakai/gparted | src/Dialog_FileSystem_Label.cc | C++ | gpl-2.0 | 2,325 | 30.849315 | 95 | 0.67828 | false |
/*
* max77693.c - mfd core driver for the Maxim 77693
*
* Copyright (C) 2011 Samsung Electronics
* SangYoung Son <hello.son@smasung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* This driver is based on max8997.c
*/
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/interrupt.h>
#include <linux/mutex.h>
#include <linux/mfd/core.h>
#include <linux/mfd/max77693.h>
#include <linux/mfd/max77693-private.h>
#include <linux/regulator/machine.h>
#include <linux/export.h>
#include <linux/module.h>
#if defined (CONFIG_OF)
#include <linux/of_device.h>
#include <linux/of_gpio.h>
#endif
#define I2C_ADDR_PMIC (0xCC >> 1) /* Charger, Flash LED */
#define I2C_ADDR_MUIC (0x4A >> 1)
#define I2C_ADDR_HAPTIC (0x90 >> 1)
static struct mfd_cell max77693_devs[] = {
{ .name = "max77693-charger", },
{ .name = "max77693-led", },
{ .name = "max77693-muic", },
{ .name = "max77693-safeout", },
{ .name = "max77693-haptic", },
};
int max77693_read_reg(struct i2c_client *i2c, u8 reg, u8 *dest)
{
struct max77693_dev *max77693 = i2c_get_clientdata(i2c);
int ret;
mutex_lock(&max77693->iolock);
ret = i2c_smbus_read_byte_data(i2c, reg);
mutex_unlock(&max77693->iolock);
if (ret < 0)
return ret;
ret &= 0xff;
*dest = ret;
return 0;
}
EXPORT_SYMBOL_GPL(max77693_read_reg);
int max77693_bulk_read(struct i2c_client *i2c, u8 reg, int count, u8 *buf)
{
struct max77693_dev *max77693 = i2c_get_clientdata(i2c);
int ret;
mutex_lock(&max77693->iolock);
ret = i2c_smbus_read_i2c_block_data(i2c, reg, count, buf);
mutex_unlock(&max77693->iolock);
if (ret < 0)
return ret;
return 0;
}
EXPORT_SYMBOL_GPL(max77693_bulk_read);
int max77693_write_reg(struct i2c_client *i2c, u8 reg, u8 value)
{
struct max77693_dev *max77693 = i2c_get_clientdata(i2c);
int ret;
mutex_lock(&max77693->iolock);
ret = i2c_smbus_write_byte_data(i2c, reg, value);
mutex_unlock(&max77693->iolock);
return ret;
}
EXPORT_SYMBOL_GPL(max77693_write_reg);
int max77693_bulk_write(struct i2c_client *i2c, u8 reg, int count, u8 *buf)
{
struct max77693_dev *max77693 = i2c_get_clientdata(i2c);
int ret;
mutex_lock(&max77693->iolock);
ret = i2c_smbus_write_i2c_block_data(i2c, reg, count, buf);
mutex_unlock(&max77693->iolock);
if (ret < 0)
return ret;
return 0;
}
EXPORT_SYMBOL_GPL(max77693_bulk_write);
int max77693_update_reg(struct i2c_client *i2c, u8 reg, u8 val, u8 mask)
{
struct max77693_dev *max77693 = i2c_get_clientdata(i2c);
int ret;
mutex_lock(&max77693->iolock);
ret = i2c_smbus_read_byte_data(i2c, reg);
if (ret >= 0) {
u8 old_val = ret & 0xff;
u8 new_val = (val & mask) | (old_val & (~mask));
ret = i2c_smbus_write_byte_data(i2c, reg, new_val);
}
mutex_unlock(&max77693->iolock);
return ret;
}
EXPORT_SYMBOL_GPL(max77693_update_reg);
static int of_max77693_dt(struct device *dev, struct max77693_platform_data *pdata)
{
// int retval = 0;
struct device_node *np = dev->of_node;
if(!np)
return -EINVAL;
pdata->irq_gpio = of_get_named_gpio_flags(np, "max77693,irq-gpio",
0, &pdata->irq_gpio_flags);
printk(KERN_CRIT "[@@MAX77693@@]%s called, gpio_base = %d",__func__,gpio_to_irq(pdata->irq_gpio));
of_property_read_u32(np, "max77693,irq-base", &pdata->irq_base);
pdata->wakeup = of_property_read_bool(np, "max77693,wakeup");
// retval = of_get_named_gpio(np, "max77693,wc-irq-gpio", 0);
// if (retval < 0)
// pdata->wc_irq_gpio = 0;
// else
// pdata->wc_irq_gpio = retval;
pr_info("%s: irq-gpio: %u \n", __func__, pdata->irq_gpio);
pr_info("%s: irq-base: %u \n", __func__, pdata->irq_base);
// pr_info("%s: wc-irq-gpio: %u \n", __func__, pdata->wc_irq_gpio);
return 0;
}
static int max77693_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct max77693_dev *max77693;
struct max77693_platform_data *pdata;
u8 reg_data;
int ret = 0;
printk(KERN_CRIT "[@@MAX77693@@]: %s called.\n",__func__);
max77693 = kzalloc(sizeof(struct max77693_dev), GFP_KERNEL);
if (max77693 == NULL)
return -ENOMEM;
if (i2c->dev.of_node) {
pdata = devm_kzalloc(&i2c->dev,
sizeof(struct max77693_platform_data),
GFP_KERNEL);
if (!pdata) {
dev_err(&i2c->dev, "Failed to allocate memory \n");
ret = -ENOMEM;
goto err;
}
ret = of_max77693_dt(&i2c->dev, pdata);
if (ret < 0){
dev_err(&i2c->dev, "Failed to get device of_node \n");
return ret;
}
/*Filling the platform data*/
pdata->num_regulators = MAX77693_REG_MAX;
pdata->muic = &max77693_muic;
#if defined(CONFIG_CHARGER_MAX77693)
pdata->charger_data = &sec_battery_pdata;
#endif
pdata->regulators = max77693_regulators,
#ifdef CONFIG_VIBETONZ
pdata->haptic_data = &max77693_haptic_pdata;
#endif
#ifdef CONFIG_LEDS_MAX77693
pdata->led_data = &max77693_led_pdata;
#endif
#if defined(CONFIG_CHARGER_MAX77803)
/* set irq_base at sec_battery_pdata */
sec_battery_pdata.bat_irq = pdata->irq_base + MAX77693_CHG_IRQ_BATP_I;
#endif
/*pdata update to other modules*/
i2c->dev.platform_data = pdata;
} else
pdata = i2c->dev.platform_data;
i2c_set_clientdata(i2c, max77693);
max77693->dev = &i2c->dev;
max77693->i2c = i2c;
max77693->irq = i2c->irq;
// max77693->type = id->driver_data;
if (pdata) {
max77693->irq_base = pdata->irq_base;
max77693->irq_gpio = pdata->irq_gpio;
max77693->wakeup = pdata->wakeup;
gpio_tlmm_config(GPIO_CFG(max77693->irq_gpio, 0, GPIO_CFG_INPUT,
GPIO_CFG_NO_PULL, GPIO_CFG_2MA), GPIO_CFG_DISABLE);
} else {
ret = -EIO;
goto err;
}
mutex_init(&max77693->iolock);
printk(KERN_CRIT "[@@MAX77693@@]: %s called,after mutex_init\n",__func__);
if (max77693_read_reg(i2c, MAX77693_PMIC_REG_PMIC_ID2, ®_data) < 0) {
dev_err(max77693->dev,
"device not found on this channel (this is not an error)\n");
ret = -ENODEV;
goto err;
} else {
/* print rev */
max77693->pmic_rev = (reg_data & 0x7);
max77693->pmic_ver = ((reg_data & 0xF8) >> 0x3);
pr_info("%s: device found: rev.0x%x, ver.0x%x\n", __func__,
max77693->pmic_rev, max77693->pmic_ver);
}
max77693_update_reg(i2c, MAX77693_CHG_REG_SAFEOUT_CTRL, 0x00, 0x30);
max77693->muic = i2c_new_dummy(i2c->adapter, I2C_ADDR_MUIC);
i2c_set_clientdata(max77693->muic, max77693);
max77693->haptic = i2c_new_dummy(i2c->adapter, I2C_ADDR_HAPTIC);
i2c_set_clientdata(max77693->haptic, max77693);
ret = max77693_irq_init(max77693);
if (ret < 0)
goto err_irq_init;
ret = mfd_add_devices(max77693->dev, -1, max77693_devs,
ARRAY_SIZE(max77693_devs), NULL, 0);
if (ret < 0)
goto err_mfd;
device_init_wakeup(max77693->dev, pdata->wakeup);
return ret;
err_mfd:
mfd_remove_devices(max77693->dev);
err_irq_init:
i2c_unregister_device(max77693->muic);
i2c_unregister_device(max77693->haptic);
err:
kfree(max77693);
return ret;
}
static int max77693_i2c_remove(struct i2c_client *i2c)
{
struct max77693_dev *max77693 = i2c_get_clientdata(i2c);
mfd_remove_devices(max77693->dev);
i2c_unregister_device(max77693->muic);
i2c_unregister_device(max77693->haptic);
kfree(max77693);
return 0;
}
static const struct i2c_device_id max77693_i2c_id[] = {
{ "max77693", TYPE_MAX77693 },
{ }
};
MODULE_DEVICE_TABLE(i2c, max77693_i2c_id);
static struct of_device_id max77693_i2c_match_table[] = {
{ .compatible = "max77693,i2c", },
{ },
};
MODULE_DEVICE_TABLE(of, max77693_i2c_match_table);
#ifdef CONFIG_PM
static int max77693_suspend(struct device *dev)
{
struct i2c_client *i2c = container_of(dev, struct i2c_client, dev);
struct max77693_dev *max77693 = i2c_get_clientdata(i2c);
if (device_may_wakeup(dev))
enable_irq_wake(max77693->irq);
return 0;
}
static int max77693_resume(struct device *dev)
{
struct i2c_client *i2c = container_of(dev, struct i2c_client, dev);
struct max77693_dev *max77693 = i2c_get_clientdata(i2c);
if (device_may_wakeup(dev))
disable_irq_wake(max77693->irq);
return max77693_irq_resume(max77693);
}
#else
#define max77693_suspend NULL
#define max77693_resume NULL
#endif /* CONFIG_PM */
#ifdef CONFIG_HIBERNATION
u8 max77693_dumpaddr_pmic[] = {
MAX77693_LED_REG_IFLASH1,
MAX77693_LED_REG_IFLASH2,
MAX77693_LED_REG_ITORCH,
MAX77693_LED_REG_ITORCHTORCHTIMER,
MAX77693_LED_REG_FLASH_TIMER,
MAX77693_LED_REG_FLASH_EN,
MAX77693_LED_REG_MAX_FLASH1,
MAX77693_LED_REG_MAX_FLASH2,
MAX77693_LED_REG_VOUT_CNTL,
MAX77693_LED_REG_VOUT_FLASH1,
MAX77693_LED_REG_FLASH_INT_STATUS,
MAX77693_PMIC_REG_TOPSYS_INT_MASK,
MAX77693_PMIC_REG_MAINCTRL1,
MAX77693_PMIC_REG_LSCNFG,
MAX77693_CHG_REG_CHG_INT_MASK,
MAX77693_CHG_REG_CHG_CNFG_00,
MAX77693_CHG_REG_CHG_CNFG_01,
MAX77693_CHG_REG_CHG_CNFG_02,
MAX77693_CHG_REG_CHG_CNFG_03,
MAX77693_CHG_REG_CHG_CNFG_04,
MAX77693_CHG_REG_CHG_CNFG_05,
MAX77693_CHG_REG_CHG_CNFG_06,
MAX77693_CHG_REG_CHG_CNFG_07,
MAX77693_CHG_REG_CHG_CNFG_08,
MAX77693_CHG_REG_CHG_CNFG_09,
MAX77693_CHG_REG_CHG_CNFG_10,
MAX77693_CHG_REG_CHG_CNFG_11,
MAX77693_CHG_REG_CHG_CNFG_12,
MAX77693_CHG_REG_CHG_CNFG_13,
MAX77693_CHG_REG_CHG_CNFG_14,
MAX77693_CHG_REG_SAFEOUT_CTRL,
};
u8 max77693_dumpaddr_muic[] = {
MAX77693_MUIC_REG_INTMASK1,
MAX77693_MUIC_REG_INTMASK2,
MAX77693_MUIC_REG_INTMASK3,
MAX77693_MUIC_REG_CDETCTRL1,
MAX77693_MUIC_REG_CDETCTRL2,
MAX77693_MUIC_REG_CTRL1,
MAX77693_MUIC_REG_CTRL2,
MAX77693_MUIC_REG_CTRL3,
};
u8 max77693_dumpaddr_haptic[] = {
MAX77693_HAPTIC_REG_CONFIG1,
MAX77693_HAPTIC_REG_CONFIG2,
MAX77693_HAPTIC_REG_CONFIG_CHNL,
MAX77693_HAPTIC_REG_CONFG_CYC1,
MAX77693_HAPTIC_REG_CONFG_CYC2,
MAX77693_HAPTIC_REG_CONFIG_PER1,
MAX77693_HAPTIC_REG_CONFIG_PER2,
MAX77693_HAPTIC_REG_CONFIG_PER3,
MAX77693_HAPTIC_REG_CONFIG_PER4,
MAX77693_HAPTIC_REG_CONFIG_DUTY1,
MAX77693_HAPTIC_REG_CONFIG_DUTY2,
MAX77693_HAPTIC_REG_CONFIG_PWM1,
MAX77693_HAPTIC_REG_CONFIG_PWM2,
MAX77693_HAPTIC_REG_CONFIG_PWM3,
MAX77693_HAPTIC_REG_CONFIG_PWM4,
};
static int max77693_freeze(struct device *dev)
{
struct i2c_client *i2c = container_of(dev, struct i2c_client, dev);
struct max77693_dev *max77693 = i2c_get_clientdata(i2c);
int i;
for (i = 0; i < ARRAY_SIZE(max77693_dumpaddr_pmic); i++)
max77693_read_reg(i2c, max77693_dumpaddr_pmic[i],
&max77693->reg_pmic_dump[i]);
for (i = 0; i < ARRAY_SIZE(max77693_dumpaddr_muic); i++)
max77693_read_reg(i2c, max77693_dumpaddr_muic[i],
&max77693->reg_muic_dump[i]);
for (i = 0; i < ARRAY_SIZE(max77693_dumpaddr_haptic); i++)
max77693_read_reg(i2c, max77693_dumpaddr_haptic[i],
&max77693->reg_haptic_dump[i]);
disable_irq(max77693->irq);
return 0;
}
static int max77693_restore(struct device *dev)
{
struct i2c_client *i2c = container_of(dev, struct i2c_client, dev);
struct max77693_dev *max77693 = i2c_get_clientdata(i2c);
int i;
enable_irq(max77693->irq);
for (i = 0; i < ARRAY_SIZE(max77693_dumpaddr_pmic); i++)
max77693_write_reg(i2c, max77693_dumpaddr_pmic[i],
max77693->reg_pmic_dump[i]);
for (i = 0; i < ARRAY_SIZE(max77693_dumpaddr_muic); i++)
max77693_write_reg(i2c, max77693_dumpaddr_muic[i],
max77693->reg_muic_dump[i]);
for (i = 0; i < ARRAY_SIZE(max77693_dumpaddr_haptic); i++)
max77693_write_reg(i2c, max77693_dumpaddr_haptic[i],
max77693->reg_haptic_dump[i]);
return 0;
}
#endif
const struct dev_pm_ops max77693_pm = {
.suspend = max77693_suspend,
.resume = max77693_resume,
#ifdef CONFIG_HIBERNATION
.freeze = max77693_freeze,
.thaw = max77693_restore,
.restore = max77693_restore,
#endif
};
static struct i2c_driver max77693_i2c_driver = {
.driver = {
.name = "max77693",
.owner = THIS_MODULE,
.pm = &max77693_pm,
.of_match_table = max77693_i2c_match_table,
},
.probe = max77693_i2c_probe,
.remove = max77693_i2c_remove,
.id_table = max77693_i2c_id,
};
static int __init max77693_i2c_init(void)
{
return i2c_add_driver(&max77693_i2c_driver);
}
/* init early so consumer devices can complete system boot */
subsys_initcall(max77693_i2c_init);
static void __exit max77693_i2c_exit(void)
{
i2c_del_driver(&max77693_i2c_driver);
}
module_exit(max77693_i2c_exit);
MODULE_DESCRIPTION("MAXIM 77693 multi-function core driver");
MODULE_AUTHOR("SangYoung, Son <hello.son@samsung.com>");
MODULE_LICENSE("GPL");
| Jackeagle/android_kernel_samsung_n7502 | drivers/mfd/max77693.c | C | gpl-2.0 | 13,346 | 27.517094 | 99 | 0.664768 | false |
/*
* Microblaze helper routines.
*
* Copyright (c) 2009 Edgar E. Iglesias <edgar.iglesias@gmail.com>.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
#include <assert.h>
#include "cpu.h"
#include "dyngen-exec.h"
#include "helper.h"
#include "host-utils.h"
#define D(x)
#if !defined(CONFIG_USER_ONLY)
#include "softmmu_exec.h"
#define MMUSUFFIX _mmu
#define SHIFT 0
#include "softmmu_template.h"
#define SHIFT 1
#include "softmmu_template.h"
#define SHIFT 2
#include "softmmu_template.h"
#define SHIFT 3
#include "softmmu_template.h"
/* Try to fill the TLB and return an exception if error. If retaddr is
NULL, it means that the function was called in C code (i.e. not
from generated code or from helper.c) */
/* XXX: fix it to restore all registers */
void tlb_fill (target_ulong addr, int is_write, int mmu_idx, void *retaddr)
{
TranslationBlock *tb;
CPUState *saved_env;
unsigned long pc;
int ret;
/* XXX: hack to restore env in all cases, even if not called from
generated code */
saved_env = env;
env = cpu_single_env;
ret = cpu_mb_handle_mmu_fault(env, addr, is_write, mmu_idx);
if (unlikely(ret)) {
if (retaddr) {
/* now we have a real cpu fault */
pc = (unsigned long)retaddr;
tb = tb_find_pc(pc);
if (tb) {
/* the PC is inside the translated code. It means that we have
a virtual CPU fault */
cpu_restore_state(tb, env, pc);
}
}
cpu_loop_exit(env);
}
env = saved_env;
}
#endif
void helper_put(uint32_t id, uint32_t ctrl, uint32_t data)
{
int test = ctrl & STREAM_TEST;
int atomic = ctrl & STREAM_ATOMIC;
int control = ctrl & STREAM_CONTROL;
int nonblock = ctrl & STREAM_NONBLOCK;
int exception = ctrl & STREAM_EXCEPTION;
qemu_log("Unhandled stream put to stream-id=%d data=%x %s%s%s%s%s\n",
id, data,
test ? "t" : "",
nonblock ? "n" : "",
exception ? "e" : "",
control ? "c" : "",
atomic ? "a" : "");
}
uint32_t helper_get(uint32_t id, uint32_t ctrl)
{
int test = ctrl & STREAM_TEST;
int atomic = ctrl & STREAM_ATOMIC;
int control = ctrl & STREAM_CONTROL;
int nonblock = ctrl & STREAM_NONBLOCK;
int exception = ctrl & STREAM_EXCEPTION;
qemu_log("Unhandled stream get from stream-id=%d %s%s%s%s%s\n",
id,
test ? "t" : "",
nonblock ? "n" : "",
exception ? "e" : "",
control ? "c" : "",
atomic ? "a" : "");
return 0xdead0000 | id;
}
void helper_raise_exception(uint32_t index)
{
env->exception_index = index;
cpu_loop_exit(env);
}
void helper_debug(void)
{
int i;
qemu_log("PC=%8.8x\n", env->sregs[SR_PC]);
qemu_log("rmsr=%x resr=%x rear=%x debug[%x] imm=%x iflags=%x\n",
env->sregs[SR_MSR], env->sregs[SR_ESR], env->sregs[SR_EAR],
env->debug, env->imm, env->iflags);
qemu_log("btaken=%d btarget=%x mode=%s(saved=%s) eip=%d ie=%d\n",
env->btaken, env->btarget,
(env->sregs[SR_MSR] & MSR_UM) ? "user" : "kernel",
(env->sregs[SR_MSR] & MSR_UMS) ? "user" : "kernel",
(env->sregs[SR_MSR] & MSR_EIP),
(env->sregs[SR_MSR] & MSR_IE));
for (i = 0; i < 32; i++) {
qemu_log("r%2.2d=%8.8x ", i, env->regs[i]);
if ((i + 1) % 4 == 0)
qemu_log("\n");
}
qemu_log("\n\n");
}
static inline uint32_t compute_carry(uint32_t a, uint32_t b, uint32_t cin)
{
uint32_t cout = 0;
if ((b == ~0) && cin)
cout = 1;
else if ((~0 - a) < (b + cin))
cout = 1;
return cout;
}
uint32_t helper_cmp(uint32_t a, uint32_t b)
{
uint32_t t;
t = b + ~a + 1;
if ((b & 0x80000000) ^ (a & 0x80000000))
t = (t & 0x7fffffff) | (b & 0x80000000);
return t;
}
uint32_t helper_cmpu(uint32_t a, uint32_t b)
{
uint32_t t;
t = b + ~a + 1;
if ((b & 0x80000000) ^ (a & 0x80000000))
t = (t & 0x7fffffff) | (a & 0x80000000);
return t;
}
uint32_t helper_carry(uint32_t a, uint32_t b, uint32_t cf)
{
uint32_t ncf;
ncf = compute_carry(a, b, cf);
return ncf;
}
static inline int div_prepare(uint32_t a, uint32_t b)
{
if (b == 0) {
env->sregs[SR_MSR] |= MSR_DZ;
if ((env->sregs[SR_MSR] & MSR_EE)
&& !(env->pvr.regs[2] & PVR2_DIV_ZERO_EXC_MASK)) {
env->sregs[SR_ESR] = ESR_EC_DIVZERO;
helper_raise_exception(EXCP_HW_EXCP);
}
return 0;
}
env->sregs[SR_MSR] &= ~MSR_DZ;
return 1;
}
uint32_t helper_divs(uint32_t a, uint32_t b)
{
if (!div_prepare(a, b))
return 0;
return (int32_t)a / (int32_t)b;
}
uint32_t helper_divu(uint32_t a, uint32_t b)
{
if (!div_prepare(a, b))
return 0;
return a / b;
}
/* raise FPU exception. */
static void raise_fpu_exception(void)
{
env->sregs[SR_ESR] = ESR_EC_FPU;
helper_raise_exception(EXCP_HW_EXCP);
}
static void update_fpu_flags(int flags)
{
int raise = 0;
if (flags & float_flag_invalid) {
env->sregs[SR_FSR] |= FSR_IO;
raise = 1;
}
if (flags & float_flag_divbyzero) {
env->sregs[SR_FSR] |= FSR_DZ;
raise = 1;
}
if (flags & float_flag_overflow) {
env->sregs[SR_FSR] |= FSR_OF;
raise = 1;
}
if (flags & float_flag_underflow) {
env->sregs[SR_FSR] |= FSR_UF;
raise = 1;
}
if (raise
&& (env->pvr.regs[2] & PVR2_FPU_EXC_MASK)
&& (env->sregs[SR_MSR] & MSR_EE)) {
raise_fpu_exception();
}
}
uint32_t helper_fadd(uint32_t a, uint32_t b)
{
CPU_FloatU fd, fa, fb;
int flags;
set_float_exception_flags(0, &env->fp_status);
fa.l = a;
fb.l = b;
fd.f = float32_add(fa.f, fb.f, &env->fp_status);
flags = get_float_exception_flags(&env->fp_status);
update_fpu_flags(flags);
return fd.l;
}
uint32_t helper_frsub(uint32_t a, uint32_t b)
{
CPU_FloatU fd, fa, fb;
int flags;
set_float_exception_flags(0, &env->fp_status);
fa.l = a;
fb.l = b;
fd.f = float32_sub(fb.f, fa.f, &env->fp_status);
flags = get_float_exception_flags(&env->fp_status);
update_fpu_flags(flags);
return fd.l;
}
uint32_t helper_fmul(uint32_t a, uint32_t b)
{
CPU_FloatU fd, fa, fb;
int flags;
set_float_exception_flags(0, &env->fp_status);
fa.l = a;
fb.l = b;
fd.f = float32_mul(fa.f, fb.f, &env->fp_status);
flags = get_float_exception_flags(&env->fp_status);
update_fpu_flags(flags);
return fd.l;
}
uint32_t helper_fdiv(uint32_t a, uint32_t b)
{
CPU_FloatU fd, fa, fb;
int flags;
set_float_exception_flags(0, &env->fp_status);
fa.l = a;
fb.l = b;
fd.f = float32_div(fb.f, fa.f, &env->fp_status);
flags = get_float_exception_flags(&env->fp_status);
update_fpu_flags(flags);
return fd.l;
}
uint32_t helper_fcmp_un(uint32_t a, uint32_t b)
{
CPU_FloatU fa, fb;
uint32_t r = 0;
fa.l = a;
fb.l = b;
if (float32_is_signaling_nan(fa.f) || float32_is_signaling_nan(fb.f)) {
update_fpu_flags(float_flag_invalid);
r = 1;
}
if (float32_is_quiet_nan(fa.f) || float32_is_quiet_nan(fb.f)) {
r = 1;
}
return r;
}
uint32_t helper_fcmp_lt(uint32_t a, uint32_t b)
{
CPU_FloatU fa, fb;
int r;
int flags;
set_float_exception_flags(0, &env->fp_status);
fa.l = a;
fb.l = b;
r = float32_lt(fb.f, fa.f, &env->fp_status);
flags = get_float_exception_flags(&env->fp_status);
update_fpu_flags(flags & float_flag_invalid);
return r;
}
uint32_t helper_fcmp_eq(uint32_t a, uint32_t b)
{
CPU_FloatU fa, fb;
int flags;
int r;
set_float_exception_flags(0, &env->fp_status);
fa.l = a;
fb.l = b;
r = float32_eq_quiet(fa.f, fb.f, &env->fp_status);
flags = get_float_exception_flags(&env->fp_status);
update_fpu_flags(flags & float_flag_invalid);
return r;
}
uint32_t helper_fcmp_le(uint32_t a, uint32_t b)
{
CPU_FloatU fa, fb;
int flags;
int r;
fa.l = a;
fb.l = b;
set_float_exception_flags(0, &env->fp_status);
r = float32_le(fa.f, fb.f, &env->fp_status);
flags = get_float_exception_flags(&env->fp_status);
update_fpu_flags(flags & float_flag_invalid);
return r;
}
uint32_t helper_fcmp_gt(uint32_t a, uint32_t b)
{
CPU_FloatU fa, fb;
int flags, r;
fa.l = a;
fb.l = b;
set_float_exception_flags(0, &env->fp_status);
r = float32_lt(fa.f, fb.f, &env->fp_status);
flags = get_float_exception_flags(&env->fp_status);
update_fpu_flags(flags & float_flag_invalid);
return r;
}
uint32_t helper_fcmp_ne(uint32_t a, uint32_t b)
{
CPU_FloatU fa, fb;
int flags, r;
fa.l = a;
fb.l = b;
set_float_exception_flags(0, &env->fp_status);
r = !float32_eq_quiet(fa.f, fb.f, &env->fp_status);
flags = get_float_exception_flags(&env->fp_status);
update_fpu_flags(flags & float_flag_invalid);
return r;
}
uint32_t helper_fcmp_ge(uint32_t a, uint32_t b)
{
CPU_FloatU fa, fb;
int flags, r;
fa.l = a;
fb.l = b;
set_float_exception_flags(0, &env->fp_status);
r = !float32_lt(fa.f, fb.f, &env->fp_status);
flags = get_float_exception_flags(&env->fp_status);
update_fpu_flags(flags & float_flag_invalid);
return r;
}
uint32_t helper_flt(uint32_t a)
{
CPU_FloatU fd, fa;
fa.l = a;
fd.f = int32_to_float32(fa.l, &env->fp_status);
return fd.l;
}
uint32_t helper_fint(uint32_t a)
{
CPU_FloatU fa;
uint32_t r;
int flags;
set_float_exception_flags(0, &env->fp_status);
fa.l = a;
r = float32_to_int32(fa.f, &env->fp_status);
flags = get_float_exception_flags(&env->fp_status);
update_fpu_flags(flags);
return r;
}
uint32_t helper_fsqrt(uint32_t a)
{
CPU_FloatU fd, fa;
int flags;
set_float_exception_flags(0, &env->fp_status);
fa.l = a;
fd.l = float32_sqrt(fa.f, &env->fp_status);
flags = get_float_exception_flags(&env->fp_status);
update_fpu_flags(flags);
return fd.l;
}
uint32_t helper_pcmpbf(uint32_t a, uint32_t b)
{
unsigned int i;
uint32_t mask = 0xff000000;
for (i = 0; i < 4; i++) {
if ((a & mask) == (b & mask))
return i + 1;
mask >>= 8;
}
return 0;
}
void helper_memalign(uint32_t addr, uint32_t dr, uint32_t wr, uint32_t mask)
{
if (addr & mask) {
qemu_log_mask(CPU_LOG_INT,
"unaligned access addr=%x mask=%x, wr=%d dr=r%d\n",
addr, mask, wr, dr);
env->sregs[SR_EAR] = addr;
env->sregs[SR_ESR] = ESR_EC_UNALIGNED_DATA | (wr << 10) \
| (dr & 31) << 5;
if (mask == 3) {
env->sregs[SR_ESR] |= 1 << 11;
}
if (!(env->sregs[SR_MSR] & MSR_EE)) {
return;
}
helper_raise_exception(EXCP_HW_EXCP);
}
}
#if !defined(CONFIG_USER_ONLY)
/* Writes/reads to the MMU's special regs end up here. */
uint32_t helper_mmu_read(uint32_t rn)
{
return mmu_read(env, rn);
}
void helper_mmu_write(uint32_t rn, uint32_t v)
{
mmu_write(env, rn, v);
}
void cpu_unassigned_access(CPUState *env1, target_phys_addr_t addr,
int is_write, int is_exec, int is_asi, int size)
{
CPUState *saved_env;
saved_env = env;
env = env1;
qemu_log_mask(CPU_LOG_INT, "Unassigned " TARGET_FMT_plx " wr=%d exe=%d\n",
addr, is_write, is_exec);
if (!(env->sregs[SR_MSR] & MSR_EE)) {
env = saved_env;
return;
}
env->sregs[SR_EAR] = addr;
if (is_exec) {
if ((env->pvr.regs[2] & PVR2_IOPB_BUS_EXC_MASK)) {
env->sregs[SR_ESR] = ESR_EC_INSN_BUS;
helper_raise_exception(EXCP_HW_EXCP);
}
} else {
if ((env->pvr.regs[2] & PVR2_DOPB_BUS_EXC_MASK)) {
env->sregs[SR_ESR] = ESR_EC_DATA_BUS;
helper_raise_exception(EXCP_HW_EXCP);
}
}
env = saved_env;
}
#endif
| edgarigl/tlmu | target-microblaze/op_helper.c | C | gpl-2.0 | 12,850 | 23.56979 | 79 | 0.560156 | false |
/*
* u_ether.c -- Ethernet-over-USB link layer utilities for Gadget stack
*
* Copyright (C) 2003-2005,2008 David Brownell
* Copyright (C) 2003-2004 Robert Schwebel, Benedikt Spranger
* Copyright (C) 2008 Nokia Corporation
*
* 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.
*/
/* #define VERBOSE_DEBUG */
#include <linux/kernel.h>
#include <linux/gfp.h>
#include <linux/device.h>
#include <linux/ctype.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include "u_ether.h"
/*
* This component encapsulates the Ethernet link glue needed to provide
* one (!) network link through the USB gadget stack, normally "usb0".
*
* The control and data models are handled by the function driver which
* connects to this code; such as CDC Ethernet (ECM or EEM),
* "CDC Subset", or RNDIS. That includes all descriptor and endpoint
* management.
*
* Link level addressing is handled by this component using module
* parameters; if no such parameters are provided, random link level
* addresses are used. Each end of the link uses one address. The
* host end address is exported in various ways, and is often recorded
* in configuration databases.
*
* The driver which assembles each configuration using such a link is
* responsible for ensuring that each configuration includes at most one
* instance of is network link. (The network layer provides ways for
* this single "physical" link to be used by multiple virtual links.)
*/
#define UETH__VERSION "29-May-2008"
static struct workqueue_struct *uether_wq;
struct eth_dev {
/* lock is held while accessing port_usb
* or updating its backlink port_usb->ioport
*/
spinlock_t lock;
struct gether *port_usb;
struct net_device *net;
struct usb_gadget *gadget;
spinlock_t req_lock; /* guard {rx,tx}_reqs */
struct list_head tx_reqs, rx_reqs;
unsigned tx_qlen;
/* Minimum number of TX USB request queued to UDC */
#define TX_REQ_THRESHOLD 5
int no_tx_req_used;
int tx_skb_hold_count;
u32 tx_req_bufsize;
struct sk_buff_head rx_frames;
unsigned header_len;
unsigned int ul_max_pkts_per_xfer;
unsigned int dl_max_pkts_per_xfer;
struct sk_buff *(*wrap)(struct gether *, struct sk_buff *skb);
int (*unwrap)(struct gether *,
struct sk_buff *skb,
struct sk_buff_head *list);
struct work_struct work;
struct work_struct rx_work;
unsigned long todo;
#define WORK_RX_MEMORY 0
bool zlp;
u8 host_mac[ETH_ALEN];
};
/*-------------------------------------------------------------------------*/
#define RX_EXTRA 20 /* bytes guarding against rx overflows */
#define DEFAULT_QLEN 2 /* double buffering by default */
static unsigned qmult = 5;
module_param(qmult, uint, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(qmult, "queue length multiplier at high/super speed");
/* for dual-speed hardware, use deeper queues at high/super speed */
static inline int qlen(struct usb_gadget *gadget)
{
if (gadget_is_dualspeed(gadget) && (gadget->speed == USB_SPEED_HIGH ||
gadget->speed == USB_SPEED_SUPER))
return qmult * DEFAULT_QLEN;
else
return DEFAULT_QLEN;
}
/*-------------------------------------------------------------------------*/
/* REVISIT there must be a better way than having two sets
* of debug calls ...
*/
#undef DBG
#undef VDBG
#undef ERROR
#undef INFO
#define xprintk(d, level, fmt, args...) \
printk(level "%s: " fmt , (d)->net->name , ## args)
#ifdef DEBUG
#undef DEBUG
#define DBG(dev, fmt, args...) \
xprintk(dev , KERN_DEBUG , fmt , ## args)
#else
#define DBG(dev, fmt, args...) \
do { } while (0)
#endif /* DEBUG */
#ifdef VERBOSE_DEBUG
#define VDBG DBG
#else
#define VDBG(dev, fmt, args...) \
do { } while (0)
#endif /* DEBUG */
#define ERROR(dev, fmt, args...) \
xprintk(dev , KERN_ERR , fmt , ## args)
#define INFO(dev, fmt, args...) \
xprintk(dev , KERN_INFO , fmt , ## args)
/*-------------------------------------------------------------------------*/
/* NETWORK DRIVER HOOKUP (to the layer above this driver) */
static int ueth_change_mtu(struct net_device *net, int new_mtu)
{
struct eth_dev *dev = netdev_priv(net);
unsigned long flags;
int status = 0;
/* don't change MTU on "live" link (peer won't know) */
spin_lock_irqsave(&dev->lock, flags);
if (dev->port_usb)
status = -EBUSY;
else if (new_mtu <= ETH_HLEN || new_mtu > ETH_FRAME_LEN)
status = -ERANGE;
else
net->mtu = new_mtu;
spin_unlock_irqrestore(&dev->lock, flags);
return status;
}
static void eth_get_drvinfo(struct net_device *net, struct ethtool_drvinfo *p)
{
struct eth_dev *dev = netdev_priv(net);
strlcpy(p->driver, "g_ether", sizeof p->driver);
strlcpy(p->version, UETH__VERSION, sizeof p->version);
strlcpy(p->fw_version, dev->gadget->name, sizeof p->fw_version);
strlcpy(p->bus_info, dev_name(&dev->gadget->dev), sizeof p->bus_info);
}
/* REVISIT can also support:
* - WOL (by tracking suspends and issuing remote wakeup)
* - msglevel (implies updated messaging)
* - ... probably more ethtool ops
*/
static const struct ethtool_ops ops = {
.get_drvinfo = eth_get_drvinfo,
.get_link = ethtool_op_get_link,
};
static void defer_kevent(struct eth_dev *dev, int flag)
{
if (test_and_set_bit(flag, &dev->todo))
return;
if (!schedule_work(&dev->work))
ERROR(dev, "kevent %d may have been dropped\n", flag);
else
DBG(dev, "kevent %d scheduled\n", flag);
}
static void rx_complete(struct usb_ep *ep, struct usb_request *req);
static int
rx_submit(struct eth_dev *dev, struct usb_request *req, gfp_t gfp_flags)
{
struct sk_buff *skb;
int retval = -ENOMEM;
size_t size = 0;
struct usb_ep *out;
unsigned long flags;
spin_lock_irqsave(&dev->lock, flags);
if (dev->port_usb)
out = dev->port_usb->out_ep;
else
out = NULL;
spin_unlock_irqrestore(&dev->lock, flags);
if (!out)
return -ENOTCONN;
/* Padding up to RX_EXTRA handles minor disagreements with host.
* Normally we use the USB "terminate on short read" convention;
* so allow up to (N*maxpacket), since that memory is normally
* already allocated. Some hardware doesn't deal well with short
* reads (e.g. DMA must be N*maxpacket), so for now don't trim a
* byte off the end (to force hardware errors on overflow).
*
* RNDIS uses internal framing, and explicitly allows senders to
* pad to end-of-packet. That's potentially nice for speed, but
* means receivers can't recover lost synch on their own (because
* new packets don't only start after a short RX).
*/
size += sizeof(struct ethhdr) + dev->net->mtu + RX_EXTRA;
size += dev->port_usb->header_len;
size += out->maxpacket - 1;
size -= size % out->maxpacket;
if (dev->ul_max_pkts_per_xfer)
size *= dev->ul_max_pkts_per_xfer;
if (dev->port_usb->is_fixed)
size = max_t(size_t, size, dev->port_usb->fixed_out_len);
pr_debug("%s: size: %d", __func__, size);
skb = alloc_skb(size + NET_IP_ALIGN, gfp_flags);
if (skb == NULL) {
DBG(dev, "no rx skb\n");
goto enomem;
}
/* Some platforms perform better when IP packets are aligned,
* but on at least one, checksumming fails otherwise. Note:
* RNDIS headers involve variable numbers of LE32 values.
*/
skb_reserve(skb, NET_IP_ALIGN);
req->buf = skb->data;
req->length = size;
req->complete = rx_complete;
req->context = skb;
retval = usb_ep_queue(out, req, gfp_flags);
if (retval == -ENOMEM)
enomem:
defer_kevent(dev, WORK_RX_MEMORY);
if (retval) {
DBG(dev, "rx submit --> %d\n", retval);
if (skb)
dev_kfree_skb_any(skb);
}
return retval;
}
static void rx_complete(struct usb_ep *ep, struct usb_request *req)
{
struct sk_buff *skb = req->context;
struct eth_dev *dev = ep->driver_data;
int status = req->status;
bool queue = 0;
switch (status) {
/* normal completion */
case 0:
skb_put(skb, req->actual);
if (dev->unwrap) {
unsigned long flags;
spin_lock_irqsave(&dev->lock, flags);
if (dev->port_usb) {
status = dev->unwrap(dev->port_usb,
skb,
&dev->rx_frames);
if (status == -EINVAL)
dev->net->stats.rx_errors++;
else if (status == -EOVERFLOW)
dev->net->stats.rx_over_errors++;
} else {
dev_kfree_skb_any(skb);
status = -ENOTCONN;
}
spin_unlock_irqrestore(&dev->lock, flags);
} else {
skb_queue_tail(&dev->rx_frames, skb);
}
if (!status)
queue = 1;
break;
/* software-driven interface shutdown */
case -ECONNRESET: /* unlink */
case -ESHUTDOWN: /* disconnect etc */
VDBG(dev, "rx shutdown, code %d\n", status);
goto quiesce;
/* for hardware automagic (such as pxa) */
case -ECONNABORTED: /* endpoint reset */
DBG(dev, "rx %s reset\n", ep->name);
defer_kevent(dev, WORK_RX_MEMORY);
quiesce:
dev_kfree_skb_any(skb);
goto clean;
/* data overrun */
case -EOVERFLOW:
dev->net->stats.rx_over_errors++;
/* FALLTHROUGH */
default:
queue = 1;
dev_kfree_skb_any(skb);
dev->net->stats.rx_errors++;
DBG(dev, "rx status %d\n", status);
break;
}
clean:
spin_lock(&dev->req_lock);
list_add(&req->list, &dev->rx_reqs);
spin_unlock(&dev->req_lock);
if (queue)
queue_work(uether_wq, &dev->rx_work);
}
static int prealloc(struct list_head *list, struct usb_ep *ep, unsigned n)
{
unsigned i;
struct usb_request *req;
if (!n)
return -ENOMEM;
/* queue/recycle up to N requests */
i = n;
list_for_each_entry(req, list, list) {
if (i-- == 0)
goto extra;
}
while (i--) {
req = usb_ep_alloc_request(ep, GFP_ATOMIC);
if (!req)
return list_empty(list) ? -ENOMEM : 0;
list_add(&req->list, list);
}
return 0;
extra:
/* free extras */
for (;;) {
struct list_head *next;
next = req->list.next;
list_del(&req->list);
usb_ep_free_request(ep, req);
if (next == list)
break;
req = container_of(next, struct usb_request, list);
}
return 0;
}
static int alloc_requests(struct eth_dev *dev, struct gether *link, unsigned n)
{
int status;
spin_lock(&dev->req_lock);
status = prealloc(&dev->tx_reqs, link->in_ep, n);
if (status < 0)
goto fail;
status = prealloc(&dev->rx_reqs, link->out_ep, n);
if (status < 0)
goto fail;
goto done;
fail:
DBG(dev, "can't alloc requests\n");
done:
spin_unlock(&dev->req_lock);
return status;
}
static void rx_fill(struct eth_dev *dev, gfp_t gfp_flags)
{
struct usb_request *req;
unsigned long flags;
int req_cnt = 0;
/* fill unused rxq slots with some skb */
spin_lock_irqsave(&dev->req_lock, flags);
while (!list_empty(&dev->rx_reqs)) {
/* break the nexus of continuous completion and re-submission*/
if (++req_cnt > qlen(dev->gadget))
break;
req = container_of(dev->rx_reqs.next,
struct usb_request, list);
list_del_init(&req->list);
spin_unlock_irqrestore(&dev->req_lock, flags);
if (rx_submit(dev, req, gfp_flags) < 0) {
spin_lock_irqsave(&dev->req_lock, flags);
list_add(&req->list, &dev->rx_reqs);
spin_unlock_irqrestore(&dev->req_lock, flags);
defer_kevent(dev, WORK_RX_MEMORY);
return;
}
spin_lock_irqsave(&dev->req_lock, flags);
}
spin_unlock_irqrestore(&dev->req_lock, flags);
}
static void process_rx_w(struct work_struct *work)
{
struct eth_dev *dev = container_of(work, struct eth_dev, rx_work);
struct sk_buff *skb;
int status = 0;
if (!dev->port_usb)
return;
while ((skb = skb_dequeue(&dev->rx_frames))) {
if (status < 0
|| ETH_HLEN > skb->len
|| skb->len > ETH_FRAME_LEN) {
dev->net->stats.rx_errors++;
dev->net->stats.rx_length_errors++;
DBG(dev, "rx length %d\n", skb->len);
dev_kfree_skb_any(skb);
continue;
}
skb->protocol = eth_type_trans(skb, dev->net);
dev->net->stats.rx_packets++;
dev->net->stats.rx_bytes += skb->len;
status = netif_rx_ni(skb);
}
if (netif_running(dev->net))
rx_fill(dev, GFP_KERNEL);
}
static void eth_work(struct work_struct *work)
{
struct eth_dev *dev = container_of(work, struct eth_dev, work);
if (test_and_clear_bit(WORK_RX_MEMORY, &dev->todo)) {
if (netif_running(dev->net))
rx_fill(dev, GFP_KERNEL);
}
if (dev->todo)
DBG(dev, "work done, flags = 0x%lx\n", dev->todo);
}
static void tx_complete(struct usb_ep *ep, struct usb_request *req)
{
struct sk_buff *skb = req->context;
struct eth_dev *dev;
struct net_device *net;
struct usb_request *new_req;
struct usb_ep *in;
int length;
int retval;
if (!ep->driver_data) {
usb_ep_free_request(ep, req);
return;
}
dev = ep->driver_data;
net = dev->net;
if (!dev->port_usb) {
usb_ep_free_request(ep, req);
return;
}
switch (req->status) {
default:
dev->net->stats.tx_errors++;
VDBG(dev, "tx err %d\n", req->status);
/* FALLTHROUGH */
case -ECONNRESET: /* unlink */
case -ESHUTDOWN: /* disconnect etc */
break;
case 0:
if (!req->zero)
dev->net->stats.tx_bytes += req->length-1;
else
dev->net->stats.tx_bytes += req->length;
}
dev->net->stats.tx_packets++;
spin_lock(&dev->req_lock);
list_add_tail(&req->list, &dev->tx_reqs);
if (dev->port_usb->multi_pkt_xfer) {
dev->no_tx_req_used--;
req->length = 0;
in = dev->port_usb->in_ep;
if (!list_empty(&dev->tx_reqs)) {
new_req = container_of(dev->tx_reqs.next,
struct usb_request, list);
list_del(&new_req->list);
spin_unlock(&dev->req_lock);
if (new_req->length > 0) {
length = new_req->length;
/* NCM requires no zlp if transfer is
* dwNtbInMaxSize */
if (dev->port_usb->is_fixed &&
length == dev->port_usb->fixed_in_len &&
(length % in->maxpacket) == 0)
new_req->zero = 0;
else
new_req->zero = 1;
/* use zlp framing on tx for strict CDC-Ether
* conformance, though any robust network rx
* path ignores extra padding. and some hardware
* doesn't like to write zlps.
*/
if (new_req->zero && !dev->zlp &&
(length % in->maxpacket) == 0) {
new_req->zero = 0;
length++;
}
new_req->length = length;
retval = usb_ep_queue(in, new_req, GFP_ATOMIC);
switch (retval) {
default:
DBG(dev, "tx queue err %d\n", retval);
new_req->length = 0;
spin_lock(&dev->req_lock);
list_add_tail(&new_req->list,
&dev->tx_reqs);
spin_unlock(&dev->req_lock);
break;
case 0:
spin_lock(&dev->req_lock);
dev->no_tx_req_used++;
spin_unlock(&dev->req_lock);
net->trans_start = jiffies;
}
} else {
spin_lock(&dev->req_lock);
/*
* Put the idle request at the back of the
* queue. The xmit function will put the
* unfinished request at the beginning of the
* queue.
*/
list_add_tail(&new_req->list, &dev->tx_reqs);
spin_unlock(&dev->req_lock);
}
} else {
spin_unlock(&dev->req_lock);
}
} else {
spin_unlock(&dev->req_lock);
dev_kfree_skb_any(skb);
}
if (netif_carrier_ok(dev->net))
netif_wake_queue(dev->net);
}
static inline int is_promisc(u16 cdc_filter)
{
return cdc_filter & USB_CDC_PACKET_TYPE_PROMISCUOUS;
}
static int alloc_tx_buffer(struct eth_dev *dev)
{
struct list_head *act;
struct usb_request *req;
dev->tx_req_bufsize = (dev->dl_max_pkts_per_xfer *
(dev->net->mtu
+ sizeof(struct ethhdr)
/* size of rndis_packet_msg_type */
+ 44
+ 22));
list_for_each(act, &dev->tx_reqs) {
req = container_of(act, struct usb_request, list);
if (!req->buf)
req->buf = kmalloc(dev->tx_req_bufsize,
GFP_ATOMIC);
if (!req->buf)
goto free_buf;
}
return 0;
free_buf:
/* tx_req_bufsize = 0 retries mem alloc on next eth_start_xmit */
dev->tx_req_bufsize = 0;
list_for_each(act, &dev->tx_reqs) {
req = container_of(act, struct usb_request, list);
kfree(req->buf);
}
return -ENOMEM;
}
static netdev_tx_t eth_start_xmit(struct sk_buff *skb,
struct net_device *net)
{
struct eth_dev *dev = netdev_priv(net);
int length = skb->len;
int retval;
struct usb_request *req = NULL;
unsigned long flags;
struct usb_ep *in;
u16 cdc_filter;
bool multi_pkt_xfer = false;
spin_lock_irqsave(&dev->lock, flags);
if (dev->port_usb) {
in = dev->port_usb->in_ep;
cdc_filter = dev->port_usb->cdc_filter;
multi_pkt_xfer = dev->port_usb->multi_pkt_xfer;
} else {
in = NULL;
cdc_filter = 0;
}
spin_unlock_irqrestore(&dev->lock, flags);
if (!in) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
/* Allocate memory for tx_reqs to support multi packet transfer */
if (multi_pkt_xfer && !dev->tx_req_bufsize) {
retval = alloc_tx_buffer(dev);
if (retval < 0)
return -ENOMEM;
}
/* apply outgoing CDC or RNDIS filters */
if (!is_promisc(cdc_filter)) {
u8 *dest = skb->data;
if (is_multicast_ether_addr(dest)) {
u16 type;
/* ignores USB_CDC_PACKET_TYPE_MULTICAST and host
* SET_ETHERNET_MULTICAST_FILTERS requests
*/
if (is_broadcast_ether_addr(dest))
type = USB_CDC_PACKET_TYPE_BROADCAST;
else
type = USB_CDC_PACKET_TYPE_ALL_MULTICAST;
if (!(cdc_filter & type)) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
}
/* ignores USB_CDC_PACKET_TYPE_DIRECTED */
}
spin_lock_irqsave(&dev->req_lock, flags);
/*
* this freelist can be empty if an interrupt triggered disconnect()
* and reconfigured the gadget (shutting down this queue) after the
* network stack decided to xmit but before we got the spinlock.
*/
if (list_empty(&dev->tx_reqs)) {
spin_unlock_irqrestore(&dev->req_lock, flags);
return NETDEV_TX_BUSY;
}
req = container_of(dev->tx_reqs.next, struct usb_request, list);
list_del(&req->list);
/* temporarily stop TX queue when the freelist empties */
if (list_empty(&dev->tx_reqs))
netif_stop_queue(net);
spin_unlock_irqrestore(&dev->req_lock, flags);
/* no buffer copies needed, unless the network stack did it
* or the hardware can't use skb buffers.
* or there's not enough space for extra headers we need
*/
if (dev->wrap) {
unsigned long flags;
spin_lock_irqsave(&dev->lock, flags);
if (dev->port_usb)
skb = dev->wrap(dev->port_usb, skb);
spin_unlock_irqrestore(&dev->lock, flags);
if (!skb)
goto drop;
}
spin_lock_irqsave(&dev->req_lock, flags);
dev->tx_skb_hold_count++;
spin_unlock_irqrestore(&dev->req_lock, flags);
if (multi_pkt_xfer) {
memcpy(req->buf + req->length, skb->data, skb->len);
req->length = req->length + skb->len;
length = req->length;
dev_kfree_skb_any(skb);
spin_lock_irqsave(&dev->req_lock, flags);
if (dev->tx_skb_hold_count < dev->dl_max_pkts_per_xfer) {
if (dev->no_tx_req_used > TX_REQ_THRESHOLD) {
list_add(&req->list, &dev->tx_reqs);
spin_unlock_irqrestore(&dev->req_lock, flags);
goto success;
}
}
dev->no_tx_req_used++;
spin_unlock_irqrestore(&dev->req_lock, flags);
spin_lock_irqsave(&dev->lock, flags);
dev->tx_skb_hold_count = 0;
spin_unlock_irqrestore(&dev->lock, flags);
} else {
length = skb->len;
req->buf = skb->data;
req->context = skb;
}
req->complete = tx_complete;
/* NCM requires no zlp if transfer is dwNtbInMaxSize */
if (dev->port_usb->is_fixed &&
length == dev->port_usb->fixed_in_len &&
(length % in->maxpacket) == 0)
req->zero = 0;
else
req->zero = 1;
/* use zlp framing on tx for strict CDC-Ether conformance,
* though any robust network rx path ignores extra padding.
* and some hardware doesn't like to write zlps.
*/
if (req->zero && !dev->zlp && (length % in->maxpacket) == 0) {
req->zero = 0;
length++;
}
req->length = length;
/* throttle highspeed IRQ rate back slightly */
if (gadget_is_dualspeed(dev->gadget) &&
(dev->gadget->speed == USB_SPEED_HIGH)) {
dev->tx_qlen++;
if (dev->tx_qlen == (qmult/2)) {
req->no_interrupt = 0;
dev->tx_qlen = 0;
} else {
req->no_interrupt = 1;
}
} else {
req->no_interrupt = 0;
}
retval = usb_ep_queue(in, req, GFP_ATOMIC);
switch (retval) {
default:
DBG(dev, "tx queue err %d\n", retval);
break;
case 0:
net->trans_start = jiffies;
}
if (retval) {
if (!multi_pkt_xfer)
dev_kfree_skb_any(skb);
else
req->length = 0;
drop:
dev->net->stats.tx_dropped++;
spin_lock_irqsave(&dev->req_lock, flags);
if (list_empty(&dev->tx_reqs))
netif_start_queue(net);
list_add(&req->list, &dev->tx_reqs);
spin_unlock_irqrestore(&dev->req_lock, flags);
}
success:
return NETDEV_TX_OK;
}
/*-------------------------------------------------------------------------*/
static void eth_start(struct eth_dev *dev, gfp_t gfp_flags)
{
DBG(dev, "%s\n", __func__);
/* fill the rx queue */
rx_fill(dev, gfp_flags);
/* and open the tx floodgates */
dev->tx_qlen = 0;
netif_wake_queue(dev->net);
}
static int eth_open(struct net_device *net)
{
struct eth_dev *dev = netdev_priv(net);
struct gether *link;
DBG(dev, "%s\n", __func__);
if (netif_carrier_ok(dev->net))
eth_start(dev, GFP_KERNEL);
spin_lock_irq(&dev->lock);
link = dev->port_usb;
if (link && link->open)
link->open(link);
spin_unlock_irq(&dev->lock);
return 0;
}
static int eth_stop(struct net_device *net)
{
struct eth_dev *dev = netdev_priv(net);
unsigned long flags;
VDBG(dev, "%s\n", __func__);
netif_stop_queue(net);
DBG(dev, "stop stats: rx/tx %ld/%ld, errs %ld/%ld\n",
dev->net->stats.rx_packets, dev->net->stats.tx_packets,
dev->net->stats.rx_errors, dev->net->stats.tx_errors
);
/* ensure there are no more active requests */
spin_lock_irqsave(&dev->lock, flags);
if (dev->port_usb) {
struct gether *link = dev->port_usb;
if (link->close)
link->close(link);
/* NOTE: we have no abort-queue primitive we could use
* to cancel all pending I/O. Instead, we disable then
* reenable the endpoints ... this idiom may leave toggle
* wrong, but that's a self-correcting error.
*
* REVISIT: we *COULD* just let the transfers complete at
* their own pace; the network stack can handle old packets.
* For the moment we leave this here, since it works.
*/
usb_ep_disable(link->in_ep);
usb_ep_disable(link->out_ep);
if (netif_carrier_ok(net)) {
if (config_ep_by_speed(dev->gadget, &link->func,
link->in_ep) ||
config_ep_by_speed(dev->gadget, &link->func,
link->out_ep)) {
link->in_ep->desc = NULL;
link->out_ep->desc = NULL;
return -EINVAL;
}
DBG(dev, "host still using in/out endpoints\n");
usb_ep_enable(link->in_ep);
usb_ep_enable(link->out_ep);
}
}
spin_unlock_irqrestore(&dev->lock, flags);
return 0;
}
/*-------------------------------------------------------------------------*/
static u8 host_ethaddr[ETH_ALEN];
/* initial value, changed by "ifconfig usb0 hw ether xx:xx:xx:xx:xx:xx" */
static char *dev_addr;
module_param(dev_addr, charp, S_IRUGO);
MODULE_PARM_DESC(dev_addr, "Device Ethernet Address");
/* this address is invisible to ifconfig */
static char *host_addr;
module_param(host_addr, charp, S_IRUGO);
MODULE_PARM_DESC(host_addr, "Host Ethernet Address");
static int get_ether_addr(const char *str, u8 *dev_addr)
{
if (str) {
unsigned i;
for (i = 0; i < 6; i++) {
unsigned char num;
if ((*str == '.') || (*str == ':'))
str++;
num = hex_to_bin(*str++) << 4;
num |= hex_to_bin(*str++);
dev_addr [i] = num;
}
if (is_valid_ether_addr(dev_addr))
return 0;
}
random_ether_addr(dev_addr);
return 1;
}
static int get_host_ether_addr(u8 *str, u8 *dev_addr)
{
memcpy(dev_addr, str, ETH_ALEN);
if (is_valid_ether_addr(dev_addr))
return 0;
random_ether_addr(dev_addr);
memcpy(str, dev_addr, ETH_ALEN);
return 1;
}
static struct eth_dev *the_dev;
static const struct net_device_ops eth_netdev_ops = {
.ndo_open = eth_open,
.ndo_stop = eth_stop,
.ndo_start_xmit = eth_start_xmit,
.ndo_change_mtu = ueth_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
static struct device_type gadget_type = {
.name = "gadget",
};
/**
* gether_setup - initialize one ethernet-over-usb link
* @g: gadget to associated with these links
* @ethaddr: NULL, or a buffer in which the ethernet address of the
* host side of the link is recorded
* Context: may sleep
*
* This sets up the single network link that may be exported by a
* gadget driver using this framework. The link layer addresses are
* set up using module parameters.
*
* Returns negative errno, or zero on success
*/
int gether_setup(struct usb_gadget *g, u8 ethaddr[ETH_ALEN])
{
return gether_setup_name(g, ethaddr, "usb");
}
/**
* gether_setup_name - initialize one ethernet-over-usb link
* @g: gadget to associated with these links
* @ethaddr: NULL, or a buffer in which the ethernet address of the
* host side of the link is recorded
* @netname: name for network device (for example, "usb")
* Context: may sleep
*
* This sets up the single network link that may be exported by a
* gadget driver using this framework. The link layer addresses are
* set up using module parameters.
*
* Returns negative errno, or zero on success
*/
int gether_setup_name(struct usb_gadget *g, u8 ethaddr[ETH_ALEN],
const char *netname)
{
struct eth_dev *dev;
struct net_device *net;
int status;
if (the_dev)
return -EBUSY;
net = alloc_etherdev(sizeof *dev);
if (!net)
return -ENOMEM;
dev = netdev_priv(net);
spin_lock_init(&dev->lock);
spin_lock_init(&dev->req_lock);
INIT_WORK(&dev->work, eth_work);
INIT_WORK(&dev->rx_work, process_rx_w);
INIT_LIST_HEAD(&dev->tx_reqs);
INIT_LIST_HEAD(&dev->rx_reqs);
skb_queue_head_init(&dev->rx_frames);
/* network device setup */
dev->net = net;
snprintf(net->name, sizeof(net->name), "%s%%d", netname);
if (get_ether_addr(dev_addr, net->dev_addr))
dev_warn(&g->dev,
"using random %s ethernet address\n", "self");
if (get_host_ether_addr(host_ethaddr, dev->host_mac))
dev_warn(&g->dev, "using random %s ethernet address\n", "host");
else
dev_warn(&g->dev, "using previous %s ethernet address\n", "host");
if (ethaddr)
memcpy(ethaddr, dev->host_mac, ETH_ALEN);
net->netdev_ops = ð_netdev_ops;
SET_ETHTOOL_OPS(net, &ops);
/* two kinds of host-initiated state changes:
* - iff DATA transfer is active, carrier is "on"
* - tx queueing enabled if open *and* carrier is "on"
*/
netif_carrier_off(net);
dev->gadget = g;
SET_NETDEV_DEV(net, &g->dev);
SET_NETDEV_DEVTYPE(net, &gadget_type);
status = register_netdev(net);
if (status < 0) {
dev_dbg(&g->dev, "register_netdev failed, %d\n", status);
free_netdev(net);
} else {
INFO(dev, "MAC %pM\n", net->dev_addr);
INFO(dev, "HOST MAC %pM\n", dev->host_mac);
the_dev = dev;
}
return status;
}
/**
* gether_cleanup - remove Ethernet-over-USB device
* Context: may sleep
*
* This is called to free all resources allocated by @gether_setup().
*/
void gether_cleanup(void)
{
if (!the_dev)
return;
unregister_netdev(the_dev->net);
flush_work_sync(&the_dev->work);
free_netdev(the_dev->net);
the_dev = NULL;
}
/**
* gether_connect - notify network layer that USB link is active
* @link: the USB link, set up with endpoints, descriptors matching
* current device speed, and any framing wrapper(s) set up.
* Context: irqs blocked
*
* This is called to activate endpoints and let the network layer know
* the connection is active ("carrier detect"). It may cause the I/O
* queues to open and start letting network packets flow, but will in
* any case activate the endpoints so that they respond properly to the
* USB host.
*
* Verify net_device pointer returned using IS_ERR(). If it doesn't
* indicate some error code (negative errno), ep->driver_data values
* have been overwritten.
*/
struct net_device *gether_connect(struct gether *link)
{
struct eth_dev *dev = the_dev;
int result = 0;
if (!dev)
return ERR_PTR(-EINVAL);
link->in_ep->driver_data = dev;
result = usb_ep_enable(link->in_ep);
if (result != 0) {
DBG(dev, "enable %s --> %d\n",
link->in_ep->name, result);
goto fail0;
}
link->out_ep->driver_data = dev;
result = usb_ep_enable(link->out_ep);
if (result != 0) {
DBG(dev, "enable %s --> %d\n",
link->out_ep->name, result);
goto fail1;
}
if (result == 0)
result = alloc_requests(dev, link, qlen(dev->gadget));
if (result == 0) {
dev->zlp = link->is_zlp_ok;
DBG(dev, "qlen %d\n", qlen(dev->gadget));
dev->header_len = link->header_len;
dev->unwrap = link->unwrap;
dev->wrap = link->wrap;
dev->ul_max_pkts_per_xfer = link->ul_max_pkts_per_xfer;
dev->dl_max_pkts_per_xfer = link->dl_max_pkts_per_xfer;
spin_lock(&dev->lock);
dev->tx_skb_hold_count = 0;
dev->no_tx_req_used = 0;
dev->tx_req_bufsize = 0;
dev->port_usb = link;
link->ioport = dev;
if (netif_running(dev->net)) {
if (link->open)
link->open(link);
} else {
if (link->close)
link->close(link);
}
spin_unlock(&dev->lock);
netif_carrier_on(dev->net);
if (netif_running(dev->net))
eth_start(dev, GFP_ATOMIC);
/* on error, disable any endpoints */
} else {
(void) usb_ep_disable(link->out_ep);
fail1:
(void) usb_ep_disable(link->in_ep);
}
fail0:
/* caller is responsible for cleanup on error */
if (result < 0)
return ERR_PTR(result);
return dev->net;
}
/**
* gether_disconnect - notify network layer that USB link is inactive
* @link: the USB link, on which gether_connect() was called
* Context: irqs blocked
*
* This is called to deactivate endpoints and let the network layer know
* the connection went inactive ("no carrier").
*
* On return, the state is as if gether_connect() had never been called.
* The endpoints are inactive, and accordingly without active USB I/O.
* Pointers to endpoint descriptors and endpoint private data are nulled.
*/
void gether_disconnect(struct gether *link)
{
struct eth_dev *dev = link->ioport;
struct usb_request *req;
struct sk_buff *skb;
if (!dev)
return;
DBG(dev, "%s\n", __func__);
netif_stop_queue(dev->net);
netif_carrier_off(dev->net);
/* disable endpoints, forcing (synchronous) completion
* of all pending i/o. then free the request objects
* and forget about the endpoints.
*/
usb_ep_disable(link->in_ep);
spin_lock(&dev->req_lock);
while (!list_empty(&dev->tx_reqs)) {
req = container_of(dev->tx_reqs.next,
struct usb_request, list);
list_del(&req->list);
spin_unlock(&dev->req_lock);
if (link->multi_pkt_xfer)
kfree(req->buf);
usb_ep_free_request(link->in_ep, req);
spin_lock(&dev->req_lock);
}
spin_unlock(&dev->req_lock);
link->in_ep->driver_data = NULL;
link->in_ep->desc = NULL;
usb_ep_disable(link->out_ep);
spin_lock(&dev->req_lock);
while (!list_empty(&dev->rx_reqs)) {
req = container_of(dev->rx_reqs.next,
struct usb_request, list);
list_del(&req->list);
spin_unlock(&dev->req_lock);
usb_ep_free_request(link->out_ep, req);
spin_lock(&dev->req_lock);
}
spin_unlock(&dev->req_lock);
spin_lock(&dev->rx_frames.lock);
while ((skb = __skb_dequeue(&dev->rx_frames)))
dev_kfree_skb_any(skb);
spin_unlock(&dev->rx_frames.lock);
link->out_ep->driver_data = NULL;
link->out_ep->desc = NULL;
/* finish forgetting about this USB link episode */
dev->header_len = 0;
dev->unwrap = NULL;
dev->wrap = NULL;
spin_lock(&dev->lock);
dev->port_usb = NULL;
link->ioport = NULL;
spin_unlock(&dev->lock);
}
static int __init gether_init(void)
{
uether_wq = create_singlethread_workqueue("uether");
if (!uether_wq) {
pr_err("%s: Unable to create workqueue: uether\n", __func__);
return -ENOMEM;
}
return 0;
}
module_init(gether_init);
static void __exit gether_exit(void)
{
destroy_workqueue(uether_wq);
}
module_exit(gether_exit);
MODULE_DESCRIPTION("ethernet over USB driver");
MODULE_LICENSE("GPL v2");
| paulocastro31/android_kernel_motorola_msm8226 | drivers/usb/gadget/u_ether.c | C | gpl-2.0 | 31,627 | 24.100794 | 79 | 0.640655 | false |
/*
* linux/fs/nfs/write.c
*
* Write file data over NFS.
*
* Copyright (C) 1996, 1997, Olaf Kirch <okir@monad.swb.de>
*/
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/pagemap.h>
#include <linux/file.h>
#include <linux/writeback.h>
#include <linux/swap.h>
#include <linux/migrate.h>
#include <linux/sunrpc/clnt.h>
#include <linux/nfs_fs.h>
#include <linux/nfs_mount.h>
#include <linux/nfs_page.h>
#include <linux/backing-dev.h>
#include <linux/export.h>
#include <linux/freezer.h>
#include <linux/wait.h>
#include <asm/uaccess.h>
#include "delegation.h"
#include "internal.h"
#include "iostat.h"
#include "nfs4_fs.h"
#include "fscache.h"
#include "pnfs.h"
#include "nfstrace.h"
#define NFSDBG_FACILITY NFSDBG_PAGECACHE
#define MIN_POOL_WRITE (32)
#define MIN_POOL_COMMIT (4)
/*
* Local function declarations
*/
static void nfs_redirty_request(struct nfs_page *req);
static const struct rpc_call_ops nfs_commit_ops;
static const struct nfs_pgio_completion_ops nfs_async_write_completion_ops;
static const struct nfs_commit_completion_ops nfs_commit_completion_ops;
static const struct nfs_rw_ops nfs_rw_write_ops;
static void nfs_clear_request_commit(struct nfs_page *req);
static void nfs_init_cinfo_from_inode(struct nfs_commit_info *cinfo,
struct inode *inode);
static struct nfs_page *
nfs_page_search_commits_for_head_request_locked(struct nfs_inode *nfsi,
struct page *page);
static struct kmem_cache *nfs_wdata_cachep;
static mempool_t *nfs_wdata_mempool;
static struct kmem_cache *nfs_cdata_cachep;
static mempool_t *nfs_commit_mempool;
struct nfs_commit_data *nfs_commitdata_alloc(void)
{
struct nfs_commit_data *p = mempool_alloc(nfs_commit_mempool, GFP_NOIO);
if (p) {
memset(p, 0, sizeof(*p));
INIT_LIST_HEAD(&p->pages);
}
return p;
}
EXPORT_SYMBOL_GPL(nfs_commitdata_alloc);
void nfs_commit_free(struct nfs_commit_data *p)
{
mempool_free(p, nfs_commit_mempool);
}
EXPORT_SYMBOL_GPL(nfs_commit_free);
static struct nfs_pgio_header *nfs_writehdr_alloc(void)
{
struct nfs_pgio_header *p = mempool_alloc(nfs_wdata_mempool, GFP_NOIO);
if (p)
memset(p, 0, sizeof(*p));
return p;
}
static void nfs_writehdr_free(struct nfs_pgio_header *hdr)
{
mempool_free(hdr, nfs_wdata_mempool);
}
static void nfs_context_set_write_error(struct nfs_open_context *ctx, int error)
{
ctx->error = error;
smp_wmb();
set_bit(NFS_CONTEXT_ERROR_WRITE, &ctx->flags);
}
/*
* nfs_page_find_head_request_locked - find head request associated with @page
*
* must be called while holding the inode lock.
*
* returns matching head request with reference held, or NULL if not found.
*/
static struct nfs_page *
nfs_page_find_head_request_locked(struct nfs_inode *nfsi, struct page *page)
{
struct nfs_page *req = NULL;
if (PagePrivate(page))
req = (struct nfs_page *)page_private(page);
else if (unlikely(PageSwapCache(page)))
req = nfs_page_search_commits_for_head_request_locked(nfsi,
page);
if (req) {
WARN_ON_ONCE(req->wb_head != req);
kref_get(&req->wb_kref);
}
return req;
}
/*
* nfs_page_find_head_request - find head request associated with @page
*
* returns matching head request with reference held, or NULL if not found.
*/
static struct nfs_page *nfs_page_find_head_request(struct page *page)
{
struct inode *inode = page_file_mapping(page)->host;
struct nfs_page *req = NULL;
spin_lock(&inode->i_lock);
req = nfs_page_find_head_request_locked(NFS_I(inode), page);
spin_unlock(&inode->i_lock);
return req;
}
/* Adjust the file length if we're writing beyond the end */
static void nfs_grow_file(struct page *page, unsigned int offset, unsigned int count)
{
struct inode *inode = page_file_mapping(page)->host;
loff_t end, i_size;
pgoff_t end_index;
spin_lock(&inode->i_lock);
i_size = i_size_read(inode);
end_index = (i_size - 1) >> PAGE_SHIFT;
if (i_size > 0 && page_file_index(page) < end_index)
goto out;
end = page_file_offset(page) + ((loff_t)offset+count);
if (i_size >= end)
goto out;
i_size_write(inode, end);
nfs_inc_stats(inode, NFSIOS_EXTENDWRITE);
out:
spin_unlock(&inode->i_lock);
}
/* A writeback failed: mark the page as bad, and invalidate the page cache */
static void nfs_set_pageerror(struct page *page)
{
nfs_zap_mapping(page_file_mapping(page)->host, page_file_mapping(page));
}
/*
* nfs_page_group_search_locked
* @head - head request of page group
* @page_offset - offset into page
*
* Search page group with head @head to find a request that contains the
* page offset @page_offset.
*
* Returns a pointer to the first matching nfs request, or NULL if no
* match is found.
*
* Must be called with the page group lock held
*/
static struct nfs_page *
nfs_page_group_search_locked(struct nfs_page *head, unsigned int page_offset)
{
struct nfs_page *req;
WARN_ON_ONCE(head != head->wb_head);
WARN_ON_ONCE(!test_bit(PG_HEADLOCK, &head->wb_head->wb_flags));
req = head;
do {
if (page_offset >= req->wb_pgbase &&
page_offset < (req->wb_pgbase + req->wb_bytes))
return req;
req = req->wb_this_page;
} while (req != head);
return NULL;
}
/*
* nfs_page_group_covers_page
* @head - head request of page group
*
* Return true if the page group with head @head covers the whole page,
* returns false otherwise
*/
static bool nfs_page_group_covers_page(struct nfs_page *req)
{
struct nfs_page *tmp;
unsigned int pos = 0;
unsigned int len = nfs_page_length(req->wb_page);
nfs_page_group_lock(req, false);
do {
tmp = nfs_page_group_search_locked(req->wb_head, pos);
if (tmp) {
/* no way this should happen */
WARN_ON_ONCE(tmp->wb_pgbase != pos);
pos += tmp->wb_bytes - (pos - tmp->wb_pgbase);
}
} while (tmp && pos < len);
nfs_page_group_unlock(req);
WARN_ON_ONCE(pos > len);
return pos == len;
}
/* We can set the PG_uptodate flag if we see that a write request
* covers the full page.
*/
static void nfs_mark_uptodate(struct nfs_page *req)
{
if (PageUptodate(req->wb_page))
return;
if (!nfs_page_group_covers_page(req))
return;
SetPageUptodate(req->wb_page);
}
static int wb_priority(struct writeback_control *wbc)
{
int ret = 0;
if (wbc->sync_mode == WB_SYNC_ALL)
ret = FLUSH_COND_STABLE;
return ret;
}
/*
* NFS congestion control
*/
int nfs_congestion_kb;
#define NFS_CONGESTION_ON_THRESH (nfs_congestion_kb >> (PAGE_SHIFT-10))
#define NFS_CONGESTION_OFF_THRESH \
(NFS_CONGESTION_ON_THRESH - (NFS_CONGESTION_ON_THRESH >> 2))
static void nfs_set_page_writeback(struct page *page)
{
struct nfs_server *nfss = NFS_SERVER(page_file_mapping(page)->host);
int ret = test_set_page_writeback(page);
WARN_ON_ONCE(ret != 0);
if (atomic_long_inc_return(&nfss->writeback) >
NFS_CONGESTION_ON_THRESH) {
set_bdi_congested(&nfss->backing_dev_info,
BLK_RW_ASYNC);
}
}
static void nfs_end_page_writeback(struct nfs_page *req)
{
struct inode *inode = page_file_mapping(req->wb_page)->host;
struct nfs_server *nfss = NFS_SERVER(inode);
if (!nfs_page_group_sync_on_bit(req, PG_WB_END))
return;
end_page_writeback(req->wb_page);
if (atomic_long_dec_return(&nfss->writeback) < NFS_CONGESTION_OFF_THRESH)
clear_bdi_congested(&nfss->backing_dev_info, BLK_RW_ASYNC);
}
/* nfs_page_group_clear_bits
* @req - an nfs request
* clears all page group related bits from @req
*/
static void
nfs_page_group_clear_bits(struct nfs_page *req)
{
clear_bit(PG_TEARDOWN, &req->wb_flags);
clear_bit(PG_UNLOCKPAGE, &req->wb_flags);
clear_bit(PG_UPTODATE, &req->wb_flags);
clear_bit(PG_WB_END, &req->wb_flags);
clear_bit(PG_REMOVE, &req->wb_flags);
}
/*
* nfs_unroll_locks_and_wait - unlock all newly locked reqs and wait on @req
*
* this is a helper function for nfs_lock_and_join_requests
*
* @inode - inode associated with request page group, must be holding inode lock
* @head - head request of page group, must be holding head lock
* @req - request that couldn't lock and needs to wait on the req bit lock
* @nonblock - if true, don't actually wait
*
* NOTE: this must be called holding page_group bit lock and inode spin lock
* and BOTH will be released before returning.
*
* returns 0 on success, < 0 on error.
*/
static int
nfs_unroll_locks_and_wait(struct inode *inode, struct nfs_page *head,
struct nfs_page *req, bool nonblock)
__releases(&inode->i_lock)
{
struct nfs_page *tmp;
int ret;
/* relinquish all the locks successfully grabbed this run */
for (tmp = head ; tmp != req; tmp = tmp->wb_this_page)
nfs_unlock_request(tmp);
WARN_ON_ONCE(test_bit(PG_TEARDOWN, &req->wb_flags));
/* grab a ref on the request that will be waited on */
kref_get(&req->wb_kref);
nfs_page_group_unlock(head);
spin_unlock(&inode->i_lock);
/* release ref from nfs_page_find_head_request_locked */
nfs_release_request(head);
if (!nonblock)
ret = nfs_wait_on_request(req);
else
ret = -EAGAIN;
nfs_release_request(req);
return ret;
}
/*
* nfs_destroy_unlinked_subrequests - destroy recently unlinked subrequests
*
* @destroy_list - request list (using wb_this_page) terminated by @old_head
* @old_head - the old head of the list
*
* All subrequests must be locked and removed from all lists, so at this point
* they are only "active" in this function, and possibly in nfs_wait_on_request
* with a reference held by some other context.
*/
static void
nfs_destroy_unlinked_subrequests(struct nfs_page *destroy_list,
struct nfs_page *old_head)
{
while (destroy_list) {
struct nfs_page *subreq = destroy_list;
destroy_list = (subreq->wb_this_page == old_head) ?
NULL : subreq->wb_this_page;
WARN_ON_ONCE(old_head != subreq->wb_head);
/* make sure old group is not used */
subreq->wb_head = subreq;
subreq->wb_this_page = subreq;
/* subreq is now totally disconnected from page group or any
* write / commit lists. last chance to wake any waiters */
nfs_unlock_request(subreq);
if (!test_bit(PG_TEARDOWN, &subreq->wb_flags)) {
/* release ref on old head request */
nfs_release_request(old_head);
nfs_page_group_clear_bits(subreq);
/* release the PG_INODE_REF reference */
if (test_and_clear_bit(PG_INODE_REF, &subreq->wb_flags))
nfs_release_request(subreq);
else
WARN_ON_ONCE(1);
} else {
WARN_ON_ONCE(test_bit(PG_CLEAN, &subreq->wb_flags));
/* zombie requests have already released the last
* reference and were waiting on the rest of the
* group to complete. Since it's no longer part of a
* group, simply free the request */
nfs_page_group_clear_bits(subreq);
nfs_free_request(subreq);
}
}
}
/*
* nfs_lock_and_join_requests - join all subreqs to the head req and return
* a locked reference, cancelling any pending
* operations for this page.
*
* @page - the page used to lookup the "page group" of nfs_page structures
* @nonblock - if true, don't block waiting for request locks
*
* This function joins all sub requests to the head request by first
* locking all requests in the group, cancelling any pending operations
* and finally updating the head request to cover the whole range covered by
* the (former) group. All subrequests are removed from any write or commit
* lists, unlinked from the group and destroyed.
*
* Returns a locked, referenced pointer to the head request - which after
* this call is guaranteed to be the only request associated with the page.
* Returns NULL if no requests are found for @page, or a ERR_PTR if an
* error was encountered.
*/
static struct nfs_page *
nfs_lock_and_join_requests(struct page *page, bool nonblock)
{
struct inode *inode = page_file_mapping(page)->host;
struct nfs_page *head, *subreq;
struct nfs_page *destroy_list = NULL;
unsigned int total_bytes;
int ret;
try_again:
total_bytes = 0;
WARN_ON_ONCE(destroy_list);
spin_lock(&inode->i_lock);
/*
* A reference is taken only on the head request which acts as a
* reference to the whole page group - the group will not be destroyed
* until the head reference is released.
*/
head = nfs_page_find_head_request_locked(NFS_I(inode), page);
if (!head) {
spin_unlock(&inode->i_lock);
return NULL;
}
/* holding inode lock, so always make a non-blocking call to try the
* page group lock */
ret = nfs_page_group_lock(head, true);
if (ret < 0) {
spin_unlock(&inode->i_lock);
if (!nonblock && ret == -EAGAIN) {
nfs_page_group_lock_wait(head);
nfs_release_request(head);
goto try_again;
}
nfs_release_request(head);
return ERR_PTR(ret);
}
/* lock each request in the page group */
subreq = head;
do {
/*
* Subrequests are always contiguous, non overlapping
* and in order - but may be repeated (mirrored writes).
*/
if (subreq->wb_offset == (head->wb_offset + total_bytes)) {
/* keep track of how many bytes this group covers */
total_bytes += subreq->wb_bytes;
} else if (WARN_ON_ONCE(subreq->wb_offset < head->wb_offset ||
((subreq->wb_offset + subreq->wb_bytes) >
(head->wb_offset + total_bytes)))) {
nfs_page_group_unlock(head);
spin_unlock(&inode->i_lock);
return ERR_PTR(-EIO);
}
if (!nfs_lock_request(subreq)) {
/* releases page group bit lock and
* inode spin lock and all references */
ret = nfs_unroll_locks_and_wait(inode, head,
subreq, nonblock);
if (ret == 0)
goto try_again;
return ERR_PTR(ret);
}
subreq = subreq->wb_this_page;
} while (subreq != head);
/* Now that all requests are locked, make sure they aren't on any list.
* Commit list removal accounting is done after locks are dropped */
subreq = head;
do {
nfs_clear_request_commit(subreq);
subreq = subreq->wb_this_page;
} while (subreq != head);
/* unlink subrequests from head, destroy them later */
if (head->wb_this_page != head) {
/* destroy list will be terminated by head */
destroy_list = head->wb_this_page;
head->wb_this_page = head;
/* change head request to cover whole range that
* the former page group covered */
head->wb_bytes = total_bytes;
}
/*
* prepare head request to be added to new pgio descriptor
*/
nfs_page_group_clear_bits(head);
/*
* some part of the group was still on the inode list - otherwise
* the group wouldn't be involved in async write.
* grab a reference for the head request, iff it needs one.
*/
if (!test_and_set_bit(PG_INODE_REF, &head->wb_flags))
kref_get(&head->wb_kref);
nfs_page_group_unlock(head);
/* drop lock to clean uprequests on destroy list */
spin_unlock(&inode->i_lock);
nfs_destroy_unlinked_subrequests(destroy_list, head);
/* still holds ref on head from nfs_page_find_head_request_locked
* and still has lock on head from lock loop */
return head;
}
static void nfs_write_error_remove_page(struct nfs_page *req)
{
nfs_unlock_request(req);
nfs_end_page_writeback(req);
nfs_release_request(req);
generic_error_remove_page(page_file_mapping(req->wb_page),
req->wb_page);
}
/*
* Find an associated nfs write request, and prepare to flush it out
* May return an error if the user signalled nfs_wait_on_request().
*/
static int nfs_page_async_flush(struct nfs_pageio_descriptor *pgio,
struct page *page, bool nonblock,
bool launder)
{
struct nfs_page *req;
int ret = 0;
req = nfs_lock_and_join_requests(page, nonblock);
if (!req)
goto out;
ret = PTR_ERR(req);
if (IS_ERR(req))
goto out;
nfs_set_page_writeback(page);
WARN_ON_ONCE(test_bit(PG_CLEAN, &req->wb_flags));
ret = 0;
if (!nfs_pageio_add_request(pgio, req)) {
ret = pgio->pg_error;
/*
* Remove the problematic req upon fatal errors
* in launder case, while other dirty pages can
* still be around until they get flushed.
*/
if (nfs_error_is_fatal(ret)) {
nfs_context_set_write_error(req->wb_context, ret);
if (launder) {
nfs_write_error_remove_page(req);
goto out;
}
}
nfs_redirty_request(req);
ret = -EAGAIN;
} else
nfs_add_stats(page_file_mapping(page)->host,
NFSIOS_WRITEPAGES, 1);
out:
return ret;
}
static int nfs_do_writepage(struct page *page, struct writeback_control *wbc,
struct nfs_pageio_descriptor *pgio, bool launder)
{
int ret;
nfs_pageio_cond_complete(pgio, page_file_index(page));
ret = nfs_page_async_flush(pgio, page, wbc->sync_mode == WB_SYNC_NONE,
launder);
if (ret == -EAGAIN) {
redirty_page_for_writepage(wbc, page);
ret = 0;
}
return ret;
}
/*
* Write an mmapped page to the server.
*/
static int nfs_writepage_locked(struct page *page,
struct writeback_control *wbc,
bool launder)
{
struct nfs_pageio_descriptor pgio;
struct inode *inode = page_file_mapping(page)->host;
int err;
nfs_inc_stats(inode, NFSIOS_VFSWRITEPAGE);
nfs_pageio_init_write(&pgio, inode, wb_priority(wbc),
false, &nfs_async_write_completion_ops);
err = nfs_do_writepage(page, wbc, &pgio, launder);
nfs_pageio_complete(&pgio);
if (err < 0)
return err;
if (pgio.pg_error < 0)
return pgio.pg_error;
return 0;
}
int nfs_writepage(struct page *page, struct writeback_control *wbc)
{
int ret;
ret = nfs_writepage_locked(page, wbc, false);
unlock_page(page);
return ret;
}
static int nfs_writepages_callback(struct page *page, struct writeback_control *wbc, void *data)
{
int ret;
ret = nfs_do_writepage(page, wbc, data, false);
unlock_page(page);
return ret;
}
int nfs_writepages(struct address_space *mapping, struct writeback_control *wbc)
{
struct inode *inode = mapping->host;
unsigned long *bitlock = &NFS_I(inode)->flags;
struct nfs_pageio_descriptor pgio;
int err;
/* Stop dirtying of new pages while we sync */
err = wait_on_bit_lock_action(bitlock, NFS_INO_FLUSHING,
nfs_wait_bit_killable, TASK_KILLABLE);
if (err)
goto out_err;
nfs_inc_stats(inode, NFSIOS_VFSWRITEPAGES);
nfs_pageio_init_write(&pgio, inode, wb_priority(wbc), false,
&nfs_async_write_completion_ops);
err = write_cache_pages(mapping, wbc, nfs_writepages_callback, &pgio);
nfs_pageio_complete(&pgio);
clear_bit_unlock(NFS_INO_FLUSHING, bitlock);
smp_mb__after_atomic();
wake_up_bit(bitlock, NFS_INO_FLUSHING);
if (err < 0)
goto out_err;
err = pgio.pg_error;
if (err < 0)
goto out_err;
return 0;
out_err:
return err;
}
/*
* Insert a write request into an inode
*/
static void nfs_inode_add_request(struct inode *inode, struct nfs_page *req)
{
struct nfs_inode *nfsi = NFS_I(inode);
WARN_ON_ONCE(req->wb_this_page != req);
/* Lock the request! */
nfs_lock_request(req);
spin_lock(&inode->i_lock);
if (!nfsi->nrequests &&
NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE))
inode->i_version++;
/*
* Swap-space should not get truncated. Hence no need to plug the race
* with invalidate/truncate.
*/
if (likely(!PageSwapCache(req->wb_page))) {
set_bit(PG_MAPPED, &req->wb_flags);
SetPagePrivate(req->wb_page);
set_page_private(req->wb_page, (unsigned long)req);
}
nfsi->nrequests++;
/* this a head request for a page group - mark it as having an
* extra reference so sub groups can follow suit.
* This flag also informs pgio layer when to bump nrequests when
* adding subrequests. */
WARN_ON(test_and_set_bit(PG_INODE_REF, &req->wb_flags));
kref_get(&req->wb_kref);
spin_unlock(&inode->i_lock);
}
/*
* Remove a write request from an inode
*/
static void nfs_inode_remove_request(struct nfs_page *req)
{
struct inode *inode = d_inode(req->wb_context->dentry);
struct nfs_inode *nfsi = NFS_I(inode);
struct nfs_page *head;
if (nfs_page_group_sync_on_bit(req, PG_REMOVE)) {
head = req->wb_head;
spin_lock(&inode->i_lock);
if (likely(head->wb_page && !PageSwapCache(head->wb_page))) {
set_page_private(head->wb_page, 0);
ClearPagePrivate(head->wb_page);
smp_mb__after_atomic();
wake_up_page(head->wb_page, PG_private);
clear_bit(PG_MAPPED, &head->wb_flags);
}
nfsi->nrequests--;
spin_unlock(&inode->i_lock);
} else {
spin_lock(&inode->i_lock);
nfsi->nrequests--;
spin_unlock(&inode->i_lock);
}
if (test_and_clear_bit(PG_INODE_REF, &req->wb_flags))
nfs_release_request(req);
}
static void
nfs_mark_request_dirty(struct nfs_page *req)
{
if (req->wb_page)
__set_page_dirty_nobuffers(req->wb_page);
}
/*
* nfs_page_search_commits_for_head_request_locked
*
* Search through commit lists on @inode for the head request for @page.
* Must be called while holding the inode (which is cinfo) lock.
*
* Returns the head request if found, or NULL if not found.
*/
static struct nfs_page *
nfs_page_search_commits_for_head_request_locked(struct nfs_inode *nfsi,
struct page *page)
{
struct nfs_page *freq, *t;
struct nfs_commit_info cinfo;
struct inode *inode = &nfsi->vfs_inode;
nfs_init_cinfo_from_inode(&cinfo, inode);
/* search through pnfs commit lists */
freq = pnfs_search_commit_reqs(inode, &cinfo, page);
if (freq)
return freq->wb_head;
/* Linearly search the commit list for the correct request */
list_for_each_entry_safe(freq, t, &cinfo.mds->list, wb_list) {
if (freq->wb_page == page)
return freq->wb_head;
}
return NULL;
}
/**
* nfs_request_add_commit_list_locked - add request to a commit list
* @req: pointer to a struct nfs_page
* @dst: commit list head
* @cinfo: holds list lock and accounting info
*
* This sets the PG_CLEAN bit, updates the cinfo count of
* number of outstanding requests requiring a commit as well as
* the MM page stats.
*
* The caller must hold cinfo->inode->i_lock, and the nfs_page lock.
*/
void
nfs_request_add_commit_list_locked(struct nfs_page *req, struct list_head *dst,
struct nfs_commit_info *cinfo)
{
set_bit(PG_CLEAN, &req->wb_flags);
nfs_list_add_request(req, dst);
cinfo->mds->ncommit++;
}
EXPORT_SYMBOL_GPL(nfs_request_add_commit_list_locked);
/**
* nfs_request_add_commit_list - add request to a commit list
* @req: pointer to a struct nfs_page
* @dst: commit list head
* @cinfo: holds list lock and accounting info
*
* This sets the PG_CLEAN bit, updates the cinfo count of
* number of outstanding requests requiring a commit as well as
* the MM page stats.
*
* The caller must _not_ hold the cinfo->lock, but must be
* holding the nfs_page lock.
*/
void
nfs_request_add_commit_list(struct nfs_page *req, struct nfs_commit_info *cinfo)
{
spin_lock(&cinfo->inode->i_lock);
nfs_request_add_commit_list_locked(req, &cinfo->mds->list, cinfo);
spin_unlock(&cinfo->inode->i_lock);
if (req->wb_page)
nfs_mark_page_unstable(req->wb_page, cinfo);
}
EXPORT_SYMBOL_GPL(nfs_request_add_commit_list);
/**
* nfs_request_remove_commit_list - Remove request from a commit list
* @req: pointer to a nfs_page
* @cinfo: holds list lock and accounting info
*
* This clears the PG_CLEAN bit, and updates the cinfo's count of
* number of outstanding requests requiring a commit
* It does not update the MM page stats.
*
* The caller _must_ hold the cinfo->lock and the nfs_page lock.
*/
void
nfs_request_remove_commit_list(struct nfs_page *req,
struct nfs_commit_info *cinfo)
{
if (!test_and_clear_bit(PG_CLEAN, &(req)->wb_flags))
return;
nfs_list_remove_request(req);
cinfo->mds->ncommit--;
}
EXPORT_SYMBOL_GPL(nfs_request_remove_commit_list);
static void nfs_init_cinfo_from_inode(struct nfs_commit_info *cinfo,
struct inode *inode)
{
cinfo->inode = inode;
cinfo->mds = &NFS_I(inode)->commit_info;
cinfo->ds = pnfs_get_ds_info(inode);
cinfo->dreq = NULL;
cinfo->completion_ops = &nfs_commit_completion_ops;
}
void nfs_init_cinfo(struct nfs_commit_info *cinfo,
struct inode *inode,
struct nfs_direct_req *dreq)
{
if (dreq)
nfs_init_cinfo_from_dreq(cinfo, dreq);
else
nfs_init_cinfo_from_inode(cinfo, inode);
}
EXPORT_SYMBOL_GPL(nfs_init_cinfo);
/*
* Add a request to the inode's commit list.
*/
void
nfs_mark_request_commit(struct nfs_page *req, struct pnfs_layout_segment *lseg,
struct nfs_commit_info *cinfo, u32 ds_commit_idx)
{
if (pnfs_mark_request_commit(req, lseg, cinfo, ds_commit_idx))
return;
nfs_request_add_commit_list(req, cinfo);
}
static void
nfs_clear_page_commit(struct page *page)
{
dec_zone_page_state(page, NR_UNSTABLE_NFS);
dec_wb_stat(&inode_to_bdi(page_file_mapping(page)->host)->wb,
WB_RECLAIMABLE);
}
/* Called holding inode (/cinfo) lock */
static void
nfs_clear_request_commit(struct nfs_page *req)
{
if (test_bit(PG_CLEAN, &req->wb_flags)) {
struct inode *inode = d_inode(req->wb_context->dentry);
struct nfs_commit_info cinfo;
nfs_init_cinfo_from_inode(&cinfo, inode);
if (!pnfs_clear_request_commit(req, &cinfo)) {
nfs_request_remove_commit_list(req, &cinfo);
}
nfs_clear_page_commit(req->wb_page);
}
}
int nfs_write_need_commit(struct nfs_pgio_header *hdr)
{
if (hdr->verf.committed == NFS_DATA_SYNC)
return hdr->lseg == NULL;
return hdr->verf.committed != NFS_FILE_SYNC;
}
static void nfs_write_completion(struct nfs_pgio_header *hdr)
{
struct nfs_commit_info cinfo;
unsigned long bytes = 0;
if (test_bit(NFS_IOHDR_REDO, &hdr->flags))
goto out;
nfs_init_cinfo_from_inode(&cinfo, hdr->inode);
while (!list_empty(&hdr->pages)) {
struct nfs_page *req = nfs_list_entry(hdr->pages.next);
bytes += req->wb_bytes;
nfs_list_remove_request(req);
if (test_bit(NFS_IOHDR_ERROR, &hdr->flags) &&
(hdr->good_bytes < bytes)) {
nfs_set_pageerror(req->wb_page);
nfs_context_set_write_error(req->wb_context, hdr->error);
goto remove_req;
}
if (nfs_write_need_commit(hdr)) {
memcpy(&req->wb_verf, &hdr->verf.verifier, sizeof(req->wb_verf));
nfs_mark_request_commit(req, hdr->lseg, &cinfo,
hdr->pgio_mirror_idx);
goto next;
}
remove_req:
nfs_inode_remove_request(req);
next:
nfs_unlock_request(req);
nfs_end_page_writeback(req);
nfs_release_request(req);
}
out:
hdr->release(hdr);
}
unsigned long
nfs_reqs_to_commit(struct nfs_commit_info *cinfo)
{
return cinfo->mds->ncommit;
}
/* cinfo->inode->i_lock held by caller */
int
nfs_scan_commit_list(struct list_head *src, struct list_head *dst,
struct nfs_commit_info *cinfo, int max)
{
struct nfs_page *req, *tmp;
int ret = 0;
list_for_each_entry_safe(req, tmp, src, wb_list) {
if (!nfs_lock_request(req))
continue;
kref_get(&req->wb_kref);
if (cond_resched_lock(&cinfo->inode->i_lock))
list_safe_reset_next(req, tmp, wb_list);
nfs_request_remove_commit_list(req, cinfo);
nfs_list_add_request(req, dst);
ret++;
if ((ret == max) && !cinfo->dreq)
break;
}
return ret;
}
/*
* nfs_scan_commit - Scan an inode for commit requests
* @inode: NFS inode to scan
* @dst: mds destination list
* @cinfo: mds and ds lists of reqs ready to commit
*
* Moves requests from the inode's 'commit' request list.
* The requests are *not* checked to ensure that they form a contiguous set.
*/
int
nfs_scan_commit(struct inode *inode, struct list_head *dst,
struct nfs_commit_info *cinfo)
{
int ret = 0;
spin_lock(&cinfo->inode->i_lock);
if (cinfo->mds->ncommit > 0) {
const int max = INT_MAX;
ret = nfs_scan_commit_list(&cinfo->mds->list, dst,
cinfo, max);
ret += pnfs_scan_commit_lists(inode, cinfo, max - ret);
}
spin_unlock(&cinfo->inode->i_lock);
return ret;
}
/*
* Search for an existing write request, and attempt to update
* it to reflect a new dirty region on a given page.
*
* If the attempt fails, then the existing request is flushed out
* to disk.
*/
static struct nfs_page *nfs_try_to_update_request(struct inode *inode,
struct page *page,
unsigned int offset,
unsigned int bytes)
{
struct nfs_page *req;
unsigned int rqend;
unsigned int end;
int error;
if (!PagePrivate(page))
return NULL;
end = offset + bytes;
spin_lock(&inode->i_lock);
for (;;) {
req = nfs_page_find_head_request_locked(NFS_I(inode), page);
if (req == NULL)
goto out_unlock;
/* should be handled by nfs_flush_incompatible */
WARN_ON_ONCE(req->wb_head != req);
WARN_ON_ONCE(req->wb_this_page != req);
rqend = req->wb_offset + req->wb_bytes;
/*
* Tell the caller to flush out the request if
* the offsets are non-contiguous.
* Note: nfs_flush_incompatible() will already
* have flushed out requests having wrong owners.
*/
if (offset > rqend
|| end < req->wb_offset)
goto out_flushme;
if (nfs_lock_request(req))
break;
/* The request is locked, so wait and then retry */
spin_unlock(&inode->i_lock);
error = nfs_wait_on_request(req);
nfs_release_request(req);
if (error != 0)
goto out_err;
spin_lock(&inode->i_lock);
}
/* Okay, the request matches. Update the region */
if (offset < req->wb_offset) {
req->wb_offset = offset;
req->wb_pgbase = offset;
}
if (end > rqend)
req->wb_bytes = end - req->wb_offset;
else
req->wb_bytes = rqend - req->wb_offset;
out_unlock:
if (req)
nfs_clear_request_commit(req);
spin_unlock(&inode->i_lock);
return req;
out_flushme:
spin_unlock(&inode->i_lock);
nfs_release_request(req);
error = nfs_wb_page(inode, page);
out_err:
return ERR_PTR(error);
}
/*
* Try to update an existing write request, or create one if there is none.
*
* Note: Should always be called with the Page Lock held to prevent races
* if we have to add a new request. Also assumes that the caller has
* already called nfs_flush_incompatible() if necessary.
*/
static struct nfs_page * nfs_setup_write_request(struct nfs_open_context* ctx,
struct page *page, unsigned int offset, unsigned int bytes)
{
struct inode *inode = page_file_mapping(page)->host;
struct nfs_page *req;
req = nfs_try_to_update_request(inode, page, offset, bytes);
if (req != NULL)
goto out;
req = nfs_create_request(ctx, page, NULL, offset, bytes);
if (IS_ERR(req))
goto out;
nfs_inode_add_request(inode, req);
out:
return req;
}
static int nfs_writepage_setup(struct nfs_open_context *ctx, struct page *page,
unsigned int offset, unsigned int count)
{
struct nfs_page *req;
req = nfs_setup_write_request(ctx, page, offset, count);
if (IS_ERR(req))
return PTR_ERR(req);
/* Update file length */
nfs_grow_file(page, offset, count);
nfs_mark_uptodate(req);
nfs_mark_request_dirty(req);
nfs_unlock_and_release_request(req);
return 0;
}
int nfs_flush_incompatible(struct file *file, struct page *page)
{
struct nfs_open_context *ctx = nfs_file_open_context(file);
struct nfs_lock_context *l_ctx;
struct file_lock_context *flctx = file_inode(file)->i_flctx;
struct nfs_page *req;
int do_flush, status;
/*
* Look for a request corresponding to this page. If there
* is one, and it belongs to another file, we flush it out
* before we try to copy anything into the page. Do this
* due to the lack of an ACCESS-type call in NFSv2.
* Also do the same if we find a request from an existing
* dropped page.
*/
do {
req = nfs_page_find_head_request(page);
if (req == NULL)
return 0;
l_ctx = req->wb_lock_context;
do_flush = req->wb_page != page ||
!nfs_match_open_context(req->wb_context, ctx);
/* for now, flush if more than 1 request in page_group */
do_flush |= req->wb_this_page != req;
if (l_ctx && flctx &&
!(list_empty_careful(&flctx->flc_posix) &&
list_empty_careful(&flctx->flc_flock))) {
do_flush |= l_ctx->lockowner.l_owner != current->files
|| l_ctx->lockowner.l_pid != current->tgid;
}
nfs_release_request(req);
if (!do_flush)
return 0;
status = nfs_wb_page(page_file_mapping(page)->host, page);
} while (status == 0);
return status;
}
/*
* Avoid buffered writes when a open context credential's key would
* expire soon.
*
* Returns -EACCES if the key will expire within RPC_KEY_EXPIRE_FAIL.
*
* Return 0 and set a credential flag which triggers the inode to flush
* and performs NFS_FILE_SYNC writes if the key will expired within
* RPC_KEY_EXPIRE_TIMEO.
*/
int
nfs_key_timeout_notify(struct file *filp, struct inode *inode)
{
struct nfs_open_context *ctx = nfs_file_open_context(filp);
struct rpc_auth *auth = NFS_SERVER(inode)->client->cl_auth;
return rpcauth_key_timeout_notify(auth, ctx->cred);
}
/*
* Test if the open context credential key is marked to expire soon.
*/
bool nfs_ctx_key_to_expire(struct nfs_open_context *ctx)
{
return rpcauth_cred_key_to_expire(ctx->cred);
}
/*
* If the page cache is marked as unsafe or invalid, then we can't rely on
* the PageUptodate() flag. In this case, we will need to turn off
* write optimisations that depend on the page contents being correct.
*/
static bool nfs_write_pageuptodate(struct page *page, struct inode *inode)
{
struct nfs_inode *nfsi = NFS_I(inode);
if (nfs_have_delegated_attributes(inode))
goto out;
if (nfsi->cache_validity & NFS_INO_REVAL_PAGECACHE)
return false;
smp_rmb();
if (test_bit(NFS_INO_INVALIDATING, &nfsi->flags))
return false;
out:
if (nfsi->cache_validity & NFS_INO_INVALID_DATA)
return false;
return PageUptodate(page) != 0;
}
static bool
is_whole_file_wrlock(struct file_lock *fl)
{
return fl->fl_start == 0 && fl->fl_end == OFFSET_MAX &&
fl->fl_type == F_WRLCK;
}
/* If we know the page is up to date, and we're not using byte range locks (or
* if we have the whole file locked for writing), it may be more efficient to
* extend the write to cover the entire page in order to avoid fragmentation
* inefficiencies.
*
* If the file is opened for synchronous writes then we can just skip the rest
* of the checks.
*/
static int nfs_can_extend_write(struct file *file, struct page *page, struct inode *inode)
{
int ret;
struct file_lock_context *flctx = inode->i_flctx;
struct file_lock *fl;
if (file->f_flags & O_DSYNC)
return 0;
if (!nfs_write_pageuptodate(page, inode))
return 0;
if (NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE))
return 1;
if (!flctx || (list_empty_careful(&flctx->flc_flock) &&
list_empty_careful(&flctx->flc_posix)))
return 1;
/* Check to see if there are whole file write locks */
ret = 0;
spin_lock(&flctx->flc_lock);
if (!list_empty(&flctx->flc_posix)) {
fl = list_first_entry(&flctx->flc_posix, struct file_lock,
fl_list);
if (is_whole_file_wrlock(fl))
ret = 1;
} else if (!list_empty(&flctx->flc_flock)) {
fl = list_first_entry(&flctx->flc_flock, struct file_lock,
fl_list);
if (fl->fl_type == F_WRLCK)
ret = 1;
}
spin_unlock(&flctx->flc_lock);
return ret;
}
/*
* Update and possibly write a cached page of an NFS file.
*
* XXX: Keep an eye on generic_file_read to make sure it doesn't do bad
* things with a page scheduled for an RPC call (e.g. invalidate it).
*/
int nfs_updatepage(struct file *file, struct page *page,
unsigned int offset, unsigned int count)
{
struct nfs_open_context *ctx = nfs_file_open_context(file);
struct inode *inode = page_file_mapping(page)->host;
int status = 0;
nfs_inc_stats(inode, NFSIOS_VFSUPDATEPAGE);
dprintk("NFS: nfs_updatepage(%pD2 %d@%lld)\n",
file, count, (long long)(page_file_offset(page) + offset));
if (!count)
goto out;
if (nfs_can_extend_write(file, page, inode)) {
count = max(count + offset, nfs_page_length(page));
offset = 0;
}
status = nfs_writepage_setup(ctx, page, offset, count);
if (status < 0)
nfs_set_pageerror(page);
else
__set_page_dirty_nobuffers(page);
out:
dprintk("NFS: nfs_updatepage returns %d (isize %lld)\n",
status, (long long)i_size_read(inode));
return status;
}
static int flush_task_priority(int how)
{
switch (how & (FLUSH_HIGHPRI|FLUSH_LOWPRI)) {
case FLUSH_HIGHPRI:
return RPC_PRIORITY_HIGH;
case FLUSH_LOWPRI:
return RPC_PRIORITY_LOW;
}
return RPC_PRIORITY_NORMAL;
}
static void nfs_initiate_write(struct nfs_pgio_header *hdr,
struct rpc_message *msg,
const struct nfs_rpc_ops *rpc_ops,
struct rpc_task_setup *task_setup_data, int how)
{
int priority = flush_task_priority(how);
task_setup_data->priority = priority;
rpc_ops->write_setup(hdr, msg);
nfs4_state_protect_write(NFS_SERVER(hdr->inode)->nfs_client,
&task_setup_data->rpc_client, msg, hdr);
}
/* If a nfs_flush_* function fails, it should remove reqs from @head and
* call this on each, which will prepare them to be retried on next
* writeback using standard nfs.
*/
static void nfs_redirty_request(struct nfs_page *req)
{
nfs_mark_request_dirty(req);
set_bit(NFS_CONTEXT_RESEND_WRITES, &req->wb_context->flags);
nfs_unlock_request(req);
nfs_end_page_writeback(req);
nfs_release_request(req);
}
static void nfs_async_write_error(struct list_head *head)
{
struct nfs_page *req;
while (!list_empty(head)) {
req = nfs_list_entry(head->next);
nfs_list_remove_request(req);
nfs_redirty_request(req);
}
}
static void nfs_async_write_reschedule_io(struct nfs_pgio_header *hdr)
{
nfs_async_write_error(&hdr->pages);
}
static const struct nfs_pgio_completion_ops nfs_async_write_completion_ops = {
.error_cleanup = nfs_async_write_error,
.completion = nfs_write_completion,
.reschedule_io = nfs_async_write_reschedule_io,
};
void nfs_pageio_init_write(struct nfs_pageio_descriptor *pgio,
struct inode *inode, int ioflags, bool force_mds,
const struct nfs_pgio_completion_ops *compl_ops)
{
struct nfs_server *server = NFS_SERVER(inode);
const struct nfs_pageio_ops *pg_ops = &nfs_pgio_rw_ops;
#ifdef CONFIG_NFS_V4_1
if (server->pnfs_curr_ld && !force_mds)
pg_ops = server->pnfs_curr_ld->pg_write_ops;
#endif
nfs_pageio_init(pgio, inode, pg_ops, compl_ops, &nfs_rw_write_ops,
server->wsize, ioflags);
}
EXPORT_SYMBOL_GPL(nfs_pageio_init_write);
void nfs_pageio_reset_write_mds(struct nfs_pageio_descriptor *pgio)
{
struct nfs_pgio_mirror *mirror;
if (pgio->pg_ops && pgio->pg_ops->pg_cleanup)
pgio->pg_ops->pg_cleanup(pgio);
pgio->pg_ops = &nfs_pgio_rw_ops;
nfs_pageio_stop_mirroring(pgio);
mirror = &pgio->pg_mirrors[0];
mirror->pg_bsize = NFS_SERVER(pgio->pg_inode)->wsize;
}
EXPORT_SYMBOL_GPL(nfs_pageio_reset_write_mds);
void nfs_commit_prepare(struct rpc_task *task, void *calldata)
{
struct nfs_commit_data *data = calldata;
NFS_PROTO(data->inode)->commit_rpc_prepare(task, data);
}
/*
* Special version of should_remove_suid() that ignores capabilities.
*/
static int nfs_should_remove_suid(const struct inode *inode)
{
umode_t mode = inode->i_mode;
int kill = 0;
/* suid always must be killed */
if (unlikely(mode & S_ISUID))
kill = ATTR_KILL_SUID;
/*
* sgid without any exec bits is just a mandatory locking mark; leave
* it alone. If some exec bits are set, it's a real sgid; kill it.
*/
if (unlikely((mode & S_ISGID) && (mode & S_IXGRP)))
kill |= ATTR_KILL_SGID;
if (unlikely(kill && S_ISREG(mode)))
return kill;
return 0;
}
static void nfs_writeback_check_extend(struct nfs_pgio_header *hdr,
struct nfs_fattr *fattr)
{
struct nfs_pgio_args *argp = &hdr->args;
struct nfs_pgio_res *resp = &hdr->res;
u64 size = argp->offset + resp->count;
if (!(fattr->valid & NFS_ATTR_FATTR_SIZE))
fattr->size = size;
if (nfs_size_to_loff_t(fattr->size) < i_size_read(hdr->inode)) {
fattr->valid &= ~NFS_ATTR_FATTR_SIZE;
return;
}
if (size != fattr->size)
return;
/* Set attribute barrier */
nfs_fattr_set_barrier(fattr);
/* ...and update size */
fattr->valid |= NFS_ATTR_FATTR_SIZE;
}
void nfs_writeback_update_inode(struct nfs_pgio_header *hdr)
{
struct nfs_fattr *fattr = &hdr->fattr;
struct inode *inode = hdr->inode;
spin_lock(&inode->i_lock);
nfs_writeback_check_extend(hdr, fattr);
nfs_post_op_update_inode_force_wcc_locked(inode, fattr);
spin_unlock(&inode->i_lock);
}
EXPORT_SYMBOL_GPL(nfs_writeback_update_inode);
/*
* This function is called when the WRITE call is complete.
*/
static int nfs_writeback_done(struct rpc_task *task,
struct nfs_pgio_header *hdr,
struct inode *inode)
{
int status;
/*
* ->write_done will attempt to use post-op attributes to detect
* conflicting writes by other clients. A strict interpretation
* of close-to-open would allow us to continue caching even if
* another writer had changed the file, but some applications
* depend on tighter cache coherency when writing.
*/
status = NFS_PROTO(inode)->write_done(task, hdr);
if (status != 0)
return status;
nfs_add_stats(inode, NFSIOS_SERVERWRITTENBYTES, hdr->res.count);
if (hdr->res.verf->committed < hdr->args.stable &&
task->tk_status >= 0) {
/* We tried a write call, but the server did not
* commit data to stable storage even though we
* requested it.
* Note: There is a known bug in Tru64 < 5.0 in which
* the server reports NFS_DATA_SYNC, but performs
* NFS_FILE_SYNC. We therefore implement this checking
* as a dprintk() in order to avoid filling syslog.
*/
static unsigned long complain;
/* Note this will print the MDS for a DS write */
if (time_before(complain, jiffies)) {
dprintk("NFS: faulty NFS server %s:"
" (committed = %d) != (stable = %d)\n",
NFS_SERVER(inode)->nfs_client->cl_hostname,
hdr->res.verf->committed, hdr->args.stable);
complain = jiffies + 300 * HZ;
}
}
/* Deal with the suid/sgid bit corner case */
if (nfs_should_remove_suid(inode))
nfs_mark_for_revalidate(inode);
return 0;
}
/*
* This function is called when the WRITE call is complete.
*/
static void nfs_writeback_result(struct rpc_task *task,
struct nfs_pgio_header *hdr)
{
struct nfs_pgio_args *argp = &hdr->args;
struct nfs_pgio_res *resp = &hdr->res;
if (resp->count < argp->count) {
static unsigned long complain;
/* This a short write! */
nfs_inc_stats(hdr->inode, NFSIOS_SHORTWRITE);
/* Has the server at least made some progress? */
if (resp->count == 0) {
if (time_before(complain, jiffies)) {
printk(KERN_WARNING
"NFS: Server wrote zero bytes, expected %u.\n",
argp->count);
complain = jiffies + 300 * HZ;
}
nfs_set_pgio_error(hdr, -EIO, argp->offset);
task->tk_status = -EIO;
return;
}
/* For non rpc-based layout drivers, retry-through-MDS */
if (!task->tk_ops) {
hdr->pnfs_error = -EAGAIN;
return;
}
/* Was this an NFSv2 write or an NFSv3 stable write? */
if (resp->verf->committed != NFS_UNSTABLE) {
/* Resend from where the server left off */
hdr->mds_offset += resp->count;
argp->offset += resp->count;
argp->pgbase += resp->count;
argp->count -= resp->count;
} else {
/* Resend as a stable write in order to avoid
* headaches in the case of a server crash.
*/
argp->stable = NFS_FILE_SYNC;
}
rpc_restart_call_prepare(task);
}
}
static int wait_on_commit(struct nfs_mds_commit_info *cinfo)
{
return wait_on_atomic_t(&cinfo->rpcs_out,
nfs_wait_atomic_killable, TASK_KILLABLE);
}
static void nfs_commit_begin(struct nfs_mds_commit_info *cinfo)
{
atomic_inc(&cinfo->rpcs_out);
}
static void nfs_commit_end(struct nfs_mds_commit_info *cinfo)
{
if (atomic_dec_and_test(&cinfo->rpcs_out))
wake_up_atomic_t(&cinfo->rpcs_out);
}
void nfs_commitdata_release(struct nfs_commit_data *data)
{
put_nfs_open_context(data->context);
nfs_commit_free(data);
}
EXPORT_SYMBOL_GPL(nfs_commitdata_release);
int nfs_initiate_commit(struct rpc_clnt *clnt, struct nfs_commit_data *data,
const struct nfs_rpc_ops *nfs_ops,
const struct rpc_call_ops *call_ops,
int how, int flags)
{
struct rpc_task *task;
int priority = flush_task_priority(how);
struct rpc_message msg = {
.rpc_argp = &data->args,
.rpc_resp = &data->res,
.rpc_cred = data->cred,
};
struct rpc_task_setup task_setup_data = {
.task = &data->task,
.rpc_client = clnt,
.rpc_message = &msg,
.callback_ops = call_ops,
.callback_data = data,
.workqueue = nfsiod_workqueue,
.flags = RPC_TASK_ASYNC | flags,
.priority = priority,
};
/* Set up the initial task struct. */
nfs_ops->commit_setup(data, &msg);
dprintk("NFS: initiated commit call\n");
nfs4_state_protect(NFS_SERVER(data->inode)->nfs_client,
NFS_SP4_MACH_CRED_COMMIT, &task_setup_data.rpc_client, &msg);
task = rpc_run_task(&task_setup_data);
if (IS_ERR(task))
return PTR_ERR(task);
if (how & FLUSH_SYNC)
rpc_wait_for_completion_task(task);
rpc_put_task(task);
return 0;
}
EXPORT_SYMBOL_GPL(nfs_initiate_commit);
static loff_t nfs_get_lwb(struct list_head *head)
{
loff_t lwb = 0;
struct nfs_page *req;
list_for_each_entry(req, head, wb_list)
if (lwb < (req_offset(req) + req->wb_bytes))
lwb = req_offset(req) + req->wb_bytes;
return lwb;
}
/*
* Set up the argument/result storage required for the RPC call.
*/
void nfs_init_commit(struct nfs_commit_data *data,
struct list_head *head,
struct pnfs_layout_segment *lseg,
struct nfs_commit_info *cinfo)
{
struct nfs_page *first = nfs_list_entry(head->next);
struct inode *inode = d_inode(first->wb_context->dentry);
/* Set up the RPC argument and reply structs
* NB: take care not to mess about with data->commit et al. */
list_splice_init(head, &data->pages);
data->inode = inode;
data->cred = first->wb_context->cred;
data->lseg = lseg; /* reference transferred */
/* only set lwb for pnfs commit */
if (lseg)
data->lwb = nfs_get_lwb(&data->pages);
data->mds_ops = &nfs_commit_ops;
data->completion_ops = cinfo->completion_ops;
data->dreq = cinfo->dreq;
data->args.fh = NFS_FH(data->inode);
/* Note: we always request a commit of the entire inode */
data->args.offset = 0;
data->args.count = 0;
data->context = get_nfs_open_context(first->wb_context);
data->res.fattr = &data->fattr;
data->res.verf = &data->verf;
nfs_fattr_init(&data->fattr);
}
EXPORT_SYMBOL_GPL(nfs_init_commit);
void nfs_retry_commit(struct list_head *page_list,
struct pnfs_layout_segment *lseg,
struct nfs_commit_info *cinfo,
u32 ds_commit_idx)
{
struct nfs_page *req;
while (!list_empty(page_list)) {
req = nfs_list_entry(page_list->next);
nfs_list_remove_request(req);
nfs_mark_request_commit(req, lseg, cinfo, ds_commit_idx);
if (!cinfo->dreq)
nfs_clear_page_commit(req->wb_page);
nfs_unlock_and_release_request(req);
}
}
EXPORT_SYMBOL_GPL(nfs_retry_commit);
static void
nfs_commit_resched_write(struct nfs_commit_info *cinfo,
struct nfs_page *req)
{
__set_page_dirty_nobuffers(req->wb_page);
}
/*
* Commit dirty pages
*/
static int
nfs_commit_list(struct inode *inode, struct list_head *head, int how,
struct nfs_commit_info *cinfo)
{
struct nfs_commit_data *data;
/* another commit raced with us */
if (list_empty(head))
return 0;
data = nfs_commitdata_alloc();
if (!data)
goto out_bad;
/* Set up the argument struct */
nfs_init_commit(data, head, NULL, cinfo);
atomic_inc(&cinfo->mds->rpcs_out);
return nfs_initiate_commit(NFS_CLIENT(inode), data, NFS_PROTO(inode),
data->mds_ops, how, 0);
out_bad:
nfs_retry_commit(head, NULL, cinfo, 0);
return -ENOMEM;
}
int nfs_commit_file(struct file *file, struct nfs_write_verifier *verf)
{
struct inode *inode = file_inode(file);
struct nfs_open_context *open;
struct nfs_commit_info cinfo;
struct nfs_page *req;
int ret;
open = get_nfs_open_context(nfs_file_open_context(file));
req = nfs_create_request(open, NULL, NULL, 0, i_size_read(inode));
if (IS_ERR(req)) {
ret = PTR_ERR(req);
goto out_put;
}
nfs_init_cinfo_from_inode(&cinfo, inode);
memcpy(&req->wb_verf, verf, sizeof(struct nfs_write_verifier));
nfs_request_add_commit_list(req, &cinfo);
ret = nfs_commit_inode(inode, FLUSH_SYNC);
if (ret > 0)
ret = 0;
nfs_free_request(req);
out_put:
put_nfs_open_context(open);
return ret;
}
EXPORT_SYMBOL_GPL(nfs_commit_file);
/*
* COMMIT call returned
*/
static void nfs_commit_done(struct rpc_task *task, void *calldata)
{
struct nfs_commit_data *data = calldata;
dprintk("NFS: %5u nfs_commit_done (status %d)\n",
task->tk_pid, task->tk_status);
/* Call the NFS version-specific code */
NFS_PROTO(data->inode)->commit_done(task, data);
}
static void nfs_commit_release_pages(struct nfs_commit_data *data)
{
struct nfs_page *req;
int status = data->task.tk_status;
struct nfs_commit_info cinfo;
struct nfs_server *nfss;
while (!list_empty(&data->pages)) {
req = nfs_list_entry(data->pages.next);
nfs_list_remove_request(req);
if (req->wb_page)
nfs_clear_page_commit(req->wb_page);
dprintk("NFS: commit (%s/%llu %d@%lld)",
req->wb_context->dentry->d_sb->s_id,
(unsigned long long)NFS_FILEID(d_inode(req->wb_context->dentry)),
req->wb_bytes,
(long long)req_offset(req));
if (status < 0) {
nfs_context_set_write_error(req->wb_context, status);
nfs_inode_remove_request(req);
dprintk(", error = %d\n", status);
goto next;
}
/* Okay, COMMIT succeeded, apparently. Check the verifier
* returned by the server against all stored verfs. */
if (!memcmp(&req->wb_verf, &data->verf.verifier, sizeof(req->wb_verf))) {
/* We have a match */
nfs_inode_remove_request(req);
dprintk(" OK\n");
goto next;
}
/* We have a mismatch. Write the page again */
dprintk(" mismatch\n");
nfs_mark_request_dirty(req);
set_bit(NFS_CONTEXT_RESEND_WRITES, &req->wb_context->flags);
next:
nfs_unlock_and_release_request(req);
}
nfss = NFS_SERVER(data->inode);
if (atomic_long_read(&nfss->writeback) < NFS_CONGESTION_OFF_THRESH)
clear_bdi_congested(&nfss->backing_dev_info, BLK_RW_ASYNC);
nfs_init_cinfo(&cinfo, data->inode, data->dreq);
nfs_commit_end(cinfo.mds);
}
static void nfs_commit_release(void *calldata)
{
struct nfs_commit_data *data = calldata;
data->completion_ops->completion(data);
nfs_commitdata_release(calldata);
}
static const struct rpc_call_ops nfs_commit_ops = {
.rpc_call_prepare = nfs_commit_prepare,
.rpc_call_done = nfs_commit_done,
.rpc_release = nfs_commit_release,
};
static const struct nfs_commit_completion_ops nfs_commit_completion_ops = {
.completion = nfs_commit_release_pages,
.resched_write = nfs_commit_resched_write,
};
int nfs_generic_commit_list(struct inode *inode, struct list_head *head,
int how, struct nfs_commit_info *cinfo)
{
int status;
status = pnfs_commit_list(inode, head, how, cinfo);
if (status == PNFS_NOT_ATTEMPTED)
status = nfs_commit_list(inode, head, how, cinfo);
return status;
}
int nfs_commit_inode(struct inode *inode, int how)
{
LIST_HEAD(head);
struct nfs_commit_info cinfo;
int may_wait = how & FLUSH_SYNC;
int error = 0;
int res;
nfs_init_cinfo_from_inode(&cinfo, inode);
nfs_commit_begin(cinfo.mds);
res = nfs_scan_commit(inode, &head, &cinfo);
if (res)
error = nfs_generic_commit_list(inode, &head, how, &cinfo);
nfs_commit_end(cinfo.mds);
if (error < 0)
goto out_error;
if (!may_wait)
goto out_mark_dirty;
error = wait_on_commit(cinfo.mds);
if (error < 0)
return error;
return res;
out_error:
res = error;
/* Note: If we exit without ensuring that the commit is complete,
* we must mark the inode as dirty. Otherwise, future calls to
* sync_inode() with the WB_SYNC_ALL flag set will fail to ensure
* that the data is on the disk.
*/
out_mark_dirty:
__mark_inode_dirty(inode, I_DIRTY_DATASYNC);
return res;
}
EXPORT_SYMBOL_GPL(nfs_commit_inode);
int nfs_write_inode(struct inode *inode, struct writeback_control *wbc)
{
struct nfs_inode *nfsi = NFS_I(inode);
int flags = FLUSH_SYNC;
int ret = 0;
/* no commits means nothing needs to be done */
if (!nfsi->commit_info.ncommit)
return ret;
if (wbc->sync_mode == WB_SYNC_NONE) {
/* Don't commit yet if this is a non-blocking flush and there
* are a lot of outstanding writes for this mapping.
*/
if (nfsi->commit_info.ncommit <= (nfsi->nrequests >> 1))
goto out_mark_dirty;
/* don't wait for the COMMIT response */
flags = 0;
}
ret = nfs_commit_inode(inode, flags);
if (ret >= 0) {
if (wbc->sync_mode == WB_SYNC_NONE) {
if (ret < wbc->nr_to_write)
wbc->nr_to_write -= ret;
else
wbc->nr_to_write = 0;
}
return 0;
}
out_mark_dirty:
__mark_inode_dirty(inode, I_DIRTY_DATASYNC);
return ret;
}
EXPORT_SYMBOL_GPL(nfs_write_inode);
/*
* flush the inode to disk.
*/
int nfs_wb_all(struct inode *inode)
{
int ret;
trace_nfs_writeback_inode_enter(inode);
ret = filemap_write_and_wait(inode->i_mapping);
if (ret)
goto out;
ret = nfs_commit_inode(inode, FLUSH_SYNC);
if (ret < 0)
goto out;
pnfs_sync_inode(inode, true);
ret = 0;
out:
trace_nfs_writeback_inode_exit(inode, ret);
return ret;
}
EXPORT_SYMBOL_GPL(nfs_wb_all);
int nfs_wb_page_cancel(struct inode *inode, struct page *page)
{
struct nfs_page *req;
int ret = 0;
wait_on_page_writeback(page);
/* blocking call to cancel all requests and join to a single (head)
* request */
req = nfs_lock_and_join_requests(page, false);
if (IS_ERR(req)) {
ret = PTR_ERR(req);
} else if (req) {
/* all requests from this page have been cancelled by
* nfs_lock_and_join_requests, so just remove the head
* request from the inode / page_private pointer and
* release it */
nfs_inode_remove_request(req);
nfs_unlock_and_release_request(req);
}
return ret;
}
/*
* Write back all requests on one page - we do this before reading it.
*/
int nfs_wb_single_page(struct inode *inode, struct page *page, bool launder)
{
loff_t range_start = page_file_offset(page);
loff_t range_end = range_start + (loff_t)(PAGE_SIZE - 1);
struct writeback_control wbc = {
.sync_mode = WB_SYNC_ALL,
.nr_to_write = 0,
.range_start = range_start,
.range_end = range_end,
};
int ret;
trace_nfs_writeback_page_enter(inode);
for (;;) {
wait_on_page_writeback(page);
if (clear_page_dirty_for_io(page)) {
ret = nfs_writepage_locked(page, &wbc, launder);
if (ret < 0)
goto out_error;
continue;
}
ret = 0;
if (!PagePrivate(page))
break;
ret = nfs_commit_inode(inode, FLUSH_SYNC);
if (ret < 0)
goto out_error;
}
out_error:
trace_nfs_writeback_page_exit(inode, ret);
return ret;
}
#ifdef CONFIG_MIGRATION
int nfs_migrate_page(struct address_space *mapping, struct page *newpage,
struct page *page, enum migrate_mode mode)
{
/*
* If PagePrivate is set, then the page is currently associated with
* an in-progress read or write request. Don't try to migrate it.
*
* FIXME: we could do this in principle, but we'll need a way to ensure
* that we can safely release the inode reference while holding
* the page lock.
*/
if (PagePrivate(page))
return -EBUSY;
if (!nfs_fscache_release_page(page, GFP_KERNEL))
return -EBUSY;
return migrate_page(mapping, newpage, page, mode);
}
#endif
int __init nfs_init_writepagecache(void)
{
nfs_wdata_cachep = kmem_cache_create("nfs_write_data",
sizeof(struct nfs_pgio_header),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (nfs_wdata_cachep == NULL)
return -ENOMEM;
nfs_wdata_mempool = mempool_create_slab_pool(MIN_POOL_WRITE,
nfs_wdata_cachep);
if (nfs_wdata_mempool == NULL)
goto out_destroy_write_cache;
nfs_cdata_cachep = kmem_cache_create("nfs_commit_data",
sizeof(struct nfs_commit_data),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (nfs_cdata_cachep == NULL)
goto out_destroy_write_mempool;
nfs_commit_mempool = mempool_create_slab_pool(MIN_POOL_COMMIT,
nfs_cdata_cachep);
if (nfs_commit_mempool == NULL)
goto out_destroy_commit_cache;
/*
* NFS congestion size, scale with available memory.
*
* 64MB: 8192k
* 128MB: 11585k
* 256MB: 16384k
* 512MB: 23170k
* 1GB: 32768k
* 2GB: 46340k
* 4GB: 65536k
* 8GB: 92681k
* 16GB: 131072k
*
* This allows larger machines to have larger/more transfers.
* Limit the default to 256M
*/
nfs_congestion_kb = (16*int_sqrt(totalram_pages)) << (PAGE_SHIFT-10);
if (nfs_congestion_kb > 256*1024)
nfs_congestion_kb = 256*1024;
return 0;
out_destroy_commit_cache:
kmem_cache_destroy(nfs_cdata_cachep);
out_destroy_write_mempool:
mempool_destroy(nfs_wdata_mempool);
out_destroy_write_cache:
kmem_cache_destroy(nfs_wdata_cachep);
return -ENOMEM;
}
void nfs_destroy_writepagecache(void)
{
mempool_destroy(nfs_commit_mempool);
kmem_cache_destroy(nfs_cdata_cachep);
mempool_destroy(nfs_wdata_mempool);
kmem_cache_destroy(nfs_wdata_cachep);
}
static const struct nfs_rw_ops nfs_rw_write_ops = {
.rw_mode = FMODE_WRITE,
.rw_alloc_header = nfs_writehdr_alloc,
.rw_free_header = nfs_writehdr_free,
.rw_done = nfs_writeback_done,
.rw_result = nfs_writeback_result,
.rw_initiate = nfs_initiate_write,
};
| gompa/linux | fs/nfs/write.c | C | gpl-2.0 | 56,355 | 25.721195 | 96 | 0.678964 | false |
/* Base/prototype target for default child (native) targets.
Copyright (C) 2004-2020 Free Software Foundation, Inc.
This file is part of GDB.
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 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 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/>. */
#ifndef INF_CHILD_H
#define INF_CHILD_H
#include "target.h"
#include "process-stratum-target.h"
/* A prototype child target. The client can override it with local
methods. */
class inf_child_target
: public memory_breakpoint_target<process_stratum_target>
{
public:
inf_child_target () = default;
~inf_child_target () override = 0;
const target_info &info () const override;
void close () override;
void disconnect (const char *, int) override;
void fetch_registers (struct regcache *, int) override = 0;
void store_registers (struct regcache *, int) override = 0;
void prepare_to_store (struct regcache *) override;
bool supports_terminal_ours () override;
void terminal_init () override;
void terminal_inferior () override;
void terminal_save_inferior () override;
void terminal_ours_for_output () override;
void terminal_ours () override;
void terminal_info (const char *, int) override;
void interrupt () override;
void pass_ctrlc () override;
void post_startup_inferior (ptid_t) override;
void mourn_inferior () override;
bool can_run () override;
bool can_create_inferior () override;
void create_inferior (const char *, const std::string &,
char **, int) override = 0;
bool can_attach () override;
void attach (const char *, int) override = 0;
void post_attach (int) override;
char *pid_to_exec_file (int pid) override;
int fileio_open (struct inferior *inf, const char *filename,
int flags, int mode, int warn_if_slow,
int *target_errno) override;
int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
ULONGEST offset, int *target_errno) override;
int fileio_pread (int fd, gdb_byte *read_buf, int len,
ULONGEST offset, int *target_errno) override;
int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
int fileio_close (int fd, int *target_errno) override;
int fileio_unlink (struct inferior *inf,
const char *filename,
int *target_errno) override;
gdb::optional<std::string> fileio_readlink (struct inferior *inf,
const char *filename,
int *target_errno) override;
bool use_agent (bool use) override;
bool can_use_agent () override;
protected:
/* Unpush the target if it wasn't explicitly open with "target native"
and there are no live inferiors left. Note: if calling this as a
result of a mourn or detach, the current inferior shall already
have its PID cleared, so it isn't counted as live. That's usually
done by calling either generic_mourn_inferior or
detach_inferior. */
void maybe_unpush_target ();
};
/* Functions for helping to write a native target. */
/* This is for native targets which use a unix/POSIX-style waitstatus. */
extern void store_waitstatus (struct target_waitstatus *, int);
/* Register TARGET as native target and set it up to respond to the
"target native" command. */
extern void add_inf_child_target (inf_child_target *target);
/* target_open_ftype callback for inf-child targets. Used by targets
that want to register an alternative target_info object. Most
targets use add_inf_child_target instead. */
extern void inf_child_open_target (const char *arg, int from_tty);
#endif
| mattstock/binutils-bexkat1 | gdb/inf-child.h | C | gpl-2.0 | 4,056 | 33.372881 | 76 | 0.711045 | false |
/*
* Copyright (C) 2013 Apple 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.
*/
#ifndef ElementChildIterator_h
#define ElementChildIterator_h
#include "ElementIterator.h"
namespace WebCore {
template <typename ElementType>
class ElementChildIterator : public ElementIterator<ElementType> {
public:
typedef ElementType value_type;
typedef ptrdiff_t difference_type;
typedef ElementType* pointer;
typedef ElementType& reference;
typedef std::forward_iterator_tag iterator_category;
ElementChildIterator(const ContainerNode& parent);
ElementChildIterator(const ContainerNode& parent, ElementType* current);
ElementChildIterator& operator--();
ElementChildIterator& operator++();
};
template <typename ElementType>
class ElementChildConstIterator : public ElementConstIterator<ElementType> {
public:
typedef const ElementType value_type;
typedef ptrdiff_t difference_type;
typedef const ElementType* pointer;
typedef const ElementType& reference;
typedef std::forward_iterator_tag iterator_category;
ElementChildConstIterator(const ContainerNode& parent);
ElementChildConstIterator(const ContainerNode& parent, const ElementType* current);
ElementChildConstIterator& operator--();
ElementChildConstIterator& operator++();
};
template <typename ElementType>
class ElementChildIteratorAdapter {
public:
ElementChildIteratorAdapter(ContainerNode& parent);
ElementChildIterator<ElementType> begin();
ElementChildIterator<ElementType> end();
ElementChildIterator<ElementType> beginAt(ElementType&);
ElementType* first();
ElementType* last();
private:
ContainerNode& m_parent;
};
template <typename ElementType>
class ElementChildConstIteratorAdapter {
public:
ElementChildConstIteratorAdapter(const ContainerNode& parent);
ElementChildConstIterator<ElementType> begin() const;
ElementChildConstIterator<ElementType> end() const;
ElementChildConstIterator<ElementType> beginAt(const ElementType&) const;
const ElementType* first() const;
const ElementType* last() const;
private:
const ContainerNode& m_parent;
};
template <typename ElementType> ElementChildIteratorAdapter<ElementType> childrenOfType(ContainerNode&);
template <typename ElementType> ElementChildConstIteratorAdapter<ElementType> childrenOfType(const ContainerNode&);
// ElementChildIterator
template <typename ElementType>
inline ElementChildIterator<ElementType>::ElementChildIterator(const ContainerNode& parent)
: ElementIterator<ElementType>(&parent)
{
}
template <typename ElementType>
inline ElementChildIterator<ElementType>::ElementChildIterator(const ContainerNode& parent, ElementType* current)
: ElementIterator<ElementType>(&parent, current)
{
}
template <typename ElementType>
inline ElementChildIterator<ElementType>& ElementChildIterator<ElementType>::operator--()
{
return static_cast<ElementChildIterator<ElementType>&>(ElementIterator<ElementType>::traversePreviousSibling());
}
template <typename ElementType>
inline ElementChildIterator<ElementType>& ElementChildIterator<ElementType>::operator++()
{
return static_cast<ElementChildIterator<ElementType>&>(ElementIterator<ElementType>::traverseNextSibling());
}
// ElementChildConstIterator
template <typename ElementType>
inline ElementChildConstIterator<ElementType>::ElementChildConstIterator(const ContainerNode& parent)
: ElementConstIterator<ElementType>(&parent)
{
}
template <typename ElementType>
inline ElementChildConstIterator<ElementType>::ElementChildConstIterator(const ContainerNode& parent, const ElementType* current)
: ElementConstIterator<ElementType>(&parent, current)
{
}
template <typename ElementType>
inline ElementChildConstIterator<ElementType>& ElementChildConstIterator<ElementType>::operator--()
{
return static_cast<ElementChildConstIterator<ElementType>&>(ElementConstIterator<ElementType>::traversePreviousSibling());
}
template <typename ElementType>
inline ElementChildConstIterator<ElementType>& ElementChildConstIterator<ElementType>::operator++()
{
return static_cast<ElementChildConstIterator<ElementType>&>(ElementConstIterator<ElementType>::traverseNextSibling());
}
// ElementChildIteratorAdapter
template <typename ElementType>
inline ElementChildIteratorAdapter<ElementType>::ElementChildIteratorAdapter(ContainerNode& parent)
: m_parent(parent)
{
}
template <typename ElementType>
inline ElementChildIterator<ElementType> ElementChildIteratorAdapter<ElementType>::begin()
{
return ElementChildIterator<ElementType>(m_parent, Traversal<ElementType>::firstChild(m_parent));
}
template <typename ElementType>
inline ElementChildIterator<ElementType> ElementChildIteratorAdapter<ElementType>::end()
{
return ElementChildIterator<ElementType>(m_parent);
}
template <typename ElementType>
inline ElementType* ElementChildIteratorAdapter<ElementType>::first()
{
return Traversal<ElementType>::firstChild(m_parent);
}
template <typename ElementType>
inline ElementType* ElementChildIteratorAdapter<ElementType>::last()
{
return Traversal<ElementType>::lastChild(m_parent);
}
template <typename ElementType>
inline ElementChildIterator<ElementType> ElementChildIteratorAdapter<ElementType>::beginAt(ElementType& child)
{
ASSERT(child.parentNode() == &m_parent);
return ElementChildIterator<ElementType>(m_parent, &child);
}
// ElementChildConstIteratorAdapter
template <typename ElementType>
inline ElementChildConstIteratorAdapter<ElementType>::ElementChildConstIteratorAdapter(const ContainerNode& parent)
: m_parent(parent)
{
}
template <typename ElementType>
inline ElementChildConstIterator<ElementType> ElementChildConstIteratorAdapter<ElementType>::begin() const
{
return ElementChildConstIterator<ElementType>(m_parent, Traversal<ElementType>::firstChild(m_parent));
}
template <typename ElementType>
inline ElementChildConstIterator<ElementType> ElementChildConstIteratorAdapter<ElementType>::end() const
{
return ElementChildConstIterator<ElementType>(m_parent);
}
template <typename ElementType>
inline const ElementType* ElementChildConstIteratorAdapter<ElementType>::first() const
{
return Traversal<ElementType>::firstChild(m_parent);
}
template <typename ElementType>
inline const ElementType* ElementChildConstIteratorAdapter<ElementType>::last() const
{
return Traversal<ElementType>::lastChild(m_parent);
}
template <typename ElementType>
inline ElementChildConstIterator<ElementType> ElementChildConstIteratorAdapter<ElementType>::beginAt(const ElementType& child) const
{
ASSERT(child.parentNode() == &m_parent);
return ElementChildConstIterator<ElementType>(m_parent, &child);
}
// Standalone functions
template <typename ElementType>
inline ElementChildIteratorAdapter<ElementType> childrenOfType(ContainerNode& parent)
{
return ElementChildIteratorAdapter<ElementType>(parent);
}
template <typename ElementType>
inline ElementChildConstIteratorAdapter<ElementType> childrenOfType(const ContainerNode& parent)
{
return ElementChildConstIteratorAdapter<ElementType>(parent);
}
}
#endif
| teamfx/openjfx-9-dev-rt | modules/javafx.web/src/main/native/Source/WebCore/dom/ElementChildIterator.h | C | gpl-2.0 | 8,392 | 33.253061 | 132 | 0.79826 | false |
/*
* (C) 1999-2003 Lars Knoll (knoll@kde.org)
* Copyright (C) 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef CSSInheritedValue_h
#define CSSInheritedValue_h
#include "CSSValue.h"
#include <wtf/PassRefPtr.h>
namespace WebCore {
class CSSInheritedValue : public CSSValue {
public:
static PassRef<CSSInheritedValue> create()
{
return adoptRef(*new CSSInheritedValue);
}
String customCSSText() const;
bool equals(const CSSInheritedValue&) const { return true; }
private:
CSSInheritedValue()
: CSSValue(InheritedClass)
{
}
};
CSS_VALUE_TYPE_CASTS(CSSInheritedValue, isInheritedValue())
} // namespace WebCore
#endif // CSSInheritedValue_h
| lostdj/Jaklin-OpenJFX | modules/web/src/main/native/Source/WebCore/css/CSSInheritedValue.h | C | gpl-2.0 | 1,489 | 28.196078 | 76 | 0.727334 | false |
<?php namespace Milon\Barcode\Facades;
use Illuminate\Support\Facades\Facade;
class DNS2DFacade extends Facade {
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor() {
return 'DNS2D';
}
}
| kelvinmbwilo/VVS | vendor/milon/barcode/src/Milon/Barcode/Facades/DNS2DFacade.php | PHP | gpl-2.0 | 295 | 17.4375 | 51 | 0.644068 | false |
/*
* 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) 1994, 95, 96, 97, 98, 99, 2000 by Ralf Baechle at alii
* Copyright (C) 1999 Silicon Graphics, Inc.
*/
#ifndef _ASM_PGTABLE_H
#define _ASM_PGTABLE_H
#include <linux/config.h>
#include <asm/addrspace.h>
#include <asm/page.h>
#ifndef _LANGUAGE_ASSEMBLY
#include <linux/linkage.h>
#include <asm/cachectl.h>
#include <asm/cacheflush.h>
#include <asm/fixmap.h>
#include <asm/types.h>
/*
* This flag is used to indicate that the page pointed to by a pte
* is dirty and requires cleaning before returning it to the user.
*/
#define PG_dcache_dirty PG_arch_1
#define Page_dcache_dirty(page) \
test_bit(PG_dcache_dirty, &(page)->flags)
#define SetPageDcacheDirty(page) \
set_bit(PG_dcache_dirty, &(page)->flags)
#define ClearPageDcacheDirty(page) \
clear_bit(PG_dcache_dirty, &(page)->flags)
/*
* - add_wired_entry() add a fixed TLB entry, and move wired register
*/
extern void add_wired_entry(unsigned long entrylo0, unsigned long entrylo1,
unsigned long entryhi, unsigned long pagemask);
/*
* - add_temporary_entry() add a temporary TLB entry. We use TLB entries
* starting at the top and working down. This is for populating the
* TLB before trap_init() puts the TLB miss handler in place. It
* should be used only for entries matching the actual page tables,
* to prevent inconsistencies.
*/
extern int add_temporary_entry(unsigned long entrylo0, unsigned long entrylo1,
unsigned long entryhi, unsigned long pagemask);
/* Basically we have the same two-level (which is the logical three level
* Linux page table layout folded) page tables as the i386. Some day
* when we have proper page coloring support we can have a 1% quicker
* tlb refill handling mechanism, but for now it is a bit slower but
* works even with the cache aliasing problem the R4k and above have.
*/
/* PMD_SHIFT determines the size of the area a second-level page table can map */
#ifdef CONFIG_64BIT_PHYS_ADDR
extern int remap_page_range_high(unsigned long from, phys_t to, unsigned long size, pgprot_t prot);
#endif
#endif /* !defined (_LANGUAGE_ASSEMBLY) */
#define PMD_SIZE (1UL << PMD_SHIFT)
#define PMD_MASK (~(PMD_SIZE-1))
/* PGDIR_SHIFT determines what a third-level page table entry can map */
#define PGDIR_SHIFT PMD_SHIFT
#define PGDIR_SIZE (1UL << PGDIR_SHIFT)
#define PGDIR_MASK (~(PGDIR_SIZE-1))
#define USER_PTRS_PER_PGD (0x80000000UL/PGDIR_SIZE)
#define FIRST_USER_PGD_NR 0
#define VMALLOC_START KSEG2
#define VMALLOC_VMADDR(x) ((unsigned long)(x))
#if CONFIG_HIGHMEM
# define VMALLOC_END (PKMAP_BASE-2*PAGE_SIZE)
#else
# define VMALLOC_END (FIXADDR_START-2*PAGE_SIZE)
#endif
#include <asm/pgtable-bits.h>
#define PAGE_NONE __pgprot(_PAGE_PRESENT | _CACHE_CACHABLE_NONCOHERENT)
#define PAGE_SHARED __pgprot(_PAGE_PRESENT | _PAGE_READ | _PAGE_WRITE | \
PAGE_CACHABLE_DEFAULT)
#define PAGE_COPY __pgprot(_PAGE_PRESENT | _PAGE_READ | \
PAGE_CACHABLE_DEFAULT)
#define PAGE_READONLY __pgprot(_PAGE_PRESENT | _PAGE_READ | \
PAGE_CACHABLE_DEFAULT)
#define PAGE_KERNEL __pgprot(_PAGE_PRESENT | __READABLE | __WRITEABLE | \
_PAGE_GLOBAL | PAGE_CACHABLE_DEFAULT)
#define PAGE_USERIO __pgprot(_PAGE_PRESENT | _PAGE_READ | _PAGE_WRITE | \
PAGE_CACHABLE_DEFAULT)
#define PAGE_KERNEL_UNCACHED __pgprot(_PAGE_PRESENT | __READABLE | \
__WRITEABLE | _PAGE_GLOBAL | _CACHE_UNCACHED)
/*
* MIPS can't do page protection for execute, and considers that the same like
* read. Also, write permissions imply read permissions. This is the closest
* we can get by reasonable means..
*/
#define __P000 PAGE_NONE
#define __P001 PAGE_READONLY
#define __P010 PAGE_COPY
#define __P011 PAGE_COPY
#define __P100 PAGE_READONLY
#define __P101 PAGE_READONLY
#define __P110 PAGE_COPY
#define __P111 PAGE_COPY
#define __S000 PAGE_NONE
#define __S001 PAGE_READONLY
#define __S010 PAGE_SHARED
#define __S011 PAGE_SHARED
#define __S100 PAGE_READONLY
#define __S101 PAGE_READONLY
#define __S110 PAGE_SHARED
#define __S111 PAGE_SHARED
#if defined(CONFIG_64BIT_PHYS_ADDR) && defined(CONFIG_CPU_MIPS32)
#include <asm/pgtable-64.h>
#else
#include <asm/pgtable-32.h>
#endif
#if !defined (_LANGUAGE_ASSEMBLY)
extern unsigned long empty_zero_page;
extern unsigned long zero_page_mask;
#define ZERO_PAGE(vaddr) \
(virt_to_page(empty_zero_page + (((unsigned long)(vaddr)) & zero_page_mask)))
extern void load_pgd(unsigned long pg_dir);
extern pmd_t invalid_pte_table[PAGE_SIZE/sizeof(pmd_t)];
/*
* Conversion functions: convert a page and protection to a page entry,
* and a page entry and page directory to the page they refer to.
*/
static inline unsigned long pmd_page(pmd_t pmd)
{
return pmd_val(pmd);
}
static inline void pmd_set(pmd_t * pmdp, pte_t * ptep)
{
pmd_val(*pmdp) = (((unsigned long) ptep) & PAGE_MASK);
}
static inline int pte_present(pte_t pte) { return pte_val(pte) & _PAGE_PRESENT; }
/*
* (pmds are folded into pgds so this doesn't get actually called,
* but the define is needed for a generic inline function.)
*/
#define set_pmd(pmdptr, pmdval) (*(pmdptr) = pmdval)
#define set_pgd(pgdptr, pgdval) (*(pgdptr) = pgdval)
/*
* Empty pgd/pmd entries point to the invalid_pte_table.
*/
static inline int pmd_none(pmd_t pmd)
{
return pmd_val(pmd) == (unsigned long) invalid_pte_table;
}
static inline int pmd_bad(pmd_t pmd)
{
return ((pmd_page(pmd) > (unsigned long) high_memory) ||
(pmd_page(pmd) < PAGE_OFFSET));
}
static inline int pmd_present(pmd_t pmd)
{
return (pmd_val(pmd) != (unsigned long) invalid_pte_table);
}
static inline void pmd_clear(pmd_t *pmdp)
{
pmd_val(*pmdp) = ((unsigned long) invalid_pte_table);
}
/*
* The "pgd_xxx()" functions here are trivial for a folded two-level
* setup: the pgd is never bad, and a pmd always exists (as it's folded
* into the pgd entry)
*/
static inline int pgd_none(pgd_t pgd) { return 0; }
static inline int pgd_bad(pgd_t pgd) { return 0; }
static inline int pgd_present(pgd_t pgd) { return 1; }
static inline void pgd_clear(pgd_t *pgdp) { }
/*
* The following only work if pte_present() is true.
* Undefined behaviour if not..
*/
static inline int pte_read(pte_t pte) { return (pte).pte_low & _PAGE_READ; }
static inline int pte_write(pte_t pte) { return (pte).pte_low & _PAGE_WRITE; }
static inline int pte_dirty(pte_t pte) { return (pte).pte_low & _PAGE_MODIFIED; }
static inline int pte_young(pte_t pte) { return (pte).pte_low & _PAGE_ACCESSED; }
/*
* (pmds are folded into pgds so this doesnt get actually called,
* but the define is needed for a generic inline function.)
*/
#define set_pmd(pmdptr, pmdval) (*(pmdptr) = pmdval)
#define set_pgd(pgdptr, pgdval) (*(pgdptr) = pgdval)
#define page_pte(page) page_pte_prot(page, __pgprot(0))
#define __pgd_offset(address) pgd_index(address)
#define __pmd_offset(address) \
(((address) >> PMD_SHIFT) & (PTRS_PER_PMD-1))
/* to find an entry in a kernel page-table-directory */
#define pgd_offset_k(address) pgd_offset(&init_mm, address)
#define pgd_index(address) ((address) >> PGDIR_SHIFT)
/* to find an entry in a page-table-directory */
static inline pgd_t *pgd_offset(struct mm_struct *mm, unsigned long address)
{
return mm->pgd + pgd_index(address);
}
/* Find an entry in the second-level page table.. */
static inline pmd_t *pmd_offset(pgd_t *dir, unsigned long address)
{
return (pmd_t *) dir;
}
/* Find an entry in the third-level page table.. */
static inline pte_t *pte_offset(pmd_t * dir, unsigned long address)
{
return (pte_t *) (pmd_page(*dir)) +
((address >> PAGE_SHIFT) & (PTRS_PER_PTE - 1));
}
extern int do_check_pgt_cache(int, int);
extern pgd_t swapper_pg_dir[1024];
extern void paging_init(void);
extern void __update_tlb(struct vm_area_struct *vma, unsigned long address,
pte_t pte);
extern void __update_cache(struct vm_area_struct *vma, unsigned long address,
pte_t pte);
static inline void update_mmu_cache(struct vm_area_struct *vma,
unsigned long address, pte_t pte)
{
__update_tlb(vma, address, pte);
__update_cache(vma, address, pte);
}
/* Swap entries must have VALID and GLOBAL bits cleared. */
#if defined(CONFIG_CPU_R3000) || defined(CONFIG_CPU_TX39XX)
#define SWP_TYPE(x) (((x).val >> 1) & 0x7f)
#define SWP_OFFSET(x) ((x).val >> 10)
#define SWP_ENTRY(type,offset) ((swp_entry_t) { ((type) << 1) | ((offset) << 10) })
#else
#define SWP_TYPE(x) (((x).val >> 1) & 0x1f)
#define SWP_OFFSET(x) ((x).val >> 8)
#define SWP_ENTRY(type,offset) ((swp_entry_t) { ((type) << 1) | ((offset) << 8) })
#endif
#define pte_to_swp_entry(pte) ((swp_entry_t) { (pte).pte_low })
#define swp_entry_to_pte(x) ((pte_t) { (x).val })
/* Needs to be defined here and not in linux/mm.h, as it is arch dependent */
#define PageSkip(page) (0)
#define kern_addr_valid(addr) (1)
#include <asm-generic/pgtable.h>
#endif /* !defined (_LANGUAGE_ASSEMBLY) */
/*
* We provide our own get_unmapped area to cope with the virtual aliasing
* constraints placed on us by the cache architecture.
*/
#define HAVE_ARCH_UNMAPPED_AREA
#ifdef CONFIG_64BIT_PHYS_ADDR
#define io_remap_page_range remap_page_range_high
#else
#define io_remap_page_range remap_page_range
#endif
/*
* No page table caches to initialise
*/
#define pgtable_cache_init() do { } while (0)
#endif /* _ASM_PGTABLE_H */
| sensysnetworks/uClinux | linux-2.4.x/include/asm-mips/pgtable.h | C | gpl-2.0 | 9,434 | 29.530744 | 99 | 0.698749 | false |
# Copyright: 2015 Masatake YAMATO
# License: GPL-2
CTAGS=$1
${CTAGS} --quiet --options=NONE --fields=-N --_force-quit
${CTAGS} --quiet --options=NONE --fields=-F --_force-quit
${CTAGS} --quiet --options=NONE --fields=-P --_force-quit
${CTAGS} --quiet --options=NONE --fields=-'{name}' --_force-quit
${CTAGS} --quiet --options=NONE --fields=-'{input}' --_force-quit
${CTAGS} --quiet --options=NONE --fields=-'{pattern}' --_force-quit
| masatake/ctags | Tmain/disable-fixed-field.d/run.sh | Shell | gpl-2.0 | 435 | 38.545455 | 67 | 0.641379 | false |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* 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 license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_XmlConnect
* @copyright Copyright (c) 2006-2014 X.commerce, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Pbridge result payment block
*
* @category Mage
* @package Mage_XmlConnect
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_XmlConnect_Block_Checkout_Pbridge_Result extends Mage_Core_Block_Abstract
{
/**
* Return url for redirect with params of Payment Bridge incoming data
*
* @return string
*/
public function getPbridgeParamsAsUrl()
{
$pbParams = Mage::helper('enterprise_pbridge')->getPbridgeParams();
$params = array_merge(
array('_nosid' => true, 'method' => 'pbridge_' . $pbParams['original_payment_method']),
$pbParams
);
return Mage::getUrl('xmlconnect/pbridge/output', $params);
}
}
| T0MM0R/magento | web/app/code/core/Mage/XmlConnect/Block/Checkout/Pbridge/Result.php | PHP | gpl-2.0 | 1,679 | 32.58 | 99 | 0.672424 | false |
/*
* Routines having to do with the 'struct sk_buff' memory handlers.
*
* Authors: Alan Cox <alan@lxorguk.ukuu.org.uk>
* Florian La Roche <rzsfl@rz.uni-sb.de>
*
* Fixes:
* Alan Cox : Fixed the worst of the load
* balancer bugs.
* Dave Platt : Interrupt stacking fix.
* Richard Kooijman : Timestamp fixes.
* Alan Cox : Changed buffer format.
* Alan Cox : destructor hook for AF_UNIX etc.
* Linus Torvalds : Better skb_clone.
* Alan Cox : Added skb_copy.
* Alan Cox : Added all the changed routines Linus
* only put in the headers
* Ray VanTassle : Fixed --skb->lock in free
* Alan Cox : skb_copy copy arp field
* Andi Kleen : slabified it.
* Robert Olsson : Removed skb_head_pool
*
* NOTE:
* The __skb_ routines should be called with interrupts
* disabled, or you better be *real* sure that the operation is atomic
* with respect to whatever list is being frobbed (e.g. via lock_sock()
* or via disabling bottom half handlers, etc).
*
* 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.
*/
/*
* The functions in this file will not compile correctly with gcc 2.4.x
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/kmemcheck.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/in.h>
#include <linux/inet.h>
#include <linux/slab.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/netdevice.h>
#ifdef CONFIG_NET_CLS_ACT
#include <net/pkt_sched.h>
#endif
#include <linux/string.h>
#include <linux/skbuff.h>
#include <linux/splice.h>
#include <linux/cache.h>
#include <linux/rtnetlink.h>
#include <linux/init.h>
#include <linux/scatterlist.h>
#include <linux/errqueue.h>
#include <linux/prefetch.h>
#include <net/protocol.h>
#include <net/dst.h>
#include <net/sock.h>
#include <net/checksum.h>
#include <net/ip6_checksum.h>
#include <net/xfrm.h>
#include <asm/uaccess.h>
#include <trace/events/skb.h>
#include <linux/highmem.h>
struct kmem_cache *skbuff_head_cache __read_mostly;
static struct kmem_cache *skbuff_fclone_cache __read_mostly;
/**
* skb_panic - private function for out-of-line support
* @skb: buffer
* @sz: size
* @addr: address
* @msg: skb_over_panic or skb_under_panic
*
* Out-of-line support for skb_put() and skb_push().
* Called via the wrapper skb_over_panic() or skb_under_panic().
* Keep out of line to prevent kernel bloat.
* __builtin_return_address is not used because it is not always reliable.
*/
static void skb_panic(struct sk_buff *skb, unsigned int sz, void *addr,
const char msg[])
{
pr_emerg("%s: text:%p len:%d put:%d head:%p data:%p tail:%#lx end:%#lx dev:%s\n",
msg, addr, skb->len, sz, skb->head, skb->data,
(unsigned long)skb->tail, (unsigned long)skb->end,
skb->dev ? skb->dev->name : "<NULL>");
BUG();
}
static void skb_over_panic(struct sk_buff *skb, unsigned int sz, void *addr)
{
skb_panic(skb, sz, addr, __func__);
}
static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr)
{
skb_panic(skb, sz, addr, __func__);
}
/*
* kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells
* the caller if emergency pfmemalloc reserves are being used. If it is and
* the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves
* may be used. Otherwise, the packet data may be discarded until enough
* memory is free
*/
#define kmalloc_reserve(size, gfp, node, pfmemalloc) \
__kmalloc_reserve(size, gfp, node, _RET_IP_, pfmemalloc)
static void *__kmalloc_reserve(size_t size, gfp_t flags, int node,
unsigned long ip, bool *pfmemalloc)
{
void *obj;
bool ret_pfmemalloc = false;
/*
* Try a regular allocation, when that fails and we're not entitled
* to the reserves, fail.
*/
obj = kmalloc_node_track_caller(size,
flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
node);
if (obj || !(gfp_pfmemalloc_allowed(flags)))
goto out;
/* Try again but now we are using pfmemalloc reserves */
ret_pfmemalloc = true;
obj = kmalloc_node_track_caller(size, flags, node);
out:
if (pfmemalloc)
*pfmemalloc = ret_pfmemalloc;
return obj;
}
/* Allocate a new skbuff. We do this ourselves so we can fill in a few
* 'private' fields and also do memory statistics to find all the
* [BEEP] leaks.
*
*/
struct sk_buff *__alloc_skb_head(gfp_t gfp_mask, int node)
{
struct sk_buff *skb;
/* Get the HEAD */
skb = kmem_cache_alloc_node(skbuff_head_cache,
gfp_mask & ~__GFP_DMA, node);
if (!skb)
goto out;
/*
* Only clear those fields we need to clear, not those that we will
* actually initialise below. Hence, don't put any more fields after
* the tail pointer in struct sk_buff!
*/
memset(skb, 0, offsetof(struct sk_buff, tail));
skb->head = NULL;
skb->truesize = sizeof(struct sk_buff);
atomic_set(&skb->users, 1);
skb->mac_header = (typeof(skb->mac_header))~0U;
out:
return skb;
}
/**
* __alloc_skb - allocate a network buffer
* @size: size to allocate
* @gfp_mask: allocation mask
* @flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
* instead of head cache and allocate a cloned (child) skb.
* If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
* allocations in case the data is required for writeback
* @node: numa node to allocate memory on
*
* Allocate a new &sk_buff. The returned buffer has no headroom and a
* tail room of at least size bytes. The object has a reference count
* of one. The return is the buffer. On a failure the return is %NULL.
*
* Buffers may only be allocated from interrupts using a @gfp_mask of
* %GFP_ATOMIC.
*/
struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
int flags, int node)
{
struct kmem_cache *cache;
struct skb_shared_info *shinfo;
struct sk_buff *skb;
u8 *data;
bool pfmemalloc;
cache = (flags & SKB_ALLOC_FCLONE)
? skbuff_fclone_cache : skbuff_head_cache;
if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
gfp_mask |= __GFP_MEMALLOC;
/* Get the HEAD */
skb = kmem_cache_alloc_node(cache, gfp_mask & ~__GFP_DMA, node);
if (!skb)
goto out;
prefetchw(skb);
/* We do our best to align skb_shared_info on a separate cache
* line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
* aligned memory blocks, unless SLUB/SLAB debug is enabled.
* Both skb->head and skb_shared_info are cache line aligned.
*/
size = SKB_DATA_ALIGN(size);
size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
data = kmalloc_reserve(size, gfp_mask, node, &pfmemalloc);
if (!data)
goto nodata;
/* kmalloc(size) might give us more room than requested.
* Put skb_shared_info exactly at the end of allocated zone,
* to allow max possible filling before reallocation.
*/
size = SKB_WITH_OVERHEAD(ksize(data));
prefetchw(data + size);
/*
* Only clear those fields we need to clear, not those that we will
* actually initialise below. Hence, don't put any more fields after
* the tail pointer in struct sk_buff!
*/
memset(skb, 0, offsetof(struct sk_buff, tail));
/* Account for allocated memory : skb + skb->head */
skb->truesize = SKB_TRUESIZE(size);
skb->pfmemalloc = pfmemalloc;
atomic_set(&skb->users, 1);
skb->head = data;
skb->data = data;
skb_reset_tail_pointer(skb);
skb->end = skb->tail + size;
skb->mac_header = (typeof(skb->mac_header))~0U;
skb->transport_header = (typeof(skb->transport_header))~0U;
/* make sure we initialize shinfo sequentially */
shinfo = skb_shinfo(skb);
memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
atomic_set(&shinfo->dataref, 1);
kmemcheck_annotate_variable(shinfo->destructor_arg);
if (flags & SKB_ALLOC_FCLONE) {
struct sk_buff *child = skb + 1;
atomic_t *fclone_ref = (atomic_t *) (child + 1);
kmemcheck_annotate_bitfield(child, flags1);
kmemcheck_annotate_bitfield(child, flags2);
skb->fclone = SKB_FCLONE_ORIG;
atomic_set(fclone_ref, 1);
child->fclone = SKB_FCLONE_UNAVAILABLE;
child->pfmemalloc = pfmemalloc;
}
out:
return skb;
nodata:
kmem_cache_free(cache, skb);
skb = NULL;
goto out;
}
EXPORT_SYMBOL(__alloc_skb);
/**
* build_skb - build a network buffer
* @data: data buffer provided by caller
* @frag_size: size of fragment, or 0 if head was kmalloced
*
* Allocate a new &sk_buff. Caller provides space holding head and
* skb_shared_info. @data must have been allocated by kmalloc() only if
* @frag_size is 0, otherwise data should come from the page allocator.
* The return is the new skb buffer.
* On a failure the return is %NULL, and @data is not freed.
* Notes :
* Before IO, driver allocates only data buffer where NIC put incoming frame
* Driver should add room at head (NET_SKB_PAD) and
* MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info))
* After IO, driver calls build_skb(), to allocate sk_buff and populate it
* before giving packet to stack.
* RX rings only contains data buffers, not full skbs.
*/
struct sk_buff *build_skb(void *data, unsigned int frag_size)
{
struct skb_shared_info *shinfo;
struct sk_buff *skb;
unsigned int size = frag_size ? : ksize(data);
skb = kmem_cache_alloc(skbuff_head_cache, GFP_ATOMIC);
if (!skb)
return NULL;
size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
memset(skb, 0, offsetof(struct sk_buff, tail));
skb->truesize = SKB_TRUESIZE(size);
skb->head_frag = frag_size != 0;
atomic_set(&skb->users, 1);
skb->head = data;
skb->data = data;
skb_reset_tail_pointer(skb);
skb->end = skb->tail + size;
skb->mac_header = (typeof(skb->mac_header))~0U;
skb->transport_header = (typeof(skb->transport_header))~0U;
/* make sure we initialize shinfo sequentially */
shinfo = skb_shinfo(skb);
memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
atomic_set(&shinfo->dataref, 1);
kmemcheck_annotate_variable(shinfo->destructor_arg);
return skb;
}
EXPORT_SYMBOL(build_skb);
struct netdev_alloc_cache {
struct page_frag frag;
/* we maintain a pagecount bias, so that we dont dirty cache line
* containing page->_count every time we allocate a fragment.
*/
unsigned int pagecnt_bias;
};
static DEFINE_PER_CPU(struct netdev_alloc_cache, netdev_alloc_cache);
static void *__netdev_alloc_frag(unsigned int fragsz, gfp_t gfp_mask)
{
struct netdev_alloc_cache *nc;
void *data = NULL;
int order;
unsigned long flags;
local_irq_save(flags);
nc = &__get_cpu_var(netdev_alloc_cache);
if (unlikely(!nc->frag.page)) {
refill:
for (order = NETDEV_FRAG_PAGE_MAX_ORDER; ;) {
gfp_t gfp = gfp_mask;
if (order)
gfp |= __GFP_COMP | __GFP_NOWARN;
nc->frag.page = alloc_pages(gfp, order);
if (likely(nc->frag.page))
break;
if (--order < 0)
goto end;
}
nc->frag.size = PAGE_SIZE << order;
recycle:
atomic_set(&nc->frag.page->_count, NETDEV_PAGECNT_MAX_BIAS);
nc->pagecnt_bias = NETDEV_PAGECNT_MAX_BIAS;
nc->frag.offset = 0;
}
if (nc->frag.offset + fragsz > nc->frag.size) {
/* avoid unnecessary locked operations if possible */
if ((atomic_read(&nc->frag.page->_count) == nc->pagecnt_bias) ||
atomic_sub_and_test(nc->pagecnt_bias, &nc->frag.page->_count))
goto recycle;
goto refill;
}
data = page_address(nc->frag.page) + nc->frag.offset;
nc->frag.offset += fragsz;
nc->pagecnt_bias--;
end:
local_irq_restore(flags);
return data;
}
/**
* netdev_alloc_frag - allocate a page fragment
* @fragsz: fragment size
*
* Allocates a frag from a page for receive buffer.
* Uses GFP_ATOMIC allocations.
*/
void *netdev_alloc_frag(unsigned int fragsz)
{
return __netdev_alloc_frag(fragsz, GFP_ATOMIC | __GFP_COLD);
}
EXPORT_SYMBOL(netdev_alloc_frag);
/**
* __netdev_alloc_skb - allocate an skbuff for rx on a specific device
* @dev: network device to receive on
* @length: length to allocate
* @gfp_mask: get_free_pages mask, passed to alloc_skb
*
* Allocate a new &sk_buff and assign it a usage count of one. The
* buffer has unspecified headroom built in. Users should allocate
* the headroom they think they need without accounting for the
* built in space. The built in space is used for optimisations.
*
* %NULL is returned if there is no free memory.
*/
struct sk_buff *__netdev_alloc_skb(struct net_device *dev,
unsigned int length, gfp_t gfp_mask)
{
struct sk_buff *skb = NULL;
unsigned int fragsz = SKB_DATA_ALIGN(length + NET_SKB_PAD) +
SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
if (fragsz <= PAGE_SIZE && !(gfp_mask & (__GFP_WAIT | GFP_DMA))) {
void *data;
if (sk_memalloc_socks())
gfp_mask |= __GFP_MEMALLOC;
data = __netdev_alloc_frag(fragsz, gfp_mask);
if (likely(data)) {
skb = build_skb(data, fragsz);
if (unlikely(!skb))
put_page(virt_to_head_page(data));
}
} else {
skb = __alloc_skb(length + NET_SKB_PAD, gfp_mask,
SKB_ALLOC_RX, NUMA_NO_NODE);
}
if (likely(skb)) {
skb_reserve(skb, NET_SKB_PAD);
skb->dev = dev;
}
return skb;
}
EXPORT_SYMBOL(__netdev_alloc_skb);
void skb_add_rx_frag(struct sk_buff *skb, int i, struct page *page, int off,
int size, unsigned int truesize)
{
skb_fill_page_desc(skb, i, page, off, size);
skb->len += size;
skb->data_len += size;
skb->truesize += truesize;
}
EXPORT_SYMBOL(skb_add_rx_frag);
void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size,
unsigned int truesize)
{
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
skb_frag_size_add(frag, size);
skb->len += size;
skb->data_len += size;
skb->truesize += truesize;
}
EXPORT_SYMBOL(skb_coalesce_rx_frag);
static void skb_drop_list(struct sk_buff **listp)
{
kfree_skb_list(*listp);
*listp = NULL;
}
static inline void skb_drop_fraglist(struct sk_buff *skb)
{
skb_drop_list(&skb_shinfo(skb)->frag_list);
}
static void skb_clone_fraglist(struct sk_buff *skb)
{
struct sk_buff *list;
skb_walk_frags(skb, list)
skb_get(list);
}
static void skb_free_head(struct sk_buff *skb)
{
if (skb->head_frag)
put_page(virt_to_head_page(skb->head));
else
kfree(skb->head);
}
static void skb_release_data(struct sk_buff *skb)
{
if (!skb->cloned ||
!atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1,
&skb_shinfo(skb)->dataref)) {
if (skb_shinfo(skb)->nr_frags) {
int i;
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
skb_frag_unref(skb, i);
}
/*
* If skb buf is from userspace, we need to notify the caller
* the lower device DMA has done;
*/
if (skb_shinfo(skb)->tx_flags & SKBTX_DEV_ZEROCOPY) {
struct ubuf_info *uarg;
uarg = skb_shinfo(skb)->destructor_arg;
if (uarg->callback)
uarg->callback(uarg, true);
}
if (skb_has_frag_list(skb))
skb_drop_fraglist(skb);
skb_free_head(skb);
}
}
/*
* Free an skbuff by memory without cleaning the state.
*/
static void kfree_skbmem(struct sk_buff *skb)
{
struct sk_buff *other;
atomic_t *fclone_ref;
switch (skb->fclone) {
case SKB_FCLONE_UNAVAILABLE:
kmem_cache_free(skbuff_head_cache, skb);
break;
case SKB_FCLONE_ORIG:
fclone_ref = (atomic_t *) (skb + 2);
if (atomic_dec_and_test(fclone_ref))
kmem_cache_free(skbuff_fclone_cache, skb);
break;
case SKB_FCLONE_CLONE:
fclone_ref = (atomic_t *) (skb + 1);
other = skb - 1;
/* The clone portion is available for
* fast-cloning again.
*/
skb->fclone = SKB_FCLONE_UNAVAILABLE;
if (atomic_dec_and_test(fclone_ref))
kmem_cache_free(skbuff_fclone_cache, other);
break;
}
}
static void skb_release_head_state(struct sk_buff *skb)
{
skb_dst_drop(skb);
#ifdef CONFIG_XFRM
secpath_put(skb->sp);
#endif
if (skb->destructor) {
WARN_ON(in_irq());
skb->destructor(skb);
}
#if IS_ENABLED(CONFIG_NF_CONNTRACK)
nf_conntrack_put(skb->nfct);
#endif
#ifdef CONFIG_BRIDGE_NETFILTER
nf_bridge_put(skb->nf_bridge);
#endif
/* XXX: IS this still necessary? - JHS */
#ifdef CONFIG_NET_SCHED
skb->tc_index = 0;
#ifdef CONFIG_NET_CLS_ACT
skb->tc_verd = 0;
#endif
#endif
}
/* Free everything but the sk_buff shell. */
static void skb_release_all(struct sk_buff *skb)
{
skb_release_head_state(skb);
if (likely(skb->head))
skb_release_data(skb);
}
/**
* __kfree_skb - private function
* @skb: buffer
*
* Free an sk_buff. Release anything attached to the buffer.
* Clean the state. This is an internal helper function. Users should
* always call kfree_skb
*/
void __kfree_skb(struct sk_buff *skb)
{
skb_release_all(skb);
kfree_skbmem(skb);
}
EXPORT_SYMBOL(__kfree_skb);
/**
* kfree_skb - free an sk_buff
* @skb: buffer to free
*
* Drop a reference to the buffer and free it if the usage count has
* hit zero.
*/
void kfree_skb(struct sk_buff *skb)
{
if (unlikely(!skb))
return;
if (likely(atomic_read(&skb->users) == 1))
smp_rmb();
else if (likely(!atomic_dec_and_test(&skb->users)))
return;
trace_kfree_skb(skb, __builtin_return_address(0));
__kfree_skb(skb);
}
EXPORT_SYMBOL(kfree_skb);
void kfree_skb_list(struct sk_buff *segs)
{
while (segs) {
struct sk_buff *next = segs->next;
kfree_skb(segs);
segs = next;
}
}
EXPORT_SYMBOL(kfree_skb_list);
/**
* skb_tx_error - report an sk_buff xmit error
* @skb: buffer that triggered an error
*
* Report xmit error if a device callback is tracking this skb.
* skb must be freed afterwards.
*/
void skb_tx_error(struct sk_buff *skb)
{
if (skb_shinfo(skb)->tx_flags & SKBTX_DEV_ZEROCOPY) {
struct ubuf_info *uarg;
uarg = skb_shinfo(skb)->destructor_arg;
if (uarg->callback)
uarg->callback(uarg, false);
skb_shinfo(skb)->tx_flags &= ~SKBTX_DEV_ZEROCOPY;
}
}
EXPORT_SYMBOL(skb_tx_error);
/**
* consume_skb - free an skbuff
* @skb: buffer to free
*
* Drop a ref to the buffer and free it if the usage count has hit zero
* Functions identically to kfree_skb, but kfree_skb assumes that the frame
* is being dropped after a failure and notes that
*/
void consume_skb(struct sk_buff *skb)
{
if (unlikely(!skb))
return;
if (likely(atomic_read(&skb->users) == 1))
smp_rmb();
else if (likely(!atomic_dec_and_test(&skb->users)))
return;
trace_consume_skb(skb);
__kfree_skb(skb);
}
EXPORT_SYMBOL(consume_skb);
static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
{
new->tstamp = old->tstamp;
new->dev = old->dev;
new->transport_header = old->transport_header;
new->network_header = old->network_header;
new->mac_header = old->mac_header;
new->inner_protocol = old->inner_protocol;
new->inner_transport_header = old->inner_transport_header;
new->inner_network_header = old->inner_network_header;
new->inner_mac_header = old->inner_mac_header;
skb_dst_copy(new, old);
skb_copy_hash(new, old);
new->ooo_okay = old->ooo_okay;
new->no_fcs = old->no_fcs;
new->encapsulation = old->encapsulation;
#ifdef CONFIG_XFRM
new->sp = secpath_get(old->sp);
#endif
memcpy(new->cb, old->cb, sizeof(old->cb));
new->csum = old->csum;
new->local_df = old->local_df;
new->pkt_type = old->pkt_type;
new->ip_summed = old->ip_summed;
skb_copy_queue_mapping(new, old);
new->priority = old->priority;
#if IS_ENABLED(CONFIG_IP_VS)
new->ipvs_property = old->ipvs_property;
#endif
new->pfmemalloc = old->pfmemalloc;
new->protocol = old->protocol;
new->mark = old->mark;
new->skb_iif = old->skb_iif;
__nf_copy(new, old);
#ifdef CONFIG_NET_SCHED
new->tc_index = old->tc_index;
#ifdef CONFIG_NET_CLS_ACT
new->tc_verd = old->tc_verd;
#endif
#endif
new->vlan_proto = old->vlan_proto;
new->vlan_tci = old->vlan_tci;
skb_copy_secmark(new, old);
#ifdef CONFIG_NET_RX_BUSY_POLL
new->napi_id = old->napi_id;
#endif
}
/*
* You should not add any new code to this function. Add it to
* __copy_skb_header above instead.
*/
static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
{
#define C(x) n->x = skb->x
n->next = n->prev = NULL;
n->sk = NULL;
__copy_skb_header(n, skb);
C(len);
C(data_len);
C(mac_len);
n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
n->cloned = 1;
n->nohdr = 0;
n->destructor = NULL;
C(tail);
C(end);
C(head);
C(head_frag);
C(data);
C(truesize);
atomic_set(&n->users, 1);
atomic_inc(&(skb_shinfo(skb)->dataref));
skb->cloned = 1;
return n;
#undef C
}
/**
* skb_morph - morph one skb into another
* @dst: the skb to receive the contents
* @src: the skb to supply the contents
*
* This is identical to skb_clone except that the target skb is
* supplied by the user.
*
* The target skb is returned upon exit.
*/
struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
{
skb_release_all(dst);
return __skb_clone(dst, src);
}
EXPORT_SYMBOL_GPL(skb_morph);
/**
* skb_copy_ubufs - copy userspace skb frags buffers to kernel
* @skb: the skb to modify
* @gfp_mask: allocation priority
*
* This must be called on SKBTX_DEV_ZEROCOPY skb.
* It will copy all frags into kernel and drop the reference
* to userspace pages.
*
* If this function is called from an interrupt gfp_mask() must be
* %GFP_ATOMIC.
*
* Returns 0 on success or a negative error code on failure
* to allocate kernel memory to copy to.
*/
int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
{
int i;
int num_frags = skb_shinfo(skb)->nr_frags;
struct page *page, *head = NULL;
struct ubuf_info *uarg = skb_shinfo(skb)->destructor_arg;
for (i = 0; i < num_frags; i++) {
u8 *vaddr;
skb_frag_t *f = &skb_shinfo(skb)->frags[i];
page = alloc_page(gfp_mask);
if (!page) {
while (head) {
struct page *next = (struct page *)page_private(head);
put_page(head);
head = next;
}
return -ENOMEM;
}
vaddr = kmap_atomic(skb_frag_page(f));
memcpy(page_address(page),
vaddr + f->page_offset, skb_frag_size(f));
kunmap_atomic(vaddr);
set_page_private(page, (unsigned long)head);
head = page;
}
/* skb frags release userspace buffers */
for (i = 0; i < num_frags; i++)
skb_frag_unref(skb, i);
uarg->callback(uarg, false);
/* skb frags point to kernel buffers */
for (i = num_frags - 1; i >= 0; i--) {
__skb_fill_page_desc(skb, i, head, 0,
skb_shinfo(skb)->frags[i].size);
head = (struct page *)page_private(head);
}
skb_shinfo(skb)->tx_flags &= ~SKBTX_DEV_ZEROCOPY;
return 0;
}
EXPORT_SYMBOL_GPL(skb_copy_ubufs);
/**
* skb_clone - duplicate an sk_buff
* @skb: buffer to clone
* @gfp_mask: allocation priority
*
* Duplicate an &sk_buff. The new one is not owned by a socket. Both
* copies share the same packet data but not structure. The new
* buffer has a reference count of 1. If the allocation fails the
* function returns %NULL otherwise the new buffer is returned.
*
* If this function is called from an interrupt gfp_mask() must be
* %GFP_ATOMIC.
*/
struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
{
struct sk_buff *n;
if (skb_orphan_frags(skb, gfp_mask))
return NULL;
n = skb + 1;
if (skb->fclone == SKB_FCLONE_ORIG &&
n->fclone == SKB_FCLONE_UNAVAILABLE) {
atomic_t *fclone_ref = (atomic_t *) (n + 1);
n->fclone = SKB_FCLONE_CLONE;
atomic_inc(fclone_ref);
} else {
if (skb_pfmemalloc(skb))
gfp_mask |= __GFP_MEMALLOC;
n = kmem_cache_alloc(skbuff_head_cache, gfp_mask);
if (!n)
return NULL;
kmemcheck_annotate_bitfield(n, flags1);
kmemcheck_annotate_bitfield(n, flags2);
n->fclone = SKB_FCLONE_UNAVAILABLE;
}
return __skb_clone(n, skb);
}
EXPORT_SYMBOL(skb_clone);
static void skb_headers_offset_update(struct sk_buff *skb, int off)
{
/* Only adjust this if it actually is csum_start rather than csum */
if (skb->ip_summed == CHECKSUM_PARTIAL)
skb->csum_start += off;
/* {transport,network,mac}_header and tail are relative to skb->head */
skb->transport_header += off;
skb->network_header += off;
if (skb_mac_header_was_set(skb))
skb->mac_header += off;
skb->inner_transport_header += off;
skb->inner_network_header += off;
skb->inner_mac_header += off;
}
static void copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
{
__copy_skb_header(new, old);
skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
}
static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
{
if (skb_pfmemalloc(skb))
return SKB_ALLOC_RX;
return 0;
}
/**
* skb_copy - create private copy of an sk_buff
* @skb: buffer to copy
* @gfp_mask: allocation priority
*
* Make a copy of both an &sk_buff and its data. This is used when the
* caller wishes to modify the data and needs a private copy of the
* data to alter. Returns %NULL on failure or the pointer to the buffer
* on success. The returned buffer has a reference count of 1.
*
* As by-product this function converts non-linear &sk_buff to linear
* one, so that &sk_buff becomes completely private and caller is allowed
* to modify all the data of returned buffer. This means that this
* function is not recommended for use in circumstances when only
* header is going to be modified. Use pskb_copy() instead.
*/
struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
{
int headerlen = skb_headroom(skb);
unsigned int size = skb_end_offset(skb) + skb->data_len;
struct sk_buff *n = __alloc_skb(size, gfp_mask,
skb_alloc_rx_flag(skb), NUMA_NO_NODE);
if (!n)
return NULL;
/* Set the data pointer */
skb_reserve(n, headerlen);
/* Set the tail pointer and length */
skb_put(n, skb->len);
if (skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len))
BUG();
copy_skb_header(n, skb);
return n;
}
EXPORT_SYMBOL(skb_copy);
/**
* __pskb_copy - create copy of an sk_buff with private head.
* @skb: buffer to copy
* @headroom: headroom of new skb
* @gfp_mask: allocation priority
*
* Make a copy of both an &sk_buff and part of its data, located
* in header. Fragmented data remain shared. This is used when
* the caller wishes to modify only header of &sk_buff and needs
* private copy of the header to alter. Returns %NULL on failure
* or the pointer to the buffer on success.
* The returned buffer has a reference count of 1.
*/
struct sk_buff *__pskb_copy(struct sk_buff *skb, int headroom, gfp_t gfp_mask)
{
unsigned int size = skb_headlen(skb) + headroom;
struct sk_buff *n = __alloc_skb(size, gfp_mask,
skb_alloc_rx_flag(skb), NUMA_NO_NODE);
if (!n)
goto out;
/* Set the data pointer */
skb_reserve(n, headroom);
/* Set the tail pointer and length */
skb_put(n, skb_headlen(skb));
/* Copy the bytes */
skb_copy_from_linear_data(skb, n->data, n->len);
n->truesize += skb->data_len;
n->data_len = skb->data_len;
n->len = skb->len;
if (skb_shinfo(skb)->nr_frags) {
int i;
if (skb_orphan_frags(skb, gfp_mask)) {
kfree_skb(n);
n = NULL;
goto out;
}
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
skb_frag_ref(skb, i);
}
skb_shinfo(n)->nr_frags = i;
}
if (skb_has_frag_list(skb)) {
skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
skb_clone_fraglist(n);
}
copy_skb_header(n, skb);
out:
return n;
}
EXPORT_SYMBOL(__pskb_copy);
/**
* pskb_expand_head - reallocate header of &sk_buff
* @skb: buffer to reallocate
* @nhead: room to add at head
* @ntail: room to add at tail
* @gfp_mask: allocation priority
*
* Expands (or creates identical copy, if @nhead and @ntail are zero)
* header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
* reference count of 1. Returns zero in the case of success or error,
* if expansion failed. In the last case, &sk_buff is not changed.
*
* All the pointers pointing into skb header may change and must be
* reloaded after call to this function.
*/
int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
gfp_t gfp_mask)
{
int i;
u8 *data;
int size = nhead + skb_end_offset(skb) + ntail;
long off;
BUG_ON(nhead < 0);
if (skb_shared(skb))
BUG();
size = SKB_DATA_ALIGN(size);
if (skb_pfmemalloc(skb))
gfp_mask |= __GFP_MEMALLOC;
data = kmalloc_reserve(size + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
gfp_mask, NUMA_NO_NODE, NULL);
if (!data)
goto nodata;
size = SKB_WITH_OVERHEAD(ksize(data));
/* Copy only real data... and, alas, header. This should be
* optimized for the cases when header is void.
*/
memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
memcpy((struct skb_shared_info *)(data + size),
skb_shinfo(skb),
offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
/*
* if shinfo is shared we must drop the old head gracefully, but if it
* is not we can just drop the old head and let the existing refcount
* be since all we did is relocate the values
*/
if (skb_cloned(skb)) {
/* copy this zero copy skb frags */
if (skb_orphan_frags(skb, gfp_mask))
goto nofrags;
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
skb_frag_ref(skb, i);
if (skb_has_frag_list(skb))
skb_clone_fraglist(skb);
skb_release_data(skb);
} else {
skb_free_head(skb);
}
off = (data + nhead) - skb->head;
skb->head = data;
skb->head_frag = 0;
skb->data += off;
#ifdef NET_SKBUFF_DATA_USES_OFFSET
skb->end = size;
off = nhead;
#else
skb->end = skb->head + size;
#endif
skb->tail += off;
skb_headers_offset_update(skb, nhead);
skb->cloned = 0;
skb->hdr_len = 0;
skb->nohdr = 0;
atomic_set(&skb_shinfo(skb)->dataref, 1);
return 0;
nofrags:
kfree(data);
nodata:
return -ENOMEM;
}
EXPORT_SYMBOL(pskb_expand_head);
/* Make private copy of skb with writable head and some headroom */
struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
{
struct sk_buff *skb2;
int delta = headroom - skb_headroom(skb);
if (delta <= 0)
skb2 = pskb_copy(skb, GFP_ATOMIC);
else {
skb2 = skb_clone(skb, GFP_ATOMIC);
if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
GFP_ATOMIC)) {
kfree_skb(skb2);
skb2 = NULL;
}
}
return skb2;
}
EXPORT_SYMBOL(skb_realloc_headroom);
/**
* skb_copy_expand - copy and expand sk_buff
* @skb: buffer to copy
* @newheadroom: new free bytes at head
* @newtailroom: new free bytes at tail
* @gfp_mask: allocation priority
*
* Make a copy of both an &sk_buff and its data and while doing so
* allocate additional space.
*
* This is used when the caller wishes to modify the data and needs a
* private copy of the data to alter as well as more space for new fields.
* Returns %NULL on failure or the pointer to the buffer
* on success. The returned buffer has a reference count of 1.
*
* You must pass %GFP_ATOMIC as the allocation priority if this function
* is called from an interrupt.
*/
struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
int newheadroom, int newtailroom,
gfp_t gfp_mask)
{
/*
* Allocate the copy buffer
*/
struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
gfp_mask, skb_alloc_rx_flag(skb),
NUMA_NO_NODE);
int oldheadroom = skb_headroom(skb);
int head_copy_len, head_copy_off;
if (!n)
return NULL;
skb_reserve(n, newheadroom);
/* Set the tail pointer and length */
skb_put(n, skb->len);
head_copy_len = oldheadroom;
head_copy_off = 0;
if (newheadroom <= head_copy_len)
head_copy_len = newheadroom;
else
head_copy_off = newheadroom - head_copy_len;
/* Copy the linear header and data. */
if (skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
skb->len + head_copy_len))
BUG();
copy_skb_header(n, skb);
skb_headers_offset_update(n, newheadroom - oldheadroom);
return n;
}
EXPORT_SYMBOL(skb_copy_expand);
/**
* skb_pad - zero pad the tail of an skb
* @skb: buffer to pad
* @pad: space to pad
*
* Ensure that a buffer is followed by a padding area that is zero
* filled. Used by network drivers which may DMA or transfer data
* beyond the buffer end onto the wire.
*
* May return error in out of memory cases. The skb is freed on error.
*/
int skb_pad(struct sk_buff *skb, int pad)
{
int err;
int ntail;
/* If the skbuff is non linear tailroom is always zero.. */
if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
memset(skb->data+skb->len, 0, pad);
return 0;
}
ntail = skb->data_len + pad - (skb->end - skb->tail);
if (likely(skb_cloned(skb) || ntail > 0)) {
err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
if (unlikely(err))
goto free_skb;
}
/* FIXME: The use of this function with non-linear skb's really needs
* to be audited.
*/
err = skb_linearize(skb);
if (unlikely(err))
goto free_skb;
memset(skb->data + skb->len, 0, pad);
return 0;
free_skb:
kfree_skb(skb);
return err;
}
EXPORT_SYMBOL(skb_pad);
/**
* pskb_put - add data to the tail of a potentially fragmented buffer
* @skb: start of the buffer to use
* @tail: tail fragment of the buffer to use
* @len: amount of data to add
*
* This function extends the used data area of the potentially
* fragmented buffer. @tail must be the last fragment of @skb -- or
* @skb itself. If this would exceed the total buffer size the kernel
* will panic. A pointer to the first byte of the extra data is
* returned.
*/
unsigned char *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
{
if (tail != skb) {
skb->data_len += len;
skb->len += len;
}
return skb_put(tail, len);
}
EXPORT_SYMBOL_GPL(pskb_put);
/**
* skb_put - add data to a buffer
* @skb: buffer to use
* @len: amount of data to add
*
* This function extends the used data area of the buffer. If this would
* exceed the total buffer size the kernel will panic. A pointer to the
* first byte of the extra data is returned.
*/
unsigned char *skb_put(struct sk_buff *skb, unsigned int len)
{
unsigned char *tmp = skb_tail_pointer(skb);
SKB_LINEAR_ASSERT(skb);
skb->tail += len;
skb->len += len;
if (unlikely(skb->tail > skb->end))
skb_over_panic(skb, len, __builtin_return_address(0));
return tmp;
}
EXPORT_SYMBOL(skb_put);
/**
* skb_push - add data to the start of a buffer
* @skb: buffer to use
* @len: amount of data to add
*
* This function extends the used data area of the buffer at the buffer
* start. If this would exceed the total buffer headroom the kernel will
* panic. A pointer to the first byte of the extra data is returned.
*/
unsigned char *skb_push(struct sk_buff *skb, unsigned int len)
{
skb->data -= len;
skb->len += len;
if (unlikely(skb->data<skb->head))
skb_under_panic(skb, len, __builtin_return_address(0));
return skb->data;
}
EXPORT_SYMBOL(skb_push);
/**
* skb_pull - remove data from the start of a buffer
* @skb: buffer to use
* @len: amount of data to remove
*
* This function removes data from the start of a buffer, returning
* the memory to the headroom. A pointer to the next data in the buffer
* is returned. Once the data has been pulled future pushes will overwrite
* the old data.
*/
unsigned char *skb_pull(struct sk_buff *skb, unsigned int len)
{
return skb_pull_inline(skb, len);
}
EXPORT_SYMBOL(skb_pull);
/**
* skb_trim - remove end from a buffer
* @skb: buffer to alter
* @len: new length
*
* Cut the length of a buffer down by removing data from the tail. If
* the buffer is already under the length specified it is not modified.
* The skb must be linear.
*/
void skb_trim(struct sk_buff *skb, unsigned int len)
{
if (skb->len > len)
__skb_trim(skb, len);
}
EXPORT_SYMBOL(skb_trim);
/* Trims skb to length len. It can change skb pointers.
*/
int ___pskb_trim(struct sk_buff *skb, unsigned int len)
{
struct sk_buff **fragp;
struct sk_buff *frag;
int offset = skb_headlen(skb);
int nfrags = skb_shinfo(skb)->nr_frags;
int i;
int err;
if (skb_cloned(skb) &&
unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
return err;
i = 0;
if (offset >= len)
goto drop_pages;
for (; i < nfrags; i++) {
int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
if (end < len) {
offset = end;
continue;
}
skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
drop_pages:
skb_shinfo(skb)->nr_frags = i;
for (; i < nfrags; i++)
skb_frag_unref(skb, i);
if (skb_has_frag_list(skb))
skb_drop_fraglist(skb);
goto done;
}
for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
fragp = &frag->next) {
int end = offset + frag->len;
if (skb_shared(frag)) {
struct sk_buff *nfrag;
nfrag = skb_clone(frag, GFP_ATOMIC);
if (unlikely(!nfrag))
return -ENOMEM;
nfrag->next = frag->next;
consume_skb(frag);
frag = nfrag;
*fragp = frag;
}
if (end < len) {
offset = end;
continue;
}
if (end > len &&
unlikely((err = pskb_trim(frag, len - offset))))
return err;
if (frag->next)
skb_drop_list(&frag->next);
break;
}
done:
if (len > skb_headlen(skb)) {
skb->data_len -= skb->len - len;
skb->len = len;
} else {
skb->len = len;
skb->data_len = 0;
skb_set_tail_pointer(skb, len);
}
return 0;
}
EXPORT_SYMBOL(___pskb_trim);
/**
* __pskb_pull_tail - advance tail of skb header
* @skb: buffer to reallocate
* @delta: number of bytes to advance tail
*
* The function makes a sense only on a fragmented &sk_buff,
* it expands header moving its tail forward and copying necessary
* data from fragmented part.
*
* &sk_buff MUST have reference count of 1.
*
* Returns %NULL (and &sk_buff does not change) if pull failed
* or value of new tail of skb in the case of success.
*
* All the pointers pointing into skb header may change and must be
* reloaded after call to this function.
*/
/* Moves tail of skb head forward, copying data from fragmented part,
* when it is necessary.
* 1. It may fail due to malloc failure.
* 2. It may change skb pointers.
*
* It is pretty complicated. Luckily, it is called only in exceptional cases.
*/
unsigned char *__pskb_pull_tail(struct sk_buff *skb, int delta)
{
/* If skb has not enough free space at tail, get new one
* plus 128 bytes for future expansions. If we have enough
* room at tail, reallocate without expansion only if skb is cloned.
*/
int i, k, eat = (skb->tail + delta) - skb->end;
if (eat > 0 || skb_cloned(skb)) {
if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
GFP_ATOMIC))
return NULL;
}
if (skb_copy_bits(skb, skb_headlen(skb), skb_tail_pointer(skb), delta))
BUG();
/* Optimization: no fragments, no reasons to preestimate
* size of pulled pages. Superb.
*/
if (!skb_has_frag_list(skb))
goto pull_pages;
/* Estimate size of pulled pages. */
eat = delta;
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
if (size >= eat)
goto pull_pages;
eat -= size;
}
/* If we need update frag list, we are in troubles.
* Certainly, it possible to add an offset to skb data,
* but taking into account that pulling is expected to
* be very rare operation, it is worth to fight against
* further bloating skb head and crucify ourselves here instead.
* Pure masohism, indeed. 8)8)
*/
if (eat) {
struct sk_buff *list = skb_shinfo(skb)->frag_list;
struct sk_buff *clone = NULL;
struct sk_buff *insp = NULL;
do {
BUG_ON(!list);
if (list->len <= eat) {
/* Eaten as whole. */
eat -= list->len;
list = list->next;
insp = list;
} else {
/* Eaten partially. */
if (skb_shared(list)) {
/* Sucks! We need to fork list. :-( */
clone = skb_clone(list, GFP_ATOMIC);
if (!clone)
return NULL;
insp = list->next;
list = clone;
} else {
/* This may be pulled without
* problems. */
insp = list;
}
if (!pskb_pull(list, eat)) {
kfree_skb(clone);
return NULL;
}
break;
}
} while (eat);
/* Free pulled out fragments. */
while ((list = skb_shinfo(skb)->frag_list) != insp) {
skb_shinfo(skb)->frag_list = list->next;
kfree_skb(list);
}
/* And insert new clone at head. */
if (clone) {
clone->next = list;
skb_shinfo(skb)->frag_list = clone;
}
}
/* Success! Now we may commit changes to skb data. */
pull_pages:
eat = delta;
k = 0;
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
if (size <= eat) {
skb_frag_unref(skb, i);
eat -= size;
} else {
skb_shinfo(skb)->frags[k] = skb_shinfo(skb)->frags[i];
if (eat) {
skb_shinfo(skb)->frags[k].page_offset += eat;
skb_frag_size_sub(&skb_shinfo(skb)->frags[k], eat);
eat = 0;
}
k++;
}
}
skb_shinfo(skb)->nr_frags = k;
skb->tail += delta;
skb->data_len -= delta;
return skb_tail_pointer(skb);
}
EXPORT_SYMBOL(__pskb_pull_tail);
/**
* skb_copy_bits - copy bits from skb to kernel buffer
* @skb: source skb
* @offset: offset in source
* @to: destination buffer
* @len: number of bytes to copy
*
* Copy the specified number of bytes from the source skb to the
* destination buffer.
*
* CAUTION ! :
* If its prototype is ever changed,
* check arch/{*}/net/{*}.S files,
* since it is called from BPF assembly code.
*/
int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
{
int start = skb_headlen(skb);
struct sk_buff *frag_iter;
int i, copy;
if (offset > (int)skb->len - len)
goto fault;
/* Copy header. */
if ((copy = start - offset) > 0) {
if (copy > len)
copy = len;
skb_copy_from_linear_data_offset(skb, offset, to, copy);
if ((len -= copy) == 0)
return 0;
offset += copy;
to += copy;
}
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
int end;
skb_frag_t *f = &skb_shinfo(skb)->frags[i];
WARN_ON(start > offset + len);
end = start + skb_frag_size(f);
if ((copy = end - offset) > 0) {
u8 *vaddr;
if (copy > len)
copy = len;
vaddr = kmap_atomic(skb_frag_page(f));
memcpy(to,
vaddr + f->page_offset + offset - start,
copy);
kunmap_atomic(vaddr);
if ((len -= copy) == 0)
return 0;
offset += copy;
to += copy;
}
start = end;
}
skb_walk_frags(skb, frag_iter) {
int end;
WARN_ON(start > offset + len);
end = start + frag_iter->len;
if ((copy = end - offset) > 0) {
if (copy > len)
copy = len;
if (skb_copy_bits(frag_iter, offset - start, to, copy))
goto fault;
if ((len -= copy) == 0)
return 0;
offset += copy;
to += copy;
}
start = end;
}
if (!len)
return 0;
fault:
return -EFAULT;
}
EXPORT_SYMBOL(skb_copy_bits);
/*
* Callback from splice_to_pipe(), if we need to release some pages
* at the end of the spd in case we error'ed out in filling the pipe.
*/
static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
{
put_page(spd->pages[i]);
}
static struct page *linear_to_page(struct page *page, unsigned int *len,
unsigned int *offset,
struct sock *sk)
{
struct page_frag *pfrag = sk_page_frag(sk);
if (!sk_page_frag_refill(sk, pfrag))
return NULL;
*len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
memcpy(page_address(pfrag->page) + pfrag->offset,
page_address(page) + *offset, *len);
*offset = pfrag->offset;
pfrag->offset += *len;
return pfrag->page;
}
static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
struct page *page,
unsigned int offset)
{
return spd->nr_pages &&
spd->pages[spd->nr_pages - 1] == page &&
(spd->partial[spd->nr_pages - 1].offset +
spd->partial[spd->nr_pages - 1].len == offset);
}
/*
* Fill page/offset/length into spd, if it can hold more pages.
*/
static bool spd_fill_page(struct splice_pipe_desc *spd,
struct pipe_inode_info *pipe, struct page *page,
unsigned int *len, unsigned int offset,
bool linear,
struct sock *sk)
{
if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
return true;
if (linear) {
page = linear_to_page(page, len, &offset, sk);
if (!page)
return true;
}
if (spd_can_coalesce(spd, page, offset)) {
spd->partial[spd->nr_pages - 1].len += *len;
return false;
}
get_page(page);
spd->pages[spd->nr_pages] = page;
spd->partial[spd->nr_pages].len = *len;
spd->partial[spd->nr_pages].offset = offset;
spd->nr_pages++;
return false;
}
static bool __splice_segment(struct page *page, unsigned int poff,
unsigned int plen, unsigned int *off,
unsigned int *len,
struct splice_pipe_desc *spd, bool linear,
struct sock *sk,
struct pipe_inode_info *pipe)
{
if (!*len)
return true;
/* skip this segment if already processed */
if (*off >= plen) {
*off -= plen;
return false;
}
/* ignore any bits we already processed */
poff += *off;
plen -= *off;
*off = 0;
do {
unsigned int flen = min(*len, plen);
if (spd_fill_page(spd, pipe, page, &flen, poff,
linear, sk))
return true;
poff += flen;
plen -= flen;
*len -= flen;
} while (*len && plen);
return false;
}
/*
* Map linear and fragment data from the skb to spd. It reports true if the
* pipe is full or if we already spliced the requested length.
*/
static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
unsigned int *offset, unsigned int *len,
struct splice_pipe_desc *spd, struct sock *sk)
{
int seg;
/* map the linear part :
* If skb->head_frag is set, this 'linear' part is backed by a
* fragment, and if the head is not shared with any clones then
* we can avoid a copy since we own the head portion of this page.
*/
if (__splice_segment(virt_to_page(skb->data),
(unsigned long) skb->data & (PAGE_SIZE - 1),
skb_headlen(skb),
offset, len, spd,
skb_head_is_locked(skb),
sk, pipe))
return true;
/*
* then map the fragments
*/
for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
if (__splice_segment(skb_frag_page(f),
f->page_offset, skb_frag_size(f),
offset, len, spd, false, sk, pipe))
return true;
}
return false;
}
/*
* Map data from the skb to a pipe. Should handle both the linear part,
* the fragments, and the frag list. It does NOT handle frag lists within
* the frag list, if such a thing exists. We'd probably need to recurse to
* handle that cleanly.
*/
int skb_splice_bits(struct sk_buff *skb, unsigned int offset,
struct pipe_inode_info *pipe, unsigned int tlen,
unsigned int flags)
{
struct partial_page partial[MAX_SKB_FRAGS];
struct page *pages[MAX_SKB_FRAGS];
struct splice_pipe_desc spd = {
.pages = pages,
.partial = partial,
.nr_pages_max = MAX_SKB_FRAGS,
.flags = flags,
.ops = &nosteal_pipe_buf_ops,
.spd_release = sock_spd_release,
};
struct sk_buff *frag_iter;
struct sock *sk = skb->sk;
int ret = 0;
/*
* __skb_splice_bits() only fails if the output has no room left,
* so no point in going over the frag_list for the error case.
*/
if (__skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk))
goto done;
else if (!tlen)
goto done;
/*
* now see if we have a frag_list to map
*/
skb_walk_frags(skb, frag_iter) {
if (!tlen)
break;
if (__skb_splice_bits(frag_iter, pipe, &offset, &tlen, &spd, sk))
break;
}
done:
if (spd.nr_pages) {
/*
* Drop the socket lock, otherwise we have reverse
* locking dependencies between sk_lock and i_mutex
* here as compared to sendfile(). We enter here
* with the socket lock held, and splice_to_pipe() will
* grab the pipe inode lock. For sendfile() emulation,
* we call into ->sendpage() with the i_mutex lock held
* and networking will grab the socket lock.
*/
release_sock(sk);
ret = splice_to_pipe(pipe, &spd);
lock_sock(sk);
}
return ret;
}
/**
* skb_store_bits - store bits from kernel buffer to skb
* @skb: destination buffer
* @offset: offset in destination
* @from: source buffer
* @len: number of bytes to copy
*
* Copy the specified number of bytes from the source buffer to the
* destination skb. This function handles all the messy bits of
* traversing fragment lists and such.
*/
int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
{
int start = skb_headlen(skb);
struct sk_buff *frag_iter;
int i, copy;
if (offset > (int)skb->len - len)
goto fault;
if ((copy = start - offset) > 0) {
if (copy > len)
copy = len;
skb_copy_to_linear_data_offset(skb, offset, from, copy);
if ((len -= copy) == 0)
return 0;
offset += copy;
from += copy;
}
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
int end;
WARN_ON(start > offset + len);
end = start + skb_frag_size(frag);
if ((copy = end - offset) > 0) {
u8 *vaddr;
if (copy > len)
copy = len;
vaddr = kmap_atomic(skb_frag_page(frag));
memcpy(vaddr + frag->page_offset + offset - start,
from, copy);
kunmap_atomic(vaddr);
if ((len -= copy) == 0)
return 0;
offset += copy;
from += copy;
}
start = end;
}
skb_walk_frags(skb, frag_iter) {
int end;
WARN_ON(start > offset + len);
end = start + frag_iter->len;
if ((copy = end - offset) > 0) {
if (copy > len)
copy = len;
if (skb_store_bits(frag_iter, offset - start,
from, copy))
goto fault;
if ((len -= copy) == 0)
return 0;
offset += copy;
from += copy;
}
start = end;
}
if (!len)
return 0;
fault:
return -EFAULT;
}
EXPORT_SYMBOL(skb_store_bits);
/* Checksum skb data. */
__wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
__wsum csum, const struct skb_checksum_ops *ops)
{
int start = skb_headlen(skb);
int i, copy = start - offset;
struct sk_buff *frag_iter;
int pos = 0;
/* Checksum header. */
if (copy > 0) {
if (copy > len)
copy = len;
csum = ops->update(skb->data + offset, copy, csum);
if ((len -= copy) == 0)
return csum;
offset += copy;
pos = copy;
}
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
int end;
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
WARN_ON(start > offset + len);
end = start + skb_frag_size(frag);
if ((copy = end - offset) > 0) {
__wsum csum2;
u8 *vaddr;
if (copy > len)
copy = len;
vaddr = kmap_atomic(skb_frag_page(frag));
csum2 = ops->update(vaddr + frag->page_offset +
offset - start, copy, 0);
kunmap_atomic(vaddr);
csum = ops->combine(csum, csum2, pos, copy);
if (!(len -= copy))
return csum;
offset += copy;
pos += copy;
}
start = end;
}
skb_walk_frags(skb, frag_iter) {
int end;
WARN_ON(start > offset + len);
end = start + frag_iter->len;
if ((copy = end - offset) > 0) {
__wsum csum2;
if (copy > len)
copy = len;
csum2 = __skb_checksum(frag_iter, offset - start,
copy, 0, ops);
csum = ops->combine(csum, csum2, pos, copy);
if ((len -= copy) == 0)
return csum;
offset += copy;
pos += copy;
}
start = end;
}
BUG_ON(len);
return csum;
}
EXPORT_SYMBOL(__skb_checksum);
__wsum skb_checksum(const struct sk_buff *skb, int offset,
int len, __wsum csum)
{
const struct skb_checksum_ops ops = {
.update = csum_partial_ext,
.combine = csum_block_add_ext,
};
return __skb_checksum(skb, offset, len, csum, &ops);
}
EXPORT_SYMBOL(skb_checksum);
/* Both of above in one bottle. */
__wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
u8 *to, int len, __wsum csum)
{
int start = skb_headlen(skb);
int i, copy = start - offset;
struct sk_buff *frag_iter;
int pos = 0;
/* Copy header. */
if (copy > 0) {
if (copy > len)
copy = len;
csum = csum_partial_copy_nocheck(skb->data + offset, to,
copy, csum);
if ((len -= copy) == 0)
return csum;
offset += copy;
to += copy;
pos = copy;
}
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
int end;
WARN_ON(start > offset + len);
end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
if ((copy = end - offset) > 0) {
__wsum csum2;
u8 *vaddr;
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
if (copy > len)
copy = len;
vaddr = kmap_atomic(skb_frag_page(frag));
csum2 = csum_partial_copy_nocheck(vaddr +
frag->page_offset +
offset - start, to,
copy, 0);
kunmap_atomic(vaddr);
csum = csum_block_add(csum, csum2, pos);
if (!(len -= copy))
return csum;
offset += copy;
to += copy;
pos += copy;
}
start = end;
}
skb_walk_frags(skb, frag_iter) {
__wsum csum2;
int end;
WARN_ON(start > offset + len);
end = start + frag_iter->len;
if ((copy = end - offset) > 0) {
if (copy > len)
copy = len;
csum2 = skb_copy_and_csum_bits(frag_iter,
offset - start,
to, copy, 0);
csum = csum_block_add(csum, csum2, pos);
if ((len -= copy) == 0)
return csum;
offset += copy;
to += copy;
pos += copy;
}
start = end;
}
BUG_ON(len);
return csum;
}
EXPORT_SYMBOL(skb_copy_and_csum_bits);
/**
* skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
* @from: source buffer
*
* Calculates the amount of linear headroom needed in the 'to' skb passed
* into skb_zerocopy().
*/
unsigned int
skb_zerocopy_headlen(const struct sk_buff *from)
{
unsigned int hlen = 0;
if (!from->head_frag ||
skb_headlen(from) < L1_CACHE_BYTES ||
skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS)
hlen = skb_headlen(from);
if (skb_has_frag_list(from))
hlen = from->len;
return hlen;
}
EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
/**
* skb_zerocopy - Zero copy skb to skb
* @to: destination buffer
* @from: source buffer
* @len: number of bytes to copy from source buffer
* @hlen: size of linear headroom in destination buffer
*
* Copies up to `len` bytes from `from` to `to` by creating references
* to the frags in the source buffer.
*
* The `hlen` as calculated by skb_zerocopy_headlen() specifies the
* headroom in the `to` buffer.
*
* Return value:
* 0: everything is OK
* -ENOMEM: couldn't orphan frags of @from due to lack of memory
* -EFAULT: skb_copy_bits() found some problem with skb geometry
*/
int
skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
{
int i, j = 0;
int plen = 0; /* length of skb->head fragment */
int ret;
struct page *page;
unsigned int offset;
BUG_ON(!from->head_frag && !hlen);
/* dont bother with small payloads */
if (len <= skb_tailroom(to))
return skb_copy_bits(from, 0, skb_put(to, len), len);
if (hlen) {
ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
if (unlikely(ret))
return ret;
len -= hlen;
} else {
plen = min_t(int, skb_headlen(from), len);
if (plen) {
page = virt_to_head_page(from->head);
offset = from->data - (unsigned char *)page_address(page);
__skb_fill_page_desc(to, 0, page, offset, plen);
get_page(page);
j = 1;
len -= plen;
}
}
to->truesize += len + plen;
to->len += len + plen;
to->data_len += len + plen;
if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
skb_tx_error(from);
return -ENOMEM;
}
for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
if (!len)
break;
skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
skb_shinfo(to)->frags[j].size = min_t(int, skb_shinfo(to)->frags[j].size, len);
len -= skb_shinfo(to)->frags[j].size;
skb_frag_ref(to, j);
j++;
}
skb_shinfo(to)->nr_frags = j;
return 0;
}
EXPORT_SYMBOL_GPL(skb_zerocopy);
void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
{
__wsum csum;
long csstart;
if (skb->ip_summed == CHECKSUM_PARTIAL)
csstart = skb_checksum_start_offset(skb);
else
csstart = skb_headlen(skb);
BUG_ON(csstart > skb_headlen(skb));
skb_copy_from_linear_data(skb, to, csstart);
csum = 0;
if (csstart != skb->len)
csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
skb->len - csstart, 0);
if (skb->ip_summed == CHECKSUM_PARTIAL) {
long csstuff = csstart + skb->csum_offset;
*((__sum16 *)(to + csstuff)) = csum_fold(csum);
}
}
EXPORT_SYMBOL(skb_copy_and_csum_dev);
/**
* skb_dequeue - remove from the head of the queue
* @list: list to dequeue from
*
* Remove the head of the list. The list lock is taken so the function
* may be used safely with other locking list functions. The head item is
* returned or %NULL if the list is empty.
*/
struct sk_buff *skb_dequeue(struct sk_buff_head *list)
{
unsigned long flags;
struct sk_buff *result;
spin_lock_irqsave(&list->lock, flags);
result = __skb_dequeue(list);
spin_unlock_irqrestore(&list->lock, flags);
return result;
}
EXPORT_SYMBOL(skb_dequeue);
/**
* skb_dequeue_tail - remove from the tail of the queue
* @list: list to dequeue from
*
* Remove the tail of the list. The list lock is taken so the function
* may be used safely with other locking list functions. The tail item is
* returned or %NULL if the list is empty.
*/
struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
{
unsigned long flags;
struct sk_buff *result;
spin_lock_irqsave(&list->lock, flags);
result = __skb_dequeue_tail(list);
spin_unlock_irqrestore(&list->lock, flags);
return result;
}
EXPORT_SYMBOL(skb_dequeue_tail);
/**
* skb_queue_purge - empty a list
* @list: list to empty
*
* Delete all buffers on an &sk_buff list. Each buffer is removed from
* the list and one reference dropped. This function takes the list
* lock and is atomic with respect to other list locking functions.
*/
void skb_queue_purge(struct sk_buff_head *list)
{
struct sk_buff *skb;
while ((skb = skb_dequeue(list)) != NULL)
kfree_skb(skb);
}
EXPORT_SYMBOL(skb_queue_purge);
/**
* skb_queue_head - queue a buffer at the list head
* @list: list to use
* @newsk: buffer to queue
*
* Queue a buffer at the start of the list. This function takes the
* list lock and can be used safely with other locking &sk_buff functions
* safely.
*
* A buffer cannot be placed on two lists at the same time.
*/
void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
{
unsigned long flags;
spin_lock_irqsave(&list->lock, flags);
__skb_queue_head(list, newsk);
spin_unlock_irqrestore(&list->lock, flags);
}
EXPORT_SYMBOL(skb_queue_head);
/**
* skb_queue_tail - queue a buffer at the list tail
* @list: list to use
* @newsk: buffer to queue
*
* Queue a buffer at the tail of the list. This function takes the
* list lock and can be used safely with other locking &sk_buff functions
* safely.
*
* A buffer cannot be placed on two lists at the same time.
*/
void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
{
unsigned long flags;
spin_lock_irqsave(&list->lock, flags);
__skb_queue_tail(list, newsk);
spin_unlock_irqrestore(&list->lock, flags);
}
EXPORT_SYMBOL(skb_queue_tail);
/**
* skb_unlink - remove a buffer from a list
* @skb: buffer to remove
* @list: list to use
*
* Remove a packet from a list. The list locks are taken and this
* function is atomic with respect to other list locked calls
*
* You must know what list the SKB is on.
*/
void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
{
unsigned long flags;
spin_lock_irqsave(&list->lock, flags);
__skb_unlink(skb, list);
spin_unlock_irqrestore(&list->lock, flags);
}
EXPORT_SYMBOL(skb_unlink);
/**
* skb_append - append a buffer
* @old: buffer to insert after
* @newsk: buffer to insert
* @list: list to use
*
* Place a packet after a given packet in a list. The list locks are taken
* and this function is atomic with respect to other list locked calls.
* A buffer cannot be placed on two lists at the same time.
*/
void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
{
unsigned long flags;
spin_lock_irqsave(&list->lock, flags);
__skb_queue_after(list, old, newsk);
spin_unlock_irqrestore(&list->lock, flags);
}
EXPORT_SYMBOL(skb_append);
/**
* skb_insert - insert a buffer
* @old: buffer to insert before
* @newsk: buffer to insert
* @list: list to use
*
* Place a packet before a given packet in a list. The list locks are
* taken and this function is atomic with respect to other list locked
* calls.
*
* A buffer cannot be placed on two lists at the same time.
*/
void skb_insert(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
{
unsigned long flags;
spin_lock_irqsave(&list->lock, flags);
__skb_insert(newsk, old->prev, old, list);
spin_unlock_irqrestore(&list->lock, flags);
}
EXPORT_SYMBOL(skb_insert);
static inline void skb_split_inside_header(struct sk_buff *skb,
struct sk_buff* skb1,
const u32 len, const int pos)
{
int i;
skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
pos - len);
/* And move data appendix as is. */
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
skb_shinfo(skb)->nr_frags = 0;
skb1->data_len = skb->data_len;
skb1->len += skb1->data_len;
skb->data_len = 0;
skb->len = len;
skb_set_tail_pointer(skb, len);
}
static inline void skb_split_no_header(struct sk_buff *skb,
struct sk_buff* skb1,
const u32 len, int pos)
{
int i, k = 0;
const int nfrags = skb_shinfo(skb)->nr_frags;
skb_shinfo(skb)->nr_frags = 0;
skb1->len = skb1->data_len = skb->len - len;
skb->len = len;
skb->data_len = len - pos;
for (i = 0; i < nfrags; i++) {
int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
if (pos + size > len) {
skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
if (pos < len) {
/* Split frag.
* We have two variants in this case:
* 1. Move all the frag to the second
* part, if it is possible. F.e.
* this approach is mandatory for TUX,
* where splitting is expensive.
* 2. Split is accurately. We make this.
*/
skb_frag_ref(skb, i);
skb_shinfo(skb1)->frags[0].page_offset += len - pos;
skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
skb_shinfo(skb)->nr_frags++;
}
k++;
} else
skb_shinfo(skb)->nr_frags++;
pos += size;
}
skb_shinfo(skb1)->nr_frags = k;
}
/**
* skb_split - Split fragmented skb to two parts at length len.
* @skb: the buffer to split
* @skb1: the buffer to receive the second part
* @len: new length for skb
*/
void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
{
int pos = skb_headlen(skb);
skb_shinfo(skb1)->tx_flags = skb_shinfo(skb)->tx_flags & SKBTX_SHARED_FRAG;
if (len < pos) /* Split line is inside header. */
skb_split_inside_header(skb, skb1, len, pos);
else /* Second chunk has no header, nothing to copy. */
skb_split_no_header(skb, skb1, len, pos);
}
EXPORT_SYMBOL(skb_split);
/* Shifting from/to a cloned skb is a no-go.
*
* Caller cannot keep skb_shinfo related pointers past calling here!
*/
static int skb_prepare_for_shift(struct sk_buff *skb)
{
return skb_cloned(skb) && pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
}
/**
* skb_shift - Shifts paged data partially from skb to another
* @tgt: buffer into which tail data gets added
* @skb: buffer from which the paged data comes from
* @shiftlen: shift up to this many bytes
*
* Attempts to shift up to shiftlen worth of bytes, which may be less than
* the length of the skb, from skb to tgt. Returns number bytes shifted.
* It's up to caller to free skb if everything was shifted.
*
* If @tgt runs out of frags, the whole operation is aborted.
*
* Skb cannot include anything else but paged data while tgt is allowed
* to have non-paged data as well.
*
* TODO: full sized shift could be optimized but that would need
* specialized skb free'er to handle frags without up-to-date nr_frags.
*/
int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
{
int from, to, merge, todo;
struct skb_frag_struct *fragfrom, *fragto;
BUG_ON(shiftlen > skb->len);
BUG_ON(skb_headlen(skb)); /* Would corrupt stream */
todo = shiftlen;
from = 0;
to = skb_shinfo(tgt)->nr_frags;
fragfrom = &skb_shinfo(skb)->frags[from];
/* Actual merge is delayed until the point when we know we can
* commit all, so that we don't have to undo partial changes
*/
if (!to ||
!skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
fragfrom->page_offset)) {
merge = -1;
} else {
merge = to - 1;
todo -= skb_frag_size(fragfrom);
if (todo < 0) {
if (skb_prepare_for_shift(skb) ||
skb_prepare_for_shift(tgt))
return 0;
/* All previous frag pointers might be stale! */
fragfrom = &skb_shinfo(skb)->frags[from];
fragto = &skb_shinfo(tgt)->frags[merge];
skb_frag_size_add(fragto, shiftlen);
skb_frag_size_sub(fragfrom, shiftlen);
fragfrom->page_offset += shiftlen;
goto onlymerged;
}
from++;
}
/* Skip full, not-fitting skb to avoid expensive operations */
if ((shiftlen == skb->len) &&
(skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
return 0;
if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
return 0;
while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
if (to == MAX_SKB_FRAGS)
return 0;
fragfrom = &skb_shinfo(skb)->frags[from];
fragto = &skb_shinfo(tgt)->frags[to];
if (todo >= skb_frag_size(fragfrom)) {
*fragto = *fragfrom;
todo -= skb_frag_size(fragfrom);
from++;
to++;
} else {
__skb_frag_ref(fragfrom);
fragto->page = fragfrom->page;
fragto->page_offset = fragfrom->page_offset;
skb_frag_size_set(fragto, todo);
fragfrom->page_offset += todo;
skb_frag_size_sub(fragfrom, todo);
todo = 0;
to++;
break;
}
}
/* Ready to "commit" this state change to tgt */
skb_shinfo(tgt)->nr_frags = to;
if (merge >= 0) {
fragfrom = &skb_shinfo(skb)->frags[0];
fragto = &skb_shinfo(tgt)->frags[merge];
skb_frag_size_add(fragto, skb_frag_size(fragfrom));
__skb_frag_unref(fragfrom);
}
/* Reposition in the original skb */
to = 0;
while (from < skb_shinfo(skb)->nr_frags)
skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
skb_shinfo(skb)->nr_frags = to;
BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
onlymerged:
/* Most likely the tgt won't ever need its checksum anymore, skb on
* the other hand might need it if it needs to be resent
*/
tgt->ip_summed = CHECKSUM_PARTIAL;
skb->ip_summed = CHECKSUM_PARTIAL;
/* Yak, is it really working this way? Some helper please? */
skb->len -= shiftlen;
skb->data_len -= shiftlen;
skb->truesize -= shiftlen;
tgt->len += shiftlen;
tgt->data_len += shiftlen;
tgt->truesize += shiftlen;
return shiftlen;
}
/**
* skb_prepare_seq_read - Prepare a sequential read of skb data
* @skb: the buffer to read
* @from: lower offset of data to be read
* @to: upper offset of data to be read
* @st: state variable
*
* Initializes the specified state variable. Must be called before
* invoking skb_seq_read() for the first time.
*/
void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
unsigned int to, struct skb_seq_state *st)
{
st->lower_offset = from;
st->upper_offset = to;
st->root_skb = st->cur_skb = skb;
st->frag_idx = st->stepped_offset = 0;
st->frag_data = NULL;
}
EXPORT_SYMBOL(skb_prepare_seq_read);
/**
* skb_seq_read - Sequentially read skb data
* @consumed: number of bytes consumed by the caller so far
* @data: destination pointer for data to be returned
* @st: state variable
*
* Reads a block of skb data at @consumed relative to the
* lower offset specified to skb_prepare_seq_read(). Assigns
* the head of the data block to @data and returns the length
* of the block or 0 if the end of the skb data or the upper
* offset has been reached.
*
* The caller is not required to consume all of the data
* returned, i.e. @consumed is typically set to the number
* of bytes already consumed and the next call to
* skb_seq_read() will return the remaining part of the block.
*
* Note 1: The size of each block of data returned can be arbitrary,
* this limitation is the cost for zerocopy seqeuental
* reads of potentially non linear data.
*
* Note 2: Fragment lists within fragments are not implemented
* at the moment, state->root_skb could be replaced with
* a stack for this purpose.
*/
unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
struct skb_seq_state *st)
{
unsigned int block_limit, abs_offset = consumed + st->lower_offset;
skb_frag_t *frag;
if (unlikely(abs_offset >= st->upper_offset)) {
if (st->frag_data) {
kunmap_atomic(st->frag_data);
st->frag_data = NULL;
}
return 0;
}
next_skb:
block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
if (abs_offset < block_limit && !st->frag_data) {
*data = st->cur_skb->data + (abs_offset - st->stepped_offset);
return block_limit - abs_offset;
}
if (st->frag_idx == 0 && !st->frag_data)
st->stepped_offset += skb_headlen(st->cur_skb);
while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
block_limit = skb_frag_size(frag) + st->stepped_offset;
if (abs_offset < block_limit) {
if (!st->frag_data)
st->frag_data = kmap_atomic(skb_frag_page(frag));
*data = (u8 *) st->frag_data + frag->page_offset +
(abs_offset - st->stepped_offset);
return block_limit - abs_offset;
}
if (st->frag_data) {
kunmap_atomic(st->frag_data);
st->frag_data = NULL;
}
st->frag_idx++;
st->stepped_offset += skb_frag_size(frag);
}
if (st->frag_data) {
kunmap_atomic(st->frag_data);
st->frag_data = NULL;
}
if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
st->frag_idx = 0;
goto next_skb;
} else if (st->cur_skb->next) {
st->cur_skb = st->cur_skb->next;
st->frag_idx = 0;
goto next_skb;
}
return 0;
}
EXPORT_SYMBOL(skb_seq_read);
/**
* skb_abort_seq_read - Abort a sequential read of skb data
* @st: state variable
*
* Must be called if skb_seq_read() was not called until it
* returned 0.
*/
void skb_abort_seq_read(struct skb_seq_state *st)
{
if (st->frag_data)
kunmap_atomic(st->frag_data);
}
EXPORT_SYMBOL(skb_abort_seq_read);
#define TS_SKB_CB(state) ((struct skb_seq_state *) &((state)->cb))
static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
struct ts_config *conf,
struct ts_state *state)
{
return skb_seq_read(offset, text, TS_SKB_CB(state));
}
static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
{
skb_abort_seq_read(TS_SKB_CB(state));
}
/**
* skb_find_text - Find a text pattern in skb data
* @skb: the buffer to look in
* @from: search offset
* @to: search limit
* @config: textsearch configuration
* @state: uninitialized textsearch state variable
*
* Finds a pattern in the skb data according to the specified
* textsearch configuration. Use textsearch_next() to retrieve
* subsequent occurrences of the pattern. Returns the offset
* to the first occurrence or UINT_MAX if no match was found.
*/
unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
unsigned int to, struct ts_config *config,
struct ts_state *state)
{
unsigned int ret;
config->get_next_block = skb_ts_get_next_block;
config->finish = skb_ts_finish;
skb_prepare_seq_read(skb, from, to, TS_SKB_CB(state));
ret = textsearch_find(config, state);
return (ret <= to - from ? ret : UINT_MAX);
}
EXPORT_SYMBOL(skb_find_text);
/**
* skb_append_datato_frags - append the user data to a skb
* @sk: sock structure
* @skb: skb structure to be appened with user data.
* @getfrag: call back function to be used for getting the user data
* @from: pointer to user message iov
* @length: length of the iov message
*
* Description: This procedure append the user data in the fragment part
* of the skb if any page alloc fails user this procedure returns -ENOMEM
*/
int skb_append_datato_frags(struct sock *sk, struct sk_buff *skb,
int (*getfrag)(void *from, char *to, int offset,
int len, int odd, struct sk_buff *skb),
void *from, int length)
{
int frg_cnt = skb_shinfo(skb)->nr_frags;
int copy;
int offset = 0;
int ret;
struct page_frag *pfrag = ¤t->task_frag;
do {
/* Return error if we don't have space for new frag */
if (frg_cnt >= MAX_SKB_FRAGS)
return -EMSGSIZE;
if (!sk_page_frag_refill(sk, pfrag))
return -ENOMEM;
/* copy the user data to page */
copy = min_t(int, length, pfrag->size - pfrag->offset);
ret = getfrag(from, page_address(pfrag->page) + pfrag->offset,
offset, copy, 0, skb);
if (ret < 0)
return -EFAULT;
/* copy was successful so update the size parameters */
skb_fill_page_desc(skb, frg_cnt, pfrag->page, pfrag->offset,
copy);
frg_cnt++;
pfrag->offset += copy;
get_page(pfrag->page);
skb->truesize += copy;
atomic_add(copy, &sk->sk_wmem_alloc);
skb->len += copy;
skb->data_len += copy;
offset += copy;
length -= copy;
} while (length > 0);
return 0;
}
EXPORT_SYMBOL(skb_append_datato_frags);
/**
* skb_pull_rcsum - pull skb and update receive checksum
* @skb: buffer to update
* @len: length of data pulled
*
* This function performs an skb_pull on the packet and updates
* the CHECKSUM_COMPLETE checksum. It should be used on
* receive path processing instead of skb_pull unless you know
* that the checksum difference is zero (e.g., a valid IP header)
* or you are setting ip_summed to CHECKSUM_NONE.
*/
unsigned char *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
{
BUG_ON(len > skb->len);
skb->len -= len;
BUG_ON(skb->len < skb->data_len);
skb_postpull_rcsum(skb, skb->data, len);
return skb->data += len;
}
EXPORT_SYMBOL_GPL(skb_pull_rcsum);
/**
* skb_segment - Perform protocol segmentation on skb.
* @head_skb: buffer to segment
* @features: features for the output path (see dev->features)
*
* This function performs segmentation on the given skb. It returns
* a pointer to the first in a list of new skbs for the segments.
* In case of error it returns ERR_PTR(err).
*/
struct sk_buff *skb_segment(struct sk_buff *head_skb,
netdev_features_t features)
{
struct sk_buff *segs = NULL;
struct sk_buff *tail = NULL;
struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
skb_frag_t *frag = skb_shinfo(head_skb)->frags;
unsigned int mss = skb_shinfo(head_skb)->gso_size;
unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
struct sk_buff *frag_skb = head_skb;
unsigned int offset = doffset;
unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
unsigned int headroom;
unsigned int len;
__be16 proto;
bool csum;
int sg = !!(features & NETIF_F_SG);
int nfrags = skb_shinfo(head_skb)->nr_frags;
int err = -ENOMEM;
int i = 0;
int pos;
int dummy;
proto = skb_network_protocol(head_skb, &dummy);
if (unlikely(!proto))
return ERR_PTR(-EINVAL);
csum = !!can_checksum_protocol(features, proto);
__skb_push(head_skb, doffset);
headroom = skb_headroom(head_skb);
pos = skb_headlen(head_skb);
do {
struct sk_buff *nskb;
skb_frag_t *nskb_frag;
int hsize;
int size;
len = head_skb->len - offset;
if (len > mss)
len = mss;
hsize = skb_headlen(head_skb) - offset;
if (hsize < 0)
hsize = 0;
if (hsize > len || !sg)
hsize = len;
if (!hsize && i >= nfrags && skb_headlen(list_skb) &&
(skb_headlen(list_skb) == len || sg)) {
BUG_ON(skb_headlen(list_skb) > len);
i = 0;
nfrags = skb_shinfo(list_skb)->nr_frags;
frag = skb_shinfo(list_skb)->frags;
frag_skb = list_skb;
pos += skb_headlen(list_skb);
while (pos < offset + len) {
BUG_ON(i >= nfrags);
size = skb_frag_size(frag);
if (pos + size > offset + len)
break;
i++;
pos += size;
frag++;
}
nskb = skb_clone(list_skb, GFP_ATOMIC);
list_skb = list_skb->next;
if (unlikely(!nskb))
goto err;
if (unlikely(pskb_trim(nskb, len))) {
kfree_skb(nskb);
goto err;
}
hsize = skb_end_offset(nskb);
if (skb_cow_head(nskb, doffset + headroom)) {
kfree_skb(nskb);
goto err;
}
nskb->truesize += skb_end_offset(nskb) - hsize;
skb_release_head_state(nskb);
__skb_push(nskb, doffset);
} else {
nskb = __alloc_skb(hsize + doffset + headroom,
GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
NUMA_NO_NODE);
if (unlikely(!nskb))
goto err;
skb_reserve(nskb, headroom);
__skb_put(nskb, doffset);
}
if (segs)
tail->next = nskb;
else
segs = nskb;
tail = nskb;
__copy_skb_header(nskb, head_skb);
nskb->mac_len = head_skb->mac_len;
skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
nskb->data - tnl_hlen,
doffset + tnl_hlen);
if (nskb->len == len + doffset)
goto perform_csum_check;
if (!sg) {
nskb->ip_summed = CHECKSUM_NONE;
nskb->csum = skb_copy_and_csum_bits(head_skb, offset,
skb_put(nskb, len),
len, 0);
continue;
}
nskb_frag = skb_shinfo(nskb)->frags;
skb_copy_from_linear_data_offset(head_skb, offset,
skb_put(nskb, hsize), hsize);
skb_shinfo(nskb)->tx_flags = skb_shinfo(head_skb)->tx_flags &
SKBTX_SHARED_FRAG;
while (pos < offset + len) {
if (i >= nfrags) {
BUG_ON(skb_headlen(list_skb));
i = 0;
nfrags = skb_shinfo(list_skb)->nr_frags;
frag = skb_shinfo(list_skb)->frags;
frag_skb = list_skb;
BUG_ON(!nfrags);
list_skb = list_skb->next;
}
if (unlikely(skb_shinfo(nskb)->nr_frags >=
MAX_SKB_FRAGS)) {
net_warn_ratelimited(
"skb_segment: too many frags: %u %u\n",
pos, mss);
goto err;
}
if (unlikely(skb_orphan_frags(frag_skb, GFP_ATOMIC)))
goto err;
*nskb_frag = *frag;
__skb_frag_ref(nskb_frag);
size = skb_frag_size(nskb_frag);
if (pos < offset) {
nskb_frag->page_offset += offset - pos;
skb_frag_size_sub(nskb_frag, offset - pos);
}
skb_shinfo(nskb)->nr_frags++;
if (pos + size <= offset + len) {
i++;
frag++;
pos += size;
} else {
skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
goto skip_fraglist;
}
nskb_frag++;
}
skip_fraglist:
nskb->data_len = len - hsize;
nskb->len += nskb->data_len;
nskb->truesize += nskb->data_len;
perform_csum_check:
if (!csum) {
nskb->csum = skb_checksum(nskb, doffset,
nskb->len - doffset, 0);
nskb->ip_summed = CHECKSUM_NONE;
}
} while ((offset += len) < head_skb->len);
return segs;
err:
kfree_skb_list(segs);
return ERR_PTR(err);
}
EXPORT_SYMBOL_GPL(skb_segment);
int skb_gro_receive(struct sk_buff **head, struct sk_buff *skb)
{
struct skb_shared_info *pinfo, *skbinfo = skb_shinfo(skb);
unsigned int offset = skb_gro_offset(skb);
unsigned int headlen = skb_headlen(skb);
struct sk_buff *nskb, *lp, *p = *head;
unsigned int len = skb_gro_len(skb);
unsigned int delta_truesize;
unsigned int headroom;
if (unlikely(p->len + len >= 65536))
return -E2BIG;
lp = NAPI_GRO_CB(p)->last ?: p;
pinfo = skb_shinfo(lp);
if (headlen <= offset) {
skb_frag_t *frag;
skb_frag_t *frag2;
int i = skbinfo->nr_frags;
int nr_frags = pinfo->nr_frags + i;
if (nr_frags > MAX_SKB_FRAGS)
goto merge;
offset -= headlen;
pinfo->nr_frags = nr_frags;
skbinfo->nr_frags = 0;
frag = pinfo->frags + nr_frags;
frag2 = skbinfo->frags + i;
do {
*--frag = *--frag2;
} while (--i);
frag->page_offset += offset;
skb_frag_size_sub(frag, offset);
/* all fragments truesize : remove (head size + sk_buff) */
delta_truesize = skb->truesize -
SKB_TRUESIZE(skb_end_offset(skb));
skb->truesize -= skb->data_len;
skb->len -= skb->data_len;
skb->data_len = 0;
NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE;
goto done;
} else if (skb->head_frag) {
int nr_frags = pinfo->nr_frags;
skb_frag_t *frag = pinfo->frags + nr_frags;
struct page *page = virt_to_head_page(skb->head);
unsigned int first_size = headlen - offset;
unsigned int first_offset;
if (nr_frags + 1 + skbinfo->nr_frags > MAX_SKB_FRAGS)
goto merge;
first_offset = skb->data -
(unsigned char *)page_address(page) +
offset;
pinfo->nr_frags = nr_frags + 1 + skbinfo->nr_frags;
frag->page.p = page;
frag->page_offset = first_offset;
skb_frag_size_set(frag, first_size);
memcpy(frag + 1, skbinfo->frags, sizeof(*frag) * skbinfo->nr_frags);
/* We dont need to clear skbinfo->nr_frags here */
delta_truesize = skb->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE_STOLEN_HEAD;
goto done;
}
if (pinfo->frag_list)
goto merge;
if (skb_gro_len(p) != pinfo->gso_size)
return -E2BIG;
headroom = skb_headroom(p);
nskb = alloc_skb(headroom + skb_gro_offset(p), GFP_ATOMIC);
if (unlikely(!nskb))
return -ENOMEM;
__copy_skb_header(nskb, p);
nskb->mac_len = p->mac_len;
skb_reserve(nskb, headroom);
__skb_put(nskb, skb_gro_offset(p));
skb_set_mac_header(nskb, skb_mac_header(p) - p->data);
skb_set_network_header(nskb, skb_network_offset(p));
skb_set_transport_header(nskb, skb_transport_offset(p));
__skb_pull(p, skb_gro_offset(p));
memcpy(skb_mac_header(nskb), skb_mac_header(p),
p->data - skb_mac_header(p));
skb_shinfo(nskb)->frag_list = p;
skb_shinfo(nskb)->gso_size = pinfo->gso_size;
pinfo->gso_size = 0;
skb_header_release(p);
NAPI_GRO_CB(nskb)->last = p;
nskb->data_len += p->len;
nskb->truesize += p->truesize;
nskb->len += p->len;
*head = nskb;
nskb->next = p->next;
p->next = NULL;
p = nskb;
merge:
delta_truesize = skb->truesize;
if (offset > headlen) {
unsigned int eat = offset - headlen;
skbinfo->frags[0].page_offset += eat;
skb_frag_size_sub(&skbinfo->frags[0], eat);
skb->data_len -= eat;
skb->len -= eat;
offset = headlen;
}
__skb_pull(skb, offset);
if (!NAPI_GRO_CB(p)->last)
skb_shinfo(p)->frag_list = skb;
else
NAPI_GRO_CB(p)->last->next = skb;
NAPI_GRO_CB(p)->last = skb;
skb_header_release(skb);
lp = p;
done:
NAPI_GRO_CB(p)->count++;
p->data_len += len;
p->truesize += delta_truesize;
p->len += len;
if (lp != p) {
lp->data_len += len;
lp->truesize += delta_truesize;
lp->len += len;
}
NAPI_GRO_CB(skb)->same_flow = 1;
return 0;
}
EXPORT_SYMBOL_GPL(skb_gro_receive);
void __init skb_init(void)
{
skbuff_head_cache = kmem_cache_create("skbuff_head_cache",
sizeof(struct sk_buff),
0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC,
NULL);
skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
(2*sizeof(struct sk_buff)) +
sizeof(atomic_t),
0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC,
NULL);
}
/**
* skb_to_sgvec - Fill a scatter-gather list from a socket buffer
* @skb: Socket buffer containing the buffers to be mapped
* @sg: The scatter-gather list to map into
* @offset: The offset into the buffer's contents to start mapping
* @len: Length of buffer space to be mapped
*
* Fill the specified scatter-gather list with mappings/pointers into a
* region of the buffer space attached to a socket buffer.
*/
static int
__skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
{
int start = skb_headlen(skb);
int i, copy = start - offset;
struct sk_buff *frag_iter;
int elt = 0;
if (copy > 0) {
if (copy > len)
copy = len;
sg_set_buf(sg, skb->data + offset, copy);
elt++;
if ((len -= copy) == 0)
return elt;
offset += copy;
}
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
int end;
WARN_ON(start > offset + len);
end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
if ((copy = end - offset) > 0) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
if (copy > len)
copy = len;
sg_set_page(&sg[elt], skb_frag_page(frag), copy,
frag->page_offset+offset-start);
elt++;
if (!(len -= copy))
return elt;
offset += copy;
}
start = end;
}
skb_walk_frags(skb, frag_iter) {
int end;
WARN_ON(start > offset + len);
end = start + frag_iter->len;
if ((copy = end - offset) > 0) {
if (copy > len)
copy = len;
elt += __skb_to_sgvec(frag_iter, sg+elt, offset - start,
copy);
if ((len -= copy) == 0)
return elt;
offset += copy;
}
start = end;
}
BUG_ON(len);
return elt;
}
/* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
* sglist without mark the sg which contain last skb data as the end.
* So the caller can mannipulate sg list as will when padding new data after
* the first call without calling sg_unmark_end to expend sg list.
*
* Scenario to use skb_to_sgvec_nomark:
* 1. sg_init_table
* 2. skb_to_sgvec_nomark(payload1)
* 3. skb_to_sgvec_nomark(payload2)
*
* This is equivalent to:
* 1. sg_init_table
* 2. skb_to_sgvec(payload1)
* 3. sg_unmark_end
* 4. skb_to_sgvec(payload2)
*
* When mapping mutilple payload conditionally, skb_to_sgvec_nomark
* is more preferable.
*/
int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
int offset, int len)
{
return __skb_to_sgvec(skb, sg, offset, len);
}
EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
{
int nsg = __skb_to_sgvec(skb, sg, offset, len);
sg_mark_end(&sg[nsg - 1]);
return nsg;
}
EXPORT_SYMBOL_GPL(skb_to_sgvec);
/**
* skb_cow_data - Check that a socket buffer's data buffers are writable
* @skb: The socket buffer to check.
* @tailbits: Amount of trailing space to be added
* @trailer: Returned pointer to the skb where the @tailbits space begins
*
* Make sure that the data buffers attached to a socket buffer are
* writable. If they are not, private copies are made of the data buffers
* and the socket buffer is set to use these instead.
*
* If @tailbits is given, make sure that there is space to write @tailbits
* bytes of data beyond current end of socket buffer. @trailer will be
* set to point to the skb in which this space begins.
*
* The number of scatterlist elements required to completely map the
* COW'd and extended socket buffer will be returned.
*/
int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
{
int copyflag;
int elt;
struct sk_buff *skb1, **skb_p;
/* If skb is cloned or its head is paged, reallocate
* head pulling out all the pages (pages are considered not writable
* at the moment even if they are anonymous).
*/
if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
__pskb_pull_tail(skb, skb_pagelen(skb)-skb_headlen(skb)) == NULL)
return -ENOMEM;
/* Easy case. Most of packets will go this way. */
if (!skb_has_frag_list(skb)) {
/* A little of trouble, not enough of space for trailer.
* This should not happen, when stack is tuned to generate
* good frames. OK, on miss we reallocate and reserve even more
* space, 128 bytes is fair. */
if (skb_tailroom(skb) < tailbits &&
pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
return -ENOMEM;
/* Voila! */
*trailer = skb;
return 1;
}
/* Misery. We are in troubles, going to mincer fragments... */
elt = 1;
skb_p = &skb_shinfo(skb)->frag_list;
copyflag = 0;
while ((skb1 = *skb_p) != NULL) {
int ntail = 0;
/* The fragment is partially pulled by someone,
* this can happen on input. Copy it and everything
* after it. */
if (skb_shared(skb1))
copyflag = 1;
/* If the skb is the last, worry about trailer. */
if (skb1->next == NULL && tailbits) {
if (skb_shinfo(skb1)->nr_frags ||
skb_has_frag_list(skb1) ||
skb_tailroom(skb1) < tailbits)
ntail = tailbits + 128;
}
if (copyflag ||
skb_cloned(skb1) ||
ntail ||
skb_shinfo(skb1)->nr_frags ||
skb_has_frag_list(skb1)) {
struct sk_buff *skb2;
/* Fuck, we are miserable poor guys... */
if (ntail == 0)
skb2 = skb_copy(skb1, GFP_ATOMIC);
else
skb2 = skb_copy_expand(skb1,
skb_headroom(skb1),
ntail,
GFP_ATOMIC);
if (unlikely(skb2 == NULL))
return -ENOMEM;
if (skb1->sk)
skb_set_owner_w(skb2, skb1->sk);
/* Looking around. Are we still alive?
* OK, link new skb, drop old one */
skb2->next = skb1->next;
*skb_p = skb2;
kfree_skb(skb1);
skb1 = skb2;
}
elt++;
*trailer = skb1;
skb_p = &skb1->next;
}
return elt;
}
EXPORT_SYMBOL_GPL(skb_cow_data);
static void sock_rmem_free(struct sk_buff *skb)
{
struct sock *sk = skb->sk;
atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
}
/*
* Note: We dont mem charge error packets (no sk_forward_alloc changes)
*/
int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
{
int len = skb->len;
if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
(unsigned int)sk->sk_rcvbuf)
return -ENOMEM;
skb_orphan(skb);
skb->sk = sk;
skb->destructor = sock_rmem_free;
atomic_add(skb->truesize, &sk->sk_rmem_alloc);
/* before exiting rcu section, make sure dst is refcounted */
skb_dst_force(skb);
skb_queue_tail(&sk->sk_error_queue, skb);
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_data_ready(sk, len);
return 0;
}
EXPORT_SYMBOL(sock_queue_err_skb);
void skb_tstamp_tx(struct sk_buff *orig_skb,
struct skb_shared_hwtstamps *hwtstamps)
{
struct sock *sk = orig_skb->sk;
struct sock_exterr_skb *serr;
struct sk_buff *skb;
int err;
if (!sk)
return;
if (hwtstamps) {
*skb_hwtstamps(orig_skb) =
*hwtstamps;
} else {
/*
* no hardware time stamps available,
* so keep the shared tx_flags and only
* store software time stamp
*/
orig_skb->tstamp = ktime_get_real();
}
skb = skb_clone(orig_skb, GFP_ATOMIC);
if (!skb)
return;
serr = SKB_EXT_ERR(skb);
memset(serr, 0, sizeof(*serr));
serr->ee.ee_errno = ENOMSG;
serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
err = sock_queue_err_skb(sk, skb);
if (err)
kfree_skb(skb);
}
EXPORT_SYMBOL_GPL(skb_tstamp_tx);
void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
{
struct sock *sk = skb->sk;
struct sock_exterr_skb *serr;
int err;
skb->wifi_acked_valid = 1;
skb->wifi_acked = acked;
serr = SKB_EXT_ERR(skb);
memset(serr, 0, sizeof(*serr));
serr->ee.ee_errno = ENOMSG;
serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
err = sock_queue_err_skb(sk, skb);
if (err)
kfree_skb(skb);
}
EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
/**
* skb_partial_csum_set - set up and verify partial csum values for packet
* @skb: the skb to set
* @start: the number of bytes after skb->data to start checksumming.
* @off: the offset from start to place the checksum.
*
* For untrusted partially-checksummed packets, we need to make sure the values
* for skb->csum_start and skb->csum_offset are valid so we don't oops.
*
* This function checks and sets those values and skb->ip_summed: if this
* returns false you should drop the packet.
*/
bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
{
if (unlikely(start > skb_headlen(skb)) ||
unlikely((int)start + off > skb_headlen(skb) - 2)) {
net_warn_ratelimited("bad partial csum: csum=%u/%u len=%u\n",
start, off, skb_headlen(skb));
return false;
}
skb->ip_summed = CHECKSUM_PARTIAL;
skb->csum_start = skb_headroom(skb) + start;
skb->csum_offset = off;
skb_set_transport_header(skb, start);
return true;
}
EXPORT_SYMBOL_GPL(skb_partial_csum_set);
static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
unsigned int max)
{
if (skb_headlen(skb) >= len)
return 0;
/* If we need to pullup then pullup to the max, so we
* won't need to do it again.
*/
if (max > skb->len)
max = skb->len;
if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
return -ENOMEM;
if (skb_headlen(skb) < len)
return -EPROTO;
return 0;
}
#define MAX_TCP_HDR_LEN (15 * 4)
static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
typeof(IPPROTO_IP) proto,
unsigned int off)
{
switch (proto) {
int err;
case IPPROTO_TCP:
err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
off + MAX_TCP_HDR_LEN);
if (!err && !skb_partial_csum_set(skb, off,
offsetof(struct tcphdr,
check)))
err = -EPROTO;
return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
case IPPROTO_UDP:
err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
off + sizeof(struct udphdr));
if (!err && !skb_partial_csum_set(skb, off,
offsetof(struct udphdr,
check)))
err = -EPROTO;
return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
}
return ERR_PTR(-EPROTO);
}
/* This value should be large enough to cover a tagged ethernet header plus
* maximally sized IP and TCP or UDP headers.
*/
#define MAX_IP_HDR_LEN 128
static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
{
unsigned int off;
bool fragment;
__sum16 *csum;
int err;
fragment = false;
err = skb_maybe_pull_tail(skb,
sizeof(struct iphdr),
MAX_IP_HDR_LEN);
if (err < 0)
goto out;
if (ip_hdr(skb)->frag_off & htons(IP_OFFSET | IP_MF))
fragment = true;
off = ip_hdrlen(skb);
err = -EPROTO;
if (fragment)
goto out;
csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
if (IS_ERR(csum))
return PTR_ERR(csum);
if (recalculate)
*csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
ip_hdr(skb)->daddr,
skb->len - off,
ip_hdr(skb)->protocol, 0);
err = 0;
out:
return err;
}
/* This value should be large enough to cover a tagged ethernet header plus
* an IPv6 header, all options, and a maximal TCP or UDP header.
*/
#define MAX_IPV6_HDR_LEN 256
#define OPT_HDR(type, skb, off) \
(type *)(skb_network_header(skb) + (off))
static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
{
int err;
u8 nexthdr;
unsigned int off;
unsigned int len;
bool fragment;
bool done;
__sum16 *csum;
fragment = false;
done = false;
off = sizeof(struct ipv6hdr);
err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
if (err < 0)
goto out;
nexthdr = ipv6_hdr(skb)->nexthdr;
len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
while (off <= len && !done) {
switch (nexthdr) {
case IPPROTO_DSTOPTS:
case IPPROTO_HOPOPTS:
case IPPROTO_ROUTING: {
struct ipv6_opt_hdr *hp;
err = skb_maybe_pull_tail(skb,
off +
sizeof(struct ipv6_opt_hdr),
MAX_IPV6_HDR_LEN);
if (err < 0)
goto out;
hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
nexthdr = hp->nexthdr;
off += ipv6_optlen(hp);
break;
}
case IPPROTO_AH: {
struct ip_auth_hdr *hp;
err = skb_maybe_pull_tail(skb,
off +
sizeof(struct ip_auth_hdr),
MAX_IPV6_HDR_LEN);
if (err < 0)
goto out;
hp = OPT_HDR(struct ip_auth_hdr, skb, off);
nexthdr = hp->nexthdr;
off += ipv6_authlen(hp);
break;
}
case IPPROTO_FRAGMENT: {
struct frag_hdr *hp;
err = skb_maybe_pull_tail(skb,
off +
sizeof(struct frag_hdr),
MAX_IPV6_HDR_LEN);
if (err < 0)
goto out;
hp = OPT_HDR(struct frag_hdr, skb, off);
if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
fragment = true;
nexthdr = hp->nexthdr;
off += sizeof(struct frag_hdr);
break;
}
default:
done = true;
break;
}
}
err = -EPROTO;
if (!done || fragment)
goto out;
csum = skb_checksum_setup_ip(skb, nexthdr, off);
if (IS_ERR(csum))
return PTR_ERR(csum);
if (recalculate)
*csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
&ipv6_hdr(skb)->daddr,
skb->len - off, nexthdr, 0);
err = 0;
out:
return err;
}
/**
* skb_checksum_setup - set up partial checksum offset
* @skb: the skb to set up
* @recalculate: if true the pseudo-header checksum will be recalculated
*/
int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
{
int err;
switch (skb->protocol) {
case htons(ETH_P_IP):
err = skb_checksum_setup_ipv4(skb, recalculate);
break;
case htons(ETH_P_IPV6):
err = skb_checksum_setup_ipv6(skb, recalculate);
break;
default:
err = -EPROTO;
break;
}
return err;
}
EXPORT_SYMBOL(skb_checksum_setup);
void __skb_warn_lro_forwarding(const struct sk_buff *skb)
{
net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
skb->dev->name);
}
EXPORT_SYMBOL(__skb_warn_lro_forwarding);
void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
{
if (head_stolen) {
skb_release_head_state(skb);
kmem_cache_free(skbuff_head_cache, skb);
} else {
__kfree_skb(skb);
}
}
EXPORT_SYMBOL(kfree_skb_partial);
/**
* skb_try_coalesce - try to merge skb to prior one
* @to: prior buffer
* @from: buffer to add
* @fragstolen: pointer to boolean
* @delta_truesize: how much more was allocated than was requested
*/
bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
bool *fragstolen, int *delta_truesize)
{
int i, delta, len = from->len;
*fragstolen = false;
if (skb_cloned(to))
return false;
if (len <= skb_tailroom(to)) {
BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
*delta_truesize = 0;
return true;
}
if (skb_has_frag_list(to) || skb_has_frag_list(from))
return false;
if (skb_headlen(from) != 0) {
struct page *page;
unsigned int offset;
if (skb_shinfo(to)->nr_frags +
skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS)
return false;
if (skb_head_is_locked(from))
return false;
delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
page = virt_to_head_page(from->head);
offset = from->data - (unsigned char *)page_address(page);
skb_fill_page_desc(to, skb_shinfo(to)->nr_frags,
page, offset, skb_headlen(from));
*fragstolen = true;
} else {
if (skb_shinfo(to)->nr_frags +
skb_shinfo(from)->nr_frags > MAX_SKB_FRAGS)
return false;
delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
}
WARN_ON_ONCE(delta < len);
memcpy(skb_shinfo(to)->frags + skb_shinfo(to)->nr_frags,
skb_shinfo(from)->frags,
skb_shinfo(from)->nr_frags * sizeof(skb_frag_t));
skb_shinfo(to)->nr_frags += skb_shinfo(from)->nr_frags;
if (!skb_cloned(from))
skb_shinfo(from)->nr_frags = 0;
/* if the skb is not cloned this does nothing
* since we set nr_frags to 0.
*/
for (i = 0; i < skb_shinfo(from)->nr_frags; i++)
skb_frag_ref(from, i);
to->truesize += delta;
to->len += len;
to->data_len += len;
*delta_truesize = delta;
return true;
}
EXPORT_SYMBOL(skb_try_coalesce);
/**
* skb_scrub_packet - scrub an skb
*
* @skb: buffer to clean
* @xnet: packet is crossing netns
*
* skb_scrub_packet can be used after encapsulating or decapsulting a packet
* into/from a tunnel. Some information have to be cleared during these
* operations.
* skb_scrub_packet can also be used to clean a skb before injecting it in
* another namespace (@xnet == true). We have to clear all information in the
* skb that could impact namespace isolation.
*/
void skb_scrub_packet(struct sk_buff *skb, bool xnet)
{
if (xnet)
skb_orphan(skb);
skb->tstamp.tv64 = 0;
skb->pkt_type = PACKET_HOST;
skb->skb_iif = 0;
skb->local_df = 0;
skb_dst_drop(skb);
skb->mark = 0;
secpath_reset(skb);
nf_reset(skb);
nf_reset_trace(skb);
}
EXPORT_SYMBOL_GPL(skb_scrub_packet);
/**
* skb_gso_transport_seglen - Return length of individual segments of a gso packet
*
* @skb: GSO skb
*
* skb_gso_transport_seglen is used to determine the real size of the
* individual segments, including Layer4 headers (TCP/UDP).
*
* The MAC/L2 or network (IP, IPv6) headers are not accounted for.
*/
unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
{
const struct skb_shared_info *shinfo = skb_shinfo(skb);
unsigned int hdr_len;
if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
hdr_len = tcp_hdrlen(skb);
else
hdr_len = sizeof(struct udphdr);
return hdr_len + shinfo->gso_size;
}
EXPORT_SYMBOL_GPL(skb_gso_transport_seglen);
| longman88/kernel-qspinlock | net/core/skbuff.c | C | gpl-2.0 | 99,989 | 24.326494 | 88 | 0.647741 | false |
/*
* f_rndis.c -- RNDIS link function driver
*
* Copyright (C) 2003-2005,2008 David Brownell
* Copyright (C) 2003-2004 Robert Schwebel, Benedikt Spranger
* Copyright (C) 2008 Nokia Corporation
* Copyright (C) 2009 Samsung Electronics
* Author: Michal Nazarewicz (m.nazarewicz@samsung.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* #define VERBOSE_DEBUG */
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/etherdevice.h>
#include <linux/usb/android_composite.h>
#include <asm/atomic.h>
#include "u_ether.h"
#include "rndis.h"
/*
* This function is an RNDIS Ethernet port -- a Microsoft protocol that's
* been promoted instead of the standard CDC Ethernet. The published RNDIS
* spec is ambiguous, incomplete, and needlessly complex. Variants such as
* ActiveSync have even worse status in terms of specification.
*
* In short: it's a protocol controlled by (and for) Microsoft, not for an
* Open ecosystem or markets. Linux supports it *only* because Microsoft
* doesn't support the CDC Ethernet standard.
*
* The RNDIS data transfer model is complex, with multiple Ethernet packets
* per USB message, and out of band data. The control model is built around
* what's essentially an "RNDIS RPC" protocol. It's all wrapped in a CDC ACM
* (modem, not Ethernet) veneer, with those ACM descriptors being entirely
* useless (they're ignored). RNDIS expects to be the only function in its
* configuration, so it's no real help if you need composite devices; and
* it expects to be the first configuration too.
*
* There is a single technical advantage of RNDIS over CDC Ethernet, if you
* discount the fluff that its RPC can be made to deliver: it doesn't need
* a NOP altsetting for the data interface. That lets it work on some of the
* "so smart it's stupid" hardware which takes over configuration changes
* from the software, and adds restrictions like "no altsettings".
*
* Unfortunately MSFT's RNDIS drivers are buggy. They hang or oops, and
* have all sorts of contrary-to-specification oddities that can prevent
* them from working sanely. Since bugfixes (or accurate specs, letting
* Linux work around those bugs) are unlikely to ever come from MSFT, you
* may want to avoid using RNDIS on purely operational grounds.
*
* Omissions from the RNDIS 1.0 specification include:
*
* - Power management ... references data that's scattered around lots
* of other documentation, which is incorrect/incomplete there too.
*
* - There are various undocumented protocol requirements, like the need
* to send garbage in some control-OUT messages.
*
* - MS-Windows drivers sometimes emit undocumented requests.
*/
/*
* Debugging macro and defines
*/
/* #undef CSY_DEBUG */
//#define CSY_DEBUG
#ifdef CSY_DEBUG
# define CSY_DBG(fmt, args...) \
printk(KERN_INFO "usb %s:%d "fmt, __func__, __LINE__, ##args)
#else /* DO NOT PRINT LOG */
# define CSY_DBG(fmt, args...) do { } while (0)
#endif /* CSY_DEBUG */
#ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE
/*#define CSY_SAMSUNG_COMMAND_LOG */
/*#define CSY_SAMSUNG_NO_IAD */
/* soonyong.cho : For using RNDIS interface 0, 1.
* If RNDIS uses another interface number, host driver will have some problem.
*/
# define CSY_SAMSUNG_FIX_IAD_INTERFACE_NUMBER
#endif
#ifdef CSY_DEBUG
#undef DBG
# define DBG(devvalue, fmt, args...) \
printk(KERN_INFO "usb %s:%d "fmt, __func__, __LINE__, ##args)
#endif
#ifdef CSY_DEBUG
#undef VDBG
# define VDBG(devvalue, fmt, args...) \
printk(KERN_INFO "usb %s:%d "fmt, __func__, __LINE__, ##args)
#endif
struct rndis_ep_descs {
struct usb_endpoint_descriptor *in;
struct usb_endpoint_descriptor *out;
struct usb_endpoint_descriptor *notify;
};
struct f_rndis {
struct gether port;
u8 ctrl_id, data_id;
u8 ethaddr[ETH_ALEN];
int config;
struct rndis_ep_descs fs;
struct rndis_ep_descs hs;
struct usb_ep *notify;
struct usb_endpoint_descriptor *notify_desc;
struct usb_request *notify_req;
atomic_t notify_count;
};
static inline struct f_rndis *func_to_rndis(struct usb_function *f)
{
return container_of(f, struct f_rndis, port.func);
}
/* peak (theoretical) bulk transfer rate in bits-per-second */
static unsigned int bitrate(struct usb_gadget *g)
{
if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
return 13 * 512 * 8 * 1000 * 8;
else
return 19 * 64 * 1 * 1000 * 8;
}
/*-------------------------------------------------------------------------*/
/*
*/
#define LOG2_STATUS_INTERVAL_MSEC 5 /* 1 << 5 == 32 msec */
#define STATUS_BYTECOUNT 8 /* 8 bytes data */
/* interface descriptor: */
static struct usb_interface_descriptor rndis_control_intf = {
.bLength = sizeof rndis_control_intf,
.bDescriptorType = USB_DT_INTERFACE,
/* .bInterfaceNumber = DYNAMIC */
/* status endpoint is optional; this could be patched later */
.bNumEndpoints = 1,
#ifdef CONFIG_USB_ANDROID_RNDIS_WCEIS
/* "Wireless" RNDIS; auto-detected by Windows */
.bInterfaceClass = USB_CLASS_WIRELESS_CONTROLLER,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 3,
#else
.bInterfaceClass = USB_CLASS_COMM,
.bInterfaceSubClass = USB_CDC_SUBCLASS_ACM,
.bInterfaceProtocol = USB_CDC_ACM_PROTO_VENDOR,
#endif
/* .iInterface = DYNAMIC */
};
static struct usb_cdc_header_desc header_desc = {
.bLength = sizeof header_desc,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_HEADER_TYPE,
.bcdCDC = cpu_to_le16(0x0110),
};
static struct usb_cdc_call_mgmt_descriptor call_mgmt_descriptor = {
.bLength = sizeof call_mgmt_descriptor,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_CALL_MANAGEMENT_TYPE,
.bmCapabilities = 0x00,
.bDataInterface = 0x01,
};
static struct usb_cdc_acm_descriptor rndis_acm_descriptor = {
.bLength = sizeof rndis_acm_descriptor,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_ACM_TYPE,
.bmCapabilities = 0x00,
};
static struct usb_cdc_union_desc rndis_union_desc = {
.bLength = sizeof(rndis_union_desc),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_UNION_TYPE,
/* .bMasterInterface0 = DYNAMIC */
/* .bSlaveInterface0 = DYNAMIC */
};
/* the data interface has two bulk endpoints */
static struct usb_interface_descriptor rndis_data_intf = {
.bLength = sizeof rndis_data_intf,
.bDescriptorType = USB_DT_INTERFACE,
/* .bInterfaceNumber = DYNAMIC */
.bNumEndpoints = 2,
.bInterfaceClass = USB_CLASS_CDC_DATA,
.bInterfaceSubClass = 0,
.bInterfaceProtocol = 0,
/* .iInterface = DYNAMIC */
};
#ifdef CSY_SAMSUNG_NO_IAD
/* Nothing to do */
#else
static struct usb_interface_assoc_descriptor
rndis_iad_descriptor = {
.bLength = sizeof rndis_iad_descriptor,
.bDescriptorType = USB_DT_INTERFACE_ASSOCIATION,
.bFirstInterface = 0, /* XXX, hardcoded */
.bInterfaceCount = 2, // control + data
# ifdef CONFIG_USB_ANDROID_SAMSUNG_RNDIS_WITH_MS_COMPOSITE
.bFunctionClass = 0xe0,
.bFunctionSubClass = 0x01,
.bFunctionProtocol = 0x03,
# else
.bFunctionClass = USB_CLASS_COMM,
.bFunctionSubClass = USB_CDC_SUBCLASS_ETHERNET,
.bFunctionProtocol = USB_CDC_PROTO_NONE,
# endif
/* .iFunction = DYNAMIC */
};
#endif
/* full speed support: */
static struct usb_endpoint_descriptor fs_notify_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = cpu_to_le16(STATUS_BYTECOUNT),
.bInterval = 1 << LOG2_STATUS_INTERVAL_MSEC,
};
static struct usb_endpoint_descriptor fs_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_endpoint_descriptor fs_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_descriptor_header *eth_fs_function[] = {
#ifdef CSY_SAMSUNG_NO_IAD
/* Nothing to do */
#else
(struct usb_descriptor_header *) &rndis_iad_descriptor,
#endif
/* control interface matches ACM, not Ethernet */
(struct usb_descriptor_header *) &rndis_control_intf,
(struct usb_descriptor_header *) &header_desc,
(struct usb_descriptor_header *) &call_mgmt_descriptor,
(struct usb_descriptor_header *) &rndis_acm_descriptor,
(struct usb_descriptor_header *) &rndis_union_desc,
(struct usb_descriptor_header *) &fs_notify_desc,
/* data interface has no altsetting */
(struct usb_descriptor_header *) &rndis_data_intf,
(struct usb_descriptor_header *) &fs_in_desc,
(struct usb_descriptor_header *) &fs_out_desc,
NULL,
};
/* high speed support: */
static struct usb_endpoint_descriptor hs_notify_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = cpu_to_le16(STATUS_BYTECOUNT),
.bInterval = LOG2_STATUS_INTERVAL_MSEC + 4,
};
static struct usb_endpoint_descriptor hs_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(512),
};
static struct usb_endpoint_descriptor hs_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(512),
};
static struct usb_descriptor_header *eth_hs_function[] = {
#ifdef CSY_SAMSUNG_NO_IAD
/* Nothing to do */
#else
(struct usb_descriptor_header *) &rndis_iad_descriptor,
#endif
/* control interface matches ACM, not Ethernet */
(struct usb_descriptor_header *) &rndis_control_intf,
(struct usb_descriptor_header *) &header_desc,
(struct usb_descriptor_header *) &call_mgmt_descriptor,
(struct usb_descriptor_header *) &rndis_acm_descriptor,
(struct usb_descriptor_header *) &rndis_union_desc,
(struct usb_descriptor_header *) &hs_notify_desc,
/* data interface has no altsetting */
(struct usb_descriptor_header *) &rndis_data_intf,
(struct usb_descriptor_header *) &hs_in_desc,
(struct usb_descriptor_header *) &hs_out_desc,
NULL,
};
/* string descriptors: */
static struct usb_string rndis_string_defs[] = {
[0].s = "RNDIS Communications Control",
[1].s = "RNDIS Ethernet Data",
#ifdef CSY_SAMSUNG_NO_IAD
/* Nothing to do */
#else
[2].s = "RNDIS",
#endif
{ } /* end of list */
};
static struct usb_gadget_strings rndis_string_table = {
.language = 0x0409, /* en-us */
.strings = rndis_string_defs,
};
static struct usb_gadget_strings *rndis_strings[] = {
&rndis_string_table,
NULL,
};
#ifdef CONFIG_USB_ANDROID_RNDIS
static struct usb_ether_platform_data *rndis_pdata;
#endif
/*-------------------------------------------------------------------------*/
static struct sk_buff *rndis_add_header(struct gether *port,
struct sk_buff *skb)
{
struct sk_buff *skb2;
skb2 = skb_realloc_headroom(skb, sizeof(struct rndis_packet_msg_type));
if (skb2)
rndis_add_hdr(skb2);
dev_kfree_skb_any(skb);
return skb2;
}
static void rndis_response_available(void *_rndis)
{
struct f_rndis *rndis = _rndis;
struct usb_request *req = rndis->notify_req;
struct usb_composite_dev *cdev = rndis->port.func.config->cdev;
__le32 *data = req->buf;
int status;
if (atomic_inc_return(&rndis->notify_count) != 1)
return;
/* Send RNDIS RESPONSE_AVAILABLE notification; a
* USB_CDC_NOTIFY_RESPONSE_AVAILABLE "should" work too
*
* This is the only notification defined by RNDIS.
*/
data[0] = cpu_to_le32(1);
data[1] = cpu_to_le32(0);
status = usb_ep_queue(rndis->notify, req, GFP_ATOMIC);
if (status) {
atomic_dec(&rndis->notify_count);
DBG(cdev, "notify/0 --> %d\n", status);
}
}
static void rndis_response_complete(struct usb_ep *ep, struct usb_request *req)
{
struct f_rndis *rndis = req->context;
struct usb_composite_dev *cdev = rndis->port.func.config->cdev;
int status = req->status;
CSY_DBG("rndis_response_complete req->length=0x%x\n", req->length);
/* after TX:
* - USB_CDC_GET_ENCAPSULATED_RESPONSE (ep0/control)
* - RNDIS_RESPONSE_AVAILABLE (status/irq)
*/
switch (status) {
case -ECONNRESET:
case -ESHUTDOWN:
/* connection gone */
atomic_set(&rndis->notify_count, 0);
break;
default:
DBG(cdev, "RNDIS %s response error %d, %d/%d\n",
ep->name, status,
req->actual, req->length);
/* FALLTHROUGH */
case 0:
if (ep != rndis->notify)
break;
/* handle multiple pending RNDIS_RESPONSE_AVAILABLE
* notifications by resending until we're done
*/
if (atomic_dec_and_test(&rndis->notify_count))
break;
status = usb_ep_queue(rndis->notify, req, GFP_ATOMIC);
if (status) {
atomic_dec(&rndis->notify_count);
DBG(cdev, "notify/1 --> %d\n", status);
}
break;
}
}
static void rndis_command_complete(struct usb_ep *ep, struct usb_request *req)
{
struct f_rndis *rndis = req->context;
struct usb_composite_dev *cdev = rndis->port.func.config->cdev;
int status;
/* received RNDIS command from USB_CDC_SEND_ENCAPSULATED_COMMAND */
// spin_lock(&dev->lock);
#ifdef CSY_SAMSUNG_COMMAND_LOG
int i;
printk("usb rndis_command_complete buf=");
for(i=0; i < req->length; i++)
{
printk("%02x ", ((char*)req->buf)[i]);
}
printk("\n");
#endif
status = rndis_msg_parser(rndis->config, (u8 *) req->buf);
if (status < 0)
ERROR(cdev, "RNDIS command error %d, %d/%d\n",
status, req->actual, req->length);
CSY_DBG("rndis_command_complete req->length=0x%x\n", req->length);
// spin_unlock(&dev->lock);
}
static int
rndis_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
{
struct f_rndis *rndis = func_to_rndis(f);
struct usb_composite_dev *cdev = f->config->cdev;
struct usb_request *req = cdev->req;
int value = -EOPNOTSUPP;
u16 w_index = le16_to_cpu(ctrl->wIndex);
u16 w_value = le16_to_cpu(ctrl->wValue);
u16 w_length = le16_to_cpu(ctrl->wLength);
#ifdef CSY_DEBUG
u16 rt = ctrl->bRequestType << 8;
CSY_DBG("bRequestType=0x%x, ctrl->bRequest=0x%x, req->length=%d w_length=%d,rndis->ctrl_id=%d,w_index=%d\n", rt, ctrl->bRequest, req->length,w_length, rndis->ctrl_id, w_index);
#endif
#ifdef CONFIG_USB_ANDROID_SAMSUNG_COMPOSITE
/* soonyong.cho : if you use composite framework and RNDIS is not first in all function list,
you have to change w_index number. And please use RNDIS only if you possible.
*/
if (w_index == 0)
w_index = rndis->ctrl_id;
#endif
/* composite driver infrastructure handles everything except
* CDC class messages; interface activation uses set_alt().
*/
switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {
/* RNDIS uses the CDC command encapsulation mechanism to implement
* an RPC scheme, with much getting/setting of attributes by OID.
*/
case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
| USB_CDC_SEND_ENCAPSULATED_COMMAND:
CSY_DBG("USB_CDC_SEND_ENCAPSULATED_COMMAND++\n");
if (w_length > req->length || w_value
|| w_index != rndis->ctrl_id)
goto invalid;
/* read the request; process it later */
value = w_length;
req->complete = rndis_command_complete;
req->context = rndis;
CSY_DBG("USB_CDC_SEND_ENCAPSULATED_COMMAND--\n");
/* later, rndis_response_available() sends a notification */
break;
case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
| USB_CDC_GET_ENCAPSULATED_RESPONSE:
CSY_DBG("USB_CDC_GET_ENCAPSULATED_COMMAND++\n");
if (w_value || w_index != rndis->ctrl_id)
goto invalid;
else {
u8 *buf;
u32 n;
/* return the result */
buf = rndis_get_next_response(rndis->config, &n);
if (buf) {
memcpy(req->buf, buf, n);
req->complete = rndis_response_complete;
rndis_free_response(rndis->config, buf);
value = n;
}
CSY_DBG("USB_CDC_GET_ENCAPSULATED_COMMAND--\n");
/* else stalls ... spec says to avoid that */
}
break;
default:
invalid:
VDBG(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
ctrl->bRequestType, ctrl->bRequest,
w_value, w_index, w_length);
}
/* respond with data transfer or status phase? */
if (value >= 0) {
DBG(cdev, "rndis req%02x.%02x v%04x i%04x l%d\n",
ctrl->bRequestType, ctrl->bRequest,
w_value, w_index, w_length);
req->zero = (value < w_length);
req->length = value;
CSY_DBG("rndis_setup value>=0, req->length=0x%x\n", req->length);
value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
if (value < 0)
ERROR(cdev, "rndis response on err %d\n", value);
}
/* device either stalls (value < 0) or reports success */
return value;
}
static int rndis_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
{
struct f_rndis *rndis = func_to_rndis(f);
struct usb_composite_dev *cdev = f->config->cdev;
/* we know alt == 0 */
CSY_DBG("rndis_set_alt: intf=0x%x,rndis->ctrl_id=0x%x,rndis->data_id=0x%x,alt=0x%x",
intf, rndis->ctrl_id, rndis->data_id,alt);
if (intf == rndis->ctrl_id) {
if (rndis->notify->driver_data) {
VDBG(cdev, "reset rndis control %d\n", intf);
usb_ep_disable(rndis->notify);
} else {
VDBG(cdev, "init rndis ctrl %d\n", intf);
}
rndis->notify_desc = ep_choose(cdev->gadget,
rndis->hs.notify,
rndis->fs.notify);
usb_ep_enable(rndis->notify, rndis->notify_desc);
rndis->notify->driver_data = rndis;
} else if (intf == rndis->data_id) {
struct net_device *net;
if (rndis->port.in_ep->driver_data) {
DBG(cdev, "reset rndis\n");
gether_disconnect(&rndis->port);
}
if (!rndis->port.in) {
DBG(cdev, "init rndis\n");
}
rndis->port.in = ep_choose(cdev->gadget,
rndis->hs.in, rndis->fs.in);
rndis->port.out = ep_choose(cdev->gadget,
rndis->hs.out, rndis->fs.out);
/* Avoid ZLPs; they can be troublesome. */
rndis->port.is_zlp_ok = false;
/* RNDIS should be in the "RNDIS uninitialized" state,
* either never activated or after rndis_uninit().
*
* We don't want data to flow here until a nonzero packet
* filter is set, at which point it enters "RNDIS data
* initialized" state ... but we do want the endpoints
* to be activated. It's a strange little state.
*
* REVISIT the RNDIS gadget code has done this wrong for a
* very long time. We need another call to the link layer
* code -- gether_updown(...bool) maybe -- to do it right.
*/
rndis->port.cdc_filter = 0;
DBG(cdev, "RNDIS RX/TX early activation ... \n");
net = gether_connect(&rndis->port);
CSY_DBG("gether_connect ret=0x%p\n", net);
if (IS_ERR(net))
return PTR_ERR(net);
rndis_set_param_dev(rndis->config, net,
&rndis->port.cdc_filter);
} else
goto fail;
return 0;
fail:
return -EINVAL;
}
static void rndis_disable(struct usb_function *f)
{
struct f_rndis *rndis = func_to_rndis(f);
struct usb_composite_dev *cdev = f->config->cdev;
if (!rndis->notify->driver_data)
return;
DBG(cdev, "rndis deactivated\n");
rndis_uninit(rndis->config);
gether_disconnect(&rndis->port);
usb_ep_disable(rndis->notify);
rndis->notify->driver_data = NULL;
}
/*-------------------------------------------------------------------------*/
/*
* This isn't quite the same mechanism as CDC Ethernet, since the
* notification scheme passes less data, but the same set of link
* states must be tested. A key difference is that altsettings are
* not used to tell whether the link should send packets or not.
*/
static void rndis_open(struct gether *geth)
{
struct f_rndis *rndis = func_to_rndis(&geth->func);
struct usb_composite_dev *cdev = geth->func.config->cdev;
DBG(cdev, "%s\n", __func__);
rndis_set_param_medium(rndis->config, NDIS_MEDIUM_802_3,
bitrate(cdev->gadget) / 100);
rndis_signal_connect(rndis->config);
}
static void rndis_close(struct gether *geth)
{
struct f_rndis *rndis = func_to_rndis(&geth->func);
DBG(geth->func.config->cdev, "%s\n", __func__);
rndis_set_param_medium(rndis->config, NDIS_MEDIUM_802_3, 0);
rndis_signal_disconnect(rndis->config);
}
/*-------------------------------------------------------------------------*/
/* ethernet function driver setup/binding */
static int
rndis_bind(struct usb_configuration *c, struct usb_function *f)
{
struct usb_composite_dev *cdev = c->cdev;
struct f_rndis *rndis = func_to_rndis(f);
int status;
struct usb_ep *ep;
/* allocate instance-specific interface IDs */
status = usb_interface_id(c, f);
if (status < 0)
goto fail;
rndis->ctrl_id = status;
#ifdef CSY_SAMSUNG_NO_IAD
/* Nothing to do */
#else
# ifdef CSY_SAMSUNG_FIX_IAD_INTERFACE_NUMBER
/* Nothing to do */
# else
rndis_iad_descriptor.bFirstInterface = status;
# endif
#endif
rndis_control_intf.bInterfaceNumber = status;
rndis_union_desc.bMasterInterface0 = status;
status = usb_interface_id(c, f);
if (status < 0)
goto fail;
rndis->data_id = status;
rndis_data_intf.bInterfaceNumber = status;
rndis_union_desc.bSlaveInterface0 = status;
status = -ENODEV;
/* allocate instance-specific endpoints */
ep = usb_ep_autoconfig(cdev->gadget, &fs_in_desc);
if (!ep)
goto fail;
rndis->port.in_ep = ep;
ep->driver_data = cdev; /* claim */
ep = usb_ep_autoconfig(cdev->gadget, &fs_out_desc);
if (!ep)
goto fail;
rndis->port.out_ep = ep;
ep->driver_data = cdev; /* claim */
/* NOTE: a status/notification endpoint is, strictly speaking,
* optional. We don't treat it that way though! It's simpler,
* and some newer profiles don't treat it as optional.
*/
ep = usb_ep_autoconfig(cdev->gadget, &fs_notify_desc);
if (!ep)
goto fail;
rndis->notify = ep;
ep->driver_data = cdev; /* claim */
status = -ENOMEM;
/* allocate notification request and buffer */
rndis->notify_req = usb_ep_alloc_request(ep, GFP_KERNEL);
if (!rndis->notify_req)
goto fail;
rndis->notify_req->buf = kmalloc(STATUS_BYTECOUNT, GFP_KERNEL);
if (!rndis->notify_req->buf)
goto fail;
rndis->notify_req->length = STATUS_BYTECOUNT;
CSY_DBG("rndis->notify->>length=0x%x\n", rndis->notify_req->length);
rndis->notify_req->context = rndis;
rndis->notify_req->complete = rndis_response_complete;
/* copy descriptors, and track endpoint copies */
f->descriptors = usb_copy_descriptors(eth_fs_function);
if (!f->descriptors)
goto fail;
rndis->fs.in = usb_find_endpoint(eth_fs_function,
f->descriptors, &fs_in_desc);
rndis->fs.out = usb_find_endpoint(eth_fs_function,
f->descriptors, &fs_out_desc);
rndis->fs.notify = usb_find_endpoint(eth_fs_function,
f->descriptors, &fs_notify_desc);
/* support all relevant hardware speeds... we expect that when
* hardware is dual speed, all bulk-capable endpoints work at
* both speeds
*/
if (gadget_is_dualspeed(c->cdev->gadget)) {
hs_in_desc.bEndpointAddress =
fs_in_desc.bEndpointAddress;
hs_out_desc.bEndpointAddress =
fs_out_desc.bEndpointAddress;
hs_notify_desc.bEndpointAddress =
fs_notify_desc.bEndpointAddress;
/* copy descriptors, and track endpoint copies */
f->hs_descriptors = usb_copy_descriptors(eth_hs_function);
if (!f->hs_descriptors)
goto fail;
rndis->hs.in = usb_find_endpoint(eth_hs_function,
f->hs_descriptors, &hs_in_desc);
rndis->hs.out = usb_find_endpoint(eth_hs_function,
f->hs_descriptors, &hs_out_desc);
rndis->hs.notify = usb_find_endpoint(eth_hs_function,
f->hs_descriptors, &hs_notify_desc);
}
rndis->port.open = rndis_open;
rndis->port.close = rndis_close;
status = rndis_register(rndis_response_available, rndis);
if (status < 0)
goto fail;
rndis->config = status;
rndis_set_param_medium(rndis->config, NDIS_MEDIUM_802_3, 0);
rndis_set_host_mac(rndis->config, rndis->ethaddr);
#ifdef CONFIG_USB_ANDROID_RNDIS
if (rndis_pdata) {
if (rndis_set_param_vendor(rndis->config, rndis_pdata->vendorID,
rndis_pdata->vendorDescr))
goto fail;
}
#endif
/* NOTE: all that is done without knowing or caring about
* the network link ... which is unavailable to this code
* until we're activated via set_alt().
*/
DBG(cdev, "RNDIS: %s speed IN/%s OUT/%s NOTIFY/%s\n",
gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
rndis->port.in_ep->name, rndis->port.out_ep->name,
rndis->notify->name);
return 0;
fail:
if (gadget_is_dualspeed(c->cdev->gadget) && f->hs_descriptors)
usb_free_descriptors(f->hs_descriptors);
if (f->descriptors)
usb_free_descriptors(f->descriptors);
if (rndis->notify_req) {
kfree(rndis->notify_req->buf);
usb_ep_free_request(rndis->notify, rndis->notify_req);
}
/* we might as well release our claims on endpoints */
if (rndis->notify)
rndis->notify->driver_data = NULL;
if (rndis->port.out)
rndis->port.out_ep->driver_data = NULL;
if (rndis->port.in)
rndis->port.in_ep->driver_data = NULL;
ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
return status;
}
static void
rndis_unbind(struct usb_configuration *c, struct usb_function *f)
{
struct f_rndis *rndis = func_to_rndis(f);
rndis_deregister(rndis->config);
rndis_exit();
if (gadget_is_dualspeed(c->cdev->gadget))
usb_free_descriptors(f->hs_descriptors);
usb_free_descriptors(f->descriptors);
kfree(rndis->notify_req->buf);
usb_ep_free_request(rndis->notify, rndis->notify_req);
kfree(rndis);
}
/* Some controllers can't support RNDIS ... */
static inline bool can_support_rndis(struct usb_configuration *c)
{
/* everything else is *presumably* fine */
return true;
}
/**
* rndis_bind_config - add RNDIS network link to a configuration
* @c: the configuration to support the network link
* @ethaddr: a buffer in which the ethernet address of the host side
* side of the link was recorded
* Context: single threaded during gadget setup
*
* Returns zero on success, else negative errno.
*
* Caller must have called @gether_setup(). Caller is also responsible
* for calling @gether_cleanup() before module unload.
*/
int
rndis_bind_config(struct usb_configuration *c, u8 ethaddr[ETH_ALEN])
{
struct f_rndis *rndis;
int status;
if (!can_support_rndis(c) || !ethaddr)
return -EINVAL;
/* maybe allocate device-global string IDs */
if (rndis_string_defs[0].id == 0) {
/* ... and setup RNDIS itself */
status = rndis_init();
if (status < 0)
return status;
/* control interface label */
status = usb_string_id(c->cdev);
if (status < 0)
return status;
rndis_string_defs[0].id = status;
rndis_control_intf.iInterface = status;
/* data interface label */
status = usb_string_id(c->cdev);
if (status < 0)
return status;
rndis_string_defs[1].id = status;
rndis_data_intf.iInterface = status;
#ifdef CSY_SAMSUNG_NO_IAD
/* Nothing to do */
#else
/* IAD iFunction label */
status = usb_string_id(c->cdev);
if (status < 0)
return status;
rndis_string_defs[2].id = status;
rndis_iad_descriptor.iFunction = status;
#endif
}
/* allocate and initialize one new instance */
status = -ENOMEM;
rndis = kzalloc(sizeof *rndis, GFP_KERNEL);
if (!rndis)
goto fail;
memcpy(rndis->ethaddr, ethaddr, ETH_ALEN);
/* RNDIS activates when the host changes this filter */
rndis->port.cdc_filter = 0;
/* RNDIS has special (and complex) framing */
rndis->port.header_len = sizeof(struct rndis_packet_msg_type);
rndis->port.wrap = rndis_add_header;
rndis->port.unwrap = rndis_rm_hdr;
rndis->port.func.name = "rndis";
rndis->port.func.strings = rndis_strings;
/* descriptors are per-instance copies */
rndis->port.func.bind = rndis_bind;
rndis->port.func.unbind = rndis_unbind;
rndis->port.func.set_alt = rndis_set_alt;
rndis->port.func.setup = rndis_setup;
rndis->port.func.disable = rndis_disable;
#ifdef CONFIG_USB_ANDROID_RNDIS
/* start disabled */
rndis->port.func.disabled = 1;
#endif
status = usb_add_function(c, &rndis->port.func);
if (status) {
kfree(rndis);
fail:
rndis_exit();
}
return status;
}
#ifdef CONFIG_USB_ANDROID_RNDIS
#include "rndis.c"
static int rndis_probe(struct platform_device *pdev)
{
rndis_pdata = pdev->dev.platform_data;
return 0;
}
static struct platform_driver rndis_platform_driver = {
.driver = { .name = "rndis", },
.probe = rndis_probe,
};
int rndis_function_bind_config(struct usb_configuration *c)
{
int ret;
if (!rndis_pdata) {
printk(KERN_ERR "rndis_pdata null in rndis_function_bind_config\n");
return -1;
}
#ifdef CSY_SAMSUNG
CSY_DBG(
#else
printk(KERN_INFO
#endif
"rndis_function_bind_config MAC: %02X:%02X:%02X:%02X:%02X:%02X\n",
rndis_pdata->ethaddr[0], rndis_pdata->ethaddr[1],
rndis_pdata->ethaddr[2], rndis_pdata->ethaddr[3],
rndis_pdata->ethaddr[4], rndis_pdata->ethaddr[5]);
ret = gether_setup(c->cdev->gadget, rndis_pdata->ethaddr);
CSY_DBG("gether_setup ret=%d\n",ret);
if (ret == 0){
ret = rndis_bind_config(c, rndis_pdata->ethaddr);
CSY_DBG("rndis_bind_config ret=%d\n", ret);
}
return ret;
}
static struct android_usb_function rndis_function = {
.name = "rndis",
.bind_config = rndis_function_bind_config,
};
static int __init init(void)
{
printk(KERN_INFO "f_rndis init\n");
platform_driver_register(&rndis_platform_driver);
android_register_function(&rndis_function);
return 0;
}
module_init(init);
#endif /* CONFIG_USB_ANDROID_RNDIS */
| EpicCM/SPH-D700-Kernel | drivers/usb/gadget/f_rndis.c | C | gpl-2.0 | 29,870 | 27.832046 | 177 | 0.682123 | false |
<!DOCTYPE html>
<html lang="en">
<head>
<title>All Units</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<link rel="StyleSheet" type="text/css" href="pasdoc.css">
</head>
<body>
<h1 class="allitems">All Units</h1>
<table class="unitstable wide_list">
<tr class="listheader">
<th class="itemname">Name</th>
<th class="itemdesc">Description</th>
</tr>
<tr class="list">
<td class="itemname"><a class="bold" href="ok_longcode_underscores.html">ok_longcode_underscores</a></td>
<td class="itemdesc"><p>2005-06-07: Latex version of docs for this unit are wrong, because ConvertString is not called to convert _ char. So _ is not escaped and latex fails. Also, HTML version is bad, because "With" is formatted in bold, because it's treated like keyword.
<p>Fixed by adding _ to AlphaNumeric in PasDoc_Gen in FormatPascalCode.
<p></p>
<pre class="longcode">
Identifier_With_Underscores;</pre>
<p></p></td>
</tr>
</table>
</body></html>
| pasdoc/pasdoc | tests/testcases_output/htmlhelp/ok_longcode_underscores/index.html | HTML | gpl-2.0 | 1,040 | 33.666667 | 283 | 0.713462 | false |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>CORE POS - Fannie: SuperDeptEmailsModel Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() {
if ($('.searchresults').length > 0) { searchBox.DOMSearchField().focus(); }
});
</script>
<link rel="search" href="search-opensearch.php?v=opensearch.xml" type="application/opensearchdescription+xml" title="CORE POS - Fannie"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">CORE POS - Fannie
</div>
<div id="projectbrief">The CORE POS back end</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.6 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<div class="left">
<form id="FSearchBox" action="search.php" method="get">
<img id="MSearchSelect" src="search/mag.png" alt=""/>
<input type="text" id="MSearchField" name="query" value="Search" size="20" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"/>
</form>
</div><div class="right"></div>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="#pro-attribs">Protected Attributes</a> |
<a href="class_super_dept_emails_model-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">SuperDeptEmailsModel Class Reference</div> </div>
</div><!--header-->
<div class="contents">
<div class="dynheader">
Inheritance diagram for SuperDeptEmailsModel:</div>
<div class="dyncontent">
<div class="center">
<img src="class_super_dept_emails_model.png" usemap="#SuperDeptEmailsModel_map" alt=""/>
<map id="SuperDeptEmailsModel_map" name="SuperDeptEmailsModel_map">
<area href="class_basic_model.html" alt="BasicModel" shape="rect" coords="0,56,143,80"/>
</map>
</div></div>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:aab0bd1bb11fe9cbcf682bd5fbd237039"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aab0bd1bb11fe9cbcf682bd5fbd237039"></a>
 </td><td class="memItemRight" valign="bottom"><b>doc</b> ()</td></tr>
<tr class="separator:aab0bd1bb11fe9cbcf682bd5fbd237039"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pub_methods_class_basic_model"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_class_basic_model')"><img src="closed.png" alt="-"/> Public Member Functions inherited from <a class="el" href="class_basic_model.html">BasicModel</a></td></tr>
<tr class="memitem:adf202d3a03b0a2501bd3f0b83bf22d67 inherit pub_methods_class_basic_model"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_basic_model.html#adf202d3a03b0a2501bd3f0b83bf22d67">__construct</a> ($con)</td></tr>
<tr class="separator:adf202d3a03b0a2501bd3f0b83bf22d67 inherit pub_methods_class_basic_model"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ae26e5f467c35ce2193f552b746a9f6b6 inherit pub_methods_class_basic_model"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae26e5f467c35ce2193f552b746a9f6b6"></a>
 </td><td class="memItemRight" valign="bottom"><b>pushToLanes</b> ()</td></tr>
<tr class="separator:ae26e5f467c35ce2193f552b746a9f6b6 inherit pub_methods_class_basic_model"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a296a452d06597e1d2c03f1d096abeb32 inherit pub_methods_class_basic_model"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a296a452d06597e1d2c03f1d096abeb32"></a>
 </td><td class="memItemRight" valign="bottom"><b>deleteFromLanes</b> ()</td></tr>
<tr class="separator:a296a452d06597e1d2c03f1d096abeb32 inherit pub_methods_class_basic_model"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aa7dd5a31fd19610473446b28e2d63d02 inherit pub_methods_class_basic_model"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_basic_model.html#aa7dd5a31fd19610473446b28e2d63d02">getModels</a> ()</td></tr>
<tr class="separator:aa7dd5a31fd19610473446b28e2d63d02 inherit pub_methods_class_basic_model"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ab6666102560d876f7734a545decd86c1 inherit pub_methods_class_basic_model"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_basic_model.html#ab6666102560d876f7734a545decd86c1">setConnectionByName</a> ($db_name)</td></tr>
<tr class="separator:ab6666102560d876f7734a545decd86c1 inherit pub_methods_class_basic_model"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pro-attribs"></a>
Protected Attributes</h2></td></tr>
<tr class="memitem:a4ccef58aa9205e9620848ff6cfa520c9"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a4ccef58aa9205e9620848ff6cfa520c9"></a>
 </td><td class="memItemRight" valign="bottom"><b>$name</b> = "superDeptEmails"</td></tr>
<tr class="separator:a4ccef58aa9205e9620848ff6cfa520c9"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a7f4df8a9b161a98a7c8daa02c923b801"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a7f4df8a9b161a98a7c8daa02c923b801"></a>
 </td><td class="memItemRight" valign="bottom"><b>$preferred_db</b> = 'op'</td></tr>
<tr class="separator:a7f4df8a9b161a98a7c8daa02c923b801"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aca062bf6c7e6ffb669d46f62bb228d06"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><b>$columns</b></td></tr>
<tr class="separator:aca062bf6c7e6ffb669d46f62bb228d06"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pro_attribs_class_basic_model"><td colspan="2" onclick="javascript:toggleInherit('pro_attribs_class_basic_model')"><img src="closed.png" alt="-"/> Protected Attributes inherited from <a class="el" href="class_basic_model.html">BasicModel</a></td></tr>
<tr class="memitem:a4b5fc957344894415b5e86f3ca8c48cf inherit pro_attribs_class_basic_model"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_basic_model.html#a4b5fc957344894415b5e86f3ca8c48cf">$normalize_lanes</a> = false</td></tr>
<tr class="separator:a4b5fc957344894415b5e86f3ca8c48cf inherit pro_attribs_class_basic_model"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aa5bb3c12738e03074a9e2c90420e158e inherit pro_attribs_class_basic_model"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_basic_model.html#aa5bb3c12738e03074a9e2c90420e158e">$currently_normalizing_lane</a> = false</td></tr>
<tr class="separator:aa5bb3c12738e03074a9e2c90420e158e inherit pro_attribs_class_basic_model"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="inherited"></a>
Additional Inherited Members</h2></td></tr>
<tr class="inherit_header pub_attribs_class_basic_model"><td colspan="2" onclick="javascript:toggleInherit('pub_attribs_class_basic_model')"><img src="closed.png" alt="-"/> Public Attributes inherited from <a class="el" href="class_basic_model.html">BasicModel</a></td></tr>
<tr class="memitem:a984e5d160a7f726db726054a46a2d0cc inherit pub_attribs_class_basic_model"><td class="memItemLeft" align="right" valign="top">const </td><td class="memItemRight" valign="bottom"><a class="el" href="class_basic_model.html#a984e5d160a7f726db726054a46a2d0cc">NORMALIZE_MODE_CHECK</a> = 1</td></tr>
<tr class="separator:a984e5d160a7f726db726054a46a2d0cc inherit pub_attribs_class_basic_model"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:af71bad9cde0f24c517b70b94106ca0cf inherit pub_attribs_class_basic_model"><td class="memItemLeft" align="right" valign="top">const </td><td class="memItemRight" valign="bottom"><a class="el" href="class_basic_model.html#af71bad9cde0f24c517b70b94106ca0cf">NORMALIZE_MODE_APPLY</a> = 2</td></tr>
<tr class="separator:af71bad9cde0f24c517b70b94106ca0cf inherit pub_attribs_class_basic_model"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pro_methods_class_basic_model"><td colspan="2" onclick="javascript:toggleInherit('pro_methods_class_basic_model')"><img src="closed.png" alt="-"/> Protected Member Functions inherited from <a class="el" href="class_basic_model.html">BasicModel</a></td></tr>
<tr class="memitem:a48cf78db2b4dbd298e3d779c30e7e255 inherit pro_methods_class_basic_model"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a48cf78db2b4dbd298e3d779c30e7e255"></a>
 </td><td class="memItemRight" valign="bottom"><b>normalizeLanes</b> ($db_name, $mode=<a class="el" href="class_basic_model.html#a984e5d160a7f726db726054a46a2d0cc">BasicModel::NORMALIZE_MODE_CHECK</a>)</td></tr>
<tr class="separator:a48cf78db2b4dbd298e3d779c30e7e255 inherit pro_methods_class_basic_model"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a2973605b6ff4f80e7846e301cc91b02d inherit pro_methods_class_basic_model"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_basic_model.html#a2973605b6ff4f80e7846e301cc91b02d">loadHooks</a> ()</td></tr>
<tr class="separator:a2973605b6ff4f80e7846e301cc91b02d inherit pro_methods_class_basic_model"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a5e6e34f927fb90831f6ca36a8935eff5 inherit pro_methods_class_basic_model"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_basic_model.html#a5e6e34f927fb90831f6ca36a8935eff5">afterNormalize</a> ($db_name, $mode)</td></tr>
<tr class="separator:a5e6e34f927fb90831f6ca36a8935eff5 inherit pro_methods_class_basic_model"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<h2 class="groupheader">Member Data Documentation</h2>
<a class="anchor" id="aca062bf6c7e6ffb669d46f62bb228d06"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">SuperDeptEmailsModel::$columns</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">protected</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<b>Initial value:</b><div class="fragment"><div class="line">= array(</div>
<div class="line"> <span class="stringliteral">'superID'</span> => array(<span class="stringliteral">'type'</span>=><span class="stringliteral">'INT'</span>, <span class="stringliteral">'primary_key'</span>=><span class="keyword">true</span>),</div>
<div class="line"> <span class="stringliteral">'emailAddress'</span> => array(<span class="stringliteral">'type'</span>=><span class="stringliteral">'VARCHAR(255)'</span>, <span class="stringliteral">'replaces'</span>=><span class="stringliteral">'email_address'</span>),</div>
<div class="line"> )</div>
</div><!-- fragment -->
</div>
</div>
<hr/>The documentation for this class was generated from the following file:<ul>
<li>fannie/classlib2.0/data/models/op/SuperDeptEmailsModel.php</li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Fri Sep 2 2016 11:31:11 for CORE POS - Fannie by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.6
</small></address>
</body>
</html>
| CORE-POS/IS4C | documentation/doxy/output/fannie/html/class_super_dept_emails_model.html | HTML | gpl-2.0 | 14,022 | 79.125714 | 329 | 0.713664 | false |
var ipLocal="192.168.4.104";
var imgPort="8080";
var quality=50;
var widthCamera=250;
var heightCamera=250;
var defaultImg;//="http://"+ipLocal+":"+imgPort+"/snapshot?topic=/stereo/right/image_raw?quality="+quality+"?width="+widthCamera+"?height="+heightCamera;
var recognizeObjImg;// = "http://"+ipLocal+":"+imgPort+"/snapshot?topic=/qbo_stereo_selector/viewer?quality="+quality+"?width="+widthCamera+"?height="+heightCamera;
var recognizeFaceImg;// = "http://"+ipLocal+":"+imgPort+"/snapshot?topic=/qbo_face_tracking/viewer?quality="+quality+"?width="+widthCamera+"?height="+heightCamera;
var fps=24;
var ctx;
var img = new Image();
var canvas;
var loop;
var action;
var countdown;
var bool_drawing=false;
var recording = false;
var watching = false;
var training = false;
var auxTime4Coundown;
var name2Learn;
var objectORface="object";
var msgWebCamWatching = "Watching";
var msgWebCamTraining = "Training...";
var msgWebCam = "";
var msgWebCamRec = "Rec";
function startEverything(){
$.post('/mjpegServer/start', function(data){
//Getting images
output = {image:"live_rightEye", quality: quality, width: widthCamera, height: heightCamera};
$.post('/mjpegServer/getUrlFrom',output,function(data) {
defaultImg = "http://"+ipLocal+":"+imgPort+data;
cameraURL=defaultImg;
});
output = {image:"objects", quality: quality, width: widthCamera, height:heightCamera};
$.post('/mjpegServer/getUrlFrom',output,function(data) {
recognizeObjImg = "http://"+ipLocal+":"+imgPort+data;
});
output = {image:"faces", quality: quality, width: widthCamera, height:heightCamera};
$.post('/mjpegServer/getUrlFrom',output,function(data) {
recognizeFaceImg = "http://"+ipLocal+":"+imgPort+data;
});
});
/* $( "input:submit, a, button" ).button();
$( "#radio" ).buttonset();*/
//Camera settings
//Inicializacion de vriables para refreshWebCam
canvas = document.getElementById('canvasWebcam');
ctx=canvas.getContext('2d');
loop=setInterval(refreshWebCam,fps);
$("#training").click(function(){
name2Learn = $("#face_object_name").val().toUpperCase();
if(name2Learn==""){
$("#answer").html(${language['test']});
}else{
//launch Nodes
$.post('/training/launchNodes',function(data) {
if(objectORface == "object"){
cameraURL=recognizeObjImg;
}else{
cameraURL=recognizeFaceImg;
}
auxTime4Coundown = new Date().getTime();
action="learning";
countdown=3;
bool_drawing=true;
});
}
});
$("#guessing").click(function(){
//launch Nodes
$.post('/training/launchNodes',function(data) {
if(objectORface == "object"){
cameraURL=recognizeObjImg;
}else{
cameraURL=recognizeFaceImg;
}
auxTime4Coundown = new Date().getTime();
action="recognizing";
countdown=3;
bool_drawing=true;
});
});
$("#radioFace").click(function(){
$.post('/training/selectFaceRecognition',function(data) {
$("#personORobject").html("person");
});
});
$("#radioObject").click(function(){
$.post('/training/selectObjectRecognition',function(data) {
$("#personORobject").html("object");
});
});
};
function refreshWebCam(){
//We check wether we are in the tab that is showing the canvas y we just left, so we have to stop everthing
if( $("#ui-tabs-4").hasClass('ui-tabs-hide') ){
clearInterval(loop);
//stop mjpeg server
$.post('/mjpegServer/stop', function(data) {
if(data=="ERROR"){
}
});
}
try{
img.src=cameraURL;
img.onload = function(){
ctx.drawImage(img, 0, 0, img.width, img.height);
if(bool_drawing){
//Painting countdown
if(countdown > -1){
if ( new Date().getTime() - auxTime4Coundown >= 1000 ){
countdown = countdown - 1;
auxTime4Coundown = new Date().getTime();
}
if(countdown != -1){
ctx.font = "bold 36px sans-serif";
ctx.fillStyle = "rgb(255, 0, 0)";
ctx.fillText(countdown.toString(), 10, 200);
}else{
countdown = -100;
//alert("lanzadera");
//Lanzamos la grabacion de fotogramas
//ID_grabaFotogramas = setInterval(grabaFotogramas, delayBtwFotogramsCaptured);
if(action=="learning"){
recording=true;
disableRadioBotton(true);
startLearning();
}else if(action=="recognizing"){
watching=true;
disableRadioBotton(true);
startRecognition();
}
}
}
if(recording && countdown==-100){
ctx.font = "bold 36px sans-serif";
ctx.fillStyle = "rgb(255, 0, 0)";
ctx.fillText(msgWebCamRec, 10, 200);
}else if(training && countdown==-100){
ctx.font = "bold 36px sans-serif";
ctx.fillStyle = "rgb(255, 0, 0)";
ctx.fillText(msgWebCamTraining, 10, 200);
}else if(watching && countdown==-100){
ctx.font = "bold 36px sans-serif";
ctx.fillStyle = "rgb(255, 0, 0)";
ctx.fillText(msgWebCamWatching, 10, 200);
}
}
}
}catch(e){
}
}
function startLearning(){
//lanzamos aprendizaje
output = { objectName : name2Learn };
$.post('/training/startLearning' ,output, function(data) {
recording=false;
training=true;
$.post('/training/startTraining' , function(data) {
training=false;
bool_drawing=false;
alert(data);
if(data){
$("#answer").html("texto de se ha reconocido bien "+name2Learn);
}else{//error
$("#answer").html("texto de errorno se ha podido reoconcer "+name2Learn);
}
cameraURL=defaultImg;
$.post('/training/stopNode',function(data) {
});
});
});
}
function startRecognition(){
//start recognition
$.post('/training/startRecognition',function(data) {
cameraURL=defaultImg;
watching=false;
if(data!=""){
$("#answer").html(data.toLowerCase());
}else{
$("#answer").html("No lo se");
}
//paramos nodo
$.post('/training/stopNode',function(data) {
alert("Hemos matado los nodos");
});
cameraURL=defaultImg;
disableRadioBotton(false);
})
.error(function() {
//paramos nodo
$.post('training/stopNode',function(data) {
});
cameraURL=defaultImg;
disableRadioBotton(false);
});
}
function disableRadioBotton(disable){
if(disable){
$("#radio").attr("disabled", "disabled");
}else{
$("#radio").removeAttr("disabled");
}
}
| OpenQbo/qbo_webi | src/training/static/js/trainingTemplate.js | JavaScript | gpl-2.0 | 9,452 | 31.819444 | 164 | 0.422662 | false |
obj-$(CONFIG_DIAG_CHAR) := diagchar.o
obj-$(CONFIG_DIAG_SDIO_PIPE) += diagfwd_sdio.o
diagchar-objs := diagchar_core.o diagchar_hdlc.o diagfwd.o diagmem.o
# sangwoo.kang 2010-08-30 S
ifeq ($(CONFIG_LGE_DIAGTEST), y)
diagchar-objs += lg_diag_kernel_service.o
endif
# sangwoo.kang 2010-08-30 E
| mtmichaelson/LG_Esteem_Kernel | drivers/char/diag/Makefile | Makefile | gpl-2.0 | 291 | 35.375 | 68 | 0.728522 | false |