code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
/*
* ORXONOX - the hottest 3D action shooter ever to exist
* > www.orxonox.net <
*
*
* License notice:
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Author:
* Michael Wirth
* Co-authors:
* ...
*
*/
#ifndef _NewNewHumanController_H__
#define _NewNewHumanController_H__
#include "OrxonoxPrereqs.h"
#include "util/Math.h"
#include "core/ClassTreeMask.h"
#include "HumanController.h"
namespace orxonox
{
class _OrxonoxExport NewHumanController : public HumanController
{
public:
NewHumanController(Context* context);
virtual ~NewHumanController();
virtual void tick(float dt);
virtual void frontback(const Vector2& value);
virtual void yaw(const Vector2& value);
virtual void pitch(const Vector2& value);
static void accelerate();
static void decelerate();
virtual void doFire(unsigned int firemode);
virtual void hit(Pawn* originator, btManifoldPoint& contactpoint, float damage);
static void unfire();
virtual void doUnfire();
void centerCursor();
static void changeMode();
virtual void changedControllableEntity();
virtual void doPauseControl();
virtual void doResumeControl();
float getCurrentYaw(){ return this->currentYaw_; }
float getCurrentPitch(){ return this->currentPitch_; }
protected:
void updateTarget();
void alignArrows();
void showOverlays();
void hideOverlays();
void hideArrows();
unsigned int controlMode_;
static NewHumanController* localController_s;
private:
float currentYaw_;
float currentPitch_;
OrxonoxOverlay* crossHairOverlay_;
OrxonoxOverlay* centerOverlay_;
OrxonoxOverlay* damageOverlayTop_;
OrxonoxOverlay* damageOverlayRight_;
OrxonoxOverlay* damageOverlayBottom_;
OrxonoxOverlay* damageOverlayLeft_;
float damageOverlayTime_;
float damageOverlayTT_;
float damageOverlayTR_;
float damageOverlayTB_;
float damageOverlayTL_;
OrxonoxOverlay* arrowsOverlay1_;
OrxonoxOverlay* arrowsOverlay2_;
OrxonoxOverlay* arrowsOverlay3_;
OrxonoxOverlay* arrowsOverlay4_;
float overlaySize_;
float arrowsSize_;
bool accelerating_;
float acceleration_;
int firemode_;
bool showArrows_;
bool showDamageOverlay_;
bool showOverlays_;
ClassTreeMask targetMask_;
};
}
#endif /* _NewHumanController_H__ */
|
forivall-mirrors/orxonox-game-code
|
src/orxonox/controllers/NewHumanController.h
|
C
|
gpl-2.0
| 4,032
|
package com.aqua.ludum.ld30.screen;
import com.badlogic.gdx.Screen;
/**
* Blank transition.
* @author GeoYS_2
*
*/
public class Transition {
/**
* Begin transition out of this screen.
* @param otherScreen Might be useful for fancy transitions.
*/
public void startOutTransition(Screen otherScreen){
}
/**
* Has this screen finished transition-ing out?
* @return
*/
public boolean outTransitionFinished(){
return true;
}
/**
* Draw what should be drawn when transition-ing out.
*/
public void renderOutTransition(){
}
/**
* Update the transition out.
*/
public void updateOutTransition(float delta){
}
/**
* Begin transition in of this screen.
* @param otherScreen Might be useful for fancy transitions.
*/
public void startInTransition(Screen otherScreen){
}
/**
* Has this screen finished transition-ing in?
* @return
*/
public boolean inTransitionFinished(){
return true;
}
/**
* Draw what should be drawn when transition-ing in.
*/
public void renderInTransition(){
}
/**
* Update the transition in.
*/
public void updateInTransition(float delta){
}
}
|
GeoYS/ld30
|
src/com/aqua/ludum/ld30/screen/Transition.java
|
Java
|
gpl-2.0
| 1,148
|
/*---------------------------------------------------------------------------*
*--- (c) Martin Vuagnoux, Cambridge University, UK. ---*
*--- Aug.2004 ---*
*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*
* NAME : transmit.h
* DESCRIPTION: define send/recv functions
*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*
* NAME: send_fuzz()
* DESC: send a buffer using tcp/udp or file method:
* tcp: just use send()
* udp: use sendto with sockaddr initialized in udp_client/server_fuzz
* file: use fwrite with stream opened in file_fuzz()
* RETN: 0 if everything is OK, -1 if ERROR.
*---------------------------------------------------------------------------*/
int send_fuzz(config *conf, struct struct_block *block);
/*---------------------------------------------------------------------------*
* NAME: recv_fuzz()
* DESC: recv a buffer using tcp/udp or file method:
* tcp: just use recv()
* udp: use recvfrom with sockaddr initialized in udp_client/server_fuzz
* file: ignored
* RETN: number of bytes received
*---------------------------------------------------------------------------*/
int recv_fuzz(config *conf, struct struct_block *block, unsigned char *buffer);
|
tcell2020/autodafe-0.1-osx
|
src/autodafe/transmit.h
|
C
|
gpl-2.0
| 1,617
|
DROP TABLE IF EXISTS `creature_summon_groups`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `creature_summon_groups` (
`summonerId` mediumint(8) unsigned NOT NULL DEFAULT '0',
`summonerType` tinyint(3) unsigned NOT NULL DEFAULT '0',
`groupId` tinyint(3) unsigned NOT NULL DEFAULT '0',
`entry` mediumint(8) unsigned NOT NULL DEFAULT '0',
`position_x` float NOT NULL DEFAULT '0',
`position_y` float NOT NULL DEFAULT '0',
`position_z` float NOT NULL DEFAULT '0',
`orientation` float NOT NULL DEFAULT '0',
`summonType` tinyint(3) unsigned NOT NULL DEFAULT '0',
`summonTime` int(10) unsigned NOT NULL DEFAULT '0'
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
|
powerzilly/trinitycore
|
sql/old/3.3.5a/TDB51_to_TDB52_updates/world/2013_02_24_00_world_creature_summon_groups.sql
|
SQL
|
gpl-2.0
| 815
|
# XMIHandler
This library provides a Java representation and parser for XMI. Being currently under development, currently targets the support of XMI files exported from ArgoUML.
The library is currently a NetBeans project, so just download and open in NetBeans to test/use.
There are currently neither documentation nor guides as the project is still incomplete.
TODO list:
- Resolve XMI reference id to correct xmi element;
- Test!
- Create unit tests;
- Make xmi classes implement XMISerializable;
- Provide a more complete example;
- Generate jars;
- Create documentation;
---
Rui Couto 2015
|
ruicouto/XMIHandler
|
README.md
|
Markdown
|
gpl-2.0
| 600
|
package com.silverhillapps.boxsorter.gesture;
public class BSMoveListener {
}
|
SalvaAguilar/BoxSorter
|
src/com/silverhillapps/boxsorter/gesture/BSMoveListener.java
|
Java
|
gpl-2.0
| 80
|
//----------------------------------------------------------------------------
//Copyright (c) 2005 Zope Foundation and Contributors.
//This software is subject to the provisions of the Zope Public License,
//Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
//THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
//WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
//FOR A PARTICULAR PURPOSE.
//TestRecorder - a javascript library to support browser test recording. It
//is designed to be as cross-browser compatible as possible and to promote
//loose coupling with the user interface, making it easier to evolve the UI
//and experiment with alternative interfaces.
//caveats: popup windows undefined, cant handle framesets
//todo:
//- capture submit (w/lookback for doctest)
//- cleanup strings
//Contact Brian Lloyd (brian@zope.com) with questions or comments.
//---------------------------------------------------------------------------
if (typeof(TestRecorder) == "undefined") {
TestRecorder = {};
}
//---------------------------------------------------------------------------
//Browser -- a singleton that provides a cross-browser API for managing event
//handlers and miscellaneous browser functions.
//Methods:
//captureEvent(window, name, handler) -- capture the named event occurring
//in the given window, setting the function handler as the event handler.
//The event name should be of the form "click", "blur", "change", etc.
//releaseEvent(window, name, handler) -- release the named event occurring
//in the given window. The event name should be of the form "click", "blur",
//"change", etc.
//getSelection(window) -- return the text currently selected, or the empty
//string if no text is currently selected in the browser.
//---------------------------------------------------------------------------
if (typeof(TestRecorder.Browser) == "undefined") {
TestRecorder.Browser = {};
}
TestRecorder.Browser.captureEvent = function(wnd, name, func) {
var lname = name.toLowerCase();
var doc = wnd.document;
wnd.captureEvents(Event[name.toUpperCase()]);
wnd["on" + lname] = func;
}
TestRecorder.Browser.releaseEvent = function(wnd, name, func) {
var lname = name.toLowerCase();
var doc = wnd.document;
wnd.releaseEvents(Event[name.toUpperCase()]);
wnd["on" + lname] = null;
}
TestRecorder.Browser.getSelection = function(wnd) {
var doc = wnd.document;
if (wnd.getSelection) {
return wnd.getSelection() + "";
}
else if (doc.getSelection) {
return doc.getSelection() + "";
}
else if (doc.selection && doc.selection.createRange) {
return doc.selection.createRange().text + "";
}
return "";
}
TestRecorder.Browser.windowHeight = function(wnd) {
var doc = wnd.document;
if (wnd.innerHeight) {
return wnd.innerHeight;
}
else if (doc.documentElement && doc.documentElement.clientHeight) {
return doc.documentElement.clientHeight;
}
else if (document.body) {
return document.body.clientHeight;
}
return -1;
}
TestRecorder.Browser.windowWidth = function(wnd) {
var doc = wnd.document;
if (wnd.innerWidth) {
return wnd.innerWidth;
}
else if (doc.documentElement && doc.documentElement.clientWidth) {
return doc.documentElement.clientWidth;
}
else if (document.body) {
return document.body.clientWidth;
}
return -1;
}
//---------------------------------------------------------------------------
//Event -- a class that provides a cross-browser API dealing with most of the
//interesting information about events.
//Methods:
//type() -- returns the string type of the event (e.g. "click")
//target() -- returns the target of the event
//button() -- returns the mouse button pressed during the event. Because
//it is not possible to reliably detect a middle button press, this method
//only recognized the left and right mouse buttons. Returns one of the
//constants Event.LeftButton, Event.RightButton or Event.UnknownButton for
//a left click, right click, or indeterminate (or no mouse click).
//keycode() -- returns the index code of the key pressed. Note that this
//value may differ across browsers because of character set differences.
//Whenever possible, it is suggested to use keychar() instead.
//keychar() -- returns the char version of the key pressed rather than a
//raw numeric code. The resulting value is subject to all of the vagaries
//of browsers, character encodings in use, etc.
//shiftkey() -- returns true if the shift key was pressed.
//posX() -- return the X coordinate of the mouse relative to the document.
//posY() -- return the y coordinate of the mouse relative to the document.
//stopPropagation() -- stop event propagation (if supported)
//preventDefault() -- prevent the default action (if supported)
//---------------------------------------------------------------------------
TestRecorder.Event = function(e) {
this.event = (e) ? e : window.event;
}
TestRecorder.Event.LeftButton = 0;
TestRecorder.Event.MiddleButton = 1;
TestRecorder.Event.RightButton = 2;
TestRecorder.Event.UnknownButton = 3;
TestRecorder.Event.prototype.stopPropagation = function() {
if (this.event.stopPropagation)
this.event.stopPropagation();
}
TestRecorder.Event.prototype.preventDefault = function() {
if (this.event.preventDefault)
this.event.preventDefault();
}
TestRecorder.Event.prototype.type = function() {
return this.event.type;
}
TestRecorder.Event.prototype.button = function() {
if (this.event.button) {
if (this.event.button == 2) {
return TestRecorder.Event.RightButton;
}
return TestRecorder.Event.LeftButton;
}
else if (this.event.which) {
if (this.event.which > 1) {
return TestRecorder.Event.RightButton;
}
return TestRecorder.Event.LeftButton;
}
return TestRecorder.Event.UnknownButton;
}
TestRecorder.Event.prototype.target = function() {
var t = (this.event.target) ? this.event.target : this.event.srcElement;
if (t && t.nodeType == 3) // safari bug
return t.parentNode;
return t;
}
TestRecorder.Event.prototype.keycode = function() {
return (this.event.keyCode) ? this.event.keyCode : this.event.which;
}
TestRecorder.Event.prototype.keychar = function() {
return String.fromCharCode(this.keycode());
}
TestRecorder.Event.prototype.shiftkey = function() {
if (this.event.shiftKey)
return true;
return false;
}
TestRecorder.Event.prototype.posX = function() {
if (this.event.pageX)
return this.event.pageX;
else if (this.event.clientX) {
return this.event.clientX + document.body.scrollLeft;
}
return 0;
}
TestRecorder.Event.prototype.posY = function() {
if (this.event.pageY)
return this.event.pageY;
else if (this.event.clientY) {
return this.event.clientY + document.body.scrollTop;
}
return 0;
}
//---------------------------------------------------------------------------
//TestCase -- this class contains the interesting events that happen in
//the course of a test recording and provides some testcase metadata.
//Attributes:
//title -- the title of the test case.
//items -- an array of objects representing test actions and checks
//---------------------------------------------------------------------------
TestRecorder.TestCase = function() {
this.title = "Test Case";
// maybe some items are already stored in the background
// but we do not need them here anyway
this.items = new Array();
}
TestRecorder.TestCase.prototype.append = function(o) {
console.log('append',o);
this.items[this.items.length] = o;
chrome.runtime.sendMessage({action: "append", obj: o});
}
TestRecorder.TestCase.prototype.peek = function() {
return this.items[this.items.length - 1];
}
TestRecorder.TestCase.prototype.poke = function(o) {
this.items[this.items.length - 1] = o;
chrome.runtime.sendMessage({action: "poke", obj: o});
}
//---------------------------------------------------------------------------
//Event types -- whenever an interesting event happens (an action or a check)
//it is recorded as one of the object types defined below. All events have a
//'type' attribute that marks the type of the event (one of the values in the
//EventTypes enumeration) and different attributes to capture the pertinent
//information at the time of the event.
//---------------------------------------------------------------------------
if (typeof(TestRecorder.EventTypes) == "undefined") {
TestRecorder.EventTypes = {};
}
TestRecorder.EventTypes.OpenUrl = 0;
TestRecorder.EventTypes.Click = 1;
TestRecorder.EventTypes.Change = 2;
TestRecorder.EventTypes.Comment = 3;
TestRecorder.EventTypes.Submit = 4;
TestRecorder.EventTypes.CheckPageTitle = 5;
TestRecorder.EventTypes.CheckPageLocation = 6;
TestRecorder.EventTypes.CheckTextPresent = 7;
TestRecorder.EventTypes.CheckValue = 8;
TestRecorder.EventTypes.CheckValueContains = 9;
TestRecorder.EventTypes.CheckText = 10;
TestRecorder.EventTypes.CheckHref = 11;
TestRecorder.EventTypes.CheckEnabled = 12;
TestRecorder.EventTypes.CheckDisabled = 13;
TestRecorder.EventTypes.CheckSelectValue = 14;
TestRecorder.EventTypes.CheckSelectOptions = 15;
TestRecorder.EventTypes.CheckImageSrc = 16;
TestRecorder.EventTypes.PageLoad = 17;
TestRecorder.EventTypes.ScreenShot = 18;
TestRecorder.EventTypes.MouseDown = 19;
TestRecorder.EventTypes.MouseUp = 20;
TestRecorder.EventTypes.MouseDrag = 21;
TestRecorder.EventTypes.MouseDrop = 22;
TestRecorder.EventTypes.KeyPress = 23;
TestRecorder.ElementInfo = function(element) {
this.action = element.action;
this.method = element.method;
this.href = element.href;
this.tagName = element.tagName;
this.selector = this.getCleanCSSSelector(element);
this.value = element.value;
this.checked = element.checked;
this.name = element.name;
this.type = element.type;
if (this.type)
this.type = this.type.toLowerCase();
if (element.form)
this.form = {id: element.form.id, name: element.form.name};
this.src = element.src;
this.id = element.id;
this.title = element.title;
this.options = [];
if (element.selectedIndex) {
for (var i=0; i < element.options.length; i++) {
var o = element.options[i];
this.options[i] = {text:o.text, value:o.value};
}
}
this.label = this.findLabelText(element);
}
TestRecorder.ElementInfo.prototype.findLabelText = function(element) {
var label = this.findContainingLabel(element)
var text;
if (!label) {
label = this.findReferencingLabel(element);
}
if (label) {
text = label.innerHTML;
// remove newlines
text = text.replace('\n', ' ');
// remove tags
text = text.replace(/<[^>]*>/g, ' ');
// remove non-alphanumeric prefixes or suffixes
text = text.replace(/^\W*/mg, '')
text = text.replace(/\W*$/mg, '')
// remove extra whitespace
text = text.replace(/^\s*/, '').replace(/\s*$/, '').replace(/\s+/g, ' ');
}
return text;
}
TestRecorder.ElementInfo.prototype.findReferencingLabel = function(element) {
var labels = window.document.getElementsByTagName('label')
for (var i = 0; i < labels.length; i++) {
if (labels[i].attributes['for'] &&
labels[i].attributes['for'].value == element.id)
return labels[i]
}
}
TestRecorder.ElementInfo.prototype.findContainingLabel = function(element) {
var parent = element.parentNode;
if (!parent)
return undefined;
if (parent.tagName && parent.tagName.toLowerCase() == 'label')
return parent;
else
return this.findContainingLabel(parent);
}
TestRecorder.ElementInfo.prototype.getCleanCSSSelector = function(element) {
if(!element) return;
var selector = element.tagName ? element.tagName.toLowerCase() : '';
if(selector == '' || selector == 'html') return '';
var tmp_selector = '';
var accuracy = document.querySelectorAll(selector).length;
if(element.id) {
selector = "#" + element.id.replace(/\./g, '\\.');
accuracy = document.querySelectorAll(selector).length
if(accuracy==1) return selector;
}
if(element.className) {
tmp_selector = '.' + element.className.trim().replace(/ /g,".");
if(document.querySelectorAll(tmp_selector).length < accuracy) {
selector = tmp_selector;
accuracy = document.querySelectorAll(selector).length
if(accuracy==1) return selector;
}
}
var parent = element.parentNode;
var parent_selector = this.getCleanCSSSelector(parent);
if(parent_selector) {
// resolve sibling ambiguity
var matching_sibling = 0;
var matching_nodes = document.querySelectorAll(parent_selector + ' > ' + selector);
for(var i=0; i<matching_nodes.length;i++) {
if(matching_nodes[i].parentNode == parent) matching_sibling++;
}
if(matching_sibling > 1) {
var index = 1;
for (var sibling = element.previousElementSibling; sibling; sibling = sibling.previousElementSibling) index++;
selector = selector + ':nth-child(' + index + ')';
}
// remove useless intermediary parent
selector_array = parent_selector.split(' ');
if(selector_array.length>1) {
for(var i=1;i<selector_array.length;i++) {
tmp_selector = selector_array.slice(0,i).join(' ') + ' ' + selector;
if(document.querySelectorAll(tmp_selector).length == 1) {
selector = tmp_selector;
break;
}
}
}
// improve accuracy if still not correct
accuracy = document.querySelectorAll(selector).length
if(accuracy>1) {
tmp_selector = parent_selector + " " + selector;
if(document.querySelectorAll(tmp_selector).length==1) {
selector = tmp_selector;
} else {
selector = parent_selector + " > " + selector;
}
}
}
return selector;
}
TestRecorder.DocumentEvent = function(type, target) {
this.type = type;
this.url = target.URL;
this.title = target.title;
}
TestRecorder.ElementEvent = function(type, target, text) {
this.type = type;
this.info = new TestRecorder.ElementInfo(target);
this.text = text ? text : recorder.strip(contextmenu.innertext(target));
}
TestRecorder.CommentEvent = function(text) {
this.type = TestRecorder.EventTypes.Comment;
this.text = text;
}
TestRecorder.KeyEvent = function(target, text, code) {
this.type = TestRecorder.EventTypes.KeyPress;
this.info = new TestRecorder.ElementInfo(target);
this.text = text;
this.code = code;
}
TestRecorder.MouseEvent = function(type, target, x, y) {
this.type = type;
this.info = new TestRecorder.ElementInfo(target);
this.x = x;
this.y = y;
this.text = recorder.strip(contextmenu.innertext(target));
}
TestRecorder.ScreenShotEvent = function() {
this.type = TestRecorder.EventTypes.ScreenShot;
}
TestRecorder.OpenURLEvent = function(url) {
this.type = TestRecorder.EventTypes.OpenUrl;
this.url = url;
this.width = window.innerWidth;
this.height = window.innerHeight;
}
TestRecorder.PageLoadEvent = function(url) {
this.type = TestRecorder.EventTypes.OpenUrl;
this.url = url;
this.viaBack = back
}
//---------------------------------------------------------------------------
//ContextMenu -- this class is responsible for managing the right-click
//context menu that shows appropriate checks for targeted elements.
//All methods and attributes are private to this implementation.
//---------------------------------------------------------------------------
TestRecorder.ContextMenu = function() {
this.selected = null;
this.target = null;
this.window = null;
this.visible = false;
this.over = false;
this.menu = null;
}
contextmenu = new TestRecorder.ContextMenu();
TestRecorder.ContextMenu.prototype.build = function(t, x, y) {
var d = recorder.window.document;
var b = d.getElementsByTagName("body").item(0);
var menu = d.createElement("div");
// Needed to deal with various cross-browser insanities...
menu.setAttribute("style", "backgroundColor:#ffffff;color:#000000;border:1px solid #000000;padding:2px;position:absolute;display:none;top:" + y + "px;left:" + x + "px;border:1px;z-index:10000;");
menu.style.backgroundColor="#ffffff";
menu.style.color="#000000";
menu.style.border = "1px solid #000000";
menu.style.padding="2px";
menu.style.position = "absolute";
menu.style.display = "none";
menu.style.zIndex = "10000";
menu.style.top = y.toString();
menu.style.left = x.toString();
menu.onmouseover=contextmenu.onmouseover;
menu.onmouseout=contextmenu.onmouseout;
var selected = TestRecorder.Browser.getSelection(recorder.window).toString();
if (t.width && t.height) {
menu.appendChild(this.item("Check Image Src", this.checkImgSrc));
}
else if (t.type == "text" || t.type == "textarea") {
menu.appendChild(this.item("Check Text Value", this.checkValue));
menu.appendChild(this.item("Check Enabled", this.checkEnabled));
menu.appendChild(this.item("Check Disabled", this.checkDisabled));
}
else if (selected && (selected != "")) {
this.selected = recorder.strip(selected);
menu.appendChild(this.item("Check Text Appears On Page",
this.checkTextPresent));
}
else if (t.href) {
menu.appendChild(this.item("Check Link Text", this.checkText));
menu.appendChild(this.item("Check Link Href", this.checkHref));
}
else if (t.selectedIndex || t.type == "option") {
var name = "Check Selected Value";
if (t.type != "select-one") {
name = name + "s";
}
menu.appendChild(this.item(name, this.checkSelectValue));
menu.appendChild(this.item("Check Select Options",
this.checkSelectOptions));
menu.appendChild(this.item("Check Enabled", this.checkEnabled));
menu.appendChild(this.item("Check Disabled", this.checkDisabled));
}
else if (t.type == "button" || t.type == "submit") {
menu.appendChild(this.item("Check Button Text", this.checkText));
menu.appendChild(this.item("Check Button Value", this.checkValue));
menu.appendChild(this.item("Check Enabled", this.checkEnabled));
menu.appendChild(this.item("Check Disabled", this.checkDisabled));
}
else if (t.value) {
menu.appendChild(this.item("Check Value", this.checkValue));
menu.appendChild(this.item("Check Enabled", this.checkEnabled));
menu.appendChild(this.item("Check Disabled", this.checkDisabled));
}
else {
menu.appendChild(this.item("Check Page Location", this.checkPageLocation));
menu.appendChild(this.item("Check Page Title", this.checkPageTitle));
menu.appendChild(this.item("Screenshot", this.doScreenShot));
}
menu.appendChild(this.item("Cancel", this.cancel));
b.insertBefore(menu, b.firstChild);
return menu;
}
TestRecorder.ContextMenu.prototype.item = function(text, func) {
var doc = recorder.window.document;
var div = doc.createElement("div");
var txt = doc.createTextNode(text);
div.setAttribute("style", "padding:6px;border:1px solid #ffffff;");
div.style.border = "1px solid #ffffff";
div.style.padding = "6px";
div.appendChild(txt);
div.onmouseover = this.onitemmouseover;
div.onmouseout = this.onitemmouseout;
div.onclick = func;
return div;
}
TestRecorder.ContextMenu.prototype.show = function(e) {
if (this.menu) {
this.hide();
}
var wnd = recorder.window;
var doc = wnd.document;
this.target = e.target();
TestRecorder.Browser.captureEvent(wnd, "mousedown", this.onmousedown);
var wh = TestRecorder.Browser.windowHeight(wnd);
var ww = TestRecorder.Browser.windowWidth(wnd);
var x = e.posX();
var y = e.posY();
if ((ww >= 0) && ((ww - x) < 100)) {
x = x - 100;
}
if ((wh >= 0) && ((wh - y) < 100)) {
y = y - 100;
}
var menu = this.build(e.target(), x, y);
this.menu = menu;
menu.style.display = "";
this.visible = true;
return;
}
TestRecorder.ContextMenu.prototype.hide = function() {
var wnd = recorder.window;
TestRecorder.Browser.releaseEvent(wnd, "mousedown", this.onmousedown);
var d = wnd.document;
var b = d.getElementsByTagName("body").item(0);
this.menu.style.display = "none" ;
b.removeChild(this.menu);
this.target = null;
this.visible = false;
this.over = false;
this.menu = null;
}
TestRecorder.ContextMenu.prototype.onitemmouseover = function(e) {
this.style.backgroundColor = "#efefef";
this.style.border = "1px solid #c0c0c0";
return true;
}
TestRecorder.ContextMenu.prototype.onitemmouseout = function(e) {
this.style.backgroundColor = "#ffffff";
this.style.border = "1px solid #ffffff";
return true;
}
TestRecorder.ContextMenu.prototype.onmouseover = function(e) {
contextmenu.over = true;
}
TestRecorder.ContextMenu.prototype.onmouseout = function(e) {
contextmenu.over = false;
}
TestRecorder.ContextMenu.prototype.onmousedown = function(e) {
if(contextmenu.visible) {
if (contextmenu.over == false) {
contextmenu.hide();
return true;
}
return true ;
}
return false;
}
TestRecorder.ContextMenu.prototype.record = function(o) {
recorder.testcase.append(o);
recorder.log(o.type);
contextmenu.hide();
}
TestRecorder.ContextMenu.prototype.checkPageTitle = function() {
var doc = recorder.window.document;
var et = TestRecorder.EventTypes;
var e = new TestRecorder.DocumentEvent(et.CheckPageTitle, doc);
contextmenu.record(e);
}
TestRecorder.ContextMenu.prototype.doScreenShot = function() {
var e = new TestRecorder.ScreenShotEvent();
contextmenu.record(e);
}
TestRecorder.ContextMenu.prototype.checkPageLocation = function() {
var doc = recorder.window.document;
var et = TestRecorder.EventTypes;
var e = new TestRecorder.DocumentEvent(et.CheckPageLocation, doc);
contextmenu.record(e);
}
TestRecorder.ContextMenu.prototype.checkValue = function() {
var t = contextmenu.target;
var et = TestRecorder.EventTypes;
var e = new TestRecorder.ElementEvent(et.CheckValue, t);
contextmenu.record(e);
}
TestRecorder.ContextMenu.prototype.checkValueContains = function() {
var s = contextmenu.selected;
var t = contextmenu.target;
var et = TestRecorder.EventTypes;
var e = new TestRecorder.ElementEvent(et.CheckValueContains, t, s);
contextmenu.selected = null;
contextmenu.record(e);
}
TestRecorder.ContextMenu.prototype.innertext = function(e) {
var doc = recorder.window.document;
if (document.createRange) {
var r = recorder.window.document.createRange();
r.selectNodeContents(e);
return r.toString();
} else {
return e.innerText;
}
}
TestRecorder.ContextMenu.prototype.checkText = function() {
var t = contextmenu.target;
var s = "";
if (t.type == "button" || t.type == "submit") {
s = t.value;
}
else {
s = contextmenu.innertext(t);
}
s = recorder.strip(s);
var et = TestRecorder.EventTypes;
var e = new TestRecorder.ElementEvent(et.CheckText, t, s);
contextmenu.record(e);
}
TestRecorder.ContextMenu.prototype.checkTextPresent = function() {
var t = contextmenu.target;
var s = contextmenu.selected;
var et = TestRecorder.EventTypes;
var e = new TestRecorder.ElementEvent(et.CheckTextPresent, t, s);
contextmenu.selected = null;
contextmenu.record(e);
}
TestRecorder.ContextMenu.prototype.checkHref = function() {
var t = contextmenu.target;
var et = TestRecorder.EventTypes;
var e = new TestRecorder.ElementEvent(et.CheckHref, t);
contextmenu.record(e);
}
TestRecorder.ContextMenu.prototype.checkEnabled = function() {
var t = contextmenu.target;
var et = TestRecorder.EventTypes;
var e = new TestRecorder.ElementEvent(et.CheckEnabled, t);
contextmenu.record(e);
}
TestRecorder.ContextMenu.prototype.checkDisabled = function() {
var t = contextmenu.target;
var et = TestRecorder.EventTypes;
var e = new TestRecorder.ElementEvent(et.CheckDisabled, t);
contextmenu.record(e);
}
TestRecorder.ContextMenu.prototype.checkSelectValue = function() {
var t = contextmenu.target;
var et = TestRecorder.EventTypes;
var e = new TestRecorder.ElementEvent(et.CheckSelectValue, t);
contextmenu.record(e);
}
TestRecorder.ContextMenu.prototype.checkSelectOptions = function() {
var t = contextmenu.target;
var et = TestRecorder.EventTypes;
var e = new TestRecorder.ElementEvent(et.CheckSelectOptions, t);
contextmenu.record(e);
}
TestRecorder.ContextMenu.prototype.checkImgSrc = function() {
var t = contextmenu.target;
var et = TestRecorder.EventTypes;
var e = new TestRecorder.ElementEvent(et.CheckImageSrc, t);
contextmenu.record(e);
}
TestRecorder.ContextMenu.prototype.cancel = function() {
contextmenu.hide();
}
//---------------------------------------------------------------------------
//Recorder -- a controller class that manages the recording of web browser
//activities to produce a test case.
//Instance Methods:
//start() -- start recording browser events.
//stop() -- stop recording browser events.
//reset() -- reset the recorder and initialize a new test case.
//---------------------------------------------------------------------------
TestRecorder.Recorder = function() {
this.testcase = new TestRecorder.TestCase();
this.logfunc = null;
this.window = null;
this.active = false;
}
//The recorder is a singleton -- there is no real reason to have more than
//one instance, and many of its methods are event handlers which need a
//stable reference to the instance.
recorder = new TestRecorder.Recorder();
recorder.logfunc = function(msg) {console.log(msg);};
TestRecorder.Recorder.prototype.start = function() {
this.window = window;
this.captureEvents();
// OVERRIDE stopPropagation
var actualCode = '(' + function() {
var overloadStopPropagation = Event.prototype.stopPropagation;
Event.prototype.stopPropagation = function(){
console.log(this);
overloadStopPropagation.apply(this, arguments);
};
} + ')();';
var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);
this.active = true;
this.log("recorder started");
}
TestRecorder.Recorder.prototype.stop = function() {
this.releaseEvents();
this.active = false;
this.log("recorder stopped");
return;
}
TestRecorder.Recorder.prototype.open = function(url) {
var e = new TestRecorder.OpenURLEvent(url);
this.testcase.append(e);
this.log("open url: " + url);
}
TestRecorder.Recorder.prototype.pageLoad = function() {
var doc = recorder.window.document;
var et = TestRecorder.EventTypes;
var e = new TestRecorder.DocumentEvent(et.PageLoad, doc);
this.testcase.append(e);
this.log("page loaded url: " + e.url);
}
TestRecorder.Recorder.prototype.captureEvents = function() {
var wnd = this.window;
TestRecorder.Browser.captureEvent(wnd, "contextmenu", this.oncontextmenu);
TestRecorder.Browser.captureEvent(wnd, "drag", this.ondrag);
TestRecorder.Browser.captureEvent(wnd, "mousedown", this.onmousedown);
TestRecorder.Browser.captureEvent(wnd, "mouseup", this.onmouseup);
TestRecorder.Browser.captureEvent(wnd, "click", this.onclick);
TestRecorder.Browser.captureEvent(wnd, "change", this.onchange);
TestRecorder.Browser.captureEvent(wnd, "keydown", this.onkeypress);
TestRecorder.Browser.captureEvent(wnd, "select", this.onselect);
TestRecorder.Browser.captureEvent(wnd, "submit", this.onsubmit);
}
TestRecorder.Recorder.prototype.releaseEvents = function() {
var wnd = this.window;
TestRecorder.Browser.releaseEvent(wnd, "contextmenu", this.oncontextmenu);
TestRecorder.Browser.releaseEvent(wnd, "drag", this.ondrag);
TestRecorder.Browser.releaseEvent(wnd, "mousedown", this.onmousedown);
TestRecorder.Browser.releaseEvent(wnd, "mouseup", this.onmouseup);
TestRecorder.Browser.releaseEvent(wnd, "click", this.onclick);
TestRecorder.Browser.releaseEvent(wnd, "change", this.onchange);
TestRecorder.Browser.releaseEvent(wnd, "keydown", this.onkeypress);
TestRecorder.Browser.releaseEvent(wnd, "select", this.onselect);
TestRecorder.Browser.releaseEvent(wnd, "submit", this.onsubmit);
}
TestRecorder.Recorder.prototype.clickaction = function(e) {
// This method is called by our low-level event handler when the mouse
// is clicked in normal mode. Its job is decide whether the click is
// something we care about. If so, we record the event in the test case.
//
// If the context menu is visible, then the click is either over the
// menu (selecting a check) or out of the menu (cancelling it) so we
// always discard clicks that happen when the menu is visible.
if (!contextmenu.visible) {
var et = TestRecorder.EventTypes;
var t = e.target();
if (t.href || (t.type && t.type == "submit") ||
(t.type && t.type == "submit")) {
this.testcase.append(new TestRecorder.ElementEvent(et.Click,e.target()));
} else {
recorder.testcase.append(
new TestRecorder.MouseEvent(
TestRecorder.EventTypes.Click, e.target(), e.posX(), e.posY()
));
}
}
}
TestRecorder.Recorder.prototype.addComment = function(text) {
this.testcase.append(new TestRecorder.CommentEvent(text));
}
TestRecorder.Recorder.prototype.check = function(e) {
// This method is called by our low-level event handler when the mouse
// is clicked in check mode. Its job is decide whether the click is
// something we care about. If so, we record the check in the test case.
contextmenu.show(e);
var target = e.target();
if (target.type) {
var type = target.type.toLowerCase();
if (type == "submit" || type == "button" || type == "image") {
recorder.log('check button == "' + target.value + '"');
}
}
else if (target.href) {
if (target.innerText) {
var text = recorder.strip(target.innerText);
recorder.log('check link == "' + target.text + '"');
}
}
}
TestRecorder.Recorder.prototype.onpageload = function() {
if (this.active) {
// This must be called each time a new document is fully loaded into the
// testing target frame to ensure that events are captured for the page.
recorder.captureEvents();
// if a new page has loaded, but there doesn't seem to be a reason why,
// then we need to record the fact or the information will be lost
if (this.testcase.peek()) {
var last_event_type = this.testcase.peek().type;
if (last_event_type != TestRecorder.EventTypes.OpenUrl &&
last_event_type != TestRecorder.EventTypes.Click &&
last_event_type != TestRecorder.EventTypes.Submit) {
this.open(this.window.location.toString());
}
}
// record the fact that a page load happened
if (this.window)
this.pageLoad();
}
}
TestRecorder.Recorder.prototype.onchange = function(e) {
var e = new TestRecorder.Event(e);
var et = TestRecorder.EventTypes;
var v = new TestRecorder.ElementEvent(et.Change, e.target());
recorder.log("value changed: " + e.target().value, recorder.testcase ,v);
recorder.testcase.append(v);
}
TestRecorder.Recorder.prototype.onselect = function(e) {
var e = new TestRecorder.Event(e);
recorder.log("select: " + e.target());
}
TestRecorder.Recorder.prototype.onsubmit = function(e) {
var e = new TestRecorder.Event(e);
var et = TestRecorder.EventTypes;
// We want to save the form element as the event target
var t = e.target();
while (t.parentNode && t.tagName != "FORM") {
t = t.parentNode;
}
var v = new TestRecorder.ElementEvent(et.Submit, t);
recorder.testcase.append(v);
recorder.log("submit: " + e.target());
}
TestRecorder.Recorder.prototype.ondrag = function(e) {
var e = new TestRecorder.Event(e);
recorder.testcase.append(
new TestRecorder.MouseEvent(
TestRecorder.EventTypes.MouseDrag, e.target(), e.posX(), e.posY()
));
}
TestRecorder.Recorder.prototype.onmousedown = function(e) {
if(!contextmenu.visible) {
var e = new TestRecorder.Event(e);
if (e.button() == TestRecorder.Event.LeftButton) {
recorder.testcase.append(
new TestRecorder.MouseEvent(
TestRecorder.EventTypes.MouseDown, e.target(), e.posX(), e.posY()
));
}
}
}
TestRecorder.Recorder.prototype.onmouseup = function(e) {
if(!contextmenu.visible) {
var e = new TestRecorder.Event(e);
if (e.button() == TestRecorder.Event.LeftButton) {
recorder.testcase.append(
new TestRecorder.MouseEvent(
TestRecorder.EventTypes.MouseUp, e.target(), e.posX(), e.posY()
));
}
}
}
//The dance here between onclick and oncontextmenu requires a bit of
//explanation. IE and Moz/Firefox have wildly different behaviors when
//a right-click occurs. IE6 fires only an oncontextmenu event; Firefox
//gets an onclick event first followed by an oncontextment event. So
//to do the right thing here, we need to silently consume oncontextmenu
//on Firefox, and reroute oncontextmenu to look like a click event for
//IE. In both cases, we need to prevent the default action for cmenu.
TestRecorder.Recorder.prototype.onclick = function(e) {
var e = new TestRecorder.Event(e);
if (e.shiftkey()) {
recorder.check(e);
e.stopPropagation();
e.preventDefault();
return false;
}
if (e.button() == TestRecorder.Event.RightButton) {
recorder.check(e);
return true;
} else if (e.button() == TestRecorder.Event.LeftButton) {
recorder.clickaction(e);
return true;
}
e.stopPropagation();
e.preventDefault();
return false;
}
TestRecorder.Recorder.prototype.oncontextmenu = function(e) {
var e = new TestRecorder.Event(e);
recorder.check(e);
e.stopPropagation();
e.preventDefault();
return false;
}
TestRecorder.Recorder.prototype.onkeypress = function(e) {
var e = new TestRecorder.Event(e);
if (e.shiftkey() && (e.keychar() == 'C')) {
// TODO show comment box here
}
if (e.shiftkey() && (e.keychar() == 'S')) {
recorder.testcase.append(new TestRecorder.ScreenShotEvent());
e.stopPropagation();
e.preventDefault();
return false;
}
var last = recorder.testcase.peek();
if(last.type == TestRecorder.EventTypes.KeyPress) {
last.text = last.text + e.keychar();
recorder.testcase.poke(last);
} else {
recorder.testcase.append(
new TestRecorder.KeyEvent(e.target(), e.keychar(), e.keycode())
);
}
return true;
}
TestRecorder.Recorder.prototype.strip = function(s) {
return s.replace('\n', ' ').replace(/^\s*/, "").replace(/\s*$/, "");
}
TestRecorder.Recorder.prototype.log = function(text) {
if (this.logfunc) {
this.logfunc(text);
}
}
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action == "start") {
recorder.start();
sendResponse({});
}
if (request.action == "stop") {
recorder.stop();
sendResponse({});
}
if (request.action == "open") {
recorder.open(request.url);
sendResponse({});
}
if (request.action == "addComment") {
recorder.addComment(request.text);
sendResponse({});
}
});
//get current status from background
chrome.runtime.sendMessage({action: "get_status"}, function(response) {
if (response.active) {
recorder.start();
}
});
|
johann8384/resurrectio
|
recorder.js
|
JavaScript
|
gpl-2.0
| 37,130
|
/*
* print.c Routines to print stuff.
*
* Version: $Id$
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
* Copyright 2000,2006 The FreeRADIUS server project
*/
RCSID("$Id$")
#include <freeradius-devel/libradius.h>
#include <ctype.h>
/** Checks for utf-8, taken from http://www.w3.org/International/questions/qa-forms-utf-8
*
* @param str input string.
* @param inlen length of input string. May be -1 if str is \0 terminated.
*/
int fr_utf8_char(uint8_t const *str, ssize_t inlen)
{
if (inlen == 0) return 0;
if (inlen < 0) inlen = 4; /* longest char */
if (*str < 0x20) return 0;
if (*str <= 0x7e) return 1; /* 1 */
if (*str <= 0xc1) return 0;
if (inlen < 2) return 0;
if ((str[0] >= 0xc2) && /* 2 */
(str[0] <= 0xdf) &&
(str[1] >= 0x80) &&
(str[1] <= 0xbf)) {
return 2;
}
if (inlen < 3) return 0;
if ((str[0] == 0xe0) && /* 3 */
(str[1] >= 0xa0) &&
(str[1] <= 0xbf) &&
(str[2] >= 0x80) &&
(str[2] <= 0xbf)) {
return 3;
}
if ((str[0] >= 0xe1) && /* 4a */
(str[0] <= 0xec) &&
(str[1] >= 0x80) &&
(str[1] <= 0xbf) &&
(str[2] >= 0x80) &&
(str[2] <= 0xbf)) {
return 3;
}
if ((str[0] >= 0xee) && /* 4b */
(str[0] <= 0xef) &&
(str[1] >= 0x80) &&
(str[1] <= 0xbf) &&
(str[2] >= 0x80) &&
(str[2] <= 0xbf)) {
return 3;
}
if ((str[0] == 0xed) && /* 5 */
(str[1] >= 0x80) &&
(str[1] <= 0x9f) &&
(str[2] >= 0x80) &&
(str[2] <= 0xbf)) {
return 3;
}
if (inlen < 4) return 0;
if ((str[0] == 0xf0) && /* 6 */
(str[1] >= 0x90) &&
(str[1] <= 0xbf) &&
(str[2] >= 0x80) &&
(str[2] <= 0xbf) &&
(str[3] >= 0x80) &&
(str[3] <= 0xbf)) {
return 4;
}
if ((str[0] >= 0xf1) && /* 6 */
(str[1] <= 0xf3) &&
(str[1] >= 0x80) &&
(str[1] <= 0xbf) &&
(str[2] >= 0x80) &&
(str[2] <= 0xbf) &&
(str[3] >= 0x80) &&
(str[3] <= 0xbf)) {
return 4;
}
if ((str[0] == 0xf4) && /* 7 */
(str[1] >= 0x80) &&
(str[1] <= 0x8f) &&
(str[2] >= 0x80) &&
(str[2] <= 0xbf) &&
(str[3] >= 0x80) &&
(str[3] <= 0xbf)) {
return 4;
}
/*
* Invalid UTF-8 Character
*/
return 0;
}
/** Return a pointer to the first UTF8 char in a string.
*
* @param[out] chr_len Where to write the length of the multibyte char passed in chr (may be NULL).
* @param[in] str Haystack.
* @param[in] chr Multibyte needle.
* @return
* - Position of chr in str.
* - NULL if not found.
*/
char const *fr_utf8_strchr(int *chr_len, char const *str, char const *chr)
{
int cchr;
cchr = fr_utf8_char((uint8_t const *)chr, -1);
if (cchr == 0) cchr = 1;
if (chr_len) *chr_len = cchr;
while (*str) {
int schr;
schr = fr_utf8_char((uint8_t const *) str, -1);
if (schr == 0) schr = 1;
if (schr != cchr) goto next;
if (memcmp(str, chr, schr) == 0) {
return (char const *) str;
}
next:
str += schr;
}
return NULL;
}
/** Escape any non printable or non-UTF8 characters in the input string
*
* @note Return value should be checked with is_truncated
* @note Will always \0 terminate unless outlen == 0.
*
* @param[in] in string to escape.
* @param[in] inlen length of string to escape (lets us deal with embedded NULs)
* @param[out] out where to write the escaped string.
* @param[out] outlen the length of the buffer pointed to by out.
* @param[in] quote the quotation character
* @return
* - The number of bytes written to the out buffer.
* - A number >= outlen if truncation has occurred.
*/
size_t fr_snprint(char *out, size_t outlen, char const *in, ssize_t inlen, char quote)
{
uint8_t const *p = (uint8_t const *) in;
size_t utf8;
size_t used;
size_t freespace;
/* No input, so no output... */
if (!in) {
if (out && outlen) *out = '\0';
return 0;
}
/* Figure out the length of the input string */
if (inlen < 0) inlen = strlen(in);
/*
* No quotation character, just use memcpy, ensuring we
* don't overflow the output buffer.
*/
if (!quote) {
if (!out) return inlen;
if ((size_t)inlen >= outlen) {
memcpy(out, in, outlen - 1);
out[outlen - 1] = '\0';
} else {
memcpy(out, in, inlen);
out[inlen] = '\0';
}
return inlen;
}
/*
* Check the output buffer and length. Zero both of them
* out if either are zero.
*/
freespace = outlen;
if (freespace == 0) out = NULL;
if (!out) freespace = 0;
used = 0;
while (inlen > 0) {
int sp = 0;
/*
* Always escape the quotation character.
*/
if (*p == quote) {
sp = quote;
goto do_escape;
}
/*
* Escape the backslash ONLY for single quoted strings.
*/
if (quote == '\'') {
if (*p == '\\') {
sp = '\\';
}
goto do_escape;
}
/*
* Try to convert 0x0a --> \r, etc.
* Backslashes get handled specially.
*/
switch (*p) {
case '\r':
sp = 'r';
break;
case '\n':
sp = 'n';
break;
case '\t':
sp = 't';
break;
case '\\':
sp = '\\';
break;
default:
sp = '\0';
break;
} /* escape the character at *p */
do_escape:
if (sp) {
if ((freespace > 0) && (freespace <= 2)) {
if (out) out[used] = '\0';
out = NULL;
freespace = 0;
} else if (freespace > 2) { /* room for char AND trailing zero */
if (out) {
out[used] = '\\';
out[used + 1] = sp;
}
freespace -= 2;
}
used += 2;
p++;
inlen--;
continue;
}
/*
* All strings are UTF-8 clean.
*/
utf8 = fr_utf8_char(p, inlen);
/*
* If we have an invalid UTF-8 character, it gets
* copied over as a 1-byte character for single
* quoted strings. Which means that the output
* isn't strictly UTF-8, but oh well...
*
* For double quoted strints, the invalid
* characters get escaped as octal encodings.
*/
if (utf8 == 0) {
if (quote == '\'') {
utf8 = 1;
} else {
if ((freespace > 0) && (freespace <= 4)) {
if (out) out[used] = '\0';
out = NULL;
freespace = 0;
} else if (freespace > 4) { /* room for char AND trailing zero */
if (out) snprintf(out + used, freespace, "\\%03o", *p);
freespace -= 4;
}
used += 4;
p++;
inlen--;
continue;
}
}
if ((freespace > 0) && (freespace <= utf8)) {
if (out) out[used] = '\0';
out = NULL;
freespace = 0;
} else if (freespace > utf8) { /* room for char AND trailing zero */
if (out) memcpy(out + used, p, utf8);
freespace -= utf8;
}
used += utf8;
p += utf8;
inlen -= utf8;
}
/*
* Ensure that the output buffer is always zero terminated.
*/
if (out && freespace) out[used] = '\0';
return used;
}
/** Find the length of the buffer required to fully escape a string with fr_prints
*
* Were assuming here that's it's cheaper to figure out the length and do one
* alloc than repeatedly expand the buffer when we find extra chars which need
* to be added.
*
* @param in string to calculate the escaped length for.
* @param inlen length of the input string, if < 0 strlen will be used to check the length.
* @param[in] quote the quotation character.
* @return the size of buffer required to hold the escaped string including the NUL byte.
*/
size_t fr_snprint_len(char const *in, ssize_t inlen, char quote)
{
return fr_snprint(NULL, 0, in, inlen, quote) + 1;
}
/** Escape string that may contain binary data, and write it to a new buffer
*
* This is useful in situations where we expect printable strings as input,
* but under some conditions may get binary data. A good example is libldap
* and the arrays of struct berval ldap_get_values_len returns.
*
* @param[in] ctx To allocate new buffer in.
* @param[in] in String to escape.
* @param[in] inlen Length of string. Should be >= 0 if the data may contain
* embedded \0s. Must be >= 0 if data may not be \0 terminated.
* If < 0 inlen will be calculated using strlen.
* @param[in] quote the quotation character.
* @return new buffer holding the escaped string.
*/
char *fr_asprint(TALLOC_CTX *ctx, char const *in, ssize_t inlen, char quote)
{
size_t len, ret;
char *out;
len = fr_snprint_len(in, inlen, quote);
out = talloc_array(ctx, char, len);
ret = fr_snprint(out, len, in, inlen, quote);
/*
* This is a fatal error, but fr_cond_assert is the strongest
* assert we're allowed to use in library functions.
*/
if (!fr_cond_assert(ret == (len - 1))) {
talloc_free(out);
return NULL;
}
return out;
}
|
mans0954/freeradius-server
|
src/lib/print.c
|
C
|
gpl-2.0
| 9,125
|
#include <linux/capability.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/in.h>
#include <linux/init.h>
#include <linux/if_ether.h>
#include <linux/if_vlan.h>
#include <linux/semaphore.h>
#include <linux/version.h>
#include <net/genetlink.h>
#include <net/sock.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
#include "vlan_mon.h"
#define VLAN_MON_MAGIC 0x639fa78c
#define VLAN_MON_PROTO_IP 0
#define VLAN_MON_PROTO_PPPOE 1
//#define VLAN_MON_PROTO_IP6 2
#define VLAN_MON_NLMSG_SIZE (NLMSG_DEFAULT_SIZE - GENL_HDRLEN - 128)
#ifndef DEFINE_SEMAPHORE
#define DEFINE_SEMAPHORE(name) struct semaphore name = __SEMAPHORE_INITIALIZER(name, 1)
#endif
#ifndef NETIF_F_HW_VLAN_FILTER
#define NETIF_F_HW_VLAN_FILTER NETIF_F_HW_VLAN_CTAG_FILTER
#endif
#ifndef RHEL_MAJOR
#define RHEL_MAJOR 0
#endif
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4,0,0) || RHEL_MAJOR == 7
#define vlan_tx_tag_present(skb) skb_vlan_tag_present(skb)
#endif
#if LINUX_VERSION_CODE < KERNEL_VERSION(5,2,0)
#define nla_nest_start_noflag(skb, attr) nla_nest_start(skb, attr)
#endif
struct vlan_dev {
unsigned int magic;
int ifindex;
struct rcu_head rcu_head;
struct list_head entry;
spinlock_t lock;
unsigned long vid[2][4096/8/sizeof(long)];
unsigned long busy[4096/8/sizeof(long)];
int proto;
};
struct vlan_notify {
struct list_head entry;
int ifindex;
int vlan_ifindex;
int vid;
int proto;
};
static int autoclean = 0;
static LIST_HEAD(vlan_devices);
static LIST_HEAD(vlan_notifies);
static DEFINE_SPINLOCK(vlan_lock);
static struct work_struct vlan_notify_work;
static struct genl_family vlan_mon_nl_family;
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,13,0) && RHEL_MAJOR < 7
static struct genl_multicast_group vlan_mon_nl_mcg;
#endif
static DEFINE_SEMAPHORE(vlan_mon_lock);
static inline int vlan_mon_proto(int proto)
{
if (proto == ETH_P_PPP_DISC)
return VLAN_MON_PROTO_PPPOE;
if (proto == ETH_P_IP)
return VLAN_MON_PROTO_IP;
return -ENOSYS;
}
static int vlan_pt_recv(struct sk_buff *skb, struct net_device *dev, struct packet_type *prev, struct net_device *orig_dev)
{
struct vlan_dev *d;
struct vlan_notify *n;
int vid;
int vlan_ifindex = 0;
int proto;
if (!dev->ml_priv)
goto out;
if (!vlan_tx_tag_present(skb))
goto out;
if (skb->protocol == htons(ETH_P_IP) || skb->protocol == htons(ETH_P_ARP))
proto = VLAN_MON_PROTO_IP;
//else if (skb->protocol == htons(ETH_P_IPV6))
// proto = VLAN_MON_PROTO_IP6;
else if (skb->protocol == htons(ETH_P_PPP_DISC))
proto = VLAN_MON_PROTO_PPPOE;
else
goto out;
rcu_read_lock();
d = rcu_dereference(dev->ml_priv);
if (!d || d->magic != VLAN_MON_MAGIC || d->ifindex != dev->ifindex || (d->proto & (1 << proto)) == 0) {
rcu_read_unlock();
goto out;
}
vid = skb->vlan_tci & VLAN_VID_MASK;
if (likely(d->busy[vid / (8*sizeof(long))] & (1lu << (vid % (8*sizeof(long))))))
vid = -1;
else if (likely(!(d->vid[proto][vid / (8*sizeof(long))] & (1lu << (vid % (8*sizeof(long))))))) {
spin_lock(&d->lock);
d->busy[vid / (8*sizeof(long))] |= 1lu << (vid % (8*sizeof(long)));
d->vid[proto][vid / (8*sizeof(long))] |= 1lu << (vid % (8*sizeof(long)));
spin_unlock(&d->lock);
} else
vid = -1;
if (vid > 0) {
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,10,0)
struct net_device *vd = __vlan_find_dev_deep(dev, vid);
#elif LINUX_VERSION_CODE < KERNEL_VERSION(3,16,0) && RHEL_MAJOR < 7
struct net_device *vd = __vlan_find_dev_deep(dev, skb->vlan_proto, vid);
#else
struct net_device *vd = __vlan_find_dev_deep_rcu(dev, skb->vlan_proto, vid);
#endif
if (vd)
vlan_ifindex = vd->ifindex;
}
rcu_read_unlock();
if (vid == -1)
goto out;
//pr_info("queue %i %i %04x\n", dev->ifindex, vid, skb->protocol);
n = kmalloc(sizeof(*n), GFP_ATOMIC);
if (!n)
goto out;
n->ifindex = dev->ifindex;
n->vlan_ifindex = vlan_ifindex;
n->vid = vid;
n->proto = ntohs(skb->protocol);
spin_lock(&vlan_lock);
list_add_tail(&n->entry, &vlan_notifies);
spin_unlock(&vlan_lock);
schedule_work(&vlan_notify_work);
out:
kfree_skb(skb);
return 0;
}
static void vlan_do_notify(struct work_struct *w)
{
struct vlan_notify *n;
struct sk_buff *report_skb = NULL;
void *header = NULL;
struct nlattr *ns;
int id = 1;
//pr_info("vlan_do_notify\n");
while (1) {
spin_lock_bh(&vlan_lock);
if (list_empty(&vlan_notifies))
n = NULL;
else {
n = list_first_entry(&vlan_notifies, typeof(*n), entry);
list_del(&n->entry);
}
spin_unlock_bh(&vlan_lock);
if (!n)
break;
if (!report_skb) {
report_skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,13,0) && RHEL_MAJOR < 7
header = genlmsg_put(report_skb, 0, vlan_mon_nl_mcg.id, &vlan_mon_nl_family, 0, VLAN_MON_NOTIFY);
#else
header = genlmsg_put(report_skb, 0, 0, &vlan_mon_nl_family, 0, VLAN_MON_NOTIFY);
#endif
}
//pr_info("notify %i vlan %i\n", id, n->vid);
ns = nla_nest_start_noflag(report_skb, id++);
if (!ns)
goto nl_err;
if (nla_put_u32(report_skb, VLAN_MON_ATTR_IFINDEX, n->ifindex))
goto nl_err;
if (n->vlan_ifindex && nla_put_u32(report_skb, VLAN_MON_ATTR_VLAN_IFINDEX, n->vlan_ifindex))
goto nl_err;
if (nla_put_u16(report_skb, VLAN_MON_ATTR_VID, n->vid))
goto nl_err;
if (nla_put_u16(report_skb, VLAN_MON_ATTR_PROTO, n->proto))
goto nl_err;
if (nla_nest_end(report_skb, ns) >= VLAN_MON_NLMSG_SIZE || id == 255) {
genlmsg_end(report_skb, header);
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,13,0) && RHEL_MAJOR < 7
genlmsg_multicast(report_skb, 0, vlan_mon_nl_mcg.id, GFP_KERNEL);
#else
genlmsg_multicast(&vlan_mon_nl_family, report_skb, 0, 0, GFP_KERNEL);
#endif
report_skb = NULL;
id = 1;
}
kfree(n);
continue;
nl_err:
nlmsg_free(report_skb);
report_skb = NULL;
}
if (report_skb) {
genlmsg_end(report_skb, header);
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,13,0) && RHEL_MAJOR < 7
genlmsg_multicast(report_skb, 0, vlan_mon_nl_mcg.id, GFP_KERNEL);
#else
genlmsg_multicast(&vlan_mon_nl_family, report_skb, 0, 0, GFP_KERNEL);
#endif
}
}
static int vlan_mon_nl_cmd_noop(struct sk_buff *skb, struct genl_info *info)
{
struct sk_buff *msg;
void *hdr;
int ret = -ENOBUFS;
msg = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
if (!msg) {
ret = -ENOMEM;
goto out;
}
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,7,0)
hdr = genlmsg_put(msg, info->snd_pid, info->snd_seq, &vlan_mon_nl_family, 0, VLAN_MON_CMD_NOOP);
#else
hdr = genlmsg_put(msg, info->snd_portid, info->snd_seq, &vlan_mon_nl_family, 0, VLAN_MON_CMD_NOOP);
#endif
if (IS_ERR(hdr)) {
ret = PTR_ERR(hdr);
goto err_out;
}
genlmsg_end(msg, hdr);
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,7,0)
return genlmsg_unicast(genl_info_net(info), msg, info->snd_pid);
#else
return genlmsg_unicast(genl_info_net(info), msg, info->snd_portid);
#endif
err_out:
nlmsg_free(msg);
out:
return ret;
}
static int vlan_mon_nl_cmd_add_vlan_mon(struct sk_buff *skb, struct genl_info *info)
{
struct vlan_dev *d;
struct net_device *dev;
int ifindex, i, proto;
if (!info->attrs[VLAN_MON_ATTR_IFINDEX])
return -EINVAL;
if (!info->attrs[VLAN_MON_ATTR_PROTO])
return -EINVAL;
proto = nla_get_u16(info->attrs[VLAN_MON_ATTR_PROTO]);
proto = vlan_mon_proto(proto);
if (proto < 0)
return proto;
ifindex = nla_get_u32(info->attrs[VLAN_MON_ATTR_IFINDEX]);
dev = dev_get_by_index(&init_net, ifindex);
if (!dev)
return -ENODEV;
down(&vlan_mon_lock);
if (dev->ml_priv) {
d = (struct vlan_dev *)dev->ml_priv;
if (d->magic != VLAN_MON_MAGIC || (d->proto & (1 << proto))) {
up(&vlan_mon_lock);
dev_put(dev);
return -EBUSY;
}
} else {
d = kzalloc(sizeof(*d), GFP_KERNEL);
if (!d) {
up(&vlan_mon_lock);
dev_put(dev);
return -ENOMEM;
}
spin_lock_init(&d->lock);
d->magic = VLAN_MON_MAGIC;
d->ifindex = ifindex;
d->proto = 0;
rcu_assign_pointer(dev->ml_priv, d);
list_add_tail(&d->entry, &vlan_devices);
}
d->proto |= 1 << proto;
if (info->attrs[VLAN_MON_ATTR_VLAN_MASK]) {
memcpy(d->vid[proto], nla_data(info->attrs[VLAN_MON_ATTR_VLAN_MASK]), min((int)nla_len(info->attrs[VLAN_MON_ATTR_VLAN_MASK]), (int)sizeof(d->vid)));
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,10,0)
if (dev->features & NETIF_F_HW_VLAN_FILTER) {
rtnl_lock();
for (i = 1; i < 4096; i++) {
if (!(d->vid[proto][i / (8*sizeof(long))] & (1lu << (i % (8*sizeof(long))))))
dev->netdev_ops->ndo_vlan_rx_add_vid(dev, i);
}
rtnl_unlock();
}
#else
if (dev->features & NETIF_F_HW_VLAN_CTAG_FILTER) {
rtnl_lock();
for (i = 1; i < 4096; i++) {
if (!(d->vid[proto][i / (8*sizeof(long))] & (1lu << (i % (8*sizeof(long))))))
dev->netdev_ops->ndo_vlan_rx_add_vid(dev, htons(ETH_P_8021Q), i);
}
rtnl_unlock();
}
#endif
}
up(&vlan_mon_lock);
dev_put(dev);
return 0;
}
static int vlan_mon_nl_cmd_add_vlan_mon_vid(struct sk_buff *skb, struct genl_info *info)
{
struct vlan_dev *d;
int ifindex, vid, proto;
struct net_device *dev;
if (!info->attrs[VLAN_MON_ATTR_IFINDEX] || !info->attrs[VLAN_MON_ATTR_VID] || !info->attrs[VLAN_MON_ATTR_PROTO])
return -EINVAL;
ifindex = nla_get_u32(info->attrs[VLAN_MON_ATTR_IFINDEX]);
vid = nla_get_u16(info->attrs[VLAN_MON_ATTR_VID]);
proto = nla_get_u16(info->attrs[VLAN_MON_ATTR_PROTO]);
proto = vlan_mon_proto(proto);
if (proto < 0)
return proto;
dev = dev_get_by_index(&init_net, ifindex);
if (!dev)
return -ENODEV;
down(&vlan_mon_lock);
if (!dev->ml_priv) {
up(&vlan_mon_lock);
dev_put(dev);
return -EINVAL;
}
d = dev->ml_priv;
spin_lock_bh(&d->lock);
d->vid[proto][vid / (8*sizeof(long))] &= ~(1lu << (vid % (8*sizeof(long))));
d->busy[vid / (8*sizeof(long))] &= ~(1lu << (vid % (8*sizeof(long))));
spin_unlock_bh(&d->lock);
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,10,0)
if (dev->features & NETIF_F_HW_VLAN_FILTER) {
rtnl_lock();
dev->netdev_ops->ndo_vlan_rx_add_vid(dev, vid);
rtnl_unlock();
}
#else
if (dev->features & NETIF_F_HW_VLAN_CTAG_FILTER) {
rtnl_lock();
dev->netdev_ops->ndo_vlan_rx_add_vid(dev, htons(ETH_P_8021Q), vid);
rtnl_unlock();
}
#endif
up(&vlan_mon_lock);
dev_put(dev);
return 0;
}
static int vlan_mon_nl_cmd_del_vlan_mon_vid(struct sk_buff *skb, struct genl_info *info)
{
struct vlan_dev *d;
int ifindex, vid, proto;
struct net_device *dev;
if (!info->attrs[VLAN_MON_ATTR_IFINDEX] || !info->attrs[VLAN_MON_ATTR_VID] || !info->attrs[VLAN_MON_ATTR_PROTO])
return -EINVAL;
ifindex = nla_get_u32(info->attrs[VLAN_MON_ATTR_IFINDEX]);
vid = nla_get_u16(info->attrs[VLAN_MON_ATTR_VID]);
proto = nla_get_u16(info->attrs[VLAN_MON_ATTR_PROTO]);
proto = vlan_mon_proto(proto);
if (proto < 0)
return proto;
down(&vlan_mon_lock);
rtnl_lock();
dev = __dev_get_by_index(&init_net, ifindex);
if (!dev) {
rtnl_unlock();
up(&vlan_mon_lock);
return -ENODEV;
}
if (!dev->ml_priv) {
rtnl_unlock();
up(&vlan_mon_lock);
return -EINVAL;
}
d = dev->ml_priv;
spin_lock_bh(&d->lock);
d->vid[proto][vid / (8*sizeof(long))] |= 1lu << (vid % (8*sizeof(long)));
d->busy[vid / (8*sizeof(long))] &= ~(1lu << (vid % (8*sizeof(long))));
spin_unlock_bh(&d->lock);
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,10,0)
if (dev->features & NETIF_F_HW_VLAN_FILTER)
dev->netdev_ops->ndo_vlan_rx_add_vid(dev, vid);
#else
if (dev->features & NETIF_F_HW_VLAN_CTAG_FILTER)
dev->netdev_ops->ndo_vlan_rx_add_vid(dev, htons(ETH_P_8021Q), vid);
#endif
rtnl_unlock();
up(&vlan_mon_lock);
return 0;
}
static void vlan_dev_clean(struct vlan_dev *d, struct net_device *dev, struct list_head *list)
{
int i;
struct net_device *vd;
for (i = 1; i < 4096; i++) {
if (d->busy[i / (8*sizeof(long))] & (1lu << (i % (8*sizeof(long))))) {
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,10,0)
vd = __vlan_find_dev_deep(dev, i);
#elif LINUX_VERSION_CODE < KERNEL_VERSION(3,16,0) && RHEL_MAJOR < 7
vd = __vlan_find_dev_deep(dev, htons(ETH_P_8021Q), i);
if (!vd)
vd = __vlan_find_dev_deep(dev, htons(ETH_P_8021AD), i);
#else
vd = __vlan_find_dev_deep_rcu(dev, htons(ETH_P_8021Q), i);
if (!vd)
vd = __vlan_find_dev_deep_rcu(dev, htons(ETH_P_8021AD), i);
#endif
if (vd)
vd->rtnl_link_ops->dellink(vd, list);
}
}
}
static int vlan_mon_nl_cmd_del_vlan_mon(struct sk_buff *skb, struct genl_info *info)
{
struct vlan_dev *d;
struct vlan_notify *vn;
int ifindex, proto = 0xffff;
unsigned long flags;
struct list_head *pos, *n;
struct net_device *dev;
LIST_HEAD(list_kill);
if (info->attrs[VLAN_MON_ATTR_PROTO]) {
proto = nla_get_u16(info->attrs[VLAN_MON_ATTR_PROTO]);
proto = vlan_mon_proto(proto);
if (proto < 0)
return proto;
proto = 1 << proto;
}
if (info->attrs[VLAN_MON_ATTR_IFINDEX])
ifindex = nla_get_u32(info->attrs[VLAN_MON_ATTR_IFINDEX]);
else
ifindex = -1;
down(&vlan_mon_lock);
rtnl_lock();
rcu_read_lock();
list_for_each_safe(pos, n, &vlan_devices) {
d = list_entry(pos, typeof(*d), entry);
if ((ifindex == -1 || d->ifindex == ifindex) && (d->proto & proto)) {
d->proto &= ~proto;
dev = __dev_get_by_index(&init_net, d->ifindex);
if (dev) {
if (dev->ml_priv == d) {
if (!d->proto)
rcu_assign_pointer(dev->ml_priv, NULL);
}
if (!d->proto && autoclean)
vlan_dev_clean(d, dev, &list_kill);
}
if (!d->proto) {
list_del(&d->entry);
kfree_rcu(d, rcu_head);
}
}
}
rcu_read_unlock();
if (!list_empty(&list_kill)) {
unregister_netdevice_many(&list_kill);
if (list_kill.next != LIST_POISON1)
list_del(&list_kill);
}
rtnl_unlock();
up(&vlan_mon_lock);
synchronize_net();
spin_lock_irqsave(&vlan_lock, flags);
list_for_each_safe(pos, n, &vlan_notifies) {
vn = list_entry(pos, typeof(*vn), entry);
if ((ifindex == -1 || vn->ifindex == ifindex) && (proto & (1 << vlan_mon_proto(vn->proto)))) {
list_del(&vn->entry);
kfree(vn);
}
}
spin_unlock_irqrestore(&vlan_lock, flags);
return 0;
}
static int vlan_mon_nl_cmd_check_busy(struct sk_buff *skb, struct genl_info *info)
{
int ifindex, vid;
struct net_device *dev;
int ret = 0;
if (!info->attrs[VLAN_MON_ATTR_IFINDEX] || !info->attrs[VLAN_MON_ATTR_VID])
return -EINVAL;
ifindex = nla_get_u32(info->attrs[VLAN_MON_ATTR_IFINDEX]);
vid = nla_get_u16(info->attrs[VLAN_MON_ATTR_VID]);
down(&vlan_mon_lock);
rtnl_lock();
dev = __dev_get_by_index(&init_net, ifindex);
if (dev) {
struct vlan_dev *d = dev->ml_priv;
if (d) {
if (d->busy[vid / (8*sizeof(long))] & (1lu << (vid % (8*sizeof(long)))))
ret = -EBUSY;
}
}
rtnl_unlock();
up(&vlan_mon_lock);
return ret;
}
static const struct nla_policy vlan_mon_nl_policy[VLAN_MON_ATTR_MAX + 1] = {
[VLAN_MON_ATTR_NONE] = { .type = NLA_UNSPEC, },
[VLAN_MON_ATTR_VLAN_MASK] = { .type = NLA_BINARY, .len = 4096/8 },
[VLAN_MON_ATTR_PROTO] = { .type = NLA_U16, },
[VLAN_MON_ATTR_IFINDEX] = { .type = NLA_U32, },
[VLAN_MON_ATTR_VID] = { .type = NLA_U16, },
};
static const struct genl_ops vlan_mon_nl_ops[] = {
{
.cmd = VLAN_MON_CMD_NOOP,
.doit = vlan_mon_nl_cmd_noop,
#if LINUX_VERSION_CODE < KERNEL_VERSION(5,2,0)
.policy = vlan_mon_nl_policy,
#endif
/* can be retrieved by unprivileged users */
},
{
.cmd = VLAN_MON_CMD_ADD,
.doit = vlan_mon_nl_cmd_add_vlan_mon,
.flags = GENL_ADMIN_PERM,
#if LINUX_VERSION_CODE < KERNEL_VERSION(5,2,0)
.policy = vlan_mon_nl_policy,
#endif
},
{
.cmd = VLAN_MON_CMD_ADD_VID,
.doit = vlan_mon_nl_cmd_add_vlan_mon_vid,
.flags = GENL_ADMIN_PERM,
#if LINUX_VERSION_CODE < KERNEL_VERSION(5,2,0)
.policy = vlan_mon_nl_policy,
#endif
},
{
.cmd = VLAN_MON_CMD_DEL,
.doit = vlan_mon_nl_cmd_del_vlan_mon,
.flags = GENL_ADMIN_PERM,
#if LINUX_VERSION_CODE < KERNEL_VERSION(5,2,0)
.policy = vlan_mon_nl_policy,
#endif
},
{
.cmd = VLAN_MON_CMD_CHECK_BUSY,
.doit = vlan_mon_nl_cmd_check_busy,
.flags = GENL_ADMIN_PERM,
#if LINUX_VERSION_CODE < KERNEL_VERSION(5,2,0)
.policy = vlan_mon_nl_policy,
#endif
},
{
.cmd = VLAN_MON_CMD_DEL_VID,
.doit = vlan_mon_nl_cmd_del_vlan_mon_vid,
.flags = GENL_ADMIN_PERM,
#if LINUX_VERSION_CODE < KERNEL_VERSION(5,2,0)
.policy = vlan_mon_nl_policy,
#endif
},
};
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,13,0) && RHEL_MAJOR < 7
static struct genl_multicast_group vlan_mon_nl_mcg = {
.name = VLAN_MON_GENL_MCG,
};
#else
static struct genl_multicast_group vlan_mon_nl_mcgs[] = {
{ .name = VLAN_MON_GENL_MCG, }
};
#endif
static struct genl_family vlan_mon_nl_family = {
#if LINUX_VERSION_CODE < KERNEL_VERSION(4,10,0)
.id = GENL_ID_GENERATE,
#endif
.name = VLAN_MON_GENL_NAME,
.version = VLAN_MON_GENL_VERSION,
.hdrsize = 0,
.maxattr = VLAN_MON_ATTR_MAX,
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4,10,0)
.module = THIS_MODULE,
.ops = vlan_mon_nl_ops,
.n_ops = ARRAY_SIZE(vlan_mon_nl_ops),
.mcgrps = vlan_mon_nl_mcgs,
.n_mcgrps = ARRAY_SIZE(vlan_mon_nl_mcgs),
#endif
#if LINUX_VERSION_CODE >= KERNEL_VERSION(5,2,0)
.policy = vlan_mon_nl_policy,
#endif
};
static struct packet_type vlan_pt __read_mostly = {
.type = __constant_htons(ETH_P_ALL),
.func = vlan_pt_recv,
};
static int __init vlan_mon_init(void)
{
int err;
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,35)
int i;
#endif
printk("vlan-mon driver v1.11\n");
INIT_WORK(&vlan_notify_work, vlan_do_notify);
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,13,0) && RHEL_MAJOR < 7
err = genl_register_family_with_ops(&vlan_mon_nl_family, vlan_mon_nl_ops, ARRAY_SIZE(vlan_mon_nl_ops));
#elif LINUX_VERSION_CODE < KERNEL_VERSION(4,10,0)
err = genl_register_family_with_ops_groups(&vlan_mon_nl_family, vlan_mon_nl_ops, vlan_mon_nl_mcgs);
#else
err = genl_register_family(&vlan_mon_nl_family);
#endif
if (err < 0) {
printk(KERN_INFO "vlan_mon: can't register netlink interface\n");
goto out;
}
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,13,0) && RHEL_MAJOR < 7
err = genl_register_mc_group(&vlan_mon_nl_family, &vlan_mon_nl_mcg);
if (err < 0) {
printk(KERN_INFO "vlan_mon: can't register netlink multicast group\n");
goto out_unreg;
}
#endif
dev_add_pack(&vlan_pt);
return 0;
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,13,0) && RHEL_MAJOR < 7
out_unreg:
#endif
genl_unregister_family(&vlan_mon_nl_family);
out:
return err;
}
static void __exit vlan_mon_fini(void)
{
struct vlan_dev *d;
struct vlan_notify *vn;
struct net_device *dev;
LIST_HEAD(list_kill);
dev_remove_pack(&vlan_pt);
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,13,0) && RHEL_MAJOR < 7
genl_unregister_mc_group(&vlan_mon_nl_family, &vlan_mon_nl_mcg);
#endif
genl_unregister_family(&vlan_mon_nl_family);
down(&vlan_mon_lock);
up(&vlan_mon_lock);
rtnl_lock();
rcu_read_lock();
while (!list_empty(&vlan_devices)) {
d = list_first_entry(&vlan_devices, typeof(*d), entry);
dev = __dev_get_by_index(&init_net, d->ifindex);
if (dev) {
rcu_assign_pointer(dev->ml_priv, NULL);
if (autoclean)
vlan_dev_clean(d, dev, &list_kill);
}
list_del(&d->entry);
kfree_rcu(d, rcu_head);
}
rcu_read_unlock();
if (!list_empty(&list_kill)) {
unregister_netdevice_many(&list_kill);
if (list_kill.next != LIST_POISON1)
list_del(&list_kill);
}
rtnl_unlock();
synchronize_net();
while (!list_empty(&vlan_notifies)) {
vn = list_first_entry(&vlan_notifies, typeof(*vn), entry);
list_del(&vn->entry);
kfree(vn);
}
synchronize_rcu();
}
module_init(vlan_mon_init);
module_exit(vlan_mon_fini);
MODULE_LICENSE("GPL");
module_param(autoclean, int, 0);
//MODULE_PARAM_DESC(autoclean, "automaticaly remove created vlan interfaces on restart");
|
xebd/accel-ppp
|
drivers/vlan_mon/vlan_mon.c
|
C
|
gpl-2.0
| 19,721
|
<?php
/**
* @package Bookpro
* @author Nguyen Dinh Cuong
* @link http://ibookingonline.com
* @copyright Copyright (C) 2011 - 2012 Nguyen Dinh Cuong
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* @version $Id: bus.php 48 2012-07-13 14:13:31Z quannv $
**/
defined('_JEXEC') or die('Restricted access');
//import needed Joomla! libraries
jimport('joomla.application.component.model');
//import needed JoomLIB helpers
AImporter::helper('bookpro', 'model');
//import needed tables
class BookProModelbusRateLog extends AModelFrontEnd
{
var $_table;
var $_ids;
function __construct()
{
parent::__construct();
if (! class_exists('TablebusRateLog')) {
AImporter::table('busratelog');
}
$this->_table = $this->getTable('busratelog');
}
function getObject()
{
$query = 'SELECT `obj`.* FROM `' . $this->_table->getTableName() . '` AS `obj` ';
$query .= 'WHERE `obj`.`id` = ' . (int) $this->_id;
$this->_db->setQuery($query);
if (($object = &$this->_db->loadObject())) {
$this->_table->bind($object);
return $this->_table;
}
return parent::getObject();
}
function getObjectByCode($code)
{
$query = 'SELECT * FROM '. $this->_table->getTableName() . ' AS obj ';
$query .= 'WHERE obj.code = "' . $code .'"';
$this->_db->setQuery($query);
if (($object = &$this->_db->loadObject())) {
$this->_table->bind($object);
return $this->_table;
}
return parent::getObject();
}
function store($data)
{
$config = &AFactory::getConfig();
$id = (int) $data['id'];
$this->_table->init();
$this->_table->load($id);
if (! $this->_table->bind($data)) {
$this->setError($this->_db->getErrorMsg());
return false;
}
unset($data['id']);
if (! $this->_table->check()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
if (! $this->_table->store()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
return $this->_table->id;
}
function trash($cids)
{
foreach ($cids as $id){
if( !$this->_table->delete($id))
{
$this->setError($this->_db->getErrorMsg());
return false;
}
}
return true;
}
function unpublish($cids){
return $this->state('state', $cids, 0, 1);
}
function publish($cids){
return $this->state('state', $cids, 1, 0);
}
function saveorder($cids, $order)
{
$branches = array();
for ($i = 0; $i < count($cids); $i ++) {
$this->_table->load((int) $cids[$i]);
$branches[] = $this->_table->parent;
if ($this->_table->ordering != $order[$i]) {
$this->_table->ordering = $order[$i];
if (! $this->_table->store()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
}
}
$branches = array_unique($branches);
foreach ($branches as $group) {
$this->_table->reorder('parent = ' . (int) $group);
}
return true;
}
}
?>
|
cuongnd/test_pro
|
components/com_bookpro/models/busratelog.php
|
PHP
|
gpl-2.0
| 3,064
|
/* Copyright (c) 2012, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/mfd/pm8xxx/pm8921.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/mfd/pm8xxx/pm8921.h>
#include <linux/slab.h>
#include <linux/pm_runtime.h>
#include <linux/slimbus/slimbus.h>
#include <sound/core.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <sound/soc-dsp.h>
#include <sound/pcm.h>
#include <sound/jack.h>
#include <asm/mach-types.h>
#include <mach/socinfo.h>
#include "msm-pcm-routing.h"
#include "../codecs/wcd9310.h"
/* 8064 machine driver */
#define PM8921_GPIO_BASE NR_GPIO_IRQS
#define PM8921_GPIO_PM_TO_SYS(pm_gpio) (pm_gpio - 1 + PM8921_GPIO_BASE)
#define MSM8064_SPK_ON 1
#define MSM8064_SPK_OFF 0
#define MSM_SLIM_0_RX_MAX_CHANNELS 2
#define MSM_SLIM_0_TX_MAX_CHANNELS 4
#define BTSCO_RATE_8KHZ 8000
#define BTSCO_RATE_16KHZ 16000
#define BOTTOM_SPK_AMP_POS 0x1
#define BOTTOM_SPK_AMP_NEG 0x2
#define TOP_SPK_AMP_POS 0x4
#define TOP_SPK_AMP_NEG 0x8
#define TOP_SPK_AMP 0x10
#define GPIO_AUX_PCM_DOUT 43
#define GPIO_AUX_PCM_DIN 44
#define GPIO_AUX_PCM_SYNC 45
#define GPIO_AUX_PCM_CLK 46
#define TABLA_EXT_CLK_RATE 12288000
#define TABLA_MBHC_DEF_BUTTONS 8
#define TABLA_MBHC_DEF_RLOADS 5
#define JACK_DETECT_GPIO 38
#define APQ_I2S_SLAVE_CONFIG 0
/* MCLK selection GPIOs from PMIC */
#define PM_GPIO_MCLK_MDM 10
#define PM_GPIO_MCLK_APQ 41
/* SPKR I2S Configuration */
#define GPIO_SPKR_I2S_MCLK 39
#define GPIO_SPKR_I2S_SCK 40
#define GPIO_SPKR_I2S_DOUT 41
#define GPIO_SPKR_I2S_WS 42
/* MIC I2S Configuration */
#define GPIO_MIC_I2S_MCLK 34
#define GPIO_MIC_I2S_SCK 35
#define GPIO_MIC_I2S_WS 36
#define GPIO_MIC_I2S_DIN0 37
#define GPIO_MIC_I2S_DIN1 38
/* MI2S Configuration */
#define GPIO_MI2S_WS 27
#define GPIO_MI2S_SCK 28
#define GPIO_MI2S_SD3 29
#define GPIO_MI2S_SD2 30
#define GPIO_MI2S_SD1 31
#define GPIO_MI2S_SD0 32
#define GPIO_MI2S_MCLK 33
struct request_gpio {
unsigned gpio_no;
char *gpio_name;
};
/* SD0 as RX and SD3 as TX. SD1 and SD2 are unused */
static struct request_gpio mi2s_gpio[] = {
{
.gpio_no = GPIO_MI2S_WS,
.gpio_name = "MI2S_WS",
},
{
.gpio_no = GPIO_MI2S_SCK,
.gpio_name = "MI2S_SCK",
},
{
.gpio_no = GPIO_MI2S_SD3,
.gpio_name = "MI2S_SD3",
},
{
.gpio_no = GPIO_MI2S_SD0,
.gpio_name = "MI2S_SD0",
},
{
.gpio_no = GPIO_MI2S_MCLK,
.gpio_name = "MI2S_MCLK",
},
};
/* I2S RX is slave so MCLK is not needed */
static struct request_gpio spkr_i2s_gpio[] = {
{
.gpio_no = GPIO_SPKR_I2S_WS,
.gpio_name = "SPKR_I2S_WS",
},
{
.gpio_no = GPIO_SPKR_I2S_SCK,
.gpio_name = "SPKR_I2S_SCK",
},
{
.gpio_no = GPIO_SPKR_I2S_DOUT,
.gpio_name = "SPKR_I2S_DOUT",
},
};
/* I2S TX is slave so MCLK is not needed. DIN1 is not used */
static struct request_gpio mic_i2s_gpio[] = {
{
.gpio_no = GPIO_MIC_I2S_WS,
.gpio_name = "MIC_I2S_WS",
},
{
.gpio_no = GPIO_MIC_I2S_SCK,
.gpio_name = "MIC_I2S_SCK",
},
{
.gpio_no = GPIO_MIC_I2S_DIN0,
.gpio_name = "MIC_I2S_DIN",
},
};
/* Shared channel numbers for Slimbus ports that connect APQ to MDM. */
enum {
SLIM_1_RX_1 = 145, /* BT-SCO and USB TX */
SLIM_1_TX_1 = 146, /* BT-SCO and USB RX */
SLIM_3_RX_1 = 151, /* External echo-cancellation ref */
SLIM_3_RX_2 = 152, /* External echo-cancellation ref */
SLIM_3_TX_1 = 153, /* HDMI RX */
SLIM_3_TX_2 = 154, /* HDMI RX */
SLIM_4_TX_1 = 148, /* In-call recording RX */
SLIM_4_TX_2 = 149, /* In-call recording RX */
SLIM_4_RX_1 = 150, /* In-call music delivery TX */
};
enum {
INCALL_REC_MONO,
INCALL_REC_STEREO,
};
#if APQ_I2S_SLAVE_CONFIG
static u32 mdm_mclk_gpio = PM8921_GPIO_PM_TO_SYS(PM_GPIO_MCLK_MDM);
static u32 apq_mclk_gpio = PM8921_GPIO_PM_TO_SYS(PM_GPIO_MCLK_APQ);
#endif
static u32 top_spk_pamp_gpio = PM8921_GPIO_PM_TO_SYS(18);
static u32 bottom_spk_pamp_gpio = PM8921_GPIO_PM_TO_SYS(19);
static int msm_spk_control;
static int msm_ext_bottom_spk_pamp;
static int msm_ext_top_spk_pamp;
static int msm_slim_0_rx_ch = 1;
static int msm_slim_0_tx_ch = 1;
static int msm_slim_3_rx_ch = 1;
static struct clk *i2s_rx_bit_clk;
static struct clk *i2s_tx_bit_clk;
#if (!APQ_I2S_SLAVE_CONFIG)
static struct clk *mi2s_osr_clk;
#endif
static struct clk *mi2s_bit_clk;
static int msm_i2s_rx_ch = 1;
static int msm_i2s_tx_ch = 1;
static int msm_mi2s_rx_ch = 1;
static int msm_mi2s_tx_ch = 1;
/* MI2S TX and RX share the same control block*/
static atomic_t mi2s_rsc_ref;
static int msm_btsco_rate = BTSCO_RATE_8KHZ;
static int msm_btsco_ch = 1;
static int rec_mode = INCALL_REC_MONO;
static struct clk *codec_clk;
static int clk_users;
static struct snd_soc_jack hs_jack;
static struct snd_soc_jack button_jack;
static int apq8064_i2s_hs_detect_use_gpio = -1;
module_param(apq8064_i2s_hs_detect_use_gpio, int, 0444);
MODULE_PARM_DESC(apq8064_i2s_hs_detect_use_gpio, "Use GPIO for headset detection");
static bool apq8064_i2s_hs_detect_use_firmware;
module_param(apq8064_i2s_hs_detect_use_firmware, bool, 0444);
MODULE_PARM_DESC(apq8064_i2s_hs_detect_use_firmware,
"Use firmware for headset detection");
static int msm_enable_codec_ext_clk(struct snd_soc_codec *codec, int enable,
bool dapm);
static struct tabla_mbhc_config mbhc_cfg = {
.headset_jack = &hs_jack,
.button_jack = &button_jack,
.read_fw_bin = false,
.calibration = NULL,
.micbias = TABLA_MICBIAS2,
.mclk_cb_fn = msm_enable_codec_ext_clk,
.mclk_rate = TABLA_EXT_CLK_RATE,
.gpio = 0,
.gpio_irq = 0,
.gpio_level_insert = 1,
};
static struct mutex cdc_mclk_mutex;
static void msm_enable_ext_spk_amp_gpio(u32 spk_amp_gpio)
{
int ret = 0;
struct pm_gpio param = {
.direction = PM_GPIO_DIR_OUT,
.output_buffer = PM_GPIO_OUT_BUF_CMOS,
.output_value = 1,
.pull = PM_GPIO_PULL_NO,
.vin_sel = PM_GPIO_VIN_S4,
.out_strength = PM_GPIO_STRENGTH_MED,
.
function = PM_GPIO_FUNC_NORMAL,
};
if (spk_amp_gpio == bottom_spk_pamp_gpio) {
ret = gpio_request(bottom_spk_pamp_gpio, "BOTTOM_SPK_AMP");
if (ret) {
pr_err("%s: Error requesting BOTTOM SPK AMP GPIO %u\n",
__func__, bottom_spk_pamp_gpio);
return;
}
ret = pm8xxx_gpio_config(bottom_spk_pamp_gpio, ¶m);
if (ret)
pr_err("%s: Failed to configure Bottom Spk Ampl gpio %u\n",
__func__, bottom_spk_pamp_gpio);
else {
pr_debug("%s: enable Bottom spkr amp gpio\n", __func__);
gpio_direction_output(bottom_spk_pamp_gpio, 1);
}
} else if (spk_amp_gpio == top_spk_pamp_gpio) {
ret = gpio_request(top_spk_pamp_gpio, "TOP_SPK_AMP");
if (ret) {
pr_err("%s: Error requesting GPIO %d\n", __func__,
top_spk_pamp_gpio);
return;
}
ret = pm8xxx_gpio_config(top_spk_pamp_gpio, ¶m);
if (ret)
pr_err("%s: Failed to configure Top Spk Ampl gpio %u\n",
__func__, top_spk_pamp_gpio);
else {
pr_debug("%s: enable Top spkr amp gpio\n", __func__);
gpio_direction_output(top_spk_pamp_gpio, 1);
}
} else {
pr_err("%s: ERROR : Invalid External Speaker Ampl GPIO gpio = %u\n",
__func__, spk_amp_gpio);
return;
}
}
static void msm_ext_spk_power_amp_on(u32 spk)
{
if (spk & (BOTTOM_SPK_AMP_POS | BOTTOM_SPK_AMP_NEG)) {
if ((msm_ext_bottom_spk_pamp & BOTTOM_SPK_AMP_POS) &&
(msm_ext_bottom_spk_pamp & BOTTOM_SPK_AMP_NEG)) {
pr_debug("%s() External Bottom Speaker Ampl already turned on\n"
"spk = 0x%08x\n", __func__, spk);
return;
}
msm_ext_bottom_spk_pamp |= spk;
if ((msm_ext_bottom_spk_pamp & BOTTOM_SPK_AMP_POS) &&
(msm_ext_bottom_spk_pamp & BOTTOM_SPK_AMP_NEG)) {
msm_enable_ext_spk_amp_gpio(bottom_spk_pamp_gpio);
pr_debug("%s: slepping 4 ms after turning on external\n"
"Bottom Speaker Ampl\n", __func__);
usleep_range(4000, 4000);
}
} else if (spk & (TOP_SPK_AMP_POS | TOP_SPK_AMP_NEG | TOP_SPK_AMP)) {
pr_debug("%s():top_spk_amp_state = 0x%x spk_event = 0x%x\n",
__func__, msm_ext_top_spk_pamp, spk);
if (((msm_ext_top_spk_pamp & TOP_SPK_AMP_POS) &&
(msm_ext_top_spk_pamp & TOP_SPK_AMP_NEG)) ||
(msm_ext_top_spk_pamp & TOP_SPK_AMP)) {
pr_debug("%s() External Top Speaker Ampl already turned on\n"
"spk = 0x%08x\n", __func__, spk);
return;
}
msm_ext_top_spk_pamp |= spk;
if (((msm_ext_top_spk_pamp & TOP_SPK_AMP_POS) &&
(msm_ext_top_spk_pamp & TOP_SPK_AMP_NEG)) ||
(msm_ext_top_spk_pamp & TOP_SPK_AMP)) {
msm_enable_ext_spk_amp_gpio(top_spk_pamp_gpio);
pr_debug("%s: sleeping 4 ms after turning on\n"
"external Top Speaker Ampl\n", __func__);
usleep_range(4000, 4000);
}
} else {
pr_err("%s: ERROR : Invalid External Speaker Ampl. spk = 0x%08x\n",
__func__, spk);
return;
}
}
static void msm_ext_spk_power_amp_off(u32 spk)
{
if (spk & (BOTTOM_SPK_AMP_POS | BOTTOM_SPK_AMP_NEG)) {
if (!msm_ext_bottom_spk_pamp)
return;
gpio_direction_output(bottom_spk_pamp_gpio, 0);
gpio_free(bottom_spk_pamp_gpio);
msm_ext_bottom_spk_pamp = 0;
pr_debug("%s: sleeping 4 ms after turning off external Bottom\n"
"Speaker Ampl\n", __func__);
usleep_range(4000, 4000);
} else if (spk & (TOP_SPK_AMP_POS | TOP_SPK_AMP_NEG | TOP_SPK_AMP)) {
pr_debug("%s: top_spk_amp_state = 0x%x spk_event = 0x%x\n",
__func__, msm_ext_top_spk_pamp, spk);
if (!msm_ext_top_spk_pamp)
return;
if ((spk & TOP_SPK_AMP_POS) || (spk & TOP_SPK_AMP_NEG)) {
msm_ext_top_spk_pamp &= (~(TOP_SPK_AMP_POS |
TOP_SPK_AMP_NEG));
} else if (spk & TOP_SPK_AMP) {
msm_ext_top_spk_pamp &= ~TOP_SPK_AMP;
}
if (msm_ext_top_spk_pamp)
return;
gpio_direction_output(top_spk_pamp_gpio, 0);
gpio_free(top_spk_pamp_gpio);
msm_ext_top_spk_pamp = 0;
pr_debug("%s: sleeping 4 ms after ext Top Spek Ampl is off\n",
__func__);
usleep_range(4000, 4000);
} else {
pr_err("%s: ERROR : Invalid Ext Spk Ampl. spk = 0x%08x\n",
__func__, spk);
return;
}
}
static void msm_ext_control(struct snd_soc_codec *codec)
{
struct snd_soc_dapm_context *dapm = &codec->dapm;
pr_debug("%s: msm_spk_control = %d", __func__, msm_spk_control);
if (msm_spk_control == MSM8064_SPK_ON) {
snd_soc_dapm_enable_pin(dapm, "Ext Spk Bottom Pos");
snd_soc_dapm_enable_pin(dapm, "Ext Spk Bottom Neg");
snd_soc_dapm_enable_pin(dapm, "Ext Spk Top Pos");
snd_soc_dapm_enable_pin(dapm, "Ext Spk Top Neg");
} else {
snd_soc_dapm_disable_pin(dapm, "Ext Spk Bottom Pos");
snd_soc_dapm_disable_pin(dapm, "Ext Spk Bottom Neg");
snd_soc_dapm_disable_pin(dapm, "Ext Spk Top Pos");
snd_soc_dapm_disable_pin(dapm, "Ext Spk Top Neg");
}
snd_soc_dapm_sync(dapm);
}
static int msm_get_spk(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm_spk_control = %d", __func__, msm_spk_control);
ucontrol->value.integer.value[0] = msm_spk_control;
return 0;
}
static int msm_set_spk(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
pr_debug("%s()\n", __func__);
if (msm_spk_control == ucontrol->value.integer.value[0])
return 0;
msm_spk_control = ucontrol->value.integer.value[0];
msm_ext_control(codec);
return 1;
}
static int msm_spkramp_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *k, int event)
{
pr_debug("%s() %x\n", __func__, SND_SOC_DAPM_EVENT_ON(event));
if (SND_SOC_DAPM_EVENT_ON(event)) {
if (!strncmp(w->name, "Ext Spk Bottom Pos", 18))
msm_ext_spk_power_amp_on(BOTTOM_SPK_AMP_POS);
else if (!strncmp(w->name, "Ext Spk Bottom Neg", 18))
msm_ext_spk_power_amp_on(BOTTOM_SPK_AMP_NEG);
else if (!strncmp(w->name, "Ext Spk Top Pos", 15))
msm_ext_spk_power_amp_on(TOP_SPK_AMP_POS);
else if (!strncmp(w->name, "Ext Spk Top Neg", 15))
msm_ext_spk_power_amp_on(TOP_SPK_AMP_NEG);
else if (!strncmp(w->name, "Ext Spk Top", 12))
msm_ext_spk_power_amp_on(TOP_SPK_AMP);
else {
pr_err("%s() Invalid Speaker Widget = %s\n",
__func__, w->name);
return -EINVAL;
}
} else {
if (!strncmp(w->name, "Ext Spk Bottom Pos", 18))
msm_ext_spk_power_amp_off(BOTTOM_SPK_AMP_POS);
else if (!strncmp(w->name, "Ext Spk Bottom Neg", 18))
msm_ext_spk_power_amp_off(BOTTOM_SPK_AMP_NEG);
else if (!strncmp(w->name, "Ext Spk Top Pos", 15))
msm_ext_spk_power_amp_off(TOP_SPK_AMP_POS);
else if (!strncmp(w->name, "Ext Spk Top Neg", 15))
msm_ext_spk_power_amp_off(TOP_SPK_AMP_NEG);
else if (!strncmp(w->name, "Ext Spk Top", 12))
msm_ext_spk_power_amp_off(TOP_SPK_AMP);
else {
pr_err("%s() Invalid Speaker Widget = %s\n",
__func__, w->name);
return -EINVAL;
}
}
return 0;
}
static int msm_enable_codec_ext_clk(struct snd_soc_codec *codec, int enable,
bool dapm)
{
int r = 0;
pr_debug("%s: enable = %d\n", __func__, enable);
mutex_lock(&cdc_mclk_mutex);
if (enable) {
clk_users++;
pr_debug("%s: clk_users = %d\n", __func__, clk_users);
if (clk_users == 1) {
if (codec_clk) {
/*
* For MBHC calc, the MCLK is from APQ side
* so APQ has control of the MCLK at this point
*/
clk_set_rate(codec_clk, TABLA_EXT_CLK_RATE);
clk_prepare_enable(codec_clk);
tabla_mclk_enable(codec, 1, dapm);
} else {
pr_err("%s: Error setting Tabla MCLK\n",
__func__);
clk_users--;
r = -EINVAL;
}
}
} else {
if (clk_users > 0) {
clk_users--;
pr_debug("%s: clk_users = %d\n", __func__, clk_users);
if (clk_users == 0) {
pr_debug("%s: disabling MCLK. clk_users = %d\n",
__func__, clk_users);
tabla_mclk_enable(codec, 0, dapm);
/*
* For MBHC calc, the MCLK is from APQ side
* so APQ has control of the MCLK at this point
*/
clk_disable_unprepare(codec_clk);
}
} else {
pr_err("%s: Error releasing Tabla MCLK\n", __func__);
r = -EINVAL;
}
}
mutex_unlock(&cdc_mclk_mutex);
return r;
}
static int msm_mclk_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
clk_users++;
pr_debug("%s: clk_users = %d\n", __func__, clk_users);
if (clk_users != 1)
return 0;
if (codec_clk) {
/*
* Since the MCLK is from MDM side so APQ side
* has no control of the MCLK at this point
*/
/*clk_set_rate(codec_clk, TABLA_EXT_CLK_RATE);
clk_prepare_enable(codec_clk); */
tabla_mclk_enable(w->codec, 1, true);
} else {
pr_err("%s: Error setting Tabla MCLK\n", __func__);
clk_users--;
return -EINVAL;
}
break;
case SND_SOC_DAPM_POST_PMD:
pr_debug("%s: clk_users = %d\n", __func__, clk_users);
if (clk_users == 0)
return 0;
clk_users--;
if (!clk_users) {
pr_debug("%s: disabling MCLK. clk_users = %d\n",
__func__, clk_users);
tabla_mclk_enable(w->codec, 0, true);
/*
* Since the MCLK is from MDM side so APQ side
* has no control of the MCLK at this point
*/
/* clk_disable_unprepare(codec_clk); */
}
break;
}
return 0;
}
static const struct snd_soc_dapm_widget apq8064_dapm_widgets[] = {
SND_SOC_DAPM_SUPPLY("MCLK", SND_SOC_NOPM, 0, 0,
msm_mclk_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SPK("Ext Spk Bottom Pos", msm_spkramp_event),
SND_SOC_DAPM_SPK("Ext Spk Bottom Neg", msm_spkramp_event),
SND_SOC_DAPM_SPK("Ext Spk Top Pos", msm_spkramp_event),
SND_SOC_DAPM_SPK("Ext Spk Top Neg", msm_spkramp_event),
SND_SOC_DAPM_SPK("Ext Spk Top", msm_spkramp_event),
/************ Analog MICs ************/
/**
* Analog mic7 (Front Top) on Liquid.
* Used as Handset mic on CDP.
*/
SND_SOC_DAPM_MIC("Analog mic7", NULL),
SND_SOC_DAPM_MIC("Headset Mic", NULL),
SND_SOC_DAPM_MIC("ANCRight Headset Mic", NULL),
SND_SOC_DAPM_MIC("ANCLeft Headset Mic", NULL),
/*********** Digital Mics ***************/
SND_SOC_DAPM_MIC("Digital Mic1", NULL),
SND_SOC_DAPM_MIC("Digital Mic2", NULL),
SND_SOC_DAPM_MIC("Digital Mic3", NULL),
SND_SOC_DAPM_MIC("Digital Mic4", NULL),
SND_SOC_DAPM_MIC("Digital Mic5", NULL),
SND_SOC_DAPM_MIC("Digital Mic6", NULL),
};
static const struct snd_soc_dapm_route apq8064_common_audio_map[] = {
{"RX_BIAS", NULL, "MCLK"},
{"LDO_H", NULL, "MCLK"},
{"HEADPHONE", NULL, "LDO_H"},
/* Speaker path */
{"Ext Spk Bottom Pos", NULL, "LINEOUT1"},
{"Ext Spk Bottom Neg", NULL, "LINEOUT3"},
{"Ext Spk Top Pos", NULL, "LINEOUT2"},
{"Ext Spk Top Neg", NULL, "LINEOUT4"},
{"Ext Spk Top", NULL, "LINEOUT5"},
/************ Analog MIC Paths ************/
/* Headset Mic */
{"AMIC2", NULL, "MIC BIAS2 External"},
{"MIC BIAS2 External", NULL, "Headset Mic"},
/* Headset ANC microphones */
{"AMIC3", NULL, "MIC BIAS3 Internal1"},
{"MIC BIAS3 Internal1", NULL, "ANCRight Headset Mic"},
{"AMIC4", NULL, "MIC BIAS1 Internal2"},
{"MIC BIAS1 Internal2", NULL, "ANCLeft Headset Mic"},
};
static const struct snd_soc_dapm_route apq8064_mtp_audio_map[] = {
/************ Digital MIC Paths ************/
/*
* Digital Mic1 (Front bottom Left) on MTP.
* Conncted to DMIC1 Input on Tabla codec.
*/
{"DMIC1", NULL, "MIC BIAS1 External"},
{"MIC BIAS1 External", NULL, "Digital Mic1"},
/**
* Digital Mic2 (Front bottom right) on MTP.
* Conncted to DMIC2 Input on Tabla codec.
*/
{"DMIC2", NULL, "MIC BIAS1 External"},
{"MIC BIAS1 External", NULL, "Digital Mic2"},
/**
* Digital Mic3 (Back bottom) on MTP.
* Conncted to DMIC3 Input on Tabla codec.
*/
{"DMIC3", NULL, "MIC BIAS3 External"},
{"MIC BIAS3 External", NULL, "Digital Mic3"},
/**
* Digital Mic4 (Back top) on MTP.
* Conncted to DMIC4 Input on Tabla codec.
*/
{"DMIC4", NULL, "MIC BIAS3 External"},
{"MIC BIAS3 External", NULL, "Digital Mic4"},
/**
* Digital Mic5 (Top front Mic) on MTP.
* Conncted to DMIC6 Input on Tabla codec.
*/
{"DMIC6", NULL, "MIC BIAS4 External"},
{"MIC BIAS4 External", NULL, "Digital Mic5"},
};
static const struct snd_soc_dapm_route apq8064_liquid_cdp_audio_map[] = {
/************ Analog MIC Paths ************/
/**
* Analog mic7 (Front Top Mic) on Liquid.
* Used as Handset mic on CDP.
* Not there on MTP.
*/
{"AMIC1", NULL, "MIC BIAS1 External"},
{"MIC BIAS1 External", NULL, "Analog mic7"},
/************ Digital MIC Paths ************/
/**
* The digital Mic routes are setup considering
* Liquid as default device.
*/
/**
* Digital Mic1 (Front bottom left corner) on Liquid.
* Digital Mic2 (Front bottom right) on MTP.
* Digital Mic GM1 on CDP mainboard.
* Conncted to DMIC2 Input on Tabla codec.
*/
{"DMIC2", NULL, "MIC BIAS1 External"},
{"MIC BIAS1 External", NULL, "Digital Mic1"},
/**
* Digital Mic2 (Front left side) on Liquid.
* Digital Mic GM2 on CDP mainboard.
* Not there on MTP.
* Conncted to DMIC3 Input on Tabla codec.
*/
{"DMIC3", NULL, "MIC BIAS3 External"},
{"MIC BIAS3 External", NULL, "Digital Mic2"},
/**
* Digital Mic3. Front bottom left of middle on Liquid.
* Digital Mic5 (Top front Mic) on MTP.
* Digital Mic GM5 on CDP mainboard.
* Conncted to DMIC6 Input on Tabla codec.
*/
{"DMIC6", NULL, "MIC BIAS4 External"},
{"MIC BIAS4 External", NULL, "Digital Mic3"},
/**
* Digital Mic4. Back bottom on Liquid.
* Digital Mic GM3 on CDP mainboard.
* Top Front Mic on MTP.
* Conncted to DMIC5 Input on Tabla codec.
*/
{"DMIC5", NULL, "MIC BIAS4 External"},
{"MIC BIAS4 External", NULL, "Digital Mic4"},
/**
* Digital Mic5. Front bottom right of middle on Liquid.
* Digital Mic GM6 on CDP mainboard.
* Not there on MTP.
* Conncted to DMIC4 Input on Tabla codec.
*/
{"DMIC4", NULL, "MIC BIAS3 External"},
{"MIC BIAS3 External", NULL, "Digital Mic5"},
/* Digital Mic6 (Front bottom right corner) on Liquid.
* Digital Mic1 (Front bottom Left) on MTP.
* Digital Mic GM4 on CDP.
* Conncted to DMIC1 Input on Tabla codec.
*/
{"DMIC1", NULL, "MIC BIAS1 External"},
{"MIC BIAS1 External", NULL, "Digital Mic6"},
};
static const char * const spk_function[] = {"Off", "On"};
static const char * const rx_ch_text[] = {"One", "Two"};
static const char * const tx_ch_text[] = {"One", "Two", "Three", "Four"};
static const struct soc_enum msm_enum[] = {
SOC_ENUM_SINGLE_EXT(2, spk_function),
SOC_ENUM_SINGLE_EXT(2, rx_ch_text),
SOC_ENUM_SINGLE_EXT(4, tx_ch_text),
};
static const char * const btsco_rate_text[] = {"8000", "16000"};
static const struct soc_enum msm_btsco_enum[] = {
SOC_ENUM_SINGLE_EXT(2, btsco_rate_text),
};
static int msm_slim_0_rx_ch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm_slim_0_rx_ch = %d\n", __func__,
msm_slim_0_rx_ch);
ucontrol->value.integer.value[0] = msm_slim_0_rx_ch - 1;
return 0;
}
static int msm_slim_0_rx_ch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
msm_slim_0_rx_ch = ucontrol->value.integer.value[0] + 1;
pr_debug("%s: msm_slim_0_rx_ch = %d\n", __func__,
msm_slim_0_rx_ch);
return 1;
}
static int msm_slim_0_tx_ch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm_slim_0_tx_ch = %d\n", __func__,
msm_slim_0_tx_ch);
ucontrol->value.integer.value[0] = msm_slim_0_tx_ch - 1;
return 0;
}
static int msm_slim_0_tx_ch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
msm_slim_0_tx_ch = ucontrol->value.integer.value[0] + 1;
pr_debug("%s: msm_slim_0_tx_ch = %d\n", __func__,
msm_slim_0_tx_ch);
return 1;
}
static int msm_slim_3_rx_ch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm_slim_3_rx_ch = %d\n", __func__,
msm_slim_3_rx_ch);
ucontrol->value.integer.value[0] = msm_slim_3_rx_ch - 1;
return 0;
}
static int msm_slim_3_rx_ch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
msm_slim_3_rx_ch = ucontrol->value.integer.value[0] + 1;
pr_debug("%s: msm_slim_3_rx_ch = %d\n", __func__,
msm_slim_3_rx_ch);
return 1;
}
static int msm_btsco_rate_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm_btsco_rate = %d", __func__,
msm_btsco_rate);
ucontrol->value.integer.value[0] = msm_btsco_rate;
return 0;
}
static int msm_btsco_rate_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
switch (ucontrol->value.integer.value[0]) {
case 0:
msm_btsco_rate = BTSCO_RATE_8KHZ;
break;
case 1:
msm_btsco_rate = BTSCO_RATE_16KHZ;
break;
default:
msm_btsco_rate = BTSCO_RATE_8KHZ;
break;
}
pr_debug("%s: msm_btsco_rate = %d\n", __func__,
msm_btsco_rate);
return 0;
}
static int msm_incall_rec_mode_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] = rec_mode;
return 0;
}
static int msm_incall_rec_mode_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
rec_mode = ucontrol->value.integer.value[0];
pr_debug("%s: rec_mode:%d\n", __func__, rec_mode);
return 0;
}
static const struct snd_kcontrol_new tabla_msm_controls[] = {
SOC_ENUM_EXT("Speaker Function", msm_enum[0], msm_get_spk,
msm_set_spk),
SOC_ENUM_EXT("SLIM_0_RX Channels", msm_enum[1],
msm_slim_0_rx_ch_get, msm_slim_0_rx_ch_put),
SOC_ENUM_EXT("SLIM_0_TX Channels", msm_enum[2],
msm_slim_0_tx_ch_get, msm_slim_0_tx_ch_put),
};
static const struct snd_kcontrol_new int_btsco_rate_mixer_controls[] = {
SOC_ENUM_EXT("Internal BTSCO SampleRate", msm_btsco_enum[0],
msm_btsco_rate_get, msm_btsco_rate_put),
};
static const struct snd_kcontrol_new incall_rec_mode_mixer_controls[] = {
SOC_SINGLE_EXT("Incall Rec Mode", SND_SOC_NOPM, 0, 1, 0,
msm_incall_rec_mode_get, msm_incall_rec_mode_put),
};
static int msm_btsco_init(struct snd_soc_pcm_runtime *rtd)
{
int err = 0;
struct snd_soc_platform *platform = rtd->platform;
err = snd_soc_add_platform_controls(platform,
int_btsco_rate_mixer_controls,
ARRAY_SIZE(int_btsco_rate_mixer_controls));
if (err < 0)
return err;
return 0;
}
static const struct snd_kcontrol_new slim_3_mixer_controls[] = {
SOC_ENUM_EXT("SLIM_3_RX Channels", msm_enum[1],
msm_slim_3_rx_ch_get, msm_slim_3_rx_ch_put),
};
static int msm_slim_3_init(struct snd_soc_pcm_runtime *rtd)
{
int err = 0;
struct snd_soc_platform *platform = rtd->platform;
err = snd_soc_add_platform_controls(platform,
slim_3_mixer_controls,
ARRAY_SIZE(slim_3_mixer_controls));
if (err < 0)
return err;
return 0;
}
static int msm_incall_rec_init(struct snd_soc_pcm_runtime *rtd)
{
int err = 0;
struct snd_soc_platform *platform = rtd->platform;
err = snd_soc_add_platform_controls(platform,
incall_rec_mode_mixer_controls,
ARRAY_SIZE(incall_rec_mode_mixer_controls));
if (err < 0)
return err;
return 0;
}
static int msm_mi2s_rx_ch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm_mi2s_rx_ch = %d\n", __func__,
msm_mi2s_rx_ch);
ucontrol->value.integer.value[0] = msm_mi2s_rx_ch - 1;
return 0;
}
static int msm_mi2s_rx_ch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
msm_mi2s_rx_ch = ucontrol->value.integer.value[0] + 1;
pr_debug("%s: msm_mi2s_rx_ch = %d\n", __func__,
msm_mi2s_rx_ch);
return 1;
}
static int msm_mi2s_tx_ch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm_mi2s_tx_ch = %d\n", __func__,
msm_mi2s_tx_ch);
ucontrol->value.integer.value[0] = msm_mi2s_tx_ch - 1;
return 0;
}
static int msm_mi2s_tx_ch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
msm_mi2s_tx_ch = ucontrol->value.integer.value[0] + 1;
pr_debug("%s: msm_mi2s_tx_ch = %d\n", __func__,
msm_mi2s_tx_ch);
return 1;
}
static int msm_mi2s_get_spk(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
pr_debug("%s: msm_spk_control = %d", __func__, msm_spk_control);
ucontrol->value.integer.value[0] = msm_spk_control;
return 0;
}
static int msm_mi2s_set_spk(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
pr_debug("%s()\n", __func__);
if (msm_spk_control == ucontrol->value.integer.value[0])
return 0;
msm_spk_control = ucontrol->value.integer.value[0];
msm_ext_control(codec);
return 1;
}
static int msm_mi2s_rx_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
pr_debug("%s()\n", __func__);
rate->min = rate->max = 48000;
channels->min = channels->max = msm_mi2s_rx_ch;
return 0;
}
static int msm_mi2s_tx_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
pr_debug("%s()\n", __func__);
rate->min = rate->max = 48000;
channels->min = channels->max = msm_mi2s_tx_ch;
return 0;
}
static int msm_i2s_rx_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
pr_debug("%s()\n", __func__);
rate->min = rate->max = 48000;
channels->min = channels->max = msm_i2s_rx_ch;
return 0;
}
static int msm_i2s_tx_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
pr_debug("%s()\n", __func__);
rate->min = rate->max = 48000;
channels->min = channels->max = msm_i2s_tx_ch;
return 0;
}
static const struct snd_kcontrol_new tabla_msm_mi2s_controls[] = {
SOC_ENUM_EXT("Speaker Function", msm_enum[0], msm_mi2s_get_spk,
msm_mi2s_set_spk),
SOC_ENUM_EXT("MI2S_RX Channels", msm_enum[1],
msm_mi2s_rx_ch_get, msm_mi2s_rx_ch_put),
SOC_ENUM_EXT("MI2S_TX Channels", msm_enum[2],
msm_mi2s_tx_ch_get, msm_mi2s_tx_ch_put),
};
static int msm_mi2s_audrx_init(struct snd_soc_pcm_runtime *rtd)
{
int ret;
uint32_t revision;
struct snd_soc_codec *codec = rtd->codec;
struct snd_soc_dapm_context *dapm = &codec->dapm;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
#if APQ_I2S_SLAVE_CONFIG
struct pm_gpio param = {
.direction = PM_GPIO_DIR_OUT,
.output_buffer = PM_GPIO_OUT_BUF_CMOS,
.output_value = 1,
.pull = PM_GPIO_PULL_NO,
.vin_sel = PM_GPIO_VIN_S4,
.out_strength = PM_GPIO_STRENGTH_MED,
.function = PM_GPIO_FUNC_NORMAL,
};
#endif
pr_debug("%s(), dev_name(%s)\n", __func__, dev_name(cpu_dai->dev));
rtd->pmdown_time = 0;
ret = snd_soc_add_controls(codec, tabla_msm_mi2s_controls,
ARRAY_SIZE(tabla_msm_mi2s_controls));
if (ret < 0)
return ret;
ret = gpio_request(GPIO_MI2S_MCLK, "MI2S_MCLK");
if (ret)
pr_err("%s: Failed to request gpio %d\n", __func__,
GPIO_MI2S_MCLK);
#if APQ_I2S_SLAVE_CONFIG
/* APQ provides the mclk to codec */
ret = gpio_request(mdm_mclk_gpio, "MDM_MCLK_SWITCH");
if (ret) {
pr_err("%s: Failed to request gpio %d\n", __func__,
mdm_mclk_gpio);
return ret;
}
ret = pm8xxx_gpio_config(mdm_mclk_gpio, ¶m);
if (ret)
pr_err("%s: Failed to configure gpio %d\n", __func__,
mdm_mclk_gpio);
else
gpio_direction_output(mdm_mclk_gpio, 0);
ret = gpio_request(apq_mclk_gpio, "APQ_MCLK_SWITCH");
if (ret) {
pr_err("%s: Failed to request gpio %d\n", __func__,
apq_mclk_gpio);
return ret;
}
ret = pm8xxx_gpio_config(apq_mclk_gpio, ¶m);
if (ret)
pr_err("%s: Failed to configure gpio %d\n", __func__,
apq_mclk_gpio);
else
gpio_direction_output(apq_mclk_gpio, 1);
pr_debug("%s: Config mdm_mclk_gpio and apq_mclk_gpio\n",
__func__);
#else
pr_debug("%s: Not config mdm_mclk_gpio and apq_mclk_gpio\n",
__func__);
#endif
snd_soc_dapm_new_controls(dapm, apq8064_dapm_widgets,
ARRAY_SIZE(apq8064_dapm_widgets));
snd_soc_dapm_add_routes(dapm, apq8064_common_audio_map,
ARRAY_SIZE(apq8064_common_audio_map));
if (machine_is_apq8064_mtp()) {
snd_soc_dapm_add_routes(dapm, apq8064_mtp_audio_map,
ARRAY_SIZE(apq8064_mtp_audio_map));
} else {
snd_soc_dapm_add_routes(dapm, apq8064_liquid_cdp_audio_map,
ARRAY_SIZE(apq8064_liquid_cdp_audio_map));
}
snd_soc_dapm_enable_pin(dapm, "Ext Spk Bottom Pos");
snd_soc_dapm_enable_pin(dapm, "Ext Spk Bottom Neg");
snd_soc_dapm_enable_pin(dapm, "Ext Spk Top Pos");
snd_soc_dapm_enable_pin(dapm, "Ext Spk Top Neg");
snd_soc_dapm_sync(dapm);
ret = snd_soc_jack_new(codec, "Headset Jack",
(SND_JACK_HEADSET | SND_JACK_OC_HPHL |
SND_JACK_OC_HPHR), &hs_jack);
if (ret) {
pr_err("failed to create new jack\n");
return ret;
}
ret = snd_soc_jack_new(codec, "Button Jack",
TABLA_JACK_BUTTON_MASK, &button_jack);
if (ret) {
pr_err("failed to create new jack\n");
return ret;
}
/* Get the MCLK from MI2S block for MBHC calibration */
codec_clk = clk_get(cpu_dai->dev, "osr_clk");
pr_debug("%s: Device name is %s\n", __func__, dev_name(cpu_dai->dev));
/* APQ8064 Rev 1.1 CDP and Liquid have mechanical switch */
revision = socinfo_get_version();
if (apq8064_i2s_hs_detect_use_gpio != -1) {
if (apq8064_i2s_hs_detect_use_gpio == 1)
pr_debug("%s: MBHC mechanical is enabled by request\n",
__func__);
else if (apq8064_i2s_hs_detect_use_gpio == 0)
pr_debug("%s: MBHC mechanical is disabled by request\n",
__func__);
else
pr_warn("%s: Invalid hs_detect_use_gpio %d\n", __func__,
apq8064_i2s_hs_detect_use_gpio);
} else if (SOCINFO_VERSION_MAJOR(revision) == 0) {
pr_warn("%s: Unknown HW revision detected %d.%d\n", __func__,
SOCINFO_VERSION_MAJOR(revision),
SOCINFO_VERSION_MINOR(revision));
} else if ((SOCINFO_VERSION_MAJOR(revision) == 1 &&
SOCINFO_VERSION_MINOR(revision) >= 1 &&
(machine_is_apq8064_cdp() ||
machine_is_apq8064_liquid())) ||
SOCINFO_VERSION_MAJOR(revision) > 1) {
pr_debug("%s: MBHC mechanical switch available APQ8064 detected\n",
__func__);
apq8064_i2s_hs_detect_use_gpio = 1;
}
if (apq8064_i2s_hs_detect_use_gpio == 1) {
pr_debug("%s: Using MBHC mechanical switch\n", __func__);
mbhc_cfg.gpio = JACK_DETECT_GPIO;
mbhc_cfg.gpio_irq = gpio_to_irq(JACK_DETECT_GPIO);
ret = gpio_request(mbhc_cfg.gpio, "MBHC_HS_DETECT");
if (ret < 0) {
pr_err("%s: gpio_request %d failed %d\n", __func__,
mbhc_cfg.gpio, ret);
return ret;
}
gpio_direction_input(JACK_DETECT_GPIO);
} else
pr_debug("%s: Not using MBHC mechanical switch\n", __func__);
mbhc_cfg.read_fw_bin = apq8064_i2s_hs_detect_use_firmware;
ret = tabla_hs_detect(codec, &mbhc_cfg);
#if APQ_I2S_SLAVE_CONFIG
/* MDM provides the mclk to codec */
gpio_direction_output(apq_mclk_gpio, 0);
gpio_direction_output(mdm_mclk_gpio, 1);
pr_debug("%s: Should not running here if no clock switch\n", __func__);
#endif
/* Should we add code to put back codec clock?*/
gpio_free(GPIO_MI2S_MCLK);
pr_debug("%s: Free MCLK GPIO\n", __func__);
return ret;
}
static int msm_mi2s_free_gpios(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(mi2s_gpio); i++)
gpio_free(mi2s_gpio[i].gpio_no);
return 0;
}
static void msm_mi2s_shutdown(struct snd_pcm_substream *substream)
{
if (atomic_dec_return(&mi2s_rsc_ref) == 0) {
pr_debug("%s: free mi2s resources\n", __func__);
if (mi2s_bit_clk) {
clk_disable_unprepare(mi2s_bit_clk);
clk_put(mi2s_bit_clk);
mi2s_bit_clk = NULL;
}
#if (!APQ_I2S_SLAVE_CONFIG)
if (mi2s_osr_clk) {
clk_disable_unprepare(mi2s_osr_clk);
clk_put(mi2s_osr_clk);
mi2s_osr_clk = NULL;
}
#endif
msm_mi2s_free_gpios();
}
}
static int msm_configure_mi2s_gpio(void)
{
int rtn;
int i;
int j;
for (i = 0; i < ARRAY_SIZE(mi2s_gpio); i++) {
rtn = gpio_request(mi2s_gpio[i].gpio_no,
mi2s_gpio[i].gpio_name);
pr_debug("%s: gpio = %d, gpio name = %s, rtn = %d\n",
__func__,
mi2s_gpio[i].gpio_no,
mi2s_gpio[i].gpio_name,
rtn);
if (rtn) {
pr_err("%s: Failed to request gpio %d\n",
__func__,
mi2s_gpio[i].gpio_no);
for (j = i; j >= 0; j--)
gpio_free(mi2s_gpio[j].gpio_no);
goto err;
}
}
err:
return rtn;
}
static int msm_mi2s_startup(struct snd_pcm_substream *substream)
{
int ret = 0;
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
pr_debug("%s: dai name %s %p\n", __func__, cpu_dai->name, cpu_dai->dev);
if (atomic_inc_return(&mi2s_rsc_ref) == 1) {
pr_debug("%s: acquire mi2s resources\n", __func__);
msm_configure_mi2s_gpio();
#if APQ_I2S_SLAVE_CONFIG
pr_debug("%s: APQ is MI2S slave\n", __func__);
mi2s_bit_clk = clk_get(cpu_dai->dev, "bit_clk");
if (IS_ERR(mi2s_bit_clk))
return PTR_ERR(mi2s_bit_clk);
clk_set_rate(mi2s_bit_clk, 0);
ret = clk_prepare_enable(mi2s_bit_clk);
if (IS_ERR_VALUE(ret)) {
pr_err("Unable to enable mi2s_bit_clk\n");
clk_put(mi2s_bit_clk);
return ret;
}
ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_CBM_CFM);
if (IS_ERR_VALUE(ret))
pr_err("set format for CPU dai failed\n");
#else
pr_debug("%s: APQ is MI2S master\n", __func__);
mi2s_osr_clk = clk_get(cpu_dai->dev, "osr_clk");
if (IS_ERR(mi2s_osr_clk))
return PTR_ERR(mi2s_osr_clk);
clk_set_rate(mi2s_osr_clk, TABLA_EXT_CLK_RATE);
ret = clk_prepare_enable(mi2s_osr_clk);
if (IS_ERR_VALUE(ret)) {
pr_err("Unable to enable mi2s_osr_clk\n");
clk_put(mi2s_osr_clk);
return ret;
}
mi2s_bit_clk = clk_get(cpu_dai->dev, "bit_clk");
if (IS_ERR(mi2s_bit_clk)) {
pr_err("Unable to get mi2s_bit_clk\n");
clk_disable_unprepare(mi2s_osr_clk);
clk_put(mi2s_osr_clk);
return PTR_ERR(mi2s_bit_clk);
}
clk_set_rate(mi2s_bit_clk, 8);
ret = clk_prepare_enable(mi2s_bit_clk);
if (IS_ERR_VALUE(ret)) {
pr_err("Unable to enable mi2s_bit_clk\n");
clk_disable_unprepare(mi2s_osr_clk);
clk_put(mi2s_osr_clk);
clk_put(mi2s_bit_clk);
return ret;
}
ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_CBS_CFS);
if (IS_ERR_VALUE(ret))
pr_err("set format for CPU dai failed\n");
#endif
}
return ret;
}
static int msm_i2s_rx_free_gpios(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(spkr_i2s_gpio); i++)
gpio_free(spkr_i2s_gpio[i].gpio_no);
return 0;
}
static int msm_i2s_tx_free_gpios(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(mic_i2s_gpio); i++)
gpio_free(mic_i2s_gpio[i].gpio_no);
return 0;
}
static void msm_i2s_shutdown(struct snd_pcm_substream *substream)
{
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
pr_debug("%s: free i2s rx resources\n", __func__);
if (i2s_rx_bit_clk) {
clk_disable_unprepare(i2s_rx_bit_clk);
clk_put(i2s_rx_bit_clk);
i2s_rx_bit_clk = NULL;
}
msm_i2s_rx_free_gpios();
} else if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) {
pr_debug("%s: free i2s tx resources\n", __func__);
if (i2s_tx_bit_clk) {
clk_disable_unprepare(i2s_tx_bit_clk);
clk_put(i2s_tx_bit_clk);
i2s_tx_bit_clk = NULL;
}
msm_i2s_tx_free_gpios();
}
}
static int msm_configure_i2s_rx_gpio(void)
{
int rtn;
int i;
int j;
for (i = 0; i < ARRAY_SIZE(spkr_i2s_gpio); i++) {
rtn = gpio_request(spkr_i2s_gpio[i].gpio_no,
spkr_i2s_gpio[i].gpio_name);
pr_debug("%s: gpio = %d, gpio name = %s, rtn = %d\n",
__func__,
spkr_i2s_gpio[i].gpio_no,
spkr_i2s_gpio[i].gpio_name,
rtn);
if (rtn) {
pr_err("%s: Failed to request gpio %d\n",
__func__,
spkr_i2s_gpio[i].gpio_no);
for (j = i; j >= 0; j--)
gpio_free(spkr_i2s_gpio[j].gpio_no);
goto err;
}
}
err:
return rtn;
}
static int msm_configure_i2s_tx_gpio(void)
{
int rtn;
int i;
int j;
for (i = 0; i < ARRAY_SIZE(mic_i2s_gpio); i++) {
rtn = gpio_request(mic_i2s_gpio[i].gpio_no,
mic_i2s_gpio[i].gpio_name);
pr_debug("%s: gpio = %d, gpio name = %s, rtn = %d\n",
__func__,
mic_i2s_gpio[i].gpio_no,
mic_i2s_gpio[i].gpio_name,
rtn);
if (rtn) {
pr_err("%s: Failed to request gpio %d\n",
__func__,
mic_i2s_gpio[i].gpio_no);
for (j = i; j >= 0; j--)
gpio_free(mic_i2s_gpio[j].gpio_no);
goto err;
}
}
err:
return rtn;
}
static int msm_i2s_startup(struct snd_pcm_substream *substream)
{
int ret = 0;
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
msm_configure_i2s_rx_gpio();
i2s_rx_bit_clk = clk_get(cpu_dai->dev, "bit_clk");
if (IS_ERR(i2s_rx_bit_clk)) {
pr_err("Failed to get i2s bit_clk\n");
return PTR_ERR(i2s_rx_bit_clk);
}
clk_set_rate(i2s_rx_bit_clk, 0);
ret = clk_prepare_enable(i2s_rx_bit_clk);
if (IS_ERR_VALUE(ret)) {
pr_err("Unable to enable i2s_rx_bit_clk\n");
clk_put(i2s_rx_bit_clk);
return ret;
}
ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_CBM_CFM);
if (IS_ERR_VALUE(ret))
pr_err("set format for CPU dai failed\n");
} else if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) {
msm_configure_i2s_tx_gpio();
i2s_tx_bit_clk = clk_get(cpu_dai->dev, "bit_clk");
if (IS_ERR(i2s_tx_bit_clk)) {
pr_err("Failed to get i2s_tx_bit_clk\n");
return PTR_ERR(i2s_tx_bit_clk);
}
clk_set_rate(i2s_tx_bit_clk, 0);
ret = clk_prepare_enable(i2s_tx_bit_clk);
if (ret != 0) {
pr_err("Unable to enable i2s_tx_bit_clk\n");
clk_put(i2s_tx_bit_clk);
return ret;
}
ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_CBM_CFM);
if (IS_ERR_VALUE(ret))
pr_err("set format for CPU dai failed\n");
}
pr_debug("%s: ret = %d\n", __func__, ret);
pr_debug("%s(): substream = %s stream = %d\n", __func__,
substream->name, substream->stream);
return ret;
}
static void *def_tabla_mbhc_cal(void)
{
void *tabla_cal;
struct tabla_mbhc_btn_detect_cfg *btn_cfg;
u16 *btn_low, *btn_high;
u8 *n_ready, *n_cic, *gain;
tabla_cal = kzalloc(TABLA_MBHC_CAL_SIZE(TABLA_MBHC_DEF_BUTTONS,
TABLA_MBHC_DEF_RLOADS),
GFP_KERNEL);
if (!tabla_cal) {
pr_err("%s: out of memory\n", __func__);
return NULL;
}
#define S(X, Y) ((TABLA_MBHC_CAL_GENERAL_PTR(tabla_cal)->X) = (Y))
S(t_ldoh, 100);
S(t_bg_fast_settle, 100);
S(t_shutdown_plug_rem, 255);
S(mbhc_nsa, 4);
S(mbhc_navg, 4);
#undef S
#define S(X, Y) ((TABLA_MBHC_CAL_PLUG_DET_PTR(tabla_cal)->X) = (Y))
S(mic_current, TABLA_PID_MIC_5_UA);
S(hph_current, TABLA_PID_MIC_5_UA);
S(t_mic_pid, 100);
S(t_ins_complete, 250);
S(t_ins_retry, 200);
#undef S
#define S(X, Y) ((TABLA_MBHC_CAL_PLUG_TYPE_PTR(tabla_cal)->X) = (Y))
S(v_no_mic, 30);
S(v_hs_max, 1550);
#undef S
#define S(X, Y) ((TABLA_MBHC_CAL_BTN_DET_PTR(tabla_cal)->X) = (Y))
S(c[0], 62);
S(c[1], 124);
S(nc, 1);
S(n_meas, 3);
S(mbhc_nsc, 11);
S(n_btn_meas, 1);
S(n_btn_con, 2);
S(num_btn, TABLA_MBHC_DEF_BUTTONS);
S(v_btn_press_delta_sta, 100);
S(v_btn_press_delta_cic, 50);
#undef S
btn_cfg = TABLA_MBHC_CAL_BTN_DET_PTR(tabla_cal);
// btn_low = tabla_mbhc_cal_btn_det_mp(btn_cfg, TABLA_BTN_DET_V_BTN_LOW);
// btn_high = tabla_mbhc_cal_btn_det_mp(btn_cfg, TABLA_BTN_DET_V_BTN_HIGH);
btn_low[0] = -50;
btn_high[0] = 10;
btn_low[1] = 11;
btn_high[1] = 38;
btn_low[2] = 39;
btn_high[2] = 64;
btn_low[3] = 65;
btn_high[3] = 91;
btn_low[4] = 92;
btn_high[4] = 115;
btn_low[5] = 116;
btn_high[5] = 141;
btn_low[6] = 142;
btn_high[6] = 163;
btn_low[7] = 164;
btn_high[7] = 250;
// n_ready = tabla_mbhc_cal_btn_det_mp(btn_cfg, TABLA_BTN_DET_N_READY);
n_ready[0] = 48;
n_ready[1] = 38;
// n_cic = tabla_mbhc_cal_btn_det_mp(btn_cfg, TABLA_BTN_DET_N_CIC);
n_cic[0] = 60;
n_cic[1] = 47;
// gain = tabla_mbhc_cal_btn_det_mp(btn_cfg, TABLA_BTN_DET_GAIN);
gain[0] = 11;
gain[1] = 9;
return tabla_cal;
}
static int msm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
int ret = 0;
unsigned int rx_ch[SLIM_MAX_RX_PORTS], tx_ch[SLIM_MAX_TX_PORTS];
unsigned int rx_ch_cnt = 0, tx_ch_cnt = 0;
unsigned int num_tx_ch = 0;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
pr_debug("%s: rx_0_ch=%d\n", __func__, msm_slim_0_rx_ch);
ret = snd_soc_dai_get_channel_map(codec_dai,
&tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch);
if (ret < 0) {
pr_err("%s: failed to get codec chan map\n", __func__);
goto end;
}
ret = snd_soc_dai_set_channel_map(cpu_dai, 0, 0,
msm_slim_0_rx_ch, rx_ch);
if (ret < 0) {
pr_err("%s: failed to set cpu chan map\n", __func__);
goto end;
}
ret = snd_soc_dai_set_channel_map(codec_dai, 0, 0,
msm_slim_0_rx_ch, rx_ch);
if (ret < 0) {
pr_err("%s: failed to set codec channel map\n",
__func__);
goto end;
}
} else {
if (codec_dai->id == 2)
num_tx_ch = msm_slim_0_tx_ch;
else if (codec_dai->id == 5) {
/* DAI 5 is used for external EC reference from codec.
* Since Rx is fed as reference for EC, the config of
* this DAI is based on that of the Rx path.
*/
num_tx_ch = msm_slim_0_rx_ch;
}
pr_debug("%s: %s_tx_dai_id_%d_ch=%d\n", __func__,
codec_dai->name, codec_dai->id, num_tx_ch);
ret = snd_soc_dai_get_channel_map(codec_dai,
&tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch);
if (ret < 0) {
pr_err("%s: failed to get codec chan map\n", __func__);
goto end;
}
ret = snd_soc_dai_set_channel_map(cpu_dai,
num_tx_ch, tx_ch, 0 , 0);
if (ret < 0) {
pr_err("%s: failed to set cpu chan map\n", __func__);
goto end;
}
ret = snd_soc_dai_set_channel_map(codec_dai,
num_tx_ch, tx_ch, 0, 0);
if (ret < 0) {
pr_err("%s: failed to set codec channel map\n",
__func__);
goto end;
}
}
end:
return ret;
}
static int msm_stubrx_init(struct snd_soc_pcm_runtime *rtd)
{
rtd->pmdown_time = 0;
return 0;
}
static int msm_slimbus_2_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
int ret = 0;
unsigned int rx_ch[SLIM_MAX_RX_PORTS], tx_ch[SLIM_MAX_TX_PORTS];
unsigned int rx_ch_cnt = 0, tx_ch_cnt = 0;
unsigned int num_tx_ch = 0;
unsigned int num_rx_ch = 0;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
num_rx_ch = params_channels(params);
pr_debug("%s: %s rx_dai_id = %d num_ch = %d\n", __func__,
codec_dai->name, codec_dai->id, num_rx_ch);
ret = snd_soc_dai_get_channel_map(codec_dai,
&tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch);
if (ret < 0) {
pr_err("%s: failed to get codec chan map\n", __func__);
goto end;
}
ret = snd_soc_dai_set_channel_map(cpu_dai, 0, 0,
num_rx_ch, rx_ch);
if (ret < 0) {
pr_err("%s: failed to set cpu chan map\n", __func__);
goto end;
}
ret = snd_soc_dai_set_channel_map(codec_dai, 0, 0,
num_rx_ch, rx_ch);
if (ret < 0) {
pr_err("%s: failed to set codec channel map\n",
__func__);
goto end;
}
} else {
num_tx_ch = params_channels(params);
pr_debug("%s: %s tx_dai_id = %d num_ch = %d\n", __func__,
codec_dai->name, codec_dai->id, num_tx_ch);
ret = snd_soc_dai_get_channel_map(codec_dai,
&tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch);
if (ret < 0) {
pr_err("%s: failed to get codec chan map\n", __func__);
goto end;
}
ret = snd_soc_dai_set_channel_map(cpu_dai,
num_tx_ch, tx_ch, 0 , 0);
if (ret < 0) {
pr_err("%s: failed to set cpu chan map\n", __func__);
goto end;
}
ret = snd_soc_dai_set_channel_map(codec_dai,
num_tx_ch, tx_ch, 0, 0);
if (ret < 0) {
pr_err("%s: failed to set codec channel map\n",
__func__);
goto end;
}
}
end:
return ret;
}
static int msm_slimbus_1_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
int ret = 0;
unsigned int rx_ch = SLIM_1_RX_1, tx_ch = SLIM_1_TX_1;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
pr_debug("%s: APQ BT/USB TX -> SLIMBUS_1_RX -> MDM TX shared ch %d\n",
__func__, rx_ch);
ret = snd_soc_dai_set_channel_map(cpu_dai, 0, 0, 1, &rx_ch);
if (ret < 0) {
pr_err("%s: Erorr %d setting SLIM_1 RX channel map\n",
__func__, ret);
goto end;
}
} else {
pr_debug("%s: MDM RX -> SLIMBUS_1_TX -> APQ BT/USB Rx shared ch %d\n",
__func__, tx_ch);
ret = snd_soc_dai_set_channel_map(cpu_dai, 1, &tx_ch, 0, 0);
if (ret < 0) {
pr_err("%s: Erorr %d setting SLIM_1 TX channel map\n",
__func__, ret);
goto end;
}
}
end:
return ret;
}
static int msm_slimbus_3_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
int ret = 0;
unsigned int rx_ch[2] = {SLIM_3_RX_1, SLIM_3_RX_2};
unsigned int tx_ch[2] = {SLIM_3_TX_1, SLIM_3_TX_2};
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
pr_debug("%s: slim_3_rx_ch %d, sch %d %d\n",
__func__, msm_slim_3_rx_ch,
rx_ch[0], rx_ch[1]);
ret = snd_soc_dai_set_channel_map(cpu_dai, 0, 0,
msm_slim_3_rx_ch, rx_ch);
if (ret < 0) {
pr_err("%s: Erorr %d setting SLIM_3 RX channel map\n",
__func__, ret);
goto end;
}
} else {
pr_debug("%s: MDM RX -> SLIMBUS_3_TX -> APQ HDMI ch: %d, %d\n",
__func__, tx_ch[0], tx_ch[1]);
ret = snd_soc_dai_set_channel_map(cpu_dai, 2, tx_ch, 0, 0);
if (ret < 0) {
pr_err("%s: Erorr %d setting SLIM_3 TX channel map\n",
__func__, ret);
goto end;
}
}
end:
return ret;
}
static int msm_slimbus_4_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
int ret = 0;
unsigned int rx_ch = SLIM_4_RX_1, tx_ch[2];
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
pr_debug("%s: APQ Incall Playback SLIMBUS_4_RX -> MDM TX shared ch %d\n",
__func__, rx_ch);
ret = snd_soc_dai_set_channel_map(cpu_dai, 0, 0, 1, &rx_ch);
if (ret < 0) {
pr_err("%s: Erorr %d setting SLIM_4 RX channel map\n",
__func__, ret);
}
} else {
if (rec_mode == INCALL_REC_STEREO) {
tx_ch[0] = SLIM_4_TX_1;
tx_ch[1] = SLIM_4_TX_2;
ret = snd_soc_dai_set_channel_map(cpu_dai, 2,
tx_ch, 0, 0);
} else {
tx_ch[0] = SLIM_4_TX_1;
ret = snd_soc_dai_set_channel_map(cpu_dai, 1,
tx_ch, 0, 0);
}
pr_debug("%s: Incall Record shared tx_ch[0]:%d, tx_ch[1]:%d\n",
__func__, tx_ch[0], tx_ch[1]);
if (ret < 0) {
pr_err("%s: Erorr %d setting SLIM_4 TX channel map\n",
__func__, ret);
}
}
return ret;
}
static int msm_audrx_init(struct snd_soc_pcm_runtime *rtd)
{
int err;
uint32_t revision;
struct snd_soc_codec *codec = rtd->codec;
struct snd_soc_dapm_context *dapm = &codec->dapm;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
pr_debug("%s(), dev_name(%s)\n", __func__, dev_name(cpu_dai->dev));
/*if (machine_is_msm_liquid()) {
top_spk_pamp_gpio = (PM8921_GPIO_PM_TO_SYS(19));
bottom_spk_pamp_gpio = (PM8921_GPIO_PM_TO_SYS(18));
}*/
rtd->pmdown_time = 0;
err = snd_soc_add_controls(codec, tabla_msm_controls,
ARRAY_SIZE(tabla_msm_controls));
if (err < 0)
return err;
snd_soc_dapm_new_controls(dapm, apq8064_dapm_widgets,
ARRAY_SIZE(apq8064_dapm_widgets));
snd_soc_dapm_add_routes(dapm, apq8064_common_audio_map,
ARRAY_SIZE(apq8064_common_audio_map));
if (machine_is_apq8064_mtp()) {
snd_soc_dapm_add_routes(dapm, apq8064_mtp_audio_map,
ARRAY_SIZE(apq8064_mtp_audio_map));
} else {
snd_soc_dapm_add_routes(dapm, apq8064_liquid_cdp_audio_map,
ARRAY_SIZE(apq8064_liquid_cdp_audio_map));
}
snd_soc_dapm_enable_pin(dapm, "Ext Spk Bottom Pos");
snd_soc_dapm_enable_pin(dapm, "Ext Spk Bottom Neg");
snd_soc_dapm_enable_pin(dapm, "Ext Spk Top Pos");
snd_soc_dapm_enable_pin(dapm, "Ext Spk Top Neg");
snd_soc_dapm_sync(dapm);
err = snd_soc_jack_new(codec, "Headset Jack",
(SND_JACK_HEADSET | SND_JACK_OC_HPHL | SND_JACK_OC_HPHR),
&hs_jack);
if (err) {
pr_err("failed to create new jack\n");
return err;
}
err = snd_soc_jack_new(codec, "Button Jack",
TABLA_JACK_BUTTON_MASK, &button_jack);
if (err) {
pr_err("failed to create new jack\n");
return err;
}
codec_clk = clk_get(cpu_dai->dev, "osr_clk");
/* APQ8064 Rev 1.1 CDP and Liquid have mechanical switch */
revision = socinfo_get_version();
if (apq8064_i2s_hs_detect_use_gpio != -1) {
if (apq8064_i2s_hs_detect_use_gpio == 1)
pr_debug("%s: MBHC mechanical is enabled by request\n",
__func__);
else if (apq8064_i2s_hs_detect_use_gpio == 0)
pr_debug("%s: MBHC mechanical is disabled by request\n",
__func__);
else
pr_warn("%s: Invalid hs_detect_use_gpio %d\n", __func__,
apq8064_i2s_hs_detect_use_gpio);
} else if (SOCINFO_VERSION_MAJOR(revision) == 0) {
pr_warn("%s: Unknown HW revision detected %d.%d\n", __func__,
SOCINFO_VERSION_MAJOR(revision),
SOCINFO_VERSION_MINOR(revision));
} else if ((SOCINFO_VERSION_MAJOR(revision) == 1 &&
SOCINFO_VERSION_MINOR(revision) >= 1 &&
(machine_is_apq8064_cdp() ||
machine_is_apq8064_liquid())) ||
SOCINFO_VERSION_MAJOR(revision) > 1) {
pr_debug("%s: MBHC mechanical switch available APQ8064 detected\n",
__func__);
apq8064_i2s_hs_detect_use_gpio = 1;
}
if (apq8064_i2s_hs_detect_use_gpio == 1) {
pr_debug("%s: Using MBHC mechanical switch\n", __func__);
mbhc_cfg.gpio = JACK_DETECT_GPIO;
mbhc_cfg.gpio_irq = gpio_to_irq(JACK_DETECT_GPIO);
err = gpio_request(mbhc_cfg.gpio, "MBHC_HS_DETECT");
if (err < 0) {
pr_err("%s: gpio_request %d failed %d\n", __func__,
mbhc_cfg.gpio, err);
return err;
}
gpio_direction_input(JACK_DETECT_GPIO);
} else
pr_debug("%s: Not using MBHC mechanical switch\n", __func__);
mbhc_cfg.read_fw_bin = apq8064_i2s_hs_detect_use_firmware;
err = tabla_hs_detect(codec, &mbhc_cfg);
return err;
}
static struct snd_soc_dsp_link lpa_fe_media = {
.playback = true,
.trigger = {
SND_SOC_DSP_TRIGGER_POST,
SND_SOC_DSP_TRIGGER_POST
},
};
static struct snd_soc_dsp_link fe_media = {
.playback = true,
.capture = true,
.trigger = {
SND_SOC_DSP_TRIGGER_POST,
SND_SOC_DSP_TRIGGER_POST
},
};
/* bi-directional media definition for hostless PCM device */
static struct snd_soc_dsp_link bidir_hl_media = {
.playback = true,
.capture = true,
.trigger = {
SND_SOC_DSP_TRIGGER_POST,
SND_SOC_DSP_TRIGGER_POST
},
};
static struct snd_soc_dsp_link hdmi_rx_hl = {
.playback = true,
.trigger = {
SND_SOC_DSP_TRIGGER_POST,
SND_SOC_DSP_TRIGGER_POST
},
};
static int msm_slim_0_rx_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
pr_debug("%s()\n", __func__);
rate->min = rate->max = 48000;
channels->min = channels->max = msm_slim_0_rx_ch;
return 0;
}
static int msm_slim_0_tx_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
pr_debug("%s()\n", __func__);
rate->min = rate->max = 48000;
channels->min = channels->max = msm_slim_0_tx_ch;
return 0;
}
static int msm_slim_3_rx_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
pr_debug("%s()\n", __func__);
rate->min = rate->max = 48000;
channels->min = channels->max = msm_slim_3_rx_ch;
return 0;
}
static int msm_slim_3_tx_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
pr_debug("%s()\n", __func__);
rate->min = rate->max = 48000;
channels->min = channels->max = 2;
return 0;
}
static int msm_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
pr_debug("%s()\n", __func__);
rate->min = rate->max = 48000;
return 0;
}
static int msm_hdmi_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
pr_debug("%s channels->min %u channels->max %u ()\n", __func__,
channels->min, channels->max);
rate->min = rate->max = 48000;
return 0;
}
static int msm_btsco_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
rate->min = rate->max = msm_btsco_rate;
channels->min = channels->max = msm_btsco_ch;
return 0;
}
static int msm_auxpcm_be_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
struct snd_interval *channels = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_CHANNELS);
/* PCM only supports mono output with 8khz sample rate */
rate->min = rate->max = 8000;
channels->min = channels->max = 1;
return 0;
}
static int msm_proxy_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd,
struct snd_pcm_hw_params *params)
{
struct snd_interval *rate = hw_param_interval(params,
SNDRV_PCM_HW_PARAM_RATE);
pr_debug("%s()\n", __func__);
rate->min = rate->max = 48000;
return 0;
}
static int msm_aux_pcm_get_gpios(void)
{
int ret = 0;
pr_debug("%s\n", __func__);
ret = gpio_request(GPIO_AUX_PCM_DOUT, "AUX PCM DOUT");
if (ret < 0) {
pr_err("%s: Failed to request gpio(%d): AUX PCM DOUT",
__func__, GPIO_AUX_PCM_DOUT);
goto fail_dout;
}
ret = gpio_request(GPIO_AUX_PCM_DIN, "AUX PCM DIN");
if (ret < 0) {
pr_err("%s: Failed to request gpio(%d): AUX PCM DIN",
__func__, GPIO_AUX_PCM_DIN);
goto fail_din;
}
ret = gpio_request(GPIO_AUX_PCM_SYNC, "AUX PCM SYNC");
if (ret < 0) {
pr_err("%s: Failed to request gpio(%d): AUX PCM SYNC",
__func__, GPIO_AUX_PCM_SYNC);
goto fail_sync;
}
ret = gpio_request(GPIO_AUX_PCM_CLK, "AUX PCM CLK");
if (ret < 0) {
pr_err("%s: Failed to request gpio(%d): AUX PCM CLK",
__func__, GPIO_AUX_PCM_CLK);
goto fail_clk;
}
return 0;
fail_clk:
gpio_free(GPIO_AUX_PCM_SYNC);
fail_sync:
gpio_free(GPIO_AUX_PCM_DIN);
fail_din:
gpio_free(GPIO_AUX_PCM_DOUT);
fail_dout:
return ret;
}
static int msm_aux_pcm_free_gpios(void)
{
gpio_free(GPIO_AUX_PCM_DIN);
gpio_free(GPIO_AUX_PCM_DOUT);
gpio_free(GPIO_AUX_PCM_SYNC);
gpio_free(GPIO_AUX_PCM_CLK);
return 0;
}
static int msm_startup(struct snd_pcm_substream *substream)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
pr_debug("%s(): dai_link_str_name = %s cpu_dai = %s codec_dai = %s\n",
__func__, rtd->dai_link->stream_name,
rtd->dai_link->cpu_dai_name,
rtd->dai_link->codec_dai_name);
return 0;
}
static int msm_auxpcm_startup(struct snd_pcm_substream *substream)
{
int ret = 0;
pr_debug("%s(): substream = %s\n", __func__, substream->name);
ret = msm_aux_pcm_get_gpios();
if (ret < 0) {
pr_err("%s: Aux PCM GPIO request failed\n", __func__);
return -EINVAL;
}
return 0;
}
static int msm_slimbus_1_startup(struct snd_pcm_substream *substream)
{
struct slim_controller *slim = slim_busnum_to_ctrl(1);
pr_debug("%s(): substream = %s stream = %d\n", __func__,
substream->name, substream->stream);
if (slim != NULL)
pm_runtime_get_sync(slim->dev.parent);
return 0;
}
static void msm_auxpcm_shutdown(struct snd_pcm_substream *substream)
{
pr_debug("%s(): substream = %s\n", __func__, substream->name);
msm_aux_pcm_free_gpios();
}
static void msm_shutdown(struct snd_pcm_substream *substream)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
pr_debug("%s(): dai_link_str_name = %s cpu_dai = %s codec_dai = %s\n",
__func__, rtd->dai_link->stream_name,
rtd->dai_link->cpu_dai_name, rtd->dai_link->codec_dai_name);
}
static void msm_slimbus_1_shutdown(struct snd_pcm_substream *substream)
{
struct slim_controller *slim = slim_busnum_to_ctrl(1);
pr_debug("%s(): substream = %s stream = %d\n", __func__,
substream->name, substream->stream);
if (slim != NULL) {
pm_runtime_mark_last_busy(slim->dev.parent);
pm_runtime_put(slim->dev.parent);
}
}
static struct snd_soc_ops msm_be_ops = {
.startup = msm_startup,
.hw_params = msm_hw_params,
.shutdown = msm_shutdown,
};
static struct snd_soc_ops msm_auxpcm_be_ops = {
.startup = msm_auxpcm_startup,
.shutdown = msm_auxpcm_shutdown,
};
static struct snd_soc_ops msm_slimbus_1_be_ops = {
.startup = msm_slimbus_1_startup,
.hw_params = msm_slimbus_1_hw_params,
.shutdown = msm_slimbus_1_shutdown,
};
static struct snd_soc_ops msm_slimbus_3_be_ops = {
.startup = msm_startup,
.hw_params = msm_slimbus_3_hw_params,
.shutdown = msm_shutdown,
};
static struct snd_soc_ops msm_slimbus_4_be_ops = {
.startup = msm_startup,
.hw_params = msm_slimbus_4_hw_params,
.shutdown = msm_shutdown,
};
static struct snd_soc_ops msm_slimbus_2_be_ops = {
.startup = msm_startup,
.hw_params = msm_slimbus_2_hw_params,
.shutdown = msm_shutdown,
};
static struct snd_soc_ops msm_mi2s_be_ops = {
.startup = msm_mi2s_startup,
.shutdown = msm_mi2s_shutdown,
};
static struct snd_soc_ops msm_i2s_be_ops = {
.startup = msm_i2s_startup,
.shutdown = msm_i2s_shutdown,
};
static struct snd_soc_dai_link msm_dai_delta_mi2s[] = {
/* Backend DAI Links */
{
.name = LPASS_BE_MI2S_RX,
.stream_name = "MI2S Playback",
.cpu_dai_name = "msm-dai-q6-mi2s",
.platform_name = "msm-pcm-routing",
.codec_name = "tabla_codec",
.codec_dai_name = "tabla_i2s_rx1",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_MI2S_RX,
.init = &msm_mi2s_audrx_init,
.be_hw_params_fixup = msm_mi2s_rx_be_hw_params_fixup,
.ops = &msm_mi2s_be_ops,
},
{
.name = LPASS_BE_MI2S_TX,
.stream_name = "MI2S Capture",
.cpu_dai_name = "msm-dai-q6-mi2s",
.platform_name = "msm-pcm-routing",
.codec_name = "tabla_codec",
.codec_dai_name = "tabla_i2s_tx1",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_MI2S_TX,
.be_hw_params_fixup = msm_mi2s_tx_be_hw_params_fixup,
.ops = &msm_mi2s_be_ops,
},
{
.name = LPASS_BE_PRI_I2S_RX,
.stream_name = "Primary I2S Playback",
.cpu_dai_name = "msm-dai-q6.0",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_PRI_I2S_RX,
.be_hw_params_fixup = msm_i2s_rx_be_hw_params_fixup,
.ops = &msm_i2s_be_ops,
},
{
.name = LPASS_BE_PRI_I2S_TX,
.stream_name = "Primary I2S Capture",
.cpu_dai_name = "msm-dai-q6.1",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_PRI_I2S_TX,
.be_hw_params_fixup = msm_i2s_tx_be_hw_params_fixup,
.ops = &msm_i2s_be_ops,
},
};
static struct snd_soc_dai_link msm_dai_delta_slim[] = {
/* Hostless PMC purpose */
{
.name = "SLIMBUS_0 Hostless",
.stream_name = "SLIMBUS_0 Hostless",
.cpu_dai_name = "SLIMBUS0_HOSTLESS",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.dsp_link = &bidir_hl_media,
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
/* .be_id = do not care */
},
/* Backend DAI Links */
{
.name = LPASS_BE_SLIMBUS_0_RX,
.stream_name = "Slimbus Playback",
.cpu_dai_name = "msm-dai-q6.16384",
.platform_name = "msm-pcm-routing",
.codec_name = "tabla_codec",
.codec_dai_name = "tabla_rx1",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_SLIMBUS_0_RX,
.init = &msm_audrx_init,
.be_hw_params_fixup = msm_slim_0_rx_be_hw_params_fixup,
.ops = &msm_be_ops,
},
{
.name = LPASS_BE_SLIMBUS_0_TX,
.stream_name = "Slimbus Capture",
.cpu_dai_name = "msm-dai-q6.16385",
.platform_name = "msm-pcm-routing",
.codec_name = "tabla_codec",
.codec_dai_name = "tabla_tx1",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_SLIMBUS_0_TX,
.be_hw_params_fixup = msm_slim_0_tx_be_hw_params_fixup,
.ops = &msm_be_ops,
},
{
.name = LPASS_BE_STUB_RX,
.stream_name = "Stub Playback",
.cpu_dai_name = "msm-dai-stub",
.platform_name = "msm-pcm-routing",
.codec_name = "tabla_codec",
.codec_dai_name = "tabla_rx2",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_EXTPROC_RX,
.be_hw_params_fixup = msm_slim_0_rx_be_hw_params_fixup,
.init = &msm_stubrx_init,
.ops = &msm_be_ops,
},
{
.name = LPASS_BE_STUB_TX,
.stream_name = "Stub Capture",
.cpu_dai_name = "msm-dai-stub",
.platform_name = "msm-pcm-routing",
.codec_name = "tabla_codec",
.codec_dai_name = "tabla_tx1",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_EXTPROC_TX,
.be_hw_params_fixup = msm_slim_0_tx_be_hw_params_fixup,
.ops = &msm_be_ops,
},
{
.name = LPASS_BE_SLIMBUS_1_RX,
.stream_name = "Slimbus1 Playback",
.cpu_dai_name = "msm-dai-q6.16386",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_SLIMBUS_1_RX,
.be_hw_params_fixup = msm_btsco_be_hw_params_fixup,
.ops = &msm_slimbus_1_be_ops,
},
{
.name = LPASS_BE_SLIMBUS_1_TX,
.stream_name = "Slimbus1 Capture",
.cpu_dai_name = "msm-dai-q6.16387",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_SLIMBUS_1_TX,
.be_hw_params_fixup = msm_btsco_be_hw_params_fixup,
.ops = &msm_slimbus_1_be_ops,
},
/* Ultrasound TX Back End DAI Link */
{
.name = "SLIMBUS_2 Hostless Capture",
.stream_name = "SLIMBUS_2 Hostless Capture",
.cpu_dai_name = "msm-dai-q6.16389",
.platform_name = "msm-pcm-hostless",
.codec_name = "tabla_codec",
.codec_dai_name = "tabla_tx2",
.ignore_suspend = 1,
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ops = &msm_slimbus_2_be_ops,
},
/* Ultrasound RX Back End DAI Link */
{
.name = "SLIMBUS_2 Hostless Playback",
.stream_name = "SLIMBUS_2 Hostless Playback",
.cpu_dai_name = "msm-dai-q6.16388",
.platform_name = "msm-pcm-hostless",
.codec_name = "tabla_codec",
.codec_dai_name = "tabla_rx3",
.ignore_suspend = 1,
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ops = &msm_slimbus_2_be_ops,
},
/* Incall Music Back End DAI Link */
{
.name = LPASS_BE_SLIMBUS_4_RX,
.stream_name = "Slimbus4 Playback",
.cpu_dai_name = "msm-dai-q6.16392",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.no_codec = 1,
.be_id = MSM_BACKEND_DAI_SLIMBUS_4_RX,
.be_hw_params_fixup = msm_be_hw_params_fixup,
.ops = &msm_slimbus_4_be_ops,
},
/* Incall Record Back End DAI Link */
{
.name = LPASS_BE_SLIMBUS_4_TX,
.stream_name = "Slimbus4 Capture",
.cpu_dai_name = "msm-dai-q6.16393",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.no_codec = 1,
.be_id = MSM_BACKEND_DAI_SLIMBUS_4_TX,
.be_hw_params_fixup = msm_be_hw_params_fixup,
.init = &msm_incall_rec_init,
.ops = &msm_slimbus_4_be_ops,
},
{
.name = LPASS_BE_STUB_1_TX,
.stream_name = "Stub1 Capture",
.cpu_dai_name = "msm-dai-stub",
.platform_name = "msm-pcm-routing",
.codec_name = "tabla_codec",
.codec_dai_name = "tabla_tx3",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_EXTPROC_EC_TX,
/* This BE is used for external EC reference from codec. Since
* Rx is fed as reference for EC, the config of this DAI is
* based on that of the Rx path.
*/
.be_hw_params_fixup = msm_slim_0_rx_be_hw_params_fixup,
.ops = &msm_be_ops,
},
{
.name = LPASS_BE_SLIMBUS_3_RX,
.stream_name = "Slimbus3 Playback",
.cpu_dai_name = "msm-dai-q6.16390",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.init = &msm_slim_3_init,
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_SLIMBUS_3_RX,
.be_hw_params_fixup = msm_slim_3_rx_be_hw_params_fixup,
.ops = &msm_slimbus_3_be_ops,
},
{
.name = LPASS_BE_SLIMBUS_3_TX,
.stream_name = "Slimbus3 Capture",
.cpu_dai_name = "msm-dai-q6.16391",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_SLIMBUS_3_TX,
.be_hw_params_fixup = msm_slim_3_tx_be_hw_params_fixup,
.ops = &msm_slimbus_3_be_ops,
},
};
/* Digital audio interface glue - connects codec <---> CPU */
static struct snd_soc_dai_link msm_dai[] = {
/* FrontEnd DAI Links */
{
.name = "MSM8960 Media1",
.stream_name = "MultiMedia1",
.cpu_dai_name = "MultiMedia1",
.platform_name = "msm-pcm-dsp",
.dynamic = 1,
.dsp_link = &fe_media,
.be_id = MSM_FRONTEND_DAI_MULTIMEDIA1
},
{
.name = "MSM8960 Media2",
.stream_name = "MultiMedia2",
.cpu_dai_name = "MultiMedia2",
.platform_name = "msm-multi-ch-pcm-dsp",
.dynamic = 1,
.dsp_link = &fe_media,
.be_id = MSM_FRONTEND_DAI_MULTIMEDIA2,
},
{
.name = "Circuit-Switch Voice",
.stream_name = "CS-Voice",
.cpu_dai_name = "CS-VOICE",
.platform_name = "msm-pcm-voice",
.dynamic = 1,
.dsp_link = &fe_media,
.be_id = MSM_FRONTEND_DAI_CS_VOICE,
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
},
{
.name = "MSM VoIP",
.stream_name = "VoIP",
.cpu_dai_name = "VoIP",
.platform_name = "msm-voip-dsp",
.dynamic = 1,
.dsp_link = &fe_media,
.be_id = MSM_FRONTEND_DAI_VOIP,
},
{
.name = "MSM8960 LPA",
.stream_name = "LPA",
.cpu_dai_name = "MultiMedia3",
.platform_name = "msm-pcm-lpa",
.dynamic = 1,
.dsp_link = &lpa_fe_media,
.be_id = MSM_FRONTEND_DAI_MULTIMEDIA3,
},
{
.name = "INT_FM Hostless",
.stream_name = "INT_FM Hostless",
.cpu_dai_name = "INT_FM_HOSTLESS",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.dsp_link = &bidir_hl_media,
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
/* .be_id = do not care */
},
{
.name = "MSM AFE-PCM RX",
.stream_name = "AFE-PROXY RX",
.cpu_dai_name = "msm-dai-q6.241",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.platform_name = "msm-pcm-afe",
.ignore_suspend = 1,
},
{
.name = "MSM AFE-PCM TX",
.stream_name = "AFE-PROXY TX",
.cpu_dai_name = "msm-dai-q6.240",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.platform_name = "msm-pcm-afe",
.ignore_suspend = 1,
},
{
.name = "MSM8960 Compr",
.stream_name = "COMPR",
.cpu_dai_name = "MultiMedia4",
.platform_name = "msm-compr-dsp",
.dynamic = 1,
.dsp_link = &lpa_fe_media,
.be_id = MSM_FRONTEND_DAI_MULTIMEDIA4,
},
{
.name = "AUXPCM Hostless",
.stream_name = "AUXPCM Hostless",
.cpu_dai_name = "AUXPCM_HOSTLESS",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.dsp_link = &bidir_hl_media,
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
},
/* HDMI Hostless */
{
.name = "HDMI_RX_HOSTLESS",
.stream_name = "HDMI_RX_HOSTLESS",
.cpu_dai_name = "HDMI_HOSTLESS",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.dsp_link = &hdmi_rx_hl,
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.no_codec = 1,
.ignore_suspend = 1,
},
{
.name = "Voice Stub",
.stream_name = "Voice Stub",
.cpu_dai_name = "VOICE_STUB",
.platform_name = "msm-pcm-hostless",
.dynamic = 1,
.dsp_link = &fe_media,
.no_host_mode = SND_SOC_DAI_LINK_NO_HOST,
.ignore_suspend = 1,
.be_id = MSM_FRONTEND_DAI_VOICE_STUB,
},
/* Backend BT/FM DAI Links */
{
.name = LPASS_BE_INT_BT_SCO_RX,
.stream_name = "Internal BT-SCO Playback",
.cpu_dai_name = "msm-dai-q6.12288",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.init = &msm_btsco_init,
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_INT_BT_SCO_RX,
.be_hw_params_fixup = msm_btsco_be_hw_params_fixup,
},
{
.name = LPASS_BE_INT_BT_SCO_TX,
.stream_name = "Internal BT-SCO Capture",
.cpu_dai_name = "msm-dai-q6.12289",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_INT_BT_SCO_TX,
.be_hw_params_fixup = msm_btsco_be_hw_params_fixup,
},
{
.name = LPASS_BE_INT_FM_RX,
.stream_name = "Internal FM Playback",
.cpu_dai_name = "msm-dai-q6.12292",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_INT_FM_RX,
.be_hw_params_fixup = msm_be_hw_params_fixup,
},
{
.name = LPASS_BE_INT_FM_TX,
.stream_name = "Internal FM Capture",
.cpu_dai_name = "msm-dai-q6.12293",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_INT_FM_TX,
.be_hw_params_fixup = msm_be_hw_params_fixup,
},
/* HDMI BACK END DAI Link */
{
.name = LPASS_BE_HDMI,
.stream_name = "HDMI Playback",
.cpu_dai_name = "msm-dai-q6-hdmi.8",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.no_codec = 1,
.be_id = MSM_BACKEND_DAI_HDMI_RX,
.be_hw_params_fixup = msm_hdmi_be_hw_params_fixup,
},
/* Backend AFE DAI Links */
{
.name = LPASS_BE_AFE_PCM_RX,
.stream_name = "AFE Playback",
.cpu_dai_name = "msm-dai-q6.224",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_codec = 1,
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_AFE_PCM_RX,
.be_hw_params_fixup = msm_proxy_be_hw_params_fixup,
},
{
.name = LPASS_BE_AFE_PCM_TX,
.stream_name = "AFE Capture",
.cpu_dai_name = "msm-dai-q6.225",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_codec = 1,
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_AFE_PCM_TX,
.be_hw_params_fixup = msm_proxy_be_hw_params_fixup,
},
/* AUX PCM Backend DAI Links */
{
.name = LPASS_BE_AUXPCM_RX,
.stream_name = "AUX PCM Playback",
.cpu_dai_name = "msm-dai-q6.2",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-rx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_AUXPCM_RX,
.be_hw_params_fixup = msm_auxpcm_be_params_fixup,
.ops = &msm_auxpcm_be_ops,
},
{
.name = LPASS_BE_AUXPCM_TX,
.stream_name = "AUX PCM Capture",
.cpu_dai_name = "msm-dai-q6.3",
.platform_name = "msm-pcm-routing",
.codec_name = "msm-stub-codec.1",
.codec_dai_name = "msm-stub-tx",
.no_pcm = 1,
.be_id = MSM_BACKEND_DAI_AUXPCM_TX,
.be_hw_params_fixup = msm_auxpcm_be_params_fixup,
},
};
/* Digital audio interface glue - connects codec <---> CPU */
static struct snd_soc_dai_link msm_mi2s_dai[
ARRAY_SIZE(msm_dai) +
ARRAY_SIZE(msm_dai_delta_mi2s)];
static struct snd_soc_dai_link msm_slim_dai[
ARRAY_SIZE(msm_dai) +
ARRAY_SIZE(msm_dai_delta_slim)];
static struct snd_soc_card snd_soc_card_msm = {
.name = "apq8064-tabla-snd-card",
};
static struct platform_device *msm_snd_device;
static int __init msm_audio_init(void)
{
int ret;
u32 version = socinfo_get_platform_version();
if (!machine_is_apq8064_mtp() ||
(SOCINFO_VERSION_MINOR(version) != 1)) {
pr_info("%s: Not APQ8064 in I2S mode\n", __func__);
return -ENODEV;
}
pr_debug("%s: APQ8064 is in I2S mode\n", __func__);
mbhc_cfg.calibration = def_tabla_mbhc_cal();
if (!mbhc_cfg.calibration) {
pr_err("Calibration data allocation failed\n");
return -ENOMEM;
}
msm_snd_device = platform_device_alloc("soc-audio", 0);
if (!msm_snd_device) {
pr_err("Platform device allocation failed\n");
kfree(mbhc_cfg.calibration);
return -ENOMEM;
}
if (wcd9xxx_get_intf_type() == WCD9XXX_INTERFACE_TYPE_SLIMBUS) {
memcpy(msm_slim_dai, msm_dai, sizeof(msm_dai));
memcpy(msm_slim_dai + ARRAY_SIZE(msm_dai),
msm_dai_delta_slim, sizeof(msm_dai_delta_slim));
snd_soc_card_msm.dai_link = msm_slim_dai;
snd_soc_card_msm.num_links = ARRAY_SIZE(msm_slim_dai);
pr_info("%s: Load Slimbus Dai\n", __func__);
} else if (wcd9xxx_get_intf_type() == WCD9XXX_INTERFACE_TYPE_I2C) {
memcpy(msm_mi2s_dai, msm_dai, sizeof(msm_dai));
memcpy(msm_mi2s_dai + ARRAY_SIZE(msm_dai),
msm_dai_delta_mi2s, sizeof(msm_dai_delta_mi2s));
snd_soc_card_msm.dai_link = msm_mi2s_dai;
snd_soc_card_msm.num_links = ARRAY_SIZE(msm_mi2s_dai);
pr_info("%s: Load MI2S\n", __func__);
}
platform_set_drvdata(msm_snd_device, &snd_soc_card_msm);
ret = platform_device_add(msm_snd_device);
if (ret) {
platform_device_put(msm_snd_device);
kfree(mbhc_cfg.calibration);
return ret;
}
mutex_init(&cdc_mclk_mutex);
atomic_set(&mi2s_rsc_ref, 0);
return ret;
}
module_init(msm_audio_init);
static void __exit msm_audio_exit(void)
{
if (!cpu_is_apq8064() || (socinfo_get_id() == 130)) {
pr_err("%s: Not the right machine type\n", __func__);
return ;
}
platform_device_unregister(msm_snd_device);
if (mbhc_cfg.gpio)
gpio_free(mbhc_cfg.gpio);
kfree(mbhc_cfg.calibration);
mutex_destroy(&cdc_mclk_mutex);
}
module_exit(msm_audio_exit);
MODULE_DESCRIPTION("ALSA SoC msm");
MODULE_LICENSE("GPL v2");
|
SmokyBob/android_kernel_asus_padfone2
|
sound/soc/msm/apq8064-i2s.c
|
C
|
gpl-2.0
| 76,510
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Multishipping\Block\Checkout;
use Magento\Customer\Model\Address\Config as AddressConfig;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Session\SessionManagerInterface;
use Magento\Framework\View\Element\Template\Context;
use Magento\Multishipping\Model\Checkout\Type\Multishipping;
use Magento\Quote\Model\Quote\Address as QuoteAddress;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order\Address as OrderAddress;
use Magento\Theme\Block\Html\Title;
/**
* Multi-shipping checkout results information
*
* @api
*/
class Results extends Success
{
/**
* @var AddressConfig
*/
private $addressConfig;
/**
* @var OrderRepositoryInterface
*/
private $orderRepository;
/**
* @var SessionManagerInterface
*/
private $session;
/**
* @param Context $context
* @param Multishipping $multishipping
* @param AddressConfig $addressConfig
* @param OrderRepositoryInterface $orderRepository
* @param SessionManagerInterface $session
* @param array $data
*/
public function __construct(
Context $context,
Multishipping $multishipping,
AddressConfig $addressConfig,
OrderRepositoryInterface $orderRepository,
SessionManagerInterface $session,
array $data = []
) {
parent::__construct($context, $multishipping, $data);
$this->addressConfig = $addressConfig;
$this->orderRepository = $orderRepository;
$this->session = $session;
}
/**
* Returns shipping addresses from quote.
*
* @return array
*/
public function getQuoteShippingAddresses(): array
{
return $this->_multishipping->getQuote()->getAllShippingAddresses();
}
/**
* Returns all failed addresses from quote.
*
* @return array
*/
public function getFailedAddresses(): array
{
$addresses = $this->getQuoteShippingAddresses();
if ($this->getAddressError($this->getQuoteBillingAddress())) {
$addresses[] = $this->getQuoteBillingAddress();
}
return $addresses;
}
/**
* Retrieve order shipping address.
*
* @param int $orderId
* @return OrderAddress|null
*/
public function getOrderShippingAddress(int $orderId)
{
return $this->orderRepository->get($orderId)->getShippingAddress();
}
/**
* Retrieve quote billing address.
*
* @return QuoteAddress
*/
public function getQuoteBillingAddress(): QuoteAddress
{
return $this->getCheckout()->getQuote()->getBillingAddress();
}
/**
* Returns formatted shipping address from placed order.
*
* @param OrderAddress $address
* @return string
*/
public function formatOrderShippingAddress(OrderAddress $address): string
{
return $this->getAddressOneline($address->getData());
}
/**
* Returns formatted shipping address from quote.
*
* @param QuoteAddress $address
* @return string
*/
public function formatQuoteShippingAddress(QuoteAddress $address): string
{
return $this->getAddressOneline($address->getData());
}
/**
* Checks if address type is shipping.
*
* @param QuoteAddress $address
* @return bool
*/
public function isShippingAddress(QuoteAddress $address): bool
{
return $address->getAddressType() === QuoteAddress::ADDRESS_TYPE_SHIPPING;
}
/**
* Get unescaped address formatted as one line string.
*
* @param array $address
* @return string
*/
private function getAddressOneline(array $address): string
{
$renderer = $this->addressConfig->getFormatByCode('oneline')->getRenderer();
return $renderer->renderArray($address);
}
/**
* Returns address error.
*
* @param QuoteAddress $address
* @return string
*/
public function getAddressError(QuoteAddress $address): string
{
$errors = $this->session->getAddressErrors();
return $errors[$address->getId()] ?? '';
}
/**
* Add title to block head.
*
* @throws LocalizedException
* @return Success
*/
protected function _prepareLayout(): Success
{
/** @var Title $pageTitle */
$pageTitle = $this->getLayout()->getBlock('page.main.title');
if ($pageTitle) {
$title = $this->getOrderIds() ? $pageTitle->getPartlySuccessTitle() : $pageTitle->getFailedTitle();
$pageTitle->setPageTitle($title);
}
return parent::_prepareLayout();
}
}
|
kunj1988/Magento2
|
app/code/Magento/Multishipping/Block/Checkout/Results.php
|
PHP
|
gpl-2.0
| 4,850
|
void emesh_post_recv(EMeshComm *c, EMeshUnpack *u) {
UC(comm_post_recv(u->hbuf, c->pp));
}
void emesh_post_send(EMeshPack *p, EMeshComm *c) {
UC(comm_buffer_set(p->nbags, p->hbags, p->hbuf));
UC(comm_post_send(p->hbuf, c->pp));
}
void emesh_wait_recv(EMeshComm *c, EMeshUnpack *u) {
UC(comm_wait_recv(c->pp, u->hbuf));
UC(comm_buffer_get(u->hbuf, u->nbags, u->hbags));
}
void emesh_wait_send(EMeshComm *c) {
UC(comm_wait_send(c->pp));
}
/* momentum */
void emesh_post_recv(EMeshCommM *c, EMeshUnpackM *u) {
UC(comm_post_recv(u->hbuf, c->comm));
}
void emesh_post_send(EMeshPackM *p, EMeshCommM *c) {
UC(comm_buffer_set(p->nbags, p->hbags, p->hbuf));
UC(comm_post_send(p->hbuf, c->comm));
}
void emesh_wait_recv(EMeshCommM *c, EMeshUnpackM *u) {
UC(comm_wait_recv(c->comm, u->hbuf));
UC(comm_buffer_get(u->hbuf, u->nbags, u->hbags));
}
void emesh_wait_send(EMeshCommM *c) {
UC(comm_wait_send(c->comm));
}
|
uDeviceX/uDeviceX
|
src/exch/mesh/imp/com.h
|
C
|
gpl-2.0
| 961
|
// VirtualDub - Video processing and capture application
// Copyright (C) 1998-2001 Avery Lee
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#include "stdafx.h"
#define f_POSITIONCONTROL_CPP
#include <windows.h>
#include <commctrl.h>
#include <vd2/system/vdtypes.h>
#include <vd2/system/fraction.h>
#include <vd2/system/w32assist.h>
#include "resource.h"
#include "oshelper.h"
#include "timeline.h"
#include "prefs.h"
#include "PositionControl.h"
extern HINSTANCE g_hInst;
extern void VDPreferencesSetTimeFormat(int format);
////////////////////////////
extern const char szPositionControlName[]="birdyPositionControl";
enum { uIcon_count=15 };
static const UINT uIconIDs[uIcon_count][2]={
{ IDI_POS_STOP },
{ IDI_POS_PLAY },
{ IDI_POS_PLAYPREVIEW },
{ IDI_POS_START },
{ IDI_POS_BACKWARD },
{ IDI_POS_FORWARD },
{ IDI_POS_END },
{ IDI_POS_PREV_KEY },
{ IDI_POS_NEXT_KEY },
{ IDI_POS_SCENEREV },
{ IDI_POS_SCENEFWD },
{ IDI_POS_MARKIN, IDI_POS_MARKIN2 },
{ IDI_POS_MARKOUT, IDI_POS_MARKOUT2 },
{ IDI_POS_MARKIN, IDI_POS_MARKIN2 },
{ IDI_POS_MARKOUT, IDI_POS_MARKOUT2 },
};
static const UINT uIconIDs_x128[uIcon_count][2]={
{ IDI_POS_STOP_x128 },
{ IDI_POS_PLAY_x128 },
{ IDI_POS_PLAYPREVIEW_x128 },
{ IDI_POS_START_x128 },
{ IDI_POS_BACKWARD_x128 },
{ IDI_POS_FORWARD_x128 },
{ IDI_POS_END_x128 },
{ IDI_POS_PREV_KEY_x128 },
{ IDI_POS_NEXT_KEY_x128 },
{ IDI_POS_SCENEREV_x128 },
{ IDI_POS_SCENEFWD_x128 },
{ IDI_POS_MARKIN_x128, IDI_POS_MARKIN2_x128 },
{ IDI_POS_MARKOUT_x128, IDI_POS_MARKOUT2_x128 },
{ IDI_POS_MARKIN_x128, IDI_POS_MARKIN2_x128 },
{ IDI_POS_MARKOUT_x128, IDI_POS_MARKOUT2_x128 },
};
#undef IDC_START
enum {
IDC_TRACKBAR = 500,
IDC_FRAME = 501,
IDC_STOP = 502,
IDC_PLAY = 503,
IDC_PLAYPREVIEW = 504,
IDC_START = 505,
IDC_BACKWARD = 506,
IDC_FORWARD = 507,
IDC_END = 508,
IDC_KEYPREV = 509,
IDC_KEYNEXT = 510,
IDC_SCENEREV = 511,
IDC_SCENEFWD = 512,
IDC_MARKIN = 513,
IDC_MARKOUT = 514,
IDC_FILTER_MARKIN = 515,
IDC_FILTER_MARKOUT = 516,
};
static const struct {
UINT id;
const char *tip;
} g_posctltips[]={
{ IDC_TRACKBAR, "[Trackbar]\r\n\r\nDrag this to seek to any frame in the movie. Hold down SHIFT to snap to keyframes/I-frames." },
{ IDC_FRAME, "[Frame indicator]\r\n\r\nDisplays the current frame number, timestamp, and frame type.\r\n\r\n"
"[ ] AVI delta frame\r\n"
"[D] AVI dropped frame\r\n"
"[K] AVI key frame\r\n"
"[I] MPEG-1 intra frame\r\n"
"[P] MPEG-1 forward predicted frame\r\n"
"[B] MPEG-1 bidirectionally predicted frame" },
{ IDC_STOP, "[Stop] Stops playback or the current dub operation." },
{ IDC_PLAY, "[Input playback] Starts playback of the input file." },
{ IDC_PLAYPREVIEW, "[Output playback] Starts preview of processed output." },
{ IDC_START, "[Start] Move to the first frame." },
{ IDC_BACKWARD, "[Backward] Back up by one frame." },
{ IDC_FORWARD, "[Forward] Advance by one frame." },
{ IDC_END, "[End] Move to the last frame." },
{ IDC_KEYPREV, "[Key previous] Move to the previous key frame or I-frame." },
{ IDC_KEYNEXT, "[Key next] Move to the next key frame or I-frame." },
{ IDC_SCENEREV, "[Scene reverse] Scan backward for the last scene change." },
{ IDC_SCENEFWD, "[Scene forward] Scan forward for the next scene change." },
{ IDC_MARKIN, "[Mark in] Specify the start for processing or of a selection to delete." },
{ IDC_MARKOUT, "[Mark out] Specify the end for processing or of a selection to delete." },
{ IDC_FILTER_MARKIN, "[Mark in] Specify the start for filter range." },
{ IDC_FILTER_MARKOUT, "[Mark out] Specify the end for filter range." },
};
HBITMAP LoadImageStretch(LPSTR id, int w, int h)
{
HBITMAP bm0 = (HBITMAP)LoadImage(g_hInst, id,IMAGE_BITMAP,0,0,LR_LOADTRANSPARENT|LR_LOADMAP3DCOLORS);
if (!bm0) return 0;
HDC hdc = GetDC(0);
BITMAPINFO bmi = {0};
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = w;
bmi.bmiHeader.biHeight = h;
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biBitCount = 24;
bmi.bmiHeader.biPlanes = 1;
HBITMAP bm1 = CreateDIBSection(0,&bmi,0,0,0,0);
HDC dc0 = CreateCompatibleDC(hdc);
HDC dc1 = CreateCompatibleDC(hdc);
SelectObject(dc0,bm0);
SelectObject(dc1,bm1);
BITMAP bm0_info;
GetObject(bm0,sizeof(BITMAP),&bm0_info);
SetStretchBltMode(dc1,HALFTONE);
StretchBlt(dc1,0,0,w,h,dc0,0,0,bm0_info.bmWidth,bm0_info.bmHeight,SRCCOPY);
ReleaseDC(0, hdc);
DeleteDC(dc1);
DeleteDC(dc0);
DeleteObject(bm0);
return bm1;
}
///////////////////////////////////////////////////////////////////////////
struct VDPositionControlW32 : public vdrefcounted<IVDPositionControl> {
public:
static ATOM Register();
protected:
VDPositionControlW32(HWND hwnd);
~VDPositionControlW32();
int GetNiceHeight();
void SetFrameTypeCallback(IVDPositionControlCallback *pCB);
void SetRange(VDPosition lo, VDPosition hi, bool updateNow);
void SetRangeZoom(bool v, bool updateNow);
VDPosition GetRangeBegin();
VDPosition GetRangeEnd();
VDPosition GetPosition();
void SetPosition(VDPosition pos);
void SetDisplayedPosition(VDPosition pos);
void SetAutoPositionUpdate(bool autoUpdate);
void SetAutoStep(bool autoStep);
bool GetSelection(VDPosition& start, VDPosition& end);
void SetSelection(VDPosition start, VDPosition end, bool updateNow);
bool GetSelection2(VDPosition& start, VDPosition& end);
void SetSelection2(VDPosition start, VDPosition end, bool updateNow);
void SetTimeline(VDTimeline& t);
void SetFrameRate(const VDFraction& frameRate);
void ResetShuttle();
VDEvent<IVDPositionControl, VDPositionControlEventData>& PositionUpdated();
void SetMessage(const wchar_t* s);
protected:
void InternalSetPosition(VDPosition pos, VDPositionControlEventData::EventType eventType);
VDPosition PositionInRange(VDPosition pos);
static LRESULT APIENTRY StaticWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK WndProc(UINT msg, WPARAM wParam, LPARAM lParam);
static BOOL CALLBACK InitChildrenProc(HWND hWnd, LPARAM lParam);
void OnCreate();
void OnSize();
void OnPaint();
void UpdateString(VDPosition pos=-1);
void RecomputeMetrics();
void RecalcThumbRect(VDPosition pos, bool update = true);
bool Notify(UINT code, VDPositionControlEventData::EventType eventType);
void SetTimeFormat(int format);
inline int FrameToPixel(VDPosition pos) {
return VDFloorToInt(mPixelToFrameBias + mPixelsPerFrame * pos);
}
HWND mhwnd;
HMENU mhmenuPopup;
HFONT mFrameFont;
int nFrameCtlHeight;
int nFrameCtlWidth;
VDFraction mFrameRate;
IVDPositionControlCallback *mpCB;
void *pvFTCData;
HFONT mFrameNumberFont;
int mFrameNumberHeight;
int mFrameNumberWidth;
enum {
kBrushCurrentFrame,
kBrushTick,
kBrushTrack,
kBrushSelection,
kBrushSelection2,
kBrushes
};
HBRUSH mBrushes[kBrushes];
VDPosition mPosition;
VDPosition mRangeStart;
VDPosition mRangeEnd;
VDPosition mSelectionStart;
VDPosition mSelectionEnd;
VDPosition mSelection2Start;
VDPosition mSelection2End;
vdfastvector<sint64> marker;
vdfastvector<sint64> edit;
RECT mPositionArea; // track, ticks, bar, and numbers
RECT mTrackArea; // track, ticks, and bar
RECT mTickArea; // just ticks
RECT mTickArea2; // just ticks
RECT mTrack; // just the track
RECT mThumbRect;
int mThumbWidth;
int mTickWidth;
int mButtonSize;
int mGapSize;
double mPixelsPerFrame;
double mPixelToFrameBias;
double mFramesPerPixel;
int mWheelAccum;
int mDragOffsetX;
int mDragAccum;
VDPosition mDragAnchorPos;
enum {
kDragNone,
kDragThumbFast,
kDragThumbSlow
} mDragMode;
bool mbHasPosText;
bool mbHasNavControls;
bool mbHasPlaybackControls;
bool mbHasMarkControls;
bool mbHasSceneControls;
bool mbHasFilterControls;
bool mbButtonIcon;
bool mbAutoFrame;
bool mbAutoStep;
bool mbZoom;
VDEvent<IVDPositionControl, VDPositionControlEventData> mPositionUpdatedEvent;
HICON shIcon1[uIcon_count];
HICON shIcon2[uIcon_count];
};
ATOM VDPositionControlW32::Register() {
WNDCLASS wc;
wc.style = 0;
wc.lpfnWndProc = StaticWndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = sizeof(VDPositionControlW32 *);
wc.hInstance = g_hInst;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground= (HBRUSH)(COLOR_3DFACE+1); //GetStockObject(LTGRAY_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName= POSITIONCONTROLCLASS;
return RegisterClass(&wc);
}
ATOM RegisterPositionControl() {
return VDPositionControlW32::Register();
}
IVDPositionControl *VDGetIPositionControl(VDGUIHandle h) {
return static_cast<IVDPositionControl *>((VDPositionControlW32 *)GetWindowLongPtr((HWND)h, 0));
}
///////////////////////////////////////////////////////////////////////////
VDPositionControlW32::VDPositionControlW32(HWND hwnd)
: mhwnd(hwnd)
, mFrameFont(NULL)
, nFrameCtlHeight(0)
, nFrameCtlWidth(0)
, mFrameRate(0,0)
, mpCB(NULL)
, pvFTCData(NULL)
, mFrameNumberFont(NULL)
, mFrameNumberHeight(0)
, mPosition(0)
, mRangeStart(0)
, mRangeEnd(0)
, mSelectionStart(0)
, mSelectionEnd(-1)
, mSelection2Start(0)
, mSelection2End(-1)
, mButtonSize(0)
, mGapSize(0)
, mPixelsPerFrame(0)
, mPixelToFrameBias(0)
, mFramesPerPixel(0)
, mWheelAccum(0)
, mDragMode(kDragNone)
, mbHasPosText(false)
, mbHasNavControls(false)
, mbHasPlaybackControls(false)
, mbHasMarkControls(false)
, mbHasSceneControls(false)
, mbHasFilterControls(false)
, mbAutoFrame(true)
, mbAutoStep(false)
, mbZoom(false)
{
mBrushes[kBrushCurrentFrame] = CreateSolidBrush(RGB(255,0,0));
mBrushes[kBrushTick] = CreateSolidBrush(RGB(0,0,0));
mBrushes[kBrushTrack] = CreateSolidBrush(RGB(128,128,128));
mBrushes[kBrushSelection] = CreateSolidBrush(RGB(192,224,255));
mBrushes[kBrushSelection2] = CreateSolidBrush(RGB(247,148,29));
SetRect(&mThumbRect, 0, 0, 0, 0);
SetRect(&mTrack, 0, 0, 0, 0);
SetRect(&mTrackArea, 0, 0, 0, 0);
SetRect(&mPositionArea, 0, 0, 0, 0);
mhmenuPopup = 0;
}
VDPositionControlW32::~VDPositionControlW32() {
if (mFrameFont)
DeleteObject(mFrameFont);
if (mFrameNumberFont)
DeleteObject(mFrameNumberFont);
if (mhmenuPopup)
DestroyMenu(mhmenuPopup);
{for(int i=0; i<kBrushes; ++i) {
if (mBrushes[i])
DeleteObject(mBrushes[i]);
}}
{for(int i=0; i<uIcon_count; i++) {
if(shIcon1[i]) DeleteObject(shIcon1[i]);
if(shIcon2[i]) DeleteObject(shIcon2[i]);
}}
}
///////////////////////////////////////////////////////////////////////////
int VDPositionControlW32::GetNiceHeight() {
int s = 0;
if (mbHasPosText) s += mButtonSize;
s += mFrameNumberHeight;
s += mFrameNumberHeight*7/4;
//if (mbHasPosText) s += mFrameNumberHeight*7/4; else s += mFrameNumberHeight*14/12;
return s;
}
void VDPositionControlW32::SetFrameTypeCallback(IVDPositionControlCallback *pCB) {
mpCB = pCB;
}
void VDPositionControlW32::SetRange(VDPosition lo, VDPosition hi, bool updateNow) {
if (lo != mRangeStart || hi != mRangeEnd) {
mRangeStart = lo;
mRangeEnd = hi;
if (mPosition < mRangeStart)
mPosition = mRangeStart;
if (mPosition > mRangeEnd)
mPosition = mRangeEnd;
if (mSelectionStart < mRangeStart)
mSelectionStart = mRangeStart;
if (mSelectionEnd > mRangeEnd)
mSelectionEnd = mRangeEnd;
if (mSelection2Start < mRangeStart)
mSelection2Start = mRangeStart;
if (mSelection2End > mRangeEnd)
mSelection2End = mRangeEnd;
RecomputeMetrics();
UpdateString();
}
}
void VDPositionControlW32::SetRangeZoom(bool v, bool updateNow) {
mbZoom = v;
RecomputeMetrics();
}
VDPosition VDPositionControlW32::GetRangeBegin() {
return mRangeStart;
}
VDPosition VDPositionControlW32::GetRangeEnd() {
return mRangeEnd;
}
VDPosition VDPositionControlW32::GetPosition() {
return mPosition;
}
void VDPositionControlW32::SetPosition(VDPosition pos) {
InternalSetPosition(pos, VDPositionControlEventData::kEventJump);
if (mhwnd)
UpdateWindow(mhwnd);
}
VDPosition VDPositionControlW32::PositionInRange(VDPosition pos) {
if (pos < mRangeStart)
pos = mRangeStart;
if (pos > mRangeEnd)
pos = mRangeEnd;
return pos;
}
void VDPositionControlW32::InternalSetPosition(VDPosition pos, VDPositionControlEventData::EventType eventType) {
if (!mbZoom)
pos = PositionInRange(pos);
if (pos != mPosition) {
mPosition = pos;
RecalcThumbRect(pos, true);
VDPositionControlEventData eventData;
eventData.mPosition = mPosition;
eventData.mEventType = eventType;
mPositionUpdatedEvent.Raise(this, eventData);
}
UpdateString();
}
void VDPositionControlW32::SetDisplayedPosition(VDPosition pos) {
UpdateString(pos);
RecalcThumbRect(pos, true);
if (mhwnd)
UpdateWindow(mhwnd);
}
void VDPositionControlW32::SetAutoPositionUpdate(bool autoUpdate) {
if (autoUpdate != mbAutoFrame) {
mbAutoFrame = autoUpdate;
if (autoUpdate)
RecalcThumbRect(mPosition, true);
}
}
void VDPositionControlW32::SetAutoStep(bool autoStep) {
mbAutoStep = autoStep;
}
bool VDPositionControlW32::GetSelection(VDPosition& start, VDPosition& end) {
if (mSelectionStart < mSelectionEnd) {
start = mSelectionStart;
end = mSelectionEnd;
return true;
}
return false;
}
bool VDPositionControlW32::GetSelection2(VDPosition& start, VDPosition& end) {
if (mSelection2Start < mSelection2End) {
start = mSelection2Start;
end = mSelection2End;
return true;
}
return false;
}
void VDPositionControlW32::SetSelection(VDPosition start, VDPosition end, bool updateNow) {
const int tickHeight = mTickArea.bottom - mTickArea.top;
// wipe old selection
if (mhwnd && mSelectionStart <= mSelectionEnd) {
int selx1 = FrameToPixel(mSelectionStart);
int selx2 = FrameToPixel(mSelectionEnd);
RECT rOld = { selx1 - tickHeight, mTrack.top, selx2 + tickHeight, mTickArea.bottom };
InvalidateRect(mhwnd, &rOld, TRUE);
}
// render new selection
mSelectionStart = start;
mSelectionEnd = end;
if (mhwnd && mSelectionStart <= mSelectionEnd) {
int selx1 = FrameToPixel(mSelectionStart);
int selx2 = FrameToPixel(mSelectionEnd);
RECT rNew = { selx1 - tickHeight, mTrack.top, selx2 + tickHeight, mTickArea.bottom };
InvalidateRect(mhwnd, &rNew, TRUE);
}
}
void VDPositionControlW32::SetSelection2(VDPosition start, VDPosition end, bool updateNow) {
const int tickHeight = mTickArea2.bottom - mTickArea2.top;
// wipe old selection
if (mhwnd && mSelection2Start <= mSelection2End) {
int selx1 = FrameToPixel(mSelection2Start);
int selx2 = FrameToPixel(mSelection2End);
RECT rOld = { selx1 - tickHeight, mTickArea2.top, selx2 + tickHeight, mTickArea2.bottom };
InvalidateRect(mhwnd, &rOld, TRUE);
}
// render new selection
mSelection2Start = start;
mSelection2End = end;
if (mhwnd && mSelection2Start <= mSelection2End) {
int selx1 = FrameToPixel(mSelection2Start);
int selx2 = FrameToPixel(mSelection2End);
RECT rNew = { selx1 - tickHeight, mTickArea2.top, selx2 + tickHeight, mTickArea2.bottom };
InvalidateRect(mhwnd, &rNew, TRUE);
}
}
void VDPositionControlW32::SetTimeline(VDTimeline& t) {
edit.clear();
VDPosition p0 = 0;
while(1){
p0 = t.GetNextEdit(p0);
if(p0==-1) break;
edit.push_back(p0);
}
marker.clear();
sint64 prev = -1;
{for(int i=0; i<t.GetMarkerCount(); i++){
sint64 p = t.GetMarker(i);
if(p!=-1 && p!=prev){
marker.push_back(p);
prev = p;
}
}}
InvalidateRect(mhwnd, &mTrack, FALSE);
}
void VDPositionControlW32::SetFrameRate(const VDFraction& frameRate) {
mFrameRate = frameRate;
if (mhwnd)
UpdateString();
}
void VDPositionControlW32::ResetShuttle() {
if (!mhwnd)
return;
CheckDlgButton(mhwnd, IDC_SCENEREV, BST_UNCHECKED);
CheckDlgButton(mhwnd, IDC_SCENEFWD, BST_UNCHECKED);
}
VDEvent<IVDPositionControl, VDPositionControlEventData>& VDPositionControlW32::PositionUpdated() {
return mPositionUpdatedEvent;
}
///////////////////////////////////////////////////////////////////////////
BOOL CALLBACK VDPositionControlW32::InitChildrenProc(HWND hWnd, LPARAM lParam) {
VDPositionControlW32 *pThis = (VDPositionControlW32 *)lParam;
UINT id;
int fill = GetSysColor(COLOR_BTNFACE);
int fill_r = fill & 0xFF;
int fill_g = (fill & 0xFF00) >> 8;
int fill_b = (fill & 0xFF0000) >> 16;
int fill_y = ((fill_b * 19 + fill_g * 183 + fill_r * 54) >> 8);
switch(id = GetWindowLong(hWnd, GWL_ID)) {
case IDC_STOP:
case IDC_PLAY:
case IDC_PLAYPREVIEW:
case IDC_START:
case IDC_BACKWARD:
case IDC_FORWARD:
case IDC_END:
case IDC_KEYPREV:
case IDC_KEYNEXT:
case IDC_SCENEREV:
case IDC_SCENEFWD:
case IDC_MARKIN:
case IDC_MARKOUT:
case IDC_FILTER_MARKIN:
case IDC_FILTER_MARKOUT:
{
int i = id - IDC_STOP;
void* icon = pThis->shIcon1[i];
void* icon_dark = pThis->shIcon2[i];
if (fill_y < 128 && icon_dark) icon = icon_dark;
SendMessage(hWnd, BM_SETIMAGE, pThis->mbButtonIcon ? IMAGE_ICON:IMAGE_BITMAP, (LPARAM)icon);
}
break;
case IDC_FRAME:
SendMessage(hWnd, WM_SETFONT, (WPARAM)pThis->mFrameFont, (LPARAM)MAKELONG(FALSE, 0));
break;
}
return TRUE;
}
LRESULT APIENTRY VDPositionControlW32::StaticWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
VDPositionControlW32 *pcd = (VDPositionControlW32 *)GetWindowLongPtr(hwnd, 0);
switch(msg) {
case WM_NCCREATE:
if (!(pcd = new VDPositionControlW32(hwnd)))
return FALSE;
pcd->AddRef();
SetWindowLongPtr(hwnd, 0, (LONG_PTR)pcd);
break;
case WM_NCDESTROY:
pcd->mhwnd = NULL;
pcd->Release();
SetWindowLongPtr(hwnd, 0, 0);
pcd = NULL;
break;
}
return pcd ? pcd->WndProc(msg, wParam, lParam) : DefWindowProc(hwnd, msg, wParam, lParam);
}
LRESULT CALLBACK VDPositionControlW32::WndProc(UINT msg, WPARAM wParam, LPARAM lParam) {
switch(msg) {
case WM_CREATE:
OnCreate();
// fall through
case WM_SIZE:
OnSize();
break;
case WM_SYSCOLORCHANGE:
if (mFrameFont)
EnumChildWindows(mhwnd, (WNDENUMPROC)InitChildrenProc, (LPARAM)this);
break;
case WM_PAINT:
OnPaint();
return 0;
case WM_NOTIFY:
if (TTN_GETDISPINFO == ((LPNMHDR)lParam)->code) {
NMTTDISPINFO *lphdr = (NMTTDISPINFO *)lParam;
UINT id = (lphdr->uFlags & TTF_IDISHWND) ? GetWindowLong((HWND)lphdr->hdr.idFrom, GWL_ID) : lphdr->hdr.idFrom;
*lphdr->lpszText = 0;
SendMessage(lphdr->hdr.hwndFrom, TTM_SETMAXTIPWIDTH, 0, 5000);
for(int i=0; i<sizeof g_posctltips/sizeof g_posctltips[0]; ++i) {
if (id == g_posctltips[i].id)
lphdr->lpszText = const_cast<char *>(g_posctltips[i].tip);
}
return TRUE;
}
break;
case WM_COMMAND:
{
UINT cmd;
VDPositionControlEventData::EventType eventType = VDPositionControlEventData::kEventNone;
switch(LOWORD(wParam)) {
case IDC_STOP: cmd = PCN_STOP; break;
case IDC_PLAY: cmd = PCN_PLAY; break;
case IDC_PLAYPREVIEW: cmd = PCN_PLAYPREVIEW; break;
case IDC_MARKIN: cmd = PCN_MARKIN; break;
case IDC_MARKOUT: cmd = PCN_MARKOUT; break;
case IDC_FILTER_MARKIN: cmd = PCN_MARKIN; break;
case IDC_FILTER_MARKOUT: cmd = PCN_MARKOUT; break;
case IDC_START:
cmd = PCN_START;
if (mbAutoStep)
InternalSetPosition(mRangeStart, VDPositionControlEventData::kEventJumpToStart);
break;
case IDC_BACKWARD:
cmd = PCN_BACKWARD;
if (mbAutoStep)
InternalSetPosition(mPosition - 1, VDPositionControlEventData::kEventJumpToPrev);
break;
case IDC_FORWARD:
cmd = PCN_FORWARD;
if (mbAutoStep)
InternalSetPosition(mPosition + 1, VDPositionControlEventData::kEventJumpToNext);
break;
case IDC_END:
cmd = PCN_END;
if (mbAutoStep)
InternalSetPosition(mRangeEnd, VDPositionControlEventData::kEventJumpToEnd);
break;
case IDC_KEYPREV:
cmd = PCN_KEYPREV;
eventType = VDPositionControlEventData::kEventJumpToPrevKey;
break;
case IDC_KEYNEXT:
cmd = PCN_KEYNEXT;
eventType = VDPositionControlEventData::kEventJumpToNextKey;
break;
case IDC_SCENEREV:
cmd = PCN_SCENEREV;
if (BST_UNCHECKED!=SendMessage((HWND)lParam, BM_GETCHECK, 0, 0)) {
if (IsDlgButtonChecked(mhwnd, IDC_SCENEFWD))
CheckDlgButton(mhwnd, IDC_SCENEFWD, BST_UNCHECKED);
} else
cmd = PCN_SCENESTOP;
break;
case IDC_SCENEFWD:
cmd = PCN_SCENEFWD;
if (BST_UNCHECKED!=SendMessage((HWND)lParam, BM_GETCHECK, 0, 0)) {
if (IsDlgButtonChecked(mhwnd, IDC_SCENEREV))
CheckDlgButton(mhwnd, IDC_SCENEREV, BST_UNCHECKED);
} else
cmd = PCN_SCENESTOP;
break;
case ID_POS_COPY:
{
HWND hwndFrame = GetDlgItem(mhwnd, IDC_FRAME);
VDStringW s(VDGetWindowTextW32(hwndFrame));
VDCopyTextToClipboard(s.c_str());
}
return 0;
case ID_TIMEFORMAT_H:
SetTimeFormat(pref_time_hmst);
return 0;
case ID_TIMEFORMAT_HR:
SetTimeFormat(pref_time_hmst_r);
return 0;
case ID_TIMEFORMAT_M:
SetTimeFormat(pref_time_m);
return 0;
case ID_TIMEFORMAT_MR:
SetTimeFormat(pref_time_m_r);
return 0;
case ID_TIMEFORMAT_S:
SetTimeFormat(pref_time_s);
return 0;
case ID_TIMEFORMAT_SR:
SetTimeFormat(pref_time_s_r);
return 0;
case ID_TIMEFORMAT_MS:
SetTimeFormat(pref_time_ms);
return 0;
case ID_TIMEFORMAT_MSR:
SetTimeFormat(pref_time_ms_r);
return 0;
case ID_TIMEFORMAT_PERCENT:
SetTimeFormat(pref_time_r100);
return 0;
default:
return 0;
}
LRESULT r = SendMessage(GetParent(mhwnd), WM_COMMAND, MAKELONG(GetWindowLong(mhwnd, GWL_ID), cmd), (LPARAM)mhwnd);
if(r==-1) switch(LOWORD(wParam)) {
case IDC_SCENEREV:
case IDC_SCENEFWD:
CheckDlgButton(mhwnd,LOWORD(wParam),BST_UNCHECKED);
break;
}
}
break;
case WM_LBUTTONDOWN:
{
POINT pt = {(SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam)};
if (PtInRect(&mThumbRect, pt)) {
mDragOffsetX = pt.x - mThumbRect.left;
if (mDragMode == kDragThumbSlow)
ShowCursor(TRUE);
mDragMode = kDragThumbFast;
SetCapture(mhwnd);
if (Notify(PCN_BEGINTRACK, VDPositionControlEventData::kEventNone)) {
InvalidateRect(mhwnd, &mThumbRect, TRUE);
} else {
mDragMode = kDragNone;
ReleaseCapture();
}
} else if (PtInRect(&mPositionArea, pt)) {
VDPosition prev = mPosition;
extern bool VDPreferencesGetTimelinePageMode();
extern int VDPreferencesGetTimelinePageSize();
if (VDPreferencesGetTimelinePageMode()) {
if(pt.x>mThumbRect.right) mPosition += VDPreferencesGetTimelinePageSize();
if(pt.x<mThumbRect.left) mPosition -= VDPreferencesGetTimelinePageSize();
} else {
mPosition = mRangeStart + (sint64)floor((pt.x - mTrack.left) * mFramesPerPixel + 0.5);
}
if (mPosition < mRangeStart)
mPosition = mRangeStart;
if (mPosition > mRangeEnd)
mPosition = mRangeEnd;
if (Notify(PCN_THUMBPOSITION, VDPositionControlEventData::kEventJump)) {
if (mbAutoFrame)
UpdateString();
RecalcThumbRect(mPosition);
InvalidateRect(mhwnd, &mThumbRect, TRUE);
} else {
mPosition = prev;
}
} else if (mbHasPosText) {
HWND hwndFrame = GetDlgItem(mhwnd, IDC_FRAME);
RECT r;
GetWindowRect(hwndFrame,&r);
MapWindowPoints(0,mhwnd,(POINT*)&r,2);
if (PtInRect(&r, pt)) {
SendMessage(GetParent(mhwnd), WM_COMMAND, MAKELONG(GetWindowLong(mhwnd, GWL_ID), PCN_JUMPTO), (LPARAM)mhwnd);
}
}
}
break;
case WM_RBUTTONDOWN:
{
POINT pt = {(SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam)};
if (PtInRect(&mThumbRect, pt)) {
mDragOffsetX = pt.x - mThumbRect.left;
mDragAnchorPos = mPosition;
bool hideCursor = false;
if (mDragMode != kDragThumbSlow) {
hideCursor = true;
mDragMode = kDragThumbSlow;
}
mDragAccum = 0;
SetCapture(mhwnd);
if (Notify(PCN_BEGINTRACK, VDPositionControlEventData::kEventNone)) {
InvalidateRect(mhwnd, &mThumbRect, TRUE);
if (hideCursor)
ShowCursor(FALSE);
} else {
mDragMode = kDragNone;
ReleaseCapture();
}
} else if (mbHasPosText && mhmenuPopup) {
HWND hwndFrame = GetDlgItem(mhwnd, IDC_FRAME);
RECT r;
GetWindowRect(hwndFrame,&r);
MapWindowPoints(0,mhwnd,(POINT*)&r,2);
if (PtInRect(&r, pt)) {
HMENU popup = GetSubMenu(mhmenuPopup, 0);
ClientToScreen(mhwnd, &pt);
TrackPopupMenu(popup, TPM_RIGHTALIGN | TPM_BOTTOMALIGN, pt.x, pt.y, 0, mhwnd, NULL);
}
}
}
break;
case WM_MOUSEMOVE:
if (mDragMode == kDragThumbFast) {
POINT pt = {(SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam)};
int x = pt.x - mDragOffsetX;
if (x < mTrack.left - mThumbWidth)
x = mTrack.left - mThumbWidth;
if (x > mTrack.right - mThumbWidth)
x = mTrack.right - mThumbWidth;
if (x != mThumbRect.left) {
if (mbAutoFrame) {
InvalidateRect(mhwnd, &mThumbRect, TRUE);
mThumbRect.right = x + (mThumbRect.right - mThumbRect.left);
mThumbRect.left = x;
InvalidateRect(mhwnd, &mThumbRect, TRUE);
UpdateWindow(mhwnd);
}
sint64 pos = mRangeStart + VDRoundToInt64((x - mTrack.left + mThumbWidth) * mFramesPerPixel);
if (pos > mRangeEnd)
pos = mRangeEnd;
if (pos < mRangeStart)
pos = mRangeStart;
if (mPosition != pos) {
mPosition = pos;
if (mbAutoFrame)
UpdateString();
Notify(PCN_THUMBTRACK, VDPositionControlEventData::kEventTracking);
}
}
} else if (mDragMode == kDragThumbSlow) {
POINT pt = {(SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam)};
mDragAccum += (pt.x - (mThumbRect.left + mDragOffsetX));
int delta = mDragAccum / 8;
mDragAccum -= delta * 8;
if (delta) {
mDragAnchorPos = PositionInRange(mDragAnchorPos + delta);
SetPosition(mDragAnchorPos);
Notify(PCN_THUMBTRACK, VDPositionControlEventData::kEventTracking);
}
pt.x = mThumbRect.left + mDragOffsetX;
ClientToScreen(mhwnd, &pt);
SetCursorPos(pt.x, pt.y);
}
break;
case WM_CAPTURECHANGED:
if ((HWND)lParam == mhwnd)
break;
case WM_MOUSELEAVE:
case WM_RBUTTONUP:
case WM_LBUTTONUP:
if (mDragMode) {
if (mDragMode == kDragThumbSlow)
ShowCursor(TRUE);
mDragMode = kDragNone;
ReleaseCapture();
Notify(PCN_ENDTRACK, VDPositionControlEventData::kEventNone);
InvalidateRect(mhwnd, &mThumbRect, TRUE);
}
break;
case WM_MOUSEWHEEL:
{
mWheelAccum -= (SHORT)HIWORD(wParam);
int increments = mWheelAccum / WHEEL_DELTA;
if (increments) {
mWheelAccum -= WHEEL_DELTA * increments;
SetPosition(PositionInRange(mPosition + increments));
if (increments < 0)
Notify(PCN_THUMBPOSITIONPREV, VDPositionControlEventData::kEventJump);
else
Notify(PCN_THUMBPOSITIONNEXT, VDPositionControlEventData::kEventJump);
}
}
return 0;
}
return DefWindowProc(mhwnd, msg, wParam, lParam);
}
extern int VDPreferencesGetTimelineScaleTrack();
extern int VDPreferencesGetTimelineScaleInfo();
extern int VDPreferencesGetTimelineScaleButtons();
void VDPositionControlW32::OnCreate() {
int mTrackScale = VDPreferencesGetTimelineScaleTrack();
int mTextScale = VDPreferencesGetTimelineScaleInfo();
int mButtonScale = VDPreferencesGetTimelineScaleButtons();
DWORD dwStyles;
TOOLINFO ti;
HWND hwndTT;
dwStyles = GetWindowLong(mhwnd, GWL_STYLE);
mbHasPlaybackControls = !!(dwStyles & PCS_PLAYBACK);
mbHasMarkControls = !!(dwStyles & PCS_MARK);
mbHasSceneControls = !!(dwStyles & PCS_SCENE);
mbHasNavControls = !(dwStyles & PCS_XNAV);
mbHasPosText = !(dwStyles & PCS_XNAV);
mbHasFilterControls = !!(dwStyles & PCS_FILTER);
// We use 24px at 96 dpi.
int ht = MulDiv(24, mButtonScale, 100);
int gap = MulDiv(8, mButtonScale, 100);
mFrameFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
nFrameCtlHeight = MulDiv(18, mTextScale, 100);
nFrameCtlWidth = MulDiv(320, mTextScale, 100);
if (mFrameFont) {
if (HDC hdc = GetDC(mhwnd)) {
ht = MulDiv(GetDeviceCaps(hdc, LOGPIXELSY), ht, 96);
gap = MulDiv(GetDeviceCaps(hdc, LOGPIXELSX), gap, 96);
TEXTMETRIC tm;
int pad = 2*GetSystemMetrics(SM_CYEDGE);
int availHeight = ht;
if (mTextScale!=100) {
LOGFONT lf;
if (GetObject(mFrameFont, sizeof lf, &lf)) {
lf.lfHeight = MulDiv(lf.lfHeight,mTextScale,100);
HFONT hFont = CreateFontIndirect(&lf);
if (hFont)
mFrameFont = hFont; // the old font was a stock object, so it doesn't need to be deleted
}
}
HGDIOBJ hgoFont = SelectObject(hdc, mFrameFont);
if (GetTextMetrics(hdc, &tm)) {
LOGFONT lf;
nFrameCtlHeight = tm.tmHeight + tm.tmInternalLeading + pad;
if (nFrameCtlHeight > availHeight && GetObject(mFrameFont, sizeof lf, &lf)) {
lf.lfHeight = availHeight - pad;
nFrameCtlHeight = availHeight;
HFONT hFont = CreateFontIndirect(&lf);
if (hFont) {
DeleteObject(mFrameFont);
mFrameFont = hFont;
}
}
}
nFrameCtlHeight = (nFrameCtlHeight+1) & ~1;
SelectObject(hdc, hgoFont);
ReleaseDC(mhwnd, hdc);
}
}
mButtonSize = ht;
mGapSize = gap;
mFrameNumberFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
mFrameNumberHeight = 18;
mFrameNumberWidth = 8;
if (mFrameNumberFont) {
if (HDC hdc = GetDC(mhwnd)) {
if (mTrackScale!=100) {
LOGFONT lf;
if (GetObject(mFrameNumberFont, sizeof lf, &lf)) {
lf.lfHeight = MulDiv(lf.lfHeight,mTrackScale,100);
HFONT hFont = CreateFontIndirect(&lf);
if (hFont)
mFrameNumberFont = hFont; // the old font was a stock object, so it doesn't need to be deleted
}
}
TEXTMETRIC tm;
HGDIOBJ hgoFont = SelectObject(hdc, mFrameNumberFont);
if (GetTextMetrics(hdc, &tm))
mFrameNumberHeight = tm.tmHeight + tm.tmInternalLeading;
SIZE siz;
if (GetTextExtentPoint32(hdc, "0123456789", 10, &siz))
mFrameNumberWidth = (siz.cx + 9) / 10;
SelectObject(hdc, hgoFont);
ReleaseDC(mhwnd, hdc);
}
}
mThumbWidth = mFrameNumberHeight * 5 / 12;
mTickWidth = mFrameNumberHeight / 14;
if (mTickWidth<1) mTickWidth = 1;
if (mbHasPosText) {
CreateWindowEx(WS_EX_STATICEDGE,"STATIC",NULL,WS_CHILD|WS_VISIBLE,0,0,0,ht,mhwnd,(HMENU)IDC_FRAME,g_hInst,NULL);
mhmenuPopup = LoadMenu(g_hInst, MAKEINTRESOURCE(IDR_POSITION_MENU));
}
mbButtonIcon = true;
int iconSize = 16;
int buttonStyle = BS_ICON;
if (mButtonSize>32) {
mbButtonIcon = false;
iconSize = mButtonSize*20/24;
buttonStyle = BS_BITMAP;
}
if (mbHasPlaybackControls || mbHasNavControls || mbHasSceneControls || mbHasMarkControls || mbHasFilterControls) {
for(int i=0; i<uIcon_count; i++) {
shIcon1[i] = 0;
shIcon2[i] = 0;
if (mbButtonIcon) {
int id_light = uIconIDs[i][0];
int id_dark = uIconIDs[i][1];
if (!(shIcon1[i] = (HICON)LoadImage(g_hInst, MAKEINTRESOURCE(id_light),IMAGE_ICON,0,0,0))) {
_RPT1(0,"PositionControl: load failure on icon #%d\n",i+1);
}
if (id_dark && !(shIcon2[i] = (HICON)LoadImage(g_hInst, MAKEINTRESOURCE(id_dark),IMAGE_ICON,0,0,0))) {
_RPT1(0,"PositionControl: load failure on icon #%d\n",i+1);
}
} else {
int id_light = uIconIDs_x128[i][0];
int id_dark = uIconIDs_x128[i][1];
if (!(shIcon1[i] = (HICON)LoadImageStretch(MAKEINTRESOURCE(id_light),iconSize,iconSize))) {
_RPT1(0,"PositionControl: load failure on icon #%d\n",i+1);
}
if (id_dark && !(shIcon2[i] = (HICON)LoadImageStretch(MAKEINTRESOURCE(id_dark),iconSize,iconSize))) {
_RPT1(0,"PositionControl: load failure on icon #%d\n",i+1);
}
}
}
}
if (mbHasPlaybackControls) {
CreateWindowEx(0 ,"BUTTON" ,NULL,WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | buttonStyle ,0,0,ht,ht,mhwnd, (HMENU)IDC_STOP , g_hInst, NULL);
CreateWindowEx(0 ,"BUTTON" ,NULL,WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | buttonStyle ,0,0,ht,ht,mhwnd, (HMENU)IDC_PLAY , g_hInst, NULL);
CreateWindowEx(0 ,"BUTTON" ,NULL,WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | buttonStyle ,0,0,ht,ht,mhwnd, (HMENU)IDC_PLAYPREVIEW , g_hInst, NULL);
}
if (mbHasNavControls) {
CreateWindowEx(0 ,"BUTTON" ,NULL,WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | buttonStyle ,0,0,ht,ht,mhwnd, (HMENU)IDC_START , g_hInst, NULL);
CreateWindowEx(0 ,"BUTTON" ,NULL,WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | buttonStyle ,0,0,ht,ht,mhwnd, (HMENU)IDC_BACKWARD , g_hInst, NULL);
CreateWindowEx(0 ,"BUTTON" ,NULL,WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | buttonStyle ,0,0,ht,ht,mhwnd, (HMENU)IDC_FORWARD , g_hInst, NULL);
CreateWindowEx(0 ,"BUTTON" ,NULL,WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | buttonStyle ,0,0,ht,ht,mhwnd, (HMENU)IDC_END , g_hInst, NULL);
CreateWindowEx(0 ,"BUTTON" ,NULL,WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | buttonStyle ,0,0,ht,ht,mhwnd, (HMENU)IDC_KEYPREV , g_hInst, NULL);
CreateWindowEx(0 ,"BUTTON" ,NULL,WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | buttonStyle ,0,0,ht,ht,mhwnd, (HMENU)IDC_KEYNEXT , g_hInst, NULL);
}
if (mbHasSceneControls) {
CreateWindowEx(0 ,"BUTTON" ,NULL,WS_CHILD | WS_VISIBLE | BS_AUTOCHECKBOX | BS_PUSHLIKE | buttonStyle ,0,0,ht,ht,mhwnd, (HMENU)IDC_SCENEREV, g_hInst, NULL);
CreateWindowEx(0 ,"BUTTON" ,NULL,WS_CHILD | WS_VISIBLE | BS_AUTOCHECKBOX | BS_PUSHLIKE | buttonStyle ,0,0,ht,ht,mhwnd, (HMENU)IDC_SCENEFWD, g_hInst, NULL);
}
if (mbHasMarkControls) {
CreateWindowEx(0 ,"BUTTON" ,NULL,WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | buttonStyle ,0,0,ht,ht,mhwnd, (HMENU)IDC_MARKIN , g_hInst, NULL);
CreateWindowEx(0 ,"BUTTON" ,NULL,WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | buttonStyle ,0,0,ht,ht,mhwnd, (HMENU)IDC_MARKOUT , g_hInst, NULL);
}
if (mbHasFilterControls) {
CreateWindowEx(0 ,"BUTTON" ,NULL,WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | buttonStyle ,0,0,ht,ht,mhwnd, (HMENU)IDC_FILTER_MARKIN , g_hInst, NULL);
CreateWindowEx(0 ,"BUTTON" ,NULL,WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | buttonStyle ,0,0,ht,ht,mhwnd, (HMENU)IDC_FILTER_MARKOUT , g_hInst, NULL);
}
if (mFrameFont)
EnumChildWindows(mhwnd, (WNDENUMPROC)InitChildrenProc, (LPARAM)this);
// Create tooltip control.
hwndTT = CreateWindowEx(WS_EX_TOPMOST, TOOLTIPS_CLASS, NULL, WS_POPUP|TTS_NOPREFIX|TTS_ALWAYSTIP,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
mhwnd, NULL, g_hInst, NULL);
if (hwndTT) {
SetWindowPos(hwndTT, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
SendMessage(hwndTT, TTM_SETDELAYTIME, TTDT_AUTOMATIC, MAKELONG(2000, 0));
SendMessage(hwndTT, TTM_SETDELAYTIME, TTDT_RESHOW, MAKELONG(2000, 0));
ti.cbSize = sizeof(TOOLINFO);
ti.uFlags = TTF_SUBCLASS | TTF_IDISHWND;
ti.hwnd = mhwnd;
ti.lpszText = LPSTR_TEXTCALLBACK;
for(int i=0; i<sizeof g_posctltips/sizeof g_posctltips[0]; ++i) {
ti.uId = (WPARAM)GetDlgItem(mhwnd, g_posctltips[i].id);
if (ti.uId)
SendMessage(hwndTT, TTM_ADDTOOL, 0, (LPARAM)&ti);
}
}
}
void VDPositionControlW32::UpdateString(VDPosition pos) {
if (!mbHasPosText) return;
wchar_t buf[512];
if (pos < 0)
pos = mPosition;
bool success = false;
if (mpCB)
success = mpCB->GetFrameString(buf, sizeof buf / sizeof buf[0], pos);
if (!success) {
if (mFrameRate.getLo()) {
int ms, sec, min;
long ticks = (long)mFrameRate.scale64ir(pos * 1000);
ms = ticks %1000; ticks /= 1000;
sec = ticks % 60; ticks /= 60;
min = ticks % 60; ticks /= 60;
success = (unsigned)swprintf(buf, sizeof buf / sizeof buf[0], L" Frame %I64d (%d:%02d:%02d.%03d)", (sint64)pos, ticks, min, sec, ms) < sizeof buf / sizeof buf[0];
} else
success = (unsigned)swprintf(buf, sizeof buf / sizeof buf[0], L" Frame %I64d", (sint64)pos) < sizeof buf / sizeof buf[0];
}
if (success) {
HWND hwndFrame = GetDlgItem(mhwnd, IDC_FRAME);
VDSetWindowTextW32(hwndFrame, buf);
}
}
void VDPositionControlW32::SetTimeFormat(int format) {
VDPreferencesSetTimeFormat(format);
UpdateString();
Notify(PCN_FORMAT, VDPositionControlEventData::kEventNone);
}
void VDPositionControlW32::SetMessage(const wchar_t* s) {
if (!mbHasPosText) return;
HWND hwndFrame = GetDlgItem(mhwnd, IDC_FRAME);
VDSetWindowTextW32(hwndFrame, s);
}
void VDPositionControlW32::OnSize() {
RECT wndr;
UINT id;
int x, y;
HWND hwndButton;
GetClientRect(mhwnd, &wndr);
RecomputeMetrics();
// Reposition controls
y = wndr.bottom - mButtonSize;
x = 0;
if (mbHasPlaybackControls) {
for(id = IDC_STOP; id < IDC_START; id++) {
SetWindowPos(GetDlgItem(mhwnd, id), NULL, x, y, 0, 0, SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOZORDER);
x += mButtonSize;
}
x+=mGapSize;
}
if (mbHasNavControls) {
for(id = IDC_START; id < IDC_MARKIN; id++) {
if (hwndButton = GetDlgItem(mhwnd,id)) {
SetWindowPos(hwndButton, NULL, x, y, 0, 0, SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOZORDER);
x += mButtonSize;
}
}
x+=mGapSize;
}
if (mbHasMarkControls) {
for(id = IDC_MARKIN; id <= IDC_MARKOUT; id++) {
SetWindowPos(GetDlgItem(mhwnd, id), NULL, x, y, 0, 0, SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOZORDER);
x += mButtonSize;
}
x+=mGapSize;
}
if (mbHasFilterControls) {
for(id = IDC_FILTER_MARKIN; id <= IDC_FILTER_MARKOUT; id++) {
SetWindowPos(GetDlgItem(mhwnd, id), NULL, x, y, 0, 0, SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOZORDER);
x += mButtonSize;
}
x+=mGapSize;
}
if (mbHasPosText) {
int width = std::min<int>(wndr.right - x, nFrameCtlWidth);
SetWindowPos(GetDlgItem(mhwnd, IDC_FRAME), NULL, x, y+((mButtonSize - nFrameCtlHeight)>>1), width, nFrameCtlHeight, SWP_NOACTIVATE|SWP_NOZORDER);
}
}
void VDPositionControlW32::OnPaint() {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(mhwnd, &ps);
if (!hdc) // hrm... this is bad
return;
HGDIOBJ hOldFont = SelectObject(hdc, mFrameNumberFont);
SetBkMode(hdc, TRANSPARENT);
SetTextColor(hdc, GetSysColor(COLOR_WINDOWTEXT));
SetTextAlign(hdc, TA_TOP | TA_CENTER);
char buf[64];
RECT rClient;
VDVERIFY(GetClientRect(mhwnd, &rClient));
int trackRight = mTrack.right;
HGDIOBJ hOldPen = SelectObject(hdc, GetStockObject(BLACK_PEN));
// Determine digit spacing.
int labelDigits = mRangeEnd > 0 ? (int)floor(log10((double)mRangeEnd)) + 1 : 1;
int labelWidth = (labelDigits + 1) * mFrameNumberWidth; // Add 1 digit for nice padding.
sint64 framesPerLabel = 1;
if (mRangeEnd > mRangeStart) {
while(framesPerLabel * mPixelsPerFrame < labelWidth) {
sint64 fpl2 = framesPerLabel + framesPerLabel;
if (fpl2 * mPixelsPerFrame >= labelWidth) {
framesPerLabel = fpl2;
break;
}
sint64 fpl5 = framesPerLabel * 5;
if (fpl5 * mPixelsPerFrame >= labelWidth) {
framesPerLabel = fpl5;
break;
}
framesPerLabel *= 10;
}
}
sint64 frame = mRangeStart;
bool bDrawLabels = ps.rcPaint.bottom >= mTrackArea.bottom;
while(frame < mRangeEnd) {
int x = FrameToPixel(frame);
const RECT rTick = { x-mTickWidth/2, mTickArea.top, x-mTickWidth/2+mTickWidth, mTickArea.bottom };
FillRect(hdc, &rTick, mBrushes[kBrushTick]);
if (x > trackRight - labelWidth)
break; // don't allow labels to encroach last label
if (bDrawLabels) {
sprintf(buf, "%I64d", frame);
TextOut(hdc, x, mTrackArea.bottom, buf, strlen(buf));
}
frame += framesPerLabel;
}
const RECT rLastTick = { mTrack.right-mTickWidth/2, mTrack.bottom, mTrack.right-mTickWidth/2+mTickWidth, mTrackArea.bottom };
FillRect(hdc, &rLastTick, mBrushes[kBrushTick]);
if (bDrawLabels) {
sprintf(buf, "%I64d", mRangeEnd);
TextOut(hdc, trackRight, mTrackArea.bottom, buf, strlen(buf));
}
// Fill the track. We draw the track borders later so they're always on top.
FillRect(hdc, &mTrack, mBrushes[kBrushTrack]);
// Draw selection and ticks.
if (mSelectionEnd >= mSelectionStart) {
int selx1 = FrameToPixel(mSelectionStart);
int selx2 = FrameToPixel(mSelectionEnd);
RECT rSel={selx1, mTrack.top, selx2, mTrack.bottom};
if (rSel.right == rSel.left)
++rSel.right;
FillRect(hdc, &rSel, mBrushes[kBrushSelection]);
if (HPEN hNullPen = CreatePen(PS_NULL, 0, 0)) {
if (HGDIOBJ hLastPen = SelectObject(hdc, hNullPen)) {
if (HGDIOBJ hOldBrush = SelectObject(hdc, GetStockObject(BLACK_BRUSH))) {
const int tickHeight = mTickArea.bottom - mTickArea.top;
const POINT pts1[3]={
{ selx1+1, mTickArea.top },
{ selx1+1, mTickArea.bottom },
{ selx1+1-tickHeight, mTickArea.top },
};
const POINT pts2[3]={
{ selx2, mTickArea.top },
{ selx2, mTickArea.bottom },
{ selx2+tickHeight, mTickArea.top },
};
Polygon(hdc, pts1, 3);
Polygon(hdc, pts2, 3);
SelectObject(hdc, hOldBrush);
}
SelectObject(hdc, hLastPen);
}
DeleteObject(hNullPen);
}
}
// Draw selection2 and ticks.
if (mSelection2End >= mSelection2Start) {
int selx1 = FrameToPixel(mSelection2Start);
int selx2 = FrameToPixel(mSelection2End);
RECT rSel={selx1, (mTickArea2.top+mTickArea2.bottom)/2, selx2, mTickArea2.bottom};
if (rSel.right == rSel.left)
++rSel.right;
FillRect(hdc, &rSel, mBrushes[kBrushSelection2]);
if (HPEN hNullPen = CreatePen(PS_NULL, 0, 0)) {
if (HGDIOBJ hLastPen = SelectObject(hdc, hNullPen)) {
if (HGDIOBJ hOldBrush = SelectObject(hdc, GetStockObject(BLACK_BRUSH))) {
const int tickHeight = mTickArea2.bottom - mTickArea2.top;
const POINT pts1[3]={
{ selx1+1, mTickArea2.top },
{ selx1+1, mTickArea2.bottom },
{ selx1+1-tickHeight, mTickArea2.bottom },
};
const POINT pts2[3]={
{ selx2, mTickArea2.top },
{ selx2, mTickArea2.bottom },
{ selx2+tickHeight, mTickArea2.bottom },
};
Polygon(hdc, pts1, 3);
Polygon(hdc, pts2, 3);
SelectObject(hdc, hOldBrush);
}
SelectObject(hdc, hLastPen);
}
DeleteObject(hNullPen);
}
}
if(!edit.empty()){
HPEN hNullPen = CreatePen(PS_NULL, 0, 0);
HBRUSH br = CreateSolidBrush(RGB(255,255,255));
HGDIOBJ hLastPen = SelectObject(hdc, hNullPen);
HGDIOBJ hOldBrush = SelectObject(hdc, br);
{for(int i=0; i<edit.size(); i++){
sint64 p = edit[i];
int x1 = FrameToPixel(p)-mTickWidth/2;
const POINT pts[4]={
{ x1, mTrack.top },
{ x1, mTrack.bottom },
{ x1+mTickWidth, mTrack.bottom },
{ x1+mTickWidth, mTrack.top },
};
Polygon(hdc, pts, 4);
}}
SelectObject(hdc, hOldBrush);
SelectObject(hdc, hLastPen);
DeleteObject(hNullPen);
DeleteObject(br);
}
if(!marker.empty()){
HPEN hNullPen = CreatePen(PS_NULL, 0, 0);
HBRUSH br1 = CreateSolidBrush(RGB(0,255,0));
HBRUSH br2 = CreateSolidBrush(RGB(0,100,0));
HGDIOBJ hLastPen = SelectObject(hdc, hNullPen);
HGDIOBJ hOldBrush = SelectObject(hdc, br1);
const int tickHeight = mTrack.bottom - mTrack.top - 4;
{for(int i=0; i<marker.size(); i++){
sint64 p = marker[i];
int x1 = FrameToPixel(p);
if(p>=mSelectionStart) SelectObject(hdc, br2);
if(p>mSelectionEnd) SelectObject(hdc, br1);
const POINT pts[3]={
{ x1-tickHeight, mTrack.top+2 },
{ x1, mTrack.bottom-2 },
{ x1+tickHeight, mTrack.top+2 },
};
Polygon(hdc, pts, 3);
}}
SelectObject(hdc, hOldBrush);
SelectObject(hdc, hLastPen);
DeleteObject(hNullPen);
DeleteObject(br1);
DeleteObject(br2);
}
// Draw track border.
const int xedge = GetSystemMetrics(SM_CXEDGE);
const int yedge = GetSystemMetrics(SM_CYEDGE);
RECT rEdge = mTrack;
InflateRect(&rEdge, xedge, yedge);
DrawEdge(hdc, &rEdge, EDGE_SUNKEN, BF_RECT);
if (mbZoom) {
RECT r1 = {0, mTrack.top, mTrack.left-10, mTrack.bottom};
RECT r2 = {mTrack.right+10, mTrack.top, mPositionArea.right, mTrack.bottom};
FillRect(hdc, &r1, mBrushes[kBrushTrack]);
FillRect(hdc, &r2, mBrushes[kBrushTrack]);
InflateRect(&r1, xedge, yedge);
InflateRect(&r2, xedge, yedge);
DrawEdge(hdc, &r1, EDGE_SUNKEN, BF_RECT);
DrawEdge(hdc, &r2, EDGE_SUNKEN, BF_RECT);
}
// Draw cursor.
RECT rThumb = mThumbRect;
DrawEdge(hdc, &rThumb, EDGE_RAISED, BF_SOFT|BF_RECT|BF_ADJUST);
DrawEdge(hdc, &rThumb, EDGE_SUNKEN, BF_SOFT|BF_RECT|BF_ADJUST);
// All done.
SelectObject(hdc, hOldPen);
SelectObject(hdc, hOldFont);
EndPaint(mhwnd, &ps);
}
void VDPositionControlW32::RecomputeMetrics() {
if (!mhwnd)
return;
RECT r;
VDVERIFY(GetClientRect(mhwnd, &r));
mPositionArea = r;
if (mbHasPosText) mPositionArea.bottom -= mButtonSize;
// Compute space we need for the ticks.
int labelDigits = mRangeEnd > 0 ? ((int)floor(log10((double)mRangeEnd)) + 1) : 1;
int labelSpace = ((labelDigits * mFrameNumberWidth) >> 1) + 8;
if (labelSpace < 16)
labelSpace = 16;
if (mbZoom)
labelSpace += 16;
mTrackArea.left = mPositionArea.left;
mTrackArea.top = mPositionArea.top;
mTrackArea.right = mPositionArea.right;
mTrackArea.bottom = mPositionArea.bottom - 2 - mFrameNumberHeight;
int trackRailHeight = (mTrackArea.bottom - mTrackArea.top + 1) / 3;
mTrack.left = mTrackArea.left + labelSpace;
mTrack.top = mTrackArea.top + trackRailHeight;
mTrack.right = mTrackArea.right - labelSpace;
mTrack.bottom = mTrackArea.bottom - trackRailHeight;
mTickArea.top = mTrack.bottom + 1*GetSystemMetrics(SM_CYEDGE);
mTickArea.bottom = mTrackArea.bottom;
const int tickHeight = mTickArea.bottom - mTickArea.top;
mTickArea.left = mTrack.left - tickHeight;
mTickArea.right = mTrack.right + tickHeight;
mTickArea2.top = mPositionArea.top;
mTickArea2.bottom = mTrack.top - 1*GetSystemMetrics(SM_CYEDGE);
mTickArea2.left = mTickArea.left;
mTickArea2.right = mTickArea.right;
// (left+0.5) -> mRangeStart
// (right-0.5) -> mRangeEnd
if (mRangeEnd > mRangeStart)
mPixelsPerFrame = (double)(mTrack.right - mTrack.left - 1) / (double)(mRangeEnd - mRangeStart);
else
mPixelsPerFrame = 0.0;
mPixelToFrameBias = mTrack.left + 0.5 - mPixelsPerFrame*mRangeStart;
if (mTrack.right > mTrack.left + 1)
mFramesPerPixel = (double)(mRangeEnd - mRangeStart) / (double)(mTrack.right - mTrack.left - 1);
else
mFramesPerPixel = 0.0;
RecalcThumbRect(mPosition, false);
RECT rInv = {0,0,r.right,r.bottom-mButtonSize};
InvalidateRect(mhwnd, &rInv, TRUE);
}
void VDPositionControlW32::RecalcThumbRect(VDPosition pos, bool update) {
RECT rOld(mThumbRect);
mThumbRect.left = FrameToPixel(pos) - mThumbWidth;
mThumbRect.right = mThumbRect.left + 2*mThumbWidth;
mThumbRect.top = mTrackArea.top;
mThumbRect.bottom = mTrackArea.bottom;
if (update && mhwnd && memcmp(&mThumbRect, &rOld, sizeof(RECT))) {
InvalidateRect(mhwnd, &rOld, TRUE);
InvalidateRect(mhwnd, &mThumbRect, TRUE);
}
}
bool VDPositionControlW32::Notify(UINT code, VDPositionControlEventData::EventType eventType) {
NMHDR nm;
nm.hwndFrom = mhwnd;
nm.idFrom = GetWindowLong(mhwnd, GWL_ID);
nm.code = code;
int r = SendMessage(GetParent(mhwnd), WM_NOTIFY, nm.idFrom, (LPARAM)&nm);
if (r==-1) return false;
if (eventType) {
VDPositionControlEventData eventData;
eventData.mPosition = mPosition;
eventData.mEventType = eventType;
mPositionUpdatedEvent.Raise(this, eventData);
}
return true;
}
|
shekh/VirtualDub2
|
src/VirtualDub/source/PositionControl.cpp
|
C++
|
gpl-2.0
| 47,243
|
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Widora</title>
<link rel="stylesheet" href="style.css">
<style type="text/css">
#apDiv1 {
position: absolute;
width: 157px;
height: 186px;
z-index: 1;
left: 245px;
top: 55px;
}
</style>
</head>
<body>
<div id="m">
<div id="h">
<div id="nav">
<ul>
<li><a href="index.html">升级固件</a></li>
<li><a href="uboot.html">升级UBOOT</a></li>
<li><a href="art.html">升级ART数据</a></li>
<li><a href="about.html">关于</a></li>
</ul>
</div>
<span style="display:inline-block;position:relative;"><img src="vt.png"><B style="position:absolute;right:10px;top:10px;">TM</B></span>
</div>
<p>You are going to update <strong>firmware</strong> on the device.<br>
Please, choose file from your local hard drive and click <strong>Update firmware</strong> button.</p>
<form method="post" action="/firmware.cgi" enctype="multipart/form-data">
<p>
<input type="file" name="firmware">
<input type="submit" value="更新">
</p>
<p> </p>
<p> </p>
</form>
<div class="i w">
<strong>WARNINGS</strong>
<ul>
<li>mail:350983773@qq.com</li>
<li>do not power off the device during update</li>
<li>if everything goes well, the device will restart</li>
<li>you can upload whatever you want, so be sure that you choose proper firmware image for your device</li>
</ul>
</div>
</div>
<div id="f">You can find more information about this project on <a href="https://github.com/widora/u-boot-mt7688" target="_blank">Widora</a></div>
</body>
</html>
|
Mleaf/u-boot-mt7688
|
uip/apps/webserver/httpd-fs/index.html
|
HTML
|
gpl-2.0
| 1,742
|
<?php
# Movable Type (r) Open Source (C) 2001-2011 Six Apart, Ltd.
# This program is distributed under the terms of the
# GNU General Public License, version 2.
#
# $Id$
function smarty_function_mtentryauthorlink($args, &$ctx) {
$entry = $ctx->stash('entry');
if (!$entry) return '';
$type = $args['type'];
$displayname = encode_html( $entry->author()->nickname );
if (isset($args['show_email']))
$show_email = $args['show_email'];
else
$show_email = 0;
if (isset($args['show_url']))
$show_url = $args['show_url'];
else
$show_url = 1;
require_once("MTUtil.php");
# Open the link in a new window if requested (with new_window="1").
$target = $args['new_window'] ? ' target="_blank"' : '';
if (!$type) {
if ($show_url && $entry->author()->url && ($displayname != '')) {
$type = 'url';
} elseif ($show_email && $entry->author()->email && ($displayname != '')) {
$type = 'email';
}
}
if ($type == 'url') {
if ($entry->author()->url && ($displayname != '')) {
return sprintf('<a href="%s"%s>%s</a>', encode_html( $entry->author()->url ), $target, $displayname);
}
} elseif ($type == 'email') {
if ($entry->author()->email && ($displayname != '')) {
$str = "mailto:" . encode_html( $entry->author()->email );
if ($args['spam_protect'])
$str = spam_protect($str);
return sprintf('<a href="%s">%s</a>', $str, $displayname);
}
} elseif ($type == 'archive') {
require_once("function.mtarchivelink.php");
$link = smarty_function_mtarchivelink(array('type' => 'Author'), $ctx);
if ($link) {
return sprintf('<a href="%s"%s>%s</a>', $link, $target, $displayname);
}
}
return $displayname;
}
?>
|
alfasado/cakephp-plugin-mt-cake
|
plugins/MT/php/lib/function.mtentryauthorlink.php
|
PHP
|
gpl-2.0
| 1,875
|
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>gluon.dal.Expression</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="gluon-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a class="navbar" target="_top" href="http://www.web2py.com">web2py Web Framework</a></th>
</tr></table></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
<a href="gluon-module.html">Package gluon</a> ::
<a href="gluon.dal-module.html" onclick="show_private();">Module dal</a> ::
Class Expression
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="gluon.dal.Expression-class.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<!-- ==================== CLASS DESCRIPTION ==================== -->
<h1 class="epydoc">Class Expression</h1><p class="nomargin-top"><span class="codelink"><a href="gluon.dal-pysrc.html#Expression">source code</a></span></p>
<pre class="base-tree">
object --+
|
<strong class="uidshort">Expression</strong>
</pre>
<dl><dt>Known Subclasses:</dt>
<dd>
<ul class="subclass-list">
<li class="private"><a href="gluon.dal.Field-class.html" onclick="show_private();">Field</a></li> </ul>
</dd></dl>
<hr />
<!-- ==================== INSTANCE METHODS ==================== -->
<a name="section-InstanceMethods"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Instance Methods</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-InstanceMethods"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="gluon.dal.Expression-class.html#__init__" class="summary-sig-name">__init__</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">db</span>,
<span class="summary-sig-arg">op</span>,
<span class="summary-sig-arg">first</span>=<span class="summary-sig-default">None</span>,
<span class="summary-sig-arg">second</span>=<span class="summary-sig-default">None</span>,
<span class="summary-sig-arg">type</span>=<span class="summary-sig-default">None</span>,
<span class="summary-sig-arg">**optional_args</span>)</span><br />
x.__init__(...) initializes x; see help(type(x)) for signature</td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.__init__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="sum"></a><span class="summary-sig-name">sum</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.sum">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="max"></a><span class="summary-sig-name">max</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.max">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="min"></a><span class="summary-sig-name">min</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.min">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="len"></a><span class="summary-sig-name">len</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.len">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="avg"></a><span class="summary-sig-name">avg</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.avg">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="abs"></a><span class="summary-sig-name">abs</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.abs">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="lower"></a><span class="summary-sig-name">lower</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.lower">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="upper"></a><span class="summary-sig-name">upper</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.upper">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="replace"></a><span class="summary-sig-name">replace</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">a</span>,
<span class="summary-sig-arg">b</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.replace">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="year"></a><span class="summary-sig-name">year</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.year">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="month"></a><span class="summary-sig-name">month</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.month">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="day"></a><span class="summary-sig-name">day</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.day">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="hour"></a><span class="summary-sig-name">hour</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.hour">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="minutes"></a><span class="summary-sig-name">minutes</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.minutes">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="coalesce"></a><span class="summary-sig-name">coalesce</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">*others</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.coalesce">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="coalesce_zero"></a><span class="summary-sig-name">coalesce_zero</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.coalesce_zero">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="seconds"></a><span class="summary-sig-name">seconds</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.seconds">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="epoch"></a><span class="summary-sig-name">epoch</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.epoch">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__getslice__"></a><span class="summary-sig-name">__getslice__</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">start</span>,
<span class="summary-sig-arg">stop</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.__getslice__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__getitem__"></a><span class="summary-sig-name">__getitem__</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">i</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.__getitem__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="gluon.dal.Expression-class.html#__str__" class="summary-sig-name">__str__</a>(<span class="summary-sig-arg">self</span>)</span><br />
str(x)</td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.__str__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__or__"></a><span class="summary-sig-name">__or__</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">other</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.__or__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__invert__"></a><span class="summary-sig-name">__invert__</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.__invert__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__add__"></a><span class="summary-sig-name">__add__</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">other</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.__add__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__sub__"></a><span class="summary-sig-name">__sub__</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">other</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.__sub__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__mul__"></a><span class="summary-sig-name">__mul__</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">other</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.__mul__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__div__"></a><span class="summary-sig-name">__div__</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">other</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.__div__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__mod__"></a><span class="summary-sig-name">__mod__</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">other</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.__mod__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__eq__"></a><span class="summary-sig-name">__eq__</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.__eq__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__ne__"></a><span class="summary-sig-name">__ne__</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.__ne__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__lt__"></a><span class="summary-sig-name">__lt__</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.__lt__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__le__"></a><span class="summary-sig-name">__le__</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.__le__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__gt__"></a><span class="summary-sig-name">__gt__</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.__gt__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__ge__"></a><span class="summary-sig-name">__ge__</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.__ge__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="like"></a><span class="summary-sig-name">like</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>,
<span class="summary-sig-arg">case_sensitive</span>=<span class="summary-sig-default">False</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.like">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="regexp"></a><span class="summary-sig-name">regexp</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.regexp">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="gluon.dal.Expression-class.html#belongs" class="summary-sig-name">belongs</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">*value</span>,
<span class="summary-sig-arg">**kwattr</span>)</span><br />
Accepts the following inputs:
field.belongs(1,2)
field.belongs((1,2))
field.belongs(query)</td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.belongs">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="startswith"></a><span class="summary-sig-name">startswith</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.startswith">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="endswith"></a><span class="summary-sig-name">endswith</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.endswith">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="contains"></a><span class="summary-sig-name">contains</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>,
<span class="summary-sig-arg">all</span>=<span class="summary-sig-default">False</span>,
<span class="summary-sig-arg">case_sensitive</span>=<span class="summary-sig-default">False</span>)</span><br />
The case_sensitive parameters is only useful for PostgreSQL For other
RDMBs it is ignored and contains is always case in-sensitive For
MongoDB and GAE contains is always case sensitive</td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.contains">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="with_alias"></a><span class="summary-sig-name">with_alias</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">alias</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.with_alias">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="st_asgeojson"></a><span class="summary-sig-name">st_asgeojson</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">precision</span>=<span class="summary-sig-default">15</span>,
<span class="summary-sig-arg">options</span>=<span class="summary-sig-default">0</span>,
<span class="summary-sig-arg">version</span>=<span class="summary-sig-default">1</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.st_asgeojson">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="st_astext"></a><span class="summary-sig-name">st_astext</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.st_astext">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="st_x"></a><span class="summary-sig-name">st_x</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.st_x">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="st_y"></a><span class="summary-sig-name">st_y</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.st_y">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="st_distance"></a><span class="summary-sig-name">st_distance</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">other</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.st_distance">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="st_simplify"></a><span class="summary-sig-name">st_simplify</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.st_simplify">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="st_contains"></a><span class="summary-sig-name">st_contains</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.st_contains">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="st_equals"></a><span class="summary-sig-name">st_equals</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.st_equals">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="st_intersects"></a><span class="summary-sig-name">st_intersects</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.st_intersects">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="st_overlaps"></a><span class="summary-sig-name">st_overlaps</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.st_overlaps">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="st_touches"></a><span class="summary-sig-name">st_touches</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.st_touches">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="st_within"></a><span class="summary-sig-name">st_within</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="gluon.dal-pysrc.html#Expression.st_within">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>:
<code>__delattr__</code>,
<code>__format__</code>,
<code>__getattribute__</code>,
<code>__hash__</code>,
<code>__new__</code>,
<code>__reduce__</code>,
<code>__reduce_ex__</code>,
<code>__repr__</code>,
<code>__setattr__</code>,
<code>__sizeof__</code>,
<code>__subclasshook__</code>
</p>
</td>
</tr>
</table>
<!-- ==================== PROPERTIES ==================== -->
<a name="section-Properties"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Properties</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Properties"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>:
<code>__class__</code>
</p>
</td>
</tr>
</table>
<!-- ==================== METHOD DETAILS ==================== -->
<a name="section-MethodDetails"></a>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Method Details</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-MethodDetails"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
</table>
<a name="__init__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__init__</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">db</span>,
<span class="sig-arg">op</span>,
<span class="sig-arg">first</span>=<span class="sig-default">None</span>,
<span class="sig-arg">second</span>=<span class="sig-default">None</span>,
<span class="sig-arg">type</span>=<span class="sig-default">None</span>,
<span class="sig-arg">**optional_args</span>)</span>
<br /><em class="fname">(Constructor)</em>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="gluon.dal-pysrc.html#Expression.__init__">source code</a></span>
</td>
</tr></table>
<p>x.__init__(...) initializes x; see help(type(x)) for signature</p>
<dl class="fields">
<dt>Overrides:
object.__init__
<dd><em class="note">(inherited documentation)</em></dd>
</dt>
</dl>
</td></tr></table>
</div>
<a name="__str__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__str__</span>(<span class="sig-arg">self</span>)</span>
<br /><em class="fname">(Informal representation operator)</em>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="gluon.dal-pysrc.html#Expression.__str__">source code</a></span>
</td>
</tr></table>
<p>str(x)</p>
<dl class="fields">
<dt>Overrides:
object.__str__
<dd><em class="note">(inherited documentation)</em></dd>
</dt>
</dl>
</td></tr></table>
</div>
<a name="belongs"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">belongs</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">*value</span>,
<span class="sig-arg">**kwattr</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="gluon.dal-pysrc.html#Expression.belongs">source code</a></span>
</td>
</tr></table>
<pre class="literalblock">
Accepts the following inputs:
field.belongs(1,2)
field.belongs((1,2))
field.belongs(query)
Does NOT accept:
field.belongs(1)
</pre>
<dl class="fields">
</dl>
</td></tr></table>
</div>
<br />
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="gluon-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a class="navbar" target="_top" href="http://www.web2py.com">web2py Web Framework</a></th>
</tr></table></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0.1 on Mon Oct 14 15:17:00 2013
</td>
<td align="right" class="footer">
<a target="mainFrame" href="http://epydoc.sourceforge.net"
>http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
// -->
</script>
</body>
</html>
|
AbsentMoniker/ECE463Honors
|
web2py/applications/examples/static/epydoc/gluon.dal.Expression-class.html
|
HTML
|
gpl-2.0
| 47,582
|
<?php
# MantisBT - a php based bugtracking system
# MantisBT 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.
#
# MantisBT 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 MantisBT. If not, see <http://www.gnu.org/licenses/>.
/**
* This page updates a user's information
* If an account is protected then changes are forbidden
* The page gets redirected back to account_page.php
*
* @package MantisBT
* @copyright Copyright (C) 2000 - 2002 Kenzaburo Ito - kenito@300baud.org
* @copyright Copyright (C) 2002 - 2013 MantisBT Team - mantisbt-dev@lists.sourceforge.net
* @link http://www.mantisbt.org
*/
/**
* MantisBT Core API's
*/
require_once( 'core.php' );
require_once( 'email_api.php' );
form_security_validate('account_update');
auth_ensure_user_authenticated();
current_user_ensure_unprotected();
$f_email = gpc_get_string( 'email', '' );
$f_realname = gpc_get_string( 'realname', '' );
$f_password = gpc_get_string( 'password', '' );
$f_password_confirm = gpc_get_string( 'password_confirm', '' );
// get the user id once, so that if we decide in the future to enable this for
// admins / managers to change details of other users.
$t_user_id = auth_get_current_user_id();
$t_redirect = 'account_page.php';
/** @todo Listing what fields were updated is not standard behaviour of MantisBT - it also complicates the code. */
$t_email_updated = false;
$t_password_updated = false;
$t_realname_updated = false;
$t_ldap = ( LDAP == config_get( 'login_method' ) );
# Update email (but only if LDAP isn't being used)
if ( !( $t_ldap && config_get( 'use_ldap_email' ) ) ) {
$f_email = email_append_domain( $f_email );
email_ensure_valid( $f_email );
email_ensure_not_disposable( $f_email );
if ( $f_email != user_get_email( $t_user_id ) ) {
user_set_email( $t_user_id, $f_email );
$t_email_updated = true;
}
}
# Update real name (but only if LDAP isn't being used)
if ( !( $t_ldap && config_get( 'use_ldap_realname' ) ) ) {
# strip extra spaces from real name
$t_realname = string_normalize( $f_realname );
if ( $t_realname != user_get_field( $t_user_id, 'realname' ) ) {
# checks for problems with realnames
user_ensure_realname_valid( $t_realname );
$t_username = user_get_field( $t_user_id, 'username' );
user_ensure_realname_unique( $t_username, $t_realname );
user_set_realname( $t_user_id, $t_realname );
$t_realname_updated = true;
}
}
# Update password if the two match and are not empty
if ( !is_blank( $f_password ) ) {
if ( $f_password != $f_password_confirm ) {
trigger_error( ERROR_USER_CREATE_PASSWORD_MISMATCH, ERROR );
} else {
if ( !auth_does_password_match( $t_user_id, $f_password ) ) {
user_set_password( $t_user_id, $f_password );
$t_password_updated = true;
}
}
}
form_security_purge('account_update');
html_page_top( null, $t_redirect );
echo '<br /><div align="center">';
if ( $t_email_updated ) {
echo lang_get( 'email_updated' ) . '<br />';
}
if ( $t_password_updated ) {
echo lang_get( 'password_updated' ) . '<br />';
}
if ( $t_realname_updated ) {
echo lang_get( 'realname_updated' ) . '<br />';
}
echo lang_get( 'operation_successful' ) . '<br />';
print_bracket_link( $t_redirect, lang_get( 'proceed' ) );
echo '</div>';
html_page_bottom();
|
CouponVoodoo/theshoppingpro
|
mantis/account_update.php
|
PHP
|
gpl-2.0
| 3,804
|
/* Copyright (C)
* 2015 - John Melton, G0ORX/N6LYT
*
* 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 <gtk/gtk.h>
#include <semaphore.h>
#include <stdio.h>
#include <string.h>
#include "new_menu.h"
#include "general_menu.h"
#include "band.h"
#include "filter.h"
#include "radio.h"
static GtkWidget *parent_window=NULL;
static GtkWidget *menu_b=NULL;
static GtkWidget *dialog=NULL;
static gboolean close_cb (GtkWidget *widget, GdkEventButton *event, gpointer data) {
if(dialog!=NULL) {
gtk_widget_destroy(dialog);
dialog=NULL;
sub_menu=NULL;
}
return TRUE;
}
static void vfo_divisor_value_changed_cb(GtkWidget *widget, gpointer data) {
vfo_encoder_divisor=gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(widget));
}
static void toolbar_dialog_buttons_cb(GtkWidget *widget, gpointer data) {
toolbar_dialog_buttons=toolbar_dialog_buttons==1?0:1;
update_toolbar_labels();
}
static void ptt_cb(GtkWidget *widget, gpointer data) {
mic_ptt_enabled=mic_ptt_enabled==1?0:1;
}
static void ptt_ring_cb(GtkWidget *widget, gpointer data) {
mic_ptt_tip_bias_ring=0;
}
static void ptt_tip_cb(GtkWidget *widget, gpointer data) {
mic_ptt_tip_bias_ring=1;
}
static void bias_cb(GtkWidget *widget, gpointer data) {
mic_bias_enabled=mic_bias_enabled==1?0:1;
}
static void apollo_cb(GtkWidget *widget, gpointer data);
static void alex_cb(GtkWidget *widget, gpointer data) {
if(filter_board==ALEX) {
filter_board=NONE;
} else if(filter_board==NONE) {
filter_board=ALEX;
} else if(filter_board==APOLLO) {
GtkWidget *w=(GtkWidget *)data;
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (w), FALSE);
filter_board=ALEX;
}
if(protocol==NEW_PROTOCOL) {
filter_board_changed();
}
if(filter_board==ALEX) {
BAND *band=band_get_current_band();
BANDSTACK_ENTRY* entry=bandstack_entry_get_current();
setFrequency(entry->frequencyA);
setMode(entry->mode);
FILTER* band_filters=filters[entry->mode];
FILTER* band_filter=&band_filters[entry->filter];
setFilter(band_filter->low,band_filter->high);
set_alex_rx_antenna(band->alexRxAntenna);
set_alex_tx_antenna(band->alexTxAntenna);
set_alex_attenuation(band->alexAttenuation);
}
}
static void apollo_cb(GtkWidget *widget, gpointer data) {
if(filter_board==APOLLO) {
filter_board=NONE;
} else if(filter_board==NONE) {
filter_board=APOLLO;
} else if(filter_board==ALEX) {
GtkWidget *w=(GtkWidget *)data;
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (w), FALSE);
filter_board=APOLLO;
}
if(protocol==NEW_PROTOCOL) {
filter_board_changed();
}
if(filter_board==APOLLO) {
BAND *band=band_get_current_band();
BANDSTACK_ENTRY* entry=bandstack_entry_get_current();
setFrequency(entry->frequencyA);
setMode(entry->mode);
FILTER* band_filters=filters[entry->mode];
FILTER* band_filter=&band_filters[entry->filter];
setFilter(band_filter->low,band_filter->high);
}
}
/*
static void apollo_tuner_cb(GtkWidget *widget, gpointer data) {
apollo_tuner=apollo_tuner==1?0:1;
if(protocol==NEW_PROTOCOL) {
tuner_changed();
}
}
static void pa_cb(GtkWidget *widget, gpointer data) {
pa=pa==1?0:1;
if(protocol==NEW_PROTOCOL) {
pa_changed();
}
}
*/
static void rx_dither_cb(GtkWidget *widget, gpointer data) {
rx_dither=rx_dither==1?0:1;
if(protocol==NEW_PROTOCOL) {
}
}
static void rx_random_cb(GtkWidget *widget, gpointer data) {
rx_random=rx_random==1?0:1;
if(protocol==NEW_PROTOCOL) {
}
}
static void rx_preamp_cb(GtkWidget *widget, gpointer data) {
rx_preamp=rx_preamp==1?0:1;
if(protocol==NEW_PROTOCOL) {
}
}
static void sample_rate_cb(GtkWidget *widget, gpointer data) {
if(protocol==ORIGINAL_PROTOCOL) {
old_protocol_new_sample_rate((int)data);
} else if(protocol==NEW_PROTOCOL) {
new_protocol_new_sample_rate((int)data);
#ifdef RTLSDR
} else if(protocol==RTLSDR_PROTOCOL) {
rtl_protocol_stop();
sample_rate = (int)data;
wdsp_new_sample_rate(sample_rate);
rtl_protocol_init(0,gtk_widget_get_allocated_width (parent_window));
#endif
}
}
static void rit_cb(GtkWidget *widget,gpointer data) {
rit_increment=(int)data;
}
void general_menu(GtkWidget *parent) {
parent_window=parent;
dialog=gtk_dialog_new();
gtk_window_set_transient_for(GTK_WINDOW(dialog),GTK_WINDOW(parent_window));
gtk_window_set_decorated(GTK_WINDOW(dialog),FALSE);
GdkRGBA color;
color.red = 1.0;
color.green = 1.0;
color.blue = 1.0;
color.alpha = 1.0;
gtk_widget_override_background_color(dialog,GTK_STATE_FLAG_NORMAL,&color);
GtkWidget *content=gtk_dialog_get_content_area(GTK_DIALOG(dialog));
GtkWidget *grid=gtk_grid_new();
gtk_grid_set_column_spacing (GTK_GRID(grid),10);
//gtk_grid_set_row_spacing (GTK_GRID(grid),10);
//gtk_grid_set_row_homogeneous(GTK_GRID(grid),TRUE);
//gtk_grid_set_column_homogeneous(GTK_GRID(grid),TRUE);
GtkWidget *close_b=gtk_button_new_with_label("Close General");
g_signal_connect (close_b, "button_press_event", G_CALLBACK(close_cb), NULL);
gtk_grid_attach(GTK_GRID(grid),close_b,0,0,1,1);
GtkWidget *vfo_divisor_label=gtk_label_new("VFO Encoder Divisor: ");
gtk_grid_attach(GTK_GRID(grid),vfo_divisor_label,4,1,1,1);
GtkWidget *vfo_divisor=gtk_spin_button_new_with_range(1.0,60.0,1.0);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(vfo_divisor),(double)vfo_encoder_divisor);
gtk_grid_attach(GTK_GRID(grid),vfo_divisor,4,2,1,1);
g_signal_connect(vfo_divisor,"value_changed",G_CALLBACK(vfo_divisor_value_changed_cb),NULL);
if(protocol==ORIGINAL_PROTOCOL || protocol==NEW_PROTOCOL) {
GtkWidget *rx_dither_b=gtk_check_button_new_with_label("Dither");
//gtk_widget_override_font(rx_dither_b, pango_font_description_from_string("Arial 18"));
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (rx_dither_b), rx_dither);
gtk_grid_attach(GTK_GRID(grid),rx_dither_b,1,4,1,1);
g_signal_connect(rx_dither_b,"toggled",G_CALLBACK(rx_dither_cb),NULL);
GtkWidget *rx_random_b=gtk_check_button_new_with_label("Random");
//gtk_widget_override_font(rx_random_b, pango_font_description_from_string("Arial 18"));
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (rx_random_b), rx_random);
gtk_grid_attach(GTK_GRID(grid),rx_random_b,1,5,1,1);
g_signal_connect(rx_random_b,"toggled",G_CALLBACK(rx_random_cb),NULL);
if((protocol==NEW_PROTOCOL && device==NEW_DEVICE_ORION) ||
(protocol==NEW_PROTOCOL && device==NEW_DEVICE_ORION2) ||
(protocol==ORIGINAL_PROTOCOL && device==DEVICE_ORION)) {
GtkWidget *ptt_ring_b=gtk_radio_button_new_with_label(NULL,"PTT On Ring, Mic and Bias on Tip");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (ptt_ring_b), mic_ptt_tip_bias_ring==0);
gtk_grid_attach(GTK_GRID(grid),ptt_ring_b,3,1,1,1);
g_signal_connect(ptt_ring_b,"pressed",G_CALLBACK(ptt_ring_cb),NULL);
GtkWidget *ptt_tip_b=gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(ptt_ring_b),"PTT On Tip, Mic and Bias on Ring");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (ptt_tip_b), mic_ptt_tip_bias_ring==1);
gtk_grid_attach(GTK_GRID(grid),ptt_tip_b,3,2,1,1);
g_signal_connect(ptt_tip_b,"pressed",G_CALLBACK(ptt_tip_cb),NULL);
GtkWidget *ptt_b=gtk_check_button_new_with_label("PTT Enabled");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (ptt_b), mic_ptt_enabled);
gtk_grid_attach(GTK_GRID(grid),ptt_b,3,3,1,1);
g_signal_connect(ptt_b,"toggled",G_CALLBACK(ptt_cb),NULL);
GtkWidget *bias_b=gtk_check_button_new_with_label("BIAS Enabled");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (bias_b), mic_bias_enabled);
gtk_grid_attach(GTK_GRID(grid),bias_b,3,4,1,1);
g_signal_connect(bias_b,"toggled",G_CALLBACK(bias_cb),NULL);
}
GtkWidget *alex_b=gtk_check_button_new_with_label("ALEX");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (alex_b), filter_board==ALEX);
gtk_grid_attach(GTK_GRID(grid),alex_b,1,1,1,1);
GtkWidget *apollo_b=gtk_check_button_new_with_label("APOLLO");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (apollo_b), filter_board==APOLLO);
gtk_grid_attach(GTK_GRID(grid),apollo_b,1,2,1,1);
g_signal_connect(alex_b,"toggled",G_CALLBACK(alex_cb),apollo_b);
g_signal_connect(apollo_b,"toggled",G_CALLBACK(apollo_cb),alex_b);
}
GtkWidget *sample_rate_label=gtk_label_new("Sample Rate:");
gtk_grid_attach(GTK_GRID(grid),sample_rate_label,0,1,1,1);
if(protocol==ORIGINAL_PROTOCOL || protocol==NEW_PROTOCOL || protocol==RTLSDR_PROTOCOL) {
GtkWidget *sample_rate_48=gtk_radio_button_new_with_label(NULL,"48000");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (sample_rate_48), sample_rate==48000);
gtk_grid_attach(GTK_GRID(grid),sample_rate_48,0,2,1,1);
g_signal_connect(sample_rate_48,"pressed",G_CALLBACK(sample_rate_cb),(gpointer *)48000);
GtkWidget *sample_rate_96=gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(sample_rate_48),"96000");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (sample_rate_96), sample_rate==96000);
gtk_grid_attach(GTK_GRID(grid),sample_rate_96,0,3,1,1);
g_signal_connect(sample_rate_96,"pressed",G_CALLBACK(sample_rate_cb),(gpointer *)96000);
GtkWidget *sample_rate_192=gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(sample_rate_96),"192000");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (sample_rate_192), sample_rate==192000);
gtk_grid_attach(GTK_GRID(grid),sample_rate_192,0,4,1,1);
g_signal_connect(sample_rate_192,"pressed",G_CALLBACK(sample_rate_cb),(gpointer *)192000);
GtkWidget *sample_rate_384=gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(sample_rate_192),"384000");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (sample_rate_384), sample_rate==384000);
gtk_grid_attach(GTK_GRID(grid),sample_rate_384,0,5,1,1);
g_signal_connect(sample_rate_384,"pressed",G_CALLBACK(sample_rate_cb),(gpointer *)384000);
if(protocol==NEW_PROTOCOL || protocol==RTLSDR_PROTOCOL) {
GtkWidget *sample_rate_768=gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(sample_rate_384),"768000");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (sample_rate_768), sample_rate==768000);
gtk_grid_attach(GTK_GRID(grid),sample_rate_768,0,6,1,1);
g_signal_connect(sample_rate_768,"pressed",G_CALLBACK(sample_rate_cb),(gpointer *)768000);
GtkWidget *sample_rate_1536=gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(sample_rate_768),"1536000");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (sample_rate_1536), sample_rate==1536000);
gtk_grid_attach(GTK_GRID(grid),sample_rate_1536,0,7,1,1);
g_signal_connect(sample_rate_1536,"pressed",G_CALLBACK(sample_rate_cb),(gpointer *)1536000);
#ifdef raspberrypi
gtk_widget_set_sensitive(sample_rate_768,FALSE);
gtk_widget_set_sensitive(sample_rate_1536,FALSE);
#endif
}
}
#ifdef LIMESDR
if(protocol==LIMESDR_PROTOCOL) {
GtkWidget *sample_rate_1M=gtk_radio_button_new_with_label(NULL,"1000000");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (sample_rate_1M), sample_rate==1000000);
gtk_grid_attach(GTK_GRID(grid),sample_rate_1M,0,2,1,1);
g_signal_connect(sample_rate_1M,"pressed",G_CALLBACK(sample_rate_cb),(gpointer *)1000000);
GtkWidget *sample_rate_2M=gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(sample_rate_1M),"2000000");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (sample_rate_2M), sample_rate==2000000);
gtk_grid_attach(GTK_GRID(grid),sample_rate_2M,0,3,1,1);
g_signal_connect(sample_rate_2M,"pressed",G_CALLBACK(sample_rate_cb),(gpointer *)2000000);
}
#endif
GtkWidget *rit_label=gtk_label_new("RIT step: ");
gtk_grid_attach(GTK_GRID(grid),rit_label,5,1,1,1);
GtkWidget *rit_1=gtk_radio_button_new_with_label(NULL,"1 Hz");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (rit_1), rit_increment==1);
gtk_grid_attach(GTK_GRID(grid),rit_1,5,2,1,1);
g_signal_connect(rit_1,"pressed",G_CALLBACK(rit_cb),(gpointer *)1);
GtkWidget *rit_10=gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(rit_1),"10");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (rit_10), rit_increment==10);
gtk_grid_attach(GTK_GRID(grid),rit_10,5,3,1,1);
g_signal_connect(rit_10,"pressed",G_CALLBACK(rit_cb),(gpointer *)10);
GtkWidget *rit_100=gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(rit_10),"100");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (rit_100), rit_increment==100);
gtk_grid_attach(GTK_GRID(grid),rit_100,5,4,1,1);
g_signal_connect(rit_100,"pressed",G_CALLBACK(rit_cb),(gpointer *)100);
gtk_container_add(GTK_CONTAINER(content),grid);
sub_menu=dialog;
gtk_widget_show_all(dialog);
}
|
n1gp/pihpsdr
|
general_menu.c
|
C
|
gpl-2.0
| 13,477
|
<?php
/**
* @package supertracker
* @copyright Copyright 2003-2006 Zen Cart Development Team
* @developer Created by Mark Stephens, http://www.phpworks.co.uk
* @developer Added keywords filters by Monika Mathé, http://www.monikamathe.com
* @developer Added keywords processing by Andrew Berezin, http://eCommerce-Service.com
* @developer Ported to Zen-Cart by Andrew Berezin, http://eCommerce-Service.com
* @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
* @version Based $Id: supertracker.php v 3.20b 21 Mar 2006 Mark Stephens $
* @version $Id: jscript_supertracker.php, v 1.0.0 09.05.2007 17:40 Andrew Berezin andrew@ecommerce-service.com $
*/
require(DIR_WS_CLASSES . 'supertracker.php');
$supertracker = new supertracker;
$supertracker->update();
?>
|
Zen4All/Zen-Cart-Supertracker
|
1_Install_Files/includes/templates/YOUR_TEMPLATE/jscript/jscript_supertracker.php
|
PHP
|
gpl-2.0
| 793
|
#!/bin/sh
set -x
# autoconf needs build-aux directory
mkdir -p build-aux || exit 1
mkdir -p m4 || exit 1
sh version.sh
# libtoolize generates m4 dir
libtoolize || exit 1
aclocal -I m4 || exit 1
autoheader || exit 1
automake --add-missing --copy || exit 1
autoconf || exit 1
|
perarnau/ccontrol
|
autogen.sh
|
Shell
|
gpl-2.0
| 274
|
const true_ = ['yes', 'y', 'true', 't', 'on', 'enabled', '1', '-1'];
const false_ = ['no', 'n', 'false', 'f', 'off', 'disabled', '0'];
module.exports = function validateNumber(expr, allowNull, options) {
expr = expr.toLowerCase();
if (~true_.indexOf(String(expr))) {
return true;
} else if (~false_.indexOf(String(expr))) {
return false;
} else if (expr === null && allowNull) {
return null;
} else {
throw new Error('Invalid boolean: ' + JSON.stringify(expr));
}
};
|
battlesnake/js-validators
|
boolean.js
|
JavaScript
|
gpl-2.0
| 482
|
/*
*************************************************************************
* Ralink Tech Inc.
* 5F., No.36, Taiyuan St., Jhubei City,
* Hsinchu County 302,
* Taiwan, R.O.C.
*
* (c) Copyright 2002-2010, Ralink Technology, Inc.
*
* 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. *
* *
*************************************************************************/
#ifdef RT30xx
#ifndef RTMP_RF_RW_SUPPORT
#error "You Should Enable compile flag RTMP_RF_RW_SUPPORT for this chip"
#endif /* RTMP_RF_RW_SUPPORT */
#include "rt_config.h"
/*
RF register initialization set
*/
REG_PAIR RT3020_RFRegTable[] = {
{RF_R04, 0x40},
{RF_R05, 0x03},
{RF_R06, 0x02},
{RF_R07, 0x60},
{RF_R09, 0x0F},
{RF_R10, 0x41},
{RF_R11, 0x21},
{RF_R12, 0x7B},
{RF_R14, 0x90},
{RF_R15, 0x58},
{RF_R16, 0xB3},
{RF_R17, 0x92},
{RF_R18, 0x2C},
{RF_R19, 0x02},
{RF_R20, 0xBA},
{RF_R21, 0xDB},
{RF_R24, 0x16},
{RF_R25, 0x03},
{RF_R29, 0x1F},
};
UCHAR NUM_RF_3020_REG_PARMS = (sizeof(RT3020_RFRegTable) / sizeof(REG_PAIR));
#ifdef RTMP_FLASH_SUPPORT
UCHAR RT3090_EeBuffer[EEPROM_SIZE] = {
0x92, 0x30, 0x02, 0x01, 0x00, 0x0c, 0x43, 0x30, 0x92, 0x00, 0x92, 0x30, 0x14, 0x18, 0x01, 0x80,
0x00, 0x00, 0x92, 0x30, 0x14, 0x18, 0x00, 0x00, 0x01, 0x00, 0x6a, 0xff, 0x13, 0x02, 0xff, 0xff,
0xff, 0xff, 0xc1, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0x8e, 0x75, 0x01, 0x43, 0x22, 0x08, 0x27, 0x00, 0xff, 0xff, 0x16, 0x01, 0xff, 0xff, 0xd9, 0xfa,
0xcc, 0x88, 0xff, 0xff, 0x0a, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff,
0xff, 0xff, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x1d, 0x1a,
0x15, 0x11, 0x0f, 0x0d, 0x0a, 0x07, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x88, 0x88,
0xcc, 0xcc, 0xaa, 0x88, 0xcc, 0xcc, 0xaa, 0x88, 0xcc, 0xcc, 0xaa, 0x88, 0xcc, 0xcc, 0xaa, 0x88,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, };
#endif /* RTMP_FLASH_SUPPORT */
/*
========================================================================
Routine Description:
Initialize RT35xx.
Arguments:
pAd - WLAN control block pointer
Return Value:
None
Note:
========================================================================
*/
VOID RT30xx_Init(
IN PRTMP_ADAPTER pAd)
{
RTMP_CHIP_OP *pChipOps = &pAd->chipOps;
RTMP_CHIP_CAP *pChipCap = &pAd->chipCap;
/* init capability */
/*
WARNING:
Currently following table are shared by all RT30xx based IC, change it carefully when you add a new IC here.
*/
pChipCap->pRFRegTable = RT3020_RFRegTable;
pChipCap->MaxNumOfBbpId = 185;
pChipCap->TXWISize = 16;
pChipCap->RXWISize = 16;
/* init operator */
#ifdef RT3090
if (pAd->infType == RTMP_DEV_INF_PCIE)
{
pChipOps->AsicRfInit = NICInitRT3090RFRegisters;
#ifdef RTMP_FLASH_SUPPORT
pChipCap->eebuf = RT3090_EeBuffer;
#endif /* RTMP_FLASH_SUPPORT */
}
#endif /* RT3090 */
pChipOps->AsicHaltAction = RT30xxHaltAction;
pChipOps->AsicRfTurnOff = RT30xxLoadRFSleepModeSetup;
pChipOps->AsicReverseRfFromSleepMode = RT30xxReverseRFSleepModeSetup;
pChipOps->ChipSwitchChannel = RT30xx_ChipSwitchChannel;
pChipOps->ChipBBPAdjust = RT30xx_ChipBBPAdjust;
pChipOps->ChipAGCInit = RT30xx_ChipAGCInit;
/* 1T1R only */
if (pAd->RfIcType == RFIC_3020)
{
pChipOps->SetRxAnt = RT30xxSetRxAnt;
pAd->Mlme.bEnableAutoAntennaCheck = FALSE;
}
pChipOps->AsicGetTxPowerOffset = AsicGetTxPowerOffset;
pChipOps->AsicTxAlcGetAutoAgcOffset = AsicGetAutoAgcOffsetForExternalTxAlc;
/*pChipOps->ChipResumeMsduTransmission = NULL; */
/*pChipOps->VdrTuning1 = NULL; */
pChipOps->RxSensitivityTuning = NULL;
#ifdef RTMP_FREQ_CALIBRATION_SUPPORT
pChipOps->AsicFreqCalInit = NULL;
pChipOps->AsicFreqCalStop = NULL;
pChipOps->AsicFreqCal = NULL;
pChipOps->AsicFreqOffsetGet = NULL;
#endif /* RTMP_FREQ_CALIBRATION_SUPPORT */
}
/*
Antenna divesity use GPIO3 and EESK pin for control
Antenna and EEPROM access are both using EESK pin,
Therefor we should avoid accessing EESK at the same time
Then restore antenna after EEPROM access
The original name of this function is AsicSetRxAnt(), now change to
*/
VOID RT30xxSetRxAnt(
IN PRTMP_ADAPTER pAd,
IN UCHAR Ant)
{
UINT32 Value;
#ifdef RTMP_MAC_PCI
UINT32 x;
#endif /* RTMP_MAC_PCI */
if (/*(!pAd->NicConfig2.field.AntDiversity) ||*/
(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)) ||
(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)) ||
(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF)) ||
(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
{
return;
}
/* the antenna selection is through firmware and MAC register(GPIO3) */
if (IS_RT2070(pAd) || (IS_RT3070(pAd) && pAd->RfIcType == RFIC_3020) ||
(IS_RT3090(pAd) && pAd->RfIcType == RFIC_3020))
{
if (Ant == 0)
{
/*
Main antenna
E2PROM_CSR only in PCI bus Reg., USB Bus need MCU commad to control the EESK pin.
*/
#ifdef RTMP_MAC_PCI
RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
x |= (EESK);
RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
#endif /* RTMP_MAC_PCI */
RTMP_IO_READ32(pAd, GPIO_CTRL_CFG, &Value);
Value &= ~(0x0808);
RTMP_IO_WRITE32(pAd, GPIO_CTRL_CFG, Value);
DBGPRINT_RAW(RT_DEBUG_TRACE, ("AsicSetRxAnt, switch to main antenna\n"));
}
else
{
/*
Aux antenna
E2PROM_CSR only in PCI bus Reg., USB Bus need MCU commad to control the EESK pin.
*/
#ifdef RTMP_MAC_PCI
RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
x &= ~(EESK);
RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
#endif /* RTMP_MAC_PCI */
RTMP_IO_READ32(pAd, GPIO_CTRL_CFG, &Value);
Value &= ~(0x0808);
Value |= 0x08;
RTMP_IO_WRITE32(pAd, GPIO_CTRL_CFG, Value);
DBGPRINT_RAW(RT_DEBUG_TRACE, ("AsicSetRxAnt, switch to aux antenna\n"));
}
}
}
/*
========================================================================
Routine Description:
For RF filter calibration purpose
Arguments:
pAd Pointer to our adapter
Return Value:
None
IRQL = PASSIVE_LEVEL
========================================================================
*/
VOID RTMPFilterCalibration(
IN PRTMP_ADAPTER pAd)
{
UCHAR R55x = 0, value, FilterTarget = 0x1E, BBPValue=0;
UINT loop = 0, count = 0, loopcnt = 0, ReTry = 0;
UCHAR RF_R24_Value = 0;
/* Give bbp filter initial value */
pAd->Mlme.CaliBW20RfR24 = 0x1F;
pAd->Mlme.CaliBW40RfR24 = 0x2F; /* Bit[5] must be 1 for BW 40 */
do
{
if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))
return;
if (loop == 1) /*BandWidth = 40 MHz*/
{
/* Write 0x27 to RF_R24 to program filter*/
RT30xxReadRFRegister(pAd, RF_R24, (PUCHAR)(&RF_R24_Value));
RF_R24_Value = (RF_R24_Value & 0xC0) | 0x27; /* <bit 5>:tx_h20M<bit 5> and <bit 4:0>:tx_agc_fc<bit 4:0>*/
RT30xxWriteRFRegister(pAd, RF_R24, RF_R24_Value);
if (IS_RT3071(pAd) || IS_RT3572(pAd))
FilterTarget = 0x15;
else
FilterTarget = 0x19;
/* when calibrate BW40, BBP mask must set to BW40.*/
RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
BBPValue&= (~0x18);
BBPValue|= (0x10);
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
/* set to BW40*/
RT30xxReadRFRegister(pAd, RF_R31, &value);
value |= 0x20;
RT30xxWriteRFRegister(pAd, RF_R31, value);
}
else /*BandWidth = 20 MHz*/
{
/* Write 0x07 to RF_R24 to program filter*/
RT30xxReadRFRegister(pAd, RF_R24, (PUCHAR)(&RF_R24_Value));
RF_R24_Value = (RF_R24_Value & 0xC0) | 0x07; /* <bit 5>:tx_h20M<bit 5> and <bit 4:0>:tx_agc_fc<bit 4:0>*/
RT30xxWriteRFRegister(pAd, RF_R24, RF_R24_Value);
if (IS_RT3071(pAd) || IS_RT3572(pAd))
FilterTarget = 0x13;
else
FilterTarget = 0x16;
/*set to BW20*/
RT30xxReadRFRegister(pAd, RF_R31, &value);
value &= (~0x20);
RT30xxWriteRFRegister(pAd, RF_R31, value);
}
/* Write 0x01 to RF_R22 to enable baseband loopback mode*/
RT30xxReadRFRegister(pAd, RF_R22, &value);
value |= 0x01;
RT30xxWriteRFRegister(pAd, RF_R22, value);
/* Write 0x00 to BBP_R24 to set power & frequency of passband test tone*/
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R24, 0);
do
{
if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))
return;
/* Write 0x90 to BBP_R25 to transmit test tone*/
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R25, 0x90);
RTMPusecDelay(1000);
/* Read BBP_R55[6:0] for received power, set R55x = BBP_R55[6:0]*/
RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R55, &value);
R55x = value & 0xFF;
} while ((ReTry++ < 100) && (R55x == 0));
/* Write 0x06 to BBP_R24 to set power & frequency of stopband test tone*/
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R24, 0x06);
while(TRUE)
{
if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))
return;
/* Write 0x90 to BBP_R25 to transmit test tone*/
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R25, 0x90);
/*We need to wait for calibration*/
RTMPusecDelay(1000);
RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R55, &value);
value &= 0xFF;
if ((R55x - value) < FilterTarget)
{
RF_R24_Value ++;
}
else if ((R55x - value) == FilterTarget)
{
RF_R24_Value ++;
count ++;
}
else
{
break;
}
/* prevent infinite loop cause driver hang.*/
if (loopcnt++ > 100)
{
DBGPRINT(RT_DEBUG_ERROR, ("RTMPFilterCalibration - can't find a valid value, loopcnt=%d stop calibrating", loopcnt));
break;
}
/*Write RF_R24 to program filter*/
RT30xxWriteRFRegister(pAd, RF_R24, RF_R24_Value);
}
if (count > 0)
{
RF_R24_Value = RF_R24_Value - ((count) ? (1) : (0));
}
/* Store for future usage*/
if (loopcnt < 100)
{
if (loop++ == 0)
{
/*BandWidth = 20 MHz*/
pAd->Mlme.CaliBW20RfR24 = (UCHAR)RF_R24_Value;
}
else
{
/*BandWidth = 40 MHz*/
pAd->Mlme.CaliBW40RfR24 = (UCHAR)RF_R24_Value;
break;
}
}
else
break;
RT30xxWriteRFRegister(pAd, RF_R24, RF_R24_Value);
/* reset count*/
count = 0;
} while(TRUE);
/* Set back to initial state*/
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R24, 0);
RT30xxReadRFRegister(pAd, RF_R22, &value);
value &= ~(0x01);
RT30xxWriteRFRegister(pAd, RF_R22, value);
/* set BBP back to BW20*/
RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
BBPValue&= (~0x18);
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
DBGPRINT(RT_DEBUG_TRACE, ("RTMPFilterCalibration - CaliBW20RfR24=0x%x, CaliBW40RfR24=0x%x\n", pAd->Mlme.CaliBW20RfR24, pAd->Mlme.CaliBW40RfR24));
}
/*
add by johnli, RF power sequence setup
==========================================================================
Description:
Load RF normal operation-mode setup
==========================================================================
*/
VOID RT30xxLoadRFNormalModeSetup(
IN PRTMP_ADAPTER pAd)
{
UCHAR RFValue, bbpreg = 0;
{
/* improve power consumption */
RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R138, &bbpreg);
if (pAd->Antenna.field.TxPath == 1)
{
/* turn off tx DAC_1*/
bbpreg = (bbpreg | 0x20);
}
if (pAd->Antenna.field.RxPath == 1)
{
/* turn off tx ADC_1*/
bbpreg &= (~0x2);
}
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R138, bbpreg);
}
/*RX0_PD & TX0_PD, RF R1 register Bit 2 & Bit 3 to 0 and RF_BLOCK_en,RX1_PD & TX1_PD, Bit0, Bit 4 & Bit5 to 1*/
RT30xxReadRFRegister(pAd, RF_R01, &RFValue);
RFValue = (RFValue & (~0x0C)) | 0x31;
RT30xxWriteRFRegister(pAd, RF_R01, RFValue);
/* TX_LO2_en, RF R15 register Bit 3 to 0*/
RT30xxReadRFRegister(pAd, RF_R15, &RFValue);
RFValue &= (~0x08);
RT30xxWriteRFRegister(pAd, RF_R15, RFValue);
/* TX_LO1_en, RF R17 register Bit 3 to 0*/
RT30xxReadRFRegister(pAd, RF_R17, &RFValue);
RFValue &= (~0x08);
/* to fix rx long range issue*/
if (((pAd->MACVersion & 0xffff) >= 0x0211) && (pAd->NicConfig2.field.ExternalLNAForG == 0))
{
RFValue |= 0x20;
}
/* set RF_R17_bit[2:0] equal to EEPROM setting at 0x48h*/
if (pAd->TxMixerGain24G >= 2)
{
RFValue &= (~0x7); /* clean bit [2:0]*/
RFValue |= pAd->TxMixerGain24G;
}
RT30xxWriteRFRegister(pAd, RF_R17, RFValue);
/* RX_LO1_en, RF R20 register Bit 3 to 0*/
RT30xxReadRFRegister(pAd, RF_R20, &RFValue);
RFValue &= (~0x08);
RT30xxWriteRFRegister(pAd, RF_R20, RFValue);
/* RX_LO2_en, RF R21 register Bit 3 to 0*/
RT30xxReadRFRegister(pAd, RF_R21, &RFValue);
RFValue &= (~0x08);
RT30xxWriteRFRegister(pAd, RF_R21, RFValue);
}
/*
==========================================================================
Description:
Load RF sleep-mode setup
==========================================================================
*/
VOID RT30xxLoadRFSleepModeSetup(
IN PRTMP_ADAPTER pAd)
{
UCHAR RFValue;
UINT32 MACValue;
{
/* RF_BLOCK_en. RF R1 register Bit 0 to 0*/
RT30xxReadRFRegister(pAd, RF_R01, &RFValue);
RFValue &= (~0x01);
RT30xxWriteRFRegister(pAd, RF_R01, RFValue);
/* VCO_IC, RF R7 register Bit 4 & Bit 5 to 0*/
RT30xxReadRFRegister(pAd, RF_R07, &RFValue);
RFValue &= (~0x30);
RT30xxWriteRFRegister(pAd, RF_R07, RFValue);
/* Idoh, RF R9 register Bit 1, Bit 2 & Bit 3 to 0*/
RT30xxReadRFRegister(pAd, RF_R09, &RFValue);
RFValue &= (~0x0E);
RT30xxWriteRFRegister(pAd, RF_R09, RFValue);
/* RX_CTB_en, RF R21 register Bit 7 to 0*/
RT30xxReadRFRegister(pAd, RF_R21, &RFValue);
RFValue &= (~0x80);
RT30xxWriteRFRegister(pAd, RF_R21, RFValue);
}
/* Don't touch LDO_CFG0 for 3090F & 3593, possibly the board is single power scheme*/
if (IS_RT3090(pAd) || /*IS_RT3090 including RT309x and RT3071/72*/
(IS_RT3070(pAd) && ((pAd->MACVersion & 0xffff) < 0x0201)))
{
RT30xxReadRFRegister(pAd, RF_R27, &RFValue);
RFValue |= 0x77;
RT30xxWriteRFRegister(pAd, RF_R27, RFValue);
RTMP_IO_READ32(pAd, LDO_CFG0, &MACValue);
MACValue |= 0x1D000000;
RTMP_IO_WRITE32(pAd, LDO_CFG0, MACValue);
}
}
/*
==========================================================================
Description:
Reverse RF sleep-mode setup
==========================================================================
*/
VOID RT30xxReverseRFSleepModeSetup(
IN PRTMP_ADAPTER pAd,
IN BOOLEAN FlgIsInitState)
{
UCHAR RFValue;
UINT32 MACValue;
if(!IS_RT3572(pAd))
{
/* RF_BLOCK_en, RF R1 register Bit 0 to 1*/
RT30xxReadRFRegister(pAd, RF_R01, &RFValue);
RFValue |= 0x01;
RT30xxWriteRFRegister(pAd, RF_R01, RFValue);
/* VCO_IC, RF R7 register Bit 4 & Bit 5 to 1*/
RT30xxReadRFRegister(pAd, RF_R07, &RFValue);
RFValue |= 0x20;
RT30xxWriteRFRegister(pAd, RF_R07, RFValue);
/* Idoh, RF R9 register Bit 1, Bit 2 & Bit 3 to 1*/
RT30xxReadRFRegister(pAd, RF_R09, &RFValue);
RFValue |= 0x0E;
RT30xxWriteRFRegister(pAd, RF_R09, RFValue);
/* RX_CTB_en, RF R21 register Bit 7 to 1*/
RT30xxReadRFRegister(pAd, RF_R21, &RFValue);
RFValue |= 0x80;
RT30xxWriteRFRegister(pAd, RF_R21, RFValue);
}
if (IS_RT3090(pAd) || /* IS_RT3090 including RT309x and RT3071/72*/
IS_RT3390(pAd) ||
(IS_RT3070(pAd) && ((pAd->MACVersion & 0xffff) < 0x0201)))
{
{
RT30xxReadRFRegister(pAd, RF_R27, &RFValue);
if ((pAd->MACVersion & 0xffff) < 0x0211)
RFValue = (RFValue & (~0x77)) | 0x3;
else
RFValue = (RFValue & (~0x77));
RT30xxWriteRFRegister(pAd, RF_R27, RFValue);
}
/* RT3071 version E has fixed this issue*/
if ((pAd->NicConfig2.field.DACTestBit == 1) && ((pAd->MACVersion & 0xffff) < 0x0211))
{
/* patch tx EVM issue temporarily*/
RTMP_IO_READ32(pAd, LDO_CFG0, &MACValue);
MACValue = ((MACValue & 0xE0FFFFFF) | 0x0D000000);
RTMP_IO_WRITE32(pAd, LDO_CFG0, MACValue);
}
else if (!IS_RT3090(pAd))
{
RTMP_IO_READ32(pAd, LDO_CFG0, &MACValue);
MACValue = ((MACValue & 0xE0FFFFFF) | 0x01000000);
RTMP_IO_WRITE32(pAd, LDO_CFG0, MACValue);
}
}
}
/* end johnli*/
VOID RT30xxHaltAction(
IN PRTMP_ADAPTER pAd)
{
UINT32 TxPinCfg = 0x00050F0F;
/* Turn off LNA_PE or TRSW_POL*/
if ((IS_RT3071(pAd) || IS_RT3572(pAd))
#ifdef RTMP_EFUSE_SUPPORT
&& (pAd->bUseEfuse)
#endif /* RTMP_EFUSE_SUPPORT */
)
{
TxPinCfg &= 0xFFFBF0F0; /* bit18 off */
}
else
{
TxPinCfg &= 0xFFFFF0F0;
}
RTMP_IO_WRITE32(pAd, TX_PIN_CFG, TxPinCfg);
}
VOID RT30xx_ChipSwitchChannel(
IN PRTMP_ADAPTER pAd,
IN UCHAR Channel,
IN BOOLEAN bScan)
{
CHAR TxPwer = 0, TxPwer2 = DEFAULT_RF_TX_POWER; /*Bbp94 = BBPR94_DEFAULT, TxPwer2 = DEFAULT_RF_TX_POWER;*/
UCHAR index;
UINT32 Value = 0; /*BbpReg, Value;*/
UCHAR RFValue;
UINT32 i = 0;
#ifdef RT33xx
#ifdef RTMP_MAC_PCI
UCHAR Tx0FinePowerCtrl = 0, Tx1FinePowerCtrl = 0;
BBP_R109_STRUC BbpR109 = {{0}};
#endif
#endif
i = i; /* avoid compile warning */
RFValue = 0;
/* Search Tx power value*/
/*
We can't use ChannelList to search channel, since some central channl's txpowr doesn't list
in ChannelList, so use TxPower array instead.
*/
for (index = 0; index < MAX_NUM_OF_CHANNELS; index++)
{
if (Channel == pAd->TxPower[index].Channel)
{
TxPwer = pAd->TxPower[index].Power;
TxPwer2 = pAd->TxPower[index].Power2;
#ifdef RT33xx
#ifdef RTMP_MAC_PCI
if ((IS_RT3090A(pAd) || IS_RT3390(pAd)) &&
(pAd->infType == RTMP_DEV_INF_PCI || pAd->infType == RTMP_DEV_INF_PCIE))
{
Tx0FinePowerCtrl = pAd->TxPower[index].Tx0FinePowerCtrl;
Tx1FinePowerCtrl = pAd->TxPower[index].Tx1FinePowerCtrl;
}
#endif /* RTMP_MAC_PCI */
#endif /* RT33xx */
break;
}
}
if (index == MAX_NUM_OF_CHANNELS)
{
DBGPRINT(RT_DEBUG_ERROR, ("AsicSwitchChannel: Can't find the Channel#%d \n", Channel));
}
#ifdef RT30xx
/* The RF programming sequence is difference between 3xxx and 2xxx*/
{
/* modify by WY for Read RF Reg. error */
UCHAR calRFValue;
for (index = 0; index < NUM_OF_3020_CHNL; index++)
{
if (Channel == FreqItems3020[index].Channel)
{
/* Programming channel parameters*/
RT30xxWriteRFRegister(pAd, RF_R02, FreqItems3020[index].N);
/*
RT3370/RT3390 RF version is 0x3320 RF_R3 [7:4] is not reserved bits
RF_R3[6:4] (pa1_bc_cck) : PA1 Bias CCK
RF_R3[7] (pa2_cc_cck) : PA2 Cascode Bias CCK
*/
RT30xxReadRFRegister(pAd, RF_R03, (PUCHAR)(&RFValue));
RFValue = (RFValue & 0xF0) | (FreqItems3020[index].K & ~0xF0); /* <bit 3:0>:K<bit 3:0>*/
RT30xxWriteRFRegister(pAd, RF_R03, RFValue);
RT30xxReadRFRegister(pAd, RF_R06, &RFValue);
RFValue = (RFValue & 0xFC) | FreqItems3020[index].R;
RT30xxWriteRFRegister(pAd, RF_R06, RFValue);
/* Set Tx0 Power*/
RT30xxReadRFRegister(pAd, RF_R12, &RFValue);
RFValue = (RFValue & 0xE0) | TxPwer;
RT30xxWriteRFRegister(pAd, RF_R12, RFValue);
/*Set Tx1 Power*/
RT30xxReadRFRegister(pAd, RF_R13, &RFValue);
RFValue = (RFValue & 0xE0) | TxPwer2;
RT30xxWriteRFRegister(pAd, RF_R13, RFValue);
#ifdef RT33xx
#ifdef RTMP_MAC_PCI
/* Set the BBP Tx fine power control in 0.1dB step*/
if ((IS_RT3090A(pAd) || IS_RT3390(pAd)) &&
(pAd->infType == RTMP_DEV_INF_PCI || pAd->infType == RTMP_DEV_INF_PCIE))
{
BbpR109.field.Tx0PowerCtrl = Tx0FinePowerCtrl;
if (pAd->Antenna.field.TxPath >= 2)
{
BbpR109.field.Tx1PowerCtrl = Tx1FinePowerCtrl;
}
else
{
BbpR109.field.Tx1PowerCtrl = 0;
}
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R109, BbpR109.byte);
DBGPRINT(RT_DEBUG_INFO, ("%s: Channel = %d, BBP_R109 = 0x%X\n",
__FUNCTION__,
Channel,
BbpR109.byte));
}
#endif /* RTMP_MAC_PCI */
#endif /* RT33xx */
/* Tx/Rx Stream setting*/
RT30xxReadRFRegister(pAd, RF_R01, &RFValue);
RFValue &= 0x03; /*clear bit[7~2]*/
if (pAd->Antenna.field.TxPath == 1)
RFValue |= 0xA0;
else if (pAd->Antenna.field.TxPath == 2)
RFValue |= 0x80;
if (pAd->Antenna.field.RxPath == 1)
RFValue |= 0x50;
else if (pAd->Antenna.field.RxPath == 2)
RFValue |= 0x40;
RT30xxWriteRFRegister(pAd, RF_R01, RFValue);
/* Set RF offset*/
RT30xxReadRFRegister(pAd, RF_R23, &RFValue);
RFValue = (RFValue & 0x80) | pAd->RfFreqOffset;
RT30xxWriteRFRegister(pAd, RF_R23, RFValue);
/* Set BW*/
if (!bScan && (pAd->CommonCfg.BBPCurrentBW == BW_40))
{
calRFValue = pAd->Mlme.CaliBW40RfR24;
}
else
{
calRFValue = pAd->Mlme.CaliBW20RfR24;
}
/*
RT3370/RT3390 RF version is 0x3320 RF_R24 [7:6] is not reserved bits
RF_R24[6] (BB_Rx1_out_en) : enable baseband output and ADC input
RF_R24[7] (BB_Tx1_out_en) : enable DAC output or baseband input
*/
RT30xxReadRFRegister(pAd, RF_R24, (PUCHAR)(&RFValue));
calRFValue = (RFValue & 0xC0) | (calRFValue & ~0xC0); /* <bit 5>:tx_h20M<bit 5> and <bit 4:0>:tx_agc_fc<bit 4:0>*/
RT30xxWriteRFRegister(pAd, RF_R24, calRFValue);
/*
RT3370/RT3390 RF version is 0x3320 RF_R31 [7:6] is not reserved bits
RF_R31[4:0] (rx_agc_fc) : capacitor control in baseband filter
RF_R31[5] (rx_ h20M) : rx_ h20M: 0=10 MHz and 1=20MHz
RF_R31[7:6] (drv_bc_cck) : Driver Bias CCK
*/
/* Set BW*/
if (IS_RT3390(pAd)) /* RT3390 has different AGC for Tx and Rx*/
{
if (!bScan && (pAd->CommonCfg.BBPCurrentBW == BW_40))
{
calRFValue = pAd->Mlme.CaliBW40RfR31;
}
else
{
calRFValue = pAd->Mlme.CaliBW20RfR31;
}
}
RT30xxReadRFRegister(pAd, RF_R31, (PUCHAR)(&RFValue));
calRFValue = (RFValue & 0xC0) | (calRFValue & ~0xC0); /* <bit 5>:rx_h20M<bit 5> and <bit 4:0>:rx_agc_fc<bit 4:0>*/
RT30xxWriteRFRegister(pAd, RF_R31, calRFValue);
/* Enable RF tuning*/
RT30xxReadRFRegister(pAd, RF_R07, &RFValue);
RFValue = RFValue | 0x1;
RT30xxWriteRFRegister(pAd, RF_R07, RFValue);
RT30xxReadRFRegister(pAd, RF_R30, (PUCHAR)&RFValue);
RFValue |= 0x80;
RT30xxWriteRFRegister(pAd, RF_R30, (UCHAR)RFValue);
RTMPusecDelay(1000);
RFValue &= 0x7F;
RT30xxWriteRFRegister(pAd, RF_R30, (UCHAR)RFValue);
/* latch channel for future usage.*/
pAd->LatchRfRegs.Channel = Channel;
DBGPRINT(RT_DEBUG_TRACE, ("SwitchChannel#%d(RF=%d, Pwr0=%d, Pwr1=%d, %dT), N=0x%02X, K=0x%02X, R=0x%02X\n",
Channel,
pAd->RfIcType,
TxPwer,
TxPwer2,
pAd->Antenna.field.TxPath,
FreqItems3020[index].N,
FreqItems3020[index].K,
FreqItems3020[index].R));
break;
}
}
}
#endif /* RT30xx */
/* Change BBP setting during siwtch from a->g, g->a*/
if (Channel <= 14)
{
ULONG TxPinCfg = 0x00050F0A;/*Gary 2007/08/09 0x050A0A*/
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R62, (0x37 - GET_LNA_GAIN(pAd)));
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R63, (0x37 - GET_LNA_GAIN(pAd)));
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R64, (0x37 - GET_LNA_GAIN(pAd)));
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R86, 0);/*(0x44 - GET_LNA_GAIN(pAd))); According the Rory's suggestion to solve the middle range issue.*/
/* Rx High power VGA offset for LNA select*/
{
if (pAd->NicConfig2.field.ExternalLNAForG)
{
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0x62);
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R75, 0x46);
}
else
{
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0x84);
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R75, 0x50);
}
}
/* 5G band selection PIN, bit1 and bit2 are complement*/
RTMP_IO_READ32(pAd, TX_BAND_CFG, &Value);
Value &= (~0x6);
Value |= (0x04);
RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value);
{
/* Turn off unused PA or LNA when only 1T or 1R*/
if (pAd->Antenna.field.TxPath == 1)
{
TxPinCfg &= 0xFFFFFFF3;
}
if (pAd->Antenna.field.RxPath == 1)
{
TxPinCfg &= 0xFFFFF3FF;
}
}
RTMP_IO_WRITE32(pAd, TX_PIN_CFG, TxPinCfg);
#if defined(RT3090) || defined(RT3390)
/* PCIe PHY Transmit attenuation adjustment*/
if ((IS_RT3090A(pAd) || IS_RT3390(pAd)) && IS_PCIE_INF(pAd))
{
INTERNAL_1_STRUCT Internal_1 = { { 0 } };
RTMP_IO_READ32(pAd, INTERNAL_1, &Internal_1.word);
if (Channel == 14) /* Channel #14*/
{
Internal_1.field.PCIE_PHY_TX_ATTEN_EN = 1; /* Enable PCIe PHY Tx attenuation*/
Internal_1.field.PCIE_PHY_TX_ATTEN_VALUE = 4; /* 9/16 full drive level*/
}
else /* Channel #1~#13*/
{
Internal_1.field.PCIE_PHY_TX_ATTEN_EN = 0; /* Disable PCIe PHY Tx attenuation*/
Internal_1.field.PCIE_PHY_TX_ATTEN_VALUE = 0; /* n/a*/
}
RTMP_IO_WRITE32(pAd, INTERNAL_1, Internal_1.word);
}
#endif
RtmpUpdateFilterCoefficientControl(pAd, Channel);
}
/* R66 should be set according to Channel and use 20MHz when scanning*/
if (bScan)
RTMPSetAGCInitValue(pAd, BW_20);
else
RTMPSetAGCInitValue(pAd, pAd->CommonCfg.BBPCurrentBW);
/*
On 11A, We should delay and wait RF/BBP to be stable
and the appropriate time should be 1000 micro seconds
2005/06/05 - On 11G, We also need this delay time. Otherwise it's difficult to pass the WHQL.
*/
RTMPusecDelay(1000);
}
VOID RT30xx_ChipBBPAdjust(
IN RTMP_ADAPTER *pAd)
{
UINT32 Value;
UCHAR byteValue = 0;
#ifdef DOT11_N_SUPPORT
if ((pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth == BW_40) &&
(pAd->CommonCfg.RegTransmitSetting.field.EXTCHA == EXTCHA_ABOVE)
/*(pAd->CommonCfg.AddHTInfo.AddHtInfo.ExtChanOffset == EXTCHA_ABOVE)*/
)
{
{
pAd->CommonCfg.BBPCurrentBW = BW_40;
pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel + 2;
}
/* TX : control channel at lower */
RTMP_IO_READ32(pAd, TX_BAND_CFG, &Value);
Value &= (~0x1);
RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value);
/* RX : control channel at lower */
RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &byteValue);
byteValue &= (~0x20);
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, byteValue);
RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &byteValue);
byteValue &= (~0x18);
byteValue |= 0x10;
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, byteValue);
/* request by Gary 20070208 for middle and long range G Band*/
AsicBBPWriteWithRxChain(pAd, BBP_R66, 0x38, RX_CHAIN_ALL);
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x12);
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x0A);
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, 0x10);
DBGPRINT(RT_DEBUG_TRACE, ("ApStartUp : ExtAbove, ChannelWidth=%d, Channel=%d, ExtChanOffset=%d(%d) \n",
pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth,
pAd->CommonCfg.Channel,
pAd->CommonCfg.RegTransmitSetting.field.EXTCHA,
pAd->CommonCfg.AddHTInfo.AddHtInfo.ExtChanOffset));
}
else if ((pAd->CommonCfg.Channel > 2) &&
(pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth == BW_40) &&
(pAd->CommonCfg.RegTransmitSetting.field.EXTCHA == EXTCHA_BELOW)
/*(pAd->CommonCfg.AddHTInfo.AddHtInfo.ExtChanOffset == EXTCHA_BELOW)*/)
{
pAd->CommonCfg.BBPCurrentBW = BW_40;
if (pAd->CommonCfg.Channel == 14)
pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel - 1;
else
pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel - 2;
/* TX : control channel at upper */
RTMP_IO_READ32(pAd, TX_BAND_CFG, &Value);
Value |= (0x1);
RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value);
/* RX : control channel at upper */
RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &byteValue);
byteValue |= (0x20);
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, byteValue);
RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &byteValue);
byteValue &= (~0x18);
byteValue |= 0x10;
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, byteValue);
/* request by Gary 20070208 for middle and long range G band*/
AsicBBPWriteWithRxChain(pAd, BBP_R66, 0x38, RX_CHAIN_ALL);
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x12);
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x0A);
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, 0x10);
DBGPRINT(RT_DEBUG_TRACE, ("ApStartUp : ExtBlow, ChannelWidth=%d, Channel=%d, ExtChanOffset=%d(%d) \n",
pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth,
pAd->CommonCfg.Channel,
pAd->CommonCfg.RegTransmitSetting.field.EXTCHA,
pAd->CommonCfg.AddHTInfo.AddHtInfo.ExtChanOffset));
}
else
#endif /* DOT11_N_SUPPORT */
{
pAd->CommonCfg.BBPCurrentBW = BW_20;
pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel;
/* TX : control channel at lower */
RTMP_IO_READ32(pAd, TX_BAND_CFG, &Value);
Value &= (~0x1);
RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value);
RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &byteValue);
byteValue &= (~0x18);
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, byteValue);
/* 20 MHz bandwidth*/
/* request by Gary 20070208*/
/*AsicBBPWriteWithRxChain(pAd, BBP_R66, 0x30, RX_CHAIN_ALL);*/
/*RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, 0x30);*/
/* request by Brian 20070306*/
AsicBBPWriteWithRxChain(pAd, BBP_R66, 0x38, RX_CHAIN_ALL);
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x12);
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x0a);
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, 0x10);
#ifdef DOT11_N_SUPPORT
DBGPRINT(RT_DEBUG_TRACE, ("ApStartUp : 20MHz, ChannelWidth=%d, Channel=%d, ExtChanOffset=%d(%d) \n",
pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth,
pAd->CommonCfg.Channel,
pAd->CommonCfg.RegTransmitSetting.field.EXTCHA,
pAd->CommonCfg.AddHTInfo.AddHtInfo.ExtChanOffset));
#endif /* DOT11_N_SUPPORT */
}
/* request by Gary 20070208 for middle and long range G band*/
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R62, 0x2D);
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R63, 0x2D);
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R64, 0x2D);
/*RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R86, 0x2D);*/
}
VOID RT30xx_ChipAGCInit(
IN PRTMP_ADAPTER pAd,
IN UCHAR BandWidth)
{
UCHAR R66 = 0x30;
if (pAd->LatchRfRegs.Channel <= 14)
{ /* BG band*/
/* Gary was verified Amazon AP and find that RT307x has BBP_R66 invalid default value */
if (IS_RT3070(pAd)||IS_RT3090(pAd) || IS_RT3390(pAd))
{
R66 = 0x1C + 2*GET_LNA_GAIN(pAd);
AsicBBPWriteWithRxChain(pAd, BBP_R66, R66, RX_CHAIN_ALL);
}
}
else
{
/* A band */
if (BandWidth == BW_20)
{
R66 = (UCHAR)(0x32 + (GET_LNA_GAIN(pAd)*5)/3);
AsicBBPWriteWithRxChain(pAd, BBP_R66, R66, RX_CHAIN_ALL);
}
#ifdef DOT11_N_SUPPORT
else
{
R66 = (UCHAR)(0x3A + (GET_LNA_GAIN(pAd)*5)/3);
AsicBBPWriteWithRxChain(pAd, BBP_R66, R66, RX_CHAIN_ALL);
}
#endif // DOT11_N_SUPPORT //
}
}
#endif /* RT30xx */
|
agerwick/RT28XX-RT539X-Linux-driver
|
chips/rt30xx.c
|
C
|
gpl-2.0
| 32,800
|
/*
Nick McComb CS163
2/5/2013
Assignment #2
*/
#include "list.h"
queueNode::queueNode()
{
next = NULL;
}
queueNode::~queueNode()
{
}
//Default Constructor
queueType::queueType()
{
tail = NULL;
}
//Default Destructor
//Tail is used as a 'head' pointer in this function
queueType::~queueType()
{
queueNode * temp = tail->next;
tail->next = NULL;
tail = temp;
while(tail) //Walk through entire list, untill the manufactured end is reached
{
temp = tail->next;
delete tail;
tail = temp;
}
}
int queueType::enqueue(const queueNode & newData)
{
queueNode * temp = new queueNode;
temp->data = newData.data;
if(!tail) //empty list case
{
tail = temp;
tail->next = tail; //Connect the list circularily
}
else
{
temp->next = tail->next; //Connect the end of the new node to the beginning of the list
tail->next = temp; //Appends the new temp node
tail = tail->next; //Advances the tail pointer forward
}
return 1;
}
int queueType::dequeue(queueNode & foundData)
{
if(!tail) //Empty list
return 0;
//Copy data
foundData.data = tail->next->data; //Retrieve the data from the beginnning
//Delete head node
//Check if there is only one node
if(tail->data == tail->next->data)
{
delete tail;
tail = NULL;
}
else //There is more than one node in the list
{
queueNode * temp = tail->next;
tail->next = tail->next->next;
delete temp;
}
return 1;
}
int queueType::peek(queueNode & foundData)
{
if(!tail) //Empty list
return 0;
//Copy data
foundData.data = tail->next->data; //Retrieve the data from the beginning
return 1;
}
int queueType::isEmpty()
{
if(tail)
return 0;
return 1;
}
|
Nrpickle/CS163
|
Homework/Assignment 2/Code/3 - Non working/queue.cpp
|
C++
|
gpl-2.0
| 1,761
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Payment\Test\Unit\Model\Method;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class FreeTest extends \PHPUnit\Framework\TestCase
{
/** @var \Magento\Payment\Model\Method\Free */
protected $methodFree;
/** @var \PHPUnit_Framework_MockObject_MockObject */
protected $scopeConfig;
/** @var \PHPUnit_Framework_MockObject_MockObject */
protected $currencyPrice;
protected function setUp()
{
$paymentData = $this->createMock(\Magento\Payment\Helper\Data::class);
$this->scopeConfig = $this->createMock(\Magento\Framework\App\Config\ScopeConfigInterface::class);
$this->currencyPrice = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class)
->getMock();
$context = $this->createPartialMock(\Magento\Framework\Model\Context::class, ['getEventDispatcher']);
$eventManagerMock = $this->createMock(\Magento\Framework\Event\ManagerInterface::class);
$context->expects($this->any())->method('getEventDispatcher')->willReturn($eventManagerMock);
$registry = $this->createMock(\Magento\Framework\Registry::class);
$extensionAttributesFactory = $this->createMock(\Magento\Framework\Api\ExtensionAttributesFactory::class);
$customAttributeFactory = $this->createMock(\Magento\Framework\Api\AttributeValueFactory::class);
$loggerMock = $this->getMockBuilder(\Magento\Payment\Model\Method\Logger::class)
->setConstructorArgs([$this->getMockForAbstractClass(\Psr\Log\LoggerInterface::class)])
->getMock();
$this->methodFree = new \Magento\Payment\Model\Method\Free(
$context,
$registry,
$extensionAttributesFactory,
$customAttributeFactory,
$paymentData,
$this->scopeConfig,
$loggerMock,
$this->currencyPrice
);
}
/**
* @param string $orderStatus
* @param string $paymentAction
* @param mixed $result
* @dataProvider getConfigPaymentActionProvider
*/
public function testGetConfigPaymentAction($orderStatus, $paymentAction, $result)
{
$this->scopeConfig->expects($this->at(0))
->method('getValue')
->will($this->returnValue($orderStatus));
if ($orderStatus != 'pending') {
$this->scopeConfig->expects($this->at(1))
->method('getValue')
->will($this->returnValue($paymentAction));
}
$this->assertEquals($result, $this->methodFree->getConfigPaymentAction());
}
/**
* @param float $grandTotal
* @param bool $isActive
* @param bool $notEmptyQuote
* @param bool $result
* @dataProvider getIsAvailableProvider
*/
public function testIsAvailable($grandTotal, $isActive, $notEmptyQuote, $result)
{
$quote = null;
if ($notEmptyQuote) {
$quote = $this->createMock(\Magento\Quote\Model\Quote::class);
$quote->expects($this->any())
->method('__call')
->with($this->equalTo('getGrandTotal'))
->will($this->returnValue($grandTotal));
}
$this->currencyPrice->expects($this->any())
->method('round')
->willReturnArgument(0);
$this->scopeConfig->expects($this->any())
->method('getValue')
->will($this->returnValue($isActive));
$this->assertEquals($result, $this->methodFree->isAvailable($quote));
}
/**
* @return array
*/
public function getIsAvailableProvider()
{
return [
[0, true, true, true],
[0.1, true, true, false],
[0, false, false, false],
[1, true, false, false],
[0, true, false, false]
];
}
/**
* @return array
*/
public function getConfigPaymentActionProvider()
{
return [
['pending', 'action', null],
['processing', 'payment_action', 'payment_action']
];
}
}
|
kunj1988/Magento2
|
app/code/Magento/Payment/Test/Unit/Model/Method/FreeTest.php
|
PHP
|
gpl-2.0
| 4,205
|
/*
* Copyright (c) 2014 Max Schrimpf
*
* This file is part of the parallel computing term paper for the Zurich university of applied sciences.
*
* It 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.
*
* The 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
package ch.zhaw.parallelComputing.model.sentiment;
import ch.zhaw.mapreduce.CombinerInstruction;
import ch.zhaw.mapreduce.KeyValuePair;
import java.util.*;
import java.util.logging.Logger;
/**
* Combiner step to reduce the amount of data send from each map task to the master after execution.
* Combines the data for each unique key (time).
*
* Created by Max Schrimpf
*/
public class DateAvgCombiner implements CombinerInstruction {
private static final Logger LOG = Logger.getLogger(DateAvgCombiner.class.getName());
@Override
public List<KeyValuePair> combine(Iterator<KeyValuePair> keyValuePairIterator) {
LOG.entering(getClass().getName(), "combine");
Map<String, Double[]> kvPairs = new HashMap<>();
List<KeyValuePair> returnList = new ArrayList<>();
String key;
Double[] tmp;
while (keyValuePairIterator.hasNext()) {
KeyValuePair pair = keyValuePairIterator.next();
if (kvPairs.containsKey(pair.getKey())) {
tmp = kvPairs.get(pair.getKey());
tmp[0]++;
tmp[1] += Integer.parseInt(pair.getValue());
kvPairs.put(pair.getKey(), tmp);
} else {
kvPairs.put(pair.getKey(), new Double[]{1.0, Double.parseDouble(pair.getValue())});
}
}
Iterator mapIterator = kvPairs.keySet().iterator();
while (mapIterator.hasNext()) {
key = (String) mapIterator.next();
tmp = kvPairs.get(key);
LOG.info("Combined " + tmp[0] + " tweets at " + key);
returnList.add(new KeyValuePair(key, "" + (tmp[1] / tmp[0])));
}
return returnList;
}
}
|
mxmo0rhuhn/seminar_parallel_computing
|
src/main/java/ch/zhaw/parallelComputing/model/sentiment/DateAvgCombiner.java
|
Java
|
gpl-2.0
| 2,496
|
import argparse
import sys
import traceback as tb
from datetime import datetime
from cfme.utils.path import log_path
from cfme.utils.providers import list_provider_keys, get_mgmt
def parse_cmd_line():
parser = argparse.ArgumentParser(argument_default=None)
parser.add_argument('--nic-template',
help='NIC Name template to be removed', default="test", type=str)
parser.add_argument('--pip-template',
help='PIP Name template to be removed', default="test", type=str)
parser.add_argument('--days-old',
help='--days-old argument to find stack items older than X days ',
default="7", type=int)
parser.add_argument("--output", dest="output", help="target file name, default "
"'cleanup_azure.log' in "
"utils.path.log_path",
default=log_path.join('cleanup_azure.log').strpath)
args = parser.parse_args()
return args
def azure_cleanup(nic_template, pip_template, days_old, output):
with open(output, 'w') as report:
report.write('azure_cleanup.py, NICs, PIPs and Stack Cleanup')
report.write("\nDate: {}\n".format(datetime.now()))
try:
for provider_key in list_provider_keys('azure'):
provider_mgmt = get_mgmt(provider_key)
nic_list = provider_mgmt.list_free_nics(nic_template)
report.write("----- Provider: {} -----\n".format(provider_key))
if nic_list:
report.write("Removing Nics with the name \'{}\':\n".format(nic_template))
report.write("\n".join(str(k) for k in nic_list))
report.write("\n")
provider_mgmt.remove_nics_by_search(nic_template)
else:
report.write("No \'{}\' NICs were found\n".format(nic_template))
pip_list = provider_mgmt.list_free_pip(pip_template)
if pip_list:
report.write("Removing Public IPs with the name \'{}\':\n".
format(pip_template))
report.write("\n".join(str(k) for k in pip_list))
report.write("\n")
provider_mgmt.remove_pips_by_search(pip_template)
else:
report.write("No \'{}\' Public IPs were found\n".format(pip_template))
stack_list = provider_mgmt.list_stack(days_old=days_old)
if stack_list:
report.write(
"Removing empty Stacks:\n")
for stack in stack_list:
if provider_mgmt.is_stack_empty(stack):
provider_mgmt.delete_stack(stack)
report.write("Stack {} is empty - Removed\n".format(stack))
else:
report.write("No stacks older than \'{}\' days were found\n".format(
days_old))
return 0
except Exception:
report.write("Something bad happened during Azure cleanup\n")
report.write(tb.format_exc())
return 1
if __name__ == "__main__":
args = parse_cmd_line()
sys.exit(azure_cleanup(args.nic_template, args.pip_template, args.days_old, args.output))
|
jkandasa/integration_tests
|
scripts/azure_cleanup.py
|
Python
|
gpl-2.0
| 3,453
|
<?php
/**
* @version $Id: legacy.php 9764 2007-12-30 07:48:11Z ircmaxell $
* @package Joomla
* @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
* @license GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
/**
* Utility function for writing a menu link
*/
function mosGetMenuLink($mitem, $level = 0, & $params, $open = null)
{
global $Itemid;
$txt = '';
// Menu Link is a special type that is a link to another item
if ($mitem->type == 'menulink')
{
$menu = &JSite::getMenu();
if ($tmp = $menu->getItem($mitem->query['Itemid'])) {
$name = $mitem->name;
$mid = $mitem->id;
$parent = $mitem->parent;
$mitem = clone($tmp);
$mitem->name = $name;
$mitem->mid = $mid;
$mitem->parent = $parent;
} else {
return;
}
}
switch ($mitem->type)
{
case 'separator' :
break;
case 'url' :
if (eregi('index.php\?', $mitem->link)) {
if (!eregi('Itemid=', $mitem->link)) {
$mitem->link .= '&Itemid='.$mitem->id;
}
}
break;
default :
$mitem->link = 'index.php?Itemid='.$mitem->id;
break;
}
// Active Menu highlighting
$current_itemid = intval( $Itemid );
if (!$current_itemid) {
$id = '';
} else {
if ($current_itemid == $mitem->id) {
$id = 'id="active_menu' . $params->get('class_sfx') . '"';
} else {
if ($params->get('activate_parent') && isset ($open) && in_array($mitem->id, $open)) {
$id = 'id="active_menu' . $params->get('class_sfx') . '"';
} else {
if ($mitem->type == 'url' && ItemidContained($mitem->link, $current_itemid)) {
$id = 'id="active_menu' . $params->get('class_sfx') . '"';
} else {
$id = '';
}
}
}
}
if ($params->get('full_active_id'))
{
// support for `active_menu` of 'Link - Url' if link is relative
if ($id == '' && $mitem->type == 'url' && strpos('http', $mitem->link) === false) {
$url = array();
parse_str($mitem->link, $url);
if (isset ($url['Itemid'])) {
if ($url['Itemid'] == $current_itemid) {
$id = 'id="active_menu' . $params->get('class_sfx') . '"';
}
}
}
}
// replace & with amp; for xhtml compliance
$menu_params = new stdClass();
$menu_params = new JParameter($mitem->params);
$menu_secure = $menu_params->def('secure', 0);
if (strcasecmp(substr($mitem->link, 0, 4), 'http')) {
$mitem->url = JRoute::_($mitem->link, true, $menu_secure);
} else {
$mitem->url = $mitem->link;
}
$menuclass = 'mainlevel' . $params->get('class_sfx');
if ($level > 0) {
$menuclass = 'sublevel' . $params->get('class_sfx');
}
// replace & with amp; for xhtml compliance
// remove slashes from excaped characters
$mitem->name = stripslashes(htmlspecialchars($mitem->name));
switch ($mitem->browserNav)
{
// cases are slightly different
case 1 :
// open in a new window
$txt = '<a href="' . $mitem->url . '" target="_blank" class="' . $menuclass . '" ' . $id . '>' . $mitem->name . '</a>';
break;
case 2 :
// open in a popup window
$txt = "<a href=\"#\" onclick=\"javascript: window.open('" . $mitem->url . "', '', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=550'); return false\" class=\"$menuclass\" " . $id . ">" . $mitem->name . "</a>\n";
break;
case 3 :
// don't link it
$txt = '<span class="' . $menuclass . '" ' . $id . '>' . $mitem->name . '</span>';
break;
default : // formerly case 2
// open in parent window
$txt = '<a href="' . $mitem->url . '" class="' . $menuclass . '" ' . $id . '>' . $mitem->name . '</a>';
break;
}
if ($params->get('menu_images'))
{
$menu_params = new stdClass();
$menu_params = new JParameter($mitem->params);
$menu_image = $menu_params->def('menu_image', -1);
if (($menu_image <> '-1') && $menu_image) {
$image = '<img src="'.JURI::base(true).'/images/stories/' . $menu_image . '" border="0" alt="' . $mitem->name . '"/>';
if ($params->get('menu_images_align')) {
$txt = $txt . ' ' . $image;
} else {
$txt = $image . ' ' . $txt;
}
}
}
return $txt;
}
/**
* Vertically Indented Menu
*/
function mosShowVIMenu(& $params)
{
global $mainframe, $Itemid;
$template = $mainframe->getTemplate();
$menu =& JSite::getMenu();
$user =& JFactory::getUser();
// indent icons
switch ($params->get('indent_image')) {
case '1' :
{
// Default images
$imgpath = JURI::base(true).'/images/M_images';
for ($i = 1; $i < 7; $i++) {
$img[$i] = '<img src="' . $imgpath . '/indent' . $i . '.png" alt="" />';
}
}
break;
case '2' :
{
// Use Params
$imgpath = JURI::base(true).'/images/M_images';
for ($i = 1; $i < 7; $i++) {
if ($params->get('indent_image' . $i) == '-1') {
$img[$i] = NULL;
} else {
$img[$i] = '<img src="' . $imgpath . '/' . $params->get('indent_image' . $i) . '" alt="" />';
}
}
}
break;
case '3' :
{
// None
for ($i = 1; $i < 7; $i++) {
$img[$i] = NULL;
}
}
break;
default :
{
// Template
$imgpath = JURI::base(true).'/templates/' . $template . '/images';
for ($i = 1; $i < 7; $i++) {
$img[$i] = '<img src="' . $imgpath . '/indent' . $i . '.png" alt="" />';
}
}
}
$indents = array (
// block prefix / item prefix / item suffix / block suffix
array (
'<table width="100%" border="0" cellpadding="0" cellspacing="0">',
'<tr ><td>',
'</td></tr>',
'</table>'
),
array (
'',
'<div style="padding-left: 4px">' . $img[1],
'</div>',
''
),
array (
'',
'<div style="padding-left: 8px">' . $img[2],
'</div>',
''
),
array (
'',
'<div style="padding-left: 12px">' . $img[3],
'</div>',
''
),
array (
'',
'<div style="padding-left: 16px">' . $img[4],
'</div>',
''
),
array (
'',
'<div style="padding-left: 20px">' . $img[5],
'</div>',
''
),
array (
'',
'<div style="padding-left: 24px">' . $img[6],
'</div>',
''
),
);
// establish the hierarchy of the menu
$children = array ();
//get menu items
$rows = $menu->getItems('menutype', $params->get('menutype'));
// first pass - collect children
$cacheIndex = array();
if(is_array($rows) && count($rows)) {
foreach ($rows as $index => $v) {
if ($v->access <= $user->get('gid')) {
$pt = $v->parent;
$list = @ $children[$pt] ? $children[$pt] : array ();
array_push($list, $v);
$children[$pt] = $list;
}
$cacheIndex[$v->id] = $index;
}
}
// second pass - collect 'open' menus
$open = array (
$Itemid
);
$count = 20; // maximum levels - to prevent runaway loop
$id = $Itemid;
while (-- $count)
{
if (isset($cacheIndex[$id])) {
$index = $cacheIndex[$id];
if (isset ($rows[$index]) && $rows[$index]->parent > 0) {
$id = $rows[$index]->parent;
$open[] = $id;
} else {
break;
}
}
}
mosRecurseVIMenu(0, 0, $children, $open, $indents, $params);
}
/**
* Utility function to recursively work through a vertically indented
* hierarchial menu
*/
function mosRecurseVIMenu($id, $level, & $children, & $open, & $indents, & $params)
{
if (@ $children[$id]) {
$n = min($level, count($indents) - 1);
echo "\n" . $indents[$n][0];
foreach ($children[$id] as $row) {
echo "\n" . $indents[$n][1];
echo mosGetMenuLink($row, $level, $params, $open);
// show menu with menu expanded - submenus visible
if (!$params->get('expand_menu')) {
if (in_array($row->id, $open)) {
mosRecurseVIMenu($row->id, $level +1, $children, $open, $indents, $params);
}
} else {
mosRecurseVIMenu($row->id, $level +1, $children, $open, $indents, $params);
}
echo $indents[$n][2];
}
echo "\n" . $indents[$n][3];
}
}
/**
* Draws a horizontal 'flat' style menu (very simple case)
*/
function mosShowHFMenu(& $params, $style = 0)
{
$menu = & JSite::getMenu();
$user = & JFactory::getUser();
//get menu items
$rows = $menu->getItems('menutype', $params->get('menutype'));
$links = array ();
if(is_array($rows) && count($rows)) {
foreach ($rows as $row)
{
if ($row->access <= $user->get('aid', 0)) {
$links[] = mosGetMenuLink($row, 0, $params);
}
}
}
$menuclass = 'mainlevel' . $params->get('class_sfx');
$lang =& JFactory::getLanguage();
if (count($links))
{
switch ($style)
{
case 1 :
echo '<ul id="' . $menuclass . '">';
foreach ($links as $link) {
echo '<li>' . $link . '</li>';
}
echo '</ul>';
break;
default :
$spacer_start = $params->get('spacer');
$spacer_end = $params->get('end_spacer');
echo '<table width="100%" border="0" cellpadding="0" cellspacing="1">';
echo '<tr>';
echo '<td nowrap="nowrap">';
if ($spacer_end) {
echo '<span class="' . $menuclass . '"> ' . $spacer_end . ' </span>';
}
if ($spacer_start) {
$html = '<span class="' . $menuclass . '"> ' . $spacer_start . ' </span>';
echo implode($html, $links);
} else {
echo implode('', $links);
}
if ($spacer_end) {
echo '<span class="' . $menuclass . '"> ' . $spacer_end . ' </span>';
}
echo '</td>';
echo '</tr>';
echo '</table>';
break;
}
}
}
/**
* Search for Itemid in link
*/
function ItemidContained($link, $Itemid)
{
$link = str_replace('&', '&', $link);
$temp = explode("&", $link);
$linkItemid = "";
foreach ($temp as $value) {
$temp2 = explode("=", $value);
if ($temp2[0] == "Itemid") {
$linkItemid = $temp2[1];
break;
}
}
if ($linkItemid != "" && $linkItemid == $Itemid) {
return true;
} else {
return false;
}
}
|
intelogen/organica
|
templates/theme078/html/mod_mainmenu/legacy.php
|
PHP
|
gpl-2.0
| 10,373
|
/*
Syntax error: Undefined mixin 'container'.
on line 58 of /Users/cmorris/projects/clients/digitalnapkin/sites/all/themes/digitalnapkin/sass/blocks.scss, in `container'
from line 58 of /Users/cmorris/projects/clients/digitalnapkin/sites/all/themes/digitalnapkin/sass/blocks.scss
Backtrace:
/Users/cmorris/projects/clients/digitalnapkin/sites/all/themes/digitalnapkin/sass/blocks.scss:58:in `container'
/Users/cmorris/projects/clients/digitalnapkin/sites/all/themes/digitalnapkin/sass/blocks.scss:58
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/perform.rb:253:in `visit_mixin'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/base.rb:37:in `visit'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/perform.rb:100:in `visit'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/base.rb:53:in `block in visit_children'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/base.rb:53:in `map'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/base.rb:53:in `visit_children'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/perform.rb:109:in `block in visit_children'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/perform.rb:121:in `with_environment'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/perform.rb:108:in `visit_children'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/base.rb:37:in `block in visit'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/perform.rb:320:in `visit_rule'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/base.rb:37:in `visit'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/perform.rb:100:in `visit'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/base.rb:53:in `block in visit_children'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/base.rb:53:in `map'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/base.rb:53:in `visit_children'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/perform.rb:109:in `block in visit_children'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/perform.rb:121:in `with_environment'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/perform.rb:108:in `visit_children'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/base.rb:37:in `block in visit'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/perform.rb:320:in `visit_rule'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/base.rb:37:in `visit'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/perform.rb:100:in `visit'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/base.rb:53:in `block in visit_children'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/base.rb:53:in `map'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/base.rb:53:in `visit_children'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/perform.rb:109:in `block in visit_children'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/perform.rb:121:in `with_environment'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/perform.rb:108:in `visit_children'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/base.rb:37:in `block in visit'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/perform.rb:128:in `visit_root'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/base.rb:37:in `visit'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/perform.rb:100:in `visit'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/visitors/perform.rb:7:in `visit'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/tree/root_node.rb:20:in `render'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/engine.rb:315:in `_render'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/sass-3.2.9/lib/sass/engine.rb:262:in `render'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/compass-0.12.2/lib/compass/compiler.rb:140:in `block (2 levels) in compile'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/compass-0.12.2/lib/compass/compiler.rb:126:in `timed'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/compass-0.12.2/lib/compass/compiler.rb:139:in `block in compile'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/compass-0.12.2/lib/compass/logger.rb:45:in `red'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/compass-0.12.2/lib/compass/compiler.rb:138:in `compile'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/compass-0.12.2/lib/compass/compiler.rb:118:in `compile_if_required'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/compass-0.12.2/lib/compass/compiler.rb:103:in `block (2 levels) in run'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/compass-0.12.2/lib/compass/compiler.rb:101:in `each'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/compass-0.12.2/lib/compass/compiler.rb:101:in `block in run'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/compass-0.12.2/lib/compass/compiler.rb:126:in `timed'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/compass-0.12.2/lib/compass/compiler.rb:100:in `run'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/compass-0.12.2/lib/compass/commands/update_project.rb:45:in `perform'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/compass-0.12.2/lib/compass/commands/base.rb:18:in `execute'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/compass-0.12.2/lib/compass/commands/project_base.rb:19:in `execute'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/compass-0.12.2/lib/compass/exec/sub_command_ui.rb:43:in `perform!'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/compass-0.12.2/lib/compass/exec/sub_command_ui.rb:15:in `run!'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/compass-0.12.2/bin/compass:30:in `block in <top (required)>'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/compass-0.12.2/bin/compass:44:in `call'
/Applications/Koala.app/Contents/Resources/app.nw/rubygems/gems/compass-0.12.2/bin/compass:44:in `<top (required)>'
/Applications/Koala.app/Contents/Resources/app.nw/bin/compass:18:in `load'
/Applications/Koala.app/Contents/Resources/app.nw/bin/compass:18:in `<main>'
*/
body:before {
white-space: pre;
font-family: monospace;
content: "Syntax error: Undefined mixin 'container'.\A on line 58 of /Users/cmorris/projects/clients/digitalnapkin/sites/all/themes/digitalnapkin/sass/blocks.scss, in `container'\A from line 58 of /Users/cmorris/projects/clients/digitalnapkin/sites/all/themes/digitalnapkin/sass/blocks.scss"; }
|
CCI-Studios/Digital-Napkin
|
sites/all/themes/DigitalNapkin/stylesheets/blocks.css
|
CSS
|
gpl-2.0
| 8,127
|
# Copyright (C) 2015 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd 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.
#
# ycmd 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 ycmd. If not, see <http://www.gnu.org/licenses/>.
from ycmd.utils import ToUtf8IfNeeded
from ycmd.completers.completer import Completer
from ycmd import responses, utils, hmac_utils
import logging
import urlparse
import requests
import httplib
import json
import tempfile
import base64
import binascii
import threading
import os
from os import path as p
_logger = logging.getLogger( __name__ )
DIR_OF_THIS_SCRIPT = p.dirname( p.abspath( __file__ ) )
DIR_OF_THIRD_PARTY = utils.PathToNearestThirdPartyFolder( DIR_OF_THIS_SCRIPT )
RACERD_BINARY_NAME = 'racerd' + ( '.exe' if utils.OnWindows() else '' )
RACERD_BINARY = p.join( DIR_OF_THIRD_PARTY,
'racerd', 'target', 'release', RACERD_BINARY_NAME )
RACERD_HMAC_HEADER = 'x-racerd-hmac'
HMAC_SECRET_LENGTH = 16
BINARY_NOT_FOUND_MESSAGE = ( 'racerd binary not found. Did you build it? ' +
'You can do so by running ' +
'"./build.py --racer-completer".' )
ERROR_FROM_RACERD_MESSAGE = (
'Received error from racerd while retrieving completions. You did not '
'set the rust_src_path option, which is probably causing this issue. '
'See YCM docs for details.'
)
def FindRacerdBinary( user_options ):
"""
Find path to racerd binary
This function prefers the 'racerd_binary_path' value as provided in
user_options if available. It then falls back to ycmd's racerd build. If
that's not found, attempts to use racerd from current path.
"""
racerd_user_binary = user_options.get( 'racerd_binary_path' )
if racerd_user_binary:
# The user has explicitly specified a path.
if os.path.isfile( racerd_user_binary ):
return racerd_user_binary
else:
_logger.warn( 'user provided racerd_binary_path is not file' )
if os.path.isfile( RACERD_BINARY ):
return RACERD_BINARY
return utils.PathToFirstExistingExecutable( [ 'racerd' ] )
class RustCompleter( Completer ):
"""
A completer for the rust programming language backed by racerd.
https://github.com/jwilm/racerd
"""
def __init__( self, user_options ):
super( RustCompleter, self ).__init__( user_options )
self._racerd = FindRacerdBinary( user_options )
self._racerd_host = None
self._server_state_lock = threading.RLock()
self._keep_logfiles = user_options[ 'server_keep_logfiles' ]
self._hmac_secret = ''
self._rust_source_path = self._GetRustSrcPath()
if not self._rust_source_path:
_logger.warn( 'No path provided for the rustc source. Please set the '
'rust_src_path option' )
if not self._racerd:
_logger.error( BINARY_NOT_FOUND_MESSAGE )
raise RuntimeError( BINARY_NOT_FOUND_MESSAGE )
self._StartServer()
def _GetRustSrcPath( self ):
"""
Attempt to read user option for rust_src_path. Fallback to environment
variable if it's not provided.
"""
rust_src_path = self.user_options[ 'rust_src_path' ]
# Early return if user provided config
if rust_src_path:
return rust_src_path
# Fall back to environment variable
env_key = 'RUST_SRC_PATH'
if env_key in os.environ:
return os.environ[ env_key ]
return None
def SupportedFiletypes( self ):
return [ 'rust' ]
def _ComputeRequestHmac( self, method, path, body ):
if not body:
body = ''
hmac = hmac_utils.CreateRequestHmac( method, path, body, self._hmac_secret )
return binascii.hexlify( hmac )
def _GetResponse( self, handler, request_data = None, method = 'POST' ):
"""
Query racerd via HTTP
racerd returns JSON with 200 OK responses. 204 No Content responses occur
when no errors were encountered but no completions, definitions, or errors
were found.
"""
_logger.info( 'RustCompleter._GetResponse' )
url = urlparse.urljoin( self._racerd_host, handler )
parameters = self._TranslateRequest( request_data )
body = json.dumps( parameters ) if parameters else None
request_hmac = self._ComputeRequestHmac( method, handler, body )
extra_headers = { 'content-type': 'application/json' }
extra_headers[ RACERD_HMAC_HEADER ] = request_hmac
response = requests.request( method,
url,
data = body,
headers = extra_headers )
response.raise_for_status()
if response.status_code is httplib.NO_CONTENT:
return None
return response.json()
def _TranslateRequest( self, request_data ):
"""
Transform ycm request into racerd request
"""
if not request_data:
return None
file_path = request_data[ 'filepath' ]
buffers = []
for path, obj in request_data[ 'file_data' ].items():
buffers.append( {
'contents': obj[ 'contents' ],
'file_path': path
} )
line = request_data[ 'line_num' ]
col = request_data[ 'column_num' ] - 1
return {
'buffers': buffers,
'line': line,
'column': col,
'file_path': file_path
}
def _GetExtraData( self, completion ):
location = {}
if completion[ 'file_path' ]:
location[ 'filepath' ] = ToUtf8IfNeeded( completion[ 'file_path' ] )
if completion[ 'line' ]:
location[ 'line_num' ] = completion[ 'line' ]
if completion[ 'column' ]:
location[ 'column_num' ] = completion[ 'column' ] + 1
if location:
return { 'location': location }
return None
def ComputeCandidatesInner( self, request_data ):
try:
completions = self._FetchCompletions( request_data )
except requests.HTTPError:
if not self._rust_source_path:
raise RuntimeError( ERROR_FROM_RACERD_MESSAGE )
raise
if not completions:
return []
return [ responses.BuildCompletionData(
insertion_text = ToUtf8IfNeeded( completion[ 'text' ] ),
kind = ToUtf8IfNeeded( completion[ 'kind' ] ),
extra_menu_info = ToUtf8IfNeeded( completion[ 'context' ] ),
extra_data = self._GetExtraData( completion ) )
for completion in completions ]
def _FetchCompletions( self, request_data ):
return self._GetResponse( '/list_completions', request_data )
def _WriteSecretFile( self, secret ):
"""
Write a file containing the `secret` argument. The path to this file is
returned.
Note that racerd consumes the file upon reading; removal of the temp file is
intentionally not handled here.
"""
# Make temp file
secret_fd, secret_path = tempfile.mkstemp( text=True )
# Write secret
with os.fdopen( secret_fd, 'w' ) as secret_file:
secret_file.write( secret )
return secret_path
def _StartServer( self ):
"""
Start racerd.
"""
with self._server_state_lock:
self._hmac_secret = self._CreateHmacSecret()
secret_file_path = self._WriteSecretFile( self._hmac_secret )
port = utils.GetUnusedLocalhostPort()
args = [ self._racerd, 'serve',
'--port', str(port),
'-l',
'--secret-file', secret_file_path ]
# Enable logging of crashes
env = os.environ.copy()
env[ 'RUST_BACKTRACE' ] = '1'
if self._rust_source_path:
args.extend( [ '--rust-src-path', self._rust_source_path ] )
filename_format = p.join( utils.PathToTempDir(),
'racerd_{port}_{std}.log' )
self._server_stdout = filename_format.format( port = port,
std = 'stdout' )
self._server_stderr = filename_format.format( port = port,
std = 'stderr' )
with open( self._server_stderr, 'w' ) as fstderr:
with open( self._server_stdout, 'w' ) as fstdout:
self._racerd_phandle = utils.SafePopen( args,
stdout = fstdout,
stderr = fstderr,
env = env )
self._racerd_host = 'http://127.0.0.1:{0}'.format( port )
_logger.info( 'RustCompleter using host = ' + self._racerd_host )
def ServerIsRunning( self ):
"""
Check racerd status.
"""
with self._server_state_lock:
if not self._racerd_host or not self._racerd_phandle:
return False
try:
self._GetResponse( '/ping', method = 'GET' )
return True
except requests.HTTPError:
self._StopServer()
return False
def ServerIsReady( self ):
try:
self._GetResponse( '/ping', method = 'GET' )
return True
except Exception:
return False
def _StopServer( self ):
"""
Stop racerd.
"""
with self._server_state_lock:
if self._racerd_phandle:
self._racerd_phandle.terminate()
self._racerd_phandle.wait()
self._racerd_phandle = None
self._racerd_host = None
if not self._keep_logfiles:
# Remove stdout log
if self._server_stdout and p.exists( self._server_stdout ):
os.unlink( self._server_stdout )
self._server_stdout = None
# Remove stderr log
if self._server_stderr and p.exists( self._server_stderr ):
os.unlink( self._server_stderr )
self._server_stderr = None
def _RestartServer( self ):
"""
Restart racerd
"""
_logger.debug( 'RustCompleter restarting racerd' )
with self._server_state_lock:
if self.ServerIsRunning():
self._StopServer()
self._StartServer()
_logger.debug( 'RustCompleter has restarted racerd' )
def GetSubcommandsMap( self ):
return {
'GoTo' : ( lambda self, request_data, args:
self._GoToDefinition( request_data ) ),
'GoToDefinition' : ( lambda self, request_data, args:
self._GoToDefinition( request_data ) ),
'GoToDeclaration' : ( lambda self, request_data, args:
self._GoToDefinition( request_data ) ),
'StopServer' : ( lambda self, request_data, args:
self._StopServer() ),
'RestartServer' : ( lambda self, request_data, args:
self._RestartServer() ),
}
def _GoToDefinition( self, request_data ):
try:
definition = self._GetResponse( '/find_definition', request_data )
return responses.BuildGoToResponse( definition[ 'file_path' ],
definition[ 'line' ],
definition[ 'column' ] + 1 )
except Exception:
raise RuntimeError( 'Can\'t jump to definition.' )
def Shutdown( self ):
self._StopServer()
def _CreateHmacSecret( self ):
return base64.b64encode( os.urandom( HMAC_SECRET_LENGTH ) )
def DebugInfo( self, request_data ):
with self._server_state_lock:
if self.ServerIsRunning():
return ( 'racerd\n'
' listening at: {0}\n'
' racerd path: {1}\n'
' stdout log: {2}\n'
' stderr log: {3}').format( self._racerd_host,
self._racerd,
self._server_stdout,
self._server_stderr )
if self._server_stdout and self._server_stderr:
return ( 'racerd is no longer running\n',
' racerd path: {0}\n'
' stdout log: {1}\n'
' stderr log: {2}').format( self._racerd,
self._server_stdout,
self._server_stderr )
return 'racerd is not running'
|
NorfairKing/sus-depot
|
shared/shared/vim/dotvim/bundle/YouCompleteMe/third_party/ycmd/ycmd/completers/rust/rust_completer.py
|
Python
|
gpl-2.0
| 12,458
|
/////////////////////////////////////////////////////////////
// EXAMPLE PROGRAM #1
// 02.2008 aralbrec
//
// Ten software-rotated masked sprites move in straight lines
// at various speeds, bouncing off screen edges. All ten
// share the same sprite graphic which is not animated in
// this first test program.
/////////////////////////////////////////////////////////////
// zcc +ts2068 -vn ex1.c -o ex1.bin -create-app -lsp1 -lmalloc
#include <sprites/sp1.h>
#include <malloc.h>
#include <ts2068.h>
#include <string.h>
#pragma output STACKPTR=47104 // place stack at $b800 at startup
long heap; // malloc's heap pointer
// Memory Allocation Policy // the sp1 library will call these functions
// to allocate and deallocate dynamic memory
void *u_malloc(uint size) {
return malloc(size);
}
void u_free(void *addr) {
free(addr);
}
// Clipping Rectangle for Sprites
struct sp1_Rect cr = {0, 0, 64, 24}; // rectangle covering the full screen
// Table Holding Movement Data for Each Sprite
struct sprentry {
struct sp1_ss *s; // sprite handle returned by sp1_CreateSpr()
char dx; // signed horizontal speed in pixels
char dy; // signed vertical speed in pixels
};
struct sprentry sprtbl[] = { // doubled the dx speed compared to spectrum
{0,2,0}, {0,0,1}, {0,2,2}, {0,4,1}, {0,2,3}, // because we're traversing double the horizontal res
{0,6,1}, {0,4,3}, {0,6,2}, {0,2,1}, {0,4,2}
};
// A Hashed UDG for Background
uchar hash[] = {0x55,0xaa,0x55,0xaa,0x55,0xaa,0x55,0xaa};
// Attach C Variable to Sprite Graphics Declared in ASM at End of File
extern uchar gr_window[]; // gr_window will hold the address of the asm label _gr_window
main()
{
uchar i;
struct sp1_ss *s;
struct sprentry *se;
void *temp;
#asm
di
#endasm
// Initialize MALLOC.LIB
heap = 0L; // heap is empty
sbrk(40000, 5000); // add 40000-44999 to malloc
// Set 512x192 Video Mode
memset(16384, 0, 6144); // clear both halves of the display file before switching video mode
memset(24576, 0, 6144);
ts_vmod(PAPER_BLACK | VMOD_HIRES); // select 64-col mode with black background
// Initialize SP1.LIB
sp1_Initialize(SP1_IFLAG_MAKE_ROTTBL | SP1_IFLAG_OVERWRITE_TILES | SP1_IFLAG_OVERWRITE_DFILE, ' ');
sp1_TileEntry(' ', hash); // redefine graphic associated with space character
sp1_Invalidate(&cr); // invalidate entire screen so that it is all initially drawn
sp1_UpdateNow(); // draw screen area managed by sp1 now
// Create Ten Masked Software-Rotated Sprites
for (i=0; i!=10; i++) {
s = sprtbl[i].s = sp1_CreateSpr(SP1_DRAW_MASK2LB, SP1_TYPE_2BYTE, 3, 0, i);
sp1_AddColSpr(s, SP1_DRAW_MASK2, 0, 48, i);
sp1_AddColSpr(s, SP1_DRAW_MASK2RB, 0, 0, i);
sp1_MoveSprAbs(s, &cr, gr_window, 10, 14, 0, 4);
};
while (1) { // main loop
sp1_UpdateNow(); // draw screen now
for (i=0; i!=10; i++) { // move all sprites
se = &sprtbl[i];
sp1_MoveSprRel(se->s, &cr, 0, 0, 0, se->dy, se->dx);
if (se->s->row > 21) // if sprite went off screen, reverse direction
se->dy = - se->dy;
if (se->s->col > 61) // notice if coord moves less than 0, it becomes
se->dx = - se->dx; // 255 which is also caught by these cases
}
} // end main loop
}
#asm
defb @11111111, @00000000
defb @11111111, @00000000
defb @11111111, @00000000
defb @11111111, @00000000
defb @11111111, @00000000
defb @11111111, @00000000
defb @11111111, @00000000
; ASM source file created by SevenuP v1.20
; SevenuP (C) Copyright 2002-2006 by Jaime Tejedor Gomez, aka Metalbrain
;GRAPHIC DATA:
;Pixel Size: ( 16, 24)
;Char Size: ( 2, 3)
;Sort Priorities: Mask, Char line, Y char, X char
;Data Outputted: Gfx
;Interleave: Sprite
;Mask: Yes, before graphic
._gr_window
DEFB 128,127, 0,192, 0,191, 30,161
DEFB 30,161, 30,161, 30,161, 0,191
DEFB 0,191, 30,161, 30,161, 30,161
DEFB 30,161, 0,191, 0,192,128,127
DEFB 255, 0,255, 0,255, 0,255, 0
DEFB 255, 0,255, 0,255, 0,255, 0
DEFB 1,254, 0, 3, 0,253,120,133
DEFB 120,133,120,133,120,133, 0,253
DEFB 0,253,120,133,120,133,120,133
DEFB 120,133, 0,253, 0, 3, 1,254
DEFB 255, 0,255, 0,255, 0,255, 0
DEFB 255, 0,255, 0,255, 0,255, 0
#endasm
|
bitfixer/bitfixer
|
dg/z88dk/libsrc/sprites/software/sp1/ts2068hr/examples/ex1.c
|
C
|
gpl-2.0
| 4,865
|
class Account < ActiveRecord::Base
attr_accessible :email, :id, :password
end
|
fionasboots/competencyTestingQuestions
|
app/models/account.rb
|
Ruby
|
gpl-2.0
| 80
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" lang="<?php print $language->language; ?>" dir="<?php print $language->dir; ?>">
<head>
<title><?php echo $head_title;?></title>
<?php print $head; ?>
<?php //print $scripts;
?>
<link type="text/css" rel="stylesheet" href="<?php echo $base_path.drupal_get_path('theme', 'zen').'/zen-internals/css/jscal2.css'; ?>" />
<link href="<?php echo $base_path.drupal_get_path('theme', 'zen').'/zen-internals/css/virtue.css?20130310'; ?>" rel="stylesheet" type="text/css" />
<body class="virtue">
<div class="main">
<?php include_once 'common/header.php';?>
<div class="content">
<?php include_once 'common/topnav.php';?>
<div id="topsliderbox">
<div id="topslider" class="nivoSlider">
<img src="/sites/all/themes/zen/zen-internals/images/pinknew/banner_bj.jpg" alt="" data-transition="slideInLeft"/>
<img src="/sites/all/themes/zen/zen-internals/images/pinknew/banner_db.jpg" alt="" data-transition="slideInLeft"/>
<img src="/sites/all/themes/zen/zen-internals/images/pinknew/banner_dld.jpg" alt="" data-transition="slideInLeft"/>
<img src="/sites/all/themes/zen/zen-internals/images/pinknew/banner_meb.jpg" alt="" data-transition="slideInLeft"/>
<img src="/sites/all/themes/zen/zen-internals/images/pinknew/banner_ny.jpg" alt="" data-transition="slideInLeft"/>
</div>
<link rel="stylesheet" href="/sites/all/themes/zen/zen-internals/plugins/nivo-slider/nivo-slider.css" type="text/css" media="screen" />
<script type="text/javascript" src="/sites/all/themes/zen/zen-internals/plugins/nivo-slider/jquery.nivo.slider.pack.js"></script>
<script type="text/javascript">
$(window).load(function() {
$('#topslider').nivoSlider();
});
</script>
</div>
<?php echo $breadcrumb;?>
<div class="content-inner">
<!-- content start -->
<?php global $base_url;?>
<div id="content" class="row">
<div class="left">
<div class="virtueth"></div>
<div class="ningjiangtai">
<div class="awardusers">
<?php
$block = module_invoke('content_custom', 'block', 'view', 20);
print $block['content'];
?>
</div>
</div>
<div class="box">
<?php if($content['uservirtues']):?>
<div class="box_top"></div>
<div id="list" class="box_content">
<?php foreach($content['uservirtues'] as $item):?>
<dl>
<dt>
<p class="user"><a href="/user/<?php echo $item["uid"]?>/cover"><?php echo $item['uname'];?></a></p>
<p><span class="title"><?php echo $item['title'];?></span><?php echo l('查看全部', 'node/'.$item['nid'])?></p>
<?php if($item["image"]):?>
<p>
<img class="commentimg" style="width:100px;cursor:pointer;" src="/<?php echo $item["image"] ?>">
</p>
<?php endif;?>
</dt>
<dd>
<div class="date"><?php echo $item['date'];?></div>
<!-- Baidu Button BEGIN -->
<div id="bdshare" class="bdshare_t bds_tools get-codes-bdshare" data="{'text':'<?php echo $item['title'];?>','pic':'<?php echo $base_url.'/'.$item["image"]; ?>'}">
<a class="bds_qzone"></a>
<a class="bds_tsina"></a>
<a class="bds_tqq"></a>
<a class="bds_renren"></a>
<a class="bds_t163"></a>
<span class="bds_more"></span>
<a class="shareCount"></a>
</div>
<script type="text/javascript" id="bdshare_js" data="type=tools&uid=0" ></script>
<script type="text/javascript" id="bdshell_js"></script>
<script type="text/javascript">
document.getElementById("bdshell_js").src = "http://bdimg.share.baidu.com/static/js/shell_v2.js?cdnversion=" + Math.ceil(new Date()/3600000)
</script>
<!-- Baidu Button END -->
<div class="button">
<?php echo l('评论', 'node/'.$item['nid'],array('attributes' => array('class'=>'comment')));?>
<div class="comcount"><?php if($content['uservirtues_count'][$item['nid']] ->count):?><?echo $content['uservirtues_count'][$item['nid']] ->count; ?><?php else:?>0<?php endif;?></div>
<?php echo $item["vote"];?>
</div>
</dd>
</dl>
<?php endforeach;?>
</div>
<div class="box_bottom"></div>
<?php endif;?>
<div class="pagerbox">
<?php echo theme('pager', array('','','','',''));?>
<script type="text/javascript">
$("ul.pager li").hover(function(){$(this).addClass("hover");},function(){$(this).removeClass("hover");});
</script>
</div>
<div class="clear"></div>
</div>
</div>
<div class="right">
<a <?php if($logged_in):?>href="/node/add/daily-virtue"<?php endif;?> ><div class="calendar-top"></div></a>
<div class="calendar">
<div id="cont"></div>
</div>
<div class="clear"></div>
<div class="form">
<?php echo drupal_get_form('_cc_custom_virtue_form');?>
</div>
</div>
</div>
<!-- content end -->
</div>
<div class="clear"></div>
</div>
<?php include_once 'common/footer.php';?>
</div>
</body>
</html>
<script src="<?php echo $base_path.drupal_get_path('theme', 'zen').'/zen-internals/js/jcarousellite_1.0.1.min.js'; ?>" type="text/javascript"></script>
<script type="text/javascript">
$(".awardusers").jCarouselLite({
auto: 1100,
speed: 1000,
scroll: 1,
visible: 4
});
</script>
<script src="<?php echo $base_path.drupal_get_path('theme', 'zen').'/zen-internals/js/jscal2.js' ?>"></script>
<script src="<?php echo $base_path.drupal_get_path('theme', 'zen').'/zen-internals/js/cn.js' ?>"></script>
<script type="text/javascript">
var LEFT_CAL = Calendar.setup({
cont: "cont",
weekNumbers: false,
selectionType: Calendar.SEL_MULTIPLE,
//showTime: 12,
onSelect : function() {
var date = this.selection.get()[0];
var datestr = date.toString();
year = datestr.substr(0,4);
month = datestr.substr(4,2);
day = datestr.substr(6,4);
window.location = '/virtue/'+year+'-'+month+'-'+day;
}
// titleFormat: "%B %Y"
});
LEFT_CAL.setLanguage('cn');
</script>
<?php print $closure; ?>
</body>
<script type="text/javascript">
$(document).ready(function(){
$("#edit-content").focus(function(){
if($(this).attr("value") == "请填入成长记录"){
$(this).attr("value", "");
}
});
$("#edit-submit-1").hover(function(){$(this).addClass("hover");},function(){$(this).removeClass("hover");});
$(".commentimg").click(function(){
if($(this).css("width") == '100px'){
$(this).css("width",'auto').css('max-width','600px');
}
else{
$(this).css("width",'100px').css('max-width','');
}
});
})
</script>
</html>
|
edwardyy/aeb
|
sites/all/themes/zen/templates/page-virtue.tpl.php
|
PHP
|
gpl-2.0
| 7,154
|
/*
* This file is part of the TASCAR software, see <http://tascar.org/>
*
* Copyright (c) 2018 Giso Grimm
* Copyright (c) 2019 Giso Grimm
* Copyright (c) 2020 Giso Grimm
* Copyright (c) 2021 Giso Grimm
*/
/*
* TASCAR 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, version 3 of the License.
*
* TASCAR is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHATABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License, version 3 for more details.
*
* You should have received a copy of the GNU General Public License,
* Version 3 along with TASCAR. If not, see <http://www.gnu.org/licenses/>.
*/
// Author: Giso Grimm
#include "irrender.h"
#include "errorhandling.h"
#include <string.h>
#include <unistd.h>
TASCAR::wav_render_t::wav_render_t(const std::string& tscname,
const std::string& scene_, bool verbose)
: session_core_t(tscname, LOAD_FILE, tscname), scene(scene_), pscene(NULL),
verbose_(verbose), t0(clock()), t1(clock()), t2(clock())
{
read_xml();
if(!pscene)
throw TASCAR::ErrMsg("Scene " + scene + " not found.");
}
TASCAR::wav_render_t::~wav_render_t()
{
if(pscene)
delete pscene;
}
void TASCAR::wav_render_t::add_scene(tsccfg::node_t sne)
{
if((!pscene) &&
(scene.empty() || (tsccfg::node_get_attribute_value(sne,"name") == scene))) {
pscene = new render_core_t(sne);
} else {
if(pscene && (pscene->name == tsccfg::node_get_attribute_value(sne,"name")))
throw TASCAR::ErrMsg("A scene of name \"" + pscene->name +
"\" already exists in the session.");
}
}
void TASCAR::wav_render_t::set_ism_order_range(uint32_t ism_min,
uint32_t ism_max)
{
if(pscene)
pscene->set_ism_order_range(ism_min, ism_max);
}
std::vector<size_t> get_chmap(const std::vector<size_t>& chmap, size_t& nch)
{
std::vector<size_t> m;
if(chmap.empty()) {
for(size_t k = 0; k < nch; ++k)
m.push_back(k);
} else {
for(auto c : chmap)
if(c < nch)
m.push_back(c);
else
TASCAR::add_warning("Ignoring channel " + std::to_string(c) +
" (only " + std::to_string(nch) +
" channels are available).");
}
nch = m.size();
return m;
}
void TASCAR::wav_render_t::render(uint32_t fragsize, double srate,
double duration, const std::string& ofname,
double starttime, bool b_dynamic)
{
if(!pscene)
throw TASCAR::ErrMsg("No scene loaded");
// open sound files:
if(duration == 0)
duration = session_core_t::duration;
int64_t iduration(srate * duration);
chunk_cfg_t cf(srate, fragsize, 1);
uint32_t num_fragments((uint32_t)((iduration - 1) / cf.n_fragment) + 1);
// configure maximum delayline length:
double maxdist(duration * (pscene->c));
for(std::vector<TASCAR::Scene::sound_t*>::iterator isnd =
pscene->sounds.begin();
isnd != pscene->sounds.end(); ++isnd) {
if((*isnd)->maxdist > maxdist)
(*isnd)->maxdist = maxdist;
}
// initialize scene:
pscene->prepare(cf);
pscene->post_prepare();
add_licenses(this);
pscene->add_licenses(this);
size_t nch_in(pscene->num_input_ports());
size_t nch_out_scene(pscene->num_output_ports());
size_t nch_out = nch_out_scene;
std::vector<size_t> chmap = get_chmap(ochannels, nch_out);
sndfile_handle_t sf_out(ofname, cf.f_sample, nch_out);
// allocate io audio buffer:
float* sf_out_buf(new float[nch_out * cf.n_fragment]);
// allocate render audio buffer:
std::vector<float*> a_in;
for(uint32_t k = 0; k < nch_in; ++k) {
a_in.push_back(new float[cf.n_fragment]);
memset(a_in.back(), 0, sizeof(float) * cf.n_fragment);
}
std::vector<float*> a_out;
for(size_t k = 0; k < nch_out_scene; ++k) {
a_out.push_back(new float[cf.n_fragment]);
memset(a_out.back(), 0, sizeof(float) * cf.n_fragment);
}
TASCAR::transport_t tp;
tp.rolling = true;
tp.session_time_seconds = starttime;
tp.session_time_samples = starttime * cf.f_sample;
tp.object_time_seconds = starttime;
tp.object_time_samples = starttime * cf.f_sample;
pscene->process(cf.n_fragment, tp, a_in, a_out);
if(verbose_)
std::cerr << "rendering " << pscene->active_pointsources << " of "
<< pscene->total_pointsources << " point sources.\n";
t1 = clock();
int64_t n(0);
for(uint32_t k = 0; k < num_fragments; ++k) {
// load audio chunk from file
for(uint32_t kf = 0; kf < cf.n_fragment; ++kf)
for(uint32_t kc = 0; kc < nch_in; ++kc)
a_in[kc][kf] = 0.0f;
// process audio:
pscene->process(cf.n_fragment, tp, a_in, a_out);
// save audio:
for(uint32_t kf = 0; kf < cf.n_fragment; ++kf)
for(uint32_t kc = 0; kc < nch_out; ++kc)
sf_out_buf[kc + nch_out * kf] = a_out[chmap[kc]][kf];
sf_out.writef_float(
sf_out_buf,
std::max((int64_t)0, std::min(iduration - n, (int64_t)cf.n_fragment)));
// increment time:
if(b_dynamic) {
tp.session_time_samples += cf.n_fragment;
tp.session_time_seconds = ((double)tp.session_time_samples) / cf.f_sample;
tp.object_time_samples += cf.n_fragment;
tp.object_time_seconds = ((double)tp.object_time_samples) / cf.f_sample;
}
n += cf.n_fragment;
}
t2 = clock();
pscene->release();
// de-allocate render audio buffer:
for(uint32_t k = 0; k < nch_in; ++k)
delete[] a_in[k];
for(uint32_t k = 0; k < nch_out_scene; ++k)
delete[] a_out[k];
delete[] sf_out_buf;
}
void TASCAR::wav_render_t::render(uint32_t fragsize, const std::string& ifname,
const std::string& ofname, double starttime,
bool b_dynamic)
{
if(!pscene)
throw TASCAR::ErrMsg("No scene loaded");
// open sound files:
sndfile_handle_t sf_in(ifname);
chunk_cfg_t cf(sf_in.get_srate(), std::min(fragsize, sf_in.get_frames()),
sf_in.get_channels());
chunk_cfg_t cffile(cf);
uint32_t num_fragments((uint32_t)((sf_in.get_frames() - 1) / cf.n_fragment) +
1);
// configure maximum delayline length: the maximum meaningful length
// is the length of the sound file:
double maxdist((sf_in.get_frames() + 1) / cf.f_sample * (pscene->c));
for(std::vector<TASCAR::Scene::sound_t*>::iterator isnd =
pscene->sounds.begin();
isnd != pscene->sounds.end(); ++isnd) {
if((*isnd)->maxdist > maxdist)
(*isnd)->maxdist = maxdist;
}
// initialize scene:
pscene->prepare(cf);
pscene->post_prepare();
add_licenses(this);
pscene->add_licenses(this);
uint32_t nch_in(pscene->num_input_ports());
size_t nch_out_scene(pscene->num_output_ports());
size_t nch_out = nch_out_scene;
std::vector<size_t> chmap = get_chmap(ochannels, nch_out);
sndfile_handle_t sf_out(ofname, cf.f_sample, nch_out);
// allocate io audio buffer:
float* sf_in_buf(new float[cffile.n_channels * cffile.n_fragment]);
float* sf_out_buf(new float[nch_out * cf.n_fragment]);
// allocate render audio buffer:
std::vector<float*> a_in;
for(uint32_t k = 0; k < nch_in; ++k) {
a_in.push_back(new float[cffile.n_fragment]);
memset(a_in.back(), 0, sizeof(float) * cffile.n_fragment);
}
std::vector<float*> a_out;
for(uint32_t k = 0; k < nch_out_scene; ++k) {
a_out.push_back(new float[cf.n_fragment]);
memset(a_out.back(), 0, sizeof(float) * cf.n_fragment);
}
TASCAR::transport_t tp;
tp.rolling = true;
tp.session_time_seconds = starttime;
tp.session_time_samples = starttime * cf.f_sample;
tp.object_time_seconds = starttime;
tp.object_time_samples = starttime * cf.f_sample;
pscene->process(cf.n_fragment, tp, a_in, a_out);
if(verbose_)
std::cerr << "rendering " << pscene->active_pointsources << " of "
<< pscene->total_pointsources << " point sources.\n";
t1 = clock();
for(uint32_t k = 0; k < num_fragments; ++k) {
// load audio chunk from file
uint32_t n_in(sf_in.readf_float(sf_in_buf, cffile.n_fragment));
if(n_in > 0) {
if(n_in < cffile.n_fragment)
memset(&(sf_in_buf[n_in * cffile.n_channels]), 0,
(cffile.n_fragment - n_in) * cffile.n_channels * sizeof(float));
for(uint32_t kf = 0; kf < cffile.n_fragment; ++kf)
for(uint32_t kc = 0; kc < nch_in; ++kc)
if(kc < cffile.n_channels)
a_in[kc][kf] = sf_in_buf[kc + cffile.n_channels * kf];
else
a_in[kc][kf] = 0.0f;
// process audio:
pscene->process(cf.n_fragment, tp, a_in, a_out);
// save audio:
for(uint32_t kf = 0; kf < cf.n_fragment; ++kf)
for(uint32_t kc = 0; kc < nch_out; ++kc)
sf_out_buf[kc + nch_out * kf] = a_out[chmap[kc]][kf];
sf_out.writef_float(sf_out_buf, n_in);
// increment time:
if(b_dynamic) {
tp.session_time_samples += cf.n_fragment;
tp.session_time_seconds =
((double)tp.session_time_samples) / cf.f_sample;
tp.object_time_samples += cf.n_fragment;
tp.object_time_seconds = ((double)tp.object_time_samples) / cf.f_sample;
}
}
}
t2 = clock();
pscene->release();
// de-allocate render audio buffer:
for(uint32_t k = 0; k < nch_in; ++k)
delete[] a_in[k];
for(uint32_t k = 0; k < nch_out_scene; ++k)
delete[] a_out[k];
delete[] sf_in_buf;
delete[] sf_out_buf;
}
void TASCAR::wav_render_t::render_ir(uint32_t len, double fs,
const std::string& ofname,
double starttime, uint32_t inputchannel)
{
if(!pscene)
throw TASCAR::ErrMsg("No scene loaded");
// configure maximum delayline length:
double maxdist((len + 1) / fs * (pscene->c));
// std::vector<TASCAR::Scene::sound_t*> snds(pscene->linearize_sounds());
for(std::vector<TASCAR::Scene::sound_t*>::iterator isnd =
pscene->sounds.begin();
isnd != pscene->sounds.end(); ++isnd) {
(*isnd)->maxdist = maxdist;
}
chunk_cfg_t cf(fs, len);
// initialize scene:
pscene->prepare(cf);
pscene->post_prepare();
add_licenses(this);
pscene->add_licenses(this);
uint32_t nch_in(pscene->num_input_ports());
if(inputchannel >= nch_in)
throw TASCAR::ErrMsg("Input channel number " +
TASCAR::to_string(inputchannel) +
" is not smaller than number of input channels (" +
TASCAR::to_string(nch_in) + ").");
size_t nch_out_scene(pscene->num_output_ports());
size_t nch_out = nch_out_scene;
std::vector<size_t> chmap = get_chmap(ochannels, nch_out);
sndfile_handle_t sf_out(ofname, fs, nch_out);
// allocate io audio buffer:
float* sf_out_buf(new float[nch_out * len]);
// allocate render audio buffer:
std::vector<float*> a_in;
for(uint32_t k = 0; k < nch_in; ++k) {
a_in.push_back(new float[len]);
memset(a_in.back(), 0, sizeof(float) * len);
}
std::vector<float*> a_out;
for(uint32_t k = 0; k < nch_out_scene; ++k) {
a_out.push_back(new float[len]);
memset(a_out.back(), 0, sizeof(float) * len);
}
TASCAR::transport_t tp;
tp.rolling = false;
tp.session_time_seconds = starttime;
tp.session_time_samples = starttime * fs;
tp.object_time_seconds = starttime;
tp.object_time_samples = starttime * fs;
pscene->process(len, tp, a_in, a_out);
if(verbose_)
std::cerr << "rendering " << pscene->active_pointsources << " of "
<< pscene->total_pointsources << " point sources.\n";
a_in[inputchannel][0] = 1.0f;
// process audio:
pscene->process(len, tp, a_in, a_out);
// save audio:
for(uint32_t kf = 0; kf < len; ++kf)
for(uint32_t kc = 0; kc < nch_out; ++kc)
sf_out_buf[kc + nch_out * kf] = a_out[chmap[kc]][kf];
sf_out.writef_float(sf_out_buf, len);
// increment time:
// de-allocate render audio buffer:
pscene->release();
for(uint32_t k = 0; k < nch_in; ++k)
delete[] a_in[k];
for(uint32_t k = 0; k < nch_out_scene; ++k)
delete[] a_out[k];
delete[] sf_out_buf;
}
void TASCAR::wav_render_t::validate_attributes(std::string& msg) const
{
root.validate_attributes(msg);
if( pscene )
pscene->validate_attributes(msg);
}
void TASCAR::wav_render_t::set_channelmap( const std::vector<size_t>& channels )
{
ochannels = channels;
}
void TASCAR::wav_render_t::reset_channelmap()
{
ochannels.clear();
}
/*
* Local Variables:
* mode: c++
* c-basic-offset: 2
* indent-tabs-mode: nil
* compile-command: "make -C .."
* End:
*/
|
gisogrimm/tascar
|
libtascar/src/irrender.cc
|
C++
|
gpl-2.0
| 12,774
|
/**************************************************************************************
* Copyright (C) 2008 EsperTech, Inc. All rights reserved. *
* http://esper.codehaus.org *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
**************************************************************************************/
package com.espertech.esper.epl.expression;
import com.espertech.esper.epl.agg.access.AggregationAccessor;
import com.espertech.esper.epl.agg.aggregator.AggregationMethod;
import com.espertech.esper.epl.agg.service.AggregationMethodFactory;
import com.espertech.esper.epl.agg.service.AggregationSpec;
import com.espertech.esper.epl.core.MethodResolutionService;
public class ExprLastEverNodeFactory implements AggregationMethodFactory
{
private final Class childType;
private final boolean hasFilter;
public ExprLastEverNodeFactory(Class childType, boolean hasFilter) {
this.childType = childType;
this.hasFilter = hasFilter;
}
public Class getResultType()
{
return childType;
}
public AggregationSpec getSpec(boolean isMatchRecognize)
{
return null;
}
public AggregationAccessor getAccessor()
{
throw new UnsupportedOperationException();
}
public AggregationMethod make(MethodResolutionService methodResolutionService, int agentInstanceId, int groupId, int aggregationId) {
return methodResolutionService.makeLastEverValueAggregator(agentInstanceId, groupId, aggregationId, childType, hasFilter);
}
public AggregationMethodFactory getPrototypeAggregator() {
return this;
}
}
|
mobile-event-processing/Asper
|
source/src/com/espertech/esper/epl/expression/ExprLastEverNodeFactory.java
|
Java
|
gpl-2.0
| 2,060
|
ALTER TABLE wiki_pages
ADD CONSTRAINT wiki_pages_name_uniq UNIQUE (name);
|
klenin/cats-main
|
sql/migrations/20180424-wiki-name.firebird.sql
|
SQL
|
gpl-2.0
| 78
|
/* stats.c, coding statistics */
/* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
/*
* Disclaimer of Warranty
*
* These software programs are available to the user without any license fee or
* royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
* any and all warranties, whether express, implied, or statuary, including any
* implied warranties or merchantability or of fitness for a particular
* purpose. In no event shall the copyright-holder be liable for any
* incidental, punitive, or consequential damages of any kind whatsoever
* arising from the use of these programs.
*
* This disclaimer of warranty extends to the user of these programs and user's
* customers, employees, agents, transferees, successors, and assigns.
*
* The MPEG Software Simulation Group does not represent or warrant that the
* programs furnished hereunder are free of infringement of any third-party
* patents.
*
* Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
* are subject to royalty fees to patent holders. Many of these patents are
* general enough such that they are unavoidable regardless of implementation
* design.
*
*/
/* Modifications and enhancements (C) 2000/2001 Andrew Stevens */
/* These modifications are 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 <config.h>
#include <stdio.h>
#include <math.h>
#include "global.h"
#ifdef OUTPUT_STAT
static void calcSNR1(org,rec,lx,w,h,pv,pe)
unsigned char *org;
unsigned char *rec;
int lx,w,h;
double *pv,*pe;
{
int i, j;
double v1, s1, s2, e2;
s1 = s2 = e2 = 0.0;
for (j=0; j<h; j++)
{
for (i=0; i<w; i++)
{
v1 = org[i];
s1+= v1;
s2+= v1*v1;
v1-= rec[i];
e2+= v1*v1;
}
org += lx;
rec += lx;
}
s1 /= w*h;
s2 /= w*h;
e2 /= w*h;
/* prevent division by zero in calcSNR() */
if(e2==0.0)
e2 = 0.00001;
*pv = s2 - s1*s1; /* variance */
*pe = e2; /* MSE */
}
#endif
void calcSNR(Picture *picture)
{
#ifdef OUTPUT_STAT
uint8_t **org = picture->curorg;
uint8_t **rec = picture->curref;
int w,h,offs;
double v,e;
w = horizontal_size;
h = (cur_picture.pict_struct==FRAME_PICTURE) ? vertical_size : (vertical_size>>1);
offs = (cur_picture.pict_struct==BOTTOM_FIELD) ? width : 0;
calcSNR1(org[0]+offs,rec[0]+offs,width2,w,h,&v,&e);
fprintf(statfile,"Y: variance=%4.4g, MSE=%3.3g (%3.3g dB), SNR=%3.3g dB\n",
v, e, 10.0*log10(255.0*255.0/e), 10.0*log10(v/e));
if (chroma_format!=CHROMA444)
{
w >>= 1;
offs >>= 1;
}
if (chroma_format==CHROMA420)
h >>= 1;
calcSNR1(org[1]+offs,rec[1]+offs,chrom_width2,w,h,&v,&e);
fprintf(statfile,"U: variance=%4.4g, MSE=%3.3g (%3.3g dB), SNR=%3.3g dB\n",
v, e, 10.0*log10(255.0*255.0/e), 10.0*log10(v/e));
calcSNR1(org[2]+offs,rec[2]+offs,chrom_width2,w,h,&v,&e);
fprintf(statfile,"V: variance=%4.4g, MSE=%3.3g (%3.3g dB), SNR=%3.3g dB\n",
v, e, 10.0*log10(255.0*255.0/e), 10.0*log10(v/e));
#endif
}
void stats(void)
{
#ifdef OUTPUT_STAT
int i, j, k, mb_type;
int n_skipped, n_intra, n_ncoded, n_blocks, n_interp, n_forward, n_backward;
struct mbinfo *mbi;
/* Needs adjusting to reflect its move... */
#ifdef NOT_DONE_YET
if (cur_picture.pict_type!=I_TYPE)
{
fprintf(statfile," forward search window: %d...%d / %d...%d\n",
-sxf,sxf,-syf,syf);
fprintf(statfile," forward vector range: %d...%d.5 / %d...%d.5\n",
-(4<<cur_picture.forw_hor_f_code),(4<<cur_picture.forw_hor_f_code)-1,
-(4<<cur_picture.forw_vert_f_code),(4<<cur_picture.forw_vert_f_code)-1);
}
if (cur_picture.pict_type==B_TYPE)
{
fprintf(statfile," backward search window: %d...%d / %d...%d\n",
-sxb,sxb,-syb,syb);
fprintf(statfile," backward vector range: %d...%d.5 / %d...%d.5\n",
-(4<<cur_picture.back_hor_f_code),(4<<cur_picture.back_hor_f_code)-1,
-(4<<cur_picture.back_vert_f_code),(4<<cur_picture.back_vert_f_code)-1);
}
#endif
n_skipped=n_intra=n_ncoded=n_blocks=n_interp=n_forward=n_backward=0;
for (k=0; k<mb_per_pict; k++)
{
mbi = cur_picture.mbinfo+k;
if (mbi->skipped)
n_skipped++;
else if (mbi->mb_type & MB_INTRA)
n_intra++;
else if (!(mbi->mb_type & MB_PATTERN))
n_ncoded++;
for (i=0; i<block_count; i++)
if (mbi->cbp & (1<<i))
n_blocks++;
if (mbi->mb_type & MB_FORWARD)
{
if (mbi->mb_type & MB_BACKWARD)
n_interp++;
else
n_forward++;
}
else if (mbi->mb_type & MB_BACKWARD)
n_backward++;
}
fprintf(statfile,"\npicture statistics:\n");
fprintf(statfile," # of intra coded macroblocks: %4d (%.1f%%)\n",
n_intra,100.0*(double)n_intra/mb_per_pict);
fprintf(statfile," # of coded blocks: %4d (%.1f%%)\n",
n_blocks,100.0*(double)n_blocks/(block_count*mb_per_pict));
fprintf(statfile," # of not coded macroblocks: %4d (%.1f%%)\n",
n_ncoded,100.0*(double)n_ncoded/mb_per_pict);
fprintf(statfile," # of skipped macroblocks: %4d (%.1f%%)\n",
n_skipped,100.0*(double)n_skipped/mb_per_pict);
fprintf(statfile," # of forw. pred. macroblocks: %4d (%.1f%%)\n",
n_forward,100.0*(double)n_forward/mb_per_pict);
fprintf(statfile," # of backw. pred. macroblocks: %4d (%.1f%%)\n",
n_backward,100.0*(double)n_backward/mb_per_pict);
fprintf(statfile," # of interpolated macroblocks: %4d (%.1f%%)\n",
n_interp,100.0*(double)n_interp/mb_per_pict);
fprintf(statfile,"\nmacroblock_type map:\n");
k = 0;
for (j=0; j<mb_height2; j++)
{
for (i=0; i<mb_width; i++)
{
mbi = cur_picture.mbinfo + k;
mb_type = mbi->mb_type;
if (mbi->skipped)
putc('S',statfile);
else if (mb_type & MB_INTRA)
putc('I',statfile);
else switch (mb_type & (MB_FORWARD|MB_BACKWARD))
{
case MB_FORWARD:
putc(mbi->motion_type==MC_FIELD ? 'f' :
mbi->motion_type==MC_DMV ? 'p' :
'F',statfile); break;
case MB_BACKWARD:
putc(mbi->motion_type==MC_FIELD ? 'b' :
'B',statfile); break;
case MB_FORWARD|MB_BACKWARD:
putc(mbi->motion_type==MC_FIELD ? 'd' :
'D',statfile); break;
default:
putc('0',statfile); break;
}
if (mb_type & MB_QUANT)
putc('Q',statfile);
else if (mb_type & (MB_PATTERN|MB_INTRA))
putc(' ',statfile);
else
putc('N',statfile);
putc(' ',statfile);
k++;
}
putc('\n',statfile);
}
fprintf(statfile,"\nmquant map:\n");
k=0;
for (j=0; j<mb_height2; j++)
{
for (i=0; i<mb_width; i++)
{
if (i==0 || cur_picture.mbinfo[k].mquant!=cur_picture.mbinfo[k-1].mquant)
fprintf(statfile,"%3d",cur_picture.mbinfo[k].mquant);
else
fprintf(statfile," ");
k++;
}
putc('\n',statfile);
}
#if 0
fprintf(statfile,"\ncbp map:\n");
k=0;
for (j=0; j<mb_height2; j++)
{
for (i=0; i<mb_width; i++)
{
fprintf(statfile,"%02x ",mbinfo[k].cbp);
k++;
}
putc('\n',statfile);
}
if (pict_struct==FRAME_PICTURE && !frame_pred_dct)
{
fprintf(statfile,"\ndct_type map:\n");
k=0;
for (j=0; j<mb_height2; j++)
{
for (i=0; i<mb_width; i++)
{
if (mbinfo[k].mb_type & (MB_PATTERN|MB_INTRA))
fprintf(statfile,"%d ",mbinfo[k].dct_type);
else
fprintf(statfile," ");
k++;
}
putc('\n',statfile);
}
}
#endif
if (cur_picture.pict_type!=I_TYPE )
{
fprintf(statfile,"\nforward motion vectors (first vector, horizontal):\n");
k=0;
for (j=0; j<mb_height2; j++)
{
for (i=0; i<mb_width; i++)
{
if (cur_picture.mbinfo[k].mb_type & MB_FORWARD)
fprintf(statfile,"%4d",cur_picture.mbinfo[k].MV[0][0][0]);
else
fprintf(statfile," .");
k++;
}
putc('\n',statfile);
}
fprintf(statfile,"\nforward motion vectors (first vector, vertical):\n");
k=0;
for (j=0; j<mb_height2; j++)
{
for (i=0; i<mb_width; i++)
{
if (cur_picture.mbinfo[k].mb_type & MB_FORWARD)
fprintf(statfile,"%4d",cur_picture.mbinfo[k].MV[0][0][1]);
else
fprintf(statfile," .");
k++;
}
putc('\n',statfile);
}
fprintf(statfile,"\nforward motion vectors (second vector, horizontal):\n");
k=0;
for (j=0; j<mb_height2; j++)
{
for (i=0; i<mb_width; i++)
{
if (cur_picture.mbinfo[k].mb_type & MB_FORWARD
&& ((cur_picture.pict_struct==FRAME_PICTURE && cur_picture.mbinfo[k].motion_type==MC_FIELD) ||
(cur_picture.pict_struct!=FRAME_PICTURE && cur_picture.mbinfo[k].motion_type==MC_16X8)))
fprintf(statfile,"%4d",cur_picture.mbinfo[k].MV[1][0][0]);
else
fprintf(statfile," .");
k++;
}
putc('\n',statfile);
}
fprintf(statfile,"\nforward motion vectors (second vector, vertical):\n");
k=0;
for (j=0; j<mb_height2; j++)
{
for (i=0; i<mb_width; i++)
{
if (cur_picture.mbinfo[k].mb_type & MB_FORWARD
&& ((cur_picture.pict_struct==FRAME_PICTURE && cur_picture.mbinfo[k].motion_type==MC_FIELD) ||
(cur_picture.pict_struct!=FRAME_PICTURE && cur_picture.mbinfo[k].motion_type==MC_16X8)))
fprintf(statfile,"%4d",cur_picture.mbinfo[k].MV[1][0][1]);
else
fprintf(statfile," .");
k++;
}
putc('\n',statfile);
}
}
if (cur_picture.pict_type==B_TYPE)
{
fprintf(statfile,"\nbackward motion vectors (first vector, horizontal):\n");
k=0;
for (j=0; j<mb_height2; j++)
{
for (i=0; i<mb_width; i++)
{
if (cur_picture.mbinfo[k].mb_type & MB_BACKWARD)
fprintf(statfile,"%4d",cur_picture.mbinfo[k].MV[0][1][0]);
else
fprintf(statfile," .");
k++;
}
putc('\n',statfile);
}
fprintf(statfile,"\nbackward motion vectors (first vector, vertical):\n");
k=0;
for (j=0; j<mb_height2; j++)
{
for (i=0; i<mb_width; i++)
{
if (cur_picture.mbinfo[k].mb_type & MB_BACKWARD)
fprintf(statfile,"%4d",cur_picture.mbinfo[k].MV[0][1][1]);
else
fprintf(statfile," .");
k++;
}
putc('\n',statfile);
}
fprintf(statfile,"\nbackward motion vectors (second vector, horizontal):\n");
k=0;
for (j=0; j<mb_height2; j++)
{
for (i=0; i<mb_width; i++)
{
if (cur_picture.mbinfo[k].mb_type & MB_BACKWARD
&& ((cur_picture.pict_struct==FRAME_PICTURE && cur_picture.mbinfo[k].motion_type==MC_FIELD) ||
(cur_picture.pict_struct!=FRAME_PICTURE && cur_picture.mbinfo[k].motion_type==MC_16X8)))
fprintf(statfile,"%4d",cur_picture.mbinfo[k].MV[1][1][0]);
else
fprintf(statfile," .");
k++;
}
putc('\n',statfile);
}
fprintf(statfile,"\nbackward motion vectors (second vector, vertical):\n");
k=0;
for (j=0; j<mb_height2; j++)
{
for (i=0; i<mb_width; i++)
{
if (cur_picture.mbinfo[k].mb_type & MB_BACKWARD
&& ((cur_picture.pict_struct==FRAME_PICTURE && cur_picture.mbinfo[k].motion_type==MC_FIELD) ||
(cur_picture.pict_struct!=FRAME_PICTURE && cur_picture.mbinfo[k].motion_type==MC_16X8)))
fprintf(statfile,"%4d",cur_picture.mbinfo[k].MV[1][1][1]);
else
fprintf(statfile," .");
k++;
}
putc('\n',statfile);
}
}
if( frame_num < 10 || frame_num > 24 )
return;
/* useful for debugging */
fprintf(statfile,"\nmacroblock info dump:\n");
k=0;
for (j=10; j<mb_height2; j++)
{
for (i=0; i<mb_width; i++)
{
k = j*mb_width+i;
fprintf(statfile,"(%d,%d): %02x %1.1f %d %3.1f %02x %d\n",
i,j,
cur_picture.mbinfo[k].mb_type,
cur_picture.mbinfo[k].N_act,
cur_picture.mbinfo[k].mquant,
cur_picture.mbinfo[k].act,
cur_picture.mbinfo[k].cbp,
cur_picture.mbinfo[k].skipped );
}
}
#if 0
k=0;
for (j=8; j<10; j++)
{
for (i=14; i<17; i++)
{
k = j*mb_width+i;
fprintf(statfile,"(%d,%d): %02x %d %d %d %d %d %d %d %d %d %d %d %d %d\n",
i,j,
cur_picture.mbinfo[k].motion_type,
cur_picture.mbinfo[k].dct_type,
cur_picture.mbinfo[k].MV[0][0][0],
cur_picture.mbinfo[k].MV[0][0][1],
cur_picture.mbinfo[k].MV[0][1][0],
cur_picture.mbinfo[k].MV[0][1][1],
cur_picture.mbinfo[k].MV[1][0][0],
cur_picture.mbinfo[k].MV[1][0][1],
cur_picture.mbinfo[k].MV[1][1][0],
cur_picture.mbinfo[k].MV[1][1][1],
cur_picture.mbinfo[k].mv_field_sel[0][0],
cur_picture.mbinfo[k].mv_field_sel[0][1],
cur_picture.mbinfo[k].mv_field_sel[1][0],
cur_picture.mbinfo[k].mv_field_sel[1][1]);
}
}
#endif
#endif
}
|
BackupTheBerlios/avidemux
|
avidemux/ADM_libraries/ADM_libmpeg2enc/stats.cc
|
C++
|
gpl-2.0
| 13,857
|
/**
* Created by qufan on 2015/7/28 0028.
*/
var Sequelize = require('sequelize');
var sequelize = require('./../lib/mysqlHelper');
var db = sequelize.db;
var orm_video_cc_callback = db.define('video_cc_callback',
{
id:{
type:Sequelize.INTEGER,
primaryKey:true,
autoIncrement:true
},
ctime:{type:Sequelize.DATE},
videoid:{type:Sequelize.STRING},
status:{type:Sequelize.STRING},
during:{type:Sequelize.INTEGER},
image:{type:Sequelize.STRING},
json:{type:Sequelize.STRING}
},
{
tableName:'video_cc_callback'
}
);
module.exports = orm_video_cc_callback;
|
im4ever/express_angularjs
|
models/video_cc_callback_model.js
|
JavaScript
|
gpl-2.0
| 678
|
/*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.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, see <http://www.gnu.org/licenses/>.
*/
#include "Battleground.h"
#include "BattlegroundRV.h"
#include "ObjectAccessor.h"
#include "Language.h"
#include "Player.h"
#include "WorldPacket.h"
#include "GameObject.h"
BattlegroundRV::BattlegroundRV()
{
BgObjects.resize(BG_RV_OBJECT_MAX);
StartDelayTimes[BG_STARTING_EVENT_FIRST] = BG_START_DELAY_1M;
StartDelayTimes[BG_STARTING_EVENT_SECOND] = BG_START_DELAY_30S;
StartDelayTimes[BG_STARTING_EVENT_THIRD] = BG_START_DELAY_15S;
StartDelayTimes[BG_STARTING_EVENT_FOURTH] = BG_START_DELAY_NONE;
StartMessageIds[BG_STARTING_EVENT_FIRST] = LANG_ARENA_ONE_MINUTE;
StartMessageIds[BG_STARTING_EVENT_SECOND] = LANG_ARENA_THIRTY_SECONDS;
StartMessageIds[BG_STARTING_EVENT_THIRD] = LANG_ARENA_FIFTEEN_SECONDS;
StartMessageIds[BG_STARTING_EVENT_FOURTH] = LANG_ARENA_HAS_BEGUN;
}
BattlegroundRV::~BattlegroundRV() { }
void BattlegroundRV::PostUpdateImpl(uint32 diff)
{
if (GetStatus() != STATUS_IN_PROGRESS)
return;
if (getTimer() < diff)
{
switch (getState())
{
case BG_RV_STATE_OPEN_FENCES:
// Open fire (only at game start)
for (uint8 i = BG_RV_OBJECT_FIRE_1; i <= BG_RV_OBJECT_FIREDOOR_2; ++i)
DoorOpen(i);
setTimer(BG_RV_CLOSE_FIRE_TIMER);
setState(BG_RV_STATE_CLOSE_FIRE);
break;
case BG_RV_STATE_CLOSE_FIRE:
for (uint8 i = BG_RV_OBJECT_FIRE_1; i <= BG_RV_OBJECT_FIREDOOR_2; ++i)
DoorClose(i);
// Fire got closed after five seconds, leaves twenty seconds before toggling pillars
setTimer(BG_RV_FIRE_TO_PILLAR_TIMER);
setState(BG_RV_STATE_SWITCH_PILLARS);
SwitchDynLos();
break;
case BG_RV_STATE_SWITCH_PILLARS:
for (uint8 i = BG_RV_OBJECT_PILAR_1; i <= BG_RV_OBJECT_PULLEY_2; ++i)
DoorOpen(i);
TogglePillarCollision();
setTimer(BG_RV_PILLAR_SWITCH_TIMER);
break;
}
}
else
setTimer(getTimer() - diff);
}
void BattlegroundRV::StartingEventCloseDoors()
{
}
void BattlegroundRV::StartingEventOpenDoors()
{
// Buff respawn
SpawnBGObject(BG_RV_OBJECT_BUFF_1, 90);
SpawnBGObject(BG_RV_OBJECT_BUFF_2, 90);
// Elevators
DoorOpen(BG_RV_OBJECT_ELEVATOR_1);
DoorOpen(BG_RV_OBJECT_ELEVATOR_2);
setState(BG_RV_STATE_OPEN_FENCES);
setTimer(BG_RV_FIRST_TIMER);
// Add all DynLoS to the map
m_DynLos[0] = GetBgMap()->AddDynLOSObject(763.632385f, -306.162384f, 25.909504f, BG_RV_PILLAR_SMALL_RADIUS, BG_RV_PILLAR_SMALL_HEIGHT);
m_DynLos[1] = GetBgMap()->AddDynLOSObject(763.611145f, -261.856750f, 25.909504f, BG_RV_PILLAR_SMALL_RADIUS, BG_RV_PILLAR_SMALL_HEIGHT);
m_DynLos[2] = GetBgMap()->AddDynLOSObject(723.644287f, -284.493256f, 24.648525f, BG_RV_PILLAR_BIG_RADIUS, BG_RV_PILLAR_BIG_RADIUS);
m_DynLos[3] = GetBgMap()->AddDynLOSObject(802.211609f, -284.493256f, 24.648525f, BG_RV_PILLAR_BIG_RADIUS, BG_RV_PILLAR_BIG_HEIGHT);
// Activate the small ones
for (uint8 i = 0; i <= 1; i++)
GetBgMap()->SetDynLOSObjectState(m_DynLos[i], true);
// Should be false at first, TogglePillarCollision will do it.
SetPillarCollision(true);
TogglePillarCollision();
}
void BattlegroundRV::AddPlayer(Player* player)
{
Battleground::AddPlayer(player);
PlayerScores[player->GetGUID()] = new BattlegroundScore;
UpdateWorldState(BG_RV_WORLD_STATE_A, GetAlivePlayersCountByTeam(ALLIANCE));
UpdateWorldState(BG_RV_WORLD_STATE_H, GetAlivePlayersCountByTeam(HORDE));
}
void BattlegroundRV::RemovePlayer(Player* /*player*/, uint64 /*guid*/, uint32 /*team*/)
{
if (GetStatus() == STATUS_WAIT_LEAVE)
return;
UpdateWorldState(BG_RV_WORLD_STATE_A, GetAlivePlayersCountByTeam(ALLIANCE));
UpdateWorldState(BG_RV_WORLD_STATE_H, GetAlivePlayersCountByTeam(HORDE));
CheckArenaWinConditions();
}
void BattlegroundRV::HandleKillPlayer(Player* player, Player* killer)
{
if (GetStatus() != STATUS_IN_PROGRESS)
return;
if (!killer)
{
sLog->outError(LOG_FILTER_BATTLEGROUND, "BattlegroundRV: Killer player not found");
return;
}
Battleground::HandleKillPlayer(player, killer);
UpdateWorldState(BG_RV_WORLD_STATE_A, GetAlivePlayersCountByTeam(ALLIANCE));
UpdateWorldState(BG_RV_WORLD_STATE_H, GetAlivePlayersCountByTeam(HORDE));
CheckArenaWinConditions();
}
bool BattlegroundRV::HandlePlayerUnderMap(Player* player)
{
// Wait for elevators to Go up, before start checking for UnderMaped players
if(GetStartTime() < uint32(StartDelayTimes[BG_STARTING_EVENT_FIRST] + 20*IN_MILLISECONDS))
return true;
player->TeleportTo(GetMapId(), 763.5f, -284, 28.276f, 2.422f);
return true;
}
void BattlegroundRV::HandleAreaTrigger(Player* player, uint32 trigger)
{
if (GetStatus() != STATUS_IN_PROGRESS)
return;
switch (trigger)
{
case 5224:
case 5226:
// fire was removed in 3.2.0
case 5473:
case 5474:
break;
default:
Battleground::HandleAreaTrigger(player, trigger);
break;
}
}
void BattlegroundRV::FillInitialWorldStates(WorldPacket &data)
{
data << uint32(BG_RV_WORLD_STATE_A) << uint32(GetAlivePlayersCountByTeam(ALLIANCE));
data << uint32(BG_RV_WORLD_STATE_H) << uint32(GetAlivePlayersCountByTeam(HORDE));
data << uint32(BG_RV_WORLD_STATE) << uint32(1);
}
void BattlegroundRV::Reset()
{
//call parent's class reset
Battleground::Reset();
}
bool BattlegroundRV::SetupBattleground()
{
// elevators
if (!AddObject(BG_RV_OBJECT_ELEVATOR_1, BG_RV_OBJECT_TYPE_ELEVATOR_1, 763.536377f, -294.535767f, 0.505383f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY)
|| !AddObject(BG_RV_OBJECT_ELEVATOR_2, BG_RV_OBJECT_TYPE_ELEVATOR_2, 763.506348f, -273.873352f, 0.505383f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY)
// buffs
|| !AddObject(BG_RV_OBJECT_BUFF_1, BG_RV_OBJECT_TYPE_BUFF_1, 735.551819f, -284.794678f, 28.276682f, 0.034906f, 0, 0, 0, RESPAWN_IMMEDIATELY)
|| !AddObject(BG_RV_OBJECT_BUFF_2, BG_RV_OBJECT_TYPE_BUFF_2, 791.224487f, -284.794464f, 28.276682f, 2.600535f, 0, 0, 0, RESPAWN_IMMEDIATELY)
// fire
|| !AddObject(BG_RV_OBJECT_FIRE_1, BG_RV_OBJECT_TYPE_FIRE_1, 743.543457f, -283.799469f, 28.286655f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY)
|| !AddObject(BG_RV_OBJECT_FIRE_2, BG_RV_OBJECT_TYPE_FIRE_2, 782.971802f, -283.799469f, 28.286655f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY)
|| !AddObject(BG_RV_OBJECT_FIREDOOR_1, BG_RV_OBJECT_TYPE_FIREDOOR_1, 743.711060f, -284.099609f, 27.542587f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY)
|| !AddObject(BG_RV_OBJECT_FIREDOOR_2, BG_RV_OBJECT_TYPE_FIREDOOR_2, 783.221252f, -284.133362f, 27.535686f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY)
// Gear
|| !AddObject(BG_RV_OBJECT_GEAR_1, BG_RV_OBJECT_TYPE_GEAR_1, 763.664551f, -261.872986f, 26.686588f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY)
|| !AddObject(BG_RV_OBJECT_GEAR_2, BG_RV_OBJECT_TYPE_GEAR_2, 763.578979f, -306.146149f, 26.665222f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY)
// Pulley
|| !AddObject(BG_RV_OBJECT_PULLEY_1, BG_RV_OBJECT_TYPE_PULLEY_1, 700.722290f, -283.990662f, 39.517582f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY)
|| !AddObject(BG_RV_OBJECT_PULLEY_2, BG_RV_OBJECT_TYPE_PULLEY_2, 826.303833f, -283.996429f, 39.517582f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY)
// Pilars
|| !AddObject(BG_RV_OBJECT_PILAR_1, BG_RV_OBJECT_TYPE_PILAR_1, 763.632385f, -306.162384f, 25.909504f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY)
|| !AddObject(BG_RV_OBJECT_PILAR_2, BG_RV_OBJECT_TYPE_PILAR_2, 723.644287f, -284.493256f, 24.648525f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY)
|| !AddObject(BG_RV_OBJECT_PILAR_3, BG_RV_OBJECT_TYPE_PILAR_3, 763.611145f, -261.856750f, 25.909504f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY)
|| !AddObject(BG_RV_OBJECT_PILAR_4, BG_RV_OBJECT_TYPE_PILAR_4, 802.211609f, -284.493256f, 24.648525f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY)
// Pilars Collision
|| !AddObject(BG_RV_OBJECT_PILAR_COLLISION_1, BG_RV_OBJECT_TYPE_PILAR_COLLISION_1, 763.632385f, -306.162384f, 30.639660f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY)
|| !AddObject(BG_RV_OBJECT_PILAR_COLLISION_2, BG_RV_OBJECT_TYPE_PILAR_COLLISION_2, 723.644287f, -284.493256f, 32.382710f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY)
|| !AddObject(BG_RV_OBJECT_PILAR_COLLISION_3, BG_RV_OBJECT_TYPE_PILAR_COLLISION_3, 763.611145f, -261.856750f, 30.639660f, 0.000000f, 0, 0, 0, RESPAWN_IMMEDIATELY)
|| !AddObject(BG_RV_OBJECT_PILAR_COLLISION_4, BG_RV_OBJECT_TYPE_PILAR_COLLISION_4, 802.211609f, -284.493256f, 32.382710f, 3.141593f, 0, 0, 0, RESPAWN_IMMEDIATELY)
)
{
sLog->outError(LOG_FILTER_SQL, "BatteGroundRV: Failed to spawn some object!");
return false;
}
return true;
}
void BattlegroundRV::TogglePillarCollision()
{
bool apply = GetPillarCollision();
for (uint8 i = BG_RV_OBJECT_PILAR_1; i <= BG_RV_OBJECT_PILAR_COLLISION_4; ++i)
{
if (GameObject* gob = GetBgMap()->GetGameObject(BgObjects[i]))
{
if (i >= BG_RV_OBJECT_PILAR_COLLISION_1)
{
uint32 _state = GO_STATE_READY;
if (gob->GetGOInfo()->door.startOpen)
_state = GO_STATE_ACTIVE;
gob->SetGoState(apply ? (GOState)_state : (GOState)(!_state));
if (gob->GetGOInfo()->door.startOpen)
gob->EnableCollision(!apply); // Forced collision toggle
}
for (BattlegroundPlayerMap::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr)
if (Player* player = ObjectAccessor::FindPlayer(MAKE_NEW_GUID(itr->first, 0, HIGHGUID_PLAYER)))
gob->SendUpdateToPlayer(player);
}
}
SetPillarCollision(!apply);
}
void BattlegroundRV::SwitchDynLos()
{
// switch all DynLos to the opposite state
for (uint8 i = 0; i <= 3; i++)
GetBgMap()->SetDynLOSObjectState(m_DynLos[i], !GetBgMap()->GetDynLOSObjectState(m_DynLos[i]));
// Force every pillar to update their status to players
for (BattlegroundPlayerMap::const_iterator itr = GetPlayers().begin(); itr != GetPlayers().end(); ++itr)
{
Player *player = ObjectAccessor::FindPlayer(itr->first);
if (!player)
continue;
if(GameObject* pilar = GetBGObject(BG_RV_OBJECT_PILAR_1))
pilar->SendUpdateToPlayer(player);
if(GameObject* pilar = GetBGObject(BG_RV_OBJECT_PILAR_2))
pilar->SendUpdateToPlayer(player);
if(GameObject* pilar = GetBGObject(BG_RV_OBJECT_PILAR_3))
pilar->SendUpdateToPlayer(player);
if(GameObject* pilar = GetBGObject(BG_RV_OBJECT_PILAR_4))
pilar->SendUpdateToPlayer(player);
}
}
|
bogzybodo/FrozenCore-3.3.5
|
src/server/game/Battlegrounds/Zones/BattlegroundRV.cpp
|
C++
|
gpl-2.0
| 11,869
|
/* ************************************************************************
qooxdoo - the new era of web development
http://qooxdoo.org
Copyright:
2004-2008 1&1 Internet AG, Germany, http://www.1und1.de
License:
LGPL: http://www.gnu.org/licenses/lgpl.html
EPL: http://www.eclipse.org/org/documents/epl-v10.php
See the LICENSE file in the project's top-level directory for details.
Authors:
* Sebastian Werner (wpbasti)
* Andreas Ecker (ecker)
************************************************************************ */
/* ************************************************************************
************************************************************************ */
/**
* Optimized version of SuperTextile
* @deprecated: Old stuff, even does not work correctly. String performance is
* quite slow. Better to omit these stuff at all at client side.
*/
qx.Class.define("qx.legacy.html.Textile",
{
/*
*****************************************************************************
STATICS
*****************************************************************************
*/
statics :
{
/**
* Textilizes a string
* http://www.textism.com/tools/textile/
*
* @param s {String} Text to be textilized.
* @return {String} The textilized text.
*/
textilize : function(s)
{
var r = s;
// quick tags first
var qtags = [ [ "\\*", "strong" ], [ "\\?\\?", "cite" ], [ "\\+", "ins" ], [ "~", "sub" ], [ "\\^", "sup" ], [ "@", "code" ] ];
var ttag, htag, re, line, lines, nr, changed, inlist, listtype;
for (var i=0; i<qtags.length; i++)
{
ttag = qtags[i][0];
htag = qtags[i][1];
re = new RegExp(ttag + "\\b(.+?)\\b" + ttag, "g");
r = r.replace(re, "<" + htag + ">" + "$1" + "</" + htag + ">");
}
// underscores count as part of a word, so do them separately
re = new RegExp("\\b_(.+?)_\\b", "g");
r = r.replace(re, "<em>$1</em>");
// jeff: so do dashes
re = new RegExp("[\s\n]-(.+?)-[\s\n]", "g");
r = r.replace(re, "<del>$1</del>");
// links
re = new RegExp('"\\b(.+?)\\(\\b(.+?)\\b\\)":([^\\s]+)', 'g');
r = r.replace(re, '<a href="$3" title="$2">$1</a>');
re = new RegExp('"\\b(.+?)\\b":([^\\s]+)', 'g');
r = r.replace(re, '<a href="$2">$1</a>');
// images
re = new RegExp("!\\b(.+?)\\(\\b(.+?)\\b\\)!", "g");
r = r.replace(re, '<img src="$1" alt="$2">');
re = new RegExp("!\\b(.+?)\\b!", "g");
r = r.replace(re, '<img src="$1">');
// block level formatting
// Jeff's hack to show single line breaks as they should.
// insert breaks - but you get some....stupid ones
re = new RegExp("(.*)\n([^#\*\n].*)", "g");
r = r.replace(re, "$1<br />$2");
// remove the stupid breaks.
re = new RegExp("\n<br />", "g");
r = r.replace(re, "\n");
lines = r.split("\n");
nr = "";
for (var i=0; i<lines.length; i++)
{
line = lines[i].replace(/\s*$/, "");
changed = 0;
if (line.search(/^\s*bq\.\s+/) != -1)
{
line = line.replace(/^\s*bq\.\s+/, "\t<blockquote>") + "</blockquote>";
changed = 1;
}
// jeff adds h#.
if (line.search(/^\s*h[1-6]\.\s+/) != -1)
{
re = new RegExp("h([1-6])\.(.+)", "g");
line = line.replace(re, "<h$1>$2</h$1>");
changed = 1;
}
if (line.search(/^\s*\*\s+/) != -1)
{
// for bullet list; make up an liu tag to be fixed later
line = line.replace(/^\s*\*\s+/, "\t<liu>") + "</liu>";
changed = 1;
}
if (line.search(/^\s*#\s+/) != -1)
{
// # for numeric list; make up an lio tag to be fixed later
line = line.replace(/^\s*#\s+/, "\t<lio>") + "</lio>";
changed = 1;
}
if (!changed && (line.replace(/\s/g, "").length > 0)) {
line = "<p>" + line + "</p>";
}
lines[i] = line + "\n";
}
// Second pass to do lists
inlist = 0;
listtype = "";
for (var i=0; i<lines.length; i++)
{
line = lines[i];
if (inlist && listtype == "ul" && !line.match(/^\t<liu/))
{
line = "</ul>\n" + line;
inlist = 0;
}
if (inlist && listtype == "ol" && !line.match(/^\t<lio/))
{
line = "</ol>\n" + line;
inlist = 0;
}
if (!inlist && line.match(/^\t<liu/))
{
line = "<ul>" + line;
inlist = 1;
listtype = "ul";
}
if (!inlist && line.match(/^\t<lio/))
{
line = "<ol>" + line;
inlist = 1;
listtype = "ol";
}
lines[i] = line;
}
r = lines.join("\n");
// jeff added : will correctly replace <li(o|u)> AND </li(o|u)>
r = r.replace(/li[o|u]>/g, "li>");
return r;
}
}
});
|
omid/webian
|
usr/qx/sdk/framework/source/class/qx/legacy/html/Textile.js
|
JavaScript
|
gpl-2.0
| 5,057
|
<!doctype html>
<!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if (IE 7)&!(IEMobile)]><html class="no-js lt-ie9 lt-ie8" lang="en"><![endif]-->
<!--[if (IE 8)&!(IEMobile)]><html class="no-js lt-ie9" lang="en"><![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"><!--<![endif]-->
<head>
{% include head.html %}
<link href="http://hutuxianren.github.io/css/tomorrow.min.css" rel="stylesheet">
</head>
<body id="post">
{% include navigation.html %}
<div id="main" role="main">
<article class="hentry">
{% if page.image.feature %}<img src="{{ site.asset_url }}/images/{{ page.image.feature }}" class="entry-feature-image" alt="{{ page.title }}" {% if site.logo == null %}style="margin-top:0;"{% endif %}>{% if page.image.credit %}<p class="image-credit">Photo Credit: <a href="{{ page.image.creditlink }}">{{ page.image.credit }}</a>{% endif %}{% endif %}
<div class="entry-wrapper">
<header class="entry-header">
<span class="entry-tags">
<i class="fa fa-tags"></i>
{% for tag in page.tags %}<a href="{{ site.url }}/tags.html#{{ tag | cgi_encode }}" title="Pages tagged {{ tag }}">{{ tag }}</a>{% unless forloop.last %} • {% endunless %}{% endfor %}</span>
{% if page.link %}
<h1 class="entry-title"><a href="{{ page.link }}">{% if page.headline %}{{ page.headline }}{% else %}{{ page.title }}{% endif %} <span class="link-arrow">→</span></a></h1>
{% else %}
<h1 class="entry-title">{% if page.headline %}{{ page.headline }}{% else %}{{ page.title }}{% endif %}</h1>
{% endif %}
</header>
<footer class="entry-meta">
<img src="{{ site.asset_url }}/images/{{ site.owner.avatar }}" alt="{{ site.owner.name }} photo" class="author-photo">
<span class="author vcard">By <span class="fn"><a href="{{ site.url }}/about.html" title="About {{ site.owner.name }}">{{ site.owner.name }}</a></span></span>
<span class="entry-date date published updated"><time datetime="{{ page.date | date_to_xmlschema }}"><i class="fa fa-calendar-o"></i> {{ page.date | date: "%B %d, %Y" }}</time></span>
{% if page.modified %}<span class="entry-date date modified updated"><time datetime="{{ page.modified }}"><i class="fa-pencil"></i> {{ page.modified | date: "%B %d, %Y" }}</time></span>{% endif %}
{% if site.disqus_shortname and page.comments %}<span class="entry-comments"><i class="fa fa-comment-o"></i> <a href="#disqus_thread">Comment</a></span>{% endif %}
<span><a href="{{ site.url }}{{ page.url }}" rel="bookmark" title="{{ page.title }}"><i class="fa fa-link"></i> Permalink</a></span>
{% if page.share %}
<span class="social-share-facebook">
<a href="https://www.facebook.com/sharer/sharer.php?u={{ site.url }}{{ page.url }}" title="Share on Facebook" itemprop="Facebook"><i class="fa fa-facebook-square"></i> Like</a></span>
<span class="social-share-twitter">
<a href="https://twitter.com/intent/tweet?hashtags={{ page.categories | join: ',' }}&text={{ page.title }}&url={{ site.url }}{{ page.url }}&via={{site.owner.twitter}}" title="Share on Twitter" itemprop="Twitter"><i class="fa fa-twitter-square"></i> Tweet</a></span>
<span class="social-share-googleplus">
<a href="https://plus.google.com/share?url={{ site.url }}{{ page.url }}" title="Share on Google Plus" itemprop="GooglePlus"><i class="fa fa-google-plus-square"></i> +1</a></span>
<!-- /.social-share -->{% endif %}
</footer>
<div id= "post-entry-content"class="entry-content">
{{ content }}
{% include post_copyright.html %}
{% include rating.html %}
<nav class="pagination" role="navigation">
{% if page.previous %}
<a href="{{ site.url }}{{ page.previous.url }}" class="btn" title="{{ page.previous.title }}">上一篇</a>
{% endif %}
{% if page.next %}
<a href="{{ site.url }}{{ page.next.url }}" class="btn" title="{{ page.next.title }}">下一篇</a>
{% endif %}
</nav><!-- /.pagination -->
{% if site.disqus_shortname and page.comments %}<div id="disqus_thread"></div><!-- /#disqus_thread -->{% endif %}
<!-- highlight.js -->
<script src="http://hutuxianren.github.io/js/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<!-- 多说评论框 start -->
<div class="ds-thread" data-thread-key={{page.id}} data-title={{page.title}} data-url="hutuxianren.github.io{{page.url}}"></div>
<!-- 多说评论框 end -->
<!-- 多说公共JS代码 start (一个网页只需插入一次) -->
<script type="text/javascript">
var duoshuoQuery = {short_name:"hutuxianren"};
(function() {
var ds = document.createElement('script');
ds.type = 'text/javascript';ds.async = true;
ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
ds.charset = 'UTF-8';
(document.getElementsByTagName('head')[0]
|| document.getElementsByTagName('body')[0]).appendChild(ds);
})();
</script>
<!-- 多说公共JS代码 end -->
<div id="hm_t_64067"></div>
<script>document.write(unescape('%3Cdiv id="hm_t_64067"%3E%3C/div%3E%3Cscript charset="utf-8" src="http://crs.baidu.com/t.js?siteId=3d8cd5acad6f5c33f8cb1324eebd6426&planId=64067&async=0&referer=') + encodeURIComponent(document.referrer) + '&title=' + encodeURIComponent(document.title) + '&rnd=' + (+new Date) + unescape('"%3E%3C/script%3E'));</script>
</div><!-- /.entry-content -->
</div><!-- /.entry-wrapper -->
</article>
</div><!-- /#main -->
<div class="footer-wrapper">
<footer role="contentinfo">
{% if site.tb_ads_display %}
<div class="tb-ads" style="margin:10px 0;">
<script type="text/javascript">
document.write('<a style="display:none!important" id="tanx-a-mm_54632328_6096791_22470523"></a>');
tanx_s = document.createElement("script");
tanx_s.type = "text/javascript";
tanx_s.charset = "gbk";
tanx_s.id = "tanx-s-mm_54632328_6096791_22470523";
tanx_s.async = true;
tanx_s.src = "http://p.tanx.com/ex?i=mm_54632328_6096791_22470523";
tanx_h = document.getElementsByTagName("head")[0];
if(tanx_h)tanx_h.insertBefore(tanx_s,tanx_h.firstChild);
</script>
</div>
{% endif %}
{% include footer.html %}
</footer>
</div><!-- /.footer-wrapper -->
{% include scripts.html %}
<script>
var isOnPc=!(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent));
if(isOnPc) {
window.tctipConfig = {
staticPrefix: "http://hutuxianren.github.io",
buttonImageId: 6,
list:{
alipay: { qrimg: "http://hutuxianren.github.io/images/zhifubao.jpg"},
weixin:{qrimg: "http://hutuxianren.github.io/images/weixinzhifu.png"}
}
};
}
</script>
<script src="/js/tctip.min.js"></script>
<!-- 百度统计 -->
<!-- 谷歌分析 -->
</body>
</html>
|
hutuxianren/hutuxianren.github.io
|
_layouts/post.html
|
HTML
|
gpl-2.0
| 7,168
|
#!/usr/bin/perl -w
# This code is a part of Slash, and is released under the GPL.
# Copyright 1997-2005 by Open Source Technology Group. See README
# and COPYING for more information, or see http://slashcode.com/.
# $Id: CommentScoreReason.pm,v 1.4 2007/10/09 18:57:10 jamiemccarthy Exp $
# Requires TagModeration plugin (not (just) Moderation)
package Slash::Tagbox::CommentScoreReason;
=head1 NAME
Slash::Tagbox::CommentScoreReason - track comment score and reason
=head1 SYNOPSIS
my $tagbox_tcu = getObject("Slash::Tagbox::CommentScoreReason");
my $feederlog_ar = $tagbox_tcu->feed_newtags($users_ar);
$tagbox_tcu->run($affected_globjid);
=cut
use strict;
use Slash;
use Slash::DB;
use Slash::Utility::Environment;
use Slash::Tagbox;
use Data::Dumper;
use vars qw( $VERSION );
$VERSION = ' $Revision: 1.4 $ ' =~ /\$Revision:\s+([^\s]+)/;
use base 'Slash::DB::Utility'; # first for object init stuff, but really
# needs to be second! figure it out. -- pudge
use base 'Slash::DB::MySQL';
sub new {
my($class, $user) = @_;
return undef unless $class->isInstalled();
# Note that getTagboxes() would call back to this new() function
# if the tagbox objects have not yet been created -- but the
# no_objects option prevents that. See getTagboxes() for details.
my($tagbox_name) = $class =~ /(\w+)$/;
my %self_hash = %{ getObject('Slash::Tagbox')->getTagboxes($tagbox_name, undef, { no_objects => 1 }) };
my $self = \%self_hash;
return undef if !$self || !keys %$self;
bless($self, $class);
$self->{virtual_user} = $user;
$self->sqlConnect();
return $self;
}
sub isInstalled {
my($class) = @_;
my $constants = getCurrentStatic();
return undef if !$constants->{plugin}{Tags} || !$constants->{plugin}{TagModeration};
my($tagbox_name) = $class =~ /(\w+)$/;
return undef if !$constants->{tagbox}{$tagbox_name};
}
sub feed_newtags {
my($self, $tags_ar) = @_;
my $constants = getCurrentStatic();
if (scalar(@$tags_ar) < 9) {
main::tagboxLog("CommentScoreReason->feed_newtags called for tags '" . join(' ', map { $_->{tagid} } @$tags_ar) . "'");
} else {
main::tagboxLog("CommentScoreReason->feed_newtags called for " . scalar(@$tags_ar) . " tags " . $tags_ar->[0]{tagid} . " ... " . $tags_ar->[-1]{tagid});
}
my $tagsdb = getObject('Slash::Tags');
# Only tags on comments matter to this tagbox.
my $comments_gtid = $self->getGlobjTypes()->{comments};
my %all_globjids = ( map { ($_->{globjid}, 1) } @$tags_ar );
my $all_globjids_str = join(",", sort { $a <=> $b } keys %all_globjids);
return [ ] if !$comments_gtid || !$all_globjids_str;
my $globjids_wanted_ar = $self->sqlSelectColArrayref(
'globjid',
'globjs',
"globjid IN ($all_globjids_str) AND gtid=$comments_gtid");
my %globjid_wanted = ( map { ($_, 1) } @$globjids_wanted_ar );
my $ret_ar = [ ];
for my $tag_hr (@$tags_ar) {
next unless $globjid_wanted{ $tag_hr->{globjid} };
my $ret_hr = {
affected_id => $tag_hr->{globjid},
importance => 1,
};
# We identify this little chunk of importance by either
# tagid or tdid depending on whether the source data had
# the tdid field (which tells us whether feed_newtags was
# "really" called via feed_deactivatedtags).
if ($tag_hr->{tdid}) { $ret_hr->{tdid} = $tag_hr->{tdid} }
else { $ret_hr->{tagid} = $tag_hr->{tagid} }
push @$ret_ar, $ret_hr;
}
return [ ] if !@$ret_ar;
main::tagboxLog("CommentScoreReason->feed_newtags returning " . scalar(@$ret_ar));
return $ret_ar;
}
sub feed_deactivatedtags {
my($self, $tags_ar) = @_;
main::tagboxLog("CommentScoreReason->feed_deactivatedtags called: tags_ar='" . join(' ', map { $_->{tagid} } @$tags_ar) . "'");
my $ret_ar = $self->feed_newtags($tags_ar);
main::tagboxLog("CommentScoreReason->feed_deactivatedtags returning " . scalar(@$ret_ar));
return $ret_ar;
}
sub feed_userchanges {
my($self, $users_ar) = @_;
# Do not currently care about any user changes, since this tagbox
# just replicates what comment moderation does and moderation does
# not care about user tag clout.
return [ ];
}
sub run {
my($self, $affected_id) = @_;
my $constants = getCurrentStatic();
my $moddb = getObject('Slash::TagModeration');
my $tagsdb = getObject('Slash::Tags');
my $tagboxdb = getObject('Slash::Tagbox');
my $reasons = $moddb->getReasons();
my @reason_ids = (
grep { $reasons->{$_}{val} != 0 }
keys %$reasons
);
my %tagnameid_reasons = ( );
for my $id (@reason_ids) {
my $name = lc $reasons->{$id}{name};
my $tagnameid = $tagsdb->getTagnameidCreate($name);
$tagnameid_reasons{$tagnameid} = $reasons->{$id};
}
my $mod_score_sum = 0;
my($gtid, $cid) = $self->getGlobjTarget($affected_id);
my $tags_ar = $tagboxdb->getTagboxTags($self->{tbid}, $affected_id, 0);
return unless $tags_ar && @$tags_ar;
my($keep_karma_bonus, $karma_bonus_downmods_left) = (1, $constants->{mod_karma_bonus_max_downmods});
my $current_reason_mode = 0;
my $allreasons_hr = {( %{$reasons} )};
for my $id (keys %$allreasons_hr) {
$allreasons_hr->{$id} = { reason => $id, c => 0 };
}
for my $tag (@$tags_ar) {
next if $tag->{inactivated};
my $reason = $tagnameid_reasons{$tag->{tagnameid}};
next unless $reason;
if ($reason->{val} < 0) {
$keep_karma_bonus = 0 if --$karma_bonus_downmods_left < 0;
}
$mod_score_sum += $reason->{val};
$allreasons_hr->{$reason->{id}}{c}++;
$current_reason_mode = $moddb->getCommentMostCommonReason($cid,
$allreasons_hr, $reason->{id}, $current_reason_mode);
}
my($points_orig, $karma_bonus) = $self->sqlSelect(
'pointsorig, karma_bonus', 'comments', "cid='$cid'");
my $new_score = $points_orig + $mod_score_sum;
my $new_karma_bonus = ($karma_bonus eq 'yes' && $keep_karma_bonus) ? 1 : 0;
#main::tagboxLog("CommentScoreReason->run setting cid $cid to score: $new_score, $reasons->{$current_reason_mode}{name} kb '$karma_bonus'->'$new_karma_bonus'");
$self->sqlUpdate('comments', {
f1 => $new_score,
f2 => $current_reason_mode,
}, "cid='$cid'");
}
1;
|
jmcvetta/slashcode
|
tagboxes/CommentScoreReason/CommentScoreReason.pm
|
Perl
|
gpl-2.0
| 5,981
|
<p>See <a href="/list.php">list.php</a></p>
|
formigone/big-brother-js
|
recordings/index.html
|
HTML
|
gpl-2.0
| 43
|
<?php /* Template Name: Partners */
get_header();
$layout = get_post_meta($post->ID, "layout", true);
if($layout == '' ) $layout = 'two-column'; ?>
<?php get_template_part('/functions/page-title'); ?>
<div id="crumbs-container">
<?php ocmx_breadcrumbs(); ?>
</div>
<div id="content" class="non-contained clearfix">
<?php
$content = get_the_content();
if($content !="") : ?>
<div class="copy page-feature-copy">
<?php the_content(); ?>
</div>
<?php endif; ?>
<ul class="grid <?php echo $layout; ?> partners">
<?php // Partners Query
$args = array( "post_type" => 'partners', 'orderby' => 'menu_order', 'order' => 'ASC', 'post_status' => 'publish', 'showposts' => '-1' );
$partners = new WP_Query($args);
while ( $partners->have_posts() ) : $partners->the_post();
global $post;
$args = array('postid' => $post->ID, 'width' => 490, 'height' => 368, 'hide_href' => true, 'exclude_video' => true, 'imglink' => false, 'imgnocontainer' => true, 'resizer' => '4-3-medium');
$image = get_obox_media($args);
$link = get_post_meta($post->ID, "link", true); ?>
<li class="column">
<?php if(isset($image) && $image !='' ): ?>
<div class="post-image">
<?php if(isset($link) && $link !='' ): ?>
<a target="_blank" href="<?php echo $link; ?>"><?php echo $image; ?></a>
<?php else : ?>
<?php echo $image; ?>
<?php endif;?>
</div>
<?php endif;?>
<h3 class="post-title">
<?php if(isset($link) && $link !='' ): ?>
<a target="_blank" href="<?php echo $link; ?>"><?php the_title(); ?></a>
<?php else : ?>
<?php the_title(); ?>
<?php endif;?>
</h3>
<div class="copy">
<?php the_excerpt(); ?>
</div>
</li>
<?php endwhile; ?>
</ul>
</div>
<?php get_footer(); ?>
|
sphrcl/traveltripper.com
|
blog/wp-content/themes/dynamo/partners.php
|
PHP
|
gpl-2.0
| 2,036
|
/* SPDX-License-Identifier: BSD-3-Clause
* Copyright (c) 2016 - 2018 Cavium Inc.
* All rights reserved.
* www.cavium.com
*/
#include "qede_ethdev.h"
#include <rte_string_fns.h>
#include <rte_alarm.h>
#include <rte_version.h>
#include <rte_kvargs.h>
/* Globals */
int qede_logtype_init;
int qede_logtype_driver;
static const struct qed_eth_ops *qed_ops;
static int qede_eth_dev_uninit(struct rte_eth_dev *eth_dev);
static int qede_eth_dev_init(struct rte_eth_dev *eth_dev);
#define QEDE_SP_TIMER_PERIOD 10000 /* 100ms */
struct rte_qede_xstats_name_off {
char name[RTE_ETH_XSTATS_NAME_SIZE];
uint64_t offset;
};
static const struct rte_qede_xstats_name_off qede_xstats_strings[] = {
{"rx_unicast_bytes",
offsetof(struct ecore_eth_stats_common, rx_ucast_bytes)},
{"rx_multicast_bytes",
offsetof(struct ecore_eth_stats_common, rx_mcast_bytes)},
{"rx_broadcast_bytes",
offsetof(struct ecore_eth_stats_common, rx_bcast_bytes)},
{"rx_unicast_packets",
offsetof(struct ecore_eth_stats_common, rx_ucast_pkts)},
{"rx_multicast_packets",
offsetof(struct ecore_eth_stats_common, rx_mcast_pkts)},
{"rx_broadcast_packets",
offsetof(struct ecore_eth_stats_common, rx_bcast_pkts)},
{"tx_unicast_bytes",
offsetof(struct ecore_eth_stats_common, tx_ucast_bytes)},
{"tx_multicast_bytes",
offsetof(struct ecore_eth_stats_common, tx_mcast_bytes)},
{"tx_broadcast_bytes",
offsetof(struct ecore_eth_stats_common, tx_bcast_bytes)},
{"tx_unicast_packets",
offsetof(struct ecore_eth_stats_common, tx_ucast_pkts)},
{"tx_multicast_packets",
offsetof(struct ecore_eth_stats_common, tx_mcast_pkts)},
{"tx_broadcast_packets",
offsetof(struct ecore_eth_stats_common, tx_bcast_pkts)},
{"rx_64_byte_packets",
offsetof(struct ecore_eth_stats_common, rx_64_byte_packets)},
{"rx_65_to_127_byte_packets",
offsetof(struct ecore_eth_stats_common,
rx_65_to_127_byte_packets)},
{"rx_128_to_255_byte_packets",
offsetof(struct ecore_eth_stats_common,
rx_128_to_255_byte_packets)},
{"rx_256_to_511_byte_packets",
offsetof(struct ecore_eth_stats_common,
rx_256_to_511_byte_packets)},
{"rx_512_to_1023_byte_packets",
offsetof(struct ecore_eth_stats_common,
rx_512_to_1023_byte_packets)},
{"rx_1024_to_1518_byte_packets",
offsetof(struct ecore_eth_stats_common,
rx_1024_to_1518_byte_packets)},
{"tx_64_byte_packets",
offsetof(struct ecore_eth_stats_common, tx_64_byte_packets)},
{"tx_65_to_127_byte_packets",
offsetof(struct ecore_eth_stats_common,
tx_65_to_127_byte_packets)},
{"tx_128_to_255_byte_packets",
offsetof(struct ecore_eth_stats_common,
tx_128_to_255_byte_packets)},
{"tx_256_to_511_byte_packets",
offsetof(struct ecore_eth_stats_common,
tx_256_to_511_byte_packets)},
{"tx_512_to_1023_byte_packets",
offsetof(struct ecore_eth_stats_common,
tx_512_to_1023_byte_packets)},
{"tx_1024_to_1518_byte_packets",
offsetof(struct ecore_eth_stats_common,
tx_1024_to_1518_byte_packets)},
{"rx_mac_crtl_frames",
offsetof(struct ecore_eth_stats_common, rx_mac_crtl_frames)},
{"tx_mac_control_frames",
offsetof(struct ecore_eth_stats_common, tx_mac_ctrl_frames)},
{"rx_pause_frames",
offsetof(struct ecore_eth_stats_common, rx_pause_frames)},
{"tx_pause_frames",
offsetof(struct ecore_eth_stats_common, tx_pause_frames)},
{"rx_priority_flow_control_frames",
offsetof(struct ecore_eth_stats_common, rx_pfc_frames)},
{"tx_priority_flow_control_frames",
offsetof(struct ecore_eth_stats_common, tx_pfc_frames)},
{"rx_crc_errors",
offsetof(struct ecore_eth_stats_common, rx_crc_errors)},
{"rx_align_errors",
offsetof(struct ecore_eth_stats_common, rx_align_errors)},
{"rx_carrier_errors",
offsetof(struct ecore_eth_stats_common, rx_carrier_errors)},
{"rx_oversize_packet_errors",
offsetof(struct ecore_eth_stats_common, rx_oversize_packets)},
{"rx_jabber_errors",
offsetof(struct ecore_eth_stats_common, rx_jabbers)},
{"rx_undersize_packet_errors",
offsetof(struct ecore_eth_stats_common, rx_undersize_packets)},
{"rx_fragments", offsetof(struct ecore_eth_stats_common, rx_fragments)},
{"rx_host_buffer_not_available",
offsetof(struct ecore_eth_stats_common, no_buff_discards)},
/* Number of packets discarded because they are bigger than MTU */
{"rx_packet_too_big_discards",
offsetof(struct ecore_eth_stats_common,
packet_too_big_discard)},
{"rx_ttl_zero_discards",
offsetof(struct ecore_eth_stats_common, ttl0_discard)},
{"rx_multi_function_tag_filter_discards",
offsetof(struct ecore_eth_stats_common, mftag_filter_discards)},
{"rx_mac_filter_discards",
offsetof(struct ecore_eth_stats_common, mac_filter_discards)},
{"rx_gft_filter_drop",
offsetof(struct ecore_eth_stats_common, gft_filter_drop)},
{"rx_hw_buffer_truncates",
offsetof(struct ecore_eth_stats_common, brb_truncates)},
{"rx_hw_buffer_discards",
offsetof(struct ecore_eth_stats_common, brb_discards)},
{"tx_error_drop_packets",
offsetof(struct ecore_eth_stats_common, tx_err_drop_pkts)},
{"rx_mac_bytes", offsetof(struct ecore_eth_stats_common, rx_mac_bytes)},
{"rx_mac_unicast_packets",
offsetof(struct ecore_eth_stats_common, rx_mac_uc_packets)},
{"rx_mac_multicast_packets",
offsetof(struct ecore_eth_stats_common, rx_mac_mc_packets)},
{"rx_mac_broadcast_packets",
offsetof(struct ecore_eth_stats_common, rx_mac_bc_packets)},
{"rx_mac_frames_ok",
offsetof(struct ecore_eth_stats_common, rx_mac_frames_ok)},
{"tx_mac_bytes", offsetof(struct ecore_eth_stats_common, tx_mac_bytes)},
{"tx_mac_unicast_packets",
offsetof(struct ecore_eth_stats_common, tx_mac_uc_packets)},
{"tx_mac_multicast_packets",
offsetof(struct ecore_eth_stats_common, tx_mac_mc_packets)},
{"tx_mac_broadcast_packets",
offsetof(struct ecore_eth_stats_common, tx_mac_bc_packets)},
{"lro_coalesced_packets",
offsetof(struct ecore_eth_stats_common, tpa_coalesced_pkts)},
{"lro_coalesced_events",
offsetof(struct ecore_eth_stats_common, tpa_coalesced_events)},
{"lro_aborts_num",
offsetof(struct ecore_eth_stats_common, tpa_aborts_num)},
{"lro_not_coalesced_packets",
offsetof(struct ecore_eth_stats_common,
tpa_not_coalesced_pkts)},
{"lro_coalesced_bytes",
offsetof(struct ecore_eth_stats_common,
tpa_coalesced_bytes)},
};
static const struct rte_qede_xstats_name_off qede_bb_xstats_strings[] = {
{"rx_1519_to_1522_byte_packets",
offsetof(struct ecore_eth_stats, bb) +
offsetof(struct ecore_eth_stats_bb,
rx_1519_to_1522_byte_packets)},
{"rx_1519_to_2047_byte_packets",
offsetof(struct ecore_eth_stats, bb) +
offsetof(struct ecore_eth_stats_bb,
rx_1519_to_2047_byte_packets)},
{"rx_2048_to_4095_byte_packets",
offsetof(struct ecore_eth_stats, bb) +
offsetof(struct ecore_eth_stats_bb,
rx_2048_to_4095_byte_packets)},
{"rx_4096_to_9216_byte_packets",
offsetof(struct ecore_eth_stats, bb) +
offsetof(struct ecore_eth_stats_bb,
rx_4096_to_9216_byte_packets)},
{"rx_9217_to_16383_byte_packets",
offsetof(struct ecore_eth_stats, bb) +
offsetof(struct ecore_eth_stats_bb,
rx_9217_to_16383_byte_packets)},
{"tx_1519_to_2047_byte_packets",
offsetof(struct ecore_eth_stats, bb) +
offsetof(struct ecore_eth_stats_bb,
tx_1519_to_2047_byte_packets)},
{"tx_2048_to_4095_byte_packets",
offsetof(struct ecore_eth_stats, bb) +
offsetof(struct ecore_eth_stats_bb,
tx_2048_to_4095_byte_packets)},
{"tx_4096_to_9216_byte_packets",
offsetof(struct ecore_eth_stats, bb) +
offsetof(struct ecore_eth_stats_bb,
tx_4096_to_9216_byte_packets)},
{"tx_9217_to_16383_byte_packets",
offsetof(struct ecore_eth_stats, bb) +
offsetof(struct ecore_eth_stats_bb,
tx_9217_to_16383_byte_packets)},
{"tx_lpi_entry_count",
offsetof(struct ecore_eth_stats, bb) +
offsetof(struct ecore_eth_stats_bb, tx_lpi_entry_count)},
{"tx_total_collisions",
offsetof(struct ecore_eth_stats, bb) +
offsetof(struct ecore_eth_stats_bb, tx_total_collisions)},
};
static const struct rte_qede_xstats_name_off qede_ah_xstats_strings[] = {
{"rx_1519_to_max_byte_packets",
offsetof(struct ecore_eth_stats, ah) +
offsetof(struct ecore_eth_stats_ah,
rx_1519_to_max_byte_packets)},
{"tx_1519_to_max_byte_packets",
offsetof(struct ecore_eth_stats, ah) +
offsetof(struct ecore_eth_stats_ah,
tx_1519_to_max_byte_packets)},
};
static const struct rte_qede_xstats_name_off qede_rxq_xstats_strings[] = {
{"rx_q_segments",
offsetof(struct qede_rx_queue, rx_segs)},
{"rx_q_hw_errors",
offsetof(struct qede_rx_queue, rx_hw_errors)},
{"rx_q_allocation_errors",
offsetof(struct qede_rx_queue, rx_alloc_errors)}
};
static void qede_interrupt_action(struct ecore_hwfn *p_hwfn)
{
ecore_int_sp_dpc((osal_int_ptr_t)(p_hwfn));
}
static void
qede_interrupt_handler_intx(void *param)
{
struct rte_eth_dev *eth_dev = (struct rte_eth_dev *)param;
struct qede_dev *qdev = eth_dev->data->dev_private;
struct ecore_dev *edev = &qdev->edev;
u64 status;
/* Check if our device actually raised an interrupt */
status = ecore_int_igu_read_sisr_reg(ECORE_LEADING_HWFN(edev));
if (status & 0x1) {
qede_interrupt_action(ECORE_LEADING_HWFN(edev));
if (rte_intr_ack(eth_dev->intr_handle))
DP_ERR(edev, "rte_intr_ack failed\n");
}
}
static void
qede_interrupt_handler(void *param)
{
struct rte_eth_dev *eth_dev = (struct rte_eth_dev *)param;
struct qede_dev *qdev = eth_dev->data->dev_private;
struct ecore_dev *edev = &qdev->edev;
qede_interrupt_action(ECORE_LEADING_HWFN(edev));
if (rte_intr_ack(eth_dev->intr_handle))
DP_ERR(edev, "rte_intr_ack failed\n");
}
static void
qede_assign_rxtx_handlers(struct rte_eth_dev *dev)
{
uint64_t tx_offloads = dev->data->dev_conf.txmode.offloads;
struct qede_dev *qdev = dev->data->dev_private;
struct ecore_dev *edev = &qdev->edev;
bool use_tx_offload = false;
if (ECORE_IS_CMT(edev)) {
dev->rx_pkt_burst = qede_recv_pkts_cmt;
dev->tx_pkt_burst = qede_xmit_pkts_cmt;
return;
}
if (dev->data->lro || dev->data->scattered_rx) {
DP_INFO(edev, "Assigning qede_recv_pkts\n");
dev->rx_pkt_burst = qede_recv_pkts;
} else {
DP_INFO(edev, "Assigning qede_recv_pkts_regular\n");
dev->rx_pkt_burst = qede_recv_pkts_regular;
}
use_tx_offload = !!(tx_offloads &
(DEV_TX_OFFLOAD_OUTER_IPV4_CKSUM | /* tunnel */
DEV_TX_OFFLOAD_TCP_TSO | /* tso */
DEV_TX_OFFLOAD_VLAN_INSERT)); /* vlan insert */
if (use_tx_offload) {
DP_INFO(edev, "Assigning qede_xmit_pkts\n");
dev->tx_pkt_burst = qede_xmit_pkts;
} else {
DP_INFO(edev, "Assigning qede_xmit_pkts_regular\n");
dev->tx_pkt_burst = qede_xmit_pkts_regular;
}
}
static void
qede_alloc_etherdev(struct qede_dev *qdev, struct qed_dev_eth_info *info)
{
rte_memcpy(&qdev->dev_info, info, sizeof(*info));
qdev->ops = qed_ops;
}
static void qede_print_adapter_info(struct qede_dev *qdev)
{
struct ecore_dev *edev = &qdev->edev;
struct qed_dev_info *info = &qdev->dev_info.common;
static char ver_str[QEDE_PMD_DRV_VER_STR_SIZE];
DP_INFO(edev, "**************************************************\n");
DP_INFO(edev, " DPDK version\t\t\t: %s\n", rte_version());
DP_INFO(edev, " Chip details\t\t\t: %s %c%d\n",
ECORE_IS_BB(edev) ? "BB" : "AH",
'A' + edev->chip_rev,
(int)edev->chip_metal);
snprintf(ver_str, QEDE_PMD_DRV_VER_STR_SIZE, "%s",
QEDE_PMD_DRV_VERSION);
DP_INFO(edev, " Driver version\t\t\t: %s\n", ver_str);
snprintf(ver_str, QEDE_PMD_DRV_VER_STR_SIZE, "%s",
QEDE_PMD_BASE_VERSION);
DP_INFO(edev, " Base version\t\t\t: %s\n", ver_str);
if (!IS_VF(edev))
snprintf(ver_str, QEDE_PMD_DRV_VER_STR_SIZE, "%s",
QEDE_PMD_FW_VERSION);
else
snprintf(ver_str, QEDE_PMD_DRV_VER_STR_SIZE, "%d.%d.%d.%d",
info->fw_major, info->fw_minor,
info->fw_rev, info->fw_eng);
DP_INFO(edev, " Firmware version\t\t\t: %s\n", ver_str);
snprintf(ver_str, MCP_DRV_VER_STR_SIZE,
"%d.%d.%d.%d",
(info->mfw_rev & QED_MFW_VERSION_3_MASK) >>
QED_MFW_VERSION_3_OFFSET,
(info->mfw_rev & QED_MFW_VERSION_2_MASK) >>
QED_MFW_VERSION_2_OFFSET,
(info->mfw_rev & QED_MFW_VERSION_1_MASK) >>
QED_MFW_VERSION_1_OFFSET,
(info->mfw_rev & QED_MFW_VERSION_0_MASK) >>
QED_MFW_VERSION_0_OFFSET);
DP_INFO(edev, " Management Firmware version\t: %s\n", ver_str);
DP_INFO(edev, " Firmware file\t\t\t: %s\n", qede_fw_file);
DP_INFO(edev, "**************************************************\n");
}
static void qede_reset_queue_stats(struct qede_dev *qdev, bool xstats)
{
struct rte_eth_dev *dev = (struct rte_eth_dev *)qdev->ethdev;
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
unsigned int i = 0, j = 0, qid;
unsigned int rxq_stat_cntrs, txq_stat_cntrs;
struct qede_tx_queue *txq;
DP_VERBOSE(edev, ECORE_MSG_DEBUG, "Clearing queue stats\n");
rxq_stat_cntrs = RTE_MIN(QEDE_RSS_COUNT(dev),
RTE_ETHDEV_QUEUE_STAT_CNTRS);
txq_stat_cntrs = RTE_MIN(QEDE_TSS_COUNT(dev),
RTE_ETHDEV_QUEUE_STAT_CNTRS);
for (qid = 0; qid < qdev->num_rx_queues; qid++) {
OSAL_MEMSET(((char *)(qdev->fp_array[qid].rxq)) +
offsetof(struct qede_rx_queue, rcv_pkts), 0,
sizeof(uint64_t));
OSAL_MEMSET(((char *)(qdev->fp_array[qid].rxq)) +
offsetof(struct qede_rx_queue, rx_hw_errors), 0,
sizeof(uint64_t));
OSAL_MEMSET(((char *)(qdev->fp_array[qid].rxq)) +
offsetof(struct qede_rx_queue, rx_alloc_errors), 0,
sizeof(uint64_t));
if (xstats)
for (j = 0; j < RTE_DIM(qede_rxq_xstats_strings); j++)
OSAL_MEMSET((((char *)
(qdev->fp_array[qid].rxq)) +
qede_rxq_xstats_strings[j].offset),
0,
sizeof(uint64_t));
i++;
if (i == rxq_stat_cntrs)
break;
}
i = 0;
for (qid = 0; qid < qdev->num_tx_queues; qid++) {
txq = qdev->fp_array[qid].txq;
OSAL_MEMSET((uint64_t *)(uintptr_t)
(((uint64_t)(uintptr_t)(txq)) +
offsetof(struct qede_tx_queue, xmit_pkts)), 0,
sizeof(uint64_t));
i++;
if (i == txq_stat_cntrs)
break;
}
}
static int
qede_stop_vport(struct ecore_dev *edev)
{
struct ecore_hwfn *p_hwfn;
uint8_t vport_id;
int rc;
int i;
vport_id = 0;
for_each_hwfn(edev, i) {
p_hwfn = &edev->hwfns[i];
rc = ecore_sp_vport_stop(p_hwfn, p_hwfn->hw_info.opaque_fid,
vport_id);
if (rc != ECORE_SUCCESS) {
DP_ERR(edev, "Stop V-PORT failed rc = %d\n", rc);
return rc;
}
}
DP_INFO(edev, "vport stopped\n");
return 0;
}
static int
qede_start_vport(struct qede_dev *qdev, uint16_t mtu)
{
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
struct ecore_sp_vport_start_params params;
struct ecore_hwfn *p_hwfn;
int rc;
int i;
if (qdev->vport_started)
qede_stop_vport(edev);
memset(¶ms, 0, sizeof(params));
params.vport_id = 0;
params.mtu = mtu;
/* @DPDK - Disable FW placement */
params.zero_placement_offset = 1;
for_each_hwfn(edev, i) {
p_hwfn = &edev->hwfns[i];
params.concrete_fid = p_hwfn->hw_info.concrete_fid;
params.opaque_fid = p_hwfn->hw_info.opaque_fid;
rc = ecore_sp_vport_start(p_hwfn, ¶ms);
if (rc != ECORE_SUCCESS) {
DP_ERR(edev, "Start V-PORT failed %d\n", rc);
return rc;
}
}
ecore_reset_vport_stats(edev);
qdev->vport_started = true;
DP_INFO(edev, "VPORT started with MTU = %u\n", mtu);
return 0;
}
#define QEDE_NPAR_TX_SWITCHING "npar_tx_switching"
#define QEDE_VF_TX_SWITCHING "vf_tx_switching"
/* Activate or deactivate vport via vport-update */
int qede_activate_vport(struct rte_eth_dev *eth_dev, bool flg)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
struct ecore_sp_vport_update_params params;
struct ecore_hwfn *p_hwfn;
uint8_t i;
int rc = -1;
memset(¶ms, 0, sizeof(struct ecore_sp_vport_update_params));
params.vport_id = 0;
params.update_vport_active_rx_flg = 1;
params.update_vport_active_tx_flg = 1;
params.vport_active_rx_flg = flg;
params.vport_active_tx_flg = flg;
if ((qdev->enable_tx_switching == false) && (flg == true)) {
params.update_tx_switching_flg = 1;
params.tx_switching_flg = !flg;
}
for_each_hwfn(edev, i) {
p_hwfn = &edev->hwfns[i];
params.opaque_fid = p_hwfn->hw_info.opaque_fid;
rc = ecore_sp_vport_update(p_hwfn, ¶ms,
ECORE_SPQ_MODE_EBLOCK, NULL);
if (rc != ECORE_SUCCESS) {
DP_ERR(edev, "Failed to update vport\n");
break;
}
}
DP_INFO(edev, "vport is %s\n", flg ? "activated" : "deactivated");
return rc;
}
static void
qede_update_sge_tpa_params(struct ecore_sge_tpa_params *sge_tpa_params,
uint16_t mtu, bool enable)
{
/* Enable LRO in split mode */
sge_tpa_params->tpa_ipv4_en_flg = enable;
sge_tpa_params->tpa_ipv6_en_flg = enable;
sge_tpa_params->tpa_ipv4_tunn_en_flg = enable;
sge_tpa_params->tpa_ipv6_tunn_en_flg = enable;
/* set if tpa enable changes */
sge_tpa_params->update_tpa_en_flg = 1;
/* set if tpa parameters should be handled */
sge_tpa_params->update_tpa_param_flg = enable;
sge_tpa_params->max_buffers_per_cqe = 20;
/* Enable TPA in split mode. In this mode each TPA segment
* starts on the new BD, so there is one BD per segment.
*/
sge_tpa_params->tpa_pkt_split_flg = 1;
sge_tpa_params->tpa_hdr_data_split_flg = 0;
sge_tpa_params->tpa_gro_consistent_flg = 0;
sge_tpa_params->tpa_max_aggs_num = ETH_TPA_MAX_AGGS_NUM;
sge_tpa_params->tpa_max_size = 0x7FFF;
sge_tpa_params->tpa_min_size_to_start = mtu / 2;
sge_tpa_params->tpa_min_size_to_cont = mtu / 2;
}
/* Enable/disable LRO via vport-update */
int qede_enable_tpa(struct rte_eth_dev *eth_dev, bool flg)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
struct ecore_sp_vport_update_params params;
struct ecore_sge_tpa_params tpa_params;
struct ecore_hwfn *p_hwfn;
int rc;
int i;
memset(¶ms, 0, sizeof(struct ecore_sp_vport_update_params));
memset(&tpa_params, 0, sizeof(struct ecore_sge_tpa_params));
qede_update_sge_tpa_params(&tpa_params, qdev->mtu, flg);
params.vport_id = 0;
params.sge_tpa_params = &tpa_params;
for_each_hwfn(edev, i) {
p_hwfn = &edev->hwfns[i];
params.opaque_fid = p_hwfn->hw_info.opaque_fid;
rc = ecore_sp_vport_update(p_hwfn, ¶ms,
ECORE_SPQ_MODE_EBLOCK, NULL);
if (rc != ECORE_SUCCESS) {
DP_ERR(edev, "Failed to update LRO\n");
return -1;
}
}
qdev->enable_lro = flg;
eth_dev->data->lro = flg;
DP_INFO(edev, "LRO is %s\n", flg ? "enabled" : "disabled");
return 0;
}
static int
qed_configure_filter_rx_mode(struct rte_eth_dev *eth_dev,
enum qed_filter_rx_mode_type type)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
struct ecore_filter_accept_flags flags;
memset(&flags, 0, sizeof(flags));
flags.update_rx_mode_config = 1;
flags.update_tx_mode_config = 1;
flags.rx_accept_filter = ECORE_ACCEPT_UCAST_MATCHED |
ECORE_ACCEPT_MCAST_MATCHED |
ECORE_ACCEPT_BCAST;
flags.tx_accept_filter = ECORE_ACCEPT_UCAST_MATCHED |
ECORE_ACCEPT_MCAST_MATCHED |
ECORE_ACCEPT_BCAST;
if (type == QED_FILTER_RX_MODE_TYPE_PROMISC) {
flags.rx_accept_filter |= ECORE_ACCEPT_UCAST_UNMATCHED;
if (IS_VF(edev)) {
flags.tx_accept_filter |= ECORE_ACCEPT_UCAST_UNMATCHED;
DP_INFO(edev, "Enabling Tx unmatched flag for VF\n");
}
} else if (type == QED_FILTER_RX_MODE_TYPE_MULTI_PROMISC) {
flags.rx_accept_filter |= ECORE_ACCEPT_MCAST_UNMATCHED;
} else if (type == (QED_FILTER_RX_MODE_TYPE_MULTI_PROMISC |
QED_FILTER_RX_MODE_TYPE_PROMISC)) {
flags.rx_accept_filter |= ECORE_ACCEPT_UCAST_UNMATCHED |
ECORE_ACCEPT_MCAST_UNMATCHED;
}
return ecore_filter_accept_cmd(edev, 0, flags, false, false,
ECORE_SPQ_MODE_CB, NULL);
}
int
qede_ucast_filter(struct rte_eth_dev *eth_dev, struct ecore_filter_ucast *ucast,
bool add)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
struct qede_ucast_entry *tmp = NULL;
struct qede_ucast_entry *u;
struct rte_ether_addr *mac_addr;
mac_addr = (struct rte_ether_addr *)ucast->mac;
if (add) {
SLIST_FOREACH(tmp, &qdev->uc_list_head, list) {
if ((memcmp(mac_addr, &tmp->mac,
RTE_ETHER_ADDR_LEN) == 0) &&
ucast->vni == tmp->vni &&
ucast->vlan == tmp->vlan) {
DP_INFO(edev, "Unicast MAC is already added"
" with vlan = %u, vni = %u\n",
ucast->vlan, ucast->vni);
return 0;
}
}
u = rte_malloc(NULL, sizeof(struct qede_ucast_entry),
RTE_CACHE_LINE_SIZE);
if (!u) {
DP_ERR(edev, "Did not allocate memory for ucast\n");
return -ENOMEM;
}
rte_ether_addr_copy(mac_addr, &u->mac);
u->vlan = ucast->vlan;
u->vni = ucast->vni;
SLIST_INSERT_HEAD(&qdev->uc_list_head, u, list);
qdev->num_uc_addr++;
} else {
SLIST_FOREACH(tmp, &qdev->uc_list_head, list) {
if ((memcmp(mac_addr, &tmp->mac,
RTE_ETHER_ADDR_LEN) == 0) &&
ucast->vlan == tmp->vlan &&
ucast->vni == tmp->vni)
break;
}
if (tmp == NULL) {
DP_INFO(edev, "Unicast MAC is not found\n");
return -EINVAL;
}
SLIST_REMOVE(&qdev->uc_list_head, tmp, qede_ucast_entry, list);
qdev->num_uc_addr--;
}
return 0;
}
static int
qede_add_mcast_filters(struct rte_eth_dev *eth_dev,
struct rte_ether_addr *mc_addrs,
uint32_t mc_addrs_num)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
struct ecore_filter_mcast mcast;
struct qede_mcast_entry *m = NULL;
uint8_t i;
int rc;
for (i = 0; i < mc_addrs_num; i++) {
m = rte_malloc(NULL, sizeof(struct qede_mcast_entry),
RTE_CACHE_LINE_SIZE);
if (!m) {
DP_ERR(edev, "Did not allocate memory for mcast\n");
return -ENOMEM;
}
rte_ether_addr_copy(&mc_addrs[i], &m->mac);
SLIST_INSERT_HEAD(&qdev->mc_list_head, m, list);
}
memset(&mcast, 0, sizeof(mcast));
mcast.num_mc_addrs = mc_addrs_num;
mcast.opcode = ECORE_FILTER_ADD;
for (i = 0; i < mc_addrs_num; i++)
rte_ether_addr_copy(&mc_addrs[i], (struct rte_ether_addr *)
&mcast.mac[i]);
rc = ecore_filter_mcast_cmd(edev, &mcast, ECORE_SPQ_MODE_CB, NULL);
if (rc != ECORE_SUCCESS) {
DP_ERR(edev, "Failed to add multicast filter (rc = %d\n)", rc);
return -1;
}
return 0;
}
static int qede_del_mcast_filters(struct rte_eth_dev *eth_dev)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
struct qede_mcast_entry *tmp = NULL;
struct ecore_filter_mcast mcast;
int j;
int rc;
memset(&mcast, 0, sizeof(mcast));
mcast.num_mc_addrs = qdev->num_mc_addr;
mcast.opcode = ECORE_FILTER_REMOVE;
j = 0;
SLIST_FOREACH(tmp, &qdev->mc_list_head, list) {
rte_ether_addr_copy(&tmp->mac,
(struct rte_ether_addr *)&mcast.mac[j]);
j++;
}
rc = ecore_filter_mcast_cmd(edev, &mcast, ECORE_SPQ_MODE_CB, NULL);
if (rc != ECORE_SUCCESS) {
DP_ERR(edev, "Failed to delete multicast filter\n");
return -1;
}
/* Init the list */
while (!SLIST_EMPTY(&qdev->mc_list_head)) {
tmp = SLIST_FIRST(&qdev->mc_list_head);
SLIST_REMOVE_HEAD(&qdev->mc_list_head, list);
}
SLIST_INIT(&qdev->mc_list_head);
return 0;
}
enum _ecore_status_t
qede_mac_int_ops(struct rte_eth_dev *eth_dev, struct ecore_filter_ucast *ucast,
bool add)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
enum _ecore_status_t rc = ECORE_INVAL;
if (add && (qdev->num_uc_addr >= qdev->dev_info.num_mac_filters)) {
DP_ERR(edev, "Ucast filter table limit exceeded,"
" Please enable promisc mode\n");
return ECORE_INVAL;
}
rc = qede_ucast_filter(eth_dev, ucast, add);
if (rc == 0)
rc = ecore_filter_ucast_cmd(edev, ucast,
ECORE_SPQ_MODE_CB, NULL);
/* Indicate error only for add filter operation.
* Delete filter operations are not severe.
*/
if ((rc != ECORE_SUCCESS) && add)
DP_ERR(edev, "MAC filter failed, rc = %d, op = %d\n",
rc, add);
return rc;
}
static int
qede_mac_addr_add(struct rte_eth_dev *eth_dev, struct rte_ether_addr *mac_addr,
__rte_unused uint32_t index, __rte_unused uint32_t pool)
{
struct ecore_filter_ucast ucast;
int re;
if (!rte_is_valid_assigned_ether_addr(mac_addr))
return -EINVAL;
qede_set_ucast_cmn_params(&ucast);
ucast.opcode = ECORE_FILTER_ADD;
ucast.type = ECORE_FILTER_MAC;
rte_ether_addr_copy(mac_addr, (struct rte_ether_addr *)&ucast.mac);
re = (int)qede_mac_int_ops(eth_dev, &ucast, 1);
return re;
}
static void
qede_mac_addr_remove(struct rte_eth_dev *eth_dev, uint32_t index)
{
struct qede_dev *qdev = eth_dev->data->dev_private;
struct ecore_dev *edev = &qdev->edev;
struct ecore_filter_ucast ucast;
PMD_INIT_FUNC_TRACE(edev);
if (index >= qdev->dev_info.num_mac_filters) {
DP_ERR(edev, "Index %u is above MAC filter limit %u\n",
index, qdev->dev_info.num_mac_filters);
return;
}
if (!rte_is_valid_assigned_ether_addr(ð_dev->data->mac_addrs[index]))
return;
qede_set_ucast_cmn_params(&ucast);
ucast.opcode = ECORE_FILTER_REMOVE;
ucast.type = ECORE_FILTER_MAC;
/* Use the index maintained by rte */
rte_ether_addr_copy(ð_dev->data->mac_addrs[index],
(struct rte_ether_addr *)&ucast.mac);
qede_mac_int_ops(eth_dev, &ucast, false);
}
static int
qede_mac_addr_set(struct rte_eth_dev *eth_dev, struct rte_ether_addr *mac_addr)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
if (IS_VF(edev) && !ecore_vf_check_mac(ECORE_LEADING_HWFN(edev),
mac_addr->addr_bytes)) {
DP_ERR(edev, "Setting MAC address is not allowed\n");
return -EPERM;
}
qede_mac_addr_remove(eth_dev, 0);
return qede_mac_addr_add(eth_dev, mac_addr, 0, 0);
}
void qede_config_accept_any_vlan(struct qede_dev *qdev, bool flg)
{
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
struct ecore_sp_vport_update_params params;
struct ecore_hwfn *p_hwfn;
uint8_t i;
int rc;
memset(¶ms, 0, sizeof(struct ecore_sp_vport_update_params));
params.vport_id = 0;
params.update_accept_any_vlan_flg = 1;
params.accept_any_vlan = flg;
for_each_hwfn(edev, i) {
p_hwfn = &edev->hwfns[i];
params.opaque_fid = p_hwfn->hw_info.opaque_fid;
rc = ecore_sp_vport_update(p_hwfn, ¶ms,
ECORE_SPQ_MODE_EBLOCK, NULL);
if (rc != ECORE_SUCCESS) {
DP_ERR(edev, "Failed to configure accept-any-vlan\n");
return;
}
}
DP_INFO(edev, "%s accept-any-vlan\n", flg ? "enabled" : "disabled");
}
static int qede_vlan_stripping(struct rte_eth_dev *eth_dev, bool flg)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
struct ecore_sp_vport_update_params params;
struct ecore_hwfn *p_hwfn;
uint8_t i;
int rc;
memset(¶ms, 0, sizeof(struct ecore_sp_vport_update_params));
params.vport_id = 0;
params.update_inner_vlan_removal_flg = 1;
params.inner_vlan_removal_flg = flg;
for_each_hwfn(edev, i) {
p_hwfn = &edev->hwfns[i];
params.opaque_fid = p_hwfn->hw_info.opaque_fid;
rc = ecore_sp_vport_update(p_hwfn, ¶ms,
ECORE_SPQ_MODE_EBLOCK, NULL);
if (rc != ECORE_SUCCESS) {
DP_ERR(edev, "Failed to update vport\n");
return -1;
}
}
qdev->vlan_strip_flg = flg;
DP_INFO(edev, "VLAN stripping %s\n", flg ? "enabled" : "disabled");
return 0;
}
static int qede_vlan_filter_set(struct rte_eth_dev *eth_dev,
uint16_t vlan_id, int on)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
struct qed_dev_eth_info *dev_info = &qdev->dev_info;
struct qede_vlan_entry *tmp = NULL;
struct qede_vlan_entry *vlan;
struct ecore_filter_ucast ucast;
int rc;
if (on) {
if (qdev->configured_vlans == dev_info->num_vlan_filters) {
DP_ERR(edev, "Reached max VLAN filter limit"
" enabling accept_any_vlan\n");
qede_config_accept_any_vlan(qdev, true);
return 0;
}
SLIST_FOREACH(tmp, &qdev->vlan_list_head, list) {
if (tmp->vid == vlan_id) {
DP_INFO(edev, "VLAN %u already configured\n",
vlan_id);
return 0;
}
}
vlan = rte_malloc(NULL, sizeof(struct qede_vlan_entry),
RTE_CACHE_LINE_SIZE);
if (!vlan) {
DP_ERR(edev, "Did not allocate memory for VLAN\n");
return -ENOMEM;
}
qede_set_ucast_cmn_params(&ucast);
ucast.opcode = ECORE_FILTER_ADD;
ucast.type = ECORE_FILTER_VLAN;
ucast.vlan = vlan_id;
rc = ecore_filter_ucast_cmd(edev, &ucast, ECORE_SPQ_MODE_CB,
NULL);
if (rc != 0) {
DP_ERR(edev, "Failed to add VLAN %u rc %d\n", vlan_id,
rc);
rte_free(vlan);
} else {
vlan->vid = vlan_id;
SLIST_INSERT_HEAD(&qdev->vlan_list_head, vlan, list);
qdev->configured_vlans++;
DP_INFO(edev, "VLAN %u added, configured_vlans %u\n",
vlan_id, qdev->configured_vlans);
}
} else {
SLIST_FOREACH(tmp, &qdev->vlan_list_head, list) {
if (tmp->vid == vlan_id)
break;
}
if (!tmp) {
if (qdev->configured_vlans == 0) {
DP_INFO(edev,
"No VLAN filters configured yet\n");
return 0;
}
DP_ERR(edev, "VLAN %u not configured\n", vlan_id);
return -EINVAL;
}
SLIST_REMOVE(&qdev->vlan_list_head, tmp, qede_vlan_entry, list);
qede_set_ucast_cmn_params(&ucast);
ucast.opcode = ECORE_FILTER_REMOVE;
ucast.type = ECORE_FILTER_VLAN;
ucast.vlan = vlan_id;
rc = ecore_filter_ucast_cmd(edev, &ucast, ECORE_SPQ_MODE_CB,
NULL);
if (rc != 0) {
DP_ERR(edev, "Failed to delete VLAN %u rc %d\n",
vlan_id, rc);
} else {
qdev->configured_vlans--;
DP_INFO(edev, "VLAN %u removed configured_vlans %u\n",
vlan_id, qdev->configured_vlans);
}
}
return rc;
}
static int qede_vlan_offload_set(struct rte_eth_dev *eth_dev, int mask)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
uint64_t rx_offloads = eth_dev->data->dev_conf.rxmode.offloads;
if (mask & ETH_VLAN_STRIP_MASK) {
if (rx_offloads & DEV_RX_OFFLOAD_VLAN_STRIP)
(void)qede_vlan_stripping(eth_dev, 1);
else
(void)qede_vlan_stripping(eth_dev, 0);
}
if (mask & ETH_VLAN_FILTER_MASK) {
/* VLAN filtering kicks in when a VLAN is added */
if (rx_offloads & DEV_RX_OFFLOAD_VLAN_FILTER) {
qede_vlan_filter_set(eth_dev, 0, 1);
} else {
if (qdev->configured_vlans > 1) { /* Excluding VLAN0 */
DP_ERR(edev,
" Please remove existing VLAN filters"
" before disabling VLAN filtering\n");
/* Signal app that VLAN filtering is still
* enabled
*/
eth_dev->data->dev_conf.rxmode.offloads |=
DEV_RX_OFFLOAD_VLAN_FILTER;
} else {
qede_vlan_filter_set(eth_dev, 0, 0);
}
}
}
if (mask & ETH_VLAN_EXTEND_MASK)
DP_ERR(edev, "Extend VLAN not supported\n");
qdev->vlan_offload_mask = mask;
DP_INFO(edev, "VLAN offload mask %d\n", mask);
return 0;
}
static void qede_prandom_bytes(uint32_t *buff)
{
uint8_t i;
srand((unsigned int)time(NULL));
for (i = 0; i < ECORE_RSS_KEY_SIZE; i++)
buff[i] = rand();
}
int qede_config_rss(struct rte_eth_dev *eth_dev)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
uint32_t def_rss_key[ECORE_RSS_KEY_SIZE];
struct rte_eth_rss_reta_entry64 reta_conf[2];
struct rte_eth_rss_conf rss_conf;
uint32_t i, id, pos, q;
rss_conf = eth_dev->data->dev_conf.rx_adv_conf.rss_conf;
if (!rss_conf.rss_key) {
DP_INFO(edev, "Applying driver default key\n");
rss_conf.rss_key_len = ECORE_RSS_KEY_SIZE * sizeof(uint32_t);
qede_prandom_bytes(&def_rss_key[0]);
rss_conf.rss_key = (uint8_t *)&def_rss_key[0];
}
/* Configure RSS hash */
if (qede_rss_hash_update(eth_dev, &rss_conf))
return -EINVAL;
/* Configure default RETA */
memset(reta_conf, 0, sizeof(reta_conf));
for (i = 0; i < ECORE_RSS_IND_TABLE_SIZE; i++)
reta_conf[i / RTE_RETA_GROUP_SIZE].mask = UINT64_MAX;
for (i = 0; i < ECORE_RSS_IND_TABLE_SIZE; i++) {
id = i / RTE_RETA_GROUP_SIZE;
pos = i % RTE_RETA_GROUP_SIZE;
q = i % QEDE_RSS_COUNT(eth_dev);
reta_conf[id].reta[pos] = q;
}
if (qede_rss_reta_update(eth_dev, &reta_conf[0],
ECORE_RSS_IND_TABLE_SIZE))
return -EINVAL;
return 0;
}
static void qede_fastpath_start(struct ecore_dev *edev)
{
struct ecore_hwfn *p_hwfn;
int i;
for_each_hwfn(edev, i) {
p_hwfn = &edev->hwfns[i];
ecore_hw_start_fastpath(p_hwfn);
}
}
static int qede_dev_start(struct rte_eth_dev *eth_dev)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
struct rte_eth_rxmode *rxmode = ð_dev->data->dev_conf.rxmode;
PMD_INIT_FUNC_TRACE(edev);
/* Update MTU only if it has changed */
if (qdev->new_mtu && qdev->new_mtu != qdev->mtu) {
if (qede_update_mtu(eth_dev, qdev->new_mtu))
goto err;
qdev->mtu = qdev->new_mtu;
qdev->new_mtu = 0;
}
/* Configure TPA parameters */
if (rxmode->offloads & DEV_RX_OFFLOAD_TCP_LRO) {
if (qede_enable_tpa(eth_dev, true))
return -EINVAL;
/* Enable scatter mode for LRO */
if (!eth_dev->data->scattered_rx)
rxmode->offloads |= DEV_RX_OFFLOAD_SCATTER;
}
/* Start queues */
if (qede_start_queues(eth_dev))
goto err;
if (IS_PF(edev))
qede_reset_queue_stats(qdev, true);
/* Newer SR-IOV PF driver expects RX/TX queues to be started before
* enabling RSS. Hence RSS configuration is deferred upto this point.
* Also, we would like to retain similar behavior in PF case, so we
* don't do PF/VF specific check here.
*/
if (eth_dev->data->dev_conf.rxmode.mq_mode == ETH_MQ_RX_RSS)
if (qede_config_rss(eth_dev))
goto err;
/* Enable vport*/
if (qede_activate_vport(eth_dev, true))
goto err;
/* Update link status */
qede_link_update(eth_dev, 0);
/* Start/resume traffic */
qede_fastpath_start(edev);
qede_assign_rxtx_handlers(eth_dev);
DP_INFO(edev, "Device started\n");
return 0;
err:
DP_ERR(edev, "Device start fails\n");
return -1; /* common error code is < 0 */
}
static void qede_dev_stop(struct rte_eth_dev *eth_dev)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
PMD_INIT_FUNC_TRACE(edev);
/* Disable vport */
if (qede_activate_vport(eth_dev, false))
return;
if (qdev->enable_lro)
qede_enable_tpa(eth_dev, false);
/* Stop queues */
qede_stop_queues(eth_dev);
/* Disable traffic */
ecore_hw_stop_fastpath(edev); /* TBD - loop */
DP_INFO(edev, "Device is stopped\n");
}
static const char * const valid_args[] = {
QEDE_NPAR_TX_SWITCHING,
QEDE_VF_TX_SWITCHING,
NULL,
};
static int qede_args_check(const char *key, const char *val, void *opaque)
{
unsigned long tmp;
int ret = 0;
struct rte_eth_dev *eth_dev = opaque;
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
errno = 0;
tmp = strtoul(val, NULL, 0);
if (errno) {
DP_INFO(edev, "%s: \"%s\" is not a valid integer", key, val);
return errno;
}
if ((strcmp(QEDE_NPAR_TX_SWITCHING, key) == 0) ||
((strcmp(QEDE_VF_TX_SWITCHING, key) == 0) && IS_VF(edev))) {
qdev->enable_tx_switching = !!tmp;
DP_INFO(edev, "Disabling %s tx-switching\n",
strcmp(QEDE_NPAR_TX_SWITCHING, key) ?
"VF" : "NPAR");
}
return ret;
}
static int qede_args(struct rte_eth_dev *eth_dev)
{
struct rte_pci_device *pci_dev = RTE_DEV_TO_PCI(eth_dev->device);
struct rte_kvargs *kvlist;
struct rte_devargs *devargs;
int ret;
int i;
devargs = pci_dev->device.devargs;
if (!devargs)
return 0; /* return success */
kvlist = rte_kvargs_parse(devargs->args, valid_args);
if (kvlist == NULL)
return -EINVAL;
/* Process parameters. */
for (i = 0; (valid_args[i] != NULL); ++i) {
if (rte_kvargs_count(kvlist, valid_args[i])) {
ret = rte_kvargs_process(kvlist, valid_args[i],
qede_args_check, eth_dev);
if (ret != ECORE_SUCCESS) {
rte_kvargs_free(kvlist);
return ret;
}
}
}
rte_kvargs_free(kvlist);
return 0;
}
static int qede_dev_configure(struct rte_eth_dev *eth_dev)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
struct rte_eth_rxmode *rxmode = ð_dev->data->dev_conf.rxmode;
int ret;
PMD_INIT_FUNC_TRACE(edev);
if (rxmode->mq_mode & ETH_MQ_RX_RSS_FLAG)
rxmode->offloads |= DEV_RX_OFFLOAD_RSS_HASH;
/* We need to have min 1 RX queue.There is no min check in
* rte_eth_dev_configure(), so we are checking it here.
*/
if (eth_dev->data->nb_rx_queues == 0) {
DP_ERR(edev, "Minimum one RX queue is required\n");
return -EINVAL;
}
/* Enable Tx switching by default */
qdev->enable_tx_switching = 1;
/* Parse devargs and fix up rxmode */
if (qede_args(eth_dev))
DP_NOTICE(edev, false,
"Invalid devargs supplied, requested change will not take effect\n");
if (!(rxmode->mq_mode == ETH_MQ_RX_NONE ||
rxmode->mq_mode == ETH_MQ_RX_RSS)) {
DP_ERR(edev, "Unsupported multi-queue mode\n");
return -ENOTSUP;
}
/* Flow director mode check */
if (qede_check_fdir_support(eth_dev))
return -ENOTSUP;
qede_dealloc_fp_resc(eth_dev);
qdev->num_tx_queues = eth_dev->data->nb_tx_queues * edev->num_hwfns;
qdev->num_rx_queues = eth_dev->data->nb_rx_queues * edev->num_hwfns;
if (qede_alloc_fp_resc(qdev))
return -ENOMEM;
/* If jumbo enabled adjust MTU */
if (rxmode->offloads & DEV_RX_OFFLOAD_JUMBO_FRAME)
eth_dev->data->mtu =
eth_dev->data->dev_conf.rxmode.max_rx_pkt_len -
RTE_ETHER_HDR_LEN - QEDE_ETH_OVERHEAD;
if (rxmode->offloads & DEV_RX_OFFLOAD_SCATTER)
eth_dev->data->scattered_rx = 1;
if (qede_start_vport(qdev, eth_dev->data->mtu))
return -1;
qdev->mtu = eth_dev->data->mtu;
/* Enable VLAN offloads by default */
ret = qede_vlan_offload_set(eth_dev, ETH_VLAN_STRIP_MASK |
ETH_VLAN_FILTER_MASK);
if (ret)
return ret;
DP_INFO(edev, "Device configured with RSS=%d TSS=%d\n",
QEDE_RSS_COUNT(eth_dev), QEDE_TSS_COUNT(eth_dev));
if (ECORE_IS_CMT(edev))
DP_INFO(edev, "Actual HW queues for CMT mode - RX = %d TX = %d\n",
qdev->num_rx_queues, qdev->num_tx_queues);
return 0;
}
/* Info about HW descriptor ring limitations */
static const struct rte_eth_desc_lim qede_rx_desc_lim = {
.nb_max = 0x8000, /* 32K */
.nb_min = 128,
.nb_align = 128 /* lowest common multiple */
};
static const struct rte_eth_desc_lim qede_tx_desc_lim = {
.nb_max = 0x8000, /* 32K */
.nb_min = 256,
.nb_align = 256,
.nb_seg_max = ETH_TX_MAX_BDS_PER_LSO_PACKET,
.nb_mtu_seg_max = ETH_TX_MAX_BDS_PER_NON_LSO_PACKET
};
static int
qede_dev_info_get(struct rte_eth_dev *eth_dev,
struct rte_eth_dev_info *dev_info)
{
struct qede_dev *qdev = eth_dev->data->dev_private;
struct ecore_dev *edev = &qdev->edev;
struct qed_link_output link;
uint32_t speed_cap = 0;
PMD_INIT_FUNC_TRACE(edev);
dev_info->min_rx_bufsize = (uint32_t)QEDE_MIN_RX_BUFF_SIZE;
dev_info->max_rx_pktlen = (uint32_t)ETH_TX_MAX_NON_LSO_PKT_LEN;
dev_info->rx_desc_lim = qede_rx_desc_lim;
dev_info->tx_desc_lim = qede_tx_desc_lim;
if (IS_PF(edev))
dev_info->max_rx_queues = (uint16_t)RTE_MIN(
QEDE_MAX_RSS_CNT(qdev), QEDE_PF_NUM_CONNS / 2);
else
dev_info->max_rx_queues = (uint16_t)RTE_MIN(
QEDE_MAX_RSS_CNT(qdev), ECORE_MAX_VF_CHAINS_PER_PF);
/* Since CMT mode internally doubles the number of queues */
if (ECORE_IS_CMT(edev))
dev_info->max_rx_queues = dev_info->max_rx_queues / 2;
dev_info->max_tx_queues = dev_info->max_rx_queues;
dev_info->max_mac_addrs = qdev->dev_info.num_mac_filters;
dev_info->max_vfs = 0;
dev_info->reta_size = ECORE_RSS_IND_TABLE_SIZE;
dev_info->hash_key_size = ECORE_RSS_KEY_SIZE * sizeof(uint32_t);
dev_info->flow_type_rss_offloads = (uint64_t)QEDE_RSS_OFFLOAD_ALL;
dev_info->rx_offload_capa = (DEV_RX_OFFLOAD_IPV4_CKSUM |
DEV_RX_OFFLOAD_UDP_CKSUM |
DEV_RX_OFFLOAD_TCP_CKSUM |
DEV_RX_OFFLOAD_OUTER_IPV4_CKSUM |
DEV_RX_OFFLOAD_TCP_LRO |
DEV_RX_OFFLOAD_KEEP_CRC |
DEV_RX_OFFLOAD_SCATTER |
DEV_RX_OFFLOAD_JUMBO_FRAME |
DEV_RX_OFFLOAD_VLAN_FILTER |
DEV_RX_OFFLOAD_VLAN_STRIP |
DEV_RX_OFFLOAD_RSS_HASH);
dev_info->rx_queue_offload_capa = 0;
/* TX offloads are on a per-packet basis, so it is applicable
* to both at port and queue levels.
*/
dev_info->tx_offload_capa = (DEV_TX_OFFLOAD_VLAN_INSERT |
DEV_TX_OFFLOAD_IPV4_CKSUM |
DEV_TX_OFFLOAD_UDP_CKSUM |
DEV_TX_OFFLOAD_TCP_CKSUM |
DEV_TX_OFFLOAD_OUTER_IPV4_CKSUM |
DEV_TX_OFFLOAD_MULTI_SEGS |
DEV_TX_OFFLOAD_TCP_TSO |
DEV_TX_OFFLOAD_VXLAN_TNL_TSO |
DEV_TX_OFFLOAD_GENEVE_TNL_TSO);
dev_info->tx_queue_offload_capa = dev_info->tx_offload_capa;
dev_info->default_txconf = (struct rte_eth_txconf) {
.offloads = DEV_TX_OFFLOAD_MULTI_SEGS,
};
dev_info->default_rxconf = (struct rte_eth_rxconf) {
/* Packets are always dropped if no descriptors are available */
.rx_drop_en = 1,
.offloads = 0,
};
memset(&link, 0, sizeof(struct qed_link_output));
qdev->ops->common->get_link(edev, &link);
if (link.adv_speed & NVM_CFG1_PORT_DRV_SPEED_CAPABILITY_MASK_1G)
speed_cap |= ETH_LINK_SPEED_1G;
if (link.adv_speed & NVM_CFG1_PORT_DRV_SPEED_CAPABILITY_MASK_10G)
speed_cap |= ETH_LINK_SPEED_10G;
if (link.adv_speed & NVM_CFG1_PORT_DRV_SPEED_CAPABILITY_MASK_25G)
speed_cap |= ETH_LINK_SPEED_25G;
if (link.adv_speed & NVM_CFG1_PORT_DRV_SPEED_CAPABILITY_MASK_40G)
speed_cap |= ETH_LINK_SPEED_40G;
if (link.adv_speed & NVM_CFG1_PORT_DRV_SPEED_CAPABILITY_MASK_50G)
speed_cap |= ETH_LINK_SPEED_50G;
if (link.adv_speed & NVM_CFG1_PORT_DRV_SPEED_CAPABILITY_MASK_BB_100G)
speed_cap |= ETH_LINK_SPEED_100G;
dev_info->speed_capa = speed_cap;
return 0;
}
/* return 0 means link status changed, -1 means not changed */
int
qede_link_update(struct rte_eth_dev *eth_dev, __rte_unused int wait_to_complete)
{
struct qede_dev *qdev = eth_dev->data->dev_private;
struct ecore_dev *edev = &qdev->edev;
struct qed_link_output q_link;
struct rte_eth_link link;
uint16_t link_duplex;
memset(&q_link, 0, sizeof(q_link));
memset(&link, 0, sizeof(link));
qdev->ops->common->get_link(edev, &q_link);
/* Link Speed */
link.link_speed = q_link.speed;
/* Link Mode */
switch (q_link.duplex) {
case QEDE_DUPLEX_HALF:
link_duplex = ETH_LINK_HALF_DUPLEX;
break;
case QEDE_DUPLEX_FULL:
link_duplex = ETH_LINK_FULL_DUPLEX;
break;
case QEDE_DUPLEX_UNKNOWN:
default:
link_duplex = -1;
}
link.link_duplex = link_duplex;
/* Link Status */
link.link_status = q_link.link_up ? ETH_LINK_UP : ETH_LINK_DOWN;
/* AN */
link.link_autoneg = (q_link.supported_caps & QEDE_SUPPORTED_AUTONEG) ?
ETH_LINK_AUTONEG : ETH_LINK_FIXED;
DP_INFO(edev, "Link - Speed %u Mode %u AN %u Status %u\n",
link.link_speed, link.link_duplex,
link.link_autoneg, link.link_status);
return rte_eth_linkstatus_set(eth_dev, &link);
}
static int qede_promiscuous_enable(struct rte_eth_dev *eth_dev)
{
struct qede_dev *qdev = eth_dev->data->dev_private;
struct ecore_dev *edev = &qdev->edev;
enum qed_filter_rx_mode_type type = QED_FILTER_RX_MODE_TYPE_PROMISC;
enum _ecore_status_t ecore_status;
PMD_INIT_FUNC_TRACE(edev);
if (rte_eth_allmulticast_get(eth_dev->data->port_id) == 1)
type |= QED_FILTER_RX_MODE_TYPE_MULTI_PROMISC;
ecore_status = qed_configure_filter_rx_mode(eth_dev, type);
return ecore_status >= ECORE_SUCCESS ? 0 : -EAGAIN;
}
static int qede_promiscuous_disable(struct rte_eth_dev *eth_dev)
{
struct qede_dev *qdev = eth_dev->data->dev_private;
struct ecore_dev *edev = &qdev->edev;
enum _ecore_status_t ecore_status;
PMD_INIT_FUNC_TRACE(edev);
if (rte_eth_allmulticast_get(eth_dev->data->port_id) == 1)
ecore_status = qed_configure_filter_rx_mode(eth_dev,
QED_FILTER_RX_MODE_TYPE_MULTI_PROMISC);
else
ecore_status = qed_configure_filter_rx_mode(eth_dev,
QED_FILTER_RX_MODE_TYPE_REGULAR);
return ecore_status >= ECORE_SUCCESS ? 0 : -EAGAIN;
}
static void qede_poll_sp_sb_cb(void *param)
{
struct rte_eth_dev *eth_dev = (struct rte_eth_dev *)param;
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
int rc;
qede_interrupt_action(ECORE_LEADING_HWFN(edev));
qede_interrupt_action(&edev->hwfns[1]);
rc = rte_eal_alarm_set(QEDE_SP_TIMER_PERIOD,
qede_poll_sp_sb_cb,
(void *)eth_dev);
if (rc != 0) {
DP_ERR(edev, "Unable to start periodic"
" timer rc %d\n", rc);
}
}
static void qede_dev_close(struct rte_eth_dev *eth_dev)
{
struct rte_pci_device *pci_dev = RTE_ETH_DEV_TO_PCI(eth_dev);
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
PMD_INIT_FUNC_TRACE(edev);
/* dev_stop() shall cleanup fp resources in hw but without releasing
* dma memories and sw structures so that dev_start() can be called
* by the app without reconfiguration. However, in dev_close() we
* can release all the resources and device can be brought up newly
*/
if (eth_dev->data->dev_started)
qede_dev_stop(eth_dev);
if (qdev->vport_started)
qede_stop_vport(edev);
qdev->vport_started = false;
qede_fdir_dealloc_resc(eth_dev);
qede_dealloc_fp_resc(eth_dev);
eth_dev->data->nb_rx_queues = 0;
eth_dev->data->nb_tx_queues = 0;
/* Bring the link down */
qede_dev_set_link_state(eth_dev, false);
qdev->ops->common->slowpath_stop(edev);
qdev->ops->common->remove(edev);
rte_intr_disable(&pci_dev->intr_handle);
switch (pci_dev->intr_handle.type) {
case RTE_INTR_HANDLE_UIO_INTX:
case RTE_INTR_HANDLE_VFIO_LEGACY:
rte_intr_callback_unregister(&pci_dev->intr_handle,
qede_interrupt_handler_intx,
(void *)eth_dev);
break;
default:
rte_intr_callback_unregister(&pci_dev->intr_handle,
qede_interrupt_handler,
(void *)eth_dev);
}
if (ECORE_IS_CMT(edev))
rte_eal_alarm_cancel(qede_poll_sp_sb_cb, (void *)eth_dev);
}
static int
qede_get_stats(struct rte_eth_dev *eth_dev, struct rte_eth_stats *eth_stats)
{
struct qede_dev *qdev = eth_dev->data->dev_private;
struct ecore_dev *edev = &qdev->edev;
struct ecore_eth_stats stats;
unsigned int i = 0, j = 0, qid, idx, hw_fn;
unsigned int rxq_stat_cntrs, txq_stat_cntrs;
struct qede_tx_queue *txq;
ecore_get_vport_stats(edev, &stats);
/* RX Stats */
eth_stats->ipackets = stats.common.rx_ucast_pkts +
stats.common.rx_mcast_pkts + stats.common.rx_bcast_pkts;
eth_stats->ibytes = stats.common.rx_ucast_bytes +
stats.common.rx_mcast_bytes + stats.common.rx_bcast_bytes;
eth_stats->ierrors = stats.common.rx_crc_errors +
stats.common.rx_align_errors +
stats.common.rx_carrier_errors +
stats.common.rx_oversize_packets +
stats.common.rx_jabbers + stats.common.rx_undersize_packets;
eth_stats->rx_nombuf = stats.common.no_buff_discards;
eth_stats->imissed = stats.common.mftag_filter_discards +
stats.common.mac_filter_discards +
stats.common.no_buff_discards +
stats.common.brb_truncates + stats.common.brb_discards;
/* TX stats */
eth_stats->opackets = stats.common.tx_ucast_pkts +
stats.common.tx_mcast_pkts + stats.common.tx_bcast_pkts;
eth_stats->obytes = stats.common.tx_ucast_bytes +
stats.common.tx_mcast_bytes + stats.common.tx_bcast_bytes;
eth_stats->oerrors = stats.common.tx_err_drop_pkts;
/* Queue stats */
rxq_stat_cntrs = RTE_MIN(QEDE_RSS_COUNT(eth_dev),
RTE_ETHDEV_QUEUE_STAT_CNTRS);
txq_stat_cntrs = RTE_MIN(QEDE_TSS_COUNT(eth_dev),
RTE_ETHDEV_QUEUE_STAT_CNTRS);
if (rxq_stat_cntrs != (unsigned int)QEDE_RSS_COUNT(eth_dev) ||
txq_stat_cntrs != (unsigned int)QEDE_TSS_COUNT(eth_dev))
DP_VERBOSE(edev, ECORE_MSG_DEBUG,
"Not all the queue stats will be displayed. Set"
" RTE_ETHDEV_QUEUE_STAT_CNTRS config param"
" appropriately and retry.\n");
for (qid = 0; qid < eth_dev->data->nb_rx_queues; qid++) {
eth_stats->q_ipackets[i] = 0;
eth_stats->q_errors[i] = 0;
for_each_hwfn(edev, hw_fn) {
idx = qid * edev->num_hwfns + hw_fn;
eth_stats->q_ipackets[i] +=
*(uint64_t *)
(((char *)(qdev->fp_array[idx].rxq)) +
offsetof(struct qede_rx_queue,
rcv_pkts));
eth_stats->q_errors[i] +=
*(uint64_t *)
(((char *)(qdev->fp_array[idx].rxq)) +
offsetof(struct qede_rx_queue,
rx_hw_errors)) +
*(uint64_t *)
(((char *)(qdev->fp_array[idx].rxq)) +
offsetof(struct qede_rx_queue,
rx_alloc_errors));
}
i++;
if (i == rxq_stat_cntrs)
break;
}
for (qid = 0; qid < eth_dev->data->nb_tx_queues; qid++) {
eth_stats->q_opackets[j] = 0;
for_each_hwfn(edev, hw_fn) {
idx = qid * edev->num_hwfns + hw_fn;
txq = qdev->fp_array[idx].txq;
eth_stats->q_opackets[j] +=
*((uint64_t *)(uintptr_t)
(((uint64_t)(uintptr_t)(txq)) +
offsetof(struct qede_tx_queue,
xmit_pkts)));
}
j++;
if (j == txq_stat_cntrs)
break;
}
return 0;
}
static unsigned
qede_get_xstats_count(struct qede_dev *qdev) {
struct rte_eth_dev *dev = (struct rte_eth_dev *)qdev->ethdev;
if (ECORE_IS_BB(&qdev->edev))
return RTE_DIM(qede_xstats_strings) +
RTE_DIM(qede_bb_xstats_strings) +
(RTE_DIM(qede_rxq_xstats_strings) *
QEDE_RSS_COUNT(dev) * qdev->edev.num_hwfns);
else
return RTE_DIM(qede_xstats_strings) +
RTE_DIM(qede_ah_xstats_strings) +
(RTE_DIM(qede_rxq_xstats_strings) *
QEDE_RSS_COUNT(dev));
}
static int
qede_get_xstats_names(struct rte_eth_dev *dev,
struct rte_eth_xstat_name *xstats_names,
__rte_unused unsigned int limit)
{
struct qede_dev *qdev = dev->data->dev_private;
struct ecore_dev *edev = &qdev->edev;
const unsigned int stat_cnt = qede_get_xstats_count(qdev);
unsigned int i, qid, hw_fn, stat_idx = 0;
if (xstats_names == NULL)
return stat_cnt;
for (i = 0; i < RTE_DIM(qede_xstats_strings); i++) {
strlcpy(xstats_names[stat_idx].name,
qede_xstats_strings[i].name,
sizeof(xstats_names[stat_idx].name));
stat_idx++;
}
if (ECORE_IS_BB(edev)) {
for (i = 0; i < RTE_DIM(qede_bb_xstats_strings); i++) {
strlcpy(xstats_names[stat_idx].name,
qede_bb_xstats_strings[i].name,
sizeof(xstats_names[stat_idx].name));
stat_idx++;
}
} else {
for (i = 0; i < RTE_DIM(qede_ah_xstats_strings); i++) {
strlcpy(xstats_names[stat_idx].name,
qede_ah_xstats_strings[i].name,
sizeof(xstats_names[stat_idx].name));
stat_idx++;
}
}
for (qid = 0; qid < QEDE_RSS_COUNT(dev); qid++) {
for_each_hwfn(edev, hw_fn) {
for (i = 0; i < RTE_DIM(qede_rxq_xstats_strings); i++) {
snprintf(xstats_names[stat_idx].name,
RTE_ETH_XSTATS_NAME_SIZE,
"%.4s%d.%d%s",
qede_rxq_xstats_strings[i].name,
hw_fn, qid,
qede_rxq_xstats_strings[i].name + 4);
stat_idx++;
}
}
}
return stat_cnt;
}
static int
qede_get_xstats(struct rte_eth_dev *dev, struct rte_eth_xstat *xstats,
unsigned int n)
{
struct qede_dev *qdev = dev->data->dev_private;
struct ecore_dev *edev = &qdev->edev;
struct ecore_eth_stats stats;
const unsigned int num = qede_get_xstats_count(qdev);
unsigned int i, qid, hw_fn, fpidx, stat_idx = 0;
if (n < num)
return num;
ecore_get_vport_stats(edev, &stats);
for (i = 0; i < RTE_DIM(qede_xstats_strings); i++) {
xstats[stat_idx].value = *(uint64_t *)(((char *)&stats) +
qede_xstats_strings[i].offset);
xstats[stat_idx].id = stat_idx;
stat_idx++;
}
if (ECORE_IS_BB(edev)) {
for (i = 0; i < RTE_DIM(qede_bb_xstats_strings); i++) {
xstats[stat_idx].value =
*(uint64_t *)(((char *)&stats) +
qede_bb_xstats_strings[i].offset);
xstats[stat_idx].id = stat_idx;
stat_idx++;
}
} else {
for (i = 0; i < RTE_DIM(qede_ah_xstats_strings); i++) {
xstats[stat_idx].value =
*(uint64_t *)(((char *)&stats) +
qede_ah_xstats_strings[i].offset);
xstats[stat_idx].id = stat_idx;
stat_idx++;
}
}
for (qid = 0; qid < dev->data->nb_rx_queues; qid++) {
for_each_hwfn(edev, hw_fn) {
for (i = 0; i < RTE_DIM(qede_rxq_xstats_strings); i++) {
fpidx = qid * edev->num_hwfns + hw_fn;
xstats[stat_idx].value = *(uint64_t *)
(((char *)(qdev->fp_array[fpidx].rxq)) +
qede_rxq_xstats_strings[i].offset);
xstats[stat_idx].id = stat_idx;
stat_idx++;
}
}
}
return stat_idx;
}
static int
qede_reset_xstats(struct rte_eth_dev *dev)
{
struct qede_dev *qdev = dev->data->dev_private;
struct ecore_dev *edev = &qdev->edev;
ecore_reset_vport_stats(edev);
qede_reset_queue_stats(qdev, true);
return 0;
}
int qede_dev_set_link_state(struct rte_eth_dev *eth_dev, bool link_up)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
struct qed_link_params link_params;
int rc;
DP_INFO(edev, "setting link state %d\n", link_up);
memset(&link_params, 0, sizeof(link_params));
link_params.link_up = link_up;
rc = qdev->ops->common->set_link(edev, &link_params);
if (rc != ECORE_SUCCESS)
DP_ERR(edev, "Unable to set link state %d\n", link_up);
return rc;
}
static int qede_dev_set_link_up(struct rte_eth_dev *eth_dev)
{
return qede_dev_set_link_state(eth_dev, true);
}
static int qede_dev_set_link_down(struct rte_eth_dev *eth_dev)
{
return qede_dev_set_link_state(eth_dev, false);
}
static int qede_reset_stats(struct rte_eth_dev *eth_dev)
{
struct qede_dev *qdev = eth_dev->data->dev_private;
struct ecore_dev *edev = &qdev->edev;
ecore_reset_vport_stats(edev);
qede_reset_queue_stats(qdev, false);
return 0;
}
static int qede_allmulticast_enable(struct rte_eth_dev *eth_dev)
{
enum qed_filter_rx_mode_type type =
QED_FILTER_RX_MODE_TYPE_MULTI_PROMISC;
enum _ecore_status_t ecore_status;
if (rte_eth_promiscuous_get(eth_dev->data->port_id) == 1)
type |= QED_FILTER_RX_MODE_TYPE_PROMISC;
ecore_status = qed_configure_filter_rx_mode(eth_dev, type);
return ecore_status >= ECORE_SUCCESS ? 0 : -EAGAIN;
}
static int qede_allmulticast_disable(struct rte_eth_dev *eth_dev)
{
enum _ecore_status_t ecore_status;
if (rte_eth_promiscuous_get(eth_dev->data->port_id) == 1)
ecore_status = qed_configure_filter_rx_mode(eth_dev,
QED_FILTER_RX_MODE_TYPE_PROMISC);
else
ecore_status = qed_configure_filter_rx_mode(eth_dev,
QED_FILTER_RX_MODE_TYPE_REGULAR);
return ecore_status >= ECORE_SUCCESS ? 0 : -EAGAIN;
}
static int
qede_set_mc_addr_list(struct rte_eth_dev *eth_dev,
struct rte_ether_addr *mc_addrs,
uint32_t mc_addrs_num)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
uint8_t i;
if (mc_addrs_num > ECORE_MAX_MC_ADDRS) {
DP_ERR(edev, "Reached max multicast filters limit,"
"Please enable multicast promisc mode\n");
return -ENOSPC;
}
for (i = 0; i < mc_addrs_num; i++) {
if (!rte_is_multicast_ether_addr(&mc_addrs[i])) {
DP_ERR(edev, "Not a valid multicast MAC\n");
return -EINVAL;
}
}
/* Flush all existing entries */
if (qede_del_mcast_filters(eth_dev))
return -1;
/* Set new mcast list */
return qede_add_mcast_filters(eth_dev, mc_addrs, mc_addrs_num);
}
/* Update MTU via vport-update without doing port restart.
* The vport must be deactivated before calling this API.
*/
int qede_update_mtu(struct rte_eth_dev *eth_dev, uint16_t mtu)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
struct ecore_hwfn *p_hwfn;
int rc;
int i;
if (IS_PF(edev)) {
struct ecore_sp_vport_update_params params;
memset(¶ms, 0, sizeof(struct ecore_sp_vport_update_params));
params.vport_id = 0;
params.mtu = mtu;
params.vport_id = 0;
for_each_hwfn(edev, i) {
p_hwfn = &edev->hwfns[i];
params.opaque_fid = p_hwfn->hw_info.opaque_fid;
rc = ecore_sp_vport_update(p_hwfn, ¶ms,
ECORE_SPQ_MODE_EBLOCK, NULL);
if (rc != ECORE_SUCCESS)
goto err;
}
} else {
for_each_hwfn(edev, i) {
p_hwfn = &edev->hwfns[i];
rc = ecore_vf_pf_update_mtu(p_hwfn, mtu);
if (rc == ECORE_INVAL) {
DP_INFO(edev, "VF MTU Update TLV not supported\n");
/* Recreate vport */
rc = qede_start_vport(qdev, mtu);
if (rc != ECORE_SUCCESS)
goto err;
/* Restore config lost due to vport stop */
if (eth_dev->data->promiscuous)
qede_promiscuous_enable(eth_dev);
else
qede_promiscuous_disable(eth_dev);
if (eth_dev->data->all_multicast)
qede_allmulticast_enable(eth_dev);
else
qede_allmulticast_disable(eth_dev);
qede_vlan_offload_set(eth_dev,
qdev->vlan_offload_mask);
} else if (rc != ECORE_SUCCESS) {
goto err;
}
}
}
DP_INFO(edev, "%s MTU updated to %u\n", IS_PF(edev) ? "PF" : "VF", mtu);
return 0;
err:
DP_ERR(edev, "Failed to update MTU\n");
return -1;
}
static int qede_flow_ctrl_set(struct rte_eth_dev *eth_dev,
struct rte_eth_fc_conf *fc_conf)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
struct qed_link_output current_link;
struct qed_link_params params;
memset(¤t_link, 0, sizeof(current_link));
qdev->ops->common->get_link(edev, ¤t_link);
memset(¶ms, 0, sizeof(params));
params.override_flags |= QED_LINK_OVERRIDE_PAUSE_CONFIG;
if (fc_conf->autoneg) {
if (!(current_link.supported_caps & QEDE_SUPPORTED_AUTONEG)) {
DP_ERR(edev, "Autoneg not supported\n");
return -EINVAL;
}
params.pause_config |= QED_LINK_PAUSE_AUTONEG_ENABLE;
}
/* Pause is assumed to be supported (SUPPORTED_Pause) */
if (fc_conf->mode == RTE_FC_FULL)
params.pause_config |= (QED_LINK_PAUSE_TX_ENABLE |
QED_LINK_PAUSE_RX_ENABLE);
if (fc_conf->mode == RTE_FC_TX_PAUSE)
params.pause_config |= QED_LINK_PAUSE_TX_ENABLE;
if (fc_conf->mode == RTE_FC_RX_PAUSE)
params.pause_config |= QED_LINK_PAUSE_RX_ENABLE;
params.link_up = true;
(void)qdev->ops->common->set_link(edev, ¶ms);
return 0;
}
static int qede_flow_ctrl_get(struct rte_eth_dev *eth_dev,
struct rte_eth_fc_conf *fc_conf)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
struct qed_link_output current_link;
memset(¤t_link, 0, sizeof(current_link));
qdev->ops->common->get_link(edev, ¤t_link);
if (current_link.pause_config & QED_LINK_PAUSE_AUTONEG_ENABLE)
fc_conf->autoneg = true;
if (current_link.pause_config & (QED_LINK_PAUSE_RX_ENABLE |
QED_LINK_PAUSE_TX_ENABLE))
fc_conf->mode = RTE_FC_FULL;
else if (current_link.pause_config & QED_LINK_PAUSE_RX_ENABLE)
fc_conf->mode = RTE_FC_RX_PAUSE;
else if (current_link.pause_config & QED_LINK_PAUSE_TX_ENABLE)
fc_conf->mode = RTE_FC_TX_PAUSE;
else
fc_conf->mode = RTE_FC_NONE;
return 0;
}
static const uint32_t *
qede_dev_supported_ptypes_get(struct rte_eth_dev *eth_dev)
{
static const uint32_t ptypes[] = {
RTE_PTYPE_L2_ETHER,
RTE_PTYPE_L2_ETHER_VLAN,
RTE_PTYPE_L3_IPV4,
RTE_PTYPE_L3_IPV6,
RTE_PTYPE_L4_TCP,
RTE_PTYPE_L4_UDP,
RTE_PTYPE_TUNNEL_VXLAN,
RTE_PTYPE_L4_FRAG,
RTE_PTYPE_TUNNEL_GENEVE,
RTE_PTYPE_TUNNEL_GRE,
/* Inner */
RTE_PTYPE_INNER_L2_ETHER,
RTE_PTYPE_INNER_L2_ETHER_VLAN,
RTE_PTYPE_INNER_L3_IPV4,
RTE_PTYPE_INNER_L3_IPV6,
RTE_PTYPE_INNER_L4_TCP,
RTE_PTYPE_INNER_L4_UDP,
RTE_PTYPE_INNER_L4_FRAG,
RTE_PTYPE_UNKNOWN
};
if (eth_dev->rx_pkt_burst == qede_recv_pkts ||
eth_dev->rx_pkt_burst == qede_recv_pkts_regular ||
eth_dev->rx_pkt_burst == qede_recv_pkts_cmt)
return ptypes;
return NULL;
}
static void qede_init_rss_caps(uint8_t *rss_caps, uint64_t hf)
{
*rss_caps = 0;
*rss_caps |= (hf & ETH_RSS_IPV4) ? ECORE_RSS_IPV4 : 0;
*rss_caps |= (hf & ETH_RSS_IPV6) ? ECORE_RSS_IPV6 : 0;
*rss_caps |= (hf & ETH_RSS_IPV6_EX) ? ECORE_RSS_IPV6 : 0;
*rss_caps |= (hf & ETH_RSS_NONFRAG_IPV4_TCP) ? ECORE_RSS_IPV4_TCP : 0;
*rss_caps |= (hf & ETH_RSS_NONFRAG_IPV6_TCP) ? ECORE_RSS_IPV6_TCP : 0;
*rss_caps |= (hf & ETH_RSS_IPV6_TCP_EX) ? ECORE_RSS_IPV6_TCP : 0;
*rss_caps |= (hf & ETH_RSS_NONFRAG_IPV4_UDP) ? ECORE_RSS_IPV4_UDP : 0;
*rss_caps |= (hf & ETH_RSS_NONFRAG_IPV6_UDP) ? ECORE_RSS_IPV6_UDP : 0;
}
int qede_rss_hash_update(struct rte_eth_dev *eth_dev,
struct rte_eth_rss_conf *rss_conf)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
struct ecore_sp_vport_update_params vport_update_params;
struct ecore_rss_params rss_params;
struct ecore_hwfn *p_hwfn;
uint32_t *key = (uint32_t *)rss_conf->rss_key;
uint64_t hf = rss_conf->rss_hf;
uint8_t len = rss_conf->rss_key_len;
uint8_t idx, i, j, fpidx;
int rc;
memset(&vport_update_params, 0, sizeof(vport_update_params));
memset(&rss_params, 0, sizeof(rss_params));
DP_INFO(edev, "RSS hf = 0x%lx len = %u key = %p\n",
(unsigned long)hf, len, key);
if (hf != 0) {
/* Enabling RSS */
DP_INFO(edev, "Enabling rss\n");
/* RSS caps */
qede_init_rss_caps(&rss_params.rss_caps, hf);
rss_params.update_rss_capabilities = 1;
/* RSS hash key */
if (key) {
if (len > (ECORE_RSS_KEY_SIZE * sizeof(uint32_t))) {
DP_ERR(edev, "RSS key length exceeds limit\n");
return -EINVAL;
}
DP_INFO(edev, "Applying user supplied hash key\n");
rss_params.update_rss_key = 1;
memcpy(&rss_params.rss_key, key, len);
}
rss_params.rss_enable = 1;
}
rss_params.update_rss_config = 1;
/* tbl_size has to be set with capabilities */
rss_params.rss_table_size_log = 7;
vport_update_params.vport_id = 0;
for_each_hwfn(edev, i) {
/* pass the L2 handles instead of qids */
for (j = 0 ; j < ECORE_RSS_IND_TABLE_SIZE ; j++) {
idx = j % QEDE_RSS_COUNT(eth_dev);
fpidx = idx * edev->num_hwfns + i;
rss_params.rss_ind_table[j] =
qdev->fp_array[fpidx].rxq->handle;
}
vport_update_params.rss_params = &rss_params;
p_hwfn = &edev->hwfns[i];
vport_update_params.opaque_fid = p_hwfn->hw_info.opaque_fid;
rc = ecore_sp_vport_update(p_hwfn, &vport_update_params,
ECORE_SPQ_MODE_EBLOCK, NULL);
if (rc) {
DP_ERR(edev, "vport-update for RSS failed\n");
return rc;
}
}
qdev->rss_enable = rss_params.rss_enable;
/* Update local structure for hash query */
qdev->rss_conf.rss_hf = hf;
qdev->rss_conf.rss_key_len = len;
if (qdev->rss_enable) {
if (qdev->rss_conf.rss_key == NULL) {
qdev->rss_conf.rss_key = (uint8_t *)malloc(len);
if (qdev->rss_conf.rss_key == NULL) {
DP_ERR(edev, "No memory to store RSS key\n");
return -ENOMEM;
}
}
if (key && len) {
DP_INFO(edev, "Storing RSS key\n");
memcpy(qdev->rss_conf.rss_key, key, len);
}
} else if (!qdev->rss_enable && len == 0) {
if (qdev->rss_conf.rss_key) {
free(qdev->rss_conf.rss_key);
qdev->rss_conf.rss_key = NULL;
DP_INFO(edev, "Free RSS key\n");
}
}
return 0;
}
static int qede_rss_hash_conf_get(struct rte_eth_dev *eth_dev,
struct rte_eth_rss_conf *rss_conf)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
rss_conf->rss_hf = qdev->rss_conf.rss_hf;
rss_conf->rss_key_len = qdev->rss_conf.rss_key_len;
if (rss_conf->rss_key && qdev->rss_conf.rss_key)
memcpy(rss_conf->rss_key, qdev->rss_conf.rss_key,
rss_conf->rss_key_len);
return 0;
}
int qede_rss_reta_update(struct rte_eth_dev *eth_dev,
struct rte_eth_rss_reta_entry64 *reta_conf,
uint16_t reta_size)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(eth_dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
struct ecore_sp_vport_update_params vport_update_params;
struct ecore_rss_params *params;
uint16_t i, j, idx, fid, shift;
struct ecore_hwfn *p_hwfn;
uint8_t entry;
int rc = 0;
if (reta_size > ETH_RSS_RETA_SIZE_128) {
DP_ERR(edev, "reta_size %d is not supported by hardware\n",
reta_size);
return -EINVAL;
}
memset(&vport_update_params, 0, sizeof(vport_update_params));
params = rte_zmalloc("qede_rss", sizeof(*params), RTE_CACHE_LINE_SIZE);
if (params == NULL) {
DP_ERR(edev, "failed to allocate memory\n");
return -ENOMEM;
}
params->update_rss_ind_table = 1;
params->rss_table_size_log = 7;
params->update_rss_config = 1;
vport_update_params.vport_id = 0;
/* Use the current value of rss_enable */
params->rss_enable = qdev->rss_enable;
vport_update_params.rss_params = params;
for_each_hwfn(edev, i) {
for (j = 0; j < reta_size; j++) {
idx = j / RTE_RETA_GROUP_SIZE;
shift = j % RTE_RETA_GROUP_SIZE;
if (reta_conf[idx].mask & (1ULL << shift)) {
entry = reta_conf[idx].reta[shift];
fid = entry * edev->num_hwfns + i;
/* Pass rxq handles to ecore */
params->rss_ind_table[j] =
qdev->fp_array[fid].rxq->handle;
/* Update the local copy for RETA query cmd */
qdev->rss_ind_table[j] = entry;
}
}
p_hwfn = &edev->hwfns[i];
vport_update_params.opaque_fid = p_hwfn->hw_info.opaque_fid;
rc = ecore_sp_vport_update(p_hwfn, &vport_update_params,
ECORE_SPQ_MODE_EBLOCK, NULL);
if (rc) {
DP_ERR(edev, "vport-update for RSS failed\n");
goto out;
}
}
out:
rte_free(params);
return rc;
}
static int qede_rss_reta_query(struct rte_eth_dev *eth_dev,
struct rte_eth_rss_reta_entry64 *reta_conf,
uint16_t reta_size)
{
struct qede_dev *qdev = eth_dev->data->dev_private;
struct ecore_dev *edev = &qdev->edev;
uint16_t i, idx, shift;
uint8_t entry;
if (reta_size > ETH_RSS_RETA_SIZE_128) {
DP_ERR(edev, "reta_size %d is not supported\n",
reta_size);
return -EINVAL;
}
for (i = 0; i < reta_size; i++) {
idx = i / RTE_RETA_GROUP_SIZE;
shift = i % RTE_RETA_GROUP_SIZE;
if (reta_conf[idx].mask & (1ULL << shift)) {
entry = qdev->rss_ind_table[i];
reta_conf[idx].reta[shift] = entry;
}
}
return 0;
}
static int qede_set_mtu(struct rte_eth_dev *dev, uint16_t mtu)
{
struct qede_dev *qdev = QEDE_INIT_QDEV(dev);
struct ecore_dev *edev = QEDE_INIT_EDEV(qdev);
struct rte_eth_dev_info dev_info = {0};
struct qede_fastpath *fp;
uint32_t max_rx_pkt_len;
uint32_t frame_size;
uint16_t bufsz;
bool restart = false;
int i, rc;
PMD_INIT_FUNC_TRACE(edev);
rc = qede_dev_info_get(dev, &dev_info);
if (rc != 0) {
DP_ERR(edev, "Error during getting ethernet device info\n");
return rc;
}
max_rx_pkt_len = mtu + QEDE_MAX_ETHER_HDR_LEN;
frame_size = max_rx_pkt_len;
if (mtu < RTE_ETHER_MIN_MTU || frame_size > dev_info.max_rx_pktlen) {
DP_ERR(edev, "MTU %u out of range, %u is maximum allowable\n",
mtu, dev_info.max_rx_pktlen - RTE_ETHER_HDR_LEN -
QEDE_ETH_OVERHEAD);
return -EINVAL;
}
if (!dev->data->scattered_rx &&
frame_size > dev->data->min_rx_buf_size - RTE_PKTMBUF_HEADROOM) {
DP_INFO(edev, "MTU greater than minimum RX buffer size of %u\n",
dev->data->min_rx_buf_size);
return -EINVAL;
}
/* Temporarily replace I/O functions with dummy ones. It cannot
* be set to NULL because rte_eth_rx_burst() doesn't check for NULL.
*/
dev->rx_pkt_burst = qede_rxtx_pkts_dummy;
dev->tx_pkt_burst = qede_rxtx_pkts_dummy;
if (dev->data->dev_started) {
dev->data->dev_started = 0;
qede_dev_stop(dev);
restart = true;
}
rte_delay_ms(1000);
qdev->new_mtu = mtu;
/* Fix up RX buf size for all queues of the port */
for (i = 0; i < qdev->num_rx_queues; i++) {
fp = &qdev->fp_array[i];
if (fp->rxq != NULL) {
bufsz = (uint16_t)rte_pktmbuf_data_room_size(
fp->rxq->mb_pool) - RTE_PKTMBUF_HEADROOM;
/* cache align the mbuf size to simplfy rx_buf_size
* calculation
*/
bufsz = QEDE_FLOOR_TO_CACHE_LINE_SIZE(bufsz);
rc = qede_calc_rx_buf_size(dev, bufsz, frame_size);
if (rc < 0)
return rc;
fp->rxq->rx_buf_size = rc;
}
}
if (max_rx_pkt_len > RTE_ETHER_MAX_LEN)
dev->data->dev_conf.rxmode.offloads |= DEV_RX_OFFLOAD_JUMBO_FRAME;
else
dev->data->dev_conf.rxmode.offloads &= ~DEV_RX_OFFLOAD_JUMBO_FRAME;
if (!dev->data->dev_started && restart) {
qede_dev_start(dev);
dev->data->dev_started = 1;
}
/* update max frame size */
dev->data->dev_conf.rxmode.max_rx_pkt_len = max_rx_pkt_len;
/* Reassign back */
qede_assign_rxtx_handlers(dev);
if (ECORE_IS_CMT(edev)) {
dev->rx_pkt_burst = qede_recv_pkts_cmt;
dev->tx_pkt_burst = qede_xmit_pkts_cmt;
} else {
dev->rx_pkt_burst = qede_recv_pkts;
dev->tx_pkt_burst = qede_xmit_pkts;
}
return 0;
}
static int
qede_dev_reset(struct rte_eth_dev *dev)
{
int ret;
ret = qede_eth_dev_uninit(dev);
if (ret)
return ret;
return qede_eth_dev_init(dev);
}
static const struct eth_dev_ops qede_eth_dev_ops = {
.dev_configure = qede_dev_configure,
.dev_infos_get = qede_dev_info_get,
.rx_queue_setup = qede_rx_queue_setup,
.rx_queue_release = qede_rx_queue_release,
.rx_descriptor_status = qede_rx_descriptor_status,
.tx_queue_setup = qede_tx_queue_setup,
.tx_queue_release = qede_tx_queue_release,
.dev_start = qede_dev_start,
.dev_reset = qede_dev_reset,
.dev_set_link_up = qede_dev_set_link_up,
.dev_set_link_down = qede_dev_set_link_down,
.link_update = qede_link_update,
.promiscuous_enable = qede_promiscuous_enable,
.promiscuous_disable = qede_promiscuous_disable,
.allmulticast_enable = qede_allmulticast_enable,
.allmulticast_disable = qede_allmulticast_disable,
.set_mc_addr_list = qede_set_mc_addr_list,
.dev_stop = qede_dev_stop,
.dev_close = qede_dev_close,
.stats_get = qede_get_stats,
.stats_reset = qede_reset_stats,
.xstats_get = qede_get_xstats,
.xstats_reset = qede_reset_xstats,
.xstats_get_names = qede_get_xstats_names,
.mac_addr_add = qede_mac_addr_add,
.mac_addr_remove = qede_mac_addr_remove,
.mac_addr_set = qede_mac_addr_set,
.vlan_offload_set = qede_vlan_offload_set,
.vlan_filter_set = qede_vlan_filter_set,
.flow_ctrl_set = qede_flow_ctrl_set,
.flow_ctrl_get = qede_flow_ctrl_get,
.dev_supported_ptypes_get = qede_dev_supported_ptypes_get,
.rss_hash_update = qede_rss_hash_update,
.rss_hash_conf_get = qede_rss_hash_conf_get,
.reta_update = qede_rss_reta_update,
.reta_query = qede_rss_reta_query,
.mtu_set = qede_set_mtu,
.filter_ctrl = qede_dev_filter_ctrl,
.udp_tunnel_port_add = qede_udp_dst_port_add,
.udp_tunnel_port_del = qede_udp_dst_port_del,
};
static const struct eth_dev_ops qede_eth_vf_dev_ops = {
.dev_configure = qede_dev_configure,
.dev_infos_get = qede_dev_info_get,
.rx_queue_setup = qede_rx_queue_setup,
.rx_queue_release = qede_rx_queue_release,
.rx_descriptor_status = qede_rx_descriptor_status,
.tx_queue_setup = qede_tx_queue_setup,
.tx_queue_release = qede_tx_queue_release,
.dev_start = qede_dev_start,
.dev_reset = qede_dev_reset,
.dev_set_link_up = qede_dev_set_link_up,
.dev_set_link_down = qede_dev_set_link_down,
.link_update = qede_link_update,
.promiscuous_enable = qede_promiscuous_enable,
.promiscuous_disable = qede_promiscuous_disable,
.allmulticast_enable = qede_allmulticast_enable,
.allmulticast_disable = qede_allmulticast_disable,
.set_mc_addr_list = qede_set_mc_addr_list,
.dev_stop = qede_dev_stop,
.dev_close = qede_dev_close,
.stats_get = qede_get_stats,
.stats_reset = qede_reset_stats,
.xstats_get = qede_get_xstats,
.xstats_reset = qede_reset_xstats,
.xstats_get_names = qede_get_xstats_names,
.vlan_offload_set = qede_vlan_offload_set,
.vlan_filter_set = qede_vlan_filter_set,
.dev_supported_ptypes_get = qede_dev_supported_ptypes_get,
.rss_hash_update = qede_rss_hash_update,
.rss_hash_conf_get = qede_rss_hash_conf_get,
.reta_update = qede_rss_reta_update,
.reta_query = qede_rss_reta_query,
.mtu_set = qede_set_mtu,
.udp_tunnel_port_add = qede_udp_dst_port_add,
.udp_tunnel_port_del = qede_udp_dst_port_del,
.mac_addr_add = qede_mac_addr_add,
.mac_addr_remove = qede_mac_addr_remove,
.mac_addr_set = qede_mac_addr_set,
};
static void qede_update_pf_params(struct ecore_dev *edev)
{
struct ecore_pf_params pf_params;
memset(&pf_params, 0, sizeof(struct ecore_pf_params));
pf_params.eth_pf_params.num_cons = QEDE_PF_NUM_CONNS;
pf_params.eth_pf_params.num_arfs_filters = QEDE_RFS_MAX_FLTR;
qed_ops->common->update_pf_params(edev, &pf_params);
}
static int qede_common_dev_init(struct rte_eth_dev *eth_dev, bool is_vf)
{
struct rte_pci_device *pci_dev;
struct rte_pci_addr pci_addr;
struct qede_dev *adapter;
struct ecore_dev *edev;
struct qed_dev_eth_info dev_info;
struct qed_slowpath_params params;
static bool do_once = true;
uint8_t bulletin_change;
uint8_t vf_mac[RTE_ETHER_ADDR_LEN];
uint8_t is_mac_forced;
bool is_mac_exist;
/* Fix up ecore debug level */
uint32_t dp_module = ~0 & ~ECORE_MSG_HW;
uint8_t dp_level = ECORE_LEVEL_VERBOSE;
uint32_t int_mode;
int rc;
/* Extract key data structures */
adapter = eth_dev->data->dev_private;
adapter->ethdev = eth_dev;
edev = &adapter->edev;
pci_dev = RTE_ETH_DEV_TO_PCI(eth_dev);
pci_addr = pci_dev->addr;
PMD_INIT_FUNC_TRACE(edev);
snprintf(edev->name, NAME_SIZE, PCI_SHORT_PRI_FMT ":dpdk-port-%u",
pci_addr.bus, pci_addr.devid, pci_addr.function,
eth_dev->data->port_id);
if (rte_eal_process_type() != RTE_PROC_PRIMARY) {
DP_ERR(edev, "Skipping device init from secondary process\n");
return 0;
}
rte_eth_copy_pci_info(eth_dev, pci_dev);
/* @DPDK */
edev->vendor_id = pci_dev->id.vendor_id;
edev->device_id = pci_dev->id.device_id;
qed_ops = qed_get_eth_ops();
if (!qed_ops) {
DP_ERR(edev, "Failed to get qed_eth_ops_pass\n");
rc = -EINVAL;
goto err;
}
DP_INFO(edev, "Starting qede probe\n");
rc = qed_ops->common->probe(edev, pci_dev, dp_module,
dp_level, is_vf);
if (rc != 0) {
DP_ERR(edev, "qede probe failed rc %d\n", rc);
rc = -ENODEV;
goto err;
}
qede_update_pf_params(edev);
switch (pci_dev->intr_handle.type) {
case RTE_INTR_HANDLE_UIO_INTX:
case RTE_INTR_HANDLE_VFIO_LEGACY:
int_mode = ECORE_INT_MODE_INTA;
rte_intr_callback_register(&pci_dev->intr_handle,
qede_interrupt_handler_intx,
(void *)eth_dev);
break;
default:
int_mode = ECORE_INT_MODE_MSIX;
rte_intr_callback_register(&pci_dev->intr_handle,
qede_interrupt_handler,
(void *)eth_dev);
}
if (rte_intr_enable(&pci_dev->intr_handle)) {
DP_ERR(edev, "rte_intr_enable() failed\n");
rc = -ENODEV;
goto err;
}
/* Start the Slowpath-process */
memset(¶ms, 0, sizeof(struct qed_slowpath_params));
params.int_mode = int_mode;
params.drv_major = QEDE_PMD_VERSION_MAJOR;
params.drv_minor = QEDE_PMD_VERSION_MINOR;
params.drv_rev = QEDE_PMD_VERSION_REVISION;
params.drv_eng = QEDE_PMD_VERSION_PATCH;
strncpy((char *)params.name, QEDE_PMD_VER_PREFIX,
QEDE_PMD_DRV_VER_STR_SIZE);
qede_assign_rxtx_handlers(eth_dev);
eth_dev->tx_pkt_prepare = qede_xmit_prep_pkts;
/* For CMT mode device do periodic polling for slowpath events.
* This is required since uio device uses only one MSI-x
* interrupt vector but we need one for each engine.
*/
if (ECORE_IS_CMT(edev) && IS_PF(edev)) {
rc = rte_eal_alarm_set(QEDE_SP_TIMER_PERIOD,
qede_poll_sp_sb_cb,
(void *)eth_dev);
if (rc != 0) {
DP_ERR(edev, "Unable to start periodic"
" timer rc %d\n", rc);
rc = -EINVAL;
goto err;
}
}
rc = qed_ops->common->slowpath_start(edev, ¶ms);
if (rc) {
DP_ERR(edev, "Cannot start slowpath rc = %d\n", rc);
rte_eal_alarm_cancel(qede_poll_sp_sb_cb,
(void *)eth_dev);
rc = -ENODEV;
goto err;
}
rc = qed_ops->fill_dev_info(edev, &dev_info);
if (rc) {
DP_ERR(edev, "Cannot get device_info rc %d\n", rc);
qed_ops->common->slowpath_stop(edev);
qed_ops->common->remove(edev);
rte_eal_alarm_cancel(qede_poll_sp_sb_cb,
(void *)eth_dev);
rc = -ENODEV;
goto err;
}
qede_alloc_etherdev(adapter, &dev_info);
if (do_once) {
qede_print_adapter_info(adapter);
do_once = false;
}
adapter->ops->common->set_name(edev, edev->name);
if (!is_vf)
adapter->dev_info.num_mac_filters =
(uint32_t)RESC_NUM(ECORE_LEADING_HWFN(edev),
ECORE_MAC);
else
ecore_vf_get_num_mac_filters(ECORE_LEADING_HWFN(edev),
(uint32_t *)&adapter->dev_info.num_mac_filters);
/* Allocate memory for storing MAC addr */
eth_dev->data->mac_addrs = rte_zmalloc(edev->name,
(RTE_ETHER_ADDR_LEN *
adapter->dev_info.num_mac_filters),
RTE_CACHE_LINE_SIZE);
if (eth_dev->data->mac_addrs == NULL) {
DP_ERR(edev, "Failed to allocate MAC address\n");
qed_ops->common->slowpath_stop(edev);
qed_ops->common->remove(edev);
rte_eal_alarm_cancel(qede_poll_sp_sb_cb,
(void *)eth_dev);
return -ENOMEM;
}
if (!is_vf) {
rte_ether_addr_copy((struct rte_ether_addr *)edev->hwfns[0].
hw_info.hw_mac_addr,
ð_dev->data->mac_addrs[0]);
rte_ether_addr_copy(ð_dev->data->mac_addrs[0],
&adapter->primary_mac);
} else {
ecore_vf_read_bulletin(ECORE_LEADING_HWFN(edev),
&bulletin_change);
if (bulletin_change) {
is_mac_exist =
ecore_vf_bulletin_get_forced_mac(
ECORE_LEADING_HWFN(edev),
vf_mac,
&is_mac_forced);
if (is_mac_exist) {
DP_INFO(edev, "VF macaddr received from PF\n");
rte_ether_addr_copy(
(struct rte_ether_addr *)&vf_mac,
ð_dev->data->mac_addrs[0]);
rte_ether_addr_copy(
ð_dev->data->mac_addrs[0],
&adapter->primary_mac);
} else {
DP_ERR(edev, "No VF macaddr assigned\n");
}
}
}
eth_dev->dev_ops = (is_vf) ? &qede_eth_vf_dev_ops : &qede_eth_dev_ops;
/* Bring-up the link */
qede_dev_set_link_state(eth_dev, true);
adapter->num_tx_queues = 0;
adapter->num_rx_queues = 0;
SLIST_INIT(&adapter->arfs_info.arfs_list_head);
SLIST_INIT(&adapter->vlan_list_head);
SLIST_INIT(&adapter->uc_list_head);
SLIST_INIT(&adapter->mc_list_head);
adapter->mtu = RTE_ETHER_MTU;
adapter->vport_started = false;
/* VF tunnel offloads is enabled by default in PF driver */
adapter->vxlan.num_filters = 0;
adapter->geneve.num_filters = 0;
adapter->ipgre.num_filters = 0;
if (is_vf) {
adapter->vxlan.enable = true;
adapter->vxlan.filter_type = ETH_TUNNEL_FILTER_IMAC |
ETH_TUNNEL_FILTER_IVLAN;
adapter->vxlan.udp_port = QEDE_VXLAN_DEF_PORT;
adapter->geneve.enable = true;
adapter->geneve.filter_type = ETH_TUNNEL_FILTER_IMAC |
ETH_TUNNEL_FILTER_IVLAN;
adapter->geneve.udp_port = QEDE_GENEVE_DEF_PORT;
adapter->ipgre.enable = true;
adapter->ipgre.filter_type = ETH_TUNNEL_FILTER_IMAC |
ETH_TUNNEL_FILTER_IVLAN;
} else {
adapter->vxlan.enable = false;
adapter->geneve.enable = false;
adapter->ipgre.enable = false;
}
DP_INFO(edev, "MAC address : %02x:%02x:%02x:%02x:%02x:%02x\n",
adapter->primary_mac.addr_bytes[0],
adapter->primary_mac.addr_bytes[1],
adapter->primary_mac.addr_bytes[2],
adapter->primary_mac.addr_bytes[3],
adapter->primary_mac.addr_bytes[4],
adapter->primary_mac.addr_bytes[5]);
DP_INFO(edev, "Device initialized\n");
return 0;
err:
if (do_once) {
qede_print_adapter_info(adapter);
do_once = false;
}
return rc;
}
static int qedevf_eth_dev_init(struct rte_eth_dev *eth_dev)
{
return qede_common_dev_init(eth_dev, 1);
}
static int qede_eth_dev_init(struct rte_eth_dev *eth_dev)
{
return qede_common_dev_init(eth_dev, 0);
}
static int qede_dev_common_uninit(struct rte_eth_dev *eth_dev)
{
struct qede_dev *qdev = eth_dev->data->dev_private;
struct ecore_dev *edev = &qdev->edev;
PMD_INIT_FUNC_TRACE(edev);
/* only uninitialize in the primary process */
if (rte_eal_process_type() != RTE_PROC_PRIMARY)
return 0;
/* safe to close dev here */
qede_dev_close(eth_dev);
eth_dev->dev_ops = NULL;
eth_dev->rx_pkt_burst = NULL;
eth_dev->tx_pkt_burst = NULL;
return 0;
}
static int qede_eth_dev_uninit(struct rte_eth_dev *eth_dev)
{
return qede_dev_common_uninit(eth_dev);
}
static int qedevf_eth_dev_uninit(struct rte_eth_dev *eth_dev)
{
return qede_dev_common_uninit(eth_dev);
}
static const struct rte_pci_id pci_id_qedevf_map[] = {
#define QEDEVF_RTE_PCI_DEVICE(dev) RTE_PCI_DEVICE(PCI_VENDOR_ID_QLOGIC, dev)
{
QEDEVF_RTE_PCI_DEVICE(PCI_DEVICE_ID_QLOGIC_NX2_VF)
},
{
QEDEVF_RTE_PCI_DEVICE(PCI_DEVICE_ID_QLOGIC_57980S_IOV)
},
{
QEDEVF_RTE_PCI_DEVICE(PCI_DEVICE_ID_QLOGIC_AH_IOV)
},
{.vendor_id = 0,}
};
static const struct rte_pci_id pci_id_qede_map[] = {
#define QEDE_RTE_PCI_DEVICE(dev) RTE_PCI_DEVICE(PCI_VENDOR_ID_QLOGIC, dev)
{
QEDE_RTE_PCI_DEVICE(PCI_DEVICE_ID_QLOGIC_NX2_57980E)
},
{
QEDE_RTE_PCI_DEVICE(PCI_DEVICE_ID_QLOGIC_NX2_57980S)
},
{
QEDE_RTE_PCI_DEVICE(PCI_DEVICE_ID_QLOGIC_57980S_40)
},
{
QEDE_RTE_PCI_DEVICE(PCI_DEVICE_ID_QLOGIC_57980S_25)
},
{
QEDE_RTE_PCI_DEVICE(PCI_DEVICE_ID_QLOGIC_57980S_100)
},
{
QEDE_RTE_PCI_DEVICE(PCI_DEVICE_ID_QLOGIC_57980S_50)
},
{
QEDE_RTE_PCI_DEVICE(PCI_DEVICE_ID_QLOGIC_AH_50G)
},
{
QEDE_RTE_PCI_DEVICE(PCI_DEVICE_ID_QLOGIC_AH_10G)
},
{
QEDE_RTE_PCI_DEVICE(PCI_DEVICE_ID_QLOGIC_AH_40G)
},
{
QEDE_RTE_PCI_DEVICE(PCI_DEVICE_ID_QLOGIC_AH_25G)
},
{.vendor_id = 0,}
};
static int qedevf_eth_dev_pci_probe(struct rte_pci_driver *pci_drv __rte_unused,
struct rte_pci_device *pci_dev)
{
return rte_eth_dev_pci_generic_probe(pci_dev,
sizeof(struct qede_dev), qedevf_eth_dev_init);
}
static int qedevf_eth_dev_pci_remove(struct rte_pci_device *pci_dev)
{
return rte_eth_dev_pci_generic_remove(pci_dev, qedevf_eth_dev_uninit);
}
static struct rte_pci_driver rte_qedevf_pmd = {
.id_table = pci_id_qedevf_map,
.drv_flags = RTE_PCI_DRV_NEED_MAPPING | RTE_PCI_DRV_INTR_LSC,
.probe = qedevf_eth_dev_pci_probe,
.remove = qedevf_eth_dev_pci_remove,
};
static int qede_eth_dev_pci_probe(struct rte_pci_driver *pci_drv __rte_unused,
struct rte_pci_device *pci_dev)
{
return rte_eth_dev_pci_generic_probe(pci_dev,
sizeof(struct qede_dev), qede_eth_dev_init);
}
static int qede_eth_dev_pci_remove(struct rte_pci_device *pci_dev)
{
return rte_eth_dev_pci_generic_remove(pci_dev, qede_eth_dev_uninit);
}
static struct rte_pci_driver rte_qede_pmd = {
.id_table = pci_id_qede_map,
.drv_flags = RTE_PCI_DRV_NEED_MAPPING | RTE_PCI_DRV_INTR_LSC,
.probe = qede_eth_dev_pci_probe,
.remove = qede_eth_dev_pci_remove,
};
RTE_PMD_REGISTER_PCI(net_qede, rte_qede_pmd);
RTE_PMD_REGISTER_PCI_TABLE(net_qede, pci_id_qede_map);
RTE_PMD_REGISTER_KMOD_DEP(net_qede, "* igb_uio | uio_pci_generic | vfio-pci");
RTE_PMD_REGISTER_PCI(net_qede_vf, rte_qedevf_pmd);
RTE_PMD_REGISTER_PCI_TABLE(net_qede_vf, pci_id_qedevf_map);
RTE_PMD_REGISTER_KMOD_DEP(net_qede_vf, "* igb_uio | vfio-pci");
RTE_INIT(qede_init_log)
{
qede_logtype_init = rte_log_register("pmd.net.qede.init");
if (qede_logtype_init >= 0)
rte_log_set_level(qede_logtype_init, RTE_LOG_NOTICE);
qede_logtype_driver = rte_log_register("pmd.net.qede.driver");
if (qede_logtype_driver >= 0)
rte_log_set_level(qede_logtype_driver, RTE_LOG_NOTICE);
}
|
grivet/dpdk
|
drivers/net/qede/qede_ethdev.c
|
C
|
gpl-2.0
| 82,085
|
<?php
/**
* @package WordPress
* @subpackage Industrial
* @since Industrial 1.0
*
* Blog Page Full Width Video Post Format Template
* Created by CMSMasters
*
*/
$cmsms_post_video_type = get_post_meta(get_the_ID(), 'cmsms_post_video_type', true);
$cmsms_post_video_link = get_post_meta(get_the_ID(), 'cmsms_post_video_link', true);
$cmsms_post_video_links = get_post_meta(get_the_ID(), 'cmsms_post_video_links', true);
?>
<!--_________________________ Start Video Article _________________________ -->
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="cmsms_info">
<span class="cmsms_post_format_img"></span>
<div class="cmsms_like"><?php cmsmsLike(); ?></div>
</div>
<div class="ovh">
<header class="entry-header">
<?php cmsms_heading(get_the_ID()); ?>
<div class="cmsms_post_info">
<?php
cmsms_post_date();
if (!post_password_required()) {
cmsms_comments();
}
cmsms_meta();
?>
</div>
<?php
if (!post_password_required()) {
if ($cmsms_post_video_type == 'selfhosted' && !empty($cmsms_post_video_links) && sizeof($cmsms_post_video_links) > 0) {
foreach ($cmsms_post_video_links as $cmsms_post_video_link_url) {
$video_link[$cmsms_post_video_link_url[0]] = $cmsms_post_video_link_url[1];
}
if (has_post_thumbnail()) {
$poster = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()), 'full-thumb');
$video_link['poster'] = $poster[0];
}
echo '<div class="cmsms_blog_media">' . "\n" .
cmsmastersSingleVideoPlayer($video_link) . "\r\t\t" .
'</div>' . "\r\t\t";
} elseif ($cmsms_post_video_type == 'embedded' && $cmsms_post_video_link != '') {
echo '<div class="cmsms_blog_media">' . "\n\t\t\t" .
'<div class="resizable_block">' . "\n\t\t\t\t" .
get_video_iframe($cmsms_post_video_link) . "\r\t\t\t" .
'</div>' . "\r\t\t" .
'</div>' . "\r\t\t";
}
}
?>
</header>
<footer class="entry-meta">
<?php
cmsms_exc_cont();
cmsms_more(get_the_ID());
cmsms_tags(get_the_ID(), 'post', 'page');
?>
</footer>
</div>
</article>
<!--_________________________ Finish Video Article _________________________ -->
|
gx761/jhm
|
wp-content/themes/industrial/framework/postType/blog/page/fullwidth/video.php
|
PHP
|
gpl-2.0
| 2,299
|
/* Copyright (c) 2010-2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/delay.h>
#include <linux/debugfs.h>
#include <linux/mfd/pmic8058.h>
#include <linux/mfd/pmic8901.h>
#include <linux/mfd/msm-adie-codec.h>
#include <linux/regulator/consumer.h>
#include <linux/regulator/machine.h>
#include <mach/qdsp6v2/audio_dev_ctl.h>
#include <sound/apr_audio.h>
#include <asm/mach-types.h>
#include <asm/uaccess.h>
#include <mach/board-msm8660.h>
#include "snddev_icodec.h"
#include "snddev_ecodec.h"
#include "timpani_profile_8x60.h"
#include "snddev_hdmi.h"
#include "snddev_mi2s.h"
#include "snddev_virtual.h"
#ifdef CONFIG_SKY_SND_EXTAMP //N1066 20120410 Sound Patch
#include <linux/i2c-gpio.h> /* elecjang 20110421 for max97001 subsystem */
#include "sky_snd_ext_amp_max97001.h"
#endif
#ifdef CONFIG_DEBUG_FS
static struct dentry *debugfs_hsed_config;
static void snddev_hsed_config_modify_setting(int type);
static void snddev_hsed_config_restore_setting(void);
#endif
/* GPIO_CLASS_D0_EN */
#define SNDDEV_GPIO_CLASS_D0_EN 227
/* GPIO_CLASS_D1_EN */
#define SNDDEV_GPIO_CLASS_D1_EN 229
#define SNDDEV_GPIO_MIC2_ANCR_SEL 294
#define SNDDEV_GPIO_MIC1_ANCL_SEL 295
#define SNDDEV_GPIO_HS_MIC4_SEL 296
#define DSP_RAM_BASE_8x60 0x46700000
#define DSP_RAM_SIZE_8x60 0x2000000
static int dspcrashd_pdata_8x60 = 0xDEADDEAD;
static struct resource resources_dspcrashd_8x60[] = {
{
.name = "msm_dspcrashd",
.start = DSP_RAM_BASE_8x60,
.end = DSP_RAM_BASE_8x60 + DSP_RAM_SIZE_8x60,
.flags = IORESOURCE_DMA,
},
};
struct platform_device msm_device_dspcrashd_8x60 = {
.name = "msm_dspcrashd",
.num_resources = ARRAY_SIZE(resources_dspcrashd_8x60),
.resource = resources_dspcrashd_8x60,
.dev = { .platform_data = &dspcrashd_pdata_8x60 },
};
static struct resource msm_cdcclk_ctl_resources[] = {
{
.name = "msm_snddev_tx_mclk",
.start = 108,
.end = 108,
.flags = IORESOURCE_IO,
},
{
.name = "msm_snddev_rx_mclk",
.start = 109,
.end = 109,
.flags = IORESOURCE_IO,
},
};
static struct platform_device msm_cdcclk_ctl_device = {
.name = "msm_cdcclk_ctl",
.num_resources = ARRAY_SIZE(msm_cdcclk_ctl_resources),
.resource = msm_cdcclk_ctl_resources,
};
static struct resource msm_aux_pcm_resources[] = {
{
.name = "aux_pcm_dout",
.start = 111,
.end = 111,
.flags = IORESOURCE_IO,
},
{
.name = "aux_pcm_din",
.start = 112,
.end = 112,
.flags = IORESOURCE_IO,
},
{
.name = "aux_pcm_syncout",
.start = 113,
.end = 113,
.flags = IORESOURCE_IO,
},
{
.name = "aux_pcm_clkin_a",
.start = 114,
.end = 114,
.flags = IORESOURCE_IO,
},
};
static struct platform_device msm_aux_pcm_device = {
.name = "msm_aux_pcm",
.num_resources = ARRAY_SIZE(msm_aux_pcm_resources),
.resource = msm_aux_pcm_resources,
};
static struct resource msm_mi2s_gpio_resources[] = {
{
.name = "mi2s_ws",
.start = 101,
.end = 101,
.flags = IORESOURCE_IO,
},
{
.name = "mi2s_sclk",
.start = 102,
.end = 102,
.flags = IORESOURCE_IO,
},
{
.name = "mi2s_mclk",
.start = 103,
.end = 103,
.flags = IORESOURCE_IO,
},
{
.name = "fm_mi2s_sd",
.start = 107,
.end = 107,
.flags = IORESOURCE_IO,
},
};
static struct platform_device msm_mi2s_device = {
.name = "msm_mi2s",
.num_resources = ARRAY_SIZE(msm_mi2s_gpio_resources),
.resource = msm_mi2s_gpio_resources,
};
/* Must be same size as msm_icodec_gpio_resources */
static int msm_icodec_gpio_defaults[] = {
0,
0,
};
static struct resource msm_icodec_gpio_resources[] = {
{
.name = "msm_icodec_speaker_left",
.start = SNDDEV_GPIO_CLASS_D0_EN,
.end = SNDDEV_GPIO_CLASS_D0_EN,
.flags = IORESOURCE_IO,
},
{
.name = "msm_icodec_speaker_right",
.start = SNDDEV_GPIO_CLASS_D1_EN,
.end = SNDDEV_GPIO_CLASS_D1_EN,
.flags = IORESOURCE_IO,
},
};
static struct platform_device msm_icodec_gpio_device = {
.name = "msm_icodec_gpio",
.num_resources = ARRAY_SIZE(msm_icodec_gpio_resources),
.resource = msm_icodec_gpio_resources,
.dev = { .platform_data = &msm_icodec_gpio_defaults },
};
static struct regulator *s3;
static struct regulator *mvs;
static int msm_snddev_enable_dmic_power(void)
{
int ret;
s3 = regulator_get(NULL, "8058_s3");
if (IS_ERR(s3)) {
ret = -EBUSY;
goto fail_get_s3;
}
ret = regulator_set_voltage(s3, 1800000, 1800000);
if (ret) {
pr_err("%s: error setting voltage\n", __func__);
goto fail_s3;
}
ret = regulator_enable(s3);
if (ret) {
pr_err("%s: error enabling regulator\n", __func__);
goto fail_s3;
}
mvs = regulator_get(NULL, "8901_mvs0");
if (IS_ERR(mvs))
goto fail_mvs0_get;
ret = regulator_enable(mvs);
if (ret) {
pr_err("%s: error setting regulator\n", __func__);
goto fail_mvs0_enable;
}
return ret;
fail_mvs0_enable:
regulator_put(mvs);
mvs = NULL;
fail_mvs0_get:
regulator_disable(s3);
fail_s3:
regulator_put(s3);
s3 = NULL;
fail_get_s3:
return ret;
}
static void msm_snddev_disable_dmic_power(void)
{
int ret;
if (mvs) {
ret = regulator_disable(mvs);
if (ret < 0)
pr_err("%s: error disabling vreg mvs\n", __func__);
regulator_put(mvs);
mvs = NULL;
}
if (s3) {
ret = regulator_disable(s3);
if (ret < 0)
pr_err("%s: error disabling regulator s3\n", __func__);
regulator_put(s3);
s3 = NULL;
}
}
#define PM8901_MPP_3 (2) /* PM8901 MPP starts from 0 */
static int config_class_d0_gpio(int enable)
{
int rc;
struct pm8xxx_mpp_config_data class_d0_mpp = {
.type = PM8XXX_MPP_TYPE_D_OUTPUT,
.level = PM8901_MPP_DIG_LEVEL_MSMIO,
};
if (enable) {
class_d0_mpp.control = PM8XXX_MPP_DOUT_CTRL_HIGH;
rc = pm8xxx_mpp_config(PM8901_MPP_PM_TO_SYS(PM8901_MPP_3),
&class_d0_mpp);
if (rc) {
pr_err("%s: CLASS_D0_EN failed\n", __func__);
return rc;
}
rc = gpio_request(SNDDEV_GPIO_CLASS_D0_EN, "CLASSD0_EN");
if (rc) {
pr_err("%s: spkr pamp gpio pm8901 mpp3 request"
"failed\n", __func__);
class_d0_mpp.control = PM8XXX_MPP_DOUT_CTRL_LOW;
pm8xxx_mpp_config(PM8901_MPP_PM_TO_SYS(PM8901_MPP_3),
&class_d0_mpp);
return rc;
}
gpio_direction_output(SNDDEV_GPIO_CLASS_D0_EN, 1);
gpio_set_value_cansleep(SNDDEV_GPIO_CLASS_D0_EN, 1);
} else {
class_d0_mpp.control = PM8XXX_MPP_DOUT_CTRL_LOW;
pm8xxx_mpp_config(PM8901_MPP_PM_TO_SYS(PM8901_MPP_3),
&class_d0_mpp);
gpio_set_value_cansleep(SNDDEV_GPIO_CLASS_D0_EN, 0);
gpio_free(SNDDEV_GPIO_CLASS_D0_EN);
}
return 0;
}
static int config_class_d1_gpio(int enable)
{
int rc;
if (enable) {
rc = gpio_request(SNDDEV_GPIO_CLASS_D1_EN, "CLASSD1_EN");
if (rc) {
pr_err("%s: Right Channel spkr gpio request"
" failed\n", __func__);
return rc;
}
gpio_direction_output(SNDDEV_GPIO_CLASS_D1_EN, 1);
gpio_set_value_cansleep(SNDDEV_GPIO_CLASS_D1_EN, 1);
} else {
gpio_set_value_cansleep(SNDDEV_GPIO_CLASS_D1_EN, 0);
gpio_free(SNDDEV_GPIO_CLASS_D1_EN);
}
return 0;
}
static atomic_t pamp_ref_cnt;
static int msm_snddev_poweramp_on(void)
{
int rc;
if (atomic_inc_return(&pamp_ref_cnt) > 1)
return 0;
pr_debug("%s: enable stereo spkr amp\n", __func__);
rc = config_class_d0_gpio(1);
if (rc) {
pr_err("%s: d0 gpio configuration failed\n", __func__);
goto config_gpio_fail;
}
rc = config_class_d1_gpio(1);
if (rc) {
pr_err("%s: d1 gpio configuration failed\n", __func__);
goto config_gpio_fail;
}
config_gpio_fail:
return rc;
}
static void msm_snddev_poweramp_off(void)
{
if (atomic_dec_return(&pamp_ref_cnt) == 0) {
pr_debug("%s: disable stereo spkr amp\n", __func__);
config_class_d0_gpio(0);
config_class_d1_gpio(0);
msleep(30);
}
}
#ifdef CONFIG_SKY_SND_EXTAMP //N1066 20120410 Sound Patch /* elecjang 20110421 for max97001 subsystem */
#ifndef CONFIG_MACH_MSM8X60_PRESTO // jmlee
static int msm_snddev_poweramp_handset_on(void)
{
//pr_debug("%s: msm_snddev_poweramp_handset_on\n", __func__);
snd_extamp_api_SetDevice(1, SND_DEVICE_HANDSET_RX);
return 0;
}
static void msm_snddev_poweramp_handset_off(void)
{
//pr_debug("%s: msm_snddev_poweramp_handset_off\n", __func__);
snd_extamp_api_SetDevice(0, SND_DEVICE_HANDSET_RX);
}
#endif
static int msm_snddev_poweramp_speaker_on(void)
{
//pr_debug("%s: msm_snddev_poweramp_speaker_on\n", __func__);
snd_extamp_api_SetDevice(1, SND_DEVICE_SPEAKER_RX);
return 0;
}
static void msm_snddev_poweramp_speaker_off(void)
{
//pr_debug("%s: msm_snddev_poweramp_speaker_off\n", __func__);
snd_extamp_api_SetDevice(0, SND_DEVICE_SPEAKER_RX);
}
static int msm_snddev_poweramp_headset_on(void)
{
//pr_debug("%s: msm_snddev_poweramp_headset_on\n", __func__);
snd_extamp_api_SetDevice(1, SND_DEVICE_HEADSET_RX);
return 0;
}
static void msm_snddev_poweramp_headset_off(void)
{
//pr_debug("%s: msm_snddev_poweramp_headset_off\n", __func__);
snd_extamp_api_SetDevice(0, SND_DEVICE_HEADSET_RX);
}
static int msm_snddev_poweramp_headset_speaker_on(void)
{
//pr_debug("%s: msm_snddev_poweramp_headset_speaker_on\n", __func__);
snd_extamp_api_SetDevice(1, SND_DEVICE_SPEAKER_HEADSET_RX);
return 0;
}
static void msm_snddev_poweramp_headset_speaker_off(void)
{
//pr_debug("%s: msm_snddev_poweramp_headset_speaker_off\n", __func__);
snd_extamp_api_SetDevice(0, SND_DEVICE_SPEAKER_HEADSET_RX);
}
static int msm_snddev_poweramp_voip_headset_on(void)
{
//pr_debug("%s: msm_snddev_poweramp_voip_headset_on\n", __func__);
snd_extamp_api_SetDevice(1, SND_SKY_DEVICE_VOIP_HEADSET_RX);
return 0;
}
static void msm_snddev_poweramp_voip_headset_off(void)
{
//pr_debug("%s: msm_snddev_poweramp_voip_headset_off\n", __func__);
snd_extamp_api_SetDevice(0, SND_SKY_DEVICE_VOIP_HEADSET_RX);
}
static int msm_snddev_poweramp_vt_speaker_on(void) //N1066 20120607 GB UI Merge
{
//pr_debug("%s: msm_snddev_poweramp_speaker_on\n", __func__);
snd_extamp_api_SetDevice(1, SND_SKY_DEVICE_VT_SPEAKER_RX);
return 0;
}
static void msm_snddev_poweramp_vt_speaker_off(void)
{
//pr_debug("%s: msm_snddev_poweramp_speaker_off\n", __func__);
snd_extamp_api_SetDevice(0, SND_SKY_DEVICE_VT_SPEAKER_RX);
}
#endif
#ifndef CONFIG_SKY_SND_CTRL //N1066 20120410 Sound Patch
/* Regulator 8058_l10 supplies regulator 8058_ncp. */
static struct regulator *snddev_reg_ncp;
static struct regulator *snddev_reg_l10;
#endif
static atomic_t preg_ref_cnt;
static int msm_snddev_voltage_on(void)
{
#ifdef CONFIG_SKY_SND_CTRL //N1066 20120410 Sound Patch
return 0;
#else
int rc;
pr_debug("%s\n", __func__);
if (atomic_inc_return(&preg_ref_cnt) > 1)
return 0;
snddev_reg_l10 = regulator_get(NULL, "8058_l10");
if (IS_ERR(snddev_reg_l10)) {
pr_err("%s: regulator_get(%s) failed (%ld)\n", __func__,
"l10", PTR_ERR(snddev_reg_l10));
return -EBUSY;
}
rc = regulator_set_voltage(snddev_reg_l10, 2600000, 2600000);
if (rc < 0)
pr_err("%s: regulator_set_voltage(l10) failed (%d)\n",
__func__, rc);
rc = regulator_enable(snddev_reg_l10);
if (rc < 0)
pr_err("%s: regulator_enable(l10) failed (%d)\n", __func__, rc);
snddev_reg_ncp = regulator_get(NULL, "8058_ncp");
if (IS_ERR(snddev_reg_ncp)) {
pr_err("%s: regulator_get(%s) failed (%ld)\n", __func__,
"ncp", PTR_ERR(snddev_reg_ncp));
return -EBUSY;
}
rc = regulator_set_voltage(snddev_reg_ncp, 1800000, 1800000);
if (rc < 0) {
pr_err("%s: regulator_set_voltage(ncp) failed (%d)\n",
__func__, rc);
goto regulator_fail;
}
rc = regulator_enable(snddev_reg_ncp);
if (rc < 0) {
pr_err("%s: regulator_enable(ncp) failed (%d)\n", __func__, rc);
goto regulator_fail;
}
return rc;
regulator_fail:
regulator_put(snddev_reg_ncp);
snddev_reg_ncp = NULL;
return rc;
#endif /* CONFIG_SKY_SND_CTRL */
}
static void msm_snddev_voltage_off(void)
{
#ifndef CONFIG_SKY_SND_CTRL //N1066 20120410 Sound Patch
int rc;
pr_debug("%s\n", __func__);
if (!snddev_reg_ncp)
goto done;
if (atomic_dec_return(&preg_ref_cnt) == 0) {
rc = regulator_disable(snddev_reg_ncp);
if (rc < 0)
pr_err("%s: regulator_disable(ncp) failed (%d)\n",
__func__, rc);
regulator_put(snddev_reg_ncp);
snddev_reg_ncp = NULL;
}
done:
if (!snddev_reg_l10)
return;
rc = regulator_disable(snddev_reg_l10);
if (rc < 0)
pr_err("%s: regulator_disable(l10) failed (%d)\n",
__func__, rc);
regulator_put(snddev_reg_l10);
snddev_reg_l10 = NULL;
#endif /* CONFIG_SKY_SND_CTRL */
}
static int msm_snddev_enable_amic_power(void)
{
int ret = 0;
#ifdef CONFIG_PMIC8058_OTHC
if (machine_is_msm8x60_fluid()) {
ret = pm8058_micbias_enable(OTHC_MICBIAS_0,
OTHC_SIGNAL_ALWAYS_ON);
if (ret)
pr_err("%s: Enabling amic power failed\n", __func__);
ret = gpio_request(SNDDEV_GPIO_MIC2_ANCR_SEL, "MIC2_ANCR_SEL");
if (ret) {
pr_err("%s: spkr pamp gpio %d request failed\n",
__func__, SNDDEV_GPIO_MIC2_ANCR_SEL);
return ret;
}
gpio_direction_output(SNDDEV_GPIO_MIC2_ANCR_SEL, 0);
ret = gpio_request(SNDDEV_GPIO_MIC1_ANCL_SEL, "MIC1_ANCL_SEL");
if (ret) {
pr_err("%s: mic1 ancl gpio %d request failed\n",
__func__, SNDDEV_GPIO_MIC1_ANCL_SEL);
gpio_free(SNDDEV_GPIO_MIC2_ANCR_SEL);
return ret;
}
gpio_direction_output(SNDDEV_GPIO_MIC1_ANCL_SEL, 0);
} else {
#ifdef CONFIG_SKY_SND_CTRL //N1066 20120410 Sound Patch
ret = pm8058_micbias_enable(OTHC_MICBIAS_0,
OTHC_SIGNAL_ALWAYS_ON);
#else
ret = pm8058_micbias_enable(OTHC_MICBIAS_2,
OTHC_SIGNAL_ALWAYS_ON);
#endif
if (ret)
pr_err("%s: Enabling amic power failed\n", __func__);
}
#endif
return ret;
}
static void msm_snddev_disable_amic_power(void)
{
#ifdef CONFIG_PMIC8058_OTHC
int ret;
if (machine_is_msm8x60_fluid()) {
ret = pm8058_micbias_enable(OTHC_MICBIAS_0,
OTHC_SIGNAL_OFF);
gpio_free(SNDDEV_GPIO_MIC1_ANCL_SEL);
gpio_free(SNDDEV_GPIO_MIC2_ANCR_SEL);
} else
#ifdef CONFIG_SKY_SND_CTRL //N1066 20120410 Sound Patch
ret = pm8058_micbias_enable(OTHC_MICBIAS_0, OTHC_SIGNAL_OFF);
#else
ret = pm8058_micbias_enable(OTHC_MICBIAS_2, OTHC_SIGNAL_OFF);
#endif
if (ret)
pr_err("%s: Disabling amic power failed\n", __func__);
#endif
}
static int msm_snddev_enable_anc_power(void)
{
int ret = 0;
#ifdef CONFIG_PMIC8058_OTHC
ret = pm8058_micbias_enable(OTHC_MICBIAS_2,
OTHC_SIGNAL_ALWAYS_ON);
if (ret)
pr_err("%s: Enabling anc micbias 2 failed\n", __func__);
if (machine_is_msm8x60_fluid()) {
ret = pm8058_micbias_enable(OTHC_MICBIAS_0,
OTHC_SIGNAL_ALWAYS_ON);
if (ret)
pr_err("%s: Enabling anc micbias 0 failed\n", __func__);
ret = gpio_request(SNDDEV_GPIO_MIC2_ANCR_SEL, "MIC2_ANCR_SEL");
if (ret) {
pr_err("%s: mic2 ancr gpio %d request failed\n",
__func__, SNDDEV_GPIO_MIC2_ANCR_SEL);
return ret;
}
gpio_direction_output(SNDDEV_GPIO_MIC2_ANCR_SEL, 1);
ret = gpio_request(SNDDEV_GPIO_MIC1_ANCL_SEL, "MIC1_ANCL_SEL");
if (ret) {
pr_err("%s: mic1 ancl gpio %d request failed\n",
__func__, SNDDEV_GPIO_MIC1_ANCL_SEL);
gpio_free(SNDDEV_GPIO_MIC2_ANCR_SEL);
return ret;
}
gpio_direction_output(SNDDEV_GPIO_MIC1_ANCL_SEL, 1);
}
#endif
return ret;
}
static void msm_snddev_disable_anc_power(void)
{
#ifdef CONFIG_PMIC8058_OTHC
int ret;
ret = pm8058_micbias_enable(OTHC_MICBIAS_2, OTHC_SIGNAL_OFF);
if (machine_is_msm8x60_fluid()) {
ret |= pm8058_micbias_enable(OTHC_MICBIAS_0,
OTHC_SIGNAL_OFF);
gpio_free(SNDDEV_GPIO_MIC2_ANCR_SEL);
gpio_free(SNDDEV_GPIO_MIC1_ANCL_SEL);
}
if (ret)
pr_err("%s: Disabling anc power failed\n", __func__);
#endif
}
static int msm_snddev_enable_amic_sec_power(void)
{
#ifdef CONFIG_PMIC8058_OTHC
int ret;
if (machine_is_msm8x60_fluid()) {
ret = pm8058_micbias_enable(OTHC_MICBIAS_2,
OTHC_SIGNAL_ALWAYS_ON);
if (ret)
pr_err("%s: Enabling amic2 power failed\n", __func__);
ret = gpio_request(SNDDEV_GPIO_HS_MIC4_SEL,
"HS_MIC4_SEL");
if (ret) {
pr_err("%s: spkr pamp gpio %d request failed\n",
__func__, SNDDEV_GPIO_HS_MIC4_SEL);
return ret;
}
gpio_direction_output(SNDDEV_GPIO_HS_MIC4_SEL, 1);
}
#endif
msm_snddev_enable_amic_power();
return 0;
}
static void msm_snddev_disable_amic_sec_power(void)
{
#ifdef CONFIG_PMIC8058_OTHC
int ret;
if (machine_is_msm8x60_fluid()) {
ret = pm8058_micbias_enable(OTHC_MICBIAS_2,
OTHC_SIGNAL_OFF);
if (ret)
pr_err("%s: Disabling amic2 power failed\n", __func__);
gpio_free(SNDDEV_GPIO_HS_MIC4_SEL);
}
#endif
msm_snddev_disable_amic_power();
}
static int msm_snddev_enable_dmic_sec_power(void)
{
int ret;
ret = msm_snddev_enable_dmic_power();
if (ret) {
pr_err("%s: Error: Enabling dmic power failed\n", __func__);
return ret;
}
#ifdef CONFIG_PMIC8058_OTHC
ret = pm8058_micbias_enable(OTHC_MICBIAS_2, OTHC_SIGNAL_ALWAYS_ON);
if (ret) {
pr_err("%s: Error: Enabling micbias failed\n", __func__);
msm_snddev_disable_dmic_power();
return ret;
}
#endif
return 0;
}
static void msm_snddev_disable_dmic_sec_power(void)
{
msm_snddev_disable_dmic_power();
#ifdef CONFIG_PMIC8058_OTHC
pm8058_micbias_enable(OTHC_MICBIAS_2, OTHC_SIGNAL_OFF);
#endif
}
static struct adie_codec_action_unit iearpiece_48KHz_osr256_actions[] =
EAR_PRI_MONO_8000_OSR_256;
static struct adie_codec_hwsetting_entry iearpiece_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = iearpiece_48KHz_osr256_actions,
.action_sz = ARRAY_SIZE(iearpiece_48KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile iearpiece_profile = {
.path_type = ADIE_CODEC_RX,
.settings = iearpiece_settings,
.setting_sz = ARRAY_SIZE(iearpiece_settings),
};
static struct snddev_icodec_data snddev_iearpiece_data = {
.capability = (SNDDEV_CAP_RX | SNDDEV_CAP_VOICE),
.name = "handset_rx",
.copp_id = 0,
.profile = &iearpiece_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
#ifdef CONFIG_MACH_MSM8X60_PRESTO //N1066 20120410 Sound Patch // jmlee
.pamp_on = msm_snddev_enable_iearpiece_on,
.pamp_off = msm_snddev_disable_iearpeace_off,
#elif defined (CONFIG_SKY_SND_EXTAMP) /* elecjang 20110421 for max97001 subsystem */
.pamp_on = msm_snddev_poweramp_handset_on,
.pamp_off = msm_snddev_poweramp_handset_off,
#endif
};
static struct platform_device msm_iearpiece_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_iearpiece_data },
};
#ifdef CONFIG_SKY_SND_VT_VOIP //N1066 20120410 Sound Patch // SangwonLee 110406 DeviceSeparation
static struct adie_codec_action_unit voip_iearpiece_48KHz_osr256_actions[] =
EAR_PRI_MONO_8000_OSR_256;
static struct adie_codec_hwsetting_entry voip_iearpiece_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = voip_iearpiece_48KHz_osr256_actions,
.action_sz = ARRAY_SIZE(voip_iearpiece_48KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile voip_iearpiece_profile = {
.path_type = ADIE_CODEC_RX,
.settings = voip_iearpiece_settings,
.setting_sz = ARRAY_SIZE(voip_iearpiece_settings),
};
static struct snddev_icodec_data voip_snddev_iearpiece_data = {
.capability = (SNDDEV_CAP_RX | SNDDEV_CAP_VOICE),
.name = "voip_handset_rx",
.copp_id = 0,
.profile = &voip_iearpiece_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
#ifdef CONFIG_SKY_SND_EXTAMP
.pamp_on = msm_snddev_poweramp_handset_on,
.pamp_off = msm_snddev_poweramp_handset_off,
#endif
};
static struct platform_device voip_msm_iearpiece_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &voip_snddev_iearpiece_data },
};
#ifndef NO_VT_SEPARATION
static struct adie_codec_action_unit vt_iearpiece_48KHz_osr256_actions[] =
EAR_PRI_MONO_8000_OSR_256;
static struct adie_codec_hwsetting_entry vt_iearpiece_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = vt_iearpiece_48KHz_osr256_actions,
.action_sz = ARRAY_SIZE(vt_iearpiece_48KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile vt_iearpiece_profile = {
.path_type = ADIE_CODEC_RX,
.settings = vt_iearpiece_settings,
.setting_sz = ARRAY_SIZE(vt_iearpiece_settings),
};
static struct snddev_icodec_data vt_snddev_iearpiece_data = {
.capability = (SNDDEV_CAP_RX | SNDDEV_CAP_VOICE),
.name = "vt_handset_rx",
.copp_id = 0,
.profile = &vt_iearpiece_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
#ifdef CONFIG_SKY_SND_EXTAMP
.pamp_on = msm_snddev_poweramp_handset_on,
.pamp_off = msm_snddev_poweramp_handset_off,
#endif
};
static struct platform_device vt_msm_iearpiece_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &vt_snddev_iearpiece_data },
};
#endif
#endif // CONFIG_SKY_SND_VT_VOIP
static struct adie_codec_action_unit imic_48KHz_osr256_actions[] =
AMIC_PRI_MONO_OSR_256;
static struct adie_codec_hwsetting_entry imic_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = imic_48KHz_osr256_actions,
.action_sz = ARRAY_SIZE(imic_48KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile imic_profile = {
.path_type = ADIE_CODEC_TX,
.settings = imic_settings,
.setting_sz = ARRAY_SIZE(imic_settings),
};
static struct snddev_icodec_data snddev_imic_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "handset_tx",
.copp_id = 1,
.profile = &imic_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_amic_power,
.pamp_off = msm_snddev_disable_amic_power,
};
static struct platform_device msm_imic_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_imic_data },
};
static struct snddev_icodec_data snddev_fluid_ispkr_mic_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "speaker_mono_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &imic_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_amic_power,
.pamp_off = msm_snddev_disable_amic_power,
};
static struct platform_device msm_fluid_ispkr_mic_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_fluid_ispkr_mic_data },
};
#ifdef CONFIG_SKY_SND_VT_VOIP //N1066 20120410 Sound Patch // SangwonLee 110406 DeviceSeparation
static struct adie_codec_action_unit voip_imic_48KHz_osr256_actions[] =
AMIC_PRI_MONO_8000_OSR_256;
static struct adie_codec_hwsetting_entry voip_imic_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = voip_imic_48KHz_osr256_actions,
.action_sz = ARRAY_SIZE(voip_imic_48KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile voip_imic_profile = {
.path_type = ADIE_CODEC_TX,
.settings = voip_imic_settings,
.setting_sz = ARRAY_SIZE(voip_imic_settings),
};
static struct snddev_icodec_data voip_snddev_imic_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "voip_handset_tx",
.copp_id = 1,
.profile = &voip_imic_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_amic_power,
.pamp_off = msm_snddev_disable_amic_power,
};
static struct platform_device voip_msm_imic_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &voip_snddev_imic_data },
};
#ifndef NO_VT_SEPARATION
static struct adie_codec_action_unit vt_imic_48KHz_osr256_actions[] =
AMIC_PRI_MONO_8000_OSR_256;
static struct adie_codec_hwsetting_entry vt_imic_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = vt_imic_48KHz_osr256_actions,
.action_sz = ARRAY_SIZE(vt_imic_48KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile vt_imic_profile = {
.path_type = ADIE_CODEC_TX,
.settings = vt_imic_settings,
.setting_sz = ARRAY_SIZE(vt_imic_settings),
};
static struct snddev_icodec_data vt_snddev_imic_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "vt_handset_tx",
.copp_id = 1,
.profile = &vt_imic_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_amic_power,
.pamp_off = msm_snddev_disable_amic_power,
};
static struct platform_device vt_msm_imic_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &vt_snddev_imic_data },
};
#endif
#endif // CONFIG_SKY_SND_VT_VOIP
static struct adie_codec_action_unit headset_ab_cpls_48KHz_osr256_actions[] =
#ifdef CONFIG_SKY_SND_CTRL //N1066 20120410 Sound Patch /* 20110429-jhpark: RX HPH CLASS AB LEGACY */
HPH_PRI_AB_LEG_STEREO;
#else
HEADSET_AB_CPLS_48000_OSR_256;
#endif
static struct adie_codec_hwsetting_entry headset_ab_cpls_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = headset_ab_cpls_48KHz_osr256_actions,
.action_sz = ARRAY_SIZE(headset_ab_cpls_48KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile headset_ab_cpls_profile = {
.path_type = ADIE_CODEC_RX,
.settings = headset_ab_cpls_settings,
.setting_sz = ARRAY_SIZE(headset_ab_cpls_settings),
};
static struct snddev_icodec_data snddev_ihs_stereo_rx_data = {
.capability = (SNDDEV_CAP_RX | SNDDEV_CAP_VOICE),
.name = "headset_stereo_rx",
.copp_id = 0,
.profile = &headset_ab_cpls_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
.voltage_on = msm_snddev_voltage_on,
.voltage_off = msm_snddev_voltage_off,
#ifdef CONFIG_SKY_SND_EXTAMP //N1066 20120410 Sound Patch /* elecjang 20110421 for max97001 subsystem */
.pamp_on = msm_snddev_poweramp_headset_on,
.pamp_off = msm_snddev_poweramp_headset_off,
#endif
};
static struct platform_device msm_headset_stereo_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_ihs_stereo_rx_data },
};
#ifdef CONFIG_SKY_SND_VT_VOIP //N1066 20120410 Sound Patch // SangwonLee 110406 DeviceSeparation
static struct adie_codec_action_unit voip_headset_ab_cpls_48KHz_osr256_actions[] =
#ifdef CONFIG_SKY_SND_CTRL
VOIP_HPH_PRI_AB_LEG_STEREO;
#else
HEADSET_AB_CPLS_48000_OSR_256;
#endif
static struct adie_codec_hwsetting_entry voip_headset_ab_cpls_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = voip_headset_ab_cpls_48KHz_osr256_actions,
.action_sz = ARRAY_SIZE(voip_headset_ab_cpls_48KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile voip_headset_ab_cpls_profile = {
.path_type = ADIE_CODEC_RX,
.settings = voip_headset_ab_cpls_settings,
.setting_sz = ARRAY_SIZE(voip_headset_ab_cpls_settings),
};
static struct snddev_icodec_data voip_snddev_ihs_stereo_rx_data = {
.capability = (SNDDEV_CAP_RX | SNDDEV_CAP_VOICE),
.name = "voip_headset_stereo_rx",
.copp_id = 0,
.profile = &voip_headset_ab_cpls_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
.voltage_on = msm_snddev_voltage_on,
.voltage_off = msm_snddev_voltage_off,
#ifdef CONFIG_SKY_SND_EXTAMP
.pamp_on = msm_snddev_poweramp_voip_headset_on,
.pamp_off = msm_snddev_poweramp_voip_headset_off,
#endif
};
static struct platform_device voip_msm_headset_stereo_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &voip_snddev_ihs_stereo_rx_data },
};
#ifndef NO_VT_SEPARATION
static struct adie_codec_action_unit vt_headset_ab_cpls_48KHz_osr256_actions[] =
#ifdef CONFIG_SKY_SND_CTRL
VT_HPH_PRI_AB_LEG_STEREO;
#else
HEADSET_AB_CPLS_48000_OSR_256;
#endif
static struct adie_codec_hwsetting_entry vt_headset_ab_cpls_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = vt_headset_ab_cpls_48KHz_osr256_actions,
.action_sz = ARRAY_SIZE(vt_headset_ab_cpls_48KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile vt_headset_ab_cpls_profile = {
.path_type = ADIE_CODEC_RX,
.settings = vt_headset_ab_cpls_settings,
.setting_sz = ARRAY_SIZE(vt_headset_ab_cpls_settings),
};
static struct snddev_icodec_data vt_snddev_ihs_stereo_rx_data = {
.capability = (SNDDEV_CAP_RX | SNDDEV_CAP_VOICE),
.name = "vt_headset_stereo_rx",
.copp_id = 0,
.profile = &vt_headset_ab_cpls_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
.voltage_on = msm_snddev_voltage_on,
.voltage_off = msm_snddev_voltage_off,
#ifdef CONFIG_SKY_SND_EXTAMP
.pamp_on = msm_snddev_poweramp_headset_on,
.pamp_off = msm_snddev_poweramp_headset_off,
#endif
};
static struct platform_device vt_msm_headset_stereo_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &vt_snddev_ihs_stereo_rx_data },
};
#endif
#endif // CONFIG_SKY_SND_VT_VOIP
static struct adie_codec_action_unit headset_anc_48KHz_osr256_actions[] =
ANC_HEADSET_CPLS_AMIC1_AUXL_RX1_48000_OSR_256;
static struct adie_codec_hwsetting_entry headset_anc_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = headset_anc_48KHz_osr256_actions,
.action_sz = ARRAY_SIZE(headset_anc_48KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile headset_anc_profile = {
.path_type = ADIE_CODEC_RX,
.settings = headset_anc_settings,
.setting_sz = ARRAY_SIZE(headset_anc_settings),
};
static struct snddev_icodec_data snddev_anc_headset_data = {
.capability = (SNDDEV_CAP_RX | SNDDEV_CAP_VOICE | SNDDEV_CAP_ANC),
.name = "anc_headset_stereo_rx",
.copp_id = PRIMARY_I2S_RX,
.profile = &headset_anc_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_anc_power,
.pamp_off = msm_snddev_disable_anc_power,
.voltage_on = msm_snddev_voltage_on,
.voltage_off = msm_snddev_voltage_off,
};
static struct platform_device msm_anc_headset_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_anc_headset_data },
};
static struct adie_codec_action_unit ispkr_stereo_48KHz_osr256_actions[] =
SPEAKER_PRI_STEREO_48000_OSR_256;
static struct adie_codec_hwsetting_entry ispkr_stereo_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ispkr_stereo_48KHz_osr256_actions,
.action_sz = ARRAY_SIZE(ispkr_stereo_48KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile ispkr_stereo_profile = {
.path_type = ADIE_CODEC_RX,
.settings = ispkr_stereo_settings,
.setting_sz = ARRAY_SIZE(ispkr_stereo_settings),
};
static struct snddev_icodec_data snddev_ispkr_stereo_data = {
.capability = (SNDDEV_CAP_RX | SNDDEV_CAP_VOICE),
.name = "speaker_stereo_rx",
.copp_id = 0,
.profile = &ispkr_stereo_profile,
#ifdef CONFIG_SKY_SND_CTRL //N1066 20120410 Sound Patch /* 20110521-jhpark:If you use 2, it is stereo so please use 1 then L+R will be mixed. */
.channel_mode = 1,
#else
.channel_mode = 2,
#endif
.default_sample_rate = 48000,
#ifdef CONFIG_SKY_SND_EXTAMP //N1066 20120410 Sound Patch /* elecjang 20110421 for max97001 subsystem */
.pamp_on = msm_snddev_poweramp_speaker_on,
.pamp_off = msm_snddev_poweramp_speaker_off,
#else
.pamp_on = msm_snddev_poweramp_on,
.pamp_off = msm_snddev_poweramp_off,
#endif
};
static struct platform_device msm_ispkr_stereo_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_ispkr_stereo_data },
};
#ifdef CONFIG_SKY_SND_VT_VOIP //N1066 20120410 Sound Patch // SangwonLee 110406 DeviceSeparation
static struct adie_codec_action_unit voip_ispkr_stereo_48KHz_osr256_actions[] =
SPEAKER_PRI_STEREO_48000_OSR_256;
static struct adie_codec_hwsetting_entry voip_ispkr_stereo_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = voip_ispkr_stereo_48KHz_osr256_actions,
.action_sz = ARRAY_SIZE(voip_ispkr_stereo_48KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile voip_ispkr_stereo_profile = {
.path_type = ADIE_CODEC_RX,
.settings = voip_ispkr_stereo_settings,
.setting_sz = ARRAY_SIZE(voip_ispkr_stereo_settings),
};
static struct snddev_icodec_data voip_snddev_ispkr_stereo_data = {
.capability = (SNDDEV_CAP_RX | SNDDEV_CAP_VOICE),
.name = "voip_speaker_stereo_rx",
.copp_id = 0,
.profile = &voip_ispkr_stereo_profile,
#ifdef CONFIG_SKY_SND_CTRL /* 20110521-jhpark:If you use 2, it is stereo so please use 1 then L+R will be mixed. */
.channel_mode = 1,
#else
.channel_mode = 2,
#endif
.default_sample_rate = 48000,
#ifdef CONFIG_SKY_SND_EXTAMP
.pamp_on = msm_snddev_poweramp_speaker_on,
.pamp_off = msm_snddev_poweramp_speaker_off,
#else
.pamp_on = msm_snddev_poweramp_on,
.pamp_off = msm_snddev_poweramp_off,
#endif
};
static struct platform_device voip_msm_ispkr_stereo_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &voip_snddev_ispkr_stereo_data },
};
#ifndef NO_VT_SEPARATION
static struct adie_codec_action_unit vt_ispkr_stereo_48KHz_osr256_actions[] =
SPEAKER_PRI_STEREO_48000_OSR_256;
static struct adie_codec_hwsetting_entry vt_ispkr_stereo_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = vt_ispkr_stereo_48KHz_osr256_actions,
.action_sz = ARRAY_SIZE(vt_ispkr_stereo_48KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile vt_ispkr_stereo_profile = {
.path_type = ADIE_CODEC_RX,
.settings = vt_ispkr_stereo_settings,
.setting_sz = ARRAY_SIZE(vt_ispkr_stereo_settings),
};
static struct snddev_icodec_data vt_snddev_ispkr_stereo_data = {
.capability = (SNDDEV_CAP_RX | SNDDEV_CAP_VOICE),
.name = "vt_speaker_stereo_rx",
.copp_id = 0,
.profile = &vt_ispkr_stereo_profile,
#ifdef CONFIG_SKY_SND_CTRL /* 20110521-jhpark:If you use 2, it is stereo so please use 1 then L+R will be mixed. */
.channel_mode = 1,
#else
.channel_mode = 2,
#endif
.default_sample_rate = 48000,
#ifdef CONFIG_SKY_SND_EXTAMP //N1066 20120607 GB UI Merge
.pamp_on = msm_snddev_poweramp_vt_speaker_on,
.pamp_off = msm_snddev_poweramp_vt_speaker_off,
#else
.pamp_on = msm_snddev_poweramp_on,
.pamp_off = msm_snddev_poweramp_off,
#endif
};
static struct platform_device vt_msm_ispkr_stereo_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &vt_snddev_ispkr_stereo_data },
};
#endif
#endif // CONFIG_SKY_SND_VT_VOIP
static struct adie_codec_action_unit idmic_mono_48KHz_osr256_actions[] =
DMIC1_PRI_MONO_OSR_256;
static struct adie_codec_hwsetting_entry idmic_mono_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = idmic_mono_48KHz_osr256_actions,
.action_sz = ARRAY_SIZE(idmic_mono_48KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile idmic_mono_profile = {
.path_type = ADIE_CODEC_TX,
.settings = idmic_mono_settings,
.setting_sz = ARRAY_SIZE(idmic_mono_settings),
};
static struct snddev_icodec_data snddev_ispkr_mic_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "speaker_mono_tx",
#ifdef CONFIG_SKY_SND_CTRL //N1066 20120410 Sound Patch
.copp_id = 1,
.profile = &imic_profile,
#else
.copp_id = PRIMARY_I2S_TX,
.profile = &idmic_mono_profile,
#endif
.channel_mode = 1,
.default_sample_rate = 48000,
#ifdef CONFIG_SKY_SND_CTRL //N1066 20120410 Sound Patch
.pamp_on = msm_snddev_enable_amic_power,
.pamp_off = msm_snddev_disable_amic_power,
#else
.pamp_on = msm_snddev_enable_dmic_power,
.pamp_off = msm_snddev_disable_dmic_power,
#endif
};
static struct platform_device msm_ispkr_mic_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_ispkr_mic_data },
};
#ifdef CONFIG_SKY_SND_VT_VOIP //N1066 20120410 Sound Patch // SangwonLee 110406 DeviceSeparation
static struct adie_codec_action_unit voip_imic_48KHz_osr256_actions_spk[] =
AMIC_PRI_MONO_8000_OSR_256_SPK;
static struct adie_codec_hwsetting_entry voip_imic_settings_spk[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = voip_imic_48KHz_osr256_actions_spk,
.action_sz = ARRAY_SIZE(voip_imic_48KHz_osr256_actions_spk),
}
};
static struct adie_codec_dev_profile voip_imic_profile_spk = {
.path_type = ADIE_CODEC_TX,
.settings = voip_imic_settings_spk,
.setting_sz = ARRAY_SIZE(voip_imic_settings_spk),
};
static struct snddev_icodec_data voip_snddev_ispkr_mic_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "voip_speaker_mono_tx",
.copp_id = 1,
.profile = &voip_imic_profile_spk,
.channel_mode = 1,
.default_sample_rate = 48000,
#ifdef CONFIG_SKY_SND_CTRL
.pamp_on = msm_snddev_enable_amic_power,
.pamp_off = msm_snddev_disable_amic_power,
#else
.pamp_on = msm_snddev_enable_dmic_power,
.pamp_off = msm_snddev_disable_dmic_power,
#endif
};
static struct platform_device voip_msm_ispkr_mic_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &voip_snddev_ispkr_mic_data },
};
#ifndef NO_VT_SEPARATION
static struct adie_codec_action_unit vt_imic_48KHz_osr256_actions_spk[] =
AMIC_PRI_MONO_8000_OSR_256_SPK;
static struct adie_codec_hwsetting_entry vt_imic_settings_spk[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = vt_imic_48KHz_osr256_actions_spk,
.action_sz = ARRAY_SIZE(vt_imic_48KHz_osr256_actions_spk),
}
};
static struct adie_codec_dev_profile vt_imic_profile_spk = {
.path_type = ADIE_CODEC_TX,
.settings = vt_imic_settings_spk,
.setting_sz = ARRAY_SIZE(vt_imic_settings_spk),
};
static struct snddev_icodec_data vt_snddev_ispkr_mic_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "vt_speaker_mono_tx",
.copp_id = 1,
.profile = &vt_imic_profile_spk,
.channel_mode = 1,
.default_sample_rate = 48000,
#ifdef CONFIG_SKY_SND_CTRL
.pamp_on = msm_snddev_enable_amic_power,
.pamp_off = msm_snddev_disable_amic_power,
#else
.pamp_on = msm_snddev_enable_dmic_power,
.pamp_off = msm_snddev_disable_dmic_power,
#endif
};
static struct platform_device vt_msm_ispkr_mic_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &vt_snddev_ispkr_mic_data },
};
#endif
#endif // CONFIG_SKY_SND_VT_VOIP
static struct adie_codec_action_unit iearpiece_ffa_48KHz_osr256_actions[] =
EAR_PRI_MONO_8000_OSR_256;
static struct adie_codec_hwsetting_entry iearpiece_ffa_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = iearpiece_ffa_48KHz_osr256_actions,
.action_sz = ARRAY_SIZE(iearpiece_ffa_48KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile iearpiece_ffa_profile = {
.path_type = ADIE_CODEC_RX,
.settings = iearpiece_ffa_settings,
.setting_sz = ARRAY_SIZE(iearpiece_ffa_settings),
};
static struct snddev_icodec_data snddev_iearpiece_ffa_data = {
.capability = (SNDDEV_CAP_RX | SNDDEV_CAP_VOICE),
.name = "handset_rx",
.copp_id = 0,
.profile = &iearpiece_ffa_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
};
static struct platform_device msm_iearpiece_ffa_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_iearpiece_ffa_data },
};
static struct snddev_icodec_data snddev_imic_ffa_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "handset_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &idmic_mono_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_dmic_power,
.pamp_off = msm_snddev_disable_dmic_power,
};
static struct platform_device msm_imic_ffa_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_imic_ffa_data },
};
static struct adie_codec_action_unit dual_mic_endfire_8KHz_osr256_actions[] =
DMIC1_PRI_STEREO_OSR_256;
static struct adie_codec_hwsetting_entry dual_mic_endfire_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = dual_mic_endfire_8KHz_osr256_actions,
.action_sz = ARRAY_SIZE(dual_mic_endfire_8KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile dual_mic_endfire_profile = {
.path_type = ADIE_CODEC_TX,
.settings = dual_mic_endfire_settings,
.setting_sz = ARRAY_SIZE(dual_mic_endfire_settings),
};
static struct snddev_icodec_data snddev_dual_mic_endfire_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "handset_dual_mic_endfire_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &dual_mic_endfire_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_dmic_power,
.pamp_off = msm_snddev_disable_dmic_power,
};
static struct platform_device msm_hs_dual_mic_endfire_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_dual_mic_endfire_data },
};
static struct snddev_icodec_data snddev_dual_mic_spkr_endfire_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "speaker_dual_mic_endfire_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &dual_mic_endfire_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_dmic_power,
.pamp_off = msm_snddev_disable_dmic_power,
};
static struct platform_device msm_spkr_dual_mic_endfire_device = {
.name = "snddev_icodec",
.id = 15,
.dev = { .platform_data = &snddev_dual_mic_spkr_endfire_data },
};
static struct adie_codec_action_unit dual_mic_broadside_8osr256_actions[] =
HS_DMIC2_STEREO_OSR_256;
static struct adie_codec_hwsetting_entry dual_mic_broadside_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = dual_mic_broadside_8osr256_actions,
.action_sz = ARRAY_SIZE(dual_mic_broadside_8osr256_actions),
}
};
static struct adie_codec_dev_profile dual_mic_broadside_profile = {
.path_type = ADIE_CODEC_TX,
.settings = dual_mic_broadside_settings,
.setting_sz = ARRAY_SIZE(dual_mic_broadside_settings),
};
static struct snddev_icodec_data snddev_hs_dual_mic_broadside_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "handset_dual_mic_broadside_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &dual_mic_broadside_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_dmic_sec_power,
.pamp_off = msm_snddev_disable_dmic_sec_power,
};
static struct platform_device msm_hs_dual_mic_broadside_device = {
.name = "snddev_icodec",
.id = 21,
.dev = { .platform_data = &snddev_hs_dual_mic_broadside_data },
};
static struct snddev_icodec_data snddev_spkr_dual_mic_broadside_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "speaker_dual_mic_broadside_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &dual_mic_broadside_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_dmic_sec_power,
.pamp_off = msm_snddev_disable_dmic_sec_power,
};
static struct platform_device msm_spkr_dual_mic_broadside_device = {
.name = "snddev_icodec",
.id = 18,
.dev = { .platform_data = &snddev_spkr_dual_mic_broadside_data },
};
static struct adie_codec_action_unit
fluid_dual_mic_endfire_8KHz_osr256_actions[] =
FLUID_AMIC_DUAL_8000_OSR_256;
static struct adie_codec_hwsetting_entry fluid_dual_mic_endfire_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = fluid_dual_mic_endfire_8KHz_osr256_actions,
.action_sz =
ARRAY_SIZE(fluid_dual_mic_endfire_8KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile fluid_dual_mic_endfire_profile = {
.path_type = ADIE_CODEC_TX,
.settings = fluid_dual_mic_endfire_settings,
.setting_sz = ARRAY_SIZE(fluid_dual_mic_endfire_settings),
};
static struct snddev_icodec_data snddev_fluid_dual_mic_endfire_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "handset_dual_mic_endfire_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &fluid_dual_mic_endfire_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_amic_sec_power,
.pamp_off = msm_snddev_disable_amic_sec_power,
};
static struct platform_device msm_fluid_hs_dual_mic_endfire_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_fluid_dual_mic_endfire_data },
};
static struct snddev_icodec_data snddev_fluid_dual_mic_spkr_endfire_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "speaker_dual_mic_endfire_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &fluid_dual_mic_endfire_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_amic_sec_power,
.pamp_off = msm_snddev_disable_amic_sec_power,
};
static struct platform_device msm_fluid_spkr_dual_mic_endfire_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_fluid_dual_mic_spkr_endfire_data },
};
static struct adie_codec_action_unit
fluid_dual_mic_broadside_8KHz_osr256_actions[] =
FLUID_AMIC_DUAL_BROADSIDE_8000_OSR_256;
static struct adie_codec_hwsetting_entry fluid_dual_mic_broadside_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = fluid_dual_mic_broadside_8KHz_osr256_actions,
.action_sz =
ARRAY_SIZE(fluid_dual_mic_broadside_8KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile fluid_dual_mic_broadside_profile = {
.path_type = ADIE_CODEC_TX,
.settings = fluid_dual_mic_broadside_settings,
.setting_sz = ARRAY_SIZE(fluid_dual_mic_broadside_settings),
};
static struct snddev_icodec_data snddev_fluid_dual_mic_broadside_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "handset_dual_mic_broadside_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &fluid_dual_mic_broadside_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_amic_power,
.pamp_off = msm_snddev_disable_amic_power,
};
static struct platform_device msm_fluid_hs_dual_mic_broadside_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_fluid_dual_mic_broadside_data },
};
static struct snddev_icodec_data snddev_fluid_dual_mic_spkr_broadside_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "speaker_dual_mic_broadside_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &fluid_dual_mic_broadside_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_amic_power,
.pamp_off = msm_snddev_disable_amic_power,
};
static struct platform_device msm_fluid_spkr_dual_mic_broadside_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_fluid_dual_mic_spkr_broadside_data },
};
static struct snddev_hdmi_data snddev_hdmi_stereo_rx_data = {
.capability = SNDDEV_CAP_RX ,
.name = "hdmi_stereo_rx",
.copp_id = HDMI_RX,
.channel_mode = 0,
.default_sample_rate = 48000,
};
static struct platform_device msm_snddev_hdmi_stereo_rx_device = {
.name = "snddev_hdmi",
.dev = { .platform_data = &snddev_hdmi_stereo_rx_data },
};
static struct snddev_mi2s_data snddev_mi2s_fm_tx_data = {
.capability = SNDDEV_CAP_TX ,
.name = "fmradio_stereo_tx",
.copp_id = MI2S_TX,
.channel_mode = 2, /* stereo */
.sd_lines = MI2S_SD3, /* sd3 */
.sample_rate = 48000,
};
static struct platform_device msm_mi2s_fm_tx_device = {
.name = "snddev_mi2s",
.dev = { .platform_data = &snddev_mi2s_fm_tx_data },
};
static struct snddev_mi2s_data snddev_mi2s_fm_rx_data = {
.capability = SNDDEV_CAP_RX ,
.name = "fmradio_stereo_rx",
.copp_id = MI2S_RX,
.channel_mode = 2, /* stereo */
.sd_lines = MI2S_SD3, /* sd3 */
.sample_rate = 48000,
};
static struct platform_device msm_mi2s_fm_rx_device = {
.name = "snddev_mi2s",
.id = 1,
.dev = { .platform_data = &snddev_mi2s_fm_rx_data },
};
static struct adie_codec_action_unit iheadset_mic_tx_osr256_actions[] =
HEADSET_AMIC2_TX_MONO_PRI_OSR_256;
static struct adie_codec_hwsetting_entry iheadset_mic_tx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = iheadset_mic_tx_osr256_actions,
.action_sz = ARRAY_SIZE(iheadset_mic_tx_osr256_actions),
}
};
static struct adie_codec_dev_profile iheadset_mic_profile = {
.path_type = ADIE_CODEC_TX,
.settings = iheadset_mic_tx_settings,
.setting_sz = ARRAY_SIZE(iheadset_mic_tx_settings),
};
static struct snddev_icodec_data snddev_headset_mic_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "headset_mono_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &iheadset_mic_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
};
static struct platform_device msm_headset_mic_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_headset_mic_data },
};
#ifdef CONFIG_SKY_SND_VT_VOIP //N1066 20120410 Sound Patch // SangwonLee 110406 DeviceSeparation
static struct adie_codec_action_unit voip_iheadset_mic_tx_osr256_actions[] =
HEADSET_AMIC2_TX_MONO_PRI_OSR_256;
static struct adie_codec_hwsetting_entry voip_iheadset_mic_tx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = voip_iheadset_mic_tx_osr256_actions,
.action_sz = ARRAY_SIZE(voip_iheadset_mic_tx_osr256_actions),
}
};
static struct adie_codec_dev_profile voip_iheadset_mic_profile = {
.path_type = ADIE_CODEC_TX,
.settings = voip_iheadset_mic_tx_settings,
.setting_sz = ARRAY_SIZE(voip_iheadset_mic_tx_settings),
};
static struct snddev_icodec_data voip_snddev_headset_mic_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "voip_headset_mono_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &voip_iheadset_mic_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
};
static struct platform_device voip_msm_headset_mic_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &voip_snddev_headset_mic_data },
};
#ifndef NO_VT_SEPARATION
static struct adie_codec_action_unit vt_iheadset_mic_tx_osr256_actions[] =
HEADSET_AMIC2_TX_MONO_PRI_OSR_256;
static struct adie_codec_hwsetting_entry vt_iheadset_mic_tx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = vt_iheadset_mic_tx_osr256_actions,
.action_sz = ARRAY_SIZE(vt_iheadset_mic_tx_osr256_actions),
}
};
static struct adie_codec_dev_profile vt_iheadset_mic_profile = {
.path_type = ADIE_CODEC_TX,
.settings = vt_iheadset_mic_tx_settings,
.setting_sz = ARRAY_SIZE(vt_iheadset_mic_tx_settings),
};
static struct snddev_icodec_data vt_snddev_headset_mic_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "vt_headset_mono_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &vt_iheadset_mic_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
};
static struct platform_device vt_msm_headset_mic_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &vt_snddev_headset_mic_data },
};
#endif
#endif // CONFIG_SKY_SND_VT_VOIP
#ifdef CONFIG_SKY_SND_CTRL //FEATURE_SKYSND_MDM
static struct adie_codec_action_unit mdm_handset_mic_48KHz_osr256_actions[] =
MDM_HANDSET_TX_48000_OSR_256;
static struct adie_codec_hwsetting_entry mdm_handset_mic_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = mdm_handset_mic_48KHz_osr256_actions,
.action_sz = ARRAY_SIZE(mdm_handset_mic_48KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile mdm_handset_mic_profile = {
.path_type = ADIE_CODEC_TX,
.settings = mdm_handset_mic_settings,
.setting_sz = ARRAY_SIZE(mdm_handset_mic_settings),
};
static struct snddev_icodec_data snddev_mdm_handset_mic_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "mdm_handset_tx",
.copp_id = 1,
.profile = &mdm_handset_mic_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_amic_power,
.pamp_off = msm_snddev_disable_amic_power,
};
static struct platform_device msm_mdm_handset_tx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_mdm_handset_mic_data },
};
///////////////////////////////////////
static struct adie_codec_action_unit ihs_mdm_mono_tx_48KHz_osr256_actions[] =
MDM_HEADSET_MONO_TX_48000_OSR_256;
static struct adie_codec_hwsetting_entry ihs_mdm_mono_tx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ihs_mdm_mono_tx_48KHz_osr256_actions,
.action_sz = ARRAY_SIZE(ihs_mdm_mono_tx_48KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile ihs_mdm_mono_tx_profile = {
.path_type = ADIE_CODEC_TX,
.settings = ihs_mdm_mono_tx_settings,
.setting_sz = ARRAY_SIZE(ihs_mdm_mono_tx_settings),
};
static struct snddev_icodec_data snddev_mdm_ihs_mono_tx_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "mdm_headset_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &ihs_mdm_mono_tx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
};
static struct platform_device msm_mdm_headset_tx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_mdm_ihs_mono_tx_data },
};
#endif
static struct adie_codec_action_unit
ihs_stereo_speaker_stereo_rx_48KHz_osr256_actions[] =
SPEAKER_HPH_AB_CPL_PRI_STEREO_48000_OSR_256;
static struct adie_codec_hwsetting_entry
ihs_stereo_speaker_stereo_rx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ihs_stereo_speaker_stereo_rx_48KHz_osr256_actions,
.action_sz =
ARRAY_SIZE(ihs_stereo_speaker_stereo_rx_48KHz_osr256_actions),
}
};
static struct adie_codec_dev_profile ihs_stereo_speaker_stereo_rx_profile = {
.path_type = ADIE_CODEC_RX,
.settings = ihs_stereo_speaker_stereo_rx_settings,
.setting_sz = ARRAY_SIZE(ihs_stereo_speaker_stereo_rx_settings),
};
static struct snddev_icodec_data snddev_ihs_stereo_speaker_stereo_rx_data = {
.capability = (SNDDEV_CAP_RX | SNDDEV_CAP_VOICE),
.name = "headset_stereo_speaker_stereo_rx",
.copp_id = 0,
.profile = &ihs_stereo_speaker_stereo_rx_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
#ifdef CONFIG_SKY_SND_EXTAMP //N1066 20120410 Sound Patch /* elecjang 20110421 for max97001 subsystem */
.pamp_on = msm_snddev_poweramp_headset_speaker_on,
.pamp_off = msm_snddev_poweramp_headset_speaker_off,
.voltage_on = msm_snddev_voltage_on,
.voltage_off = msm_snddev_voltage_off,
#else
.pamp_on = msm_snddev_poweramp_on,
.pamp_off = msm_snddev_poweramp_off,
.voltage_on = msm_snddev_voltage_on,
.voltage_off = msm_snddev_voltage_off,
#endif
};
static struct platform_device msm_ihs_stereo_speaker_stereo_rx_device = {
.name = "snddev_icodec",
.id = 22,
.dev = { .platform_data = &snddev_ihs_stereo_speaker_stereo_rx_data },
};
/* define the value for BT_SCO */
static struct snddev_ecodec_data snddev_bt_sco_earpiece_data = {
.capability = (SNDDEV_CAP_RX | SNDDEV_CAP_VOICE),
.name = "bt_sco_rx",
.copp_id = PCM_RX,
.channel_mode = 1,
};
static struct snddev_ecodec_data snddev_bt_sco_mic_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "bt_sco_tx",
.copp_id = PCM_TX,
.channel_mode = 1,
};
struct platform_device msm_bt_sco_earpiece_device = {
.name = "msm_snddev_ecodec",
.dev = { .platform_data = &snddev_bt_sco_earpiece_data },
};
struct platform_device msm_bt_sco_mic_device = {
.name = "msm_snddev_ecodec",
.dev = { .platform_data = &snddev_bt_sco_mic_data },
};
static struct adie_codec_action_unit itty_mono_tx_actions[] =
TTY_HEADSET_MONO_TX_OSR_256;
static struct adie_codec_hwsetting_entry itty_mono_tx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = itty_mono_tx_actions,
.action_sz = ARRAY_SIZE(itty_mono_tx_actions),
},
};
static struct adie_codec_dev_profile itty_mono_tx_profile = {
.path_type = ADIE_CODEC_TX,
.settings = itty_mono_tx_settings,
.setting_sz = ARRAY_SIZE(itty_mono_tx_settings),
};
static struct snddev_icodec_data snddev_itty_mono_tx_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE | SNDDEV_CAP_TTY),
.name = "tty_headset_mono_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &itty_mono_tx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
};
static struct platform_device msm_itty_mono_tx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_itty_mono_tx_data },
};
static struct adie_codec_action_unit itty_mono_rx_actions[] =
TTY_HEADSET_MONO_RX_8000_OSR_256;
static struct adie_codec_hwsetting_entry itty_mono_rx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = itty_mono_rx_actions,
.action_sz = ARRAY_SIZE(itty_mono_rx_actions),
},
};
static struct adie_codec_dev_profile itty_mono_rx_profile = {
.path_type = ADIE_CODEC_RX,
.settings = itty_mono_rx_settings,
.setting_sz = ARRAY_SIZE(itty_mono_rx_settings),
};
static struct snddev_icodec_data snddev_itty_mono_rx_data = {
.capability = (SNDDEV_CAP_RX | SNDDEV_CAP_VOICE | SNDDEV_CAP_TTY),
.name = "tty_headset_mono_rx",
.copp_id = PRIMARY_I2S_RX,
.profile = &itty_mono_rx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.voltage_on = msm_snddev_voltage_on,
.voltage_off = msm_snddev_voltage_off,
};
static struct platform_device msm_itty_mono_rx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_itty_mono_rx_data },
};
static struct adie_codec_action_unit linein_pri_actions[] =
LINEIN_PRI_STEREO_OSR_256;
static struct adie_codec_hwsetting_entry linein_pri_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = linein_pri_actions,
.action_sz = ARRAY_SIZE(linein_pri_actions),
},
};
static struct adie_codec_dev_profile linein_pri_profile = {
.path_type = ADIE_CODEC_TX,
.settings = linein_pri_settings,
.setting_sz = ARRAY_SIZE(linein_pri_settings),
};
static struct snddev_icodec_data snddev_linein_pri_data = {
.capability = SNDDEV_CAP_TX,
.name = "linein_pri_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &linein_pri_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
.voltage_on = msm_snddev_voltage_on,
.voltage_off = msm_snddev_voltage_off,
};
static struct platform_device msm_linein_pri_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_linein_pri_data },
};
static struct adie_codec_action_unit auxpga_lp_lo_actions[] =
LB_AUXPGA_LO_STEREO;
static struct adie_codec_hwsetting_entry auxpga_lp_lo_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = auxpga_lp_lo_actions,
.action_sz = ARRAY_SIZE(auxpga_lp_lo_actions),
},
};
static struct adie_codec_dev_profile auxpga_lp_lo_profile = {
.path_type = ADIE_CODEC_LB,
.settings = auxpga_lp_lo_settings,
.setting_sz = ARRAY_SIZE(auxpga_lp_lo_settings),
};
static struct snddev_icodec_data snddev_auxpga_lp_lo_data = {
.capability = SNDDEV_CAP_LB,
.name = "speaker_stereo_lb",
.copp_id = PRIMARY_I2S_RX,
.profile = &auxpga_lp_lo_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_poweramp_on,
.pamp_off = msm_snddev_poweramp_off,
.dev_vol_type = SNDDEV_DEV_VOL_ANALOG,
};
static struct platform_device msm_auxpga_lp_lo_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_auxpga_lp_lo_data },
};
static struct adie_codec_action_unit auxpga_lp_hs_actions[] =
LB_AUXPGA_HPH_AB_CPLS_STEREO;
static struct adie_codec_hwsetting_entry auxpga_lp_hs_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = auxpga_lp_hs_actions,
.action_sz = ARRAY_SIZE(auxpga_lp_hs_actions),
},
};
static struct adie_codec_dev_profile auxpga_lp_hs_profile = {
.path_type = ADIE_CODEC_LB,
.settings = auxpga_lp_hs_settings,
.setting_sz = ARRAY_SIZE(auxpga_lp_hs_settings),
};
static struct snddev_icodec_data snddev_auxpga_lp_hs_data = {
.capability = SNDDEV_CAP_LB,
.name = "hs_stereo_lb",
.copp_id = PRIMARY_I2S_RX,
.profile = &auxpga_lp_hs_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
.voltage_on = msm_snddev_voltage_on,
.voltage_off = msm_snddev_voltage_off,
.dev_vol_type = SNDDEV_DEV_VOL_ANALOG,
};
static struct platform_device msm_auxpga_lp_hs_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &snddev_auxpga_lp_hs_data },
};
#ifdef CONFIG_MSM8X60_FTM_AUDIO_DEVICES
static struct adie_codec_action_unit ftm_headset_mono_rx_actions[] =
HPH_PRI_AB_CPLS_MONO;
static struct adie_codec_hwsetting_entry ftm_headset_mono_rx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_headset_mono_rx_actions,
.action_sz = ARRAY_SIZE(ftm_headset_mono_rx_actions),
},
};
static struct adie_codec_dev_profile ftm_headset_mono_rx_profile = {
.path_type = ADIE_CODEC_RX,
.settings = ftm_headset_mono_rx_settings,
.setting_sz = ARRAY_SIZE(ftm_headset_mono_rx_settings),
};
static struct snddev_icodec_data ftm_headset_mono_rx_data = {
.capability = SNDDEV_CAP_RX,
.name = "ftm_headset_mono_rx",
.copp_id = PRIMARY_I2S_RX,
.profile = &ftm_headset_mono_rx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.voltage_on = msm_snddev_voltage_on,
.voltage_off = msm_snddev_voltage_off,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_headset_mono_rx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_headset_mono_rx_data},
};
static struct adie_codec_action_unit ftm_headset_mono_diff_rx_actions[] =
HEADSET_MONO_DIFF_RX;
static struct adie_codec_hwsetting_entry ftm_headset_mono_diff_rx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_headset_mono_diff_rx_actions,
.action_sz = ARRAY_SIZE(ftm_headset_mono_diff_rx_actions),
},
};
static struct adie_codec_dev_profile ftm_headset_mono_diff_rx_profile = {
.path_type = ADIE_CODEC_RX,
.settings = ftm_headset_mono_diff_rx_settings,
.setting_sz = ARRAY_SIZE(ftm_headset_mono_diff_rx_settings),
};
static struct snddev_icodec_data ftm_headset_mono_diff_rx_data = {
.capability = SNDDEV_CAP_RX,
.name = "ftm_headset_mono_diff_rx",
.copp_id = PRIMARY_I2S_RX,
.profile = &ftm_headset_mono_diff_rx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.voltage_on = msm_snddev_voltage_on,
.voltage_off = msm_snddev_voltage_off,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_headset_mono_diff_rx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_headset_mono_diff_rx_data},
};
static struct adie_codec_action_unit ftm_spkr_mono_rx_actions[] =
SPEAKER_PRI_STEREO_48000_OSR_256;
static struct adie_codec_hwsetting_entry ftm_spkr_mono_rx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_spkr_mono_rx_actions,
.action_sz = ARRAY_SIZE(ftm_spkr_mono_rx_actions),
},
};
static struct adie_codec_dev_profile ftm_spkr_mono_rx_profile = {
.path_type = ADIE_CODEC_RX,
.settings = ftm_spkr_mono_rx_settings,
.setting_sz = ARRAY_SIZE(ftm_spkr_mono_rx_settings),
};
static struct snddev_icodec_data ftm_spkr_mono_rx_data = {
.capability = SNDDEV_CAP_RX,
.name = "ftm_spkr_mono_rx",
.copp_id = PRIMARY_I2S_RX,
.profile = &ftm_spkr_mono_rx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_poweramp_on,
.pamp_off = msm_snddev_poweramp_off,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_spkr_mono_rx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_spkr_mono_rx_data},
};
static struct adie_codec_action_unit ftm_spkr_l_rx_actions[] =
FTM_SPKR_L_RX;
static struct adie_codec_hwsetting_entry ftm_spkr_l_rx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_spkr_l_rx_actions,
.action_sz = ARRAY_SIZE(ftm_spkr_l_rx_actions),
},
};
static struct adie_codec_dev_profile ftm_spkr_l_rx_profile = {
.path_type = ADIE_CODEC_RX,
.settings = ftm_spkr_l_rx_settings,
.setting_sz = ARRAY_SIZE(ftm_spkr_l_rx_settings),
};
static struct snddev_icodec_data ftm_spkr_l_rx_data = {
.capability = SNDDEV_CAP_RX,
.name = "ftm_spkr_l_rx",
.copp_id = PRIMARY_I2S_RX,
.profile = &ftm_spkr_l_rx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_poweramp_on,
.pamp_off = msm_snddev_poweramp_off,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_spkr_l_rx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_spkr_l_rx_data},
};
static struct adie_codec_action_unit ftm_spkr_r_rx_actions[] =
SPKR_R_RX;
static struct adie_codec_hwsetting_entry ftm_spkr_r_rx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_spkr_r_rx_actions,
.action_sz = ARRAY_SIZE(ftm_spkr_r_rx_actions),
},
};
static struct adie_codec_dev_profile ftm_spkr_r_rx_profile = {
.path_type = ADIE_CODEC_RX,
.settings = ftm_spkr_r_rx_settings,
.setting_sz = ARRAY_SIZE(ftm_spkr_r_rx_settings),
};
static struct snddev_icodec_data ftm_spkr_r_rx_data = {
.capability = SNDDEV_CAP_RX,
.name = "ftm_spkr_r_rx",
.copp_id = PRIMARY_I2S_RX,
.profile = &ftm_spkr_r_rx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_poweramp_on,
.pamp_off = msm_snddev_poweramp_off,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_spkr_r_rx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_spkr_r_rx_data},
};
static struct adie_codec_action_unit ftm_spkr_mono_diff_rx_actions[] =
SPKR_MONO_DIFF_RX;
static struct adie_codec_hwsetting_entry ftm_spkr_mono_diff_rx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_spkr_mono_diff_rx_actions,
.action_sz = ARRAY_SIZE(ftm_spkr_mono_diff_rx_actions),
},
};
static struct adie_codec_dev_profile ftm_spkr_mono_diff_rx_profile = {
.path_type = ADIE_CODEC_RX,
.settings = ftm_spkr_mono_diff_rx_settings,
.setting_sz = ARRAY_SIZE(ftm_spkr_mono_diff_rx_settings),
};
static struct snddev_icodec_data ftm_spkr_mono_diff_rx_data = {
.capability = SNDDEV_CAP_RX,
.name = "ftm_spkr_mono_diff_rx",
.copp_id = PRIMARY_I2S_RX,
.profile = &ftm_spkr_mono_diff_rx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_poweramp_on,
.pamp_off = msm_snddev_poweramp_off,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_spkr_mono_diff_rx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_spkr_mono_diff_rx_data},
};
static struct adie_codec_action_unit ftm_headset_mono_l_rx_actions[] =
HPH_PRI_AB_CPLS_MONO_LEFT;
static struct adie_codec_hwsetting_entry ftm_headset_mono_l_rx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_headset_mono_l_rx_actions,
.action_sz = ARRAY_SIZE(ftm_headset_mono_l_rx_actions),
},
};
static struct adie_codec_dev_profile ftm_headset_mono_l_rx_profile = {
.path_type = ADIE_CODEC_RX,
.settings = ftm_headset_mono_l_rx_settings,
.setting_sz = ARRAY_SIZE(ftm_headset_mono_l_rx_settings),
};
static struct snddev_icodec_data ftm_headset_mono_l_rx_data = {
.capability = SNDDEV_CAP_RX,
.name = "ftm_headset_mono_l_rx",
.copp_id = PRIMARY_I2S_RX,
.profile = &ftm_headset_mono_l_rx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.voltage_on = msm_snddev_voltage_on,
.voltage_off = msm_snddev_voltage_off,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_headset_mono_l_rx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_headset_mono_l_rx_data},
};
static struct adie_codec_action_unit ftm_headset_mono_r_rx_actions[] =
HPH_PRI_AB_CPLS_MONO_RIGHT;
static struct adie_codec_hwsetting_entry ftm_headset_mono_r_rx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_headset_mono_r_rx_actions,
.action_sz = ARRAY_SIZE(ftm_headset_mono_r_rx_actions),
},
};
static struct adie_codec_dev_profile ftm_headset_mono_r_rx_profile = {
.path_type = ADIE_CODEC_RX,
.settings = ftm_headset_mono_r_rx_settings,
.setting_sz = ARRAY_SIZE(ftm_headset_mono_r_rx_settings),
};
static struct snddev_icodec_data ftm_headset_mono_r_rx_data = {
.capability = SNDDEV_CAP_RX,
.name = "ftm_headset_mono_r_rx",
.copp_id = PRIMARY_I2S_RX,
.profile = &ftm_headset_mono_r_rx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.voltage_on = msm_snddev_voltage_on,
.voltage_off = msm_snddev_voltage_off,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_headset_mono_r_rx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_headset_mono_r_rx_data},
};
static struct adie_codec_action_unit ftm_linein_l_tx_actions[] =
LINEIN_MONO_L_TX;
static struct adie_codec_hwsetting_entry ftm_linein_l_tx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_linein_l_tx_actions,
.action_sz = ARRAY_SIZE(ftm_linein_l_tx_actions),
},
};
static struct adie_codec_dev_profile ftm_linein_l_tx_profile = {
.path_type = ADIE_CODEC_TX,
.settings = ftm_linein_l_tx_settings,
.setting_sz = ARRAY_SIZE(ftm_linein_l_tx_settings),
};
static struct snddev_icodec_data ftm_linein_l_tx_data = {
.capability = SNDDEV_CAP_TX,
.name = "ftm_linein_l_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &ftm_linein_l_tx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_linein_l_tx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_linein_l_tx_data },
};
static struct adie_codec_action_unit ftm_linein_r_tx_actions[] =
LINEIN_MONO_R_TX;
static struct adie_codec_hwsetting_entry ftm_linein_r_tx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_linein_r_tx_actions,
.action_sz = ARRAY_SIZE(ftm_linein_r_tx_actions),
},
};
static struct adie_codec_dev_profile ftm_linein_r_tx_profile = {
.path_type = ADIE_CODEC_TX,
.settings = ftm_linein_r_tx_settings,
.setting_sz = ARRAY_SIZE(ftm_linein_r_tx_settings),
};
static struct snddev_icodec_data ftm_linein_r_tx_data = {
.capability = SNDDEV_CAP_TX,
.name = "ftm_linein_r_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &ftm_linein_r_tx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_linein_r_tx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_linein_r_tx_data },
};
static struct adie_codec_action_unit ftm_aux_out_rx_actions[] =
AUX_OUT_RX;
static struct adie_codec_hwsetting_entry ftm_aux_out_rx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_aux_out_rx_actions,
.action_sz = ARRAY_SIZE(ftm_aux_out_rx_actions),
},
};
static struct adie_codec_dev_profile ftm_aux_out_rx_profile = {
.path_type = ADIE_CODEC_RX,
.settings = ftm_aux_out_rx_settings,
.setting_sz = ARRAY_SIZE(ftm_aux_out_rx_settings),
};
static struct snddev_icodec_data ftm_aux_out_rx_data = {
.capability = SNDDEV_CAP_RX,
.name = "ftm_aux_out_rx",
.copp_id = PRIMARY_I2S_RX,
.profile = &ftm_aux_out_rx_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_aux_out_rx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_aux_out_rx_data},
};
static struct adie_codec_action_unit ftm_dmic1_left_tx_actions[] =
DMIC1_LEFT_TX;
static struct adie_codec_hwsetting_entry ftm_dmic1_left_tx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_dmic1_left_tx_actions,
.action_sz = ARRAY_SIZE(ftm_dmic1_left_tx_actions),
},
};
static struct adie_codec_dev_profile ftm_dmic1_left_tx_profile = {
.path_type = ADIE_CODEC_TX,
.settings = ftm_dmic1_left_tx_settings,
.setting_sz = ARRAY_SIZE(ftm_dmic1_left_tx_settings),
};
static struct snddev_icodec_data ftm_dmic1_left_tx_data = {
.capability = SNDDEV_CAP_TX,
.name = "ftm_dmic1_left_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &ftm_dmic1_left_tx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_dmic_power,
.pamp_off = msm_snddev_disable_dmic_power,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_dmic1_left_tx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_dmic1_left_tx_data},
};
static struct adie_codec_action_unit ftm_dmic1_right_tx_actions[] =
DMIC1_RIGHT_TX;
static struct adie_codec_hwsetting_entry ftm_dmic1_right_tx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_dmic1_right_tx_actions,
.action_sz = ARRAY_SIZE(ftm_dmic1_right_tx_actions),
},
};
static struct adie_codec_dev_profile ftm_dmic1_right_tx_profile = {
.path_type = ADIE_CODEC_TX,
.settings = ftm_dmic1_right_tx_settings,
.setting_sz = ARRAY_SIZE(ftm_dmic1_right_tx_settings),
};
static struct snddev_icodec_data ftm_dmic1_right_tx_data = {
.capability = SNDDEV_CAP_TX,
.name = "ftm_dmic1_right_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &ftm_dmic1_right_tx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_dmic_power,
.pamp_off = msm_snddev_disable_dmic_power,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_dmic1_right_tx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_dmic1_right_tx_data},
};
static struct adie_codec_action_unit ftm_dmic1_l_and_r_tx_actions[] =
DMIC1_LEFT_AND_RIGHT_TX;
static struct adie_codec_hwsetting_entry ftm_dmic1_l_and_r_tx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_dmic1_l_and_r_tx_actions,
.action_sz = ARRAY_SIZE(ftm_dmic1_l_and_r_tx_actions),
},
};
static struct adie_codec_dev_profile ftm_dmic1_l_and_r_tx_profile = {
.path_type = ADIE_CODEC_TX,
.settings = ftm_dmic1_l_and_r_tx_settings,
.setting_sz = ARRAY_SIZE(ftm_dmic1_l_and_r_tx_settings),
};
static struct snddev_icodec_data ftm_dmic1_l_and_r_tx_data = {
.capability = SNDDEV_CAP_TX,
.name = "ftm_dmic1_l_and_r_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &ftm_dmic1_l_and_r_tx_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_dmic_power,
.pamp_off = msm_snddev_disable_dmic_power,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_dmic1_l_and_r_tx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_dmic1_l_and_r_tx_data},
};
static struct adie_codec_action_unit ftm_dmic2_left_tx_actions[] =
DMIC2_LEFT_TX;
static struct adie_codec_hwsetting_entry ftm_dmic2_left_tx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_dmic2_left_tx_actions,
.action_sz = ARRAY_SIZE(ftm_dmic2_left_tx_actions),
},
};
static struct adie_codec_dev_profile ftm_dmic2_left_tx_profile = {
.path_type = ADIE_CODEC_TX,
.settings = ftm_dmic2_left_tx_settings,
.setting_sz = ARRAY_SIZE(ftm_dmic2_left_tx_settings),
};
static struct snddev_icodec_data ftm_dmic2_left_tx_data = {
.capability = SNDDEV_CAP_TX,
.name = "ftm_dmic2_left_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &ftm_dmic2_left_tx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_dmic_power,
.pamp_off = msm_snddev_disable_dmic_power,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_dmic2_left_tx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_dmic2_left_tx_data },
};
static struct adie_codec_action_unit ftm_dmic2_right_tx_actions[] =
DMIC2_RIGHT_TX;
static struct adie_codec_hwsetting_entry ftm_dmic2_right_tx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_dmic2_right_tx_actions,
.action_sz = ARRAY_SIZE(ftm_dmic2_right_tx_actions),
},
};
static struct adie_codec_dev_profile ftm_dmic2_right_tx_profile = {
.path_type = ADIE_CODEC_TX,
.settings = ftm_dmic2_right_tx_settings,
.setting_sz = ARRAY_SIZE(ftm_dmic2_right_tx_settings),
};
static struct snddev_icodec_data ftm_dmic2_right_tx_data = {
.capability = SNDDEV_CAP_TX,
.name = "ftm_dmic2_right_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &ftm_dmic2_right_tx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_dmic_power,
.pamp_off = msm_snddev_disable_dmic_power,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_dmic2_right_tx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_dmic2_right_tx_data },
};
static struct adie_codec_action_unit ftm_dmic2_l_and_r_tx_actions[] =
DMIC2_LEFT_AND_RIGHT_TX;
static struct adie_codec_hwsetting_entry ftm_dmic2_l_and_r_tx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_dmic2_l_and_r_tx_actions,
.action_sz = ARRAY_SIZE(ftm_dmic2_l_and_r_tx_actions),
},
};
static struct adie_codec_dev_profile ftm_dmic2_l_and_r_tx_profile = {
.path_type = ADIE_CODEC_TX,
.settings = ftm_dmic2_l_and_r_tx_settings,
.setting_sz = ARRAY_SIZE(ftm_dmic2_l_and_r_tx_settings),
};
static struct snddev_icodec_data ftm_dmic2_l_and_r_tx_data = {
.capability = SNDDEV_CAP_TX,
.name = "ftm_dmic2_l_and_r_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &ftm_dmic2_l_and_r_tx_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_dmic_power,
.pamp_off = msm_snddev_disable_dmic_power,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_dmic2_l_and_r_tx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_dmic2_l_and_r_tx_data},
};
static struct adie_codec_action_unit ftm_handset_mic1_aux_in_actions[] =
HANDSET_MIC1_AUX_IN;
static struct adie_codec_hwsetting_entry ftm_handset_mic1_aux_in_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_handset_mic1_aux_in_actions,
.action_sz = ARRAY_SIZE(ftm_handset_mic1_aux_in_actions),
},
};
static struct adie_codec_dev_profile ftm_handset_mic1_aux_in_profile = {
.path_type = ADIE_CODEC_TX,
.settings = ftm_handset_mic1_aux_in_settings,
.setting_sz = ARRAY_SIZE(ftm_handset_mic1_aux_in_settings),
};
static struct snddev_icodec_data ftm_handset_mic1_aux_in_data = {
.capability = SNDDEV_CAP_TX,
.name = "ftm_handset_mic1_aux_in",
.copp_id = PRIMARY_I2S_TX,
.profile = &ftm_handset_mic1_aux_in_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
/* Assumption is that inputs are not tied to analog mic, so
* no need to enable mic bias.
*/
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_handset_mic1_aux_in_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_handset_mic1_aux_in_data},
};
static struct snddev_mi2s_data snddev_mi2s_sd0_rx_data = {
.capability = SNDDEV_CAP_RX ,
.name = "mi2s_sd0_rx",
.copp_id = MI2S_RX,
.channel_mode = 2, /* stereo */
.sd_lines = MI2S_SD0, /* sd0 */
.sample_rate = 48000,
};
static struct platform_device ftm_mi2s_sd0_rx_device = {
.name = "snddev_mi2s",
.dev = { .platform_data = &snddev_mi2s_sd0_rx_data },
};
static struct snddev_mi2s_data snddev_mi2s_sd1_rx_data = {
.capability = SNDDEV_CAP_RX ,
.name = "mi2s_sd1_rx",
.copp_id = MI2S_RX,
.channel_mode = 2, /* stereo */
.sd_lines = MI2S_SD1, /* sd1 */
.sample_rate = 48000,
};
static struct platform_device ftm_mi2s_sd1_rx_device = {
.name = "snddev_mi2s",
.dev = { .platform_data = &snddev_mi2s_sd1_rx_data },
};
static struct snddev_mi2s_data snddev_mi2s_sd2_rx_data = {
.capability = SNDDEV_CAP_RX ,
.name = "mi2s_sd2_rx",
.copp_id = MI2S_RX,
.channel_mode = 2, /* stereo */
.sd_lines = MI2S_SD2, /* sd2 */
.sample_rate = 48000,
};
static struct platform_device ftm_mi2s_sd2_rx_device = {
.name = "snddev_mi2s",
.dev = { .platform_data = &snddev_mi2s_sd2_rx_data },
};
/* earpiece */
static struct adie_codec_action_unit ftm_handset_adie_lp_rx_actions[] =
EAR_PRI_MONO_LB;
static struct adie_codec_hwsetting_entry ftm_handset_adie_lp_rx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_handset_adie_lp_rx_actions,
.action_sz = ARRAY_SIZE(ftm_handset_adie_lp_rx_actions),
}
};
static struct adie_codec_dev_profile ftm_handset_adie_lp_rx_profile = {
.path_type = ADIE_CODEC_RX,
.settings = ftm_handset_adie_lp_rx_settings,
.setting_sz = ARRAY_SIZE(ftm_handset_adie_lp_rx_settings),
};
static struct snddev_icodec_data ftm_handset_adie_lp_rx_data = {
.capability = (SNDDEV_CAP_RX | SNDDEV_CAP_VOICE),
.name = "ftm_handset_adie_lp_rx",
.copp_id = 0,
.profile = &ftm_handset_adie_lp_rx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_handset_adie_lp_rx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_handset_adie_lp_rx_data },
};
static struct adie_codec_action_unit ftm_headset_l_adie_lp_rx_actions[] =
FTM_HPH_PRI_AB_CPLS_MONO_LB_LEFT;
static struct adie_codec_hwsetting_entry ftm_headset_l_adie_lp_rx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_headset_l_adie_lp_rx_actions,
.action_sz = ARRAY_SIZE(ftm_headset_l_adie_lp_rx_actions),
},
};
static struct adie_codec_dev_profile ftm_headset_l_adie_lp_rx_profile = {
.path_type = ADIE_CODEC_RX,
.settings = ftm_headset_l_adie_lp_rx_settings,
.setting_sz = ARRAY_SIZE(ftm_headset_l_adie_lp_rx_settings),
};
static struct snddev_icodec_data ftm_headset_l_adie_lp_rx_data = {
.capability = SNDDEV_CAP_RX,
.name = "ftm_headset_l_adie_lp_rx",
.copp_id = PRIMARY_I2S_RX,
.profile = &ftm_headset_l_adie_lp_rx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.voltage_on = msm_snddev_voltage_on,
.voltage_off = msm_snddev_voltage_off,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_headset_l_adie_lp_rx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_headset_l_adie_lp_rx_data },
};
static struct adie_codec_action_unit ftm_headset_r_adie_lp_rx_actions[] =
FTM_HPH_PRI_AB_CPLS_MONO_LB_RIGHT;
static struct adie_codec_hwsetting_entry ftm_headset_r_adie_lp_rx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_headset_r_adie_lp_rx_actions,
.action_sz = ARRAY_SIZE(ftm_headset_r_adie_lp_rx_actions),
},
};
static struct adie_codec_dev_profile ftm_headset_r_adie_lp_rx_profile = {
.path_type = ADIE_CODEC_RX,
.settings = ftm_headset_r_adie_lp_rx_settings,
.setting_sz = ARRAY_SIZE(ftm_headset_r_adie_lp_rx_settings),
};
static struct snddev_icodec_data ftm_headset_r_adie_lp_rx_data = {
.capability = SNDDEV_CAP_RX,
.name = "ftm_headset_r_adie_lp_rx",
.copp_id = PRIMARY_I2S_RX,
.profile = &ftm_headset_r_adie_lp_rx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.voltage_on = msm_snddev_voltage_on,
.voltage_off = msm_snddev_voltage_off,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_headset_r_adie_lp_rx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_headset_r_adie_lp_rx_data },
};
static struct adie_codec_action_unit ftm_spkr_l_rx_lp_actions[] =
FTM_SPKR_L_RX;
static struct adie_codec_hwsetting_entry ftm_spkr_l_rx_lp_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_spkr_l_rx_lp_actions,
.action_sz = ARRAY_SIZE(ftm_spkr_l_rx_lp_actions),
},
};
static struct adie_codec_dev_profile ftm_spkr_l_rx_lp_profile = {
.path_type = ADIE_CODEC_RX,
.settings = ftm_spkr_l_rx_lp_settings,
.setting_sz = ARRAY_SIZE(ftm_spkr_l_rx_lp_settings),
};
static struct snddev_icodec_data ftm_spkr_l_rx_lp_data = {
.capability = SNDDEV_CAP_RX,
.name = "ftm_spk_l_adie_lp_rx",
.copp_id = PRIMARY_I2S_RX,
.profile = &ftm_spkr_l_rx_lp_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_poweramp_on,
.pamp_off = msm_snddev_poweramp_off,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_spk_l_adie_lp_rx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_spkr_l_rx_lp_data},
};
static struct adie_codec_action_unit ftm_spkr_r_adie_lp_rx_actions[] =
SPKR_R_RX;
static struct adie_codec_hwsetting_entry ftm_spkr_r_adie_lp_rx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_spkr_r_adie_lp_rx_actions,
.action_sz = ARRAY_SIZE(ftm_spkr_r_adie_lp_rx_actions),
},
};
static struct adie_codec_dev_profile ftm_spkr_r_adie_lp_rx_profile = {
.path_type = ADIE_CODEC_RX,
.settings = ftm_spkr_r_adie_lp_rx_settings,
.setting_sz = ARRAY_SIZE(ftm_spkr_r_adie_lp_rx_settings),
};
static struct snddev_icodec_data ftm_spkr_r_adie_lp_rx_data = {
.capability = SNDDEV_CAP_RX,
.name = "ftm_spk_r_adie_lp_rx",
.copp_id = PRIMARY_I2S_RX,
.profile = &ftm_spkr_r_adie_lp_rx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_poweramp_on,
.pamp_off = msm_snddev_poweramp_off,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_spk_r_adie_lp_rx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_spkr_r_adie_lp_rx_data},
};
static struct adie_codec_action_unit ftm_spkr_adie_lp_rx_actions[] =
FTM_SPKR_RX_LB;
static struct adie_codec_hwsetting_entry ftm_spkr_adie_lp_rx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_spkr_adie_lp_rx_actions,
.action_sz = ARRAY_SIZE(ftm_spkr_adie_lp_rx_actions),
},
};
static struct adie_codec_dev_profile ftm_spkr_adie_lp_rx_profile = {
.path_type = ADIE_CODEC_RX,
.settings = ftm_spkr_adie_lp_rx_settings,
.setting_sz = ARRAY_SIZE(ftm_spkr_adie_lp_rx_settings),
};
static struct snddev_icodec_data ftm_spkr_adie_lp_rx_data = {
.capability = SNDDEV_CAP_RX,
.name = "ftm_spk_adie_lp_rx",
.copp_id = PRIMARY_I2S_RX,
.profile = &ftm_spkr_adie_lp_rx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_poweramp_on,
.pamp_off = msm_snddev_poweramp_off,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_spk_adie_lp_rx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_spkr_adie_lp_rx_data},
};
static struct adie_codec_action_unit ftm_handset_dual_tx_lp_actions[] =
FTM_AMIC_DUAL_HANDSET_TX_LB;
static struct adie_codec_hwsetting_entry ftm_handset_dual_tx_lp_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_handset_dual_tx_lp_actions,
.action_sz = ARRAY_SIZE(ftm_handset_dual_tx_lp_actions),
}
};
static struct adie_codec_dev_profile ftm_handset_dual_tx_lp_profile = {
.path_type = ADIE_CODEC_TX,
.settings = ftm_handset_dual_tx_lp_settings,
.setting_sz = ARRAY_SIZE(ftm_handset_dual_tx_lp_settings),
};
static struct snddev_icodec_data ftm_handset_dual_tx_lp_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "handset_mic1_handset_mic2",
.copp_id = 1,
.profile = &ftm_handset_dual_tx_lp_profile,
.channel_mode = 2,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_amic_power,
.pamp_off = msm_snddev_disable_amic_power,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_handset_dual_tx_lp_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_handset_dual_tx_lp_data },
};
static struct adie_codec_action_unit ftm_handset_mic_adie_lp_tx_actions[] =
FTM_HANDSET_LB_TX;
static struct adie_codec_hwsetting_entry
ftm_handset_mic_adie_lp_tx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_handset_mic_adie_lp_tx_actions,
.action_sz = ARRAY_SIZE(ftm_handset_mic_adie_lp_tx_actions),
}
};
static struct adie_codec_dev_profile ftm_handset_mic_adie_lp_tx_profile = {
.path_type = ADIE_CODEC_TX,
.settings = ftm_handset_mic_adie_lp_tx_settings,
.setting_sz = ARRAY_SIZE(ftm_handset_mic_adie_lp_tx_settings),
};
static struct snddev_icodec_data ftm_handset_mic_adie_lp_tx_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "ftm_handset_mic_adie_lp_tx",
.copp_id = 1,
.profile = &ftm_handset_mic_adie_lp_tx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.pamp_on = msm_snddev_enable_amic_power,
.pamp_off = msm_snddev_disable_amic_power,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_handset_mic_adie_lp_tx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_handset_mic_adie_lp_tx_data },
};
static struct adie_codec_action_unit ftm_headset_mic_adie_lp_tx_actions[] =
FTM_HEADSET_LB_TX;
static struct adie_codec_hwsetting_entry
ftm_headset_mic_adie_lp_tx_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions = ftm_headset_mic_adie_lp_tx_actions,
.action_sz = ARRAY_SIZE(ftm_headset_mic_adie_lp_tx_actions),
}
};
static struct adie_codec_dev_profile ftm_headset_mic_adie_lp_tx_profile = {
.path_type = ADIE_CODEC_TX,
.settings = ftm_headset_mic_adie_lp_tx_settings,
.setting_sz = ARRAY_SIZE(ftm_headset_mic_adie_lp_tx_settings),
};
static struct snddev_icodec_data ftm_headset_mic_adie_lp_tx_data = {
.capability = (SNDDEV_CAP_TX | SNDDEV_CAP_VOICE),
.name = "ftm_headset_mic_adie_lp_tx",
.copp_id = PRIMARY_I2S_TX,
.profile = &ftm_headset_mic_adie_lp_tx_profile,
.channel_mode = 1,
.default_sample_rate = 48000,
.dev_vol_type = SNDDEV_DEV_VOL_DIGITAL,
};
static struct platform_device ftm_headset_mic_adie_lp_tx_device = {
.name = "snddev_icodec",
.dev = { .platform_data = &ftm_headset_mic_adie_lp_tx_data },
};
#endif /* CONFIG_MSM8X60_FTM_AUDIO_DEVICES */
static struct snddev_virtual_data snddev_uplink_rx_data = {
.capability = SNDDEV_CAP_RX,
.name = "uplink_rx",
.copp_id = VOICE_PLAYBACK_TX,
};
static struct platform_device msm_uplink_rx_device = {
.name = "snddev_virtual",
.dev = { .platform_data = &snddev_uplink_rx_data },
};
static struct snddev_hdmi_data snddev_hdmi_non_linear_pcm_rx_data = {
.capability = SNDDEV_CAP_RX ,
.name = "hdmi_pass_through",
.default_sample_rate = 48000,
.on_apps = 1,
};
static struct platform_device msm_snddev_hdmi_non_linear_pcm_rx_device = {
.name = "snddev_hdmi",
.dev = { .platform_data = &snddev_hdmi_non_linear_pcm_rx_data },
};
#ifdef CONFIG_DEBUG_FS
static struct adie_codec_action_unit
ihs_stereo_rx_class_d_legacy_48KHz_osr256_actions[] =
HPH_PRI_D_LEG_STEREO;
static struct adie_codec_hwsetting_entry
ihs_stereo_rx_class_d_legacy_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions =
ihs_stereo_rx_class_d_legacy_48KHz_osr256_actions,
.action_sz = ARRAY_SIZE
(ihs_stereo_rx_class_d_legacy_48KHz_osr256_actions),
}
};
static struct adie_codec_action_unit
ihs_stereo_rx_class_ab_legacy_48KHz_osr256_actions[] =
HPH_PRI_AB_LEG_STEREO;
static struct adie_codec_hwsetting_entry
ihs_stereo_rx_class_ab_legacy_settings[] = {
{
.freq_plan = 48000,
.osr = 256,
.actions =
ihs_stereo_rx_class_ab_legacy_48KHz_osr256_actions,
.action_sz = ARRAY_SIZE
(ihs_stereo_rx_class_ab_legacy_48KHz_osr256_actions),
}
};
static void snddev_hsed_config_modify_setting(int type)
{
struct platform_device *device;
struct snddev_icodec_data *icodec_data;
device = &msm_headset_stereo_device;
icodec_data = (struct snddev_icodec_data *)device->dev.platform_data;
if (icodec_data) {
if (type == 1) {
icodec_data->voltage_on = NULL;
icodec_data->voltage_off = NULL;
icodec_data->profile->settings =
ihs_stereo_rx_class_d_legacy_settings;
icodec_data->profile->setting_sz =
ARRAY_SIZE(ihs_stereo_rx_class_d_legacy_settings);
} else if (type == 2) {
icodec_data->voltage_on = NULL;
icodec_data->voltage_off = NULL;
icodec_data->profile->settings =
ihs_stereo_rx_class_ab_legacy_settings;
icodec_data->profile->setting_sz =
ARRAY_SIZE(ihs_stereo_rx_class_ab_legacy_settings);
}
}
}
static void snddev_hsed_config_restore_setting(void)
{
struct platform_device *device;
struct snddev_icodec_data *icodec_data;
device = &msm_headset_stereo_device;
icodec_data = (struct snddev_icodec_data *)device->dev.platform_data;
if (icodec_data) {
icodec_data->voltage_on = msm_snddev_voltage_on;
icodec_data->voltage_off = msm_snddev_voltage_off;
icodec_data->profile->settings = headset_ab_cpls_settings;
icodec_data->profile->setting_sz =
ARRAY_SIZE(headset_ab_cpls_settings);
}
}
static ssize_t snddev_hsed_config_debug_write(struct file *filp,
const char __user *ubuf, size_t cnt, loff_t *ppos)
{
char *lb_str = filp->private_data;
char cmd;
if (get_user(cmd, ubuf))
return -EFAULT;
if (!strcmp(lb_str, "msm_hsed_config")) {
switch (cmd) {
case '0':
snddev_hsed_config_restore_setting();
break;
case '1':
snddev_hsed_config_modify_setting(1);
break;
case '2':
snddev_hsed_config_modify_setting(2);
break;
default:
break;
}
}
return cnt;
}
static int snddev_hsed_config_debug_open(struct inode *inode, struct file *file)
{
file->private_data = inode->i_private;
return 0;
}
static const struct file_operations snddev_hsed_config_debug_fops = {
.open = snddev_hsed_config_debug_open,
.write = snddev_hsed_config_debug_write
};
#endif
static struct platform_device *snd_devices_ffa[] __initdata = {
&msm_iearpiece_ffa_device,
&msm_imic_ffa_device,
&msm_ispkr_stereo_device,
&msm_snddev_hdmi_stereo_rx_device,
&msm_headset_mic_device,
&msm_ispkr_mic_device,
&msm_bt_sco_earpiece_device,
&msm_bt_sco_mic_device,
&msm_headset_stereo_device,
&msm_itty_mono_tx_device,
&msm_itty_mono_rx_device,
&msm_mi2s_fm_tx_device,
&msm_mi2s_fm_rx_device,
&msm_hs_dual_mic_endfire_device,
&msm_spkr_dual_mic_endfire_device,
&msm_hs_dual_mic_broadside_device,
&msm_spkr_dual_mic_broadside_device,
&msm_ihs_stereo_speaker_stereo_rx_device,
&msm_anc_headset_device,
&msm_auxpga_lp_hs_device,
&msm_auxpga_lp_lo_device,
&msm_linein_pri_device,
&msm_icodec_gpio_device,
&msm_snddev_hdmi_non_linear_pcm_rx_device,
};
static struct platform_device *snd_devices_surf[] __initdata = {
&msm_iearpiece_device,
&msm_imic_device,
&msm_ispkr_stereo_device,
&msm_snddev_hdmi_stereo_rx_device,
&msm_headset_mic_device,
&msm_ispkr_mic_device,
&msm_bt_sco_earpiece_device,
&msm_bt_sco_mic_device,
&msm_headset_stereo_device,
&msm_itty_mono_tx_device,
&msm_itty_mono_rx_device,
&msm_mi2s_fm_tx_device,
&msm_mi2s_fm_rx_device,
&msm_ihs_stereo_speaker_stereo_rx_device,
&msm_auxpga_lp_hs_device,
&msm_auxpga_lp_lo_device,
&msm_linein_pri_device,
&msm_icodec_gpio_device,
&msm_snddev_hdmi_non_linear_pcm_rx_device,
#ifdef CONFIG_SKY_SND_VT_VOIP //N1066 20120410 Sound Patch // SangwonLee 110406 DeviceSeparation
&voip_msm_iearpiece_device,
&voip_msm_imic_device,
&voip_msm_headset_stereo_device,
&voip_msm_headset_mic_device,
&voip_msm_ispkr_stereo_device,
&voip_msm_ispkr_mic_device,
#ifndef NO_VT_SEPARATION
&vt_msm_iearpiece_device,
&vt_msm_imic_device,
&vt_msm_headset_stereo_device,
&vt_msm_headset_mic_device,
&vt_msm_ispkr_stereo_device,
&vt_msm_ispkr_mic_device,
#endif
#endif // CONFIG_SKY_SND_VT_VOIP
#ifdef CONFIG_SKY_SND_CTRL //FEATURE_SKYSND_MDM
&msm_mdm_handset_tx_device,
&msm_mdm_headset_tx_device,
#endif
};
static struct platform_device *snd_devices_fluid[] __initdata = {
&msm_iearpiece_device,
&msm_imic_device,
&msm_ispkr_stereo_device,
&msm_snddev_hdmi_stereo_rx_device,
&msm_headset_stereo_device,
&msm_headset_mic_device,
&msm_fluid_ispkr_mic_device,
&msm_bt_sco_earpiece_device,
&msm_bt_sco_mic_device,
&msm_mi2s_fm_tx_device,
&msm_mi2s_fm_rx_device,
&msm_fluid_hs_dual_mic_endfire_device,
&msm_fluid_spkr_dual_mic_endfire_device,
&msm_fluid_hs_dual_mic_broadside_device,
&msm_fluid_spkr_dual_mic_broadside_device,
&msm_anc_headset_device,
&msm_auxpga_lp_hs_device,
&msm_auxpga_lp_lo_device,
&msm_icodec_gpio_device,
&msm_snddev_hdmi_non_linear_pcm_rx_device,
};
static struct platform_device *snd_devices_common[] __initdata = {
&msm_aux_pcm_device,
&msm_cdcclk_ctl_device,
&msm_mi2s_device,
&msm_uplink_rx_device,
&msm_device_dspcrashd_8x60,
};
#ifdef CONFIG_MSM8X60_FTM_AUDIO_DEVICES
static struct platform_device *snd_devices_ftm[] __initdata = {
&ftm_headset_mono_rx_device,
&ftm_headset_mono_l_rx_device,
&ftm_headset_mono_r_rx_device,
&ftm_headset_mono_diff_rx_device,
&ftm_spkr_mono_rx_device,
&ftm_spkr_l_rx_device,
&ftm_spkr_r_rx_device,
&ftm_spkr_mono_diff_rx_device,
&ftm_linein_l_tx_device,
&ftm_linein_r_tx_device,
&ftm_aux_out_rx_device,
&ftm_dmic1_left_tx_device,
&ftm_dmic1_right_tx_device,
&ftm_dmic1_l_and_r_tx_device,
&ftm_dmic2_left_tx_device,
&ftm_dmic2_right_tx_device,
&ftm_dmic2_l_and_r_tx_device,
&ftm_handset_mic1_aux_in_device,
&ftm_mi2s_sd0_rx_device,
&ftm_mi2s_sd1_rx_device,
&ftm_mi2s_sd2_rx_device,
&ftm_handset_mic_adie_lp_tx_device,
&ftm_headset_mic_adie_lp_tx_device,
&ftm_handset_adie_lp_rx_device,
&ftm_headset_l_adie_lp_rx_device,
&ftm_headset_r_adie_lp_rx_device,
&ftm_spk_l_adie_lp_rx_device,
&ftm_spk_r_adie_lp_rx_device,
&ftm_spk_adie_lp_rx_device,
&ftm_handset_dual_tx_lp_device,
};
#else
static struct platform_device *snd_devices_ftm[] __initdata = {};
#endif
void __init msm_snddev_init(void)
{
int i;
int dev_id;
atomic_set(&pamp_ref_cnt, 0);
atomic_set(&preg_ref_cnt, 0);
for (i = 0, dev_id = 0; i < ARRAY_SIZE(snd_devices_common); i++)
snd_devices_common[i]->id = dev_id++;
platform_add_devices(snd_devices_common,
ARRAY_SIZE(snd_devices_common));
/* Auto detect device base on machine info */
if (machine_is_msm8x60_fusion() || machine_is_msm8x60_fusn_ffa() ||
machine_is_msm8x60_ffa()
#ifdef CONFIG_MACH_MSM8X60_EF39S //N1066 20120410 Sound Patch
|| machine_is_msm8x60_ef39s()
#endif
#ifdef CONFIG_MACH_MSM8X60_EF40K
|| machine_is_msm8x60_ef40k()
#endif
#ifdef CONFIG_MACH_MSM8X60_EF40S
|| machine_is_msm8x60_ef40s()
#endif
#ifdef CONFIG_MACH_MSM8X60_PRESTO
|| machine_is_msm8x60_presto()
#endif
) {
for (i = 0; i < ARRAY_SIZE(snd_devices_surf); i++)
snd_devices_surf[i]->id = dev_id++;
platform_add_devices(snd_devices_surf,
ARRAY_SIZE(snd_devices_surf));
} else if (machine_is_msm8x60_ffa() ||
machine_is_msm8x60_fusn_ffa()) {
for (i = 0; i < ARRAY_SIZE(snd_devices_ffa); i++)
snd_devices_ffa[i]->id = dev_id++;
platform_add_devices(snd_devices_ffa,
ARRAY_SIZE(snd_devices_ffa));
} else if (machine_is_msm8x60_fluid()) {
for (i = 0; i < ARRAY_SIZE(snd_devices_fluid); i++)
snd_devices_fluid[i]->id = dev_id++;
platform_add_devices(snd_devices_fluid,
ARRAY_SIZE(snd_devices_fluid));
}
if (machine_is_msm8x60_surf() || machine_is_msm8x60_ffa()
|| machine_is_msm8x60_fusion()
|| machine_is_msm8x60_fusn_ffa()) {
for (i = 0; i < ARRAY_SIZE(snd_devices_ftm); i++)
snd_devices_ftm[i]->id = dev_id++;
platform_add_devices(snd_devices_ftm,
ARRAY_SIZE(snd_devices_ftm));
}
#ifdef CONFIG_DEBUG_FS
debugfs_hsed_config = debugfs_create_file("msm_hsed_config",
S_IFREG | S_IRUGO, NULL,
(void *) "msm_hsed_config", &snddev_hsed_config_debug_fops);
#endif
}
|
zhaochengw/ef40s_kernel-4.2
|
arch/arm/mach-msm/qdsp6v2/board-msm8x60-audio.c
|
C
|
gpl-2.0
| 97,033
|
#!/usr/bin/python
import sys
import csv
import json
#test to make sure pyproj exists
try:
import pyproj
except ImportError:
sys.stderr.write("Please install the pyproj python module!\n")
sys.exit(3)
try:
from pymongo import MongoClient
except ImportError:
sys.stderr.write("Please install the pymongo python module!\n")
sys.exit(3)
isNAD83 = True
coordsList = []
outputFile = ""
latCol = 8
lonCol = 7
offenseCol = -1
if len(sys.argv) != 3:
print 'Supply crimedata CSV and the year!'
sys.exit(2)
csvFilename = sys.argv[1]
crimeYear = sys.argv[2]
if not crimeYear.isdigit():
print 'Please supply a valid year!'
sys.exit(2)
crimeYear = int(crimeYear)
client = MongoClient()
db = client.dc_crime
incidents = db.incidents
#set up the source and destination coordinate system
nad83=pyproj.Proj("+init=esri:102285") # Maryland State Plane for NAD 83
wgs84=pyproj.Proj("+init=EPSG:4326") # WGS84 datum
with open(csvFilename, 'r') as csvFile:
reader = csv.reader(csvFile, delimiter=',')
curLine = 1
wasSkipped = 0
for row in reader:
#we want to skip the first line
if not wasSkipped:
#check if it is LAT/LON data which seems
#to be the format for data <= 2010
if "LATITUDE" in row:
isNAD83 = False
#set the lat and lon columns
latCol = row.index("LATITUDE")
lonCol = row.index("LONGITUDE")
offenseCol = row.index("OFFENSE")
wasSkipped = 1
continue
if isNAD83:
#data is in NAD83 coordinates
#lets grab them an convert to WGS84
try:
curEastCoord = float(row[lonCol])
curNorthCoord = float(row[latCol])
#print curNorthCoord, curEastCoord
curCoords = pyproj.transform(nad83, wgs84, curEastCoord, curNorthCoord)
except ValueError:
sys.stderr.write("\nCould not parse line number %d for %s. Continuing ...\n" % (curLine, csvFilename))
continue
else:
#data is already in Lat/Lon so we are golden
#just make sure to pull from the correct columns
try:
curCoords = [ float(row[lonCol]), float(row[latCol]) ]
except ValueError:
sys.stderr.write("\nCould not parse line number %d for %s. Continuing ...\n" % (curLine, csvFilename))
continue
#for now we are just dumping everything into arrays
#coordsList.append({ "latitude" : curCoords[1], "longitude": curCoords[0]})
coordsList.append([ round(curCoords[1], 6), round(curCoords[0], 6), row[offenseCol] ])
curIncident = {
"offense": row[offenseCol],
"year": crimeYear,
"lat": round(curCoords[1], 6),
"lon": round(curCoords[0], 6)
}
incidents.insert_one(curIncident)
curLine = curLine + 1
#print json.dumps(coordsList)
|
LonnyGomes/DC-Crime-Heat-Map
|
scripts/parseCrimeDataCoords.py
|
Python
|
gpl-2.0
| 3,037
|
(function ($) {
/**
* Drag and drop table rows with field manipulation.
*
* Using the drupal_add_tabledrag() function, any table with weights or parent
* relationships may be made into draggable tables. Columns containing a field
* may optionally be hidden, providing a better user experience.
*
* Created tableDrag instances may be modified with custom behaviors by
* overriding the .onDrag, .onDrop, .row.onSwap, and .row.onIndent methods.
* See blocks.js for an example of adding additional functionality to tableDrag.
*/
Drupal.behaviors.tableDrag = {
attach: function (context, settings) {
for (var base in settings.tableDrag) {
$('#' + base, context).once('tabledrag', function () {
// Create the new tableDrag instance. Save in the Drupal variable
// to allow other scripts access to the object.
Drupal.tableDrag[base] = new Drupal.tableDrag(this, settings.tableDrag[base]);
});
}
}
};
/**
* Constructor for the tableDrag object. Provides table and field manipulation.
*
* @param table
* DOM object for the table to be made draggable.
* @param tableSettings
* Settings for the table added via drupal_add_dragtable().
*/
Drupal.tableDrag = function (table, tableSettings) {
var self = this;
// Required object variables.
this.table = table;
this.tableSettings = tableSettings;
this.dragObject = null; // Used to hold information about a current drag operation.
this.rowObject = null; // Provides operations for row manipulation.
this.oldRowElement = null; // Remember the previous element.
this.oldY = 0; // Used to determine up or down direction from last mouse move.
this.changed = false; // Whether anything in the entire table has changed.
this.maxDepth = 0; // Maximum amount of allowed parenting.
this.rtl = $(this.table).css('direction') == 'rtl' ? -1 : 1; // Direction of the table.
// Configure the scroll settings.
this.scrollSettings = { amount: 4, interval: 50, trigger: 70 };
this.scrollInterval = null;
this.scrollY = 0;
this.windowHeight = 0;
// Check this table's settings to see if there are parent relationships in
// this table. For efficiency, large sections of code can be skipped if we
// don't need to track horizontal movement and indentations.
this.indentEnabled = false;
for (var group in tableSettings) {
for (var n in tableSettings[group]) {
if (tableSettings[group][n].relationship == 'parent') {
this.indentEnabled = true;
}
if (tableSettings[group][n].limit > 0) {
this.maxDepth = tableSettings[group][n].limit;
}
}
}
if (this.indentEnabled) {
this.indentCount = 1; // Total width of indents, set in makeDraggable.
// Find the width of indentations to measure mouse movements against.
// Because the table doesn't need to start with any indentations, we
// manually append 2 indentations in the first draggable row, measure
// the offset, then remove.
var indent = Drupal.theme('tableDragIndentation');
var testRow = $('<tr/>').addClass('draggable').appendTo(table);
var testCell = $('<td/>').appendTo(testRow).prepend(indent).prepend(indent);
this.indentAmount = $('.indentation', testCell).get(1).offsetLeft - $('.indentation', testCell).get(0).offsetLeft;
testRow.remove();
}
// Make each applicable row draggable.
// Match immediate children of the parent element to allow nesting.
$('> tr.draggable, > tbody > tr.draggable', table).each(function () { self.makeDraggable(this); });
// Add a link before the table for users to show or hide weight columns.
$(table).before($('<a href="#" class="tabledrag-toggle-weight"></a>')
.attr('title', Drupal.t('Re-order rows by numerical weight instead of dragging.'))
.click(function () {
if ($.cookie('Drupal.tableDrag.showWeight') == 1) {
self.hideColumns();
}
else {
self.showColumns();
}
return false;
})
.wrap('<div class="tabledrag-toggle-weight-wrapper"></div>')
.parent()
);
// Initialize the specified columns (for example, weight or parent columns)
// to show or hide according to user preference. This aids accessibility
// so that, e.g., screen reader users can choose to enter weight values and
// manipulate form elements directly, rather than using drag-and-drop..
self.initColumns();
// Add mouse bindings to the document. The self variable is passed along
// as event handlers do not have direct access to the tableDrag object.
$(document).bind('mousemove', function (event) { return self.dragRow(event, self); });
$(document).bind('mouseup', function (event) { return self.dropRow(event, self); });
};
/**
* Initialize columns containing form elements to be hidden by default,
* according to the settings for this tableDrag instance.
*
* Identify and mark each cell with a CSS class so we can easily toggle
* show/hide it. Finally, hide columns if user does not have a
* 'Drupal.tableDrag.showWeight' cookie.
*/
Drupal.tableDrag.prototype.initColumns = function () {
for (var group in this.tableSettings) {
// Find the first field in this group.
for (var d in this.tableSettings[group]) {
var field = $('.' + this.tableSettings[group][d].target + ':first', this.table);
if (field.length && this.tableSettings[group][d].hidden) {
var hidden = this.tableSettings[group][d].hidden;
var cell = field.closest('td');
break;
}
}
// Mark the column containing this field so it can be hidden.
if (hidden && cell[0]) {
// Add 1 to our indexes. The nth-child selector is 1 based, not 0 based.
// Match immediate children of the parent element to allow nesting.
var columnIndex = $('> td', cell.parent()).index(cell.get(0)) + 1;
$('> thead > tr, > tbody > tr, > tr', this.table).each(function () {
// Get the columnIndex and adjust for any colspans in this row.
var index = columnIndex;
var cells = $(this).children();
cells.each(function (n) {
if (n < index && this.colSpan && this.colSpan > 1) {
index -= this.colSpan - 1;
}
});
if (index > 0) {
cell = cells.filter(':nth-child(' + index + ')');
if (cell[0].colSpan && cell[0].colSpan > 1) {
// If this cell has a colspan, mark it so we can reduce the colspan.
cell.addClass('tabledrag-has-colspan');
}
else {
// Mark this cell so we can hide it.
cell.addClass('tabledrag-hide');
}
}
});
}
}
// Now hide cells and reduce colspans unless cookie indicates previous choice.
// Set a cookie if it is not already present.
if ($.cookie('Drupal.tableDrag.showWeight') === null) {
$.cookie('Drupal.tableDrag.showWeight', 0, {
path: Drupal.settings.basePath,
// The cookie expires in one year.
expires: 365
});
this.hideColumns();
}
// Check cookie value and show/hide weight columns accordingly.
else {
if ($.cookie('Drupal.tableDrag.showWeight') == 1) {
this.showColumns();
}
else {
this.hideColumns();
}
}
};
/**
* Hide the columns containing weight/parent form elements.
* Undo showColumns().
*/
Drupal.tableDrag.prototype.hideColumns = function () {
// Hide weight/parent cells and headers.
$('.tabledrag-hide', 'table.tabledrag-processed').css('display', 'none');
// Show TableDrag handles.
$('.tabledrag-handle', 'table.tabledrag-processed').css('display', '');
// Reduce the colspan of any effected multi-span columns.
$('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () {
this.colSpan = this.colSpan - 1;
});
// Change link text.
$('.tabledrag-toggle-weight').text(Drupal.t('Show row weights'));
// Change cookie.
$.cookie('Drupal.tableDrag.showWeight', 0, {
path: Drupal.settings.basePath,
// The cookie expires in one year.
expires: 365
});
// Trigger an event to allow other scripts to react to this display change.
$('table.tabledrag-processed').trigger('columnschange', 'hide');
};
/**
* Show the columns containing weight/parent form elements
* Undo hideColumns().
*/
Drupal.tableDrag.prototype.showColumns = function () {
// Show weight/parent cells and headers.
$('.tabledrag-hide', 'table.tabledrag-processed').css('display', '');
// Hide TableDrag handles.
$('.tabledrag-handle', 'table.tabledrag-processed').css('display', 'none');
// Increase the colspan for any columns where it was previously reduced.
$('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () {
this.colSpan = this.colSpan + 1;
});
// Change link text.
$('.tabledrag-toggle-weight').text(Drupal.t('Hide row weights'));
// Change cookie.
$.cookie('Drupal.tableDrag.showWeight', 1, {
path: Drupal.settings.basePath,
// The cookie expires in one year.
expires: 365
});
// Trigger an event to allow other scripts to react to this display change.
$('table.tabledrag-processed').trigger('columnschange', 'show');
};
/**
* Find the target used within a particular row and group.
*/
Drupal.tableDrag.prototype.rowSettings = function (group, row) {
var field = $('.' + group, row);
for (var delta in this.tableSettings[group]) {
var targetClass = this.tableSettings[group][delta].target;
if (field.is('.' + targetClass)) {
// Return a copy of the row settings.
var rowSettings = {};
for (var n in this.tableSettings[group][delta]) {
rowSettings[n] = this.tableSettings[group][delta][n];
}
return rowSettings;
}
}
};
/**
* Take an item and add event handlers to make it become draggable.
*/
Drupal.tableDrag.prototype.makeDraggable = function (item) {
var self = this;
// Create the handle.
var handle = $('<a href="#" class="tabledrag-handle"><div class="handle"> </div></a>').attr('title', Drupal.t('Drag to re-order'));
// Insert the handle after indentations (if any).
if ($('td:first .indentation:last', item).length) {
$('td:first .indentation:last', item).after(handle);
// Update the total width of indentation in this entire table.
self.indentCount = Math.max($('.indentation', item).length, self.indentCount);
}
else {
$('td:first', item).prepend(handle);
}
// Add hover action for the handle.
handle.hover(function () {
self.dragObject == null ? $(this).addClass('tabledrag-handle-hover') : null;
}, function () {
self.dragObject == null ? $(this).removeClass('tabledrag-handle-hover') : null;
});
// Add the mousedown action for the handle.
handle.mousedown(function (event) {
// Create a new dragObject recording the event information.
self.dragObject = {};
self.dragObject.initMouseOffset = self.getMouseOffset(item, event);
self.dragObject.initMouseCoords = self.mouseCoords(event);
if (self.indentEnabled) {
self.dragObject.indentMousePos = self.dragObject.initMouseCoords;
}
// If there's a lingering row object from the keyboard, remove its focus.
if (self.rowObject) {
$('a.tabledrag-handle', self.rowObject.element).blur();
}
// Create a new rowObject for manipulation of this row.
self.rowObject = new self.row(item, 'mouse', self.indentEnabled, self.maxDepth, true);
// Save the position of the table.
self.table.topY = $(self.table).offset().top;
self.table.bottomY = self.table.topY + self.table.offsetHeight;
// Add classes to the handle and row.
$(this).addClass('tabledrag-handle-hover');
$(item).addClass('drag');
// Set the document to use the move cursor during drag.
$('body').addClass('drag');
if (self.oldRowElement) {
$(self.oldRowElement).removeClass('drag-previous');
}
// Hack for IE6 that flickers uncontrollably if select lists are moved.
if (navigator.userAgent.indexOf('MSIE 6.') != -1) {
$('select', this.table).css('display', 'none');
}
// Hack for Konqueror, prevent the blur handler from firing.
// Konqueror always gives links focus, even after returning false on mousedown.
self.safeBlur = false;
// Call optional placeholder function.
self.onDrag();
return false;
});
// Prevent the anchor tag from jumping us to the top of the page.
handle.click(function () {
return false;
});
// Similar to the hover event, add a class when the handle is focused.
handle.focus(function () {
$(this).addClass('tabledrag-handle-hover');
self.safeBlur = true;
});
// Remove the handle class on blur and fire the same function as a mouseup.
handle.blur(function (event) {
$(this).removeClass('tabledrag-handle-hover');
if (self.rowObject && self.safeBlur) {
self.dropRow(event, self);
}
});
// Add arrow-key support to the handle.
handle.keydown(function (event) {
// If a rowObject doesn't yet exist and this isn't the tab key.
if (event.keyCode != 9 && !self.rowObject) {
self.rowObject = new self.row(item, 'keyboard', self.indentEnabled, self.maxDepth, true);
}
var keyChange = false;
switch (event.keyCode) {
case 37: // Left arrow.
case 63234: // Safari left arrow.
keyChange = true;
self.rowObject.indent(-1 * self.rtl);
break;
case 38: // Up arrow.
case 63232: // Safari up arrow.
var previousRow = $(self.rowObject.element).prev('tr').get(0);
while (previousRow && $(previousRow).is(':hidden')) {
previousRow = $(previousRow).prev('tr').get(0);
}
if (previousRow) {
self.safeBlur = false; // Do not allow the onBlur cleanup.
self.rowObject.direction = 'up';
keyChange = true;
if ($(item).is('.tabledrag-root')) {
// Swap with the previous top-level row.
var groupHeight = 0;
while (previousRow && $('.indentation', previousRow).length) {
previousRow = $(previousRow).prev('tr').get(0);
groupHeight += $(previousRow).is(':hidden') ? 0 : previousRow.offsetHeight;
}
if (previousRow) {
self.rowObject.swap('before', previousRow);
// No need to check for indentation, 0 is the only valid one.
window.scrollBy(0, -groupHeight);
}
}
else if (self.table.tBodies[0].rows[0] != previousRow || $(previousRow).is('.draggable')) {
// Swap with the previous row (unless previous row is the first one
// and undraggable).
self.rowObject.swap('before', previousRow);
self.rowObject.interval = null;
self.rowObject.indent(0);
window.scrollBy(0, -parseInt(item.offsetHeight, 10));
}
handle.get(0).focus(); // Regain focus after the DOM manipulation.
}
break;
case 39: // Right arrow.
case 63235: // Safari right arrow.
keyChange = true;
self.rowObject.indent(1 * self.rtl);
break;
case 40: // Down arrow.
case 63233: // Safari down arrow.
var nextRow = $(self.rowObject.group).filter(':last').next('tr').get(0);
while (nextRow && $(nextRow).is(':hidden')) {
nextRow = $(nextRow).next('tr').get(0);
}
if (nextRow) {
self.safeBlur = false; // Do not allow the onBlur cleanup.
self.rowObject.direction = 'down';
keyChange = true;
if ($(item).is('.tabledrag-root')) {
// Swap with the next group (necessarily a top-level one).
var groupHeight = 0;
var nextGroup = new self.row(nextRow, 'keyboard', self.indentEnabled, self.maxDepth, false);
if (nextGroup) {
$(nextGroup.group).each(function () {
groupHeight += $(this).is(':hidden') ? 0 : this.offsetHeight;
});
var nextGroupRow = $(nextGroup.group).filter(':last').get(0);
self.rowObject.swap('after', nextGroupRow);
// No need to check for indentation, 0 is the only valid one.
window.scrollBy(0, parseInt(groupHeight, 10));
}
}
else {
// Swap with the next row.
self.rowObject.swap('after', nextRow);
self.rowObject.interval = null;
self.rowObject.indent(0);
window.scrollBy(0, parseInt(item.offsetHeight, 10));
}
handle.get(0).focus(); // Regain focus after the DOM manipulation.
}
break;
}
if (self.rowObject && self.rowObject.changed == true) {
$(item).addClass('drag');
if (self.oldRowElement) {
$(self.oldRowElement).removeClass('drag-previous');
}
self.oldRowElement = item;
self.restripeTable();
self.onDrag();
}
// Returning false if we have an arrow key to prevent scrolling.
if (keyChange) {
return false;
}
});
// Compatibility addition, return false on keypress to prevent unwanted scrolling.
// IE and Safari will suppress scrolling on keydown, but all other browsers
// need to return false on keypress. http://www.quirksmode.org/js/keys.html
handle.keypress(function (event) {
switch (event.keyCode) {
case 37: // Left arrow.
case 38: // Up arrow.
case 39: // Right arrow.
case 40: // Down arrow.
return false;
}
});
};
/**
* Mousemove event handler, bound to document.
*/
Drupal.tableDrag.prototype.dragRow = function (event, self) {
if (self.dragObject) {
self.currentMouseCoords = self.mouseCoords(event);
var y = self.currentMouseCoords.y - self.dragObject.initMouseOffset.y;
var x = self.currentMouseCoords.x - self.dragObject.initMouseOffset.x;
// Check for row swapping and vertical scrolling.
if (y != self.oldY) {
self.rowObject.direction = y > self.oldY ? 'down' : 'up';
self.oldY = y; // Update the old value.
// Check if the window should be scrolled (and how fast).
var scrollAmount = self.checkScroll(self.currentMouseCoords.y);
// Stop any current scrolling.
clearInterval(self.scrollInterval);
// Continue scrolling if the mouse has moved in the scroll direction.
if (scrollAmount > 0 && self.rowObject.direction == 'down' || scrollAmount < 0 && self.rowObject.direction == 'up') {
self.setScroll(scrollAmount);
}
// If we have a valid target, perform the swap and restripe the table.
var currentRow = self.findDropTargetRow(x, y);
if (currentRow) {
if (self.rowObject.direction == 'down') {
self.rowObject.swap('after', currentRow, self);
}
else {
self.rowObject.swap('before', currentRow, self);
}
self.restripeTable();
}
}
// Similar to row swapping, handle indentations.
if (self.indentEnabled) {
var xDiff = self.currentMouseCoords.x - self.dragObject.indentMousePos.x;
// Set the number of indentations the mouse has been moved left or right.
var indentDiff = Math.round(xDiff / self.indentAmount * self.rtl);
// Indent the row with our estimated diff, which may be further
// restricted according to the rows around this row.
var indentChange = self.rowObject.indent(indentDiff);
// Update table and mouse indentations.
self.dragObject.indentMousePos.x += self.indentAmount * indentChange * self.rtl;
self.indentCount = Math.max(self.indentCount, self.rowObject.indents);
}
return false;
}
};
/**
* Mouseup event handler, bound to document.
* Blur event handler, bound to drag handle for keyboard support.
*/
Drupal.tableDrag.prototype.dropRow = function (event, self) {
// Drop row functionality shared between mouseup and blur events.
if (self.rowObject != null) {
var droppedRow = self.rowObject.element;
// The row is already in the right place so we just release it.
if (self.rowObject.changed == true) {
// Update the fields in the dropped row.
self.updateFields(droppedRow);
// If a setting exists for affecting the entire group, update all the
// fields in the entire dragged group.
for (var group in self.tableSettings) {
var rowSettings = self.rowSettings(group, droppedRow);
if (rowSettings.relationship == 'group') {
for (var n in self.rowObject.children) {
self.updateField(self.rowObject.children[n], group);
}
}
}
self.rowObject.markChanged();
if (self.changed == false) {
$(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow');
self.changed = true;
}
}
if (self.indentEnabled) {
self.rowObject.removeIndentClasses();
}
if (self.oldRowElement) {
$(self.oldRowElement).removeClass('drag-previous');
}
$(droppedRow).removeClass('drag').addClass('drag-previous');
self.oldRowElement = droppedRow;
self.onDrop();
self.rowObject = null;
}
// Functionality specific only to mouseup event.
if (self.dragObject != null) {
$('.tabledrag-handle', droppedRow).removeClass('tabledrag-handle-hover');
self.dragObject = null;
$('body').removeClass('drag');
clearInterval(self.scrollInterval);
// Hack for IE6 that flickers uncontrollably if select lists are moved.
if (navigator.userAgent.indexOf('MSIE 6.') != -1) {
$('select', this.table).css('display', 'block');
}
}
};
/**
* Get the mouse coordinates from the event (allowing for browser differences).
*/
Drupal.tableDrag.prototype.mouseCoords = function (event) {
if (event.pageX || event.pageY) {
return { x: event.pageX, y: event.pageY };
}
return {
x: event.clientX + document.body.scrollLeft - document.body.clientLeft,
y: event.clientY + document.body.scrollTop - document.body.clientTop
};
};
/**
* Given a target element and a mouse event, get the mouse offset from that
* element. To do this we need the element's position and the mouse position.
*/
Drupal.tableDrag.prototype.getMouseOffset = function (target, event) {
var docPos = $(target).offset();
var mousePos = this.mouseCoords(event);
return { x: mousePos.x - docPos.left, y: mousePos.y - docPos.top };
};
/**
* Find the row the mouse is currently over. This row is then taken and swapped
* with the one being dragged.
*
* @param x
* The x coordinate of the mouse on the page (not the screen).
* @param y
* The y coordinate of the mouse on the page (not the screen).
*/
Drupal.tableDrag.prototype.findDropTargetRow = function (x, y) {
var rows = $(this.table.tBodies[0].rows).not(':hidden');
for (var n = 0; n < rows.length; n++) {
var row = rows[n];
var indentDiff = 0;
var rowY = $(row).offset().top;
// Because Safari does not report offsetHeight on table rows, but does on
// table cells, grab the firstChild of the row and use that instead.
// http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari.
if (row.offsetHeight == 0) {
var rowHeight = parseInt(row.firstChild.offsetHeight, 10) / 2;
}
// Other browsers.
else {
var rowHeight = parseInt(row.offsetHeight, 10) / 2;
}
// Because we always insert before, we need to offset the height a bit.
if ((y > (rowY - rowHeight)) && (y < (rowY + rowHeight))) {
if (this.indentEnabled) {
// Check that this row is not a child of the row being dragged.
for (var n in this.rowObject.group) {
if (this.rowObject.group[n] == row) {
return null;
}
}
}
else {
// Do not allow a row to be swapped with itself.
if (row == this.rowObject.element) {
return null;
}
}
// Check that swapping with this row is allowed.
if (!this.rowObject.isValidSwap(row)) {
return null;
}
// We may have found the row the mouse just passed over, but it doesn't
// take into account hidden rows. Skip backwards until we find a draggable
// row.
while ($(row).is(':hidden') && $(row).prev('tr').is(':hidden')) {
row = $(row).prev('tr').get(0);
}
return row;
}
}
return null;
};
/**
* After the row is dropped, update the table fields according to the settings
* set for this table.
*
* @param changedRow
* DOM object for the row that was just dropped.
*/
Drupal.tableDrag.prototype.updateFields = function (changedRow) {
for (var group in this.tableSettings) {
// Each group may have a different setting for relationship, so we find
// the source rows for each separately.
this.updateField(changedRow, group);
}
};
/**
* After the row is dropped, update a single table field according to specific
* settings.
*
* @param changedRow
* DOM object for the row that was just dropped.
* @param group
* The settings group on which field updates will occur.
*/
Drupal.tableDrag.prototype.updateField = function (changedRow, group) {
var rowSettings = this.rowSettings(group, changedRow);
// Set the row as its own target.
if (rowSettings.relationship == 'self' || rowSettings.relationship == 'group') {
var sourceRow = changedRow;
}
// Siblings are easy, check previous and next rows.
else if (rowSettings.relationship == 'sibling') {
var previousRow = $(changedRow).prev('tr').get(0);
var nextRow = $(changedRow).next('tr').get(0);
var sourceRow = changedRow;
if ($(previousRow).is('.draggable') && $('.' + group, previousRow).length) {
if (this.indentEnabled) {
if ($('.indentations', previousRow).length == $('.indentations', changedRow)) {
sourceRow = previousRow;
}
}
else {
sourceRow = previousRow;
}
}
else if ($(nextRow).is('.draggable') && $('.' + group, nextRow).length) {
if (this.indentEnabled) {
if ($('.indentations', nextRow).length == $('.indentations', changedRow)) {
sourceRow = nextRow;
}
}
else {
sourceRow = nextRow;
}
}
}
// Parents, look up the tree until we find a field not in this group.
// Go up as many parents as indentations in the changed row.
else if (rowSettings.relationship == 'parent') {
var previousRow = $(changedRow).prev('tr');
while (previousRow.length && $('.indentation', previousRow).length >= this.rowObject.indents) {
previousRow = previousRow.prev('tr');
}
// If we found a row.
if (previousRow.length) {
sourceRow = previousRow[0];
}
// Otherwise we went all the way to the left of the table without finding
// a parent, meaning this item has been placed at the root level.
else {
// Use the first row in the table as source, because it's guaranteed to
// be at the root level. Find the first item, then compare this row
// against it as a sibling.
sourceRow = $(this.table).find('tr.draggable:first').get(0);
if (sourceRow == this.rowObject.element) {
sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]).next('tr.draggable').get(0);
}
var useSibling = true;
}
}
// Because we may have moved the row from one category to another,
// take a look at our sibling and borrow its sources and targets.
this.copyDragClasses(sourceRow, changedRow, group);
rowSettings = this.rowSettings(group, changedRow);
// In the case that we're looking for a parent, but the row is at the top
// of the tree, copy our sibling's values.
if (useSibling) {
rowSettings.relationship = 'sibling';
rowSettings.source = rowSettings.target;
}
var targetClass = '.' + rowSettings.target;
var targetElement = $(targetClass, changedRow).get(0);
// Check if a target element exists in this row.
if (targetElement) {
var sourceClass = '.' + rowSettings.source;
var sourceElement = $(sourceClass, sourceRow).get(0);
switch (rowSettings.action) {
case 'depth':
// Get the depth of the target row.
targetElement.value = $('.indentation', $(sourceElement).closest('tr')).length;
break;
case 'match':
// Update the value.
targetElement.value = sourceElement.value;
break;
case 'order':
var siblings = this.rowObject.findSiblings(rowSettings);
if ($(targetElement).is('select')) {
// Get a list of acceptable values.
var values = [];
$('option', targetElement).each(function () {
values.push(this.value);
});
var maxVal = values[values.length - 1];
// Populate the values in the siblings.
$(targetClass, siblings).each(function () {
// If there are more items than possible values, assign the maximum value to the row.
if (values.length > 0) {
this.value = values.shift();
}
else {
this.value = maxVal;
}
});
}
else {
// Assume a numeric input field.
var weight = parseInt($(targetClass, siblings[0]).val(), 10) || 0;
$(targetClass, siblings).each(function () {
this.value = weight;
weight++;
});
}
break;
}
}
};
/**
* Copy all special tableDrag classes from one row's form elements to a
* different one, removing any special classes that the destination row
* may have had.
*/
Drupal.tableDrag.prototype.copyDragClasses = function (sourceRow, targetRow, group) {
var sourceElement = $('.' + group, sourceRow);
var targetElement = $('.' + group, targetRow);
if (sourceElement.length && targetElement.length) {
targetElement[0].className = sourceElement[0].className;
}
};
Drupal.tableDrag.prototype.checkScroll = function (cursorY) {
var de = document.documentElement;
var b = document.body;
var windowHeight = this.windowHeight = window.innerHeight || (de.clientHeight && de.clientWidth != 0 ? de.clientHeight : b.offsetHeight);
var scrollY = this.scrollY = (document.all ? (!de.scrollTop ? b.scrollTop : de.scrollTop) : (window.pageYOffset ? window.pageYOffset : window.scrollY));
var trigger = this.scrollSettings.trigger;
var delta = 0;
// Return a scroll speed relative to the edge of the screen.
if (cursorY - scrollY > windowHeight - trigger) {
delta = trigger / (windowHeight + scrollY - cursorY);
delta = (delta > 0 && delta < trigger) ? delta : trigger;
return delta * this.scrollSettings.amount;
}
else if (cursorY - scrollY < trigger) {
delta = trigger / (cursorY - scrollY);
delta = (delta > 0 && delta < trigger) ? delta : trigger;
return -delta * this.scrollSettings.amount;
}
};
Drupal.tableDrag.prototype.setScroll = function (scrollAmount) {
var self = this;
this.scrollInterval = setInterval(function () {
// Update the scroll values stored in the object.
self.checkScroll(self.currentMouseCoords.y);
var aboveTable = self.scrollY > self.table.topY;
var belowTable = self.scrollY + self.windowHeight < self.table.bottomY;
if (scrollAmount > 0 && belowTable || scrollAmount < 0 && aboveTable) {
window.scrollBy(0, scrollAmount);
}
}, this.scrollSettings.interval);
};
Drupal.tableDrag.prototype.restripeTable = function () {
// :even and :odd are reversed because jQuery counts from 0 and
// we count from 1, so we're out of sync.
// Match immediate children of the parent element to allow nesting.
$('> tbody > tr.draggable:visible, > tr.draggable:visible', this.table)
.removeClass('odd even')
.filter(':odd').addClass('even').end()
.filter(':even').addClass('odd');
};
/**
* Stub function. Allows a custom handler when a row begins dragging.
*/
Drupal.tableDrag.prototype.onDrag = function () {
return null;
};
/**
* Stub function. Allows a custom handler when a row is dropped.
*/
Drupal.tableDrag.prototype.onDrop = function () {
return null;
};
/**
* Constructor to make a new object to manipulate a table row.
*
* @param tableRow
* The DOM element for the table row we will be manipulating.
* @param method
* The method in which this row is being moved. Either 'keyboard' or 'mouse'.
* @param indentEnabled
* Whether the containing table uses indentations. Used for optimizations.
* @param maxDepth
* The maximum amount of indentations this row may contain.
* @param addClasses
* Whether we want to add classes to this row to indicate child relationships.
*/
Drupal.tableDrag.prototype.row = function (tableRow, method, indentEnabled, maxDepth, addClasses) {
this.element = tableRow;
this.method = method;
this.group = [tableRow];
this.groupDepth = $('.indentation', tableRow).length;
this.changed = false;
this.table = $(tableRow).closest('table').get(0);
this.indentEnabled = indentEnabled;
this.maxDepth = maxDepth;
this.direction = ''; // Direction the row is being moved.
if (this.indentEnabled) {
this.indents = $('.indentation', tableRow).length;
this.children = this.findChildren(addClasses);
this.group = $.merge(this.group, this.children);
// Find the depth of this entire group.
for (var n = 0; n < this.group.length; n++) {
this.groupDepth = Math.max($('.indentation', this.group[n]).length, this.groupDepth);
}
}
};
/**
* Find all children of rowObject by indentation.
*
* @param addClasses
* Whether we want to add classes to this row to indicate child relationships.
*/
Drupal.tableDrag.prototype.row.prototype.findChildren = function (addClasses) {
var parentIndentation = this.indents;
var currentRow = $(this.element, this.table).next('tr.draggable');
var rows = [];
var child = 0;
while (currentRow.length) {
var rowIndentation = $('.indentation', currentRow).length;
// A greater indentation indicates this is a child.
if (rowIndentation > parentIndentation) {
child++;
rows.push(currentRow[0]);
if (addClasses) {
$('.indentation', currentRow).each(function (indentNum) {
if (child == 1 && (indentNum == parentIndentation)) {
$(this).addClass('tree-child-first');
}
if (indentNum == parentIndentation) {
$(this).addClass('tree-child');
}
else if (indentNum > parentIndentation) {
$(this).addClass('tree-child-horizontal');
}
});
}
}
else {
break;
}
currentRow = currentRow.next('tr.draggable');
}
if (addClasses && rows.length) {
$('.indentation:nth-child(' + (parentIndentation + 1) + ')', rows[rows.length - 1]).addClass('tree-child-last');
}
return rows;
};
/**
* Ensure that two rows are allowed to be swapped.
*
* @param row
* DOM object for the row being considered for swapping.
*/
Drupal.tableDrag.prototype.row.prototype.isValidSwap = function (row) {
if (this.indentEnabled) {
var prevRow, nextRow;
if (this.direction == 'down') {
prevRow = row;
nextRow = $(row).next('tr').get(0);
}
else {
prevRow = $(row).prev('tr').get(0);
nextRow = row;
}
this.interval = this.validIndentInterval(prevRow, nextRow);
// We have an invalid swap if the valid indentations interval is empty.
if (this.interval.min > this.interval.max) {
return false;
}
}
// Do not let an un-draggable first row have anything put before it.
if (this.table.tBodies[0].rows[0] == row && $(row).is(':not(.draggable)')) {
return false;
}
return true;
};
/**
* Perform the swap between two rows.
*
* @param position
* Whether the swap will occur 'before' or 'after' the given row.
* @param row
* DOM element what will be swapped with the row group.
*/
Drupal.tableDrag.prototype.row.prototype.swap = function (position, row) {
Drupal.detachBehaviors(this.group, Drupal.settings, 'move');
$(row)[position](this.group);
Drupal.attachBehaviors(this.group, Drupal.settings);
this.changed = true;
this.onSwap(row);
};
/**
* Determine the valid indentations interval for the row at a given position
* in the table.
*
* @param prevRow
* DOM object for the row before the tested position
* (or null for first position in the table).
* @param nextRow
* DOM object for the row after the tested position
* (or null for last position in the table).
*/
Drupal.tableDrag.prototype.row.prototype.validIndentInterval = function (prevRow, nextRow) {
var minIndent, maxIndent;
// Minimum indentation:
// Do not orphan the next row.
minIndent = nextRow ? $('.indentation', nextRow).length : 0;
// Maximum indentation:
if (!prevRow || $(prevRow).is(':not(.draggable)') || $(this.element).is('.tabledrag-root')) {
// Do not indent:
// - the first row in the table,
// - rows dragged below a non-draggable row,
// - 'root' rows.
maxIndent = 0;
}
else {
// Do not go deeper than as a child of the previous row.
maxIndent = $('.indentation', prevRow).length + ($(prevRow).is('.tabledrag-leaf') ? 0 : 1);
// Limit by the maximum allowed depth for the table.
if (this.maxDepth) {
maxIndent = Math.min(maxIndent, this.maxDepth - (this.groupDepth - this.indents));
}
}
return { 'min': minIndent, 'max': maxIndent };
};
/**
* Indent a row within the legal bounds of the table.
*
* @param indentDiff
* The number of additional indentations proposed for the row (can be
* positive or negative). This number will be adjusted to nearest valid
* indentation level for the row.
*/
Drupal.tableDrag.prototype.row.prototype.indent = function (indentDiff) {
// Determine the valid indentations interval if not available yet.
if (!this.interval) {
var prevRow = $(this.element).prev('tr').get(0);
var nextRow = $(this.group).filter(':last').next('tr').get(0);
this.interval = this.validIndentInterval(prevRow, nextRow);
}
// Adjust to the nearest valid indentation.
var indent = this.indents + indentDiff;
indent = Math.max(indent, this.interval.min);
indent = Math.min(indent, this.interval.max);
indentDiff = indent - this.indents;
for (var n = 1; n <= Math.abs(indentDiff); n++) {
// Add or remove indentations.
if (indentDiff < 0) {
$('.indentation:first', this.group).remove();
this.indents--;
}
else {
$('td:first', this.group).prepend(Drupal.theme('tableDragIndentation'));
this.indents++;
}
}
if (indentDiff) {
// Update indentation for this row.
this.changed = true;
this.groupDepth += indentDiff;
this.onIndent();
}
return indentDiff;
};
/**
* Find all siblings for a row, either according to its subgroup or indentation.
* Note that the passed-in row is included in the list of siblings.
*
* @param settings
* The field settings we're using to identify what constitutes a sibling.
*/
Drupal.tableDrag.prototype.row.prototype.findSiblings = function (rowSettings) {
var siblings = [];
var directions = ['prev', 'next'];
var rowIndentation = this.indents;
for (var d = 0; d < directions.length; d++) {
var checkRow = $(this.element)[directions[d]]();
while (checkRow.length) {
// Check that the sibling contains a similar target field.
if ($('.' + rowSettings.target, checkRow)) {
// Either add immediately if this is a flat table, or check to ensure
// that this row has the same level of indentation.
if (this.indentEnabled) {
var checkRowIndentation = $('.indentation', checkRow).length;
}
if (!(this.indentEnabled) || (checkRowIndentation == rowIndentation)) {
siblings.push(checkRow[0]);
}
else if (checkRowIndentation < rowIndentation) {
// No need to keep looking for siblings when we get to a parent.
break;
}
}
else {
break;
}
checkRow = $(checkRow)[directions[d]]();
}
// Since siblings are added in reverse order for previous, reverse the
// completed list of previous siblings. Add the current row and continue.
if (directions[d] == 'prev') {
siblings.reverse();
siblings.push(this.element);
}
}
return siblings;
};
/**
* Remove indentation helper classes from the current row group.
*/
Drupal.tableDrag.prototype.row.prototype.removeIndentClasses = function () {
for (var n in this.children) {
$('.indentation', this.children[n])
.removeClass('tree-child')
.removeClass('tree-child-first')
.removeClass('tree-child-last')
.removeClass('tree-child-horizontal');
}
};
/**
* Add an asterisk or other marker to the changed row.
*/
Drupal.tableDrag.prototype.row.prototype.markChanged = function () {
var marker = Drupal.theme('tableDragChangedMarker');
var cell = $('td:first', this.element);
if ($('span.tabledrag-changed', cell).length == 0) {
cell.append(marker);
}
};
/**
* Stub function. Allows a custom handler when a row is indented.
*/
Drupal.tableDrag.prototype.row.prototype.onIndent = function () {
return null;
};
/**
* Stub function. Allows a custom handler when a row is swapped.
*/
Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) {
return null;
};
Drupal.theme.prototype.tableDragChangedMarker = function () {
return '<span class="warning tabledrag-changed">*</span>';
};
Drupal.theme.prototype.tableDragIndentation = function () {
return '<div class="indentation"> </div>';
};
Drupal.theme.prototype.tableDragChangedWarning = function () {
return '<div class="tabledrag-changed-warning messages warning">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t('Changes made in this table will not be saved until the form is submitted.') + '</div>';
};
})(jQuery);
;
(function ($) {
/**
* Attaches double-click behavior to toggle full path of Krumo elements.
*/
Drupal.behaviors.devel = {
attach: function (context, settings) {
// Add hint to footnote
$('.krumo-footnote .krumo-call').before('<img style="vertical-align: middle;" title="Click to expand. Double-click to show path." src="' + Drupal.settings.basePath + 'misc/help.png"/>');
var krumo_name = [];
var krumo_type = [];
function krumo_traverse(el) {
krumo_name.push($(el).html());
krumo_type.push($(el).siblings('em').html().match(/\w*/)[0]);
if ($(el).closest('.krumo-nest').length > 0) {
krumo_traverse($(el).closest('.krumo-nest').prev().find('.krumo-name'));
}
}
$('.krumo-child > div:first-child', context).dblclick(
function(e) {
if ($(this).find('> .krumo-php-path').length > 0) {
// Remove path if shown.
$(this).find('> .krumo-php-path').remove();
}
else {
// Get elements.
krumo_traverse($(this).find('> a.krumo-name'));
// Create path.
var krumo_path_string = '';
for (var i = krumo_name.length - 1; i >= 0; --i) {
// Start element.
if ((krumo_name.length - 1) == i)
krumo_path_string += '$' + krumo_name[i];
if (typeof krumo_name[(i-1)] !== 'undefined') {
if (krumo_type[i] == 'Array') {
krumo_path_string += "[";
if (!/^\d*$/.test(krumo_name[(i-1)]))
krumo_path_string += "'";
krumo_path_string += krumo_name[(i-1)];
if (!/^\d*$/.test(krumo_name[(i-1)]))
krumo_path_string += "'";
krumo_path_string += "]";
}
if (krumo_type[i] == 'Object')
krumo_path_string += '->' + krumo_name[(i-1)];
}
}
$(this).append('<div class="krumo-php-path" style="font-family: Courier, monospace; font-weight: bold;">' + krumo_path_string + '</div>');
// Reset arrays.
krumo_name = [];
krumo_type = [];
}
}
);
}
};
})(jQuery);
;
(function ($) {
/**
* A progressbar object. Initialized with the given id. Must be inserted into
* the DOM afterwards through progressBar.element.
*
* method is the function which will perform the HTTP request to get the
* progress bar state. Either "GET" or "POST".
*
* e.g. pb = new progressBar('myProgressBar');
* some_element.appendChild(pb.element);
*/
Drupal.progressBar = function (id, updateCallback, method, errorCallback) {
var pb = this;
this.id = id;
this.method = method || 'GET';
this.updateCallback = updateCallback;
this.errorCallback = errorCallback;
// The WAI-ARIA setting aria-live="polite" will announce changes after users
// have completed their current activity and not interrupt the screen reader.
this.element = $('<div class="progress" aria-live="polite"></div>').attr('id', id);
this.element.html('<div class="bar"><div class="filled"></div></div>' +
'<div class="percentage"></div>' +
'<div class="message"> </div>');
};
/**
* Set the percentage and status message for the progressbar.
*/
Drupal.progressBar.prototype.setProgress = function (percentage, message) {
if (percentage >= 0 && percentage <= 100) {
$('div.filled', this.element).css('width', percentage + '%');
$('div.percentage', this.element).html(percentage + '%');
}
$('div.message', this.element).html(message);
if (this.updateCallback) {
this.updateCallback(percentage, message, this);
}
};
/**
* Start monitoring progress via Ajax.
*/
Drupal.progressBar.prototype.startMonitoring = function (uri, delay) {
this.delay = delay;
this.uri = uri;
this.sendPing();
};
/**
* Stop monitoring progress via Ajax.
*/
Drupal.progressBar.prototype.stopMonitoring = function () {
clearTimeout(this.timer);
// This allows monitoring to be stopped from within the callback.
this.uri = null;
};
/**
* Request progress data from server.
*/
Drupal.progressBar.prototype.sendPing = function () {
if (this.timer) {
clearTimeout(this.timer);
}
if (this.uri) {
var pb = this;
// When doing a post request, you need non-null data. Otherwise a
// HTTP 411 or HTTP 406 (with Apache mod_security) error may result.
$.ajax({
type: this.method,
url: this.uri,
data: '',
dataType: 'json',
success: function (progress) {
// Display errors.
if (progress.status == 0) {
pb.displayError(progress.data);
return;
}
// Update display.
pb.setProgress(progress.percentage, progress.message);
// Schedule next timer.
pb.timer = setTimeout(function () { pb.sendPing(); }, pb.delay);
},
error: function (xmlhttp) {
pb.displayError(Drupal.ajaxError(xmlhttp, pb.uri));
}
});
}
};
/**
* Display errors on the page.
*/
Drupal.progressBar.prototype.displayError = function (string) {
var error = $('<div class="messages error"></div>').html(string);
$(this.element).before(error).hide();
if (this.errorCallback) {
this.errorCallback(this);
}
};
})(jQuery);
;
(function ($) {
/**
* Attaches sticky table headers.
*/
Drupal.behaviors.tableHeader = {
attach: function (context, settings) {
if (!$.support.positionFixed) {
return;
}
$('table.sticky-enabled', context).once('tableheader', function () {
$(this).data("drupal-tableheader", new Drupal.tableHeader(this));
});
}
};
/**
* Constructor for the tableHeader object. Provides sticky table headers.
*
* @param table
* DOM object for the table to add a sticky header to.
*/
Drupal.tableHeader = function (table) {
var self = this;
this.originalTable = $(table);
this.originalHeader = $(table).children('thead');
this.originalHeaderCells = this.originalHeader.find('> tr > th');
this.displayWeight = null;
// React to columns change to avoid making checks in the scroll callback.
this.originalTable.bind('columnschange', function (e, display) {
// This will force header size to be calculated on scroll.
self.widthCalculated = (self.displayWeight !== null && self.displayWeight === display);
self.displayWeight = display;
});
// Clone the table header so it inherits original jQuery properties. Hide
// the table to avoid a flash of the header clone upon page load.
this.stickyTable = $('<table class="sticky-header"/>')
.insertBefore(this.originalTable)
.css({ position: 'fixed', top: '0px' });
this.stickyHeader = this.originalHeader.clone(true)
.hide()
.appendTo(this.stickyTable);
this.stickyHeaderCells = this.stickyHeader.find('> tr > th');
this.originalTable.addClass('sticky-table');
$(window)
.bind('scroll.drupal-tableheader', $.proxy(this, 'eventhandlerRecalculateStickyHeader'))
.bind('resize.drupal-tableheader', { calculateWidth: true }, $.proxy(this, 'eventhandlerRecalculateStickyHeader'))
// Make sure the anchor being scrolled into view is not hidden beneath the
// sticky table header. Adjust the scrollTop if it does.
.bind('drupalDisplaceAnchor.drupal-tableheader', function () {
window.scrollBy(0, -self.stickyTable.outerHeight());
})
// Make sure the element being focused is not hidden beneath the sticky
// table header. Adjust the scrollTop if it does.
.bind('drupalDisplaceFocus.drupal-tableheader', function (event) {
if (self.stickyVisible && event.clientY < (self.stickyOffsetTop + self.stickyTable.outerHeight()) && event.$target.closest('sticky-header').length === 0) {
window.scrollBy(0, -self.stickyTable.outerHeight());
}
})
.triggerHandler('resize.drupal-tableheader');
// We hid the header to avoid it showing up erroneously on page load;
// we need to unhide it now so that it will show up when expected.
this.stickyHeader.show();
};
/**
* Event handler: recalculates position of the sticky table header.
*
* @param event
* Event being triggered.
*/
Drupal.tableHeader.prototype.eventhandlerRecalculateStickyHeader = function (event) {
var self = this;
var calculateWidth = event.data && event.data.calculateWidth;
// Reset top position of sticky table headers to the current top offset.
this.stickyOffsetTop = Drupal.settings.tableHeaderOffset ? eval(Drupal.settings.tableHeaderOffset + '()') : 0;
this.stickyTable.css('top', this.stickyOffsetTop + 'px');
// Save positioning data.
var viewHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
if (calculateWidth || this.viewHeight !== viewHeight) {
this.viewHeight = viewHeight;
this.vPosition = this.originalTable.offset().top - 4 - this.stickyOffsetTop;
this.hPosition = this.originalTable.offset().left;
this.vLength = this.originalTable[0].clientHeight - 100;
calculateWidth = true;
}
// Track horizontal positioning relative to the viewport and set visibility.
var hScroll = document.documentElement.scrollLeft || document.body.scrollLeft;
var vOffset = (document.documentElement.scrollTop || document.body.scrollTop) - this.vPosition;
this.stickyVisible = vOffset > 0 && vOffset < this.vLength;
this.stickyTable.css({ left: (-hScroll + this.hPosition) + 'px', visibility: this.stickyVisible ? 'visible' : 'hidden' });
// Only perform expensive calculations if the sticky header is actually
// visible or when forced.
if (this.stickyVisible && (calculateWidth || !this.widthCalculated)) {
this.widthCalculated = true;
var $that = null;
var $stickyCell = null;
var display = null;
var cellWidth = null;
// Resize header and its cell widths.
// Only apply width to visible table cells. This prevents the header from
// displaying incorrectly when the sticky header is no longer visible.
for (var i = 0, il = this.originalHeaderCells.length; i < il; i += 1) {
$that = $(this.originalHeaderCells[i]);
$stickyCell = this.stickyHeaderCells.eq($that.index());
display = $that.css('display');
if (display !== 'none') {
cellWidth = $that.css('width');
// Exception for IE7.
if (cellWidth === 'auto') {
cellWidth = $that[0].clientWidth + 'px';
}
$stickyCell.css({'width': cellWidth, 'display': display});
}
else {
$stickyCell.css('display', 'none');
}
}
this.stickyTable.css('width', this.originalTable.css('width'));
}
};
})(jQuery);
;
/**
* @file
* Attaches the behaviors for the Field UI module.
*/
(function($) {
Drupal.behaviors.fieldUIFieldOverview = {
attach: function (context, settings) {
$('table#field-overview', context).once('field-overview', function () {
Drupal.fieldUIFieldOverview.attachUpdateSelects(this, settings);
});
}
};
Drupal.fieldUIFieldOverview = {
/**
* Implements dependent select dropdowns on the 'Manage fields' screen.
*/
attachUpdateSelects: function(table, settings) {
var widgetTypes = settings.fieldWidgetTypes;
var fields = settings.fields;
// Store the default text of widget selects.
$('.widget-type-select', table).each(function () {
this.initialValue = this.options[0].text;
});
// 'Field type' select updates its 'Widget' select.
$('.field-type-select', table).each(function () {
this.targetSelect = $('.widget-type-select', $(this).closest('tr'));
$(this).bind('change keyup', function () {
var selectedFieldType = this.options[this.selectedIndex].value;
var options = (selectedFieldType in widgetTypes ? widgetTypes[selectedFieldType] : []);
this.targetSelect.fieldUIPopulateOptions(options);
});
// Trigger change on initial pageload to get the right widget options
// when field type comes pre-selected (on failed validation).
$(this).trigger('change', false);
});
// 'Existing field' select updates its 'Widget' select and 'Label' textfield.
$('.field-select', table).each(function () {
this.targetSelect = $('.widget-type-select', $(this).closest('tr'));
this.targetTextfield = $('.label-textfield', $(this).closest('tr'));
this.targetTextfield
.data('field_ui_edited', false)
.bind('keyup', function (e) {
$(this).data('field_ui_edited', $(this).val() != '');
});
$(this).bind('change keyup', function (e, updateText) {
var updateText = (typeof updateText == 'undefined' ? true : updateText);
var selectedField = this.options[this.selectedIndex].value;
var selectedFieldType = (selectedField in fields ? fields[selectedField].type : null);
var selectedFieldWidget = (selectedField in fields ? fields[selectedField].widget : null);
var options = (selectedFieldType && (selectedFieldType in widgetTypes) ? widgetTypes[selectedFieldType] : []);
this.targetSelect.fieldUIPopulateOptions(options, selectedFieldWidget);
// Only overwrite the "Label" input if it has not been manually
// changed, or if it is empty.
if (updateText && !this.targetTextfield.data('field_ui_edited')) {
this.targetTextfield.val(selectedField in fields ? fields[selectedField].label : '');
}
});
// Trigger change on initial pageload to get the right widget options
// and label when field type comes pre-selected (on failed validation).
$(this).trigger('change', false);
});
}
};
/**
* Populates options in a select input.
*/
jQuery.fn.fieldUIPopulateOptions = function (options, selected) {
return this.each(function () {
var disabled = false;
if (options.length == 0) {
options = [this.initialValue];
disabled = true;
}
// If possible, keep the same widget selected when changing field type.
// This is based on textual value, since the internal value might be
// different (options_buttons vs. node_reference_buttons).
var previousSelectedText = this.options[this.selectedIndex].text;
var html = '';
jQuery.each(options, function (value, text) {
// Figure out which value should be selected. The 'selected' param
// takes precedence.
var is_selected = ((typeof selected != 'undefined' && value == selected) || (typeof selected == 'undefined' && text == previousSelectedText));
html += '<option value="' + value + '"' + (is_selected ? ' selected="selected"' : '') + '>' + text + '</option>';
});
$(this).html(html).attr('disabled', disabled ? 'disabled' : false);
});
};
Drupal.behaviors.fieldUIDisplayOverview = {
attach: function (context, settings) {
$('table#field-display-overview', context).once('field-display-overview', function() {
Drupal.fieldUIOverview.attach(this, settings.fieldUIRowsData, Drupal.fieldUIDisplayOverview);
});
}
};
Drupal.fieldUIOverview = {
/**
* Attaches the fieldUIOverview behavior.
*/
attach: function (table, rowsData, rowHandlers) {
var tableDrag = Drupal.tableDrag[table.id];
// Add custom tabledrag callbacks.
tableDrag.onDrop = this.onDrop;
tableDrag.row.prototype.onSwap = this.onSwap;
// Create row handlers.
$('tr.draggable', table).each(function () {
// Extract server-side data for the row.
var row = this;
if (row.id in rowsData) {
var data = rowsData[row.id];
data.tableDrag = tableDrag;
// Create the row handler, make it accessible from the DOM row element.
var rowHandler = new rowHandlers[data.rowHandler](row, data);
$(row).data('fieldUIRowHandler', rowHandler);
}
});
},
/**
* Event handler to be attached to form inputs triggering a region change.
*/
onChange: function () {
var $trigger = $(this);
var row = $trigger.closest('tr').get(0);
var rowHandler = $(row).data('fieldUIRowHandler');
var refreshRows = {};
refreshRows[rowHandler.name] = $trigger.get(0);
// Handle region change.
var region = rowHandler.getRegion();
if (region != rowHandler.region) {
// Remove parenting.
$('select.field-parent', row).val('');
// Let the row handler deal with the region change.
$.extend(refreshRows, rowHandler.regionChange(region));
// Update the row region.
rowHandler.region = region;
}
// Ajax-update the rows.
Drupal.fieldUIOverview.AJAXRefreshRows(refreshRows);
},
/**
* Lets row handlers react when a row is dropped into a new region.
*/
onDrop: function () {
var dragObject = this;
var row = dragObject.rowObject.element;
var rowHandler = $(row).data('fieldUIRowHandler');
if (rowHandler !== undefined) {
var regionRow = $(row).prevAll('tr.region-message').get(0);
var region = regionRow.className.replace(/([^ ]+[ ]+)*region-([^ ]+)-message([ ]+[^ ]+)*/, '$2');
if (region != rowHandler.region) {
// Let the row handler deal with the region change.
refreshRows = rowHandler.regionChange(region);
// Update the row region.
rowHandler.region = region;
// Ajax-update the rows.
Drupal.fieldUIOverview.AJAXRefreshRows(refreshRows);
}
}
},
/**
* Refreshes placeholder rows in empty regions while a row is being dragged.
*
* Copied from block.js.
*
* @param table
* The table DOM element.
* @param rowObject
* The tableDrag rowObject for the row being dragged.
*/
onSwap: function (draggedRow) {
var rowObject = this;
$('tr.region-message', rowObject.table).each(function () {
// If the dragged row is in this region, but above the message row, swap
// it down one space.
if ($(this).prev('tr').get(0) == rowObject.group[rowObject.group.length - 1]) {
// Prevent a recursion problem when using the keyboard to move rows up.
if ((rowObject.method != 'keyboard' || rowObject.direction == 'down')) {
rowObject.swap('after', this);
}
}
// This region has become empty.
if ($(this).next('tr').is(':not(.draggable)') || $(this).next('tr').length == 0) {
$(this).removeClass('region-populated').addClass('region-empty');
}
// This region has become populated.
else if ($(this).is('.region-empty')) {
$(this).removeClass('region-empty').addClass('region-populated');
}
});
},
/**
* Triggers Ajax refresh of selected rows.
*
* The 'format type' selects can trigger a series of changes in child rows.
* The #ajax behavior is therefore not attached directly to the selects, but
* triggered manually through a hidden #ajax 'Refresh' button.
*
* @param rows
* A hash object, whose keys are the names of the rows to refresh (they
* will receive the 'ajax-new-content' effect on the server side), and
* whose values are the DOM element in the row that should get an Ajax
* throbber.
*/
AJAXRefreshRows: function (rows) {
// Separate keys and values.
var rowNames = [];
var ajaxElements = [];
$.each(rows, function (rowName, ajaxElement) {
rowNames.push(rowName);
ajaxElements.push(ajaxElement);
});
if (rowNames.length) {
// Add a throbber next each of the ajaxElements.
var $throbber = $('<div class="ajax-progress ajax-progress-throbber"><div class="throbber"> </div></div>');
$(ajaxElements)
.addClass('progress-disabled')
.after($throbber);
// Fire the Ajax update.
$('input[name=refresh_rows]').val(rowNames.join(' '));
$('input#edit-refresh').mousedown();
// Disabled elements do not appear in POST ajax data, so we mark the
// elements disabled only after firing the request.
$(ajaxElements).attr('disabled', true);
}
}
};
/**
* Row handlers for the 'Manage display' screen.
*/
Drupal.fieldUIDisplayOverview = {};
/**
* Constructor for a 'field' row handler.
*
* This handler is used for both fields and 'extra fields' rows.
*
* @param row
* The row DOM element.
* @param data
* Additional data to be populated in the constructed object.
*/
Drupal.fieldUIDisplayOverview.field = function (row, data) {
this.row = row;
this.name = data.name;
this.region = data.region;
this.tableDrag = data.tableDrag;
// Attach change listener to the 'formatter type' select.
this.$formatSelect = $('select.field-formatter-type', row);
this.$formatSelect.change(Drupal.fieldUIOverview.onChange);
return this;
};
Drupal.fieldUIDisplayOverview.field.prototype = {
/**
* Returns the region corresponding to the current form values of the row.
*/
getRegion: function () {
return (this.$formatSelect.val() == 'hidden') ? 'hidden' : 'visible';
},
/**
* Reacts to a row being changed regions.
*
* This function is called when the row is moved to a different region, as a
* result of either :
* - a drag-and-drop action (the row's form elements then probably need to be
* updated accordingly)
* - user input in one of the form elements watched by the
* Drupal.fieldUIOverview.onChange change listener.
*
* @param region
* The name of the new region for the row.
* @return
* A hash object indicating which rows should be Ajax-updated as a result
* of the change, in the format expected by
* Drupal.displayOverview.AJAXRefreshRows().
*/
regionChange: function (region) {
// When triggered by a row drag, the 'format' select needs to be adjusted
// to the new region.
var currentValue = this.$formatSelect.val();
switch (region) {
case 'visible':
if (currentValue == 'hidden') {
// Restore the formatter back to the default formatter. Pseudo-fields do
// not have default formatters, we just return to 'visible' for those.
var value = (this.defaultFormatter != undefined) ? this.defaultFormatter : 'visible';
}
break;
default:
var value = 'hidden';
break;
}
if (value != undefined) {
this.$formatSelect.val(value);
}
var refreshRows = {};
refreshRows[this.name] = this.$formatSelect.get(0);
return refreshRows;
}
};
})(jQuery);
;
(function($) {
Drupal.behaviors.fieldUIFieldsOverview = {
attach: function (context, settings) {
$('table#field-overview', context).once('field-field-overview', function() {
Drupal.fieldUIOverview.attach(this, settings.fieldUIRowsData, Drupal.fieldUIFieldOverview);
});
}
};
/**
* Row handlers for the 'Manage fields' screen.
*/
Drupal.fieldUIFieldOverview = Drupal.fieldUIFieldOverview || {};
Drupal.fieldUIFieldOverview.group = function(row, data) {
this.row = row;
this.name = data.name;
this.region = data.region;
this.tableDrag = data.tableDrag;
// Attach change listener to the 'group format' select.
this.$formatSelect = $('select.field-group-type', row);
this.$formatSelect.change(Drupal.fieldUIOverview.onChange);
return this;
};
Drupal.fieldUIFieldOverview.group.prototype = {
getRegion: function () {
return 'main';
},
regionChange: function (region, recurse) {
return {};
},
regionChangeFields: function (region, element, refreshRows) {
// Create a new tabledrag rowObject, that will compute the group's child
// rows for us.
var tableDrag = element.tableDrag;
rowObject = new tableDrag.row(element.row, 'mouse', true);
// Skip the main row, we handled it above.
rowObject.group.shift();
// Let child rows handlers deal with the region change - without recursing
// on nested group rows, we are handling them all here.
$.each(rowObject.group, function() {
var childRow = this;
var childRowHandler = $(childRow).data('fieldUIRowHandler');
$.extend(refreshRows, childRowHandler.regionChange(region, false));
});
}
};
/**
* Row handlers for the 'Manage display' screen.
*/
Drupal.fieldUIDisplayOverview = Drupal.fieldUIDisplayOverview || {};
Drupal.fieldUIDisplayOverview.group = function(row, data) {
this.row = row;
this.name = data.name;
this.region = data.region;
this.tableDrag = data.tableDrag;
// Attach change listener to the 'group format' select.
this.$formatSelect = $('select.field-group-type', row);
this.$formatSelect.change(Drupal.fieldUIOverview.onChange);
return this;
};
Drupal.fieldUIDisplayOverview.group.prototype = {
getRegion: function () {
return (this.$formatSelect.val() == 'hidden') ? 'hidden' : 'visible';
},
regionChange: function (region, recurse) {
// Default recurse to true.
recurse = (recurse == undefined) || recurse;
// When triggered by a row drag, the 'format' select needs to be adjusted to
// the new region.
var currentValue = this.$formatSelect.val();
switch (region) {
case 'visible':
if (currentValue == 'hidden') {
// Restore the group format back to 'fieldset'.
var value = 'fieldset';
}
break;
default:
var value = 'hidden';
break;
}
if (value != undefined) {
this.$formatSelect.val(value);
}
var refreshRows = {};
refreshRows[this.name] = this.$formatSelect.get(0);
if (recurse) {
this.regionChangeFields(region, this, refreshRows);
}
return refreshRows;
},
regionChangeFields: function (region, element, refreshRows) {
// Create a new tabledrag rowObject, that will compute the group's child
// rows for us.
var tableDrag = element.tableDrag;
rowObject = new tableDrag.row(element.row, 'mouse', true);
// Skip the main row, we handled it above.
rowObject.group.shift();
// Let child rows handlers deal with the region change - without recursing
// on nested group rows, we are handling them all here.
$.each(rowObject.group, function() {
var childRow = this;
var childRowHandler = $(childRow).data('fieldUIRowHandler');
$.extend(refreshRows, childRowHandler.regionChange(region, false));
});
}
};
})(jQuery);;
(function ($) {
/**
* Toggle the visibility of a fieldset using smooth animations.
*/
Drupal.toggleFieldset = function (fieldset) {
var $fieldset = $(fieldset);
if ($fieldset.is('.collapsed')) {
var $content = $('> .fieldset-wrapper', fieldset).hide();
$fieldset
.removeClass('collapsed')
.trigger({ type: 'collapsed', value: false })
.find('> legend span.fieldset-legend-prefix').html(Drupal.t('Hide'));
$content.slideDown({
duration: 'fast',
easing: 'linear',
complete: function () {
Drupal.collapseScrollIntoView(fieldset);
fieldset.animating = false;
},
step: function () {
// Scroll the fieldset into view.
Drupal.collapseScrollIntoView(fieldset);
}
});
}
else {
$fieldset.trigger({ type: 'collapsed', value: true });
$('> .fieldset-wrapper', fieldset).slideUp('fast', function () {
$fieldset
.addClass('collapsed')
.find('> legend span.fieldset-legend-prefix').html(Drupal.t('Show'));
fieldset.animating = false;
});
}
};
/**
* Scroll a given fieldset into view as much as possible.
*/
Drupal.collapseScrollIntoView = function (node) {
var h = document.documentElement.clientHeight || document.body.clientHeight || 0;
var offset = document.documentElement.scrollTop || document.body.scrollTop || 0;
var posY = $(node).offset().top;
var fudge = 55;
if (posY + node.offsetHeight + fudge > h + offset) {
if (node.offsetHeight > h) {
window.scrollTo(0, posY);
}
else {
window.scrollTo(0, posY + node.offsetHeight - h + fudge);
}
}
};
Drupal.behaviors.collapse = {
attach: function (context, settings) {
$('fieldset.collapsible', context).once('collapse', function () {
var $fieldset = $(this);
// Expand fieldset if there are errors inside, or if it contains an
// element that is targeted by the uri fragment identifier.
var anchor = location.hash && location.hash != '#' ? ', ' + location.hash : '';
if ($('.error' + anchor, $fieldset).length) {
$fieldset.removeClass('collapsed');
}
var summary = $('<span class="summary"></span>');
$fieldset.
bind('summaryUpdated', function () {
var text = $.trim($fieldset.drupalGetSummary());
summary.html(text ? ' (' + text + ')' : '');
})
.trigger('summaryUpdated');
// Turn the legend into a clickable link, but retain span.fieldset-legend
// for CSS positioning.
var $legend = $('> legend .fieldset-legend', this);
$('<span class="fieldset-legend-prefix element-invisible"></span>')
.append($fieldset.hasClass('collapsed') ? Drupal.t('Show') : Drupal.t('Hide'))
.prependTo($legend)
.after(' ');
// .wrapInner() does not retain bound events.
var $link = $('<a class="fieldset-title" href="#"></a>')
.prepend($legend.contents())
.appendTo($legend)
.click(function () {
var fieldset = $fieldset.get(0);
// Don't animate multiple times.
if (!fieldset.animating) {
fieldset.animating = true;
Drupal.toggleFieldset(fieldset);
}
return false;
});
$legend.append(summary);
});
}
};
})(jQuery);
;
(function ($) {
/**
* Retrieves the summary for the first element.
*/
$.fn.drupalGetSummary = function () {
var callback = this.data('summaryCallback');
return (this[0] && callback) ? $.trim(callback(this[0])) : '';
};
/**
* Sets the summary for all matched elements.
*
* @param callback
* Either a function that will be called each time the summary is
* retrieved or a string (which is returned each time).
*/
$.fn.drupalSetSummary = function (callback) {
var self = this;
// To facilitate things, the callback should always be a function. If it's
// not, we wrap it into an anonymous function which just returns the value.
if (typeof callback != 'function') {
var val = callback;
callback = function () { return val; };
}
return this
.data('summaryCallback', callback)
// To prevent duplicate events, the handlers are first removed and then
// (re-)added.
.unbind('formUpdated.summary')
.bind('formUpdated.summary', function () {
self.trigger('summaryUpdated');
})
// The actual summaryUpdated handler doesn't fire when the callback is
// changed, so we have to do this manually.
.trigger('summaryUpdated');
};
/**
* Sends a 'formUpdated' event each time a form element is modified.
*/
Drupal.behaviors.formUpdated = {
attach: function (context) {
// These events are namespaced so that we can remove them later.
var events = 'change.formUpdated click.formUpdated blur.formUpdated keyup.formUpdated';
$(context)
// Since context could be an input element itself, it's added back to
// the jQuery object and filtered again.
.find(':input').andSelf().filter(':input')
// To prevent duplicate events, the handlers are first removed and then
// (re-)added.
.unbind(events).bind(events, function () {
$(this).trigger('formUpdated');
});
}
};
/**
* Prepopulate form fields with information from the visitor cookie.
*/
Drupal.behaviors.fillUserInfoFromCookie = {
attach: function (context, settings) {
$('form.user-info-from-cookie').once('user-info-from-cookie', function () {
var formContext = this;
$.each(['name', 'mail', 'homepage'], function () {
var $element = $('[name=' + this + ']', formContext);
var cookie = $.cookie('Drupal.visitor.' + this);
if ($element.length && cookie) {
$element.val(cookie);
}
});
});
}
};
})(jQuery);
;
|
RomoneMc/Recipe-Gallery
|
sites/default/files/js/js_p7-hDFwYvA-RBYGgLZFH8qPEhYOYXitPMjsrOJUZZO4.js
|
JavaScript
|
gpl-2.0
| 74,044
|
#!/usr/bin/env lua
-- -*-lua-*-
--
-- $Id: dhcpv6codec_spec.lua $
--
-- Author: Markus Stenberg <markus stenberg@iki.fi>
--
-- Copyright (c) 2013 cisco Systems, Inc.
--
-- Created: Wed Feb 20 18:24:16 2013 mstenber
-- Last modified: Mon Apr 29 11:11:04 2013 mstenber
-- Edit time: 38 min
--
require "busted"
require "dhcpv6_codec"
local dhcpv6_message = dhcpv6_codec.dhcpv6_message
local known_messages = {
-- solicit
{"014f6ef30001000e0001000118b77eb3ee6e75234e2800060004001700180008000200000019000c75234e2800000e1000001518",
{
type=dhcpv6_const.MT_SOLICIT, xid=5205747,
[1]={data="0001000118b77eb3ee6e75234e28",
option=dhcpv6_const.O_CLIENTID},
[2]={option=dhcpv6_const.O_ORO,
[1]=dhcpv6_const.O_DNS_RNS, [2]=dhcpv6_const.O_DOMAIN_SEARCH,
},
[3]={value=0, option=8},
[4]={iaid=1965248040, option=dhcpv6_const.O_IA_PD, t1=3600, t2=5400},
}
},
-- solicit (IA_NA)
{'01ab1a5b0001000e0001000118c086efeeba7b99bca50008000200000003000c7b99bca500000e1000001518',
{[1]={data="0001000118c086efeeba7b99bca5", option=1},
[2]={option=8, value=0},
[3]={iaid=2073672869, option=3, t1=3600, t2=5400},
type=1, xid=11213403}
},
-- advertise
{"024f6ef30019004575234e2800000e1000001518001a001900000e1000001c20382000deadbee05c000000000000000000000d0018000041737369676e6564203120707265666978286573292e0002000e0001000118b4e92e4e65b47f205e0001000e0001000118b77eb3ee6e75234e280007000100001700102000000000000000000000000000000200180014027636036c6162076578616d706c6503636f6d00",
{
type=dhcpv6_const.MT_ADVERTISE, xid=5205747,
[1]={
option=dhcpv6_const.O_IA_PD,
iaid=1965248040, t1=3600, t2=5400,
[1]={option=dhcpv6_const.O_IAPREFIX,
preferred=3600, prefix="2000:dead:bee0:5c00::/56",
valid=7200},
[2]={code=0, message="Assigned 1 prefix(es).", option=13},
},
[2]={data="0001000118b4e92e4e65b47f205e", option=dhcpv6_const.O_SERVERID},
[3]={data="0001000118b77eb3ee6e75234e28", option=dhcpv6_const.O_CLIENTID},
[4]={option=dhcpv6_const.O_PREFERENCE, value=0},
[5]={[1]="2000::2", option=dhcpv6_const.O_DNS_RNS},
[6]={[1]={"v6", "lab", "example", "com"}, option=dhcpv6_const.O_DOMAIN_SEARCH},
},
},
-- advertise (IA_NA)
{'02ab1a5b0001000e0001000118c086efeeba7b99bca50002000e0001000118c086da1a2e8c1654c9000300417b99bca50000070800000c4e000500182000deadbee0005300000000000000a600000e1000000e10000d001500004f68206861692066726f6d20646e736d6173710007000100001700102000deadbee00053182e8cfffe1654c9',
{[1]={data="0001000118c086efeeba7b99bca5", option=1},
[2]={data="0001000118c086da1a2e8c1654c9", option=2},
[3]={[1]={addr="2000:dead:bee0:53::a6",
option=5, preferred=3600, valid=3600},
[2]={code=0, message="Oh hai from dnsmasq", option=13},
iaid=2073672869, option=3, t1=1800, t2=3150},
[4]={option=7, value=0},
[5]={[1]="2000:dead:bee0:53:182e:8cff:fe16:54c9", option=23},
type=2, xid=11213403}
},
-- request
{'03c050b00001000e0001000118b77eb3ee6e75234e280002000e0001000118b4e92e4e65b47f205e00060004001700180008000200000019002975234e2800000e1000001518001a001900001c2000001d4c382000deadbee05c000000000000000000',
{
type=3, xid=12603568,
[1]={data="0001000118b77eb3ee6e75234e28", option=1},
[2]={data="0001000118b4e92e4e65b47f205e", option=2},
[3]={[1]=23, [2]=24, option=6},
[4]={option=8, value=0},
[5]={[1]={option=26, preferred=7200, prefix="2000:dead:bee0:5c00::/56", valid=7500}, iaid=1965248040, option=25, t1=3600, t2=5400},
},
},
-- reply
{'07c050b00019004575234e2800000e1000001518001a001900000e1000001c20382000deadbee05c000000000000000000000d0018000041737369676e6564203120707265666978286573292e0002000e0001000118b4e92e4e65b47f205e0001000e0001000118b77eb3ee6e75234e280007000100001700102000000000000000000000000000000200180014027636036c6162076578616d706c6503636f6d00', nil
},
-- rebind
{'068e237d0001000e0001000118b77eb3ee6e75234e2800060004001700180008000200000019002975234e2800000e1000001518001a001900001c2000001d4c382000deadbee05c000000000000000000', nil,
},
-- reply
{'078e237d0019000c75234e2800000e10000015180002000e0001000118b4e92e4e65b47f205e0001000e0001000118b77eb3ee6e75234e280007000100001700102000000000000000000000000000000200180014027636036c6162076578616d706c6503636f6d00', nil,
},
-- info request
{'0ba34e900001000a00030001827f5ea42778000800020000',
{[1]={data="00030001827f5ea42778", option=1},
[2]={option=8, value=0},
type=11, xid=10702480},
},
}
describe("dhcpv6_message", function ()
it("endecode is sane", function ()
for i, v in ipairs(known_messages)
do
mst.d('iteration', i)
-- first try decode(h)
local h, r = unpack(v)
h = string.gsub(h, "\n", "")
local s = mst.hex_to_string(h)
local o, err = dhcpv6_message:decode(s)
mst.a(o, 'decode error', err)
-- then encode(decode(h)) == h?
local b = dhcpv6_message:encode(o)
mst.a(b == s, 'encode(decode(x)) != x!')
if r
then
mst.a(mst.repr_equal(r, o), 'mismatch', r, o)
else
mst.d('still no description for', o)
end
end
end)
end)
|
fingon/hnet-core
|
spec/dhcpv6_codec_spec.lua
|
Lua
|
gpl-2.0
| 5,748
|
#ifndef __TEXT_FILE_H__
#define __TEXT_FILE_H__
/*LICENSE_START*/
/*
* Copyright (C) 2014 Washington University School of Medicine
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/*LICENSE_END*/
#include <AString.h>
#include "DataFile.h"
namespace caret {
/**
* A simple text file.
*/
class TextFile : public DataFile {
public:
TextFile();
virtual ~TextFile();
private:
TextFile(const TextFile&);
TextFile& operator=(const TextFile&);
public:
virtual void clear();
virtual bool isEmpty() const;
virtual void readFile(const AString& filename);
virtual void writeFile(const AString& filename);
virtual AString toString() const;
AString getText() const;
std::vector<AString> getTextLines() const;
void replaceText(const AString& text);
void addText(const AString& text);
void addLine(const AString& text);
private:
AString text;
};
} // namespace
#endif // __TEXT_FILE_H__
|
Washington-University/workbench
|
src/Files/TextFile.h
|
C
|
gpl-2.0
| 1,869
|
//
// DotParser.h
// Project
//
// Created by ycc on 13-9-9.
//
//
#ifndef __Project__DotParser__
#define __Project__DotParser__
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <iostream>
#include <graphviz/cgraph.h>
using namespace std;
class DotNode;
class DotEdge
{
private:
Agedge_t *e;
public:
//Add Other attribute here, such as weight, label.
DotEdge(Agedge_t *_e);
DotNode GetHead();
DotNode GetTail();
};
class DotNode
{
public:
Agnode_t *n;
string label;
DotNode(Agnode_t *_n);
bool operator<(const DotNode &x) const; //used for map
};
class DotGraph
{
private:
Agraph_t *g;
map<DotNode, vector<DotEdge>*> OutputEdge;
map<DotNode, vector<DotEdge>*> InputEdge;
vector<DotEdge>& GetEdgeVec(DotNode n, bool IsIn);
public:
vector<DotNode> Node;
DotGraph(Agraph_t *_g);
DotGraph(string DotFile);
vector<DotEdge>& GetInEdgeVec(DotNode node); //get all input edge for node
vector<DotEdge>& GetOutEdgeVec(DotNode node); //get all output edge for node
};
#endif /* defined(__Project__DotParser__) */
|
yechencheng/LLVM_PASS
|
SGO/DotParser.h
|
C
|
gpl-2.0
| 1,126
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_67) on Tue Nov 18 14:49:14 CST 2014 -->
<title>com.flamingOctoIronman.library.math.vector Class Hierarchy</title>
<meta name="date" content="2014-11-18">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="com.flamingOctoIronman.library.math.vector Class Hierarchy";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../com/flamingOctoIronman/library/math/matrix/package-tree.html">Prev</a></li>
<li><a href="../../../../../com/flamingOctoIronman/subsystem/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/flamingOctoIronman/library/math/vector/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package com.flamingOctoIronman.library.math.vector</h1>
<span class="strong">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">com.flamingOctoIronman.library.math.vector.<a href="../../../../../com/flamingOctoIronman/library/math/vector/Vector.html" title="class in com.flamingOctoIronman.library.math.vector"><span class="strong">Vector</span></a></li>
<li type="circle">com.flamingOctoIronman.library.math.vector.<a href="../../../../../com/flamingOctoIronman/library/math/vector/VectorCalculations.html" title="class in com.flamingOctoIronman.library.math.vector"><span class="strong">VectorCalculations</span></a></li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../com/flamingOctoIronman/library/math/matrix/package-tree.html">Prev</a></li>
<li><a href="../../../../../com/flamingOctoIronman/subsystem/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/flamingOctoIronman/library/math/vector/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
fh3/flaming-octo-ironman
|
flaming-octo-ironman/doc/com/flamingOctoIronman/library/math/vector/package-tree.html
|
HTML
|
gpl-2.0
| 4,894
|
<?php
global $wpsc_query, $wpdb;
/*
* Most functions called in this page can be found in the wpsc_query.php file
*/
?>
<div id='products_page_container' class="wrap wpsc_container">
<?php if(wpsc_has_breadcrumbs()) : ?>
<div class='breadcrumb'>
<a href='<?php echo get_option('product_list_url'); ?>'><?php echo get_option('blogname'); ?></a> »
<?php while (wpsc_have_breadcrumbs()) : wpsc_the_breadcrumb(); ?>
<?php if(wpsc_breadcrumb_url()) :?>
<a href='<?php echo wpsc_breadcrumb_url(); ?>'><?php echo wpsc_breadcrumb_name(); ?></a> »
<?php else: ?>
<?php echo wpsc_breadcrumb_name(); ?>
<?php endif; ?>
<?php endwhile; ?>
</div>
<?php endif; ?>
<?php do_action('wpsc_top_of_products_page'); // Plugin hook for adding things to the top of the products page, like the live search ?>
<?php if(wpsc_display_categories()): ?>
<?php if(get_option('wpsc_category_grid_view') == 1) :?>
<div class='wpsc_categories wpsc_category_grid'>
<?php wpsc_start_category_query(array('category_group'=> get_option('wpsc_default_category'), 'show_thumbnails'=> 1)); ?>
<a href="<?php wpsc_print_category_url();?>" class="wpsc_category_grid_item" title='<?php wpsc_print_category_name();?>'>
<?php wpsc_print_category_image(45, 45); ?>
</a>
<?php wpsc_print_subcategory("", ""); ?>
<?php wpsc_end_category_query(); ?>
<div class='clear_category_group'></div>
</div>
<?php else:?>
<ul class='wpsc_categories'>
<?php wpsc_start_category_query(array('category_group'=> get_option('wpsc_default_category'), 'show_thumbnails'=> get_option('show_category_thumbnails'))); ?>
<li>
<?php wpsc_print_category_image(32, 32); ?>
<a href="<?php wpsc_print_category_url();?>" class="wpsc_category_link"><?php wpsc_print_category_name();?></a>
<?php if(get_option('wpsc_category_description')) :?>
<?php wpsc_print_category_description("<div class='wpsc_subcategory'>", "</div>"); ?>
<?php endif;?>
<?php wpsc_print_subcategory("<ul>", "</ul>"); ?>
</li>
<?php wpsc_end_category_query(); ?>
</ul>
<?php endif; ?>
<?php endif; ?>
<?php if(wpsc_display_products()): ?>
<?php if(wpsc_is_in_category()) : ?>
<div class='wpsc_category_details'>
<?php if(get_option('show_category_thumbnails') && wpsc_category_image()) : ?>
<img src='<?php echo wpsc_category_image(); ?>' alt='<?php echo wpsc_category_name(); ?>' title='<?php echo wpsc_category_name(); ?>' />
<?php endif; ?>
<?php if(get_option('wpsc_category_description') && wpsc_category_description()) : ?>
<?php echo wpsc_category_description(); ?>
<?php endif; ?>
</div>
<?php endif; ?>
<!-- Start Pagination -->
<?php if ( ( get_option( 'use_pagination' ) == 1 && ( get_option( 'wpsc_page_number_position' ) == 1 || get_option( 'wpsc_page_number_position' ) == 3 ) ) ) : ?>
<div class="wpsc_page_numbers">
<?php if ( wpsc_has_pages() ) : ?>
<div class="pagination-products-showing">Showing <?php echo wpsc_showing_products(); ?> of <?php echo wpsc_total_product_count(); ?> products</div>
<div class="pagination-pages"><?php echo wpsc_first_products_link( '« First', true ); ?> <?php echo wpsc_previous_products_link( '« Previous', true ); ?> <?php echo wpsc_pagination( 10 ); ?> <?php echo wpsc_next_products_link( 'Next »', true ); ?> <?php echo wpsc_last_products_link( 'Last »', true ); ?></div>
<?php endif; ?>
</div>
<?php endif; ?>
<!-- End Pagination -->
<?php /** start the product loop here */?>
<?php while (wpsc_have_products()) : wpsc_the_product(); ?>
<div class="productdisplay default_product_display product_view_<?php echo wpsc_the_product_id(); ?> <?php echo wpsc_category_class(); ?>">
<div class="textcol">
<?php if(get_option('show_thumbnails')) :?>
<div class="imagecol">
<?php if(wpsc_the_product_thumbnail()) :?>
<a rel="<?php echo str_replace(array(" ", '"',"'", '"','''), array("_", "", "", "",''), wpsc_the_product_title()); ?>" class="thickbox preview_link" href="<?php echo wpsc_the_product_image(); ?>">
<img class="product_image" id="product_image_<?php echo wpsc_the_product_id(); ?>" alt="<?php echo wpsc_the_product_title(); ?>" title="<?php echo wpsc_the_product_title(); ?>" src="<?php echo wpsc_the_product_thumbnail(); ?>"/>
</a>
<?php else: ?>
<div class="item_no_image">
<a href="<?php echo wpsc_the_product_permalink(); ?>">
<span>No Image Available</span>
</a>
</div>
<?php endif; ?>
</div>
<?php endif; ?>
<div class="producttext">
<h2 class="prodtitles">
<?php if(get_option('hide_name_link') == 1) : ?>
<span><?php echo wpsc_the_product_title(); ?></span>
<?php else: ?>
<a class="wpsc_product_title" href="<?php echo wpsc_the_product_permalink(); ?>"><?php echo wpsc_the_product_title(); ?></a>
<?php endif; ?>
<?php echo wpsc_edit_the_product_link(); ?>
</h2>
<?php
do_action('wpsc_product_before_description', wpsc_the_product_id(), $wpsc_query->product);
do_action('wpsc_product_addons', wpsc_the_product_id());
?>
<div class='wpsc_description'><?php echo wpsc_the_product_description(); ?></div>
<?php if(wpsc_the_product_additional_description()) : ?>
<div class='additional_description_span'>
<a href='<?php echo wpsc_the_product_permalink(); ?>' class='additional_description_link'>
<img class='additional_description_button' src='<?php echo WPSC_URL; ?>/images/icon_window_expand.gif' title='Additional Description' alt='Additional Description' /><?php echo __('More Details', 'wpsc'); ?>
</a>
<div class='additional_description'><br />
<?php
$value = '';
$the_addl_desc = wpsc_the_product_additional_description();
if( is_serialized($the_addl_desc) ) {
$addl_descriptions = @unserialize($the_addl_desc);
} else {
$addl_descriptions = array('addl_desc'=> $the_addl_desc);
}
if( isset($addl_descriptions['addl_desc']) ) {
$value = $addl_descriptions['addl_desc'];
}
if( function_exists('wpsc_addl_desc_show') ) {
echo wpsc_addl_desc_show( $addl_descriptions );
} else {
echo stripslashes( wpautop($the_addl_desc, $br=1));
}
?>
</div>
<br />
</div>
<?php endif; ?>
<?php if(wpsc_product_external_link(wpsc_the_product_id()) != '') : ?>
<?php $action = wpsc_product_external_link(wpsc_the_product_id()); ?>
<?php else: ?>
<?php $action = htmlentities(wpsc_this_page_url(),ENT_QUOTES); ?>
<?php endif; ?>
<form class='product_form' enctype="multipart/form-data" action="<?php echo $action; ?>" method="post" name="product_<?php echo wpsc_the_product_id(); ?>" id="product_<?php echo wpsc_the_product_id(); ?>" >
<?php do_action('wpsc_product_addon_after_descr', wpsc_the_product_id()); ?>
<?php /** the custom meta HTML and loop */?>
<div class="custom_meta">
<?php while (wpsc_have_custom_meta()) : wpsc_the_custom_meta();
if (stripos(wpsc_custom_meta_name(),'g:') !== FALSE){
continue;
}
?>
<strong><?php echo wpsc_custom_meta_name(); ?>: </strong><?php echo wpsc_custom_meta_value(); ?><br />
<?php endwhile; ?>
</div>
<?php /** the custom meta HTML and loop ends here */?>
<?php /** add the comment link here */?>
<?php echo wpsc_product_comment_link(); ?>
<?php /** the variation group HTML and loop */?>
<div class="wpsc_variation_forms">
<?php while (wpsc_have_variation_groups()) : wpsc_the_variation_group(); ?>
<p>
<label for="<?php echo wpsc_vargrp_form_id(); ?>"><?php echo wpsc_the_vargrp_name(); ?>:</label>
<?php /** the variation HTML and loop */?>
<select class='wpsc_select_variation' name="variation[<?php echo wpsc_vargrp_id(); ?>]" id="<?php echo wpsc_vargrp_form_id(); ?>">
<?php while (wpsc_have_variations()) : wpsc_the_variation(); ?>
<option value="<?php echo wpsc_the_variation_id(); ?>" <?php echo wpsc_the_variation_out_of_stock(); ?> ><?php echo wpsc_the_variation_name(); ?></option>
<?php endwhile; ?>
</select>
</p>
<?php endwhile; ?>
</div>
<?php /** the variation group HTML and loop ends here */?>
<!-- THIS IS THE QUANTITY OPTION MUST BE ENABLED FROM ADMIN SETTINGS -->
<?php if(wpsc_has_multi_adding()): ?>
<label class='wpsc_quantity_update' for='wpsc_quantity_update[<?php echo wpsc_the_product_id(); ?>]'><?php echo __('Quantity', 'wpsc'); ?>:</label>
<input type="text" id='wpsc_quantity_update[<?php echo wpsc_the_product_id(); ?>]' name="wpsc_quantity_update" size="2" value="1"/>
<input type="hidden" name="key" value="<?php echo wpsc_the_cart_item_key(); ?>"/>
<input type="hidden" name="wpsc_update_quantity" value="true"/>
<?php endif ;?>
<p class="wpsc_extras_forms"/>
<div class="wpsc_product_price">
<?php if(wpsc_product_is_donation()) : ?>
<label for='donation_price_<?php echo wpsc_the_product_id(); ?>'><?php echo __('Donation', 'wpsc'); ?>:</label>
<input type='text' id='donation_price_<?php echo wpsc_the_product_id(); ?>' name='donation_price' value='<?php echo $wpsc_query->product['price']; ?>' size='6' />
<br />
<?php else : ?>
<?php if(wpsc_product_on_special()) : ?>
<span class='oldprice'><?php echo __('Price', 'wpsc'); ?>: <?php echo wpsc_product_normal_price(get_option('wpsc_hide_decimals')); ?></span><br />
<?php endif; ?>
<span id="product_price_<?php echo wpsc_the_product_id(); ?>" class="pricedisplay"><?php echo wpsc_the_product_price(get_option('wpsc_hide_decimals')); ?></span><?php echo __('Price', 'wpsc'); ?>:<br/>
<?php if(get_option('display_pnp') == 1) : ?>
<span class="pricedisplay"><?php echo wpsc_product_postage_and_packaging(get_option('wpsc_hide_decimals')); ?></span><?php echo __('P&P', 'wpsc'); ?>: <br />
<?php endif; ?>
<?php endif; ?>
</div>
<input type="hidden" value="add_to_cart" name="wpsc_ajax_action"/>
<input type="hidden" value="<?php echo wpsc_the_product_id(); ?>" name="product_id"/>
<!-- END OF QUANTITY OPTION -->
<?php if((get_option('hide_addtocart_button') == 0) && (get_option('addtocart_or_buynow') !='1')) : ?>
<?php if(wpsc_product_has_stock()) : ?>
<div class='wpsc_buy_button_container'>
<?php if(wpsc_product_external_link(wpsc_the_product_id()) != '') : ?>
<?php $action = wpsc_product_external_link(wpsc_the_product_id()); ?>
<input class="wpsc_buy_button" type='button' value='<?php echo __('Buy Now', 'wpsc'); ?>' onclick='gotoexternallink("<?php echo $action; ?>")'>
<?php else: ?>
<input type='image' src='<?php echo WPSC_URL; ?>/themes/iShop/images/buy_button.gif' id='product_<?php echo wpsc_the_product_id(); ?>_submit_button' class='wpsc_buy_button' name='Buy' value="<?php echo __('Add To Cart', 'wpsc'); ?>" />
<?php endif; ?>
<div class='wpsc_loading_animation'>
<img title="Loading" alt="Loading" src="<?php echo WPSC_URL; ?>/images/indicator.gif" class="loadingimage"/>
<?php echo __('Updating cart...', 'wpsc'); ?>
</div>
</div>
<?php else : ?>
<p class='soldout'><?php echo __('This product has sold out.', 'wpsc'); ?></p>
<?php endif ; ?>
<?php endif ; ?>
</form>
<?php if((get_option('hide_addtocart_button') == 0) && (get_option('addtocart_or_buynow')=='1')) : ?>
<?php echo wpsc_buy_now_button(wpsc_the_product_id()); ?>
<?php endif ; ?>
<?php echo wpsc_product_rater(); ?>
<?php
if(function_exists('gold_shpcrt_display_gallery')) :
echo gold_shpcrt_display_gallery(wpsc_the_product_id(), true);
endif;
?>
</div>
</div>
</div>
<?php endwhile; ?>
<?php /** end the product loop here */?>
<?php if(wpsc_product_count() < 1):?>
<p><?php echo __('There are no products in this group.', 'wpsc'); ?></p>
<?php endif ; ?>
<?php
if(function_exists('fancy_notifications')) {
echo fancy_notifications();
}
?>
<!-- Start Pagination -->
<?php if ( ( get_option( 'use_pagination' ) == 1 && ( get_option( 'wpsc_page_number_position' ) == 2 || get_option( 'wpsc_page_number_position' ) == 3 ) ) ) : ?>
<div class="wpsc_page_numbers">
<?php if ( wpsc_has_pages() ) : ?>
<div class="pagination-pages"><?php echo wpsc_first_products_link( '« First', true ); ?> <?php echo wpsc_previous_products_link( '« Previous', true ); ?> <?php echo wpsc_pagination( 10 ); ?> <?php echo wpsc_next_products_link( 'Next »', true ); ?> <?php echo wpsc_last_products_link( 'Last »', true ); ?></div>
<?php endif; ?>
</div>
<?php endif; ?>
<!-- End Pagination -->
<?php endif; ?>
</div>
|
nurbsurf/downtoearth-tx
|
wp-content/uploads/wpsc/themes/iShop/products_page.php
|
PHP
|
gpl-2.0
| 13,702
|
/*
* Copyright (c) 2008, David Fishburn
* Copyright (c) 2012, Jan Larres
*
* This source code is released for free distribution under the terms of the
* GNU General Public License version 2 or (at your option) any later version.
*
* This module contains functions for generating tags for TeX language files.
*
* Tex language reference:
* http://en.wikibooks.org/wiki/TeX#The_Structure_of_TeX
*/
/*
* INCLUDE FILES
*/
#include "general.h" /* must always come first */
#include <ctype.h> /* to define isalpha () */
#ifdef DEBUG
#include <stdio.h>
#endif
#include <string.h>
#include "debug.h"
#include "entry.h"
#include "keyword.h"
#include "parse.h"
#include "read.h"
#include "routines.h"
#include "vstring.h"
/*
* MACROS
*/
#define isType(token,t) (bool) ((token)->type == (t))
#define isKeyword(token,k) (bool) ((token)->keyword == (k))
#define isIdentChar(c) \
(isalpha (c) || isdigit (c) || (((unsigned char) c) >= 0x80) || (c) == '$' || \
(c) == '_' || (c) == '#' || (c) == '-' || (c) == '.' || (c) == ':')
/*
* DATA DECLARATIONS
*/
/*
* Used to specify type of keyword.
*/
enum eKeywordId {
KEYWORD_part,
KEYWORD_chapter,
KEYWORD_section,
KEYWORD_subsection,
KEYWORD_subsubsection,
KEYWORD_paragraph,
KEYWORD_subparagraph,
KEYWORD_label,
KEYWORD_include
};
typedef int keywordId; /* to allow KEYWORD_NONE */
enum eTokenType {
/* 0..255 are the byte's value. Some are named for convenience */
TOKEN_OPEN_PAREN = '(',
TOKEN_CLOSE_PAREN = ')',
TOKEN_OPEN_CURLY = '{',
TOKEN_CLOSE_CURLY = '}',
TOKEN_OPEN_SQUARE = '[',
TOKEN_CLOSE_SQUARE = ']',
TOKEN_STAR = '*',
/* above is special types */
TOKEN_UNDEFINED = 256,
TOKEN_KEYWORD,
TOKEN_IDENTIFIER,
TOKEN_STRING,
};
typedef int tokenType;
typedef struct sTokenInfo {
tokenType type;
keywordId keyword;
vString * string;
vString * scope;
unsigned long lineNumber;
MIOPos filePosition;
} tokenInfo;
/*
* DATA DEFINITIONS
*/
static langType Lang_tex;
static vString *lastPart;
static vString *lastChapter;
static vString *lastSection;
static vString *lastSubS;
static vString *lastSubSubS;
typedef enum {
TEXTAG_PART,
TEXTAG_CHAPTER,
TEXTAG_SECTION,
TEXTAG_SUBSECTION,
TEXTAG_SUBSUBSECTION,
TEXTAG_PARAGRAPH,
TEXTAG_SUBPARAGRAPH,
TEXTAG_LABEL,
TEXTAG_INCLUDE,
TEXTAG_COUNT
} texKind;
static kindDefinition TexKinds [] = {
{ true, 'p', "part", "parts" },
{ true, 'c', "chapter", "chapters" },
{ true, 's', "section", "sections" },
{ true, 'u', "subsection", "subsections" },
{ true, 'b', "subsubsection", "subsubsections" },
{ true, 'P', "paragraph", "paragraphs" },
{ true, 'G', "subparagraph", "subparagraphs" },
{ true, 'l', "label", "labels" },
{ true, 'i', "include", "includes" }
};
static const keywordTable TexKeywordTable [] = {
/* keyword keyword ID */
{ "part", KEYWORD_part },
{ "chapter", KEYWORD_chapter },
{ "section", KEYWORD_section },
{ "subsection", KEYWORD_subsection },
{ "subsubsection", KEYWORD_subsubsection },
{ "paragraph", KEYWORD_paragraph },
{ "subparagraph", KEYWORD_subparagraph },
{ "label", KEYWORD_label },
{ "include", KEYWORD_include }
};
/*
* FUNCTION DEFINITIONS
*/
static tokenInfo *newToken (void)
{
tokenInfo *const token = xMalloc (1, tokenInfo);
token->type = TOKEN_UNDEFINED;
token->keyword = KEYWORD_NONE;
token->string = vStringNew ();
token->scope = vStringNew ();
token->lineNumber = getInputLineNumber ();
token->filePosition = getInputFilePosition ();
return token;
}
static void deleteToken (tokenInfo *const token)
{
vStringDelete (token->string);
vStringDelete (token->scope);
eFree (token);
}
static int getScopeInfo(texKind kind, vString *const parentName)
{
int parentKind = KIND_GHOST_INDEX;
int i;
/*
* Put labels separately instead of under their scope.
* Is this The Right Thing To Do?
*/
if (kind >= TEXTAG_LABEL) {
goto out;
}
/*
* This abuses the enum internals somewhat, but it should be ok in this
* case.
*/
/* TODO: This loop and conditions can be squashed. */
for (i = kind - 1; i >= TEXTAG_PART; --i) {
if (i == TEXTAG_SUBSECTION && vStringLength(lastSubS) > 0) {
parentKind = i;
break;
} else if (i == TEXTAG_SECTION && vStringLength(lastSection) > 0) {
parentKind = i;
break;
} else if (i == TEXTAG_CHAPTER && vStringLength(lastChapter) > 0) {
parentKind = i;
break;
} else if (i == TEXTAG_PART && vStringLength(lastPart) > 0) {
parentKind = i;
break;
}
}
/*
* Is '""' the best way to separate scopes? It has to be something that
* should ideally never occur in normal LaTeX text.
*/
for (i = TEXTAG_PART; i < (int)kind; ++i) {
if (i == TEXTAG_PART && vStringLength(lastPart) > 0) {
vStringCat(parentName, lastPart);
} else if (i == TEXTAG_CHAPTER && vStringLength(lastChapter) > 0) {
if (vStringLength(parentName) > 0) {
vStringCatS(parentName, "\"\"");
}
vStringCat(parentName, lastChapter);
} else if (i == TEXTAG_SECTION && vStringLength(lastSection) > 0) {
if (vStringLength(parentName) > 0) {
vStringCatS(parentName, "\"\"");
}
vStringCat(parentName, lastSection);
} else if (i == TEXTAG_SUBSECTION && vStringLength(lastSubS) > 0) {
if (vStringLength(parentName) > 0) {
vStringCatS(parentName, "\"\"");
}
vStringCat(parentName, lastSubS);
}
}
out:
return parentKind;
}
/*
* Tag generation functions
*/
static void makeTexTag (tokenInfo *const token, texKind kind)
{
if (TexKinds [kind].enabled)
{
const char *const name = vStringValue (token->string);
int parentKind = KIND_GHOST_INDEX;
vString *parentName = vStringNew();
tagEntryInfo e;
initTagEntry (&e, name, kind);
e.lineNumber = token->lineNumber;
e.filePosition = token->filePosition;
parentKind = getScopeInfo(kind, parentName);
if (parentKind != KIND_GHOST_INDEX) {
e.extensionFields.scopeKindIndex = parentKind;
e.extensionFields.scopeName = vStringValue(parentName);
}
makeTagEntry (&e);
vStringDelete (parentName);
}
}
/*
* Parsing functions
*/
/*
* Read a C identifier beginning with "firstChar" and places it into
* "name".
*/
static void parseIdentifier (vString *const string, const int firstChar)
{
int c = firstChar;
Assert (isIdentChar (c));
do
{
vStringPut (string, c);
c = getcFromInputFile ();
} while (isIdentChar (c));
if (c != EOF)
ungetcToInputFile (c); /* unget non-identifier character */
}
static bool readTokenFull (tokenInfo *const token, const bool includeWhitespaces)
{
int c;
int whitespaces = -1;
token->type = TOKEN_UNDEFINED;
token->keyword = KEYWORD_NONE;
vStringClear (token->string);
getNextChar:
do
{
c = getcFromInputFile ();
whitespaces++;
}
while (c == '\t' || c == ' ' || c == '\n');
token->lineNumber = getInputLineNumber ();
token->filePosition = getInputFilePosition ();
if (includeWhitespaces && whitespaces > 0 && c != '%' && c != EOF)
{
ungetcToInputFile (c);
c = ' ';
}
token->type = (unsigned char) c;
switch (c)
{
case EOF: return false;
case '\\':
/*
* All Tex tags start with a backslash.
* Check if the next character is an alpha character
* else it is not a potential tex tag.
*/
c = getcFromInputFile ();
if (! isalpha (c))
ungetcToInputFile (c);
else
{
vStringPut (token->string, '\\');
parseIdentifier (token->string, c);
token->keyword = lookupKeyword (vStringValue (token->string) + 1, Lang_tex);
if (isKeyword (token, KEYWORD_NONE))
token->type = TOKEN_IDENTIFIER;
else
token->type = TOKEN_KEYWORD;
}
break;
case '%':
skipToCharacterInInputFile ('\n'); /* % are single line comments */
goto getNextChar;
break;
default:
if (isIdentChar (c))
{
parseIdentifier (token->string, c);
token->type = TOKEN_IDENTIFIER;
}
break;
}
return true;
}
static bool readToken (tokenInfo *const token)
{
return readTokenFull (token, false);
}
static void copyToken (tokenInfo *const dest, tokenInfo *const src)
{
dest->lineNumber = src->lineNumber;
dest->filePosition = src->filePosition;
dest->type = src->type;
dest->keyword = src->keyword;
vStringCopy (dest->string, src->string);
vStringCopy (dest->scope, src->scope);
}
/*
* Scanning functions
*/
static bool parseTag (tokenInfo *const token, texKind kind)
{
tokenInfo *const name = newToken ();
vString * fullname;
bool useLongName = true;
bool eof = false;
fullname = vStringNew ();
/*
* Tex tags are of these formats:
* \keyword{any number of words}
* \keyword[short desc]{any number of words}
* \keyword*[short desc]{any number of words}
*
* When a keyword is found, loop through all words within
* the curly braces for the tag name.
*
* If the keyword is label like \label, words in the square
* brackets are skipped.
*/
bool enterSquare = (kind == TEXTAG_LABEL)? false: true;
if (isType (token, TOKEN_KEYWORD))
{
copyToken (name, token);
if (!readToken (token))
{
eof = true;
goto out;
}
}
if (isType (token, TOKEN_OPEN_SQUARE))
{
if (enterSquare)
useLongName = false;
if (!readToken (token))
{
eof = true;
goto out;
}
while (! isType (token, TOKEN_CLOSE_SQUARE) )
{
if (enterSquare
&& isType (token, TOKEN_IDENTIFIER))
{
if (vStringLength (fullname) > 0)
vStringPut (fullname, ' ');
vStringCat (fullname, token->string);
}
if (!readToken (token))
{
eof = true;
goto out;
}
}
if (enterSquare)
{
vStringCopy (name->string, fullname);
makeTexTag (name, kind);
}
else if (!readToken (token))
{
eof = true;
goto out;
}
}
if (isType (token, TOKEN_STAR))
{
if (!readToken (token))
{
eof = true;
goto out;
}
}
if (isType (token, TOKEN_OPEN_CURLY))
{
int depth = 1;
if (!readToken (token))
{
eof = true;
goto out;
}
while (depth > 0)
{
/* if (isType (token, TOKEN_IDENTIFIER) && useLongName) */
if (useLongName)
{
if (isType (token, TOKEN_IDENTIFIER) || isType (token, TOKEN_KEYWORD))
vStringCat (fullname, token->string);
else
vStringPut (fullname, token->type);
}
if (!readTokenFull (token, useLongName))
{
eof = true;
goto out;
}
else if (isType (token, TOKEN_OPEN_CURLY))
depth++;
else if (isType (token, TOKEN_CLOSE_CURLY))
depth--;
}
if (useLongName)
{
vStringStripTrailing (fullname);
if (vStringLength (fullname) > 0)
{
vStringCopy (name->string, fullname);
makeTexTag (name, kind);
}
}
}
/*
* save the name of the last section definitions for scope-resolution
* later
*/
switch (kind)
{
case TEXTAG_PART:
vStringCopy(lastPart, fullname);
vStringClear(lastChapter);
vStringClear(lastSection);
vStringClear(lastSubS);
vStringClear(lastSubSubS);
break;
case TEXTAG_CHAPTER:
vStringCopy(lastChapter, fullname);
vStringClear(lastSection);
vStringClear(lastSubS);
vStringClear(lastSubSubS);
break;
case TEXTAG_SECTION:
vStringCopy(lastSection, fullname);
vStringClear(lastSubS);
vStringClear(lastSubSubS);
break;
case TEXTAG_SUBSECTION:
vStringCopy(lastSubS, fullname);
vStringClear(lastSubSubS);
break;
case TEXTAG_SUBSUBSECTION:
vStringCopy(lastSubSubS, fullname);
break;
default:
break;
}
out:
deleteToken (name);
vStringDelete (fullname);
return eof;
}
static void parseTexFile (tokenInfo *const token)
{
bool eof = false;
do
{
if (!readToken (token))
break;
if (isType (token, TOKEN_KEYWORD))
{
switch (token->keyword)
{
case KEYWORD_part:
eof = parseTag (token, TEXTAG_PART);
break;
case KEYWORD_chapter:
eof = parseTag (token, TEXTAG_CHAPTER);
break;
case KEYWORD_section:
eof = parseTag (token, TEXTAG_SECTION);
break;
case KEYWORD_subsection:
eof = parseTag (token, TEXTAG_SUBSECTION);
break;
case KEYWORD_subsubsection:
eof = parseTag (token, TEXTAG_SUBSUBSECTION);
break;
case KEYWORD_paragraph:
eof = parseTag (token, TEXTAG_PARAGRAPH);
break;
case KEYWORD_subparagraph:
eof = parseTag (token, TEXTAG_SUBPARAGRAPH);
break;
case KEYWORD_label:
eof = parseTag (token, TEXTAG_LABEL);
break;
case KEYWORD_include:
eof = parseTag (token, TEXTAG_INCLUDE);
break;
default:
break;
}
}
if (eof)
break;
} while (true);
}
static void initialize (const langType language)
{
Assert (ARRAY_SIZE (TexKinds) == TEXTAG_COUNT);
Lang_tex = language;
lastPart = vStringNew();
lastChapter = vStringNew();
lastSection = vStringNew();
lastSubS = vStringNew();
lastSubSubS = vStringNew();
}
static void finalize (const langType language CTAGS_ATTR_UNUSED,
bool initialized)
{
if (initialized)
{
vStringDelete(lastPart);
lastPart = NULL;
vStringDelete(lastChapter);
lastChapter = NULL;
vStringDelete(lastSection);
lastSection = NULL;
vStringDelete(lastSubS);
lastSubS = NULL;
vStringDelete(lastSubSubS);
lastSubSubS = NULL;
}
}
static void findTexTags (void)
{
tokenInfo *const token = newToken ();
parseTexFile (token);
deleteToken (token);
}
/* Create parser definition structure */
extern parserDefinition* TexParser (void)
{
static const char *const extensions [] = { "tex", NULL };
parserDefinition *const def = parserNew ("Tex");
def->extensions = extensions;
/*
* New definitions for parsing instead of regex
*/
def->kindTable = TexKinds;
def->kindCount = ARRAY_SIZE (TexKinds);
def->parser = findTexTags;
def->initialize = initialize;
def->finalize = finalize;
def->keywordTable = TexKeywordTable;
def->keywordCount = ARRAY_SIZE (TexKeywordTable);
return def;
}
|
lizh06/ctags
|
parsers/tex.c
|
C
|
gpl-2.0
| 13,938
|
/*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* 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 "icecrown_citadel.h"
#include "AreaBoundary.h"
#include "Creature.h"
#include "CreatureAI.h"
#include "InstanceScript.h"
#include "Map.h"
#include "ObjectMgr.h"
#include "Player.h"
#include "QuestPools.h"
#include "ScriptMgr.h"
#include "TemporarySummon.h"
#include "Transport.h"
#include "TransportMgr.h"
#include "WorldStatePackets.h"
#include <unordered_set>
enum EventIds
{
EVENT_PLAYERS_GUNSHIP_SPAWN = 22663,
EVENT_PLAYERS_GUNSHIP_COMBAT = 22664,
EVENT_PLAYERS_GUNSHIP_SAURFANG = 22665,
EVENT_ENEMY_GUNSHIP_COMBAT = 22860,
EVENT_ENEMY_GUNSHIP_DESPAWN = 22861,
EVENT_QUAKE = 23437,
EVENT_SECOND_REMORSELESS_WINTER = 23507,
EVENT_TELEPORT_TO_FROSTMOURNE = 23617
};
enum TimedEvents
{
EVENT_UPDATE_EXECUTION_TIME = 1,
EVENT_QUAKE_SHATTER = 2,
EVENT_REBUILD_PLATFORM = 3,
EVENT_RESPAWN_GUNSHIP = 4
};
enum SpawnGroups
{
SPAWN_GROUP_ALLIANCE_ROS = 57,
SPAWN_GROUP_HORDE_ROS = 58
};
BossBoundaryData const boundaries =
{
{ DATA_LORD_MARROWGAR, new CircleBoundary(Position(-428.0f,2211.0f), 95.0) },
{ DATA_LORD_MARROWGAR, new RectangleBoundary(-430.0f, -330.0f, 2110.0f, 2310.0f) },
{ DATA_LADY_DEATHWHISPER, new RectangleBoundary(-670.0f, -520.0f, 2145.0f, 2280.0f) },
{ DATA_DEATHBRINGER_SAURFANG, new RectangleBoundary(-565.0f, -465.0f, 2160.0f, 2260.0f) },
{ DATA_ROTFACE, new RectangleBoundary(4385.0f, 4505.0f, 3082.0f, 3195.0f) },
{ DATA_FESTERGUT, new RectangleBoundary(4205.0f, 4325.0f, 3082.0f, 3195.0f) },
{ DATA_PROFESSOR_PUTRICIDE, new ParallelogramBoundary(Position(4356.0f, 3290.0f), Position(4435.0f, 3194.0f), Position(4280.0f, 3194.0f)) },
{ DATA_PROFESSOR_PUTRICIDE, new RectangleBoundary(4280.0f, 4435.0f, 3150.0f, 4360.0f) },
{ DATA_BLOOD_PRINCE_COUNCIL, new EllipseBoundary(Position(4660.95f, 2769.194f), 85.0, 60.0) },
{ DATA_BLOOD_QUEEN_LANA_THEL, new CircleBoundary(Position(4595.93f, 2769.365f), 64.0) },
{ DATA_BLOOD_QUEEN_LANA_THEL, new ZRangeBoundary(391.78f, 473.43f) },
{ DATA_SISTER_SVALNA, new RectangleBoundary(4291.0f, 4423.0f, 2438.0f, 2653.0f) },
{ DATA_VALITHRIA_DREAMWALKER, new RectangleBoundary(4112.5f, 4293.5f, 2385.0f, 2585.0f) },
{ DATA_SINDRAGOSA, new EllipseBoundary(Position(4408.6f, 2484.0f), 100.0, 75.0) }
};
DoorData const doorData[] =
{
{ GO_LORD_MARROWGAR_S_ENTRANCE, DATA_LORD_MARROWGAR, DOOR_TYPE_ROOM },
{ GO_ICEWALL, DATA_LORD_MARROWGAR, DOOR_TYPE_PASSAGE },
{ GO_DOODAD_ICECROWN_ICEWALL02, DATA_LORD_MARROWGAR, DOOR_TYPE_PASSAGE },
{ GO_ORATORY_OF_THE_DAMNED_ENTRANCE, DATA_LADY_DEATHWHISPER, DOOR_TYPE_ROOM },
{ GO_SAURFANG_S_DOOR, DATA_DEATHBRINGER_SAURFANG, DOOR_TYPE_PASSAGE },
{ GO_ORANGE_PLAGUE_MONSTER_ENTRANCE, DATA_FESTERGUT, DOOR_TYPE_ROOM },
{ GO_GREEN_PLAGUE_MONSTER_ENTRANCE, DATA_ROTFACE, DOOR_TYPE_ROOM },
{ GO_SCIENTIST_ENTRANCE, DATA_PROFESSOR_PUTRICIDE, DOOR_TYPE_ROOM },
{ GO_CRIMSON_HALL_DOOR, DATA_BLOOD_PRINCE_COUNCIL, DOOR_TYPE_ROOM },
{ GO_BLOOD_ELF_COUNCIL_DOOR, DATA_BLOOD_PRINCE_COUNCIL, DOOR_TYPE_PASSAGE },
{ GO_BLOOD_ELF_COUNCIL_DOOR_RIGHT, DATA_BLOOD_PRINCE_COUNCIL, DOOR_TYPE_PASSAGE },
{ GO_DOODAD_ICECROWN_BLOODPRINCE_DOOR_01, DATA_BLOOD_QUEEN_LANA_THEL, DOOR_TYPE_ROOM },
{ GO_DOODAD_ICECROWN_GRATE_01, DATA_BLOOD_QUEEN_LANA_THEL, DOOR_TYPE_PASSAGE },
{ GO_GREEN_DRAGON_BOSS_ENTRANCE, DATA_SISTER_SVALNA, DOOR_TYPE_PASSAGE },
{ GO_GREEN_DRAGON_BOSS_ENTRANCE, DATA_VALITHRIA_DREAMWALKER, DOOR_TYPE_ROOM },
{ GO_GREEN_DRAGON_BOSS_EXIT, DATA_VALITHRIA_DREAMWALKER, DOOR_TYPE_PASSAGE },
{ GO_DOODAD_ICECROWN_ROOSTPORTCULLIS_01, DATA_VALITHRIA_DREAMWALKER, DOOR_TYPE_SPAWN_HOLE },
{ GO_DOODAD_ICECROWN_ROOSTPORTCULLIS_02, DATA_VALITHRIA_DREAMWALKER, DOOR_TYPE_SPAWN_HOLE },
{ GO_DOODAD_ICECROWN_ROOSTPORTCULLIS_03, DATA_VALITHRIA_DREAMWALKER, DOOR_TYPE_SPAWN_HOLE },
{ GO_DOODAD_ICECROWN_ROOSTPORTCULLIS_04, DATA_VALITHRIA_DREAMWALKER, DOOR_TYPE_SPAWN_HOLE },
{ GO_SINDRAGOSA_ENTRANCE_DOOR, DATA_SINDRAGOSA, DOOR_TYPE_ROOM },
{ GO_SINDRAGOSA_SHORTCUT_ENTRANCE_DOOR, DATA_SINDRAGOSA, DOOR_TYPE_PASSAGE },
{ GO_SINDRAGOSA_SHORTCUT_EXIT_DOOR, DATA_SINDRAGOSA, DOOR_TYPE_PASSAGE },
{ GO_ICE_WALL, DATA_SINDRAGOSA, DOOR_TYPE_ROOM },
{ GO_ICE_WALL, DATA_SINDRAGOSA, DOOR_TYPE_ROOM },
{ 0, 0, DOOR_TYPE_ROOM } // END
};
// this doesnt have to only store questgivers, also can be used for related quest spawns
struct WeeklyQuest
{
uint32 creatureEntry;
uint32 questId[2]; // 10 and 25 man versions
};
// when changing the content, remember to update SetData, DATA_BLOOD_QUICKENING_STATE case for NPC_ALRIN_THE_AGILE index
WeeklyQuest const WeeklyQuestData[WeeklyNPCs] =
{
{ NPC_INFILTRATOR_MINCHAR, { QUEST_DEPROGRAMMING_10, QUEST_DEPROGRAMMING_25 } }, // Deprogramming
{ NPC_KOR_KRON_LIEUTENANT, { QUEST_SECURING_THE_RAMPARTS_10, QUEST_SECURING_THE_RAMPARTS_25 } }, // Securing the Ramparts
{ NPC_ROTTING_FROST_GIANT_10, { QUEST_SECURING_THE_RAMPARTS_10, QUEST_SECURING_THE_RAMPARTS_25 } }, // Securing the Ramparts
{ NPC_ROTTING_FROST_GIANT_25, { QUEST_SECURING_THE_RAMPARTS_10, QUEST_SECURING_THE_RAMPARTS_25 } }, // Securing the Ramparts
{ NPC_ALCHEMIST_ADRIANNA, { QUEST_RESIDUE_RENDEZVOUS_10, QUEST_RESIDUE_RENDEZVOUS_25 } }, // Residue Rendezvous
{ NPC_ALRIN_THE_AGILE, { QUEST_BLOOD_QUICKENING_10, QUEST_BLOOD_QUICKENING_25 } }, // Blood Quickening
{ NPC_INFILTRATOR_MINCHAR_BQ, { QUEST_BLOOD_QUICKENING_10, QUEST_BLOOD_QUICKENING_25 } }, // Blood Quickening
{ NPC_MINCHAR_BEAM_STALKER, { QUEST_BLOOD_QUICKENING_10, QUEST_BLOOD_QUICKENING_25 } }, // Blood Quickening
{ NPC_VALITHRIA_DREAMWALKER_QUEST, { QUEST_RESPITE_FOR_A_TORNMENTED_SOUL_10, QUEST_RESPITE_FOR_A_TORNMENTED_SOUL_25 } } // Respite for a Tormented Soul
};
// NPCs spawned at Light's Hammer on Lich King dead
Position const JainaSpawnPos = { -48.65278f, 2211.026f, 27.98586f, 3.124139f };
Position const MuradinSpawnPos = { -47.34549f, 2208.087f, 27.98586f, 3.106686f };
Position const UtherSpawnPos = { -26.58507f, 2211.524f, 30.19898f, 3.124139f };
Position const SylvanasSpawnPos = { -41.45833f, 2222.891f, 27.98586f, 3.647738f };
class instance_icecrown_citadel : public InstanceMapScript
{
public:
instance_icecrown_citadel() : InstanceMapScript(ICCScriptName, 631) { }
struct instance_icecrown_citadel_InstanceMapScript : public InstanceScript
{
instance_icecrown_citadel_InstanceMapScript(InstanceMap* map) : InstanceScript(map)
{
SetHeaders(DataHeader);
SetBossNumber(EncounterCount);
LoadBossBoundaries(boundaries);
LoadDoorData(doorData);
TeamInInstance = 0;
HeroicAttempts = MaxHeroicAttempts;
ColdflameJetsState = NOT_STARTED;
UpperSpireTeleporterActiveState = NOT_STARTED;
BloodQuickeningState = NOT_STARTED;
BloodQuickeningMinutes = 0;
BloodPrinceIntro = 1;
SindragosaIntro = 1;
IsBonedEligible = true;
IsOozeDanceEligible = true;
IsNauseaEligible = true;
IsOrbWhispererEligible = true;
IsFactionBuffActive = true;
}
// A function to help reduce the number of lines for teleporter management.
void SetTeleporterState(GameObject* go, bool usable)
{
if (usable)
{
go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
go->SetGoState(GO_STATE_ACTIVE);
}
else
{
go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
go->SetGoState(GO_STATE_READY);
}
}
void FillInitialWorldStates(WorldPackets::WorldState::InitWorldStates& packet) override
{
packet.Worldstates.emplace_back(WORLDSTATE_SHOW_TIMER, BloodQuickeningState == IN_PROGRESS ? 1 : 0);
packet.Worldstates.emplace_back(WORLDSTATE_EXECUTION_TIME, BloodQuickeningMinutes);
packet.Worldstates.emplace_back(WORLDSTATE_SHOW_ATTEMPTS, instance->IsHeroic() ? 1 : 0);
packet.Worldstates.emplace_back(WORLDSTATE_ATTEMPTS_REMAINING, HeroicAttempts);
packet.Worldstates.emplace_back(WORLDSTATE_ATTEMPTS_MAX, MaxHeroicAttempts);
}
void OnPlayerEnter(Player* player) override
{
if (!TeamInInstance)
TeamInInstance = player->GetTeam();
uint8 spawnGroupId = TeamInInstance == ALLIANCE ? SPAWN_GROUP_ALLIANCE_ROS : SPAWN_GROUP_HORDE_ROS;
if (!instance->IsSpawnGroupActive(spawnGroupId))
instance->SpawnGroupSpawn(spawnGroupId);
if (GetBossState(DATA_LADY_DEATHWHISPER) == DONE && GetBossState(DATA_ICECROWN_GUNSHIP_BATTLE) != DONE)
SpawnGunship();
if (IsFactionBuffActive)
DoCastSpellOnPlayer(player, TeamInInstance == ALLIANCE ? SPELL_STRENGHT_OF_WRYNN : SPELL_HELLSCREAMS_WARSONG);
}
void OnPlayerLeave(Player* player) override
{
DoRemoveAurasDueToSpellOnPlayer(player, TeamInInstance == ALLIANCE ? SPELL_STRENGHT_OF_WRYNN : SPELL_HELLSCREAMS_WARSONG, true, true);
}
void OnCreatureCreate(Creature* creature) override
{
if (creature->IsGuardian() && creature->GetOwnerGUID().IsPlayer())
{
if (IsFactionBuffActive)
creature->CastSpell(creature, TeamInInstance == ALLIANCE ? SPELL_STRENGHT_OF_WRYNN : SPELL_HELLSCREAMS_WARSONG, true);
}
switch (creature->GetEntry())
{
case NPC_LORD_MARROWGAR:
LordMarrowgarGUID = creature->GetGUID();
break;
case NPC_LADY_DEATHWHISPER:
LadyDeahtwhisperGUID = creature->GetGUID();
break;
case NPC_DEATHBRINGER_SAURFANG:
DeathbringerSaurfangGUID = creature->GetGUID();
break;
case NPC_ALLIANCE_GUNSHIP_CANNON:
case NPC_HORDE_GUNSHIP_CANNON:
creature->SetControlled(true, UNIT_STATE_ROOT);
break;
case NPC_SE_HIGH_OVERLORD_SAURFANG:
case NPC_SE_MURADIN_BRONZEBEARD:
DeathbringerSaurfangEventGUID = creature->GetGUID();
break;
case NPC_FESTERGUT:
FestergutGUID = creature->GetGUID();
break;
case NPC_ROTFACE:
RotfaceGUID = creature->GetGUID();
break;
case NPC_PROFESSOR_PUTRICIDE:
ProfessorPutricideGUID = creature->GetGUID();
break;
case NPC_VOLATILE_OOZE:
case NPC_GAS_CLOUD:
//! These creatures are summoned by something else than Professor Putricide
//! but need to be controlled/despawned by him - so they need to be
//! registered on his summon list
if (Creature* professorPutricide = instance->GetCreature(ProfessorPutricideGUID))
professorPutricide->AI()->JustSummoned(creature);
break;
case NPC_PRINCE_KELESETH:
BloodCouncilGUIDs[0] = creature->GetGUID();
break;
case NPC_PRINCE_TALDARAM:
BloodCouncilGUIDs[1] = creature->GetGUID();
break;
case NPC_PRINCE_VALANAR:
BloodCouncilGUIDs[2] = creature->GetGUID();
break;
case NPC_BLOOD_ORB_CONTROLLER:
BloodCouncilControllerGUID = creature->GetGUID();
break;
case NPC_BLOOD_QUEEN_LANA_THEL_COUNCIL:
BloodQueenLanaThelCouncilGUID = creature->GetGUID();
break;
case NPC_BLOOD_QUEEN_LANA_THEL:
BloodQueenLanaThelGUID = creature->GetGUID();
break;
case NPC_CROK_SCOURGEBANE:
CrokScourgebaneGUID = creature->GetGUID();
break;
// we can only do this because there are no gaps in their entries
case NPC_CAPTAIN_ARNATH:
case NPC_CAPTAIN_BRANDON:
case NPC_CAPTAIN_GRONDEL:
case NPC_CAPTAIN_RUPERT:
CrokCaptainGUIDs[creature->GetEntry()-NPC_CAPTAIN_ARNATH] = creature->GetGUID();
break;
case NPC_SISTER_SVALNA:
SisterSvalnaGUID = creature->GetGUID();
break;
case NPC_VALITHRIA_DREAMWALKER:
ValithriaDreamwalkerGUID = creature->GetGUID();
break;
case NPC_THE_LICH_KING_VALITHRIA:
ValithriaLichKingGUID = creature->GetGUID();
break;
case NPC_GREEN_DRAGON_COMBAT_TRIGGER:
ValithriaTriggerGUID = creature->GetGUID();
break;
case NPC_SINDRAGOSA:
SindragosaGUID = creature->GetGUID();
break;
case NPC_SPINESTALKER:
SpinestalkerGUID = creature->GetGUID();
break;
case NPC_RIMEFANG:
RimefangGUID = creature->GetGUID();
break;
case NPC_INVISIBLE_STALKER:
// Teleporter visual at center
if (creature->GetExactDist2d(4357.052f, 2769.421f) < 10.0f)
creature->CastSpell(creature, SPELL_ARTHAS_TELEPORTER_CEREMONY, false);
break;
case NPC_THE_LICH_KING:
TheLichKingGUID = creature->GetGUID();
break;
case NPC_HIGHLORD_TIRION_FORDRING_LK:
HighlordTirionFordringGUID = creature->GetGUID();
break;
case NPC_TERENAS_MENETHIL_FROSTMOURNE:
case NPC_TERENAS_MENETHIL_FROSTMOURNE_H:
TerenasMenethilGUID = creature->GetGUID();
break;
case NPC_WICKED_SPIRIT:
// Remove corpse as soon as it dies (and respawn 10 seconds later)
creature->SetCorpseDelay(0);
creature->SetReactState(REACT_PASSIVE);
break;
default:
break;
}
}
void OnCreatureRemove(Creature* creature) override
{
if (creature->GetEntry() == NPC_SINDRAGOSA)
SindragosaGUID.Clear();
}
// Weekly quest spawn prevention
uint32 GetCreatureEntry(ObjectGuid::LowType /*guidLow*/, CreatureData const* data) override
{
if (!TeamInInstance)
{
Map::PlayerList const& players = instance->GetPlayers();
if (!players.isEmpty())
if (Player* player = players.begin()->GetSource())
TeamInInstance = player->GetTeam();
}
uint32 entry = data->id;
switch (entry)
{
case NPC_INFILTRATOR_MINCHAR:
case NPC_KOR_KRON_LIEUTENANT:
case NPC_ALCHEMIST_ADRIANNA:
case NPC_ALRIN_THE_AGILE:
case NPC_INFILTRATOR_MINCHAR_BQ:
case NPC_MINCHAR_BEAM_STALKER:
case NPC_VALITHRIA_DREAMWALKER_QUEST:
{
for (uint8 questIndex = 0; questIndex < WeeklyNPCs; ++questIndex)
{
if (WeeklyQuestData[questIndex].creatureEntry == entry)
{
uint8 diffIndex = uint8(instance->GetSpawnMode() & 1);
if (!sQuestPoolMgr->IsQuestActive(WeeklyQuestData[questIndex].questId[diffIndex]))
return 0;
break;
}
}
if (entry == NPC_KOR_KRON_LIEUTENANT && TeamInInstance == ALLIANCE)
return NPC_SKYBREAKER_LIEUTENANT;
break;
}
case NPC_HORDE_GUNSHIP_CANNON:
case NPC_ORGRIMS_HAMMER_CREW:
case NPC_SKY_REAVER_KORM_BLACKSCAR:
if (TeamInInstance == ALLIANCE)
return 0;
break;
case NPC_ALLIANCE_GUNSHIP_CANNON:
case NPC_SKYBREAKER_DECKHAND:
case NPC_HIGH_CAPTAIN_JUSTIN_BARTLETT:
if (TeamInInstance == HORDE)
return 0;
break;
case NPC_ZAFOD_BOOMBOX:
if (GameObjectTemplate const* go = sObjectMgr->GetGameObjectTemplate(GO_THE_SKYBREAKER_A))
if ((TeamInInstance == ALLIANCE && data->mapId == go->moTransport.mapID) ||
(TeamInInstance == HORDE && data->mapId != go->moTransport.mapID))
return entry;
return 0;
case NPC_IGB_MURADIN_BRONZEBEARD:
if ((TeamInInstance == ALLIANCE && data->spawnPoint.GetPositionX() > 10.0f) ||
(TeamInInstance == HORDE && data->spawnPoint.GetPositionX() < 10.0f))
return entry;
return 0;
case NPC_SE_HIGH_OVERLORD_SAURFANG:
return TeamInInstance == ALLIANCE ? NPC_SE_MURADIN_BRONZEBEARD : NPC_SE_HIGH_OVERLORD_SAURFANG;
case NPC_KOR_KRON_GENERAL:
return TeamInInstance == ALLIANCE ? NPC_ALLIANCE_COMMANDER : NPC_KOR_KRON_GENERAL;
case NPC_TORTUNOK:
return TeamInInstance == ALLIANCE ? NPC_ALANA_MOONSTRIKE : NPC_TORTUNOK;
case NPC_GERARDO_THE_SUAVE:
return TeamInInstance == ALLIANCE ? NPC_TALAN_MOONSTRIKE : NPC_GERARDO_THE_SUAVE;
case NPC_UVLUS_BANEFIRE:
return TeamInInstance == ALLIANCE ? NPC_MALFUS_GRIMFROST : NPC_UVLUS_BANEFIRE;
case NPC_IKFIRUS_THE_VILE:
return TeamInInstance == ALLIANCE ? NPC_YILI : NPC_IKFIRUS_THE_VILE;
case NPC_VOL_GUK:
return TeamInInstance == ALLIANCE ? NPC_JEDEBIA : NPC_VOL_GUK;
case NPC_HARAGG_THE_UNSEEN:
return TeamInInstance == ALLIANCE ? NPC_NIBY_THE_ALMIGHTY : NPC_HARAGG_THE_UNSEEN;
case NPC_GARROSH_HELLSCREAM:
return TeamInInstance == ALLIANCE ? NPC_KING_VARIAN_WRYNN : NPC_GARROSH_HELLSCREAM;
case NPC_SE_KOR_KRON_REAVER:
return TeamInInstance == ALLIANCE ? NPC_SE_SKYBREAKER_MARINE : NPC_SE_KOR_KRON_REAVER;
default:
break;
}
return entry;
}
uint32 GetGameObjectEntry(ObjectGuid::LowType /*guidLow*/, uint32 entry) override
{
switch (entry)
{
case GO_GUNSHIP_ARMORY_H_10N:
case GO_GUNSHIP_ARMORY_H_25N:
case GO_GUNSHIP_ARMORY_H_10H:
case GO_GUNSHIP_ARMORY_H_25H:
if (TeamInInstance == ALLIANCE)
return 0;
break;
case GO_GUNSHIP_ARMORY_A_10N:
case GO_GUNSHIP_ARMORY_A_25N:
case GO_GUNSHIP_ARMORY_A_10H:
case GO_GUNSHIP_ARMORY_A_25H:
if (TeamInInstance == HORDE)
return 0;
break;
default:
break;
}
return entry;
}
void OnUnitDeath(Unit* unit) override
{
Creature* creature = unit->ToCreature();
if (!creature)
return;
switch (creature->GetEntry())
{
case NPC_YMIRJAR_BATTLE_MAIDEN:
case NPC_YMIRJAR_DEATHBRINGER:
case NPC_YMIRJAR_FROSTBINDER:
case NPC_YMIRJAR_HUNTRESS:
case NPC_YMIRJAR_WARLORD:
if (Creature* crok = instance->GetCreature(CrokScourgebaneGUID))
crok->AI()->SetGUID(creature->GetGUID(), ACTION_VRYKUL_DEATH);
break;
case NPC_FROSTWING_WHELP:
if (FrostwyrmGUIDs.empty())
return;
if (creature->AI()->GetData(1/*DATA_FROSTWYRM_OWNER*/) == DATA_SPINESTALKER)
{
SpinestalkerTrash.erase(creature->GetSpawnId());
if (SpinestalkerTrash.empty())
if (Creature* spinestalk = instance->GetCreature(SpinestalkerGUID))
spinestalk->AI()->DoAction(ACTION_START_FROSTWYRM);
}
else
{
RimefangTrash.erase(creature->GetSpawnId());
if (RimefangTrash.empty())
if (Creature* spinestalk = instance->GetCreature(RimefangGUID))
spinestalk->AI()->DoAction(ACTION_START_FROSTWYRM);
}
break;
case NPC_RIMEFANG:
case NPC_SPINESTALKER:
{
if (instance->IsHeroic() && !HeroicAttempts)
return;
if (GetBossState(DATA_SINDRAGOSA) == DONE)
return;
FrostwyrmGUIDs.erase(creature->GetSpawnId());
if (FrostwyrmGUIDs.empty())
{
instance->LoadGrid(SindragosaSpawnPos.GetPositionX(), SindragosaSpawnPos.GetPositionY());
if (Creature* boss = instance->SummonCreature(NPC_SINDRAGOSA, SindragosaSpawnPos))
boss->AI()->DoAction(ACTION_START_FROSTWYRM);
}
break;
}
default:
break;
}
}
void OnGameObjectCreate(GameObject* go) override
{
switch (go->GetEntry())
{
case GO_DOODAD_ICECROWN_ICEWALL02:
case GO_ICEWALL:
case GO_LORD_MARROWGAR_S_ENTRANCE:
case GO_ORATORY_OF_THE_DAMNED_ENTRANCE:
case GO_ORANGE_PLAGUE_MONSTER_ENTRANCE:
case GO_GREEN_PLAGUE_MONSTER_ENTRANCE:
case GO_SCIENTIST_ENTRANCE:
case GO_CRIMSON_HALL_DOOR:
case GO_BLOOD_ELF_COUNCIL_DOOR:
case GO_BLOOD_ELF_COUNCIL_DOOR_RIGHT:
case GO_DOODAD_ICECROWN_BLOODPRINCE_DOOR_01:
case GO_DOODAD_ICECROWN_GRATE_01:
case GO_GREEN_DRAGON_BOSS_ENTRANCE:
case GO_GREEN_DRAGON_BOSS_EXIT:
case GO_DOODAD_ICECROWN_ROOSTPORTCULLIS_02:
case GO_DOODAD_ICECROWN_ROOSTPORTCULLIS_03:
case GO_SINDRAGOSA_ENTRANCE_DOOR:
case GO_SINDRAGOSA_SHORTCUT_ENTRANCE_DOOR:
case GO_SINDRAGOSA_SHORTCUT_EXIT_DOOR:
case GO_ICE_WALL:
AddDoor(go, true);
break;
// these 2 gates are functional only on 25man modes
case GO_DOODAD_ICECROWN_ROOSTPORTCULLIS_01:
case GO_DOODAD_ICECROWN_ROOSTPORTCULLIS_04:
if (instance->Is25ManRaid())
AddDoor(go, true);
break;
case GO_LADY_DEATHWHISPER_ELEVATOR:
LadyDeathwisperElevatorGUID = go->GetGUID();
if (GetBossState(DATA_LADY_DEATHWHISPER) == DONE)
{
go->SetUInt32Value(GAMEOBJECT_LEVEL, 0);
go->SetGoState(GO_STATE_READY);
}
break;
case GO_THE_SKYBREAKER_H:
case GO_ORGRIMS_HAMMER_A:
EnemyGunshipGUID = go->GetGUID();
break;
case GO_GUNSHIP_ARMORY_H_10N:
case GO_GUNSHIP_ARMORY_H_25N:
case GO_GUNSHIP_ARMORY_H_10H:
case GO_GUNSHIP_ARMORY_H_25H:
case GO_GUNSHIP_ARMORY_A_10N:
case GO_GUNSHIP_ARMORY_A_25N:
case GO_GUNSHIP_ARMORY_A_10H:
case GO_GUNSHIP_ARMORY_A_25H:
GunshipArmoryGUID = go->GetGUID();
break;
case GO_SAURFANG_S_DOOR:
DeathbringerSaurfangDoorGUID = go->GetGUID();
AddDoor(go, true);
break;
case GO_DEATHBRINGER_S_CACHE_10N:
case GO_DEATHBRINGER_S_CACHE_25N:
case GO_DEATHBRINGER_S_CACHE_10H:
case GO_DEATHBRINGER_S_CACHE_25H:
DeathbringersCacheGUID = go->GetGUID();
break;
case GO_SCOURGE_TRANSPORTER_LICHKING:
TeleporterLichKingGUID = go->GetGUID();
if (GetBossState(DATA_PROFESSOR_PUTRICIDE) == DONE && GetBossState(DATA_BLOOD_QUEEN_LANA_THEL) == DONE && GetBossState(DATA_SINDRAGOSA) == DONE)
go->SetGoState(GO_STATE_ACTIVE);
break;
case GO_SCOURGE_TRANSPORTER_UPPERSPIRE:
TeleporterUpperSpireGUID = go->GetGUID();
if (GetBossState(DATA_DEATHBRINGER_SAURFANG) != DONE || GetData(DATA_UPPERSPIRE_TELE_ACT) != DONE)
SetTeleporterState(go, false);
else
SetTeleporterState(go, true);
break;
case GO_SCOURGE_TRANSPORTER_LIGHTSHAMMER:
TeleporterLightsHammerGUID = go->GetGUID();
SetTeleporterState(go, GetBossState(DATA_LORD_MARROWGAR) == DONE);
break;
case GO_SCOURGE_TRANSPORTER_RAMPART:
TeleporterRampartsGUID = go->GetGUID();
SetTeleporterState(go, GetBossState(DATA_LADY_DEATHWHISPER) == DONE);
break;
case GO_SCOURGE_TRANSPORTER_DEATHBRINGER:
TeleporterDeathBringerGUID = go->GetGUID();
SetTeleporterState(go, GetBossState(DATA_ICECROWN_GUNSHIP_BATTLE) == DONE);
break;
case GO_SCOURGE_TRANSPORTER_ORATORY:
TeleporterOratoryGUID = go->GetGUID();
SetTeleporterState(go, GetBossState(DATA_LORD_MARROWGAR) == DONE);
break;
case GO_SCOURGE_TRANSPORTER_SINDRAGOSA:
TeleporterSindragosaGUID = go->GetGUID();
SetTeleporterState(go, GetBossState(DATA_VALITHRIA_DREAMWALKER) == DONE);
break;
case GO_PLAGUE_SIGIL:
PlagueSigilGUID = go->GetGUID();
if (GetBossState(DATA_PROFESSOR_PUTRICIDE) == DONE)
HandleGameObject(PlagueSigilGUID, false, go);
break;
case GO_BLOODWING_SIGIL:
BloodwingSigilGUID = go->GetGUID();
if (GetBossState(DATA_BLOOD_QUEEN_LANA_THEL) == DONE)
HandleGameObject(BloodwingSigilGUID, false, go);
break;
case GO_SIGIL_OF_THE_FROSTWING:
FrostwingSigilGUID = go->GetGUID();
if (GetBossState(DATA_SINDRAGOSA) == DONE)
HandleGameObject(FrostwingSigilGUID, false, go);
break;
case GO_SCIENTIST_AIRLOCK_DOOR_COLLISION:
PutricideCollisionGUID = go->GetGUID();
if (GetBossState(DATA_FESTERGUT) == DONE && GetBossState(DATA_ROTFACE) == DONE)
HandleGameObject(PutricideCollisionGUID, true, go);
break;
case GO_SCIENTIST_AIRLOCK_DOOR_ORANGE:
PutricideGateGUIDs[0] = go->GetGUID();
if (GetBossState(DATA_FESTERGUT) == DONE && GetBossState(DATA_ROTFACE) == DONE)
go->SetGoState(GO_STATE_DESTROYED);
else if (GetBossState(DATA_FESTERGUT) == DONE)
HandleGameObject(PutricideGateGUIDs[1], false, go);
break;
case GO_SCIENTIST_AIRLOCK_DOOR_GREEN:
PutricideGateGUIDs[1] = go->GetGUID();
if (GetBossState(DATA_ROTFACE) == DONE && GetBossState(DATA_FESTERGUT) == DONE)
go->SetGoState(GO_STATE_DESTROYED);
else if (GetBossState(DATA_ROTFACE) == DONE)
HandleGameObject(PutricideGateGUIDs[1], false, go);
break;
case GO_DOODAD_ICECROWN_ORANGETUBES02:
PutricidePipeGUIDs[0] = go->GetGUID();
if (GetBossState(DATA_FESTERGUT) == DONE)
HandleGameObject(PutricidePipeGUIDs[0], true, go);
break;
case GO_DOODAD_ICECROWN_GREENTUBES02:
PutricidePipeGUIDs[1] = go->GetGUID();
if (GetBossState(DATA_ROTFACE) == DONE)
HandleGameObject(PutricidePipeGUIDs[1], true, go);
break;
case GO_DRINK_ME:
PutricideTableGUID = go->GetGUID();
break;
case GO_CACHE_OF_THE_DREAMWALKER_10N:
case GO_CACHE_OF_THE_DREAMWALKER_25N:
case GO_CACHE_OF_THE_DREAMWALKER_10H:
case GO_CACHE_OF_THE_DREAMWALKER_25H:
if (Creature* valithria = instance->GetCreature(ValithriaDreamwalkerGUID))
go->SetLootRecipient(valithria->GetLootRecipient(), valithria->GetLootRecipientGroup());
go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED | GO_FLAG_NOT_SELECTABLE | GO_FLAG_NODESPAWN);
break;
case GO_ARTHAS_PLATFORM:
// this enables movement at The Frozen Throne, when printed this value is 0.000000f
// however, when represented as integer client will accept only this value
go->SetUInt32Value(GAMEOBJECT_PARENTROTATION, 5535469);
ArthasPlatformGUID = go->GetGUID();
break;
case GO_ARTHAS_PRECIPICE:
go->SetUInt32Value(GAMEOBJECT_PARENTROTATION, 4178312);
ArthasPrecipiceGUID = go->GetGUID();
break;
case GO_DOODAD_ICECROWN_THRONEFROSTYEDGE01:
FrozenThroneEdgeGUID = go->GetGUID();
break;
case GO_DOODAD_ICECROWN_THRONEFROSTYWIND01:
FrozenThroneWindGUID = go->GetGUID();
break;
case GO_DOODAD_ICECROWN_SNOWEDGEWARNING01:
FrozenThroneWarningGUID = go->GetGUID();
break;
case GO_FROZEN_LAVAMAN:
FrozenBolvarGUID = go->GetGUID();
if (GetBossState(DATA_THE_LICH_KING) == DONE)
go->SetRespawnTime(7 * DAY);
break;
case GO_LAVAMAN_PILLARS_CHAINED:
PillarsChainedGUID = go->GetGUID();
if (GetBossState(DATA_THE_LICH_KING) == DONE)
go->SetRespawnTime(7 * DAY);
break;
case GO_LAVAMAN_PILLARS_UNCHAINED:
PillarsUnchainedGUID = go->GetGUID();
if (GetBossState(DATA_THE_LICH_KING) == DONE)
go->SetRespawnTime(7 * DAY);
break;
default:
break;
}
}
void OnGameObjectRemove(GameObject* go) override
{
switch (go->GetEntry())
{
case GO_DOODAD_ICECROWN_ICEWALL02:
case GO_ICEWALL:
case GO_LORD_MARROWGAR_S_ENTRANCE:
case GO_ORATORY_OF_THE_DAMNED_ENTRANCE:
case GO_SAURFANG_S_DOOR:
case GO_ORANGE_PLAGUE_MONSTER_ENTRANCE:
case GO_GREEN_PLAGUE_MONSTER_ENTRANCE:
case GO_SCIENTIST_ENTRANCE:
case GO_CRIMSON_HALL_DOOR:
case GO_BLOOD_ELF_COUNCIL_DOOR:
case GO_BLOOD_ELF_COUNCIL_DOOR_RIGHT:
case GO_DOODAD_ICECROWN_BLOODPRINCE_DOOR_01:
case GO_DOODAD_ICECROWN_GRATE_01:
case GO_GREEN_DRAGON_BOSS_ENTRANCE:
case GO_GREEN_DRAGON_BOSS_EXIT:
case GO_DOODAD_ICECROWN_ROOSTPORTCULLIS_01:
case GO_DOODAD_ICECROWN_ROOSTPORTCULLIS_02:
case GO_DOODAD_ICECROWN_ROOSTPORTCULLIS_03:
case GO_DOODAD_ICECROWN_ROOSTPORTCULLIS_04:
case GO_SINDRAGOSA_ENTRANCE_DOOR:
case GO_SINDRAGOSA_SHORTCUT_ENTRANCE_DOOR:
case GO_SINDRAGOSA_SHORTCUT_EXIT_DOOR:
case GO_ICE_WALL:
AddDoor(go, false);
break;
case GO_THE_SKYBREAKER_A:
case GO_ORGRIMS_HAMMER_H:
GunshipGUID.Clear();
break;
default:
break;
}
}
uint32 GetData(uint32 type) const override
{
switch (type)
{
case DATA_SINDRAGOSA_FROSTWYRMS:
return FrostwyrmGUIDs.size();
case DATA_SPINESTALKER:
return SpinestalkerTrash.size();
case DATA_RIMEFANG:
return RimefangTrash.size();
case DATA_COLDFLAME_JETS:
return ColdflameJetsState;
case DATA_UPPERSPIRE_TELE_ACT:
return UpperSpireTeleporterActiveState;
case DATA_TEAM_IN_INSTANCE:
return TeamInInstance;
case DATA_BLOOD_QUICKENING_STATE:
return BloodQuickeningState;
case DATA_HEROIC_ATTEMPTS:
return HeroicAttempts;
case DATA_BLOOD_PRINCE_COUNCIL_INTRO:
return BloodPrinceIntro;
case DATA_SINDRAGOSA_INTRO:
return SindragosaIntro;
case DATA_FACTION_BUFF:
return IsFactionBuffActive ? 1 : 0;
default:
break;
}
return 0;
}
ObjectGuid GetGuidData(uint32 type) const override
{
switch (type)
{
case DATA_LORD_MARROWGAR:
return LordMarrowgarGUID;
case DATA_LADY_DEATHWHISPER:
return LadyDeahtwhisperGUID;
case DATA_ICECROWN_GUNSHIP_BATTLE:
return GunshipGUID;
case DATA_ENEMY_GUNSHIP:
return EnemyGunshipGUID;
case DATA_DEATHBRINGER_SAURFANG:
return DeathbringerSaurfangGUID;
case DATA_SAURFANG_EVENT_NPC:
return DeathbringerSaurfangEventGUID;
case GO_SAURFANG_S_DOOR:
return DeathbringerSaurfangDoorGUID;
case DATA_FESTERGUT:
return FestergutGUID;
case DATA_ROTFACE:
return RotfaceGUID;
case DATA_PROFESSOR_PUTRICIDE:
return ProfessorPutricideGUID;
case DATA_PUTRICIDE_TABLE:
return PutricideTableGUID;
case DATA_PRINCE_KELESETH:
return BloodCouncilGUIDs[0];
case DATA_PRINCE_TALDARAM:
return BloodCouncilGUIDs[1];
case DATA_PRINCE_VALANAR:
return BloodCouncilGUIDs[2];
case DATA_BLOOD_PRINCES_CONTROL:
return BloodCouncilControllerGUID;
case DATA_BLOOD_QUEEN_LANA_THEL_COUNCIL:
return BloodQueenLanaThelCouncilGUID;
case DATA_BLOOD_QUEEN_LANA_THEL:
return BloodQueenLanaThelGUID;
case DATA_CROK_SCOURGEBANE:
return CrokScourgebaneGUID;
case DATA_CAPTAIN_ARNATH:
case DATA_CAPTAIN_BRANDON:
case DATA_CAPTAIN_GRONDEL:
case DATA_CAPTAIN_RUPERT:
return CrokCaptainGUIDs[type - DATA_CAPTAIN_ARNATH];
case DATA_SISTER_SVALNA:
return SisterSvalnaGUID;
case DATA_VALITHRIA_DREAMWALKER:
return ValithriaDreamwalkerGUID;
case DATA_VALITHRIA_LICH_KING:
return ValithriaLichKingGUID;
case DATA_VALITHRIA_TRIGGER:
return ValithriaTriggerGUID;
case DATA_SINDRAGOSA:
return SindragosaGUID;
case DATA_SPINESTALKER:
return SpinestalkerGUID;
case DATA_RIMEFANG:
return RimefangGUID;
case DATA_THE_LICH_KING:
return TheLichKingGUID;
case DATA_HIGHLORD_TIRION_FORDRING:
return HighlordTirionFordringGUID;
case DATA_ARTHAS_PLATFORM:
return ArthasPlatformGUID;
case DATA_TERENAS_MENETHIL:
return TerenasMenethilGUID;
default:
break;
}
return ObjectGuid::Empty;
}
void HandleHeroicAttempts()
{
if (HeroicAttempts)
{
--HeroicAttempts;
DoUpdateWorldState(WORLDSTATE_ATTEMPTS_REMAINING, HeroicAttempts);
}
if (!HeroicAttempts)
{
for (ObjectGuid const& bossGuid : { ProfessorPutricideGUID, BloodQueenLanaThelGUID, SindragosaGUID, TheLichKingGUID })
{
if (Creature* boss = instance->GetCreature(bossGuid))
if (boss->IsAlive())
boss->DespawnOrUnsummon();
}
}
}
bool SetBossState(uint32 type, EncounterState state) override
{
if (!InstanceScript::SetBossState(type, state))
return false;
switch (type)
{
case DATA_LORD_MARROWGAR:
{
if (state == DONE)
{
if (GameObject* teleporter = instance->GetGameObject(TeleporterLightsHammerGUID))
SetTeleporterState(teleporter, true);
if (GameObject* teleporter = instance->GetGameObject(TeleporterOratoryGUID))
SetTeleporterState(teleporter, true);
}
break;
}
case DATA_LADY_DEATHWHISPER:
{
if (state == DONE)
{
if (GameObject* teleporter = instance->GetGameObject(TeleporterRampartsGUID))
SetTeleporterState(teleporter, true);
if (GameObject* elevator = instance->GetGameObject(LadyDeathwisperElevatorGUID))
{
elevator->SetUInt32Value(GAMEOBJECT_LEVEL, 0);
elevator->SetGoState(GO_STATE_READY);
}
SpawnGunship();
}
break;
}
case DATA_ICECROWN_GUNSHIP_BATTLE:
if (state == DONE)
{
if (GameObject* teleporter = instance->GetGameObject(TeleporterDeathBringerGUID))
SetTeleporterState(teleporter, true);
if (GameObject* loot = instance->GetGameObject(GunshipArmoryGUID))
loot->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED | GO_FLAG_NOT_SELECTABLE | GO_FLAG_NODESPAWN);
}
else if (state == FAIL)
Events.ScheduleEvent(EVENT_RESPAWN_GUNSHIP, 30s);
break;
case DATA_DEATHBRINGER_SAURFANG:
switch (state)
{
case DONE:
{
if (GameObject* loot = instance->GetGameObject(DeathbringersCacheGUID))
{
if (Creature* deathbringer = instance->GetCreature(DeathbringerSaurfangGUID))
loot->SetLootRecipient(deathbringer->GetLootRecipient(), deathbringer->GetLootRecipientGroup());
loot->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED | GO_FLAG_NOT_SELECTABLE | GO_FLAG_NODESPAWN);
}
if (GameObject* teleporter = instance->GetGameObject(TeleporterUpperSpireGUID))
SetTeleporterState(teleporter, true);
if (GameObject* teleporter = instance->GetGameObject(TeleporterDeathBringerGUID))
SetTeleporterState(teleporter, true);
break;
}
case NOT_STARTED:
{
if (GameObject* teleporter = instance->GetGameObject(TeleporterDeathBringerGUID))
SetTeleporterState(teleporter, true);
break;
}
case IN_PROGRESS:
{
if (GameObject* teleporter = instance->GetGameObject(TeleporterDeathBringerGUID))
SetTeleporterState(teleporter, false);
break;
}
default:
break;
}
break;
case DATA_FESTERGUT:
if (state == DONE)
{
if (GetBossState(DATA_ROTFACE) == DONE)
{
HandleGameObject(PutricideCollisionGUID, true);
if (GameObject* go = instance->GetGameObject(PutricideGateGUIDs[0]))
go->SetGoState(GO_STATE_DESTROYED);
if (GameObject* go = instance->GetGameObject(PutricideGateGUIDs[1]))
go->SetGoState(GO_STATE_DESTROYED);
}
else
HandleGameObject(PutricideGateGUIDs[0], false);
HandleGameObject(PutricidePipeGUIDs[0], true);
}
break;
case DATA_ROTFACE:
if (state == DONE)
{
if (GetBossState(DATA_FESTERGUT) == DONE)
{
HandleGameObject(PutricideCollisionGUID, true);
if (GameObject* go = instance->GetGameObject(PutricideGateGUIDs[0]))
go->SetGoState(GO_STATE_DESTROYED);
if (GameObject* go = instance->GetGameObject(PutricideGateGUIDs[1]))
go->SetGoState(GO_STATE_DESTROYED);
}
else
HandleGameObject(PutricideGateGUIDs[1], false);
HandleGameObject(PutricidePipeGUIDs[1], true);
}
break;
case DATA_PROFESSOR_PUTRICIDE:
HandleGameObject(PlagueSigilGUID, state != DONE);
if (instance->IsHeroic() && state == FAIL)
HandleHeroicAttempts();
else if (state == DONE)
CheckLichKingAvailability();
break;
case DATA_BLOOD_QUEEN_LANA_THEL:
HandleGameObject(BloodwingSigilGUID, state != DONE);
if (instance->IsHeroic() && state == FAIL)
HandleHeroicAttempts();
else if (state == DONE)
CheckLichKingAvailability();
break;
case DATA_VALITHRIA_DREAMWALKER:
if (state == DONE)
{
if (sQuestPoolMgr->IsQuestActive(WeeklyQuestData[8].questId[instance->GetSpawnMode() & 1]))
instance->SummonCreature(NPC_VALITHRIA_DREAMWALKER_QUEST, ValithriaSpawnPos);
if (GameObject* teleporter = instance->GetGameObject(TeleporterSindragosaGUID))
SetTeleporterState(teleporter, true);
}
break;
case DATA_SINDRAGOSA:
HandleGameObject(FrostwingSigilGUID, state != DONE);
if (instance->IsHeroic() && state == FAIL)
HandleHeroicAttempts();
else if (state == DONE)
CheckLichKingAvailability();
break;
case DATA_THE_LICH_KING:
{
// set the platform as active object to dramatically increase visibility range
// note: "active" gameobjects do not block grid unloading
if (GameObject* precipice = instance->GetGameObject(ArthasPrecipiceGUID))
precipice->SetFarVisible(state == IN_PROGRESS);
if (GameObject* platform = instance->GetGameObject(ArthasPlatformGUID))
platform->SetFarVisible(state == IN_PROGRESS);
if (instance->IsHeroic() && state == FAIL)
HandleHeroicAttempts();
else if (state == DONE)
{
if (GameObject* bolvar = instance->GetGameObject(FrozenBolvarGUID))
bolvar->SetRespawnTime(7 * DAY);
if (GameObject* pillars = instance->GetGameObject(PillarsChainedGUID))
pillars->SetRespawnTime(7 * DAY);
if (GameObject* pillars = instance->GetGameObject(PillarsUnchainedGUID))
pillars->SetRespawnTime(7 * DAY);
instance->SummonCreature(NPC_LADY_JAINA_PROUDMOORE_QUEST, JainaSpawnPos);
instance->SummonCreature(NPC_MURADIN_BRONZEBEARD_QUEST, MuradinSpawnPos);
instance->SummonCreature(NPC_UTHER_THE_LIGHTBRINGER_QUEST, UtherSpawnPos);
instance->SummonCreature(NPC_LADY_SYLVANAS_WINDRUNNER_QUEST, SylvanasSpawnPos);
}
break;
}
default:
break;
}
return true;
}
void SpawnGunship()
{
if (!GunshipGUID)
{
SetBossState(DATA_ICECROWN_GUNSHIP_BATTLE, NOT_STARTED);
uint32 gunshipEntry = TeamInInstance == HORDE ? GO_ORGRIMS_HAMMER_H : GO_THE_SKYBREAKER_A;
if (Transport* gunship = sTransportMgr->CreateTransport(gunshipEntry, 0, instance))
GunshipGUID = gunship->GetGUID();
}
}
void SetData(uint32 type, uint32 data) override
{
switch (type)
{
case DATA_BONED_ACHIEVEMENT:
IsBonedEligible = data ? true : false;
break;
case DATA_OOZE_DANCE_ACHIEVEMENT:
IsOozeDanceEligible = data ? true : false;
break;
case DATA_NAUSEA_ACHIEVEMENT:
IsNauseaEligible = data ? true : false;
break;
case DATA_ORB_WHISPERER_ACHIEVEMENT:
IsOrbWhispererEligible = data ? true : false;
break;
case DATA_SINDRAGOSA_FROSTWYRMS:
FrostwyrmGUIDs.insert(data);
break;
case DATA_SPINESTALKER:
SpinestalkerTrash.insert(data);
break;
case DATA_RIMEFANG:
RimefangTrash.insert(data);
break;
case DATA_COLDFLAME_JETS:
ColdflameJetsState = data;
if (ColdflameJetsState == DONE)
SaveToDB();
break;
case DATA_BLOOD_QUICKENING_STATE:
{
// skip if nothing changes
if (BloodQuickeningState == data)
break;
// 5 is the index of Blood Quickening
if (!sQuestPoolMgr->IsQuestActive(WeeklyQuestData[5].questId[instance->GetSpawnMode() & 1]))
break;
switch (data)
{
case IN_PROGRESS:
Events.ScheduleEvent(EVENT_UPDATE_EXECUTION_TIME, 1min);
BloodQuickeningMinutes = 30;
DoUpdateWorldState(WORLDSTATE_SHOW_TIMER, 1);
DoUpdateWorldState(WORLDSTATE_EXECUTION_TIME, BloodQuickeningMinutes);
break;
case DONE:
Events.CancelEvent(EVENT_UPDATE_EXECUTION_TIME);
BloodQuickeningMinutes = 0;
DoUpdateWorldState(WORLDSTATE_SHOW_TIMER, 0);
break;
default:
break;
}
BloodQuickeningState = data;
SaveToDB();
break;
}
case DATA_UPPERSPIRE_TELE_ACT:
UpperSpireTeleporterActiveState = data;
if (UpperSpireTeleporterActiveState == DONE)
{
if (GameObject* go = instance->GetGameObject(TeleporterUpperSpireGUID))
SetTeleporterState(go, true);
SaveToDB();
}
break;
case DATA_BLOOD_PRINCE_COUNCIL_INTRO:
BloodPrinceIntro = data;
break;
case DATA_SINDRAGOSA_INTRO:
SindragosaIntro = data;
break;
case DATA_FACTION_BUFF:
IsFactionBuffActive = data ? true : false;
if (!IsFactionBuffActive)
DoRemoveAurasDueToSpellOnPlayers(TeamInInstance == ALLIANCE ? SPELL_STRENGHT_OF_WRYNN : SPELL_HELLSCREAMS_WARSONG, true, true);
break;
default:
break;
}
}
bool CheckAchievementCriteriaMeet(uint32 criteria_id, Player const* /*source*/, Unit const* /*target*/, uint32 /*miscvalue1*/) override
{
switch (criteria_id)
{
case CRITERIA_BONED_10N:
case CRITERIA_BONED_25N:
case CRITERIA_BONED_10H:
case CRITERIA_BONED_25H:
return IsBonedEligible;
case CRITERIA_DANCES_WITH_OOZES_10N:
case CRITERIA_DANCES_WITH_OOZES_25N:
case CRITERIA_DANCES_WITH_OOZES_10H:
case CRITERIA_DANCES_WITH_OOZES_25H:
return IsOozeDanceEligible;
case CRITERIA_NAUSEA_10N:
case CRITERIA_NAUSEA_25N:
case CRITERIA_NAUSEA_10H:
case CRITERIA_NAUSEA_25H:
return IsNauseaEligible;
case CRITERIA_ORB_WHISPERER_10N:
case CRITERIA_ORB_WHISPERER_25N:
case CRITERIA_ORB_WHISPERER_10H:
case CRITERIA_ORB_WHISPERER_25H:
return IsOrbWhispererEligible;
// Only one criteria for both modes, need to do it like this
case CRITERIA_KILL_LANA_THEL_10M:
case CRITERIA_ONCE_BITTEN_TWICE_SHY_10N:
case CRITERIA_ONCE_BITTEN_TWICE_SHY_10V:
return instance->ToInstanceMap()->GetMaxPlayers() == 10;
case CRITERIA_KILL_LANA_THEL_25M:
case CRITERIA_ONCE_BITTEN_TWICE_SHY_25N:
case CRITERIA_ONCE_BITTEN_TWICE_SHY_25V:
return instance->ToInstanceMap()->GetMaxPlayers() == 25;
default:
break;
}
return false;
}
bool CheckRequiredBosses(uint32 bossId, Player const* player = nullptr) const override
{
if (_SkipCheckRequiredBosses(player))
return true;
switch (bossId)
{
case DATA_THE_LICH_KING:
if (!CheckPlagueworks(bossId))
return false;
if (!CheckCrimsonHalls(bossId))
return false;
if (!CheckFrostwingHalls(bossId))
return false;
break;
case DATA_SINDRAGOSA:
case DATA_VALITHRIA_DREAMWALKER:
if (!CheckFrostwingHalls(bossId))
return false;
break;
case DATA_BLOOD_QUEEN_LANA_THEL:
case DATA_BLOOD_PRINCE_COUNCIL:
if (!CheckCrimsonHalls(bossId))
return false;
break;
case DATA_FESTERGUT:
case DATA_ROTFACE:
case DATA_PROFESSOR_PUTRICIDE:
if (!CheckPlagueworks(bossId))
return false;
break;
default:
break;
}
if (!CheckLowerSpire(bossId))
return false;
return true;
}
bool CheckPlagueworks(uint32 bossId) const
{
switch (bossId)
{
case DATA_THE_LICH_KING:
if (GetBossState(DATA_PROFESSOR_PUTRICIDE) != DONE)
return false;
[[fallthrough]];
case DATA_PROFESSOR_PUTRICIDE:
if (GetBossState(DATA_FESTERGUT) != DONE || GetBossState(DATA_ROTFACE) != DONE)
return false;
break;
default:
break;
}
return true;
}
bool CheckCrimsonHalls(uint32 bossId) const
{
switch (bossId)
{
case DATA_THE_LICH_KING:
if (GetBossState(DATA_BLOOD_QUEEN_LANA_THEL) != DONE)
return false;
[[fallthrough]];
case DATA_BLOOD_QUEEN_LANA_THEL:
if (GetBossState(DATA_BLOOD_PRINCE_COUNCIL) != DONE)
return false;
break;
default:
break;
}
return true;
}
bool CheckFrostwingHalls(uint32 bossId) const
{
switch (bossId)
{
case DATA_THE_LICH_KING:
if (GetBossState(DATA_SINDRAGOSA) != DONE)
return false;
[[fallthrough]];
case DATA_SINDRAGOSA:
if (GetBossState(DATA_VALITHRIA_DREAMWALKER) != DONE)
return false;
break;
default:
break;
}
return true;
}
bool CheckLowerSpire(uint32 bossId) const
{
switch (bossId)
{
case DATA_THE_LICH_KING:
case DATA_SINDRAGOSA:
case DATA_BLOOD_QUEEN_LANA_THEL:
case DATA_PROFESSOR_PUTRICIDE:
case DATA_VALITHRIA_DREAMWALKER:
case DATA_BLOOD_PRINCE_COUNCIL:
case DATA_ROTFACE:
case DATA_FESTERGUT:
if (GetBossState(DATA_DEATHBRINGER_SAURFANG) != DONE)
return false;
[[fallthrough]];
case DATA_DEATHBRINGER_SAURFANG:
if (GetBossState(DATA_ICECROWN_GUNSHIP_BATTLE) != DONE)
return false;
[[fallthrough]];
case DATA_ICECROWN_GUNSHIP_BATTLE:
if (GetBossState(DATA_LADY_DEATHWHISPER) != DONE)
return false;
[[fallthrough]];
case DATA_LADY_DEATHWHISPER:
if (GetBossState(DATA_LORD_MARROWGAR) != DONE)
return false;
[[fallthrough]];
case DATA_LORD_MARROWGAR:
default:
break;
}
return true;
}
void CheckLichKingAvailability()
{
if (GetBossState(DATA_PROFESSOR_PUTRICIDE) == DONE && GetBossState(DATA_BLOOD_QUEEN_LANA_THEL) == DONE && GetBossState(DATA_SINDRAGOSA) == DONE)
{
if (GameObject* teleporter = instance->GetGameObject(TheLichKingTeleportGUID))
{
teleporter->SetGoState(GO_STATE_ACTIVE);
std::list<Creature*> stalkers;
teleporter->GetCreatureListWithEntryInGrid(stalkers, NPC_INVISIBLE_STALKER, 100.0f);
if (stalkers.empty())
return;
stalkers.sort(Trinity::ObjectDistanceOrderPred(teleporter));
stalkers.front()->CastSpell(nullptr, SPELL_ARTHAS_TELEPORTER_CEREMONY, false);
stalkers.pop_front();
for (std::list<Creature*>::iterator itr = stalkers.begin(); itr != stalkers.end(); ++itr)
(*itr)->AI()->Reset();
}
}
}
void WriteSaveDataMore(std::ostringstream& data) override
{
data << HeroicAttempts << ' '
<< ColdflameJetsState << ' '
<< BloodQuickeningState << ' '
<< BloodQuickeningMinutes << ' '
<< UpperSpireTeleporterActiveState;
}
void ReadSaveDataMore(std::istringstream& data) override
{
uint32 temp = 0;
data >> HeroicAttempts;
data >> temp;
ColdflameJetsState = temp == DONE ? DONE : NOT_STARTED;
data >> temp;
BloodQuickeningState = temp == DONE ? DONE : NOT_STARTED;
data >> BloodQuickeningMinutes;
data >> temp;
UpperSpireTeleporterActiveState = temp == DONE ? DONE : NOT_STARTED;
}
void Update(uint32 diff) override
{
if (BloodQuickeningState != IN_PROGRESS && GetBossState(DATA_THE_LICH_KING) != IN_PROGRESS && GetBossState(DATA_ICECROWN_GUNSHIP_BATTLE) != FAIL)
return;
Events.Update(diff);
while (uint32 eventId = Events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_UPDATE_EXECUTION_TIME:
{
--BloodQuickeningMinutes;
if (BloodQuickeningMinutes)
{
Events.ScheduleEvent(EVENT_UPDATE_EXECUTION_TIME, 1min);
DoUpdateWorldState(WORLDSTATE_SHOW_TIMER, 1);
DoUpdateWorldState(WORLDSTATE_EXECUTION_TIME, BloodQuickeningMinutes);
}
else
{
BloodQuickeningState = DONE;
DoUpdateWorldState(WORLDSTATE_SHOW_TIMER, 0);
if (Creature* bq = instance->GetCreature(BloodQueenLanaThelGUID))
bq->AI()->DoAction(ACTION_KILL_MINCHAR);
}
SaveToDB();
break;
}
case EVENT_QUAKE_SHATTER:
{
if (GameObject* platform = instance->GetGameObject(ArthasPlatformGUID))
platform->SetDestructibleState(GO_DESTRUCTIBLE_DAMAGED);
if (GameObject* edge = instance->GetGameObject(FrozenThroneEdgeGUID))
edge->SetGoState(GO_STATE_ACTIVE);
if (GameObject* wind = instance->GetGameObject(FrozenThroneWindGUID))
wind->SetGoState(GO_STATE_READY);
if (GameObject* warning = instance->GetGameObject(FrozenThroneWarningGUID))
warning->SetGoState(GO_STATE_READY);
if (Creature* theLichKing = instance->GetCreature(TheLichKingGUID))
theLichKing->AI()->DoAction(ACTION_RESTORE_LIGHT);
break;
}
case EVENT_REBUILD_PLATFORM:
if (GameObject* platform = instance->GetGameObject(ArthasPlatformGUID))
platform->SetDestructibleState(GO_DESTRUCTIBLE_REBUILDING);
if (GameObject* edge = instance->GetGameObject(FrozenThroneEdgeGUID))
edge->SetGoState(GO_STATE_READY);
if (GameObject* wind = instance->GetGameObject(FrozenThroneWindGUID))
wind->SetGoState(GO_STATE_ACTIVE);
break;
case EVENT_RESPAWN_GUNSHIP:
SpawnGunship();
break;
default:
break;
}
}
}
void ProcessEvent(WorldObject* source, uint32 eventId) override
{
switch (eventId)
{
case EVENT_ENEMY_GUNSHIP_DESPAWN:
if (GetBossState(DATA_ICECROWN_GUNSHIP_BATTLE) == DONE)
source->AddObjectToRemoveList();
break;
case EVENT_ENEMY_GUNSHIP_COMBAT:
if (Creature* captain = source->FindNearestCreature(TeamInInstance == HORDE ? NPC_IGB_HIGH_OVERLORD_SAURFANG : NPC_IGB_MURADIN_BRONZEBEARD, 100.0f))
captain->AI()->DoAction(ACTION_ENEMY_GUNSHIP_TALK);
[[fallthrough]];
case EVENT_PLAYERS_GUNSHIP_SPAWN:
case EVENT_PLAYERS_GUNSHIP_COMBAT:
if (GameObject* go = source->ToGameObject())
if (Transport* transport = go->ToTransport())
transport->EnableMovement(false);
break;
case EVENT_PLAYERS_GUNSHIP_SAURFANG:
if (Creature* captain = source->FindNearestCreature(TeamInInstance == HORDE ? NPC_IGB_HIGH_OVERLORD_SAURFANG : NPC_IGB_MURADIN_BRONZEBEARD, 100.0f))
captain->AI()->DoAction(ACTION_EXIT_SHIP);
if (GameObject* go = source->ToGameObject())
if (Transport* transport = go->ToTransport())
transport->EnableMovement(false);
break;
case EVENT_QUAKE:
if (GameObject* warning = instance->GetGameObject(FrozenThroneWarningGUID))
warning->SetGoState(GO_STATE_ACTIVE);
Events.ScheduleEvent(EVENT_QUAKE_SHATTER, 5s);
break;
case EVENT_SECOND_REMORSELESS_WINTER:
if (GameObject* platform = instance->GetGameObject(ArthasPlatformGUID))
{
platform->SetDestructibleState(GO_DESTRUCTIBLE_DESTROYED);
Events.ScheduleEvent(EVENT_REBUILD_PLATFORM, 1500ms);
}
break;
case EVENT_TELEPORT_TO_FROSTMOURNE: // Harvest Soul (normal mode)
if (Creature* terenas = instance->SummonCreature(NPC_TERENAS_MENETHIL_FROSTMOURNE, TerenasSpawn, nullptr, 63000))
{
terenas->AI()->DoAction(ACTION_FROSTMOURNE_INTRO);
std::list<Creature*> triggers;
terenas->GetCreatureListWithEntryInGrid(triggers, NPC_WORLD_TRIGGER_INFINITE_AOI, 100.0f);
if (!triggers.empty())
{
triggers.sort(Trinity::ObjectDistanceOrderPred(terenas, false));
Unit* visual = triggers.front();
visual->CastSpell(visual, SPELL_FROSTMOURNE_TELEPORT_VISUAL, true);
}
if (Creature* warden = instance->SummonCreature(NPC_SPIRIT_WARDEN, SpiritWardenSpawn, nullptr, 63000))
{
terenas->AI()->AttackStart(warden);
warden->GetThreatManager().AddThreat(terenas, 300000.0f, nullptr, true, true);
}
}
break;
default:
break;
}
}
protected:
EventMap Events;
ObjectGuid LordMarrowgarGUID;
ObjectGuid LadyDeahtwhisperGUID;
ObjectGuid LadyDeathwisperElevatorGUID;
ObjectGuid GunshipGUID;
ObjectGuid EnemyGunshipGUID;
ObjectGuid GunshipArmoryGUID;
ObjectGuid DeathbringerSaurfangGUID;
ObjectGuid DeathbringerSaurfangDoorGUID;
ObjectGuid DeathbringerSaurfangEventGUID; // Muradin Bronzebeard or High Overlord Saurfang
ObjectGuid DeathbringersCacheGUID;
ObjectGuid TeleporterLichKingGUID;
ObjectGuid TeleporterUpperSpireGUID;
ObjectGuid TeleporterLightsHammerGUID;
ObjectGuid TeleporterRampartsGUID;
ObjectGuid TeleporterDeathBringerGUID;
ObjectGuid TeleporterOratoryGUID;
ObjectGuid TeleporterSindragosaGUID;
ObjectGuid PlagueSigilGUID;
ObjectGuid BloodwingSigilGUID;
ObjectGuid FrostwingSigilGUID;
ObjectGuid PutricidePipeGUIDs[2];
ObjectGuid PutricideGateGUIDs[2];
ObjectGuid PutricideCollisionGUID;
ObjectGuid FestergutGUID;
ObjectGuid RotfaceGUID;
ObjectGuid ProfessorPutricideGUID;
ObjectGuid PutricideTableGUID;
ObjectGuid BloodCouncilGUIDs[3];
ObjectGuid BloodCouncilControllerGUID;
ObjectGuid BloodQueenLanaThelCouncilGUID;
ObjectGuid BloodQueenLanaThelGUID;
ObjectGuid CrokScourgebaneGUID;
ObjectGuid CrokCaptainGUIDs[4];
ObjectGuid SisterSvalnaGUID;
ObjectGuid ValithriaDreamwalkerGUID;
ObjectGuid ValithriaLichKingGUID;
ObjectGuid ValithriaTriggerGUID;
ObjectGuid SindragosaGUID;
ObjectGuid SpinestalkerGUID;
ObjectGuid RimefangGUID;
ObjectGuid TheLichKingTeleportGUID;
ObjectGuid TheLichKingGUID;
ObjectGuid HighlordTirionFordringGUID;
ObjectGuid TerenasMenethilGUID;
ObjectGuid ArthasPlatformGUID;
ObjectGuid ArthasPrecipiceGUID;
ObjectGuid FrozenThroneEdgeGUID;
ObjectGuid FrozenThroneWindGUID;
ObjectGuid FrozenThroneWarningGUID;
ObjectGuid FrozenBolvarGUID;
ObjectGuid PillarsChainedGUID;
ObjectGuid PillarsUnchainedGUID;
uint32 TeamInInstance;
uint32 ColdflameJetsState;
uint32 UpperSpireTeleporterActiveState;
std::unordered_set<uint32> FrostwyrmGUIDs;
std::unordered_set<uint32> SpinestalkerTrash;
std::unordered_set<uint32> RimefangTrash;
uint32 BloodQuickeningState;
uint32 HeroicAttempts;
uint16 BloodQuickeningMinutes;
uint8 BloodPrinceIntro;
uint8 SindragosaIntro;
bool IsBonedEligible;
bool IsOozeDanceEligible;
bool IsNauseaEligible;
bool IsOrbWhispererEligible;
bool IsFactionBuffActive;
};
InstanceScript* GetInstanceScript(InstanceMap* map) const override
{
return new instance_icecrown_citadel_InstanceMapScript(map);
}
};
void AddSC_instance_icecrown_citadel()
{
new instance_icecrown_citadel();
}
|
Treeston/TrinityCore
|
src/server/scripts/Northrend/IcecrownCitadel/instance_icecrown_citadel.cpp
|
C++
|
gpl-2.0
| 77,060
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<title>org.myrobotlab.framework Class Hierarchy</title>
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.myrobotlab.framework Class Hierarchy";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/myrobotlab/fileLib/package-tree.html">Prev</a></li>
<li><a href="../../../org/myrobotlab/framework/repo/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/myrobotlab/framework/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package org.myrobotlab.framework</h1>
<span class="strong">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/BootstrapDalvik.html" title="class in org.myrobotlab.framework"><span class="strong">BootstrapDalvik</span></a> (implements org.myrobotlab.service.interfaces.<a href="../../../org/myrobotlab/service/interfaces/Bootstrap.html" title="interface in org.myrobotlab.service.interfaces">Bootstrap</a>)</li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/BootstrapFactory.html" title="class in org.myrobotlab.framework"><span class="strong">BootstrapFactory</span></a></li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/BootstrapHotSpot.html" title="class in org.myrobotlab.framework"><span class="strong">BootstrapHotSpot</span></a> (implements org.myrobotlab.service.interfaces.<a href="../../../org/myrobotlab/service/interfaces/Bootstrap.html" title="interface in org.myrobotlab.service.interfaces">Bootstrap</a>)</li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/Encoder.html" title="class in org.myrobotlab.framework"><span class="strong">Encoder</span></a></li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/Inbox.html" title="class in org.myrobotlab.framework"><span class="strong">Inbox</span></a> (implements java.io.Serializable)</li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/Index.html" title="class in org.myrobotlab.framework"><span class="strong">Index</span></a><T></li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/IndexNode.html" title="class in org.myrobotlab.framework"><span class="strong">IndexNode</span></a><T></li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/Message.html" title="class in org.myrobotlab.framework"><span class="strong">Message</span></a> (implements java.io.Serializable)</li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/MessageFormatter.html" title="class in org.myrobotlab.framework"><span class="strong">MessageFormatter</span></a></li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/MethodCache.html" title="class in org.myrobotlab.framework"><span class="strong">MethodCache</span></a></li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/MethodEntry.html" title="class in org.myrobotlab.framework"><span class="strong">MethodEntry</span></a> (implements java.io.Serializable)</li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/MRLListener.html" title="class in org.myrobotlab.framework"><span class="strong">MRLListener</span></a> (implements java.io.Serializable)</li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/ObjectCloner.html" title="class in org.myrobotlab.framework"><span class="strong">ObjectCloner</span></a></li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/Outbox.html" title="class in org.myrobotlab.framework"><span class="strong">Outbox</span></a> (implements java.lang.Runnable, java.io.Serializable)</li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/Peers.html" title="class in org.myrobotlab.framework"><span class="strong">Peers</span></a></li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/Platform.html" title="class in org.myrobotlab.framework"><span class="strong">Platform</span></a> (implements java.io.Serializable)</li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/PreLogger.html" title="class in org.myrobotlab.framework"><span class="strong">PreLogger</span></a></li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/RoutingEntry.html" title="class in org.myrobotlab.framework"><span class="strong">RoutingEntry</span></a> (implements java.io.Serializable)</li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/Service.html" title="class in org.myrobotlab.framework"><span class="strong">Service</span></a> (implements java.lang.Runnable, java.io.Serializable, org.myrobotlab.service.interfaces.<a href="../../../org/myrobotlab/service/interfaces/ServiceInterface.html" title="interface in org.myrobotlab.service.interfaces">ServiceInterface</a>)</li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/ServiceEnvironment.html" title="class in org.myrobotlab.framework"><span class="strong">ServiceEnvironment</span></a> (implements java.io.Serializable)</li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/ServiceReservation.html" title="class in org.myrobotlab.framework"><span class="strong">ServiceReservation</span></a></li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/SOAP.html" title="class in org.myrobotlab.framework"><span class="strong">SOAP</span></a></li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/Status.html" title="class in org.myrobotlab.framework"><span class="strong">Status</span></a> (implements java.io.Serializable)</li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/StopWatch.html" title="class in org.myrobotlab.framework"><span class="strong">StopWatch</span></a></li>
<li type="circle">java.lang.Throwable (implements java.io.Serializable)
<ul>
<li type="circle">java.lang.Exception
<ul>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/Errors.html" title="class in org.myrobotlab.framework"><span class="strong">Errors</span></a></li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/MRLError.html" title="class in org.myrobotlab.framework"><span class="strong">MRLError</span></a></li>
</ul>
</li>
</ul>
</li>
<li type="circle">java.util.TimerTask (implements java.lang.Runnable)
<ul>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/Task.html" title="class in org.myrobotlab.framework"><span class="strong">Task</span></a></li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 title="Interface Hierarchy">Interface Hierarchy</h2>
<ul>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/MessageListener.html" title="interface in org.myrobotlab.framework"><span class="strong">MessageListener</span></a></li>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/MessageSender.html" title="interface in org.myrobotlab.framework"><span class="strong">MessageSender</span></a></li>
</ul>
<h2 title="Annotation Type Hierarchy">Annotation Type Hierarchy</h2>
<ul>
<li type="circle">org.myrobotlab.framework.<a href="../../../org/myrobotlab/framework/ToolTip.html" title="annotation in org.myrobotlab.framework"><span class="strong">ToolTip</span></a> (implements java.lang.annotation.Annotation)</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/myrobotlab/fileLib/package-tree.html">Prev</a></li>
<li><a href="../../../org/myrobotlab/framework/repo/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/myrobotlab/framework/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
glaudiston/project-bianca
|
arduino/code/myrobotlab-1.0.119/javadoc/org/myrobotlab/framework/package-tree.html
|
HTML
|
gpl-2.0
| 11,186
|
/* Copyright (C) 2000 Philipp Rumpf <prumpf@tux.org>
* Copyright (C) 2006 Kyle McMartin <kyle@parisc-linux.org>
*/
#ifndef _ASM_PARISC_ATOMIC_H_
#define _ASM_PARISC_ATOMIC_H_
#include <linux/types.h>
#include <asm/cmpxchg.h>
/*
* Atomic operations that C can't guarantee us. Useful for
* resource counting etc..
*
* And probably incredibly slow on parisc. OTOH, we don't
* have to write any serious assembly. prumpf
*/
#ifdef CONFIG_SMP
#include <asm/spinlock.h>
#include <asm/cache.h> /* we use L1_CACHE_BYTES */
/* Use an array of spinlocks for our atomic_ts.
* Hash function to index into a different SPINLOCK.
* Since "a" is usually an address, use one spinlock per cacheline.
*/
# define ATOMIC_HASH_SIZE 4
# define ATOMIC_HASH(a) (&(__atomic_hash[ (((unsigned long) (a))/L1_CACHE_BYTES) & (ATOMIC_HASH_SIZE-1) ]))
extern arch_spinlock_t __atomic_hash[ATOMIC_HASH_SIZE] __lock_aligned;
/* Can't use raw_spin_lock_irq because of #include problems, so
* this is the substitute */
#define _atomic_spin_lock_irqsave(l,f) do { \
arch_spinlock_t *s = ATOMIC_HASH(l); \
local_irq_save(f); \
arch_spin_lock(s); \
} while(0)
#define _atomic_spin_unlock_irqrestore(l,f) do { \
arch_spinlock_t *s = ATOMIC_HASH(l); \
arch_spin_unlock(s); \
local_irq_restore(f); \
} while(0)
#else
# define _atomic_spin_lock_irqsave(l,f) do { local_irq_save(f); } while (0)
# define _atomic_spin_unlock_irqrestore(l,f) do { local_irq_restore(f); } while (0)
#endif
/*
* Note that we need not lock read accesses - aligned word writes/reads
* are atomic, so a reader never sees inconsistent values.
*/
/* It's possible to reduce all atomic operations to either
* __atomic_add_return, atomic_set and atomic_read (the latter
* is there only for consistency).
*/
static __inline__ int __atomic_add_return(int i, atomic_t *v)
{
int ret;
unsigned long flags;
_atomic_spin_lock_irqsave(v, flags);
ret = (v->counter += i);
_atomic_spin_unlock_irqrestore(v, flags);
return ret;
}
static __inline__ void atomic_set(atomic_t *v, int i)
{
unsigned long flags;
_atomic_spin_lock_irqsave(v, flags);
v->counter = i;
_atomic_spin_unlock_irqrestore(v, flags);
}
static __inline__ int atomic_read(const atomic_t *v)
{
return (*(volatile int *)&(v)->counter);
}
/* exported interface */
#define atomic_cmpxchg(v, o, n) (cmpxchg(&((v)->counter), (o), (n)))
#define atomic_xchg(v, new) (xchg(&((v)->counter), new))
/**
* __atomic_add_unless - add unless the number is a given value
* @v: pointer of type atomic_t
* @a: the amount to add to v...
* @u: ...unless v is equal to u.
*
* Atomically adds @a to @v, so long as it was not @u.
* Returns the old value of @v.
*/
static __inline__ int __atomic_add_unless(atomic_t *v, int a, int u)
{
int c, old;
c = atomic_read(v);
for (;;) {
if (unlikely(c == (u)))
break;
old = atomic_cmpxchg((v), c, c + (a));
if (likely(old == c))
break;
c = old;
}
return c;
}
#define atomic_add(i,v) ((void)(__atomic_add_return( (i),(v))))
#define atomic_sub(i,v) ((void)(__atomic_add_return(-(i),(v))))
#define atomic_inc(v) ((void)(__atomic_add_return( 1,(v))))
#define atomic_dec(v) ((void)(__atomic_add_return( -1,(v))))
#define atomic_add_return(i,v) (__atomic_add_return( (i),(v)))
#define atomic_sub_return(i,v) (__atomic_add_return(-(i),(v)))
#define atomic_inc_return(v) (__atomic_add_return( 1,(v)))
#define atomic_dec_return(v) (__atomic_add_return( -1,(v)))
#define atomic_add_negative(a, v) (atomic_add_return((a), (v)) < 0)
/*
* atomic_inc_and_test - increment and test
* @v: pointer of type atomic_t
*
* Atomically increments @v by 1
* and returns true if the result is zero, or false for all
* other cases.
*/
#define atomic_inc_and_test(v) (atomic_inc_return(v) == 0)
#define atomic_dec_and_test(v) (atomic_dec_return(v) == 0)
#define atomic_sub_and_test(i,v) (atomic_sub_return((i),(v)) == 0)
#define ATOMIC_INIT(i) ((atomic_t) { (i) })
#define smp_mb__before_atomic_dec() smp_mb()
#define smp_mb__after_atomic_dec() smp_mb()
#define smp_mb__before_atomic_inc() smp_mb()
#define smp_mb__after_atomic_inc() smp_mb()
#ifdef CONFIG_64BIT
#define ATOMIC64_INIT(i) ((atomic64_t) { (i) })
static __inline__ s64
__atomic64_add_return(s64 i, atomic64_t *v)
{
s64 ret;
unsigned long flags;
_atomic_spin_lock_irqsave(v, flags);
ret = (v->counter += i);
_atomic_spin_unlock_irqrestore(v, flags);
return ret;
}
static __inline__ void
atomic64_set(atomic64_t *v, s64 i)
{
unsigned long flags;
_atomic_spin_lock_irqsave(v, flags);
v->counter = i;
_atomic_spin_unlock_irqrestore(v, flags);
}
static __inline__ s64
atomic64_read(const atomic64_t *v)
{
return (*(volatile long *)&(v)->counter);
}
#define atomic64_add(i,v) ((void)(__atomic64_add_return( ((s64)(i)),(v))))
#define atomic64_sub(i,v) ((void)(__atomic64_add_return(-((s64)(i)),(v))))
#define atomic64_inc(v) ((void)(__atomic64_add_return( 1,(v))))
#define atomic64_dec(v) ((void)(__atomic64_add_return( -1,(v))))
#define atomic64_add_return(i,v) (__atomic64_add_return( ((s64)(i)),(v)))
#define atomic64_sub_return(i,v) (__atomic64_add_return(-((s64)(i)),(v)))
#define atomic64_inc_return(v) (__atomic64_add_return( 1,(v)))
#define atomic64_dec_return(v) (__atomic64_add_return( -1,(v)))
#define atomic64_add_negative(a, v) (atomic64_add_return((a), (v)) < 0)
#define atomic64_inc_and_test(v) (atomic64_inc_return(v) == 0)
#define atomic64_dec_and_test(v) (atomic64_dec_return(v) == 0)
#define atomic64_sub_and_test(i,v) (atomic64_sub_return((i),(v)) == 0)
/* exported interface */
#define atomic64_cmpxchg(v, o, n) \
((__typeof__((v)->counter))cmpxchg(&((v)->counter), (o), (n)))
#define atomic64_xchg(v, new) (xchg(&((v)->counter), new))
/**
* atomic64_add_unless - add unless the number is a given value
* @v: pointer of type atomic64_t
* @a: the amount to add to v...
* @u: ...unless v is equal to u.
*
* Atomically adds @a to @v, so long as it was not @u.
* Returns the old value of @v.
*/
static __inline__ int atomic64_add_unless(atomic64_t *v, long a, long u)
{
long c, old;
c = atomic64_read(v);
for (;;) {
if (unlikely(c == (u)))
break;
old = atomic64_cmpxchg((v), c, c + (a));
if (likely(old == c))
break;
c = old;
}
return c != (u);
}
#define atomic64_inc_not_zero(v) atomic64_add_unless((v), 1, 0)
#endif /* !CONFIG_64BIT */
#endif /* _ASM_PARISC_ATOMIC_H_ */
|
Jackeagle/android_kernel_sony_c2305
|
arch/parisc/include/asm/atomic.h
|
C
|
gpl-2.0
| 6,652
|
<?php
/* Worthless page, but WordPress needs it for some reason */
?>
|
Koda1004/harvardrunningclub
|
wp-content/themes/simple and clean/index.php
|
PHP
|
gpl-2.0
| 74
|
<?php
/**
* Model for EAD3 records in Solr.
*
* PHP version 5
*
* Copyright (C) Villanova University 2010.
* Copyright (C) The National Library of Finland 2012-2020.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* 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
*
* @category VuFind
* @package RecordDrivers
* @author Ere Maijala <ere.maijala@helsinki.fi>
* @author Samuli Sillanpää <samuli.sillanpaa@helsinki.fi>
* @author Konsta Raunio <konsta.raunio@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link http://vufind.org/wiki/vufind2:record_drivers Wiki
*/
namespace Finna\RecordDriver;
/**
* Model for EAD3 records in Solr.
*
* @category VuFind
* @package RecordDrivers
* @author Ere Maijala <ere.maijala@helsinki.fi>
* @author Samuli Sillanpää <samuli.sillanpaa@helsinki.fi>
* @author Konsta Raunio <konsta.raunio@helsinki.fi>
* @author Demian Katz <demian.katz@villanova.edu>
* @author Eoghan O'Carragain <Eoghan.OCarragan@gmail.com>
* @author Luke O'Sullivan <l.osullivan@swansea.ac.uk>
* @author Lutz Biedinger <lutz.Biedinger@gmail.com>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link http://vufind.org/wiki/vufind2:record_drivers Wiki
*/
class SolrEad3 extends SolrEad
{
// Image types
const IMAGE_MEDIUM = 'medium';
const IMAGE_LARGE = 'large';
const IMAGE_FULLRES = 'fullres';
const IMAGE_OCR = 'ocr';
// Image type map
const IMAGE_MAP = [
'Bittikartta - Fullres - Jakelukappale' => self::IMAGE_FULLRES,
'Bittikartta - Pikkukuva - Jakelukappale' => self::IMAGE_MEDIUM,
'OCR-data - Alto - Jakelukappale' => self::IMAGE_OCR,
'fullsize' => self::IMAGE_FULLRES,
'thumbnail' => self::IMAGE_MEDIUM
];
// URLs that are displayed on ExternalData record tab
// (not below record title)
const EXTERNAL_DATA_URLS = [
'Bittikartta - Fullres - Jakelukappale',
'Bittikartta - Pikkukuva - Jakelukappale',
'OCR-data - Alto - Jakelukappale',
];
// Altformavail labels
const ALTFORM_LOCATION = 'location';
const ALTFORM_PHYSICAL_LOCATION = 'physicalLocation';
const ALTFORM_TYPE = 'type';
const ALTFORM_DIGITAL_TYPE = 'digitalType';
const ALTFORM_FORMAT = 'format';
const ALTFORM_ACCESS = 'access';
const ALTFORM_ONLINE = 'online';
const ALTFORM_CONDITION = 'condition';
// Altformavail label map
const ALTFORM_MAP = [
'Tietopalvelun tarjoamispaikka' => self::ALTFORM_LOCATION,
'Tekninen tyyppi' => self::ALTFORM_TYPE,
'Digitaalisen ilmentymän tyyppi' => self::ALTFORM_DIGITAL_TYPE,
'Tallennusalusta' => self::ALTFORM_FORMAT,
'Digitaalisen aineiston tiedostomuoto' => self::ALTFORM_FORMAT,
'Ilmentymän kuntoon perustuva käyttörajoitus'
=> self::ALTFORM_ACCESS,
'Manifestation\'s access restrictions' => self::ALTFORM_ACCESS,
'Bruk av manifestationen har begränsats pga' => self::ALTFORM_ACCESS,
'Internet - ei fyysistä toimipaikkaa' => self::ALTFORM_ONLINE,
'Lisätietoa kunnosta' => self::ALTFORM_CONDITION,
'Säilytysyksikön tunniste' => self::ALTFORM_PHYSICAL_LOCATION,
];
// Accessrestrict types and their order in the UI
const ACCESS_RESTRICT_TYPES = [
'ahaa:AI24','general', 'ahaa:KR1', 'ahaa:KR2', 'ahaa:KR3',
'ahaa:KR5', 'ahaa:KR7', 'ahaa:KR9', 'ahaa:KR4'
];
// relation@encodinganalog-attribute of relations used by getRelatedRecords
const RELATION_RECORD = 'ahaa:AI30';
// relation@encodinganalog-attributes that are discarded from record links
const IGNORED_RELATIONS = [self::RELATION_RECORD, 'ahaa:AI41'];
// Relation types
const RELATION_CONTINUED_FROM = 'continued-from';
const RELATION_PART_OF = 'part-of';
const RELATION_CONTAINS = 'contains';
const RELATION_SEE_ALSO = 'see-also';
const RELATION_SEPARATED = 'separated';
// Relation type map
const RELATION_MAP = [
'On jatkoa' => self::RELATION_CONTINUED_FROM,
'Sisältyy' => self::RELATION_PART_OF,
'Sisältää' => self::RELATION_CONTAINS,
'Katso myös' => self::RELATION_SEE_ALSO,
'Erotettu aineisto' => self::RELATION_SEPARATED
];
// Relator attribute for archive origination
const RELATOR_ARCHIVE_ORIGINATION = 'Arkistonmuodostaja';
const RELATOR_TIME_INTERVAL = 'suhteen ajallinen kattavuus';
const RELATOR_UNKNOWN_TIME_INTERVAL = 'unknown - open';
// unitid is shown when label-attribute is missing or is one of:
const UNIT_IDS = [
'Tekninen', 'Analoginen', 'Vanha analoginen', 'Vanha tekninen',
'Diaarinumero', 'Asiaryhmän numero'
];
/**
* Get the institutions holding the record.
*
* @return array
*/
public function getInstitutions()
{
$result = parent::getInstitutions();
if (! $this->preferredLanguage) {
return $result;
}
if ($name = $this->getRepositoryName()) {
return [$name];
}
return $result;
}
/**
* Return buildings from index.
*
* @return array
*/
public function getBuildings()
{
if ($this->preferredLanguage && $name = $this->getRepositoryName()) {
return [$name];
}
return parent::getBuildings();
}
/**
* Return an array of associative URL arrays with one or more of the following
* keys:
*
* <li>
* <ul>desc: URL description text to display (optional)</ul>
* <ul>url: fully-formed URL (required if 'route' is absent)</ul>
* <ul>route: VuFind route to build URL with (required if 'url' is absent)</ul>
* <ul>routeParams: Parameters for route (optional)</ul>
* <ul>queryString: Query params to append after building route (optional)</ul>
* </li>
*
* @return array
*/
public function getURLs()
{
$urls = $localeUrls = [];
$url = '';
$record = $this->getXmlRecord();
$preferredLangCodes = $this->mapLanguageCode($this->preferredLanguage);
foreach ($record->did->xpath('//daoset') as $daoset) {
$localtype = (string)$daoset->attributes()->localtype;
if ($localtype && in_array($localtype, self::EXTERNAL_DATA_URLS)) {
continue;
}
foreach ($daoset->dao as $node) {
$attr = $node->attributes();
if ((string)$attr->linkrole === 'image/jpeg' || !$attr->href) {
continue;
}
$lang = (string)$attr->lang;
$preferredLang = $lang && in_array($lang, $preferredLangCodes);
$url = (string)$attr->href;
$desc = $attr->linktitle ?? $node->descriptivenote->p ?? $url;
if (!$this->urlBlocked($url, $desc)) {
$urlData = [
'url' => $url,
'desc' => (string)$desc
];
$urls[] = $urlData;
if ($preferredLang) {
$localeUrls[] = $urlData;
}
}
}
}
if ($localeUrls) {
$urls = $localeUrls;
}
return $this->resolveUrlTypes($urls);
}
/**
* Get origination
*
* @return string
*/
public function getOrigination() : string
{
$originations = $this->getOriginations();
return $originations[0] ?? '';
}
/**
* Get all originations
*
* @return array
*/
public function getOriginations() : array
{
return array_map(
function ($origination) {
return $origination['name'];
},
$this->getOriginationExtended()
);
}
/**
* Get extended origination info
*
* @return array
*/
public function getOriginationExtended() : array
{
$record = $this->getXmlRecord();
$localeResults = $results = [];
// For filtering out duplicate names
$searchNamesFn = function ($origination, $names) {
foreach ($names as $name) {
$detail1 = $origination['detail'] ?? null;
$detail2 = $name['detail'] ?? null;
if ($origination['name'] === $name['name']
&& ((!$detail1 || !$detail2) || ($detail1 === $detail2))
) {
return true;
}
}
return false;
};
foreach ($record->did->origination ?? [] as $origination) {
$originationLocaleResults = $originationResults = [];
foreach ($origination->name ?? [] as $name) {
$attr = $name->attributes();
$id = (string)$attr->identifier;
$currentName = null;
$names = $name->part ?? [];
for ($i=0; $i < count($names); $i++) {
$name = $names[$i];
$attr = $name->attributes();
$value = (string)$name;
$localType = (string)$attr->localtype;
$data = [
'id' => $id, 'name' => $value, 'detail' => $localType
];
if ($localType !== self::RELATOR_TIME_INTERVAL) {
if ($nextEl = $names[$i + 1] ?? null) {
$localType
= (string)$nextEl->attributes()->localtype;
if ($localType === self::RELATOR_TIME_INTERVAL) {
// Pick relation time interval from
// next part-element
$date = (string)$nextEl;
if ($date !== self::RELATOR_UNKNOWN_TIME_INTERVAL
) {
$data['date'] = $date;
}
$i++;
}
}
}
$lang = $this->detectNodeLanguage($name);
if ($lang['preferred']
&& !$searchNamesFn($data, $originationLocaleResults)
) {
$originationLocaleResults[] = $data;
}
if (!$searchNamesFn($data, $originationResults)) {
$originationResults[] = $data;
}
}
}
$localeResults = array_merge(
$localeResults, $originationLocaleResults ?: $originationResults
);
$results = array_merge($results, $originationResults);
}
// // Loop relations and filter out names already added from did->origination
foreach ($record->relations->relation ?? [] as $relation) {
$attr = $relation->attributes();
foreach (['relationtype', 'href', 'arcrole'] as $key) {
if (!isset($attr->{$key})) {
continue;
}
}
if ((string)$attr->relationtype !== 'cpfrelation'
|| (string)$attr->arcrole !== self::RELATOR_ARCHIVE_ORIGINATION
) {
continue;
}
$id = (string)$attr->href;
if ($name = $this->getDisplayLabel($relation, 'relationentry', true)) {
$name = $name[0];
if (!$searchNamesFn(compact('name'), $localeResults)) {
$localeResults[] = compact('id', 'name');
}
}
if ($name = $this->getDisplayLabel($relation, 'relationentry')) {
$name = $name[0];
if (!$searchNamesFn(compact('name'), $results)) {
$results[] = compact('id', 'name');
}
}
}
return $localeResults ?: $results;
}
/**
* Get all authors apart from presenters
*
* @return array
*/
public function getNonPresenterAuthors()
{
$result = [];
$xml = $this->getXmlRecord();
$names = [];
if (isset($xml->controlaccess->persname)) {
foreach ($xml->controlaccess->persname as $name) {
$names[] = $name;
}
}
if (isset($xml->controlaccess->corpname)) {
foreach ($xml->controlaccess->corpname as $name) {
$names[] = $name;
}
}
// Attempt to find names in preferred language
foreach ($names as $node) {
$name = $this->getDisplayLabel($node, 'part', true);
if (empty($name) || !$name[0]) {
continue;
}
$result[] = ['name' => $name[0]];
}
if (!empty($result)) {
return $result;
}
// Not found, search again without language filters
foreach ($names as $node) {
$name = $this->getDisplayLabel($node);
if (empty($name) || !$name[0]) {
continue;
}
$result[] = $name[0];
}
$result = array_map(
function ($name) {
return ['name' => $name];
},
array_unique($result)
);
return $result;
}
/**
* Get relations.
*
* @return array
*/
public function getRelations()
{
$result = [];
$xml = $this->getXmlRecord();
if (!isset($xml->relations->relation)) {
return $result;
}
foreach ($xml->controlaccess->name as $node) {
$attr = $node->attributes();
$relator = (string)$attr->relator;
if (self::RELATOR_ARCHIVE_ORIGINATION === $relator) {
continue;
}
$role = $this->translateRole((string)$attr->localtype, $relator);
$name = $this->getDisplayLabel($node);
if (empty($name) || !$name[0]) {
continue;
}
$result[] = [
'id' => (string)$node->attributes()->identifier,
'role' => $role,
'name' => $name[0]
];
}
return $result;
}
/**
* Get location info to be used in ExternalData-record page tab.
*
* @param string $id If defined, return only the item with the given id
*
* @return array
*/
public function getAlternativeItems($id = null)
{
$xml = $this->getXmlRecord();
if (!isset($xml->altformavail->altformavail)) {
return [];
}
// Collect daoset > dao ids. This list is used to separate non-online
// altformavail items.
$onlineIds = [];
if (isset($xml->did->daoset)) {
foreach ($xml->did->daoset as $daoset) {
if (isset($daoset->descriptivenote->p)) {
$onlineIds[] = (string)$daoset->descriptivenote->p;
}
}
}
$onlineTypes = array_keys(
array_filter(
self::ALTFORM_MAP,
function ($label, $type) {
return $type === self::ALTFORM_ONLINE;
}, ARRAY_FILTER_USE_BOTH
)
);
$results = [];
$preferredLangCodes = $this->mapLanguageCode($this->preferredLanguage);
foreach ($xml->altformavail->altformavail as $altform) {
$itemId = (string)$altform->attributes()->id;
if ($id && $id !== $itemId) {
continue;
}
$result = ['id' => $itemId, 'online' => in_array($itemId, $onlineIds)];
$accessRestrictions = [];
$owner = null;
foreach ($altform->list->defitem ?? [] as $defitem) {
$type = self::ALTFORM_MAP[(string)$defitem->label] ?? null;
if (!$type) {
continue;
}
$val = (string)$defitem->item;
switch ($type) {
case self::ALTFORM_LOCATION:
$result['location'] = $val;
if (in_array($val, $onlineTypes)) {
$result['online'] = true;
} else {
$result['service'] = true;
}
break;
case self::ALTFORM_PHYSICAL_LOCATION:
$result['physicalLocation'] = $val;
break;
case self::ALTFORM_TYPE:
$result['type'] = $val;
break;
case self::ALTFORM_DIGITAL_TYPE:
$result['digitalType'] = $val;
break;
case self::ALTFORM_FORMAT:
$result['format'] = $val;
break;
case self::ALTFORM_ACCESS:
$lang = (string)$defitem->item->attributes()->lang ?? 'fin';
$accessRestrictions[$lang] = $val;
break;
case self::ALTFORM_CONDITION:
if ($info = (string)$defitem->label) {
$info .= ': ';
}
$info .= $val;
$result['info'] = $info;
break;
}
}
if ($accessRestrictions) {
$result['accessRestriction'] = reset($accessRestrictions);
foreach ($accessRestrictions as $lang => $restriction) {
if (in_array($lang, $preferredLangCodes)) {
$result['accessRestriction'] = $restriction;
break;
}
}
}
if ($id) {
return $result;
}
$results[] = $result;
}
return $results;
}
/**
* Get unit ids
*
* @return array
*/
public function getUnitIds()
{
$xml = $this->getXmlRecord();
if (!isset($xml->did->unitid)) {
return [];
}
$ids = [];
$manyIds = count($xml->did->unitid) > 1;
foreach ($xml->did->unitid as $id) {
$label = $fallbackDisplayLabel = (string)$id->attributes()->label;
if ($label && !in_array($label, self::UNIT_IDS)) {
continue;
}
$displayLabel = null;
if ($label) {
$displayLabel = "Unit ID:$label";
} elseif ($manyIds) {
$displayLabel = 'Unit ID:unique';
}
$val = (string)$id;
if (!$val) {
$val = (string)$id->attributes()->identifier;
}
if (!$val) {
continue;
}
$ids[] = [
'data' => $val,
'detail'
=> $this->translate($displayLabel, [], $fallbackDisplayLabel)
];
}
return $ids;
}
/**
* Get notes on bibliography content.
*
* @return string[] Notes
*/
public function getBibliographyNotes()
{
return [];
}
/**
* Get an array of summary strings for the record.
*
* @return array
*/
public function getSummary()
{
$xml = $this->getXmlRecord();
if (!empty($xml->scopecontent)) {
$desc = [];
foreach ($xml->scopecontent as $el) {
if (isset($el->attributes()->encodinganalog)) {
continue;
}
if (isset($el->head) && (string)$el->head !== 'Tietosisältö') {
continue;
}
if ($desc = $this->getDisplayLabel($el, 'p', true)) {
return $desc;
}
}
}
return parent::getSummary();
}
/**
* Get identifier
*
* @return array
*/
public function getIdentifier()
{
$xml = $this->getXmlRecord();
if (isset($xml->did->unitid)) {
foreach ($xml->did->unitid as $unitId) {
if (isset($unitId->attributes()->identifier)) {
return [(string)$unitId->attributes()->identifier];
}
}
}
return [];
}
/**
* Get item history
*
* @return null|string
*/
public function getItemHistory()
{
$xml = $this->getXmlRecord();
if (!empty($xml->scopecontent)) {
foreach ($xml->scopecontent as $el) {
if (! isset($el->attributes()->encodinganalog)
|| (string)$el->attributes()->encodinganalog !== 'AI10'
) {
continue;
}
if ($desc = $this->getDisplayLabel($el, 'p')) {
return $desc[0];
}
}
}
return null;
}
/**
* Get external data (images, physical items).
*
* @return array
*/
public function getExternalData()
{
$fullResImages = $this->getFullResImages();
$ocrImages = $this->getOCRImages();
$physicalItems = $this->getPhysicalItems();
$digitized
= !empty($fullResImages) || !empty($ocrImages)
|| !empty($this->getAllImages());
$result = [];
if (!empty($fullResImages)) {
$result['items']['fullResImages'] = $fullResImages;
}
if (!empty($ocrImages)) {
$result['items']['OCRImages'] = $ocrImages;
}
if (!empty($physicalItems)) {
$result['items']['physicalItems'] = $physicalItems;
}
$result['digitized'] = $digitized;
return $result;
}
/**
* Return an array of image URLs associated with this record with keys:
* - urls Image URLs
* - small Small image (mandatory)
* - medium Medium image (mandatory)
* - large Large image (optional)
* - description Description text
* - rights Rights
* - copyright Copyright (e.g. 'CC BY 4.0') (optional)
* - description Human readable description (array)
* - link Link to copyright info
*
* @param string $language Language for copyright information
* @param bool $includePdf Whether to include first PDF file when no image
* links are found
*
* @return array
*/
public function getAllImages(
$language = 'fi', $includePdf = false
) {
$result = $images = [];
$xml = $this->getXmlRecord();
if (isset($xml->did->daoset)) {
foreach ($xml->did->daoset as $daoset) {
if (!isset($daoset->dao)) {
continue;
}
$attr = $daoset->attributes();
// localtype could be defined for daoset or for dao-element (below)
$localtype = (string)($attr->localtype ?? null);
$localtype = self::IMAGE_MAP[$localtype] ?? self::IMAGE_FULLRES;
$size = $localtype === self::IMAGE_FULLRES
? self::IMAGE_LARGE : $localtype;
if (!isset($images[$size])) {
$image[$size] = [];
}
$descId = isset($daoset->descriptivenote->p)
? (string)$daoset->descriptivenote->p : null;
foreach ($daoset->dao as $dao) {
$attr = $dao->attributes();
if (!isset($attr->linktitle) || !$attr->href) {
continue;
}
$href = (string)$attr->href;
if (!$this->isUrlLoadable($href, $this->getUniqueID())) {
continue;
}
if (isset($attr->localtype)) {
$localtype = (string)$attr->localtype;
if (!isset(self::IMAGE_MAP[$localtype])) {
continue;
}
$size = self::IMAGE_MAP[$localtype];
} elseif (!$localtype) {
continue;
}
$size = $size === self::IMAGE_FULLRES
? self::IMAGE_LARGE : $size;
if (!isset($images[$size])) {
$image[$size] = [];
}
$images[$size][] = [
'description' => (string)$attr->linktitle,
'rights' => null,
'url' => $href,
'descId' => $descId,
'sort' => (string)$attr->label,
'type' => $localtype,
'pdf' => (string)$attr->linkrole === 'application/pdf'
];
}
}
if (empty($images)) {
return [];
}
foreach ($images as $size => &$sizeImages) {
$this->sortImageUrls($sizeImages);
}
foreach ($images['large'] ?? $images['medium'] as $id => $img) {
$large = $images['large'][$id] ?? ['url' => '', 'pdf' => false];
$medium = $images['medium'][$id] ?? ['url' => '', 'pdf' => false];
$data = $img;
$data['urls'] = [
'small' => $medium['url'] ?? $large['url'] ?? null,
'medium' => $medium['url'] ?? $large['url'] ?? null,
'large' => $large['url'] ?? $medium['url'] ?? null,
];
$data['pdf'] = [
'medium' => ($medium['url'] && $medium['pdf'])
|| (!$medium['url'] && $large['url'] && $large['pdf']),
'large' => ($large['url'] && $large['pdf'])
|| (!$large['url'] && $medium['url'] && $medium['pdf'])
];
$data['pdf']['small'] = $data['pdf']['medium'];
$result[] = $data;
}
}
return $result;
}
/**
* Get an array of physical descriptions of the item.
*
* @return array
*/
public function getPhysicalDescriptions()
{
$xml = $this->getXmlRecord();
if (!isset($xml->did->physdesc)) {
return [];
}
return $this->getDisplayLabel($xml->did, 'physdesc', true);
}
/**
* Get description of content.
*
* @return string
*/
public function getContentDescription()
{
$xml = $this->getXmlRecord();
if (!isset($xml->controlaccess->genreform)) {
return [];
}
foreach ($xml->controlaccess->genreform as $genre) {
if (! isset($genre->attributes()->encodinganalog)
|| (string)$genre->attributes()->encodinganalog !== 'ahaa:AI46'
) {
continue;
}
if ($label = $this->getDisplayLabel($genre)) {
return $label[0];
}
}
return null;
}
/**
* Get the statement of responsibility that goes with the title (i.e. "by John
* Smith").
*
* @return string
*/
public function getTitleStatement()
{
$xml = $this->getXmlRecord();
if (!isset($xml->bibliography->p)) {
return null;
}
$label = $this->getDisplayLabel($xml->bibliography, 'p', true);
return $label ? $label[0] : null;
}
/**
* Get access restriction notes for the record.
*
* @return string[] Notes
*/
public function getAccessRestrictions()
{
$xml = $this->getXmlRecord();
$result = [];
if (isset($xml->userestrict)) {
foreach ($xml->userestrict as $node) {
if ($label = $this->getDisplayLabel($node, 'p', true)) {
if (empty($label[0])) {
continue;
}
$result[] = $label[0];
}
}
if (empty($result)) {
foreach ($xml->userestrict as $node) {
if ($label = $this->getDisplayLabel($node, 'p')) {
if (empty($label[0])) {
continue;
}
$result[] = $label[0];
}
}
}
}
return $result;
}
/**
* Get extended access restriction notes for the record.
*
* @return string[]
*/
public function getExtendedAccessRestrictions()
{
$xml = $this->getXmlRecord();
if (isset($xml->accessrestrict)
&& !isset($xml->accessrestrict->accessrestrict)
) {
// Case 1: no nested accessrestrict elements
$result = [];
foreach ([true, false] as $obeyPreferredLanguage) {
foreach ($xml->accessrestrict as $accessNode) {
if ($label = $this->getDisplayLabel(
$accessNode, 'p', $obeyPreferredLanguage
)
) {
if (empty($label[0])) {
continue;
}
$result[] = $label[0];
}
}
if (!empty($result)) {
break;
}
}
return $result;
}
// Case 2: nested accessrestrict elements grouped under subheadings
$restrictions = [];
foreach (self::ACCESS_RESTRICT_TYPES as $type) {
$restrictions[$type] = [];
}
$processNode = function ($access) use (&$restrictions) {
$attr = $access->attributes();
if (! isset($attr->encodinganalog)) {
$restriction['general'] = array_merge(
$restrictions['general'],
$this->getDisplayLabel($access, 'p', true)
);
} else {
$type = (string)$attr->encodinganalog;
if (in_array($type, self::ACCESS_RESTRICT_TYPES)) {
switch ($type) {
case 'ahaa:KR7':
$label = $this->getDisplayLabel(
$access->p->name, 'part', true
);
break;
case 'ahaa:KR9':
$label = [(string)($access->p->date ?? '')];
break;
default:
$label = $this->getDisplayLabel($access, 'p');
}
if ($label) {
// These are displayed under the same heading
if (in_array($type, ['ahaa:KR2', 'ahaa:KR3'])) {
$type = 'ahaa:KR1';
}
$restrictions[$type]
= array_merge($restrictions[$type], $label);
}
}
}
};
foreach ($xml->accessrestrict ?? [] as $accessNode) {
$processNode($accessNode);
foreach ($accessNode->accessrestrict ?? [] as $accessNode) {
$processNode($accessNode);
foreach ($accessNode->accessrestrict ?? [] as $accessNode) {
$processNode($accessNode);
}
}
}
$result = [];
// Sort
$order = array_flip(self::ACCESS_RESTRICT_TYPES);
$orderCnt = count($order);
$sortFn = function ($a, $b) use ($order, $orderCnt) {
$pos1 = $order[$a] ?? $orderCnt;
$pos2 = $order[$b] ?? $orderCnt;
return $pos1 - $pos2;
};
uksort($restrictions, $sortFn);
// Rename keys to match translations and filter duplicates
$renamedKeys = [];
foreach ($restrictions as $key => $val) {
if (empty($val)) {
continue;
}
$key = str_replace(':', '_', $key);
$renamedKeys[$key] = array_unique($val);
}
return $renamedKeys;
}
/**
* Return type of access restriction for the record.
*
* @param string $language Language
*
* @return mixed array with keys:
* 'copyright' Copyright (e.g. 'CC BY 4.0')
* 'link' Link to copyright info, see IndexRecord::getRightsLink
* or false if no access restriction type is defined.
*/
public function getAccessRestrictionsType($language)
{
if (! $restrictions = $this->getAccessRestrictions()) {
return false;
}
$copyright = $this->getMappedRights($restrictions[0]);
$data = [];
$data['copyright'] = $copyright;
if ($link = $this->getRightsLink($copyright, $language)) {
$data['link'] = $link;
}
return $data;
}
/**
* Return image rights.
*
* @param string $language Language
* @param bool $skipImageCheck Whether to check that images exist
*
* @return mixed array with keys:
* 'copyright' Copyright (e.g. 'CC BY 4.0') (optional)
* 'description' Human readable description (array)
* 'link' Link to copyright info
* or false if the record contains no images
*/
public function getImageRights($language, $skipImageCheck = false)
{
if (!$skipImageCheck && !$this->getAllImages()) {
return false;
}
$rights = [];
if ($type = $this->getAccessRestrictionsType($language)) {
$rights['copyright'] = $type['copyright'];
if (isset($type['link'])) {
$rights['link'] = $type['link'];
}
}
$desc = $this->getAccessRestrictions();
if ($desc && count($desc)) {
$rights['description'] = $desc[0];
}
return isset($rights['copyright']) || isset($rights['description'])
? $rights : false;
}
/**
* Get all subject headings associated with this record with extended data.
* (see getAllSubjectHeadings).
*
* @return array
*/
public function getAllSubjectHeadingsExtended()
{
return $this->getAllSubjectHeadings(true);
}
/**
* Get all subject headings associated with this record. Each heading is
* returned as an array of chunks, increasing from least specific to most
* specific.
*
* @param bool $extended Whether to return a keyed array with the following
* keys:
* - heading: the actual subject heading chunks
* - type: heading type
* - source: source vocabulary
*
* @return array
*/
public function getAllSubjectHeadings($extended = false)
{
$headings = [];
$headings = $this->getTopics();
// geographic names are returned in getRelatedPlacesExtended
foreach (['genre', 'era'] as $field) {
$headings = array_merge(
$headings,
array_map(
function ($term) {
return ['data' => $term];
},
$this->fields[$field] ?? []
)
);
}
$headings = array_merge(
$headings, $this->getRelatedPlacesExtended(['aihe'], [])
);
// The default index schema doesn't currently store subject headings in a
// broken-down format, so we'll just send each value as a single chunk.
// Other record drivers (i.e. SolrMarc) can offer this data in a more
// granular format.
$callback = function ($i) use ($extended) {
if ($extended) {
$data = [
'heading' => [$i['data']],
'type' => 'topic',
'source' => $i['source'] ?? '',
'detail' => $i['detail'] ?? ''
];
if ($id = $i['id'] ?? '') {
$data['id'] = $id;
// Categorize non-URI ID's as Unknown Names, since the
// actual authority format can not be determined from metadata.
$data['authType'] = preg_match('/^https?:/', $id)
? null : 'Unknown Name';
}
} else {
return [$i['data']];
}
return $data;
};
return array_map($callback, $headings);
}
/**
* Get related places.
*
* @param array $include Relator attributes to include
* @param array $exclude Relator attributes to exclude
*
* @return array
*/
public function getRelatedPlacesExtended($include = [], $exclude = ['aihe'])
{
$record = $this->getXmlRecord();
if (!isset($record->controlaccess->geogname)) {
return [];
}
$languageResult = $languageResultDetail = $result = $resultDetail = [];
$languages = $this->preferredLanguage
? $this->mapLanguageCode($this->preferredLanguage)
: [];
foreach ($record->controlaccess->geogname as $name) {
$attr = $name->attributes();
$relator = (string)$attr->relator;
if (!empty($include) && !in_array($relator, $include)) {
continue;
}
if (!empty($exclude) && in_array($relator, $exclude)) {
continue;
}
if (isset($name->part)) {
$part = (string)$name->part;
$data = ['data' => $part, 'detail' => $relator];
if ($attr->lang && in_array((string)$attr->lang, $languages)
&& !in_array($part, $languageResult)
) {
$languageResultDetail[] = $data;
$languageResult[] = $part;
} elseif (!in_array($part, $result)) {
$resultDetail[] = $data;
$result[] = $part;
}
}
}
return $languageResultDetail ?: $resultDetail;
}
/**
* Get the unitdate field.
*
* @return array
*/
public function getUnitDates()
{
$record = $this->getXmlRecord();
$result = [];
if (isset($record->did->unitdate)) {
foreach ($record->did->unitdate as $date) {
$attr = $date->attributes();
if ($desc = $attr->normal ?? null) {
$desc = $attr->label ?? null;
}
$date = (string)$date;
$result[] = ['data' => (string)$date, 'detail' => (string)$desc];
}
if ($result) {
return $result;
}
}
if (isset($record->did->unitdatestructured->datesingle)) {
foreach ($record->did->unitdatestructured->datesingle as $date) {
$attr = $date->attributes();
if ($attr->standarddate) {
$result[] = ['data' => (string)$attr->standarddate];
}
}
if ($result) {
return array_unique($result);
}
}
return $this->getUnitDate();
}
/**
* Get related records (used by RecordDriverRelated - Related module)
*
* Returns an associative array of group => records, where each item in
* records is either a record id or an array with keys:
* - id: record identifier to search
* - field (optional): Solr field to search in, defaults to 'identifier'.
* In addition, the query includes a filter that limits the
* results to the same datasource as the issuing record.
*
* The array may contain the following keys:
* - continued-from
* - part-of
* - contains
* - see-also
*
* Examples:
* - continued-from
* - source1.1234
* - ['id' => '1234']
* - ['id' => '1234', 'field' => 'foo']
*
* @return array
*/
public function getRelatedRecords()
{
$record = $this->getXmlRecord();
if (!isset($record->relations->relation)) {
return [];
}
$relations = [];
foreach ($record->relations->relation as $relation) {
$attr = $relation->attributes();
foreach (['encodinganalog', 'href', 'arcrole'] as $key) {
if (!isset($attr->{$key})) {
continue 2;
}
}
if ((string)$attr->encodinganalog !== self::RELATION_RECORD) {
continue;
}
$role = self::RELATION_MAP[(string)$attr->arcrole] ?? null;
if (!$role) {
continue;
}
if (!isset($relations[$role])) {
$relations[$role] = [];
}
// Search by id in identifier-field
$relations[$role][]
= ['id' => (string)$attr->href, 'field' => 'identifier'];
}
return $relations;
}
/**
* Whether the record has related records declared in metadata.
* (used by RecordDriverRelated related module).
*
* @return bool
*/
public function hasRelatedRecords()
{
return !empty($this->getRelatedRecords());
}
/**
* Get all record links related to the current record. Each link is returned as
* array.
* Format:
* array(
* array(
* 'title' => label_for_title
* 'value' => link_name
* 'link' => link_URI
* ),
* ...
* )
*
* @return null|array
*/
public function getAllRecordLinks()
{
$record = $this->getXmlRecord();
if (!isset($record->relations->relation)) {
return [];
}
$relations = [];
foreach ($record->relations->relation as $relation) {
$attr = $relation->attributes();
foreach (['encodinganalog', 'relationtype', 'href'] as $key) {
if (!isset($attr->{$key})) {
continue 2;
}
}
if ((string)$attr->relationtype !== 'resourcerelation'
|| in_array((string)$attr->encodinganalog, self::IGNORED_RELATIONS)
) {
continue;
}
$value = $href = (string)$attr->href;
if ($title = (string)$relation->relationentry) {
$value = $title;
}
$relations[] = [
'value' => $value,
'detail' => !empty($attr->arcrole) ? (string)$attr->arcrole : null,
'link' => [
'value' => $href,
'type' => 'identifier',
'filter' => ['datasource_str_mv' => $this->getDatasource()]
]
];
}
return $relations;
}
/**
* Get the hierarchy parents associated with this item (empty if none).
* The parents are listed starting from the root of the hierarchy,
* i.e. the closest parent is at the end of the result array.
*
* @param string[] $levels Optional list of level types to return
* (defaults to series and subseries)
*
* @return array Array with id and title
*/
protected function getHierarchyParents(
array $levels = self::SERIES_LEVELS
) : array {
$xml = $this->getXmlRecord();
if (!isset($xml->{'add-data'}->parent)) {
return [];
}
$result = [];
foreach ($xml->{'add-data'}->parent as $parent) {
$attr = $parent->attributes();
if (!in_array((string)$attr->level, $levels)) {
continue;
}
$result[] = [
'id' => $this->getDatasource() . '.' . (string)$attr->id,
'title' => (string)$attr->title
];
}
return array_reverse($result);
}
/**
* Get the hierarchy_parent_id(s) associated with this item (empty if none).
*
* @param string[] $levels Optional list of level types to return
* (defaults to series and subseries)
*
* @return array
*/
public function getHierarchyParentID(array $levels = self::SERIES_LEVELS) : array
{
if ($parents = $this->getHierarchyParents($levels)) {
return array_map(
function ($parent) {
return $parent['id'];
}, $parents
);
}
return parent::getHierarchyParentID($levels);
}
/**
* Get the parent title(s) associated with this item (empty if none).
* (defaults to series and subseries)
*
* @param string[] $levels Optional list of level types to return
*
* @return array
*/
public function getHierarchyParentTitle(
array $levels = self::SERIES_LEVELS
) : array {
if ($parents = $this->getHierarchyParents($levels)) {
return array_map(
function ($parent) {
return $parent['title'];
}, $parents
);
}
return parent::getHierarchyParentTitle($levels);
}
/**
* Get place of storage.
*
* @return string|null
*/
public function getPlaceOfStorage() : ?string
{
$xml = $this->getXmlRecord();
$firstLoc = $defaultLoc = null;
foreach ($xml->did->physloc ?? [] as $loc) {
if (!$firstLoc) {
$firstLoc = (string)$loc;
}
if ($lang = $this->detectNodeLanguage($loc)) {
if ($lang['preferred']) {
return (string)$loc;
}
if ($lang['default']) {
$defaultLoc = (string)$loc;
}
}
}
return $defaultLoc ?? $firstLoc;
}
/**
* Get filing unit.
*
* @return string|null
*/
public function getFilingUnit() : ?string
{
$xml = $this->getXmlRecord();
return isset($xml->did->container)
? (string)$xml->did->container : null;
}
/**
* Get appraisal information.
*
* @return string[]
*/
public function getAppraisal() : array
{
$xml = $this->getXmlRecord();
$result = $localeResult = [];
$preferredLangCodes = $this->mapLanguageCode($this->preferredLanguage);
foreach ($xml->appraisal->p ?? [] as $p) {
$value = (string)$p;
$result[] = $value;
if (in_array((string)$p->attributes()->lang, $preferredLangCodes)) {
$localeResult[] = $value;
}
}
return $localeResult ?: $result;
}
/**
* Get material arrangement information.
*
* @return string[]
*/
public function getMaterialArrangement() : array
{
$xml = $this->getXmlRecord();
$result = [];
foreach ($xml->arrangement ?? [] as $arrangement) {
$label = $this->getDisplayLabel($arrangement, 'p');
$localeLabel = $this->getDisplayLabel($arrangement, 'p', true);
$result = array_merge($result, $localeLabel ?: $label);
}
return $result;
}
/**
* Get notes on finding aids related to the record.
*
* @return array
*/
public function getFindingAids()
{
$xml = $this->getXmlRecord();
$result = $localeResult = [];
foreach ($xml->otherfindaid ?? [] as $aid) {
$result[] = (string)($aid->p ?? '');
if ($text = $this->getDisplayLabel($aid, 'p')) {
$localeResult[] = $text[0];
}
}
return $localeResult ?: $result ?: parent::getFindingAids();
}
/**
* Get container information.
*
* @return string
*/
public function getContainerInformation()
{
$xml = $this->getXmlRecord();
return (string)($xml->did->container ?? '');
}
/**
* Get fullresolution images.
*
* @return array
*/
protected function getFullResImages()
{
$images = $this->getAllImages();
$items = [];
foreach ($images as $img) {
if (!isset($img['type']) || $img['type'] !== self::IMAGE_FULLRES) {
continue;
}
$items[]
= ['label' => $img['description'], 'url' => $img['urls']['large']];
}
$info = [];
if (isset($images[0]['descId'])) {
$altItem = $this->getAlternativeItems($images[0]['descId']);
if (isset($altItem['format'])) {
$info[] = $altItem['format'];
}
}
$items = $items ? compact('info', 'items') : [];
return $items;
}
/**
* Get OCR images.
*
* @return array
*/
protected function getOCRImages()
{
$items = [];
$xml = $this->getXmlRecord();
$descId = null;
if (isset($xml->did->daoset)) {
foreach ($xml->did->daoset as $daoset) {
if (!isset($daoset->dao)) {
continue;
}
$attr = $daoset->attributes();
$localtype = (string)$attr->localtype ?? null;
if ($localtype !== self::IMAGE_OCR) {
continue;
}
if (isset($daoset->descriptivenote->p)) {
$descId = (string)$daoset->descriptivenote->p;
}
foreach ($daoset->dao as $idx => $dao) {
$attr = $dao->attributes();
if (! isset($attr->linktitle)
|| strpos((string)$attr->linktitle, 'Kuva/Aukeama') !== 0
|| ! $attr->href
) {
continue;
}
$href = (string)$attr->href;
$desc = (string)$attr->linktitle;
$sort = (string)$attr->label;
$items[] = [
'label' => $desc, 'url' => $href, 'sort' => $sort
];
}
}
}
$this->sortImageUrls($items);
$info = [];
if ($descId) {
$altItem = $this->getAlternativeItems($descId);
if ($format = $altItem['format'] ?? null) {
$info[] = $format;
}
}
return !empty($items) ? compact('info', 'items') : [];
}
/**
* Sort an array of image URLs in place.
*
* @param array $urls URLs
* @param string $field Field to use for sorting.
* The field value is casted to int before sorting.
*
* @return void
*/
protected function sortImageUrls(&$urls, $field = 'sort')
{
usort(
$urls, function ($a, $b) use ($field) {
$f1 = (int)$a[$field];
$f2 = (int)$b[$field];
if ($f1 === $f2) {
return 0;
} elseif ($f1 < $f2) {
return -1;
} else {
return 1;
}
}
);
}
/**
* Return physical items.
*
* @return array
*/
protected function getPhysicalItems()
{
return array_filter(
$this->getAlternativeItems(),
function ($item) {
return empty($item['online']) && !empty($item['location']);
}
);
}
/**
* Get topics.
*
* @return array
*/
protected function getTopics() : array
{
$record = $this->getXmlRecord();
$topics = [];
if (isset($record->controlaccess->subject)) {
foreach ([true, false] as $obeyPreferredLanguage) {
foreach ($record->controlaccess->subject as $subject) {
$attr = $subject->attributes();
if ($topic = $this->getDisplayLabel(
$subject, 'part', $obeyPreferredLanguage
)
) {
if (!$topic[0]) {
continue;
}
$topics[] = [
'data' => $topic[0],
'id' => (string)$attr->identifier,
'source' => (string)$attr->source,
'detail' => (string)$subject->attributes()->relator
];
}
}
if (!empty($topics)) {
return $topics;
}
}
}
return $topics;
}
/**
* Return translated repository display name from metadata.
*
* @return string
*/
protected function getRepositoryName()
{
$record = $this->getXmlRecord();
if (isset($record->did->repository->corpname)) {
foreach ($record->did->repository->corpname as $corpname) {
if ($name = $this->getDisplayLabel($corpname, 'part', true)) {
return $name[0];
}
}
}
return null;
}
/**
* Helper function for returning a specific language version of a display label.
*
* @param \SimpleXMLElement $node XML node
* @param string $childNodeName Name of the child node that
* contains the display label.
* @param bool $obeyPreferredLanguage If true, returns the
* translation that corresponds with the current locale.
* If false, the default language version 'fin' is returned. If not found,
* the first display label is retured.
*
* @return string[]
*/
protected function getDisplayLabel(
$node,
$childNodeName = 'part',
$obeyPreferredLanguage = false
) : array {
if (! isset($node->$childNodeName)) {
return [];
}
$allResults = [];
$defaultLanguageResults = [];
$languageResults = [];
$lang = $this->detectNodeLanguage($node);
$resolveLangFromChildNode = $lang === null;
foreach ($node->{$childNodeName} as $child) {
$name = trim((string)$child);
$allResults[] = $name;
if ($resolveLangFromChildNode) {
foreach ($child->attributes() as $key => $val) {
$lang = $this->detectNodeLanguage($child);
if ($lang) {
break;
}
}
}
if ($lang['default'] ?? false) {
$defaultLanguageResults[] = $name;
}
if ($lang['preferred'] ?? false) {
$languageResults[] = $name;
}
}
if ($obeyPreferredLanguage) {
return $languageResults;
}
if (! empty($languageResults)) {
return $languageResults;
} elseif (! empty($defaultLanguageResults)) {
return $defaultLanguageResults;
}
return $allResults;
}
/**
* Helper for detecting the language of a XML node.
* Compares the language attribute of the node to users' preferred language.
* Returns an array with keys 'default' and 'preferred'.
*
* @param \SimpleXMLElement $node XML node
* @param string $languageAttribute Name of the language attribute
* @param string $defaultLanguage Default language
*
* @return array
*/
protected function detectNodeLanguage(
\SimpleXMLElement $node,
string $languageAttribute = 'lang',
string $defaultLanguage = 'fin'
) : ?array {
if (!isset($node->attributes()->{$languageAttribute})) {
return null;
}
$languages = $this->preferredLanguage
? $this->mapLanguageCode($this->preferredLanguage)
: [];
$lang = (string)$node->attributes()->{$languageAttribute};
return [
'default' => $defaultLanguage === $lang,
'preferred' => in_array($lang, $languages)
];
}
/**
* Convert Finna language codes to EAD3 codes.
*
* @param string $languageCode Language code
*
* @return string[]
*/
protected function mapLanguageCode($languageCode)
{
$langMap
= ['fi' => ['fi','fin'], 'sv' => ['sv','swe'], 'en-gb' => ['en','eng']];
return $langMap[$languageCode] ?? [$languageCode];
}
/**
* Get role translation key
*
* @param string $role EAD3 role
* @param string $fallback Fallback to use when no supported role is found
*
* @return string Translation key
*/
protected function translateRole($role, $fallback = null)
{
// Map EAD3 roles to CreatorRole translations
$roleMap = [
'http://rdaregistry.info/Elements/e/P20047' => 'ive',
'http://rdaregistry.info/Elements/e/P20032' => 'ivr',
'http://rdaregistry.info/Elements/w/P10046' => 'pbl',
'http://www.rdaregistry.info/Elements/w/#P10311' => 'fac',
'http://rdaregistry.info/Elements/e/P20042' => 'ctg',
'http://rdaregistry.info/Elements/a/P50190' => 'cng',
'http://rdaregistry.info/Elements/w/P10058' => 'art',
'http://rdaregistry.info/Elements/w/P10066' => 'drt',
'http://rdaregistry.info/Elements/e/P20033' => 'drm',
'http://rdaregistry.info/Elements/e/P20024' => 'spk',
'http://rdaregistry.info/Elements/w/P10204' => 'lyr',
'http://rdaregistry.info/Elements/e/P20029' => 'arr',
'http://rdaregistry.info/Elements/w/P10053' => 'cmp',
'http://rdaregistry.info/Elements/w/P10065' => 'aut',
'http://rdaregistry.info/Elements/w/P10298' => 'edt',
'http://rdaregistry.info/Elements/w/P10064' => 'pro',
'http://www.rdaregistry.info/Elements/u/P60429' => 'pht',
'http://www.rdaregistry.info/Elements/e/#P20052' => 'rpy',
'http://rdaregistry.info/Elements/w/P10304' => 'rpy',
'http://rdaregistry.info/Elements/w/P10061' => 'rda:writer',
'http://rdaregistry.info/Elements/a/P50045' => 'rda:collector',
'http://www.rdaregistry.info/Elements/i/#P40019' => 'rda:former-owner'
];
return $roleMap[$role] ?? $fallback;
}
}
|
tmikkonen/NDL-VuFind2
|
module/Finna/src/Finna/RecordDriver/SolrEad3.php
|
PHP
|
gpl-2.0
| 60,055
|
using System;
namespace Server.Items
{
[FlipableAttribute(0x27A6, 0x27F1)]
public class Tetsubo : BaseBashing
{
[Constructable]
public Tetsubo()
: base(0x27A6)
{
this.Weight = 8.0;
this.Layer = Layer.TwoHanded;
}
public Tetsubo(Serial serial)
: base(serial)
{
}
public override WeaponAbility PrimaryAbility
{
get
{
return WeaponAbility.FrenziedWhirlwind;
}
}
public override WeaponAbility SecondaryAbility
{
get
{
return WeaponAbility.CrushingBlow;
}
}
public override int AosStrengthReq
{
get
{
return 35;
}
}
public override int AosMinDamage
{
get
{
return 12;
}
}
public override int AosMaxDamage
{
get
{
return 15;
}
}
public override int AosSpeed
{
get
{
return 45;
}
}
public override float MlSpeed
{
get
{
return 2.50f;
}
}
public override int DefHitSound
{
get
{
return 0x233;
}
}
public override int DefMissSound
{
get
{
return 0x238;
}
}
public override int InitMinHits
{
get
{
return 60;
}
}
public override int InitMaxHits
{
get
{
return 65;
}
}
public override WeaponAnimation DefAnimation
{
get
{
return WeaponAnimation.Bash2H;
}
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
}
|
kevin-10/ServUO
|
Scripts/Items/Equipment/Weapons/Tetsubo.cs
|
C#
|
gpl-2.0
| 2,424
|
/***************************************************************************
qgsmapboxglstyleconverter.cpp
--------------------------------------
Date : September 2020
Copyright : (C) 2020 by Nyall Dawson
Email : nyall dot dawson at gmail dot 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. *
* *
***************************************************************************/
/*
* Ported from original work by Martin Dobias, and extended by the MapTiler team!
*/
#include "qgsmapboxglstyleconverter.h"
#include "qgsvectortilebasicrenderer.h"
#include "qgsvectortilebasiclabeling.h"
#include "qgssymbollayer.h"
#include "qgssymbollayerutils.h"
#include "qgslogger.h"
#include "qgsfillsymbollayer.h"
#include "qgslinesymbollayer.h"
#include "qgsfontutils.h"
#include "qgsjsonutils.h"
#include "qgspainteffect.h"
#include "qgseffectstack.h"
#include "qgsblureffect.h"
#include "qgsmarkersymbollayer.h"
#include "qgstextbackgroundsettings.h"
QgsMapBoxGlStyleConverter::QgsMapBoxGlStyleConverter()
{
}
QgsMapBoxGlStyleConverter::Result QgsMapBoxGlStyleConverter::convert( const QVariantMap &style, QgsMapBoxGlStyleConversionContext *context )
{
mError.clear();
mWarnings.clear();
if ( style.contains( QStringLiteral( "layers" ) ) )
{
parseLayers( style.value( QStringLiteral( "layers" ) ).toList(), context );
}
else
{
mError = QObject::tr( "Could not find layers list in JSON" );
return NoLayerList;
}
return Success;
}
QgsMapBoxGlStyleConverter::Result QgsMapBoxGlStyleConverter::convert( const QString &style, QgsMapBoxGlStyleConversionContext *context )
{
return convert( QgsJsonUtils::parseJson( style ).toMap(), context );
}
QgsMapBoxGlStyleConverter::~QgsMapBoxGlStyleConverter() = default;
void QgsMapBoxGlStyleConverter::parseLayers( const QVariantList &layers, QgsMapBoxGlStyleConversionContext *context )
{
std::unique_ptr< QgsMapBoxGlStyleConversionContext > tmpContext;
if ( !context )
{
tmpContext = std::make_unique< QgsMapBoxGlStyleConversionContext >();
context = tmpContext.get();
}
QList<QgsVectorTileBasicRendererStyle> rendererStyles;
QList<QgsVectorTileBasicLabelingStyle> labelingStyles;
for ( const QVariant &layer : layers )
{
const QVariantMap jsonLayer = layer.toMap();
const QString layerType = jsonLayer.value( QStringLiteral( "type" ) ).toString();
if ( layerType == QLatin1String( "background" ) )
continue;
const QString styleId = jsonLayer.value( QStringLiteral( "id" ) ).toString();
context->setLayerId( styleId );
const QString layerName = jsonLayer.value( QStringLiteral( "source-layer" ) ).toString();
const int minZoom = jsonLayer.value( QStringLiteral( "minzoom" ), QStringLiteral( "-1" ) ).toInt();
const int maxZoom = jsonLayer.value( QStringLiteral( "maxzoom" ), QStringLiteral( "-1" ) ).toInt();
const bool enabled = jsonLayer.value( QStringLiteral( "visibility" ) ).toString() != QLatin1String( "none" );
QString filterExpression;
if ( jsonLayer.contains( QStringLiteral( "filter" ) ) )
{
filterExpression = parseExpression( jsonLayer.value( QStringLiteral( "filter" ) ).toList(), *context );
}
QgsVectorTileBasicRendererStyle rendererStyle;
QgsVectorTileBasicLabelingStyle labelingStyle;
bool hasRendererStyle = false;
bool hasLabelingStyle = false;
if ( layerType == QLatin1String( "fill" ) )
{
hasRendererStyle = parseFillLayer( jsonLayer, rendererStyle, *context );
}
else if ( layerType == QLatin1String( "line" ) )
{
hasRendererStyle = parseLineLayer( jsonLayer, rendererStyle, *context );
}
else if ( layerType == QLatin1String( "circle" ) )
{
hasRendererStyle = parseCircleLayer( jsonLayer, rendererStyle, *context );
}
else if ( layerType == QLatin1String( "symbol" ) )
{
parseSymbolLayer( jsonLayer, rendererStyle, hasRendererStyle, labelingStyle, hasLabelingStyle, *context );
}
else
{
mWarnings << QObject::tr( "%1: Skipping unknown layer type %2" ).arg( context->layerId(), layerType );
QgsDebugMsg( mWarnings.constLast() );
continue;
}
if ( hasRendererStyle )
{
rendererStyle.setStyleName( styleId );
rendererStyle.setLayerName( layerName );
rendererStyle.setFilterExpression( filterExpression );
rendererStyle.setMinZoomLevel( minZoom );
rendererStyle.setMaxZoomLevel( maxZoom );
rendererStyle.setEnabled( enabled );
rendererStyles.append( rendererStyle );
}
if ( hasLabelingStyle )
{
labelingStyle.setStyleName( styleId );
labelingStyle.setLayerName( layerName );
labelingStyle.setFilterExpression( filterExpression );
labelingStyle.setMinZoomLevel( minZoom );
labelingStyle.setMaxZoomLevel( maxZoom );
labelingStyle.setEnabled( enabled );
labelingStyles.append( labelingStyle );
}
mWarnings.append( context->warnings() );
context->clearWarnings();
}
mRenderer = std::make_unique< QgsVectorTileBasicRenderer >();
QgsVectorTileBasicRenderer *renderer = dynamic_cast< QgsVectorTileBasicRenderer *>( mRenderer.get() );
renderer->setStyles( rendererStyles );
mLabeling = std::make_unique< QgsVectorTileBasicLabeling >();
QgsVectorTileBasicLabeling *labeling = dynamic_cast< QgsVectorTileBasicLabeling * >( mLabeling.get() );
labeling->setStyles( labelingStyles );
}
bool QgsMapBoxGlStyleConverter::parseFillLayer( const QVariantMap &jsonLayer, QgsVectorTileBasicRendererStyle &style, QgsMapBoxGlStyleConversionContext &context )
{
if ( !jsonLayer.contains( QStringLiteral( "paint" ) ) )
{
context.pushWarning( QObject::tr( "%1: Layer has no paint property, skipping" ).arg( jsonLayer.value( QStringLiteral( "id" ) ).toString() ) );
return false;
}
const QVariantMap jsonPaint = jsonLayer.value( QStringLiteral( "paint" ) ).toMap();
QgsPropertyCollection ddProperties;
QgsPropertyCollection ddRasterProperties;
// fill color
QColor fillColor;
if ( jsonPaint.contains( QStringLiteral( "fill-color" ) ) )
{
const QVariant jsonFillColor = jsonPaint.value( QStringLiteral( "fill-color" ) );
switch ( jsonFillColor.type() )
{
case QVariant::Map:
ddProperties.setProperty( QgsSymbolLayer::PropertyFillColor, parseInterpolateColorByZoom( jsonFillColor.toMap(), context, &fillColor ) );
break;
case QVariant::List:
case QVariant::StringList:
ddProperties.setProperty( QgsSymbolLayer::PropertyFillColor, parseValueList( jsonFillColor.toList(), PropertyType::Color, context, 1, 255, &fillColor ) );
break;
case QVariant::String:
fillColor = parseColor( jsonFillColor.toString(), context );
break;
default:
{
context.pushWarning( QObject::tr( "%1: Skipping unsupported fill-color type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonFillColor.type() ) ) );
break;
}
}
}
else
{
// defaults to #000000
fillColor = QColor( 0, 0, 0 );
}
QColor fillOutlineColor;
if ( !jsonPaint.contains( QStringLiteral( "fill-outline-color" ) ) )
{
// fill-outline-color
if ( fillColor.isValid() )
fillOutlineColor = fillColor;
else
{
// use fill color data defined property
if ( ddProperties.isActive( QgsSymbolLayer::PropertyFillColor ) )
ddProperties.setProperty( QgsSymbolLayer::PropertyStrokeColor, ddProperties.property( QgsSymbolLayer::PropertyFillColor ) );
}
}
else
{
const QVariant jsonFillOutlineColor = jsonPaint.value( QStringLiteral( "fill-outline-color" ) );
switch ( jsonFillOutlineColor.type() )
{
case QVariant::Map:
ddProperties.setProperty( QgsSymbolLayer::PropertyStrokeColor, parseInterpolateColorByZoom( jsonFillOutlineColor.toMap(), context, &fillOutlineColor ) );
break;
case QVariant::List:
case QVariant::StringList:
ddProperties.setProperty( QgsSymbolLayer::PropertyStrokeColor, parseValueList( jsonFillOutlineColor.toList(), PropertyType::Color, context, 1, 255, &fillOutlineColor ) );
break;
case QVariant::String:
fillOutlineColor = parseColor( jsonFillOutlineColor.toString(), context );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported fill-outline-color type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonFillOutlineColor.type() ) ) );
break;
}
}
double fillOpacity = -1.0;
double rasterOpacity = -1.0;
if ( jsonPaint.contains( QStringLiteral( "fill-opacity" ) ) )
{
const QVariant jsonFillOpacity = jsonPaint.value( QStringLiteral( "fill-opacity" ) );
switch ( jsonFillOpacity.type() )
{
case QVariant::Int:
case QVariant::Double:
fillOpacity = jsonFillOpacity.toDouble();
rasterOpacity = fillOpacity;
break;
case QVariant::Map:
if ( ddProperties.isActive( QgsSymbolLayer::PropertyFillColor ) )
{
context.pushWarning( QObject::tr( "%1: Could not set opacity of layer, opacity already defined in fill color" ).arg( context.layerId() ) );
}
else
{
ddProperties.setProperty( QgsSymbolLayer::PropertyFillColor, parseInterpolateOpacityByZoom( jsonFillOpacity.toMap(), fillColor.isValid() ? fillColor.alpha() : 255 ) );
ddProperties.setProperty( QgsSymbolLayer::PropertyStrokeColor, parseInterpolateOpacityByZoom( jsonFillOpacity.toMap(), fillOutlineColor.isValid() ? fillOutlineColor.alpha() : 255 ) );
ddRasterProperties.setProperty( QgsSymbolLayer::PropertyOpacity, parseInterpolateByZoom( jsonFillOpacity.toMap(), context, 100, &rasterOpacity ) );
}
break;
case QVariant::List:
case QVariant::StringList:
if ( ddProperties.isActive( QgsSymbolLayer::PropertyFillColor ) )
{
context.pushWarning( QObject::tr( "%1: Could not set opacity of layer, opacity already defined in fill color" ).arg( context.layerId() ) );
}
else
{
ddProperties.setProperty( QgsSymbolLayer::PropertyFillColor, parseValueList( jsonFillOpacity.toList(), PropertyType::Opacity, context, 1, fillColor.isValid() ? fillColor.alpha() : 255 ) );
ddProperties.setProperty( QgsSymbolLayer::PropertyStrokeColor, parseValueList( jsonFillOpacity.toList(), PropertyType::Opacity, context, 1, fillOutlineColor.isValid() ? fillOutlineColor.alpha() : 255 ) );
ddRasterProperties.setProperty( QgsSymbolLayer::PropertyOpacity, parseValueList( jsonFillOpacity.toList(), PropertyType::Numeric, context, 100, 255, nullptr, &rasterOpacity ) );
}
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported fill-opacity type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonFillOpacity.type() ) ) );
break;
}
}
// fill-translate
QPointF fillTranslate;
if ( jsonPaint.contains( QStringLiteral( "fill-translate" ) ) )
{
const QVariant jsonFillTranslate = jsonPaint.value( QStringLiteral( "fill-translate" ) );
switch ( jsonFillTranslate.type() )
{
case QVariant::Map:
ddProperties.setProperty( QgsSymbolLayer::PropertyOffset, parseInterpolatePointByZoom( jsonFillTranslate.toMap(), context, context.pixelSizeConversionFactor(), &fillTranslate ) );
break;
case QVariant::List:
case QVariant::StringList:
fillTranslate = QPointF( jsonFillTranslate.toList().value( 0 ).toDouble() * context.pixelSizeConversionFactor(),
jsonFillTranslate.toList().value( 1 ).toDouble() * context.pixelSizeConversionFactor() );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported fill-translate type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonFillTranslate.type() ) ) );
break;
}
}
std::unique_ptr< QgsSymbol > symbol( std::make_unique< QgsFillSymbol >() );
QgsSimpleFillSymbolLayer *fillSymbol = dynamic_cast< QgsSimpleFillSymbolLayer * >( symbol->symbolLayer( 0 ) );
Q_ASSERT( fillSymbol ); // should not fail since QgsFillSymbol() constructor instantiates a QgsSimpleFillSymbolLayer
// set render units
symbol->setOutputUnit( context.targetUnit() );
fillSymbol->setOutputUnit( context.targetUnit() );
if ( !fillTranslate.isNull() )
{
fillSymbol->setOffset( fillTranslate );
}
fillSymbol->setOffsetUnit( context.targetUnit() );
if ( jsonPaint.contains( QStringLiteral( "fill-pattern" ) ) )
{
// get fill-pattern to set sprite
const QVariant fillPatternJson = jsonPaint.value( QStringLiteral( "fill-pattern" ) );
// fill-pattern disabled dillcolor
fillColor = QColor();
fillOutlineColor = QColor();
// fill-pattern can be String or Object
// String: {"fill-pattern": "dash-t"}
// Object: {"fill-pattern":{"stops":[[11,"wetland8"],[12,"wetland16"]]}}
QSize spriteSize;
QString spriteProperty, spriteSizeProperty;
const QString sprite = retrieveSpriteAsBase64( fillPatternJson, context, spriteSize, spriteProperty, spriteSizeProperty );
if ( !sprite.isEmpty() )
{
// when fill-pattern exists, set and insert QgsRasterFillSymbolLayer
QgsRasterFillSymbolLayer *rasterFill = new QgsRasterFillSymbolLayer();
rasterFill->setImageFilePath( sprite );
rasterFill->setWidth( spriteSize.width() );
rasterFill->setWidthUnit( context.targetUnit() );
rasterFill->setCoordinateMode( QgsRasterFillSymbolLayer::Viewport );
if ( rasterOpacity >= 0 )
{
rasterFill->setOpacity( rasterOpacity );
}
if ( !spriteProperty.isEmpty() )
{
ddRasterProperties.setProperty( QgsSymbolLayer::PropertyFile, QgsProperty::fromExpression( spriteProperty ) );
ddRasterProperties.setProperty( QgsSymbolLayer::PropertyWidth, QgsProperty::fromExpression( spriteSizeProperty ) );
}
rasterFill->setDataDefinedProperties( ddRasterProperties );
symbol->appendSymbolLayer( rasterFill );
}
}
fillSymbol->setDataDefinedProperties( ddProperties );
if ( fillOpacity != -1 )
{
symbol->setOpacity( fillOpacity );
}
if ( fillOutlineColor.isValid() )
{
fillSymbol->setStrokeColor( fillOutlineColor );
}
else
{
fillSymbol->setStrokeStyle( Qt::NoPen );
}
if ( fillColor.isValid() )
{
fillSymbol->setFillColor( fillColor );
}
else
{
fillSymbol->setBrushStyle( Qt::NoBrush );
}
style.setGeometryType( QgsWkbTypes::PolygonGeometry );
style.setSymbol( symbol.release() );
return true;
}
bool QgsMapBoxGlStyleConverter::parseLineLayer( const QVariantMap &jsonLayer, QgsVectorTileBasicRendererStyle &style, QgsMapBoxGlStyleConversionContext &context )
{
if ( !jsonLayer.contains( QStringLiteral( "paint" ) ) )
{
context.pushWarning( QObject::tr( "%1: Style has no paint property, skipping" ).arg( context.layerId() ) );
return false;
}
const QVariantMap jsonPaint = jsonLayer.value( QStringLiteral( "paint" ) ).toMap();
if ( jsonPaint.contains( QStringLiteral( "line-pattern" ) ) )
{
context.pushWarning( QObject::tr( "%1: Skipping unsupported line-pattern property" ).arg( context.layerId() ) );
return false;
}
QgsPropertyCollection ddProperties;
// line color
QColor lineColor;
if ( jsonPaint.contains( QStringLiteral( "line-color" ) ) )
{
const QVariant jsonLineColor = jsonPaint.value( QStringLiteral( "line-color" ) );
switch ( jsonLineColor.type() )
{
case QVariant::Map:
ddProperties.setProperty( QgsSymbolLayer::PropertyFillColor, parseInterpolateColorByZoom( jsonLineColor.toMap(), context, &lineColor ) );
ddProperties.setProperty( QgsSymbolLayer::PropertyStrokeColor, ddProperties.property( QgsSymbolLayer::PropertyFillColor ) );
break;
case QVariant::List:
case QVariant::StringList:
ddProperties.setProperty( QgsSymbolLayer::PropertyFillColor, parseValueList( jsonLineColor.toList(), PropertyType::Color, context, 1, 255, &lineColor ) );
ddProperties.setProperty( QgsSymbolLayer::PropertyStrokeColor, ddProperties.property( QgsSymbolLayer::PropertyFillColor ) );
break;
case QVariant::String:
lineColor = parseColor( jsonLineColor.toString(), context );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported line-color type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonLineColor.type() ) ) );
break;
}
}
else
{
// defaults to #000000
lineColor = QColor( 0, 0, 0 );
}
double lineWidth = 1.0;
if ( jsonPaint.contains( QStringLiteral( "line-width" ) ) )
{
const QVariant jsonLineWidth = jsonPaint.value( QStringLiteral( "line-width" ) );
switch ( jsonLineWidth.type() )
{
case QVariant::Int:
case QVariant::Double:
lineWidth = jsonLineWidth.toDouble() * context.pixelSizeConversionFactor();
break;
case QVariant::Map:
lineWidth = -1;
ddProperties.setProperty( QgsSymbolLayer::PropertyStrokeWidth, parseInterpolateByZoom( jsonLineWidth.toMap(), context, context.pixelSizeConversionFactor(), &lineWidth ) );
break;
case QVariant::List:
case QVariant::StringList:
ddProperties.setProperty( QgsSymbolLayer::PropertyStrokeWidth, parseValueList( jsonLineWidth.toList(), PropertyType::Numeric, context, context.pixelSizeConversionFactor(), 255, nullptr, &lineWidth ) );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported fill-width type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonLineWidth.type() ) ) );
break;
}
}
double lineOffset = 0.0;
if ( jsonPaint.contains( QStringLiteral( "line-offset" ) ) )
{
const QVariant jsonLineOffset = jsonPaint.value( QStringLiteral( "line-offset" ) );
switch ( jsonLineOffset.type() )
{
case QVariant::Int:
case QVariant::Double:
lineOffset = -jsonLineOffset.toDouble() * context.pixelSizeConversionFactor();
break;
case QVariant::Map:
lineWidth = -1;
ddProperties.setProperty( QgsSymbolLayer::PropertyOffset, parseInterpolateByZoom( jsonLineOffset.toMap(), context, context.pixelSizeConversionFactor() * -1, &lineOffset ) );
break;
case QVariant::List:
case QVariant::StringList:
ddProperties.setProperty( QgsSymbolLayer::PropertyOffset, parseValueList( jsonLineOffset.toList(), PropertyType::Numeric, context, context.pixelSizeConversionFactor() * -1, 255, nullptr, &lineOffset ) );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported line-offset type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonLineOffset.type() ) ) );
break;
}
}
double lineOpacity = -1.0;
if ( jsonPaint.contains( QStringLiteral( "line-opacity" ) ) )
{
const QVariant jsonLineOpacity = jsonPaint.value( QStringLiteral( "line-opacity" ) );
switch ( jsonLineOpacity.type() )
{
case QVariant::Int:
case QVariant::Double:
lineOpacity = jsonLineOpacity.toDouble();
break;
case QVariant::Map:
if ( ddProperties.isActive( QgsSymbolLayer::PropertyStrokeColor ) )
{
context.pushWarning( QObject::tr( "%1: Could not set opacity of layer, opacity already defined in stroke color" ).arg( context.layerId() ) );
}
else
{
ddProperties.setProperty( QgsSymbolLayer::PropertyStrokeColor, parseInterpolateOpacityByZoom( jsonLineOpacity.toMap(), lineColor.isValid() ? lineColor.alpha() : 255 ) );
}
break;
case QVariant::List:
case QVariant::StringList:
if ( ddProperties.isActive( QgsSymbolLayer::PropertyStrokeColor ) )
{
context.pushWarning( QObject::tr( "%1: Could not set opacity of layer, opacity already defined in stroke color" ).arg( context.layerId() ) );
}
else
{
ddProperties.setProperty( QgsSymbolLayer::PropertyStrokeColor, parseValueList( jsonLineOpacity.toList(), PropertyType::Opacity, context, 1, lineColor.isValid() ? lineColor.alpha() : 255 ) );
}
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported line-opacity type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonLineOpacity.type() ) ) );
break;
}
}
QVector< double > dashVector;
if ( jsonPaint.contains( QStringLiteral( "line-dasharray" ) ) )
{
const QVariant jsonLineDashArray = jsonPaint.value( QStringLiteral( "line-dasharray" ) );
switch ( jsonLineDashArray.type() )
{
case QVariant::Map:
{
//TODO improve parsing (use PropertyCustomDash?)
const QVariantList dashSource = jsonLineDashArray.toMap().value( QStringLiteral( "stops" ) ).toList().last().toList().value( 1 ).toList();
for ( const QVariant &v : dashSource )
{
dashVector << v.toDouble() * context.pixelSizeConversionFactor();
}
break;
}
case QVariant::List:
case QVariant::StringList:
{
const QVariantList dashSource = jsonLineDashArray.toList();
for ( const QVariant &v : dashSource )
{
dashVector << v.toDouble() * context.pixelSizeConversionFactor();
}
break;
}
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported line-dasharray type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonLineDashArray.type() ) ) );
break;
}
}
Qt::PenCapStyle penCapStyle = Qt::FlatCap;
Qt::PenJoinStyle penJoinStyle = Qt::MiterJoin;
if ( jsonLayer.contains( QStringLiteral( "layout" ) ) )
{
const QVariantMap jsonLayout = jsonLayer.value( QStringLiteral( "layout" ) ).toMap();
if ( jsonLayout.contains( QStringLiteral( "line-cap" ) ) )
{
penCapStyle = parseCapStyle( jsonLayout.value( QStringLiteral( "line-cap" ) ).toString() );
}
if ( jsonLayout.contains( QStringLiteral( "line-join" ) ) )
{
penJoinStyle = parseJoinStyle( jsonLayout.value( QStringLiteral( "line-join" ) ).toString() );
}
}
std::unique_ptr< QgsSymbol > symbol( std::make_unique< QgsLineSymbol >() );
QgsSimpleLineSymbolLayer *lineSymbol = dynamic_cast< QgsSimpleLineSymbolLayer * >( symbol->symbolLayer( 0 ) );
Q_ASSERT( lineSymbol ); // should not fail since QgsLineSymbol() constructor instantiates a QgsSimpleLineSymbolLayer
// set render units
symbol->setOutputUnit( context.targetUnit() );
lineSymbol->setOutputUnit( context.targetUnit() );
lineSymbol->setPenCapStyle( penCapStyle );
lineSymbol->setPenJoinStyle( penJoinStyle );
lineSymbol->setDataDefinedProperties( ddProperties );
lineSymbol->setOffset( lineOffset );
lineSymbol->setOffsetUnit( context.targetUnit() );
if ( lineOpacity != -1 )
{
symbol->setOpacity( lineOpacity );
}
if ( lineColor.isValid() )
{
lineSymbol->setColor( lineColor );
}
if ( lineWidth != -1 )
{
lineSymbol->setWidth( lineWidth );
}
if ( !dashVector.empty() )
{
lineSymbol->setUseCustomDashPattern( true );
lineSymbol->setCustomDashVector( dashVector );
}
style.setGeometryType( QgsWkbTypes::LineGeometry );
style.setSymbol( symbol.release() );
return true;
}
bool QgsMapBoxGlStyleConverter::parseCircleLayer( const QVariantMap &jsonLayer, QgsVectorTileBasicRendererStyle &style, QgsMapBoxGlStyleConversionContext &context )
{
if ( !jsonLayer.contains( QStringLiteral( "paint" ) ) )
{
context.pushWarning( QObject::tr( "%1: Style has no paint property, skipping" ).arg( context.layerId() ) );
return false;
}
const QVariantMap jsonPaint = jsonLayer.value( QStringLiteral( "paint" ) ).toMap();
QgsPropertyCollection ddProperties;
// circle color
QColor circleFillColor;
if ( jsonPaint.contains( QStringLiteral( "circle-color" ) ) )
{
const QVariant jsonCircleColor = jsonPaint.value( QStringLiteral( "circle-color" ) );
switch ( jsonCircleColor.type() )
{
case QVariant::Map:
ddProperties.setProperty( QgsSymbolLayer::PropertyFillColor, parseInterpolateColorByZoom( jsonCircleColor.toMap(), context, &circleFillColor ) );
break;
case QVariant::List:
case QVariant::StringList:
ddProperties.setProperty( QgsSymbolLayer::PropertyFillColor, parseValueList( jsonCircleColor.toList(), PropertyType::Color, context, 1, 255, &circleFillColor ) );
break;
case QVariant::String:
circleFillColor = parseColor( jsonCircleColor.toString(), context );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported circle-color type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonCircleColor.type() ) ) );
break;
}
}
else
{
// defaults to #000000
circleFillColor = QColor( 0, 0, 0 );
}
// circle radius
double circleDiameter = 10.0;
if ( jsonPaint.contains( QStringLiteral( "circle-radius" ) ) )
{
const QVariant jsonCircleRadius = jsonPaint.value( QStringLiteral( "circle-radius" ) );
switch ( jsonCircleRadius.type() )
{
case QVariant::Int:
case QVariant::Double:
circleDiameter = jsonCircleRadius.toDouble() * context.pixelSizeConversionFactor() * 2;
break;
case QVariant::Map:
circleDiameter = -1;
ddProperties.setProperty( QgsSymbolLayer::PropertyWidth, parseInterpolateByZoom( jsonCircleRadius.toMap(), context, context.pixelSizeConversionFactor() * 2, &circleDiameter ) );
break;
case QVariant::List:
case QVariant::StringList:
ddProperties.setProperty( QgsSymbolLayer::PropertyWidth, parseValueList( jsonCircleRadius.toList(), PropertyType::Numeric, context, context.pixelSizeConversionFactor() * 2, 255, nullptr, &circleDiameter ) );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported circle-radius type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonCircleRadius.type() ) ) );
break;
}
}
double circleOpacity = -1.0;
if ( jsonPaint.contains( QStringLiteral( "circle-opacity" ) ) )
{
const QVariant jsonCircleOpacity = jsonPaint.value( QStringLiteral( "circle-opacity" ) );
switch ( jsonCircleOpacity.type() )
{
case QVariant::Int:
case QVariant::Double:
circleOpacity = jsonCircleOpacity.toDouble();
break;
case QVariant::Map:
ddProperties.setProperty( QgsSymbolLayer::PropertyFillColor, parseInterpolateOpacityByZoom( jsonCircleOpacity.toMap(), circleFillColor.isValid() ? circleFillColor.alpha() : 255 ) );
break;
case QVariant::List:
case QVariant::StringList:
ddProperties.setProperty( QgsSymbolLayer::PropertyFillColor, parseValueList( jsonCircleOpacity.toList(), PropertyType::Opacity, context, 1, circleFillColor.isValid() ? circleFillColor.alpha() : 255 ) );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported circle-opacity type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonCircleOpacity.type() ) ) );
break;
}
}
if ( ( circleOpacity != -1 ) && circleFillColor.isValid() )
{
circleFillColor.setAlphaF( circleOpacity );
}
// circle stroke color
QColor circleStrokeColor;
if ( jsonPaint.contains( QStringLiteral( "circle-stroke-color" ) ) )
{
const QVariant jsonCircleStrokeColor = jsonPaint.value( QStringLiteral( "circle-stroke-color" ) );
switch ( jsonCircleStrokeColor.type() )
{
case QVariant::Map:
ddProperties.setProperty( QgsSymbolLayer::PropertyStrokeColor, parseInterpolateColorByZoom( jsonCircleStrokeColor.toMap(), context, &circleStrokeColor ) );
break;
case QVariant::List:
case QVariant::StringList:
ddProperties.setProperty( QgsSymbolLayer::PropertyStrokeColor, parseValueList( jsonCircleStrokeColor.toList(), PropertyType::Color, context, 1, 255, &circleStrokeColor ) );
break;
case QVariant::String:
circleStrokeColor = parseColor( jsonCircleStrokeColor.toString(), context );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported circle-stroke-color type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonCircleStrokeColor.type() ) ) );
break;
}
}
// circle stroke width
double circleStrokeWidth = -1.0;
if ( jsonPaint.contains( QStringLiteral( "circle-stroke-width" ) ) )
{
const QVariant circleStrokeWidthJson = jsonPaint.value( QStringLiteral( "circle-stroke-width" ) );
switch ( circleStrokeWidthJson.type() )
{
case QVariant::Int:
case QVariant::Double:
circleStrokeWidth = circleStrokeWidthJson.toDouble() * context.pixelSizeConversionFactor();
break;
case QVariant::Map:
circleStrokeWidth = -1.0;
ddProperties.setProperty( QgsSymbolLayer::PropertyStrokeWidth, parseInterpolateByZoom( circleStrokeWidthJson.toMap(), context, context.pixelSizeConversionFactor(), &circleStrokeWidth ) );
break;
case QVariant::List:
case QVariant::StringList:
ddProperties.setProperty( QgsSymbolLayer::PropertyStrokeWidth, parseValueList( circleStrokeWidthJson.toList(), PropertyType::Numeric, context, context.pixelSizeConversionFactor(), 255, nullptr, &circleStrokeWidth ) );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported circle-stroke-width type (%2)" ).arg( context.layerId(), QMetaType::typeName( circleStrokeWidthJson.type() ) ) );
break;
}
}
double circleStrokeOpacity = -1.0;
if ( jsonPaint.contains( QStringLiteral( "circle-stroke-opacity" ) ) )
{
const QVariant jsonCircleStrokeOpacity = jsonPaint.value( QStringLiteral( "circle-stroke-opacity" ) );
switch ( jsonCircleStrokeOpacity.type() )
{
case QVariant::Int:
case QVariant::Double:
circleStrokeOpacity = jsonCircleStrokeOpacity.toDouble();
break;
case QVariant::Map:
ddProperties.setProperty( QgsSymbolLayer::PropertyStrokeColor, parseInterpolateOpacityByZoom( jsonCircleStrokeOpacity.toMap(), circleStrokeColor.isValid() ? circleStrokeColor.alpha() : 255 ) );
break;
case QVariant::List:
case QVariant::StringList:
ddProperties.setProperty( QgsSymbolLayer::PropertyStrokeColor, parseValueList( jsonCircleStrokeOpacity.toList(), PropertyType::Opacity, context, 1, circleStrokeColor.isValid() ? circleStrokeColor.alpha() : 255 ) );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported circle-stroke-opacity type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonCircleStrokeOpacity.type() ) ) );
break;
}
}
if ( ( circleStrokeOpacity != -1 ) && circleStrokeColor.isValid() )
{
circleStrokeColor.setAlphaF( circleStrokeOpacity );
}
// translate
QPointF circleTranslate;
if ( jsonPaint.contains( QStringLiteral( "circle-translate" ) ) )
{
const QVariant jsonCircleTranslate = jsonPaint.value( QStringLiteral( "circle-translate" ) );
switch ( jsonCircleTranslate.type() )
{
case QVariant::Map:
ddProperties.setProperty( QgsSymbolLayer::PropertyOffset, parseInterpolatePointByZoom( jsonCircleTranslate.toMap(), context, context.pixelSizeConversionFactor(), &circleTranslate ) );
break;
case QVariant::List:
case QVariant::StringList:
circleTranslate = QPointF( jsonCircleTranslate.toList().value( 0 ).toDouble() * context.pixelSizeConversionFactor(),
jsonCircleTranslate.toList().value( 1 ).toDouble() * context.pixelSizeConversionFactor() );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported circle-translate type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonCircleTranslate.type() ) ) );
break;
}
}
std::unique_ptr< QgsSymbol > symbol( std::make_unique< QgsMarkerSymbol >() );
QgsSimpleMarkerSymbolLayer *markerSymbolLayer = dynamic_cast< QgsSimpleMarkerSymbolLayer * >( symbol->symbolLayer( 0 ) );
Q_ASSERT( markerSymbolLayer );
// set render units
symbol->setOutputUnit( context.targetUnit() );
symbol->setDataDefinedProperties( ddProperties );
if ( !circleTranslate.isNull() )
{
markerSymbolLayer->setOffset( circleTranslate );
markerSymbolLayer->setOffsetUnit( context.targetUnit() );
}
if ( circleFillColor.isValid() )
{
markerSymbolLayer->setFillColor( circleFillColor );
}
if ( circleDiameter != -1 )
{
markerSymbolLayer->setSize( circleDiameter );
markerSymbolLayer->setSizeUnit( context.targetUnit() );
}
if ( circleStrokeColor.isValid() )
{
markerSymbolLayer->setStrokeColor( circleStrokeColor );
}
if ( circleStrokeWidth != -1 )
{
markerSymbolLayer->setStrokeWidth( circleStrokeWidth );
markerSymbolLayer->setStrokeWidthUnit( context.targetUnit() );
}
style.setGeometryType( QgsWkbTypes::PointGeometry );
style.setSymbol( symbol.release() );
return true;
}
void QgsMapBoxGlStyleConverter::parseSymbolLayer( const QVariantMap &jsonLayer, QgsVectorTileBasicRendererStyle &renderer, bool &hasRenderer, QgsVectorTileBasicLabelingStyle &labelingStyle, bool &hasLabeling, QgsMapBoxGlStyleConversionContext &context )
{
hasLabeling = false;
hasRenderer = false;
if ( !jsonLayer.contains( QStringLiteral( "layout" ) ) )
{
context.pushWarning( QObject::tr( "%1: Style layer has no layout property, skipping" ).arg( context.layerId() ) );
return;
}
const QVariantMap jsonLayout = jsonLayer.value( QStringLiteral( "layout" ) ).toMap();
if ( !jsonLayout.contains( QStringLiteral( "text-field" ) ) )
{
hasRenderer = parseSymbolLayerAsRenderer( jsonLayer, renderer, context );
return;
}
if ( !jsonLayer.contains( QStringLiteral( "paint" ) ) )
{
context.pushWarning( QObject::tr( "%1: Style layer has no paint property, skipping" ).arg( context.layerId() ) );
return;
}
const QVariantMap jsonPaint = jsonLayer.value( QStringLiteral( "paint" ) ).toMap();
QgsPropertyCollection ddLabelProperties;
double textSize = 16.0 * context.pixelSizeConversionFactor();
QString textSizeProperty;
if ( jsonLayout.contains( QStringLiteral( "text-size" ) ) )
{
const QVariant jsonTextSize = jsonLayout.value( QStringLiteral( "text-size" ) );
switch ( jsonTextSize.type() )
{
case QVariant::Int:
case QVariant::Double:
textSize = jsonTextSize.toDouble() * context.pixelSizeConversionFactor();
break;
case QVariant::Map:
textSize = -1;
textSizeProperty = parseInterpolateByZoom( jsonTextSize.toMap(), context, context.pixelSizeConversionFactor(), &textSize );
break;
case QVariant::List:
case QVariant::StringList:
textSize = -1;
textSizeProperty = parseValueList( jsonTextSize.toList(), PropertyType::Numeric, context, context.pixelSizeConversionFactor(), 255, nullptr, &textSize );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported text-size type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonTextSize.type() ) ) );
break;
}
if ( !textSizeProperty.isEmpty() )
{
ddLabelProperties.setProperty( QgsPalLayerSettings::Size, textSizeProperty );
}
}
// a rough average of ems to character count conversion for a variety of fonts
constexpr double EM_TO_CHARS = 2.0;
double textMaxWidth = -1;
if ( jsonLayout.contains( QStringLiteral( "text-max-width" ) ) )
{
const QVariant jsonTextMaxWidth = jsonLayout.value( QStringLiteral( "text-max-width" ) );
switch ( jsonTextMaxWidth.type() )
{
case QVariant::Int:
case QVariant::Double:
textMaxWidth = jsonTextMaxWidth.toDouble() * EM_TO_CHARS;
break;
case QVariant::Map:
ddLabelProperties.setProperty( QgsPalLayerSettings::AutoWrapLength, parseInterpolateByZoom( jsonTextMaxWidth.toMap(), context, EM_TO_CHARS, &textMaxWidth ) );
break;
case QVariant::List:
case QVariant::StringList:
ddLabelProperties.setProperty( QgsPalLayerSettings::AutoWrapLength, parseValueList( jsonTextMaxWidth.toList(), PropertyType::Numeric, context, EM_TO_CHARS, 255, nullptr, &textMaxWidth ) );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported text-max-width type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonTextMaxWidth.type() ) ) );
break;
}
}
else
{
// defaults to 10
textMaxWidth = 10 * EM_TO_CHARS;
}
double textLetterSpacing = -1;
if ( jsonLayout.contains( QStringLiteral( "text-letter-spacing" ) ) )
{
const QVariant jsonTextLetterSpacing = jsonLayout.value( QStringLiteral( "text-letter-spacing" ) );
switch ( jsonTextLetterSpacing.type() )
{
case QVariant::Int:
case QVariant::Double:
textLetterSpacing = jsonTextLetterSpacing.toDouble();
break;
case QVariant::Map:
ddLabelProperties.setProperty( QgsPalLayerSettings::FontLetterSpacing, parseInterpolateByZoom( jsonTextLetterSpacing.toMap(), context, 1, &textLetterSpacing ) );
break;
case QVariant::List:
case QVariant::StringList:
ddLabelProperties.setProperty( QgsPalLayerSettings::FontLetterSpacing, parseValueList( jsonTextLetterSpacing.toList(), PropertyType::Numeric, context, 1, 255, nullptr, &textLetterSpacing ) );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported text-letter-spacing type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonTextLetterSpacing.type() ) ) );
break;
}
}
QFont textFont;
bool foundFont = false;
QString fontName;
if ( jsonLayout.contains( QStringLiteral( "text-font" ) ) )
{
auto splitFontFamily = []( const QString & fontName, QString & family, QString & style ) -> bool
{
const QStringList textFontParts = fontName.split( ' ' );
for ( int i = 1; i < textFontParts.size(); ++i )
{
const QString candidateFontName = textFontParts.mid( 0, i ).join( ' ' );
const QString candidateFontStyle = textFontParts.mid( i ).join( ' ' );
if ( QgsFontUtils::fontFamilyHasStyle( candidateFontName, candidateFontStyle ) )
{
family = candidateFontName;
style = candidateFontStyle;
return true;
}
}
if ( QFontDatabase().hasFamily( fontName ) )
{
// the json isn't following the spec correctly!!
family = fontName;
style.clear();
return true;
}
return false;
};
const QVariant jsonTextFont = jsonLayout.value( QStringLiteral( "text-font" ) );
if ( jsonTextFont.type() != QVariant::List && jsonTextFont.type() != QVariant::StringList && jsonTextFont.type() != QVariant::String
&& jsonTextFont.type() != QVariant::Map )
{
context.pushWarning( QObject::tr( "%1: Skipping unsupported text-font type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonTextFont.type() ) ) );
}
else
{
switch ( jsonTextFont.type() )
{
case QVariant::List:
case QVariant::StringList:
fontName = jsonTextFont.toList().value( 0 ).toString();
break;
case QVariant::String:
fontName = jsonTextFont.toString();
break;
case QVariant::Map:
{
QString familyCaseString = QStringLiteral( "CASE " );
QString styleCaseString = QStringLiteral( "CASE " );
QString fontFamily;
QString fontStyle;
const QVariantList stops = jsonTextFont.toMap().value( QStringLiteral( "stops" ) ).toList();
bool error = false;
for ( int i = 0; i < stops.length() - 1; ++i )
{
// bottom zoom and value
const QVariant bz = stops.value( i ).toList().value( 0 );
const QString bv = stops.value( i ).toList().value( 1 ).type() == QVariant::String ? stops.value( i ).toList().value( 1 ).toString() : stops.value( i ).toList().value( 1 ).toList().value( 0 ).toString();
if ( bz.type() == QVariant::List || bz.type() == QVariant::StringList )
{
context.pushWarning( QObject::tr( "%1: Expressions in interpolation function are not supported, skipping." ).arg( context.layerId() ) );
error = true;
break;
}
// top zoom
const QVariant tz = stops.value( i + 1 ).toList().value( 0 );
if ( tz.type() == QVariant::List || tz.type() == QVariant::StringList )
{
context.pushWarning( QObject::tr( "%1: Expressions in interpolation function are not supported, skipping." ).arg( context.layerId() ) );
error = true;
break;
}
if ( splitFontFamily( bv, fontFamily, fontStyle ) )
{
familyCaseString += QStringLiteral( "WHEN @vector_tile_zoom > %1 AND @vector_tile_zoom <= %2 "
"THEN %3 " ).arg( bz.toString(),
tz.toString(),
QgsExpression::quotedValue( fontFamily ) );
styleCaseString += QStringLiteral( "WHEN @vector_tile_zoom > %1 AND @vector_tile_zoom <= %2 "
"THEN %3 " ).arg( bz.toString(),
tz.toString(),
QgsExpression::quotedValue( fontStyle ) );
}
else
{
context.pushWarning( QObject::tr( "%1: Referenced font %2 is not available on system" ).arg( context.layerId(), bv ) );
}
}
if ( error )
break;
const QString bv = stops.constLast().toList().value( 1 ).type() == QVariant::String ? stops.constLast().toList().value( 1 ).toString() : stops.constLast().toList().value( 1 ).toList().value( 0 ).toString();
if ( splitFontFamily( bv, fontFamily, fontStyle ) )
{
familyCaseString += QStringLiteral( "ELSE %1 END" ).arg( QgsExpression::quotedValue( fontFamily ) );
styleCaseString += QStringLiteral( "ELSE %1 END" ).arg( QgsExpression::quotedValue( fontStyle ) );
}
else
{
context.pushWarning( QObject::tr( "%1: Referenced font %2 is not available on system" ).arg( context.layerId(), bv ) );
}
ddLabelProperties.setProperty( QgsPalLayerSettings::Family, QgsProperty::fromExpression( familyCaseString ) );
ddLabelProperties.setProperty( QgsPalLayerSettings::FontStyle, QgsProperty::fromExpression( styleCaseString ) );
foundFont = true;
fontName = fontFamily;
break;
}
default:
break;
}
QString fontFamily;
QString fontStyle;
if ( splitFontFamily( fontName, fontFamily, fontStyle ) )
{
textFont = QFont( fontFamily );
if ( !fontStyle.isEmpty() )
textFont.setStyleName( fontStyle );
foundFont = true;
}
}
}
else
{
// Defaults to ["Open Sans Regular","Arial Unicode MS Regular"].
if ( QgsFontUtils::fontFamilyHasStyle( QStringLiteral( "Open Sans" ), QStringLiteral( "Regular" ) ) )
{
fontName = QStringLiteral( "Open Sans" );
textFont = QFont( fontName );
textFont.setStyleName( QStringLiteral( "Regular" ) );
foundFont = true;
}
else if ( QgsFontUtils::fontFamilyHasStyle( QStringLiteral( "Arial Unicode MS" ), QStringLiteral( "Regular" ) ) )
{
fontName = QStringLiteral( "Arial Unicode MS" );
textFont = QFont( fontName );
textFont.setStyleName( QStringLiteral( "Regular" ) );
foundFont = true;
}
else
{
fontName = QStringLiteral( "Open Sans, Arial Unicode MS" );
}
}
if ( !foundFont && !fontName.isEmpty() )
{
context.pushWarning( QObject::tr( "%1: Referenced font %2 is not available on system" ).arg( context.layerId(), fontName ) );
}
// text color
QColor textColor;
if ( jsonPaint.contains( QStringLiteral( "text-color" ) ) )
{
const QVariant jsonTextColor = jsonPaint.value( QStringLiteral( "text-color" ) );
switch ( jsonTextColor.type() )
{
case QVariant::Map:
ddLabelProperties.setProperty( QgsPalLayerSettings::Color, parseInterpolateColorByZoom( jsonTextColor.toMap(), context, &textColor ) );
break;
case QVariant::List:
case QVariant::StringList:
ddLabelProperties.setProperty( QgsPalLayerSettings::Color, parseValueList( jsonTextColor.toList(), PropertyType::Color, context, 1, 255, &textColor ) );
break;
case QVariant::String:
textColor = parseColor( jsonTextColor.toString(), context );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported text-color type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonTextColor.type() ) ) );
break;
}
}
else
{
// defaults to #000000
textColor = QColor( 0, 0, 0 );
}
// buffer color
QColor bufferColor;
if ( jsonPaint.contains( QStringLiteral( "text-halo-color" ) ) )
{
const QVariant jsonBufferColor = jsonPaint.value( QStringLiteral( "text-halo-color" ) );
switch ( jsonBufferColor.type() )
{
case QVariant::Map:
ddLabelProperties.setProperty( QgsPalLayerSettings::BufferColor, parseInterpolateColorByZoom( jsonBufferColor.toMap(), context, &bufferColor ) );
break;
case QVariant::List:
case QVariant::StringList:
ddLabelProperties.setProperty( QgsPalLayerSettings::BufferColor, parseValueList( jsonBufferColor.toList(), PropertyType::Color, context, 1, 255, &bufferColor ) );
break;
case QVariant::String:
bufferColor = parseColor( jsonBufferColor.toString(), context );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported text-halo-color type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonBufferColor.type() ) ) );
break;
}
}
double bufferSize = 0.0;
// the pixel based text buffers appear larger when rendered on the web - so automatically scale
// them up when converting to a QGIS style
// (this number is based on trial-and-error comparisons only!)
constexpr double BUFFER_SIZE_SCALE = 2.0;
if ( jsonPaint.contains( QStringLiteral( "text-halo-width" ) ) )
{
const QVariant jsonHaloWidth = jsonPaint.value( QStringLiteral( "text-halo-width" ) );
switch ( jsonHaloWidth.type() )
{
case QVariant::Int:
case QVariant::Double:
bufferSize = jsonHaloWidth.toDouble() * context.pixelSizeConversionFactor() * BUFFER_SIZE_SCALE;
break;
case QVariant::Map:
bufferSize = 1;
ddLabelProperties.setProperty( QgsPalLayerSettings::BufferSize, parseInterpolateByZoom( jsonHaloWidth.toMap(), context, context.pixelSizeConversionFactor() * BUFFER_SIZE_SCALE, &bufferSize ) );
break;
case QVariant::List:
case QVariant::StringList:
bufferSize = 1;
ddLabelProperties.setProperty( QgsPalLayerSettings::BufferSize, parseValueList( jsonHaloWidth.toList(), PropertyType::Numeric, context, context.pixelSizeConversionFactor() * BUFFER_SIZE_SCALE, 255, nullptr, &bufferSize ) );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported text-halo-width type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonHaloWidth.type() ) ) );
break;
}
}
double haloBlurSize = 0;
if ( jsonPaint.contains( QStringLiteral( "text-halo-blur" ) ) )
{
const QVariant jsonTextHaloBlur = jsonPaint.value( QStringLiteral( "text-halo-blur" ) );
switch ( jsonTextHaloBlur.type() )
{
case QVariant::Int:
case QVariant::Double:
{
haloBlurSize = jsonTextHaloBlur.toDouble() * context.pixelSizeConversionFactor();
break;
}
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported text-halo-blur type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonTextHaloBlur.type() ) ) );
break;
}
}
QgsTextFormat format;
format.setSizeUnit( context.targetUnit() );
if ( textColor.isValid() )
format.setColor( textColor );
if ( textSize >= 0 )
format.setSize( textSize );
if ( foundFont )
format.setFont( textFont );
if ( textLetterSpacing > 0 )
{
QFont f = format.font();
f.setLetterSpacing( QFont::AbsoluteSpacing, textLetterSpacing );
format.setFont( f );
}
if ( bufferSize > 0 )
{
format.buffer().setEnabled( true );
format.buffer().setSize( bufferSize );
format.buffer().setSizeUnit( context.targetUnit() );
format.buffer().setColor( bufferColor );
if ( haloBlurSize > 0 )
{
QgsEffectStack *stack = new QgsEffectStack();
QgsBlurEffect *blur = new QgsBlurEffect() ;
blur->setEnabled( true );
blur->setBlurUnit( context.targetUnit() );
blur->setBlurLevel( haloBlurSize );
blur->setBlurMethod( QgsBlurEffect::StackBlur );
stack->appendEffect( blur );
stack->setEnabled( true );
format.buffer().setPaintEffect( stack );
}
}
QgsPalLayerSettings labelSettings;
if ( textMaxWidth > 0 )
{
labelSettings.autoWrapLength = textMaxWidth;
}
// convert field name
auto processLabelField = []( const QString & string, bool & isExpression )->QString
{
// {field_name} is permitted in string -- if multiple fields are present, convert them to an expression
// but if single field is covered in {}, return it directly
const QRegularExpression singleFieldRx( QStringLiteral( "^{([^}]+)}$" ) );
QRegularExpressionMatch match = singleFieldRx.match( string );
if ( match.hasMatch() )
{
isExpression = false;
return match.captured( 1 );
}
const QRegularExpression multiFieldRx( QStringLiteral( "(?={[^}]+})" ) );
const QStringList parts = string.split( multiFieldRx );
if ( parts.size() > 1 )
{
isExpression = true;
QStringList res;
for ( const QString &part : parts )
{
if ( part.isEmpty() )
continue;
// part will start at a {field} reference
const QStringList split = part.split( '}' );
res << QgsExpression::quotedColumnRef( split.at( 0 ).mid( 1 ) );
if ( !split.at( 1 ).isEmpty() )
res << QgsExpression::quotedValue( split.at( 1 ) );
}
return QStringLiteral( "concat(%1)" ).arg( res.join( ',' ) );
}
else
{
isExpression = false;
return string;
}
};
if ( jsonLayout.contains( QStringLiteral( "text-field" ) ) )
{
const QVariant jsonTextField = jsonLayout.value( QStringLiteral( "text-field" ) );
switch ( jsonTextField.type() )
{
case QVariant::String:
{
labelSettings.fieldName = processLabelField( jsonTextField.toString(), labelSettings.isExpression );
break;
}
case QVariant::List:
case QVariant::StringList:
{
const QVariantList textFieldList = jsonTextField.toList();
/*
* e.g.
* "text-field": ["format",
* "foo", { "font-scale": 1.2 },
* "bar", { "font-scale": 0.8 }
* ]
*/
if ( textFieldList.size() > 2 && textFieldList.at( 0 ).toString() == QLatin1String( "format" ) )
{
QStringList parts;
for ( int i = 1; i < textFieldList.size(); ++i )
{
bool isExpression = false;
const QString part = processLabelField( textFieldList.at( i ).toString(), isExpression );
if ( !isExpression )
parts << QgsExpression::quotedColumnRef( part );
else
parts << part;
// TODO -- we could also translate font color, underline, overline, strikethrough to HTML tags!
i += 1;
}
labelSettings.fieldName = QStringLiteral( "concat(%1)" ).arg( parts.join( ',' ) );
labelSettings.isExpression = true;
}
else
{
/*
* e.g.
* "text-field": ["to-string", ["get", "name"]]
*/
labelSettings.fieldName = parseExpression( textFieldList, context );
labelSettings.isExpression = true;
}
break;
}
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported text-field type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonTextField.type() ) ) );
break;
}
}
if ( jsonLayout.contains( QStringLiteral( "text-transform" ) ) )
{
const QString textTransform = jsonLayout.value( QStringLiteral( "text-transform" ) ).toString();
if ( textTransform == QLatin1String( "uppercase" ) )
{
labelSettings.fieldName = QStringLiteral( "upper(%1)" ).arg( labelSettings.isExpression ? labelSettings.fieldName : QgsExpression::quotedColumnRef( labelSettings.fieldName ) );
}
else if ( textTransform == QLatin1String( "lowercase" ) )
{
labelSettings.fieldName = QStringLiteral( "lower(%1)" ).arg( labelSettings.isExpression ? labelSettings.fieldName : QgsExpression::quotedColumnRef( labelSettings.fieldName ) );
}
labelSettings.isExpression = true;
}
labelSettings.placement = QgsPalLayerSettings::OverPoint;
QgsWkbTypes::GeometryType geometryType = QgsWkbTypes::PointGeometry;
if ( jsonLayout.contains( QStringLiteral( "symbol-placement" ) ) )
{
const QString symbolPlacement = jsonLayout.value( QStringLiteral( "symbol-placement" ) ).toString();
if ( symbolPlacement == QLatin1String( "line" ) )
{
labelSettings.placement = QgsPalLayerSettings::Curved;
labelSettings.lineSettings().setPlacementFlags( QgsLabeling::OnLine );
geometryType = QgsWkbTypes::LineGeometry;
if ( jsonLayout.contains( QStringLiteral( "text-rotation-alignment" ) ) )
{
const QString textRotationAlignment = jsonLayout.value( QStringLiteral( "text-rotation-alignment" ) ).toString();
if ( textRotationAlignment == QLatin1String( "viewport" ) )
{
labelSettings.placement = QgsPalLayerSettings::Horizontal;
}
}
if ( labelSettings.placement == QgsPalLayerSettings::Curved )
{
QPointF textOffset;
QString textOffsetProperty;
if ( jsonLayout.contains( QStringLiteral( "text-offset" ) ) )
{
const QVariant jsonTextOffset = jsonLayout.value( QStringLiteral( "text-offset" ) );
// units are ems!
switch ( jsonTextOffset.type() )
{
case QVariant::Map:
textOffsetProperty = parseInterpolatePointByZoom( jsonTextOffset.toMap(), context, textSizeProperty.isEmpty() ? textSize : 1.0, &textOffset );
if ( textSizeProperty.isEmpty() )
{
ddLabelProperties.setProperty( QgsPalLayerSettings::LabelDistance, QStringLiteral( "abs(array_get(%1,1))-%2" ).arg( textOffsetProperty ).arg( textSize ) );
}
else
{
ddLabelProperties.setProperty( QgsPalLayerSettings::LabelDistance, QStringLiteral( "with_variable('text_size',%2,abs(array_get(%1,1))*@text_size-@text_size)" ).arg( textOffsetProperty ).arg( textSizeProperty ) );
}
ddLabelProperties.setProperty( QgsPalLayerSettings::LinePlacementOptions, QStringLiteral( "if(array_get(%1,1)>0,'BL','AL')" ).arg( textOffsetProperty ) );
break;
case QVariant::List:
case QVariant::StringList:
textOffset = QPointF( jsonTextOffset.toList().value( 0 ).toDouble() * textSize,
jsonTextOffset.toList().value( 1 ).toDouble() * textSize );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported text-offset type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonTextOffset.type() ) ) );
break;
}
if ( !textOffset.isNull() )
{
labelSettings.distUnits = context.targetUnit();
labelSettings.dist = std::abs( textOffset.y() ) - textSize;
labelSettings.lineSettings().setPlacementFlags( textOffset.y() > 0.0 ? QgsLabeling::BelowLine : QgsLabeling::AboveLine );
if ( !textSizeProperty.isEmpty() && textOffsetProperty.isEmpty() )
{
ddLabelProperties.setProperty( QgsPalLayerSettings::LabelDistance, QStringLiteral( "with_variable('text_size',%2,%1*@text_size-@text_size)" ).arg( std::abs( textOffset.y() / textSize ) ).arg( ( textSizeProperty ) ) );
}
}
}
if ( textOffset.isNull() )
{
labelSettings.lineSettings().setPlacementFlags( QgsLabeling::OnLine );
}
}
}
}
if ( jsonLayout.contains( QStringLiteral( "text-justify" ) ) )
{
const QVariant jsonTextJustify = jsonLayout.value( QStringLiteral( "text-justify" ) );
// default is center
QString textAlign = QStringLiteral( "center" );
const QVariantMap conversionMap
{
{ QStringLiteral( "left" ), QStringLiteral( "left" ) },
{ QStringLiteral( "center" ), QStringLiteral( "center" ) },
{ QStringLiteral( "right" ), QStringLiteral( "right" ) },
{ QStringLiteral( "auto" ), QStringLiteral( "follow" ) }
};
switch ( jsonTextJustify.type() )
{
case QVariant::String:
textAlign = jsonTextJustify.toString();
break;
case QVariant::List:
ddLabelProperties.setProperty( QgsPalLayerSettings::OffsetQuad, QgsProperty::fromExpression( parseStringStops( jsonTextJustify.toList(), context, conversionMap, &textAlign ) ) );
break;
case QVariant::Map:
ddLabelProperties.setProperty( QgsPalLayerSettings::OffsetQuad, parseInterpolateStringByZoom( jsonTextJustify.toMap(), context, conversionMap, &textAlign ) );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported text-justify type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonTextJustify.type() ) ) );
break;
}
if ( textAlign == QLatin1String( "left" ) )
labelSettings.multilineAlign = QgsPalLayerSettings::MultiLeft;
else if ( textAlign == QLatin1String( "right" ) )
labelSettings.multilineAlign = QgsPalLayerSettings::MultiRight;
else if ( textAlign == QLatin1String( "center" ) )
labelSettings.multilineAlign = QgsPalLayerSettings::MultiCenter;
else if ( textAlign == QLatin1String( "follow" ) )
labelSettings.multilineAlign = QgsPalLayerSettings::MultiFollowPlacement;
}
else
{
labelSettings.multilineAlign = QgsPalLayerSettings::MultiCenter;
}
if ( labelSettings.placement == QgsPalLayerSettings::OverPoint )
{
if ( jsonLayout.contains( QStringLiteral( "text-anchor" ) ) )
{
const QVariant jsonTextAnchor = jsonLayout.value( QStringLiteral( "text-anchor" ) );
QString textAnchor;
const QVariantMap conversionMap
{
{ QStringLiteral( "center" ), 4 },
{ QStringLiteral( "left" ), 5 },
{ QStringLiteral( "right" ), 3 },
{ QStringLiteral( "top" ), 7 },
{ QStringLiteral( "bottom" ), 1 },
{ QStringLiteral( "top-left" ), 8 },
{ QStringLiteral( "top-right" ), 6 },
{ QStringLiteral( "bottom-left" ), 2 },
{ QStringLiteral( "bottom-right" ), 0 },
};
switch ( jsonTextAnchor.type() )
{
case QVariant::String:
textAnchor = jsonTextAnchor.toString();
break;
case QVariant::List:
ddLabelProperties.setProperty( QgsPalLayerSettings::OffsetQuad, QgsProperty::fromExpression( parseStringStops( jsonTextAnchor.toList(), context, conversionMap, &textAnchor ) ) );
break;
case QVariant::Map:
ddLabelProperties.setProperty( QgsPalLayerSettings::OffsetQuad, parseInterpolateStringByZoom( jsonTextAnchor.toMap(), context, conversionMap, &textAnchor ) );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported text-anchor type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonTextAnchor.type() ) ) );
break;
}
if ( textAnchor == QLatin1String( "center" ) )
labelSettings.quadOffset = QgsPalLayerSettings::QuadrantOver;
else if ( textAnchor == QLatin1String( "left" ) )
labelSettings.quadOffset = QgsPalLayerSettings::QuadrantRight;
else if ( textAnchor == QLatin1String( "right" ) )
labelSettings.quadOffset = QgsPalLayerSettings::QuadrantLeft;
else if ( textAnchor == QLatin1String( "top" ) )
labelSettings.quadOffset = QgsPalLayerSettings::QuadrantBelow;
else if ( textAnchor == QLatin1String( "bottom" ) )
labelSettings.quadOffset = QgsPalLayerSettings::QuadrantAbove;
else if ( textAnchor == QLatin1String( "top-left" ) )
labelSettings.quadOffset = QgsPalLayerSettings::QuadrantBelowRight;
else if ( textAnchor == QLatin1String( "top-right" ) )
labelSettings.quadOffset = QgsPalLayerSettings::QuadrantBelowLeft;
else if ( textAnchor == QLatin1String( "bottom-left" ) )
labelSettings.quadOffset = QgsPalLayerSettings::QuadrantAboveRight;
else if ( textAnchor == QLatin1String( "bottom-right" ) )
labelSettings.quadOffset = QgsPalLayerSettings::QuadrantAboveLeft;
}
QPointF textOffset;
if ( jsonLayout.contains( QStringLiteral( "text-offset" ) ) )
{
const QVariant jsonTextOffset = jsonLayout.value( QStringLiteral( "text-offset" ) );
// units are ems!
switch ( jsonTextOffset.type() )
{
case QVariant::Map:
ddLabelProperties.setProperty( QgsPalLayerSettings::OffsetXY, parseInterpolatePointByZoom( jsonTextOffset.toMap(), context, textSize, &textOffset ) );
break;
case QVariant::List:
case QVariant::StringList:
textOffset = QPointF( jsonTextOffset.toList().value( 0 ).toDouble() * textSize,
jsonTextOffset.toList().value( 1 ).toDouble() * textSize );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported text-offset type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonTextOffset.type() ) ) );
break;
}
if ( !textOffset.isNull() )
{
labelSettings.offsetUnits = context.targetUnit();
labelSettings.xOffset = textOffset.x();
labelSettings.yOffset = textOffset.y();
}
}
}
if ( jsonLayout.contains( QStringLiteral( "icon-image" ) ) &&
( labelSettings.placement == QgsPalLayerSettings::Horizontal || labelSettings.placement == QgsPalLayerSettings::Curved ) )
{
QSize spriteSize;
QString spriteProperty, spriteSizeProperty;
const QString sprite = retrieveSpriteAsBase64( jsonLayout.value( QStringLiteral( "icon-image" ) ), context, spriteSize, spriteProperty, spriteSizeProperty );
if ( !sprite.isEmpty() )
{
QgsRasterMarkerSymbolLayer *markerLayer = new QgsRasterMarkerSymbolLayer( );
markerLayer->setPath( sprite );
markerLayer->setSize( spriteSize.width() );
markerLayer->setSizeUnit( context.targetUnit() );
if ( !spriteProperty.isEmpty() )
{
QgsPropertyCollection markerDdProperties;
markerDdProperties.setProperty( QgsSymbolLayer::PropertyName, QgsProperty::fromExpression( spriteProperty ) );
markerLayer->setDataDefinedProperties( markerDdProperties );
ddLabelProperties.setProperty( QgsPalLayerSettings::ShapeSizeX, QgsProperty::fromExpression( spriteSizeProperty ) );
}
QgsTextBackgroundSettings backgroundSettings;
backgroundSettings.setEnabled( true );
backgroundSettings.setType( QgsTextBackgroundSettings::ShapeMarkerSymbol );
backgroundSettings.setSize( spriteSize );
backgroundSettings.setSizeUnit( context.targetUnit() );
backgroundSettings.setSizeType( QgsTextBackgroundSettings::SizeFixed );
backgroundSettings.setMarkerSymbol( new QgsMarkerSymbol( QgsSymbolLayerList() << markerLayer ) );
format.setBackground( backgroundSettings );
}
}
if ( textSize >= 0 )
{
// TODO -- this probably needs revisiting -- it was copied from the MapTiler code, but may be wrong...
labelSettings.priority = std::min( textSize / ( context.pixelSizeConversionFactor() * 3 ), 10.0 );
}
labelSettings.setFormat( format );
// use a low obstacle weight for layers by default -- we'd rather have more labels for these layers, even if placement isn't ideal
labelSettings.obstacleSettings().setFactor( 0.1 );
labelSettings.setDataDefinedProperties( ddLabelProperties );
labelingStyle.setGeometryType( geometryType );
labelingStyle.setLabelSettings( labelSettings );
hasLabeling = true;
hasRenderer = parseSymbolLayerAsRenderer( jsonLayer, renderer, context );
}
bool QgsMapBoxGlStyleConverter::parseSymbolLayerAsRenderer( const QVariantMap &jsonLayer, QgsVectorTileBasicRendererStyle &rendererStyle, QgsMapBoxGlStyleConversionContext &context )
{
if ( !jsonLayer.contains( QStringLiteral( "layout" ) ) )
{
context.pushWarning( QObject::tr( "%1: Style layer has no layout property, skipping" ).arg( context.layerId() ) );
return false;
}
const QVariantMap jsonLayout = jsonLayer.value( QStringLiteral( "layout" ) ).toMap();
if ( jsonLayout.value( QStringLiteral( "symbol-placement" ) ).toString() == QLatin1String( "line" ) && !jsonLayout.contains( QStringLiteral( "text-field" ) ) )
{
QgsPropertyCollection ddProperties;
double spacing = -1.0;
if ( jsonLayout.contains( QStringLiteral( "symbol-spacing" ) ) )
{
const QVariant jsonSpacing = jsonLayout.value( QStringLiteral( "symbol-spacing" ) );
switch ( jsonSpacing.type() )
{
case QVariant::Int:
case QVariant::Double:
spacing = jsonSpacing.toDouble() * context.pixelSizeConversionFactor();
break;
case QVariant::Map:
ddProperties.setProperty( QgsSymbolLayer::PropertyInterval, parseInterpolateByZoom( jsonSpacing.toMap(), context, context.pixelSizeConversionFactor(), &spacing ) );
break;
case QVariant::List:
case QVariant::StringList:
ddProperties.setProperty( QgsSymbolLayer::PropertyInterval, parseValueList( jsonSpacing.toList(), PropertyType::Numeric, context, context.pixelSizeConversionFactor(), 255, nullptr, &spacing ) );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported symbol-spacing type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonSpacing.type() ) ) );
break;
}
}
else
{
// defaults to 250
spacing = 250 * context.pixelSizeConversionFactor();
}
bool rotateMarkers = true;
if ( jsonLayout.contains( QStringLiteral( "icon-rotation-alignment" ) ) )
{
const QString alignment = jsonLayout.value( QStringLiteral( "icon-rotation-alignment" ) ).toString();
if ( alignment == QLatin1String( "map" ) || alignment == QLatin1String( "auto" ) )
{
rotateMarkers = true;
}
else if ( alignment == QLatin1String( "viewport" ) )
{
rotateMarkers = false;
}
}
QgsPropertyCollection markerDdProperties;
double rotation = 0.0;
if ( jsonLayout.contains( QStringLiteral( "icon-rotate" ) ) )
{
const QVariant jsonIconRotate = jsonLayout.value( QStringLiteral( "icon-rotate" ) );
switch ( jsonIconRotate.type() )
{
case QVariant::Int:
case QVariant::Double:
rotation = jsonIconRotate.toDouble();
break;
case QVariant::Map:
markerDdProperties.setProperty( QgsSymbolLayer::PropertyAngle, parseInterpolateByZoom( jsonIconRotate.toMap(), context, context.pixelSizeConversionFactor(), &rotation ) );
break;
case QVariant::List:
case QVariant::StringList:
markerDdProperties.setProperty( QgsSymbolLayer::PropertyAngle, parseValueList( jsonIconRotate.toList(), PropertyType::Numeric, context, context.pixelSizeConversionFactor(), 255, nullptr, &rotation ) );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported icon-rotate type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonIconRotate.type() ) ) );
break;
}
}
QgsMarkerLineSymbolLayer *lineSymbol = new QgsMarkerLineSymbolLayer( rotateMarkers, spacing > 0 ? spacing : 1 );
lineSymbol->setOutputUnit( context.targetUnit() );
lineSymbol->setDataDefinedProperties( ddProperties );
if ( spacing < 1 )
{
// if spacing isn't specified, it's a central point marker only
lineSymbol->setPlacement( QgsTemplatedLineSymbolLayerBase::CentralPoint );
}
QgsRasterMarkerSymbolLayer *markerLayer = new QgsRasterMarkerSymbolLayer( );
QSize spriteSize;
QString spriteProperty, spriteSizeProperty;
const QString sprite = retrieveSpriteAsBase64( jsonLayout.value( QStringLiteral( "icon-image" ) ), context, spriteSize, spriteProperty, spriteSizeProperty );
if ( !sprite.isNull() )
{
markerLayer->setPath( sprite );
markerLayer->setSize( spriteSize.width() );
markerLayer->setSizeUnit( context.targetUnit() );
if ( !spriteProperty.isEmpty() )
{
markerDdProperties.setProperty( QgsSymbolLayer::PropertyName, QgsProperty::fromExpression( spriteProperty ) );
markerDdProperties.setProperty( QgsSymbolLayer::PropertyWidth, QgsProperty::fromExpression( spriteSizeProperty ) );
}
}
if ( jsonLayout.contains( QStringLiteral( "icon-size" ) ) )
{
const QVariant jsonIconSize = jsonLayout.value( QStringLiteral( "icon-size" ) );
double size = 1.0;
QgsProperty property;
switch ( jsonIconSize.type() )
{
case QVariant::Int:
case QVariant::Double:
{
size = jsonIconSize.toDouble();
if ( !spriteSizeProperty.isEmpty() )
{
markerDdProperties.setProperty( QgsSymbolLayer::PropertyWidth,
QgsProperty::fromExpression( QStringLiteral( "with_variable('marker_size',%1,%2*@marker_size)" ).arg( spriteSizeProperty ).arg( size ) ) );
}
break;
}
case QVariant::Map:
property = parseInterpolateByZoom( jsonIconSize.toMap(), context, 1, &size );
break;
case QVariant::List:
case QVariant::StringList:
default:
context.pushWarning( QObject::tr( "%1: Skipping non-implemented icon-size type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonIconSize.type() ) ) );
break;
}
markerLayer->setSize( size * spriteSize.width() );
if ( !property.expressionString().isEmpty() )
{
if ( !spriteSizeProperty.isEmpty() )
{
markerDdProperties.setProperty( QgsSymbolLayer::PropertyWidth,
QgsProperty::fromExpression( QStringLiteral( "with_variable('marker_size',%1,(%2)*@marker_size)" ).arg( spriteSizeProperty ).arg( property.expressionString() ) ) );
}
else
{
markerDdProperties.setProperty( QgsSymbolLayer::PropertyWidth,
QgsProperty::fromExpression( QStringLiteral( "(%2)*%1" ).arg( spriteSize.width() ).arg( property.expressionString() ) ) );
}
}
}
markerLayer->setDataDefinedProperties( markerDdProperties );
markerLayer->setAngle( rotation );
lineSymbol->setSubSymbol( new QgsMarkerSymbol( QgsSymbolLayerList() << markerLayer ) );
std::unique_ptr< QgsSymbol > symbol = std::make_unique< QgsLineSymbol >( QgsSymbolLayerList() << lineSymbol );
// set render units
symbol->setOutputUnit( context.targetUnit() );
lineSymbol->setOutputUnit( context.targetUnit() );
rendererStyle.setGeometryType( QgsWkbTypes::LineGeometry );
rendererStyle.setSymbol( symbol.release() );
return true;
}
else if ( jsonLayout.contains( QStringLiteral( "icon-image" ) ) )
{
const QVariantMap jsonPaint = jsonLayer.value( QStringLiteral( "paint" ) ).toMap();
QSize spriteSize;
QString spriteProperty, spriteSizeProperty;
const QString sprite = retrieveSpriteAsBase64( jsonLayout.value( QStringLiteral( "icon-image" ) ), context, spriteSize, spriteProperty, spriteSizeProperty );
if ( !sprite.isEmpty() )
{
QgsRasterMarkerSymbolLayer *rasterMarker = new QgsRasterMarkerSymbolLayer( );
rasterMarker->setPath( sprite );
rasterMarker->setSize( spriteSize.width() );
rasterMarker->setSizeUnit( context.targetUnit() );
QgsPropertyCollection markerDdProperties;
if ( !spriteProperty.isEmpty() )
{
markerDdProperties.setProperty( QgsSymbolLayer::PropertyName, QgsProperty::fromExpression( spriteProperty ) );
markerDdProperties.setProperty( QgsSymbolLayer::PropertyWidth, QgsProperty::fromExpression( spriteSizeProperty ) );
}
if ( jsonLayout.contains( QStringLiteral( "icon-size" ) ) )
{
const QVariant jsonIconSize = jsonLayout.value( QStringLiteral( "icon-size" ) );
double size = 1.0;
QgsProperty property;
switch ( jsonIconSize.type() )
{
case QVariant::Int:
case QVariant::Double:
{
size = jsonIconSize.toDouble();
if ( !spriteSizeProperty.isEmpty() )
{
markerDdProperties.setProperty( QgsSymbolLayer::PropertyWidth,
QgsProperty::fromExpression( QStringLiteral( "with_variable('marker_size',%1,%2*@marker_size)" ).arg( spriteSizeProperty ).arg( size ) ) );
}
break;
}
case QVariant::Map:
property = parseInterpolateByZoom( jsonIconSize.toMap(), context, 1, &size );
break;
case QVariant::List:
case QVariant::StringList:
default:
context.pushWarning( QObject::tr( "%1: Skipping non-implemented icon-size type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonIconSize.type() ) ) );
break;
}
rasterMarker->setSize( size * spriteSize.width() );
if ( !property.expressionString().isEmpty() )
{
if ( !spriteSizeProperty.isEmpty() )
{
markerDdProperties.setProperty( QgsSymbolLayer::PropertyWidth,
QgsProperty::fromExpression( QStringLiteral( "with_variable('marker_size',%1,(%2)*@marker_size)" ).arg( spriteSizeProperty ).arg( property.expressionString() ) ) );
}
else
{
markerDdProperties.setProperty( QgsSymbolLayer::PropertyWidth,
QgsProperty::fromExpression( QStringLiteral( "(%2)*%1" ).arg( spriteSize.width() ).arg( property.expressionString() ) ) );
}
}
}
double rotation = 0.0;
if ( jsonLayout.contains( QStringLiteral( "icon-rotate" ) ) )
{
const QVariant jsonIconRotate = jsonLayout.value( QStringLiteral( "icon-rotate" ) );
switch ( jsonIconRotate.type() )
{
case QVariant::Int:
case QVariant::Double:
rotation = jsonIconRotate.toDouble();
break;
case QVariant::Map:
markerDdProperties.setProperty( QgsSymbolLayer::PropertyAngle, parseInterpolateByZoom( jsonIconRotate.toMap(), context, context.pixelSizeConversionFactor(), &rotation ) );
break;
case QVariant::List:
case QVariant::StringList:
markerDdProperties.setProperty( QgsSymbolLayer::PropertyAngle, parseValueList( jsonIconRotate.toList(), PropertyType::Numeric, context, context.pixelSizeConversionFactor(), 255, nullptr, &rotation ) );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported icon-rotate type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonIconRotate.type() ) ) );
break;
}
}
double iconOpacity = -1.0;
if ( jsonPaint.contains( QStringLiteral( "icon-opacity" ) ) )
{
const QVariant jsonIconOpacity = jsonPaint.value( QStringLiteral( "icon-opacity" ) );
switch ( jsonIconOpacity.type() )
{
case QVariant::Int:
case QVariant::Double:
iconOpacity = jsonIconOpacity.toDouble();
break;
case QVariant::Map:
markerDdProperties.setProperty( QgsSymbolLayer::PropertyOpacity, parseInterpolateByZoom( jsonIconOpacity.toMap(), context, 100, &iconOpacity ) );
break;
case QVariant::List:
case QVariant::StringList:
markerDdProperties.setProperty( QgsSymbolLayer::PropertyOpacity, parseValueList( jsonIconOpacity.toList(), PropertyType::Numeric, context, 100, 255, nullptr, &iconOpacity ) );
break;
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported icon-opacity type (%2)" ).arg( context.layerId(), QMetaType::typeName( jsonIconOpacity.type() ) ) );
break;
}
}
rasterMarker->setDataDefinedProperties( markerDdProperties );
rasterMarker->setAngle( rotation );
if ( iconOpacity >= 0 )
rasterMarker->setOpacity( iconOpacity );
QgsMarkerSymbol *markerSymbol = new QgsMarkerSymbol( QgsSymbolLayerList() << rasterMarker );
rendererStyle.setSymbol( markerSymbol );
rendererStyle.setGeometryType( QgsWkbTypes::PointGeometry );
return true;
}
}
return false;
}
QgsProperty QgsMapBoxGlStyleConverter::parseInterpolateColorByZoom( const QVariantMap &json, QgsMapBoxGlStyleConversionContext &context, QColor *defaultColor )
{
const double base = json.value( QStringLiteral( "base" ), QStringLiteral( "1" ) ).toDouble();
const QVariantList stops = json.value( QStringLiteral( "stops" ) ).toList();
if ( stops.empty() )
return QgsProperty();
QString caseString = QStringLiteral( "CASE " );
for ( int i = 0; i < stops.length() - 1; ++i )
{
// step bottom zoom
const QString bz = stops.at( i ).toList().value( 0 ).toString();
// step top zoom
const QString tz = stops.at( i + 1 ).toList().value( 0 ).toString();
const QColor bottomColor = parseColor( stops.at( i ).toList().value( 1 ), context );
const QColor topColor = parseColor( stops.at( i + 1 ).toList().value( 1 ), context );
int bcHue;
int bcSat;
int bcLight;
int bcAlpha;
colorAsHslaComponents( bottomColor, bcHue, bcSat, bcLight, bcAlpha );
int tcHue;
int tcSat;
int tcLight;
int tcAlpha;
colorAsHslaComponents( topColor, tcHue, tcSat, tcLight, tcAlpha );
caseString += QStringLiteral( "WHEN @vector_tile_zoom >= %1 AND @vector_tile_zoom < %2 THEN color_hsla("
"%3, %4, %5, %6) " ).arg( bz, tz,
interpolateExpression( bz.toDouble(), tz.toDouble(), bcHue, tcHue, base ),
interpolateExpression( bz.toDouble(), tz.toDouble(), bcSat, tcSat, base ),
interpolateExpression( bz.toDouble(), tz.toDouble(), bcLight, tcLight, base ),
interpolateExpression( bz.toDouble(), tz.toDouble(), bcAlpha, tcAlpha, base ) );
}
// top color
const QString tz = stops.last().toList().value( 0 ).toString();
const QColor topColor = parseColor( stops.last().toList().value( 1 ), context );
int tcHue;
int tcSat;
int tcLight;
int tcAlpha;
colorAsHslaComponents( topColor, tcHue, tcSat, tcLight, tcAlpha );
caseString += QStringLiteral( "WHEN @vector_tile_zoom >= %1 THEN color_hsla(%2, %3, %4, %5) "
"ELSE color_hsla(%2, %3, %4, %5) END" ).arg( tz )
.arg( tcHue ).arg( tcSat ).arg( tcLight ).arg( tcAlpha );
if ( !stops.empty() && defaultColor )
*defaultColor = parseColor( stops.value( 0 ).toList().value( 1 ).toString(), context );
return QgsProperty::fromExpression( caseString );
}
QgsProperty QgsMapBoxGlStyleConverter::parseInterpolateByZoom( const QVariantMap &json, QgsMapBoxGlStyleConversionContext &context, double multiplier, double *defaultNumber )
{
const double base = json.value( QStringLiteral( "base" ), QStringLiteral( "1" ) ).toDouble();
const QVariantList stops = json.value( QStringLiteral( "stops" ) ).toList();
if ( stops.empty() )
return QgsProperty();
QString scaleExpression;
if ( stops.size() <= 2 )
{
scaleExpression = interpolateExpression( stops.value( 0 ).toList().value( 0 ).toDouble(),
stops.last().toList().value( 0 ).toDouble(),
stops.value( 0 ).toList().value( 1 ).toDouble(),
stops.last().toList().value( 1 ).toDouble(), base, multiplier );
}
else
{
scaleExpression = parseStops( base, stops, multiplier, context );
}
if ( !stops.empty() && defaultNumber )
*defaultNumber = stops.value( 0 ).toList().value( 1 ).toDouble() * multiplier;
return QgsProperty::fromExpression( scaleExpression );
}
QgsProperty QgsMapBoxGlStyleConverter::parseInterpolateOpacityByZoom( const QVariantMap &json, int maxOpacity )
{
const double base = json.value( QStringLiteral( "base" ), QStringLiteral( "1" ) ).toDouble();
const QVariantList stops = json.value( QStringLiteral( "stops" ) ).toList();
if ( stops.empty() )
return QgsProperty();
QString scaleExpression;
if ( stops.length() <= 2 )
{
scaleExpression = QStringLiteral( "set_color_part(@symbol_color, 'alpha', %1)" )
.arg( interpolateExpression( stops.value( 0 ).toList().value( 0 ).toDouble(),
stops.last().toList().value( 0 ).toDouble(),
stops.value( 0 ).toList().value( 1 ).toDouble() * maxOpacity,
stops.last().toList().value( 1 ).toDouble() * maxOpacity, base ) );
}
else
{
scaleExpression = parseOpacityStops( base, stops, maxOpacity );
}
return QgsProperty::fromExpression( scaleExpression );
}
QString QgsMapBoxGlStyleConverter::parseOpacityStops( double base, const QVariantList &stops, int maxOpacity )
{
QString caseString = QStringLiteral( "CASE WHEN @vector_tile_zoom < %1 THEN set_color_part(@symbol_color, 'alpha', %2)" )
.arg( stops.value( 0 ).toList().value( 0 ).toString() )
.arg( stops.value( 0 ).toList().value( 1 ).toDouble() * maxOpacity );
for ( int i = 0; i < stops.size() - 1; ++i )
{
caseString += QStringLiteral( " WHEN @vector_tile_zoom >= %1 AND @vector_tile_zoom < %2 "
"THEN set_color_part(@symbol_color, 'alpha', %3)" )
.arg( stops.value( i ).toList().value( 0 ).toString(),
stops.value( i + 1 ).toList().value( 0 ).toString(),
interpolateExpression( stops.value( i ).toList().value( 0 ).toDouble(),
stops.value( i + 1 ).toList().value( 0 ).toDouble(),
stops.value( i ).toList().value( 1 ).toDouble() * maxOpacity,
stops.value( i + 1 ).toList().value( 1 ).toDouble() * maxOpacity, base ) );
}
caseString += QStringLiteral( " WHEN @vector_tile_zoom >= %1 "
"THEN set_color_part(@symbol_color, 'alpha', %2) END" )
.arg( stops.last().toList().value( 0 ).toString() )
.arg( stops.last().toList().value( 1 ).toDouble() * maxOpacity );
return caseString;
}
QgsProperty QgsMapBoxGlStyleConverter::parseInterpolatePointByZoom( const QVariantMap &json, QgsMapBoxGlStyleConversionContext &context, double multiplier, QPointF *defaultPoint )
{
const double base = json.value( QStringLiteral( "base" ), QStringLiteral( "1" ) ).toDouble();
const QVariantList stops = json.value( QStringLiteral( "stops" ) ).toList();
if ( stops.empty() )
return QgsProperty();
QString scaleExpression;
if ( stops.size() <= 2 )
{
scaleExpression = QStringLiteral( "array(%1,%2)" ).arg( interpolateExpression( stops.value( 0 ).toList().value( 0 ).toDouble(),
stops.last().toList().value( 0 ).toDouble(),
stops.value( 0 ).toList().value( 1 ).toList().value( 0 ).toDouble(),
stops.last().toList().value( 1 ).toList().value( 0 ).toDouble(), base, multiplier ),
interpolateExpression( stops.value( 0 ).toList().value( 0 ).toDouble(),
stops.last().toList().value( 0 ).toDouble(),
stops.value( 0 ).toList().value( 1 ).toList().value( 1 ).toDouble(),
stops.last().toList().value( 1 ).toList().value( 1 ).toDouble(), base, multiplier )
);
}
else
{
scaleExpression = parsePointStops( base, stops, context, multiplier );
}
if ( !stops.empty() && defaultPoint )
*defaultPoint = QPointF( stops.value( 0 ).toList().value( 1 ).toList().value( 0 ).toDouble() * multiplier,
stops.value( 0 ).toList().value( 1 ).toList().value( 1 ).toDouble() * multiplier );
return QgsProperty::fromExpression( scaleExpression );
}
QgsProperty QgsMapBoxGlStyleConverter::parseInterpolateStringByZoom( const QVariantMap &json, QgsMapBoxGlStyleConversionContext &context,
const QVariantMap &conversionMap, QString *defaultString )
{
const QVariantList stops = json.value( QStringLiteral( "stops" ) ).toList();
if ( stops.empty() )
return QgsProperty();
QString scaleExpression = parseStringStops( stops, context, conversionMap, defaultString );
return QgsProperty::fromExpression( scaleExpression );
}
QString QgsMapBoxGlStyleConverter::parsePointStops( double base, const QVariantList &stops, QgsMapBoxGlStyleConversionContext &context, double multiplier )
{
QString caseString = QStringLiteral( "CASE " );
for ( int i = 0; i < stops.length() - 1; ++i )
{
// bottom zoom and value
const QVariant bz = stops.value( i ).toList().value( 0 );
const QVariant bv = stops.value( i ).toList().value( 1 );
if ( bv.type() != QVariant::List && bv.type() != QVariant::StringList )
{
context.pushWarning( QObject::tr( "%1: Skipping unsupported offset interpolation type (%2)." ).arg( context.layerId(), QMetaType::typeName( bz.type() ) ) );
return QString();
}
// top zoom and value
const QVariant tz = stops.value( i + 1 ).toList().value( 0 );
const QVariant tv = stops.value( i + 1 ).toList().value( 1 );
if ( tv.type() != QVariant::List && tv.type() != QVariant::StringList )
{
context.pushWarning( QObject::tr( "%1: Skipping unsupported offset interpolation type (%2)." ).arg( context.layerId(), QMetaType::typeName( tz.type() ) ) );
return QString();
}
caseString += QStringLiteral( "WHEN @vector_tile_zoom > %1 AND @vector_tile_zoom <= %2 "
"THEN array(%3,%4)" ).arg( bz.toString(),
tz.toString(),
interpolateExpression( bz.toDouble(), tz.toDouble(), bv.toList().value( 0 ).toDouble(), tv.toList().value( 0 ).toDouble(), base, multiplier ),
interpolateExpression( bz.toDouble(), tz.toDouble(), bv.toList().value( 1 ).toDouble(), tv.toList().value( 1 ).toDouble(), base, multiplier ) );
}
caseString += QLatin1String( "END" );
return caseString;
}
QString QgsMapBoxGlStyleConverter::parseStops( double base, const QVariantList &stops, double multiplier, QgsMapBoxGlStyleConversionContext &context )
{
QString caseString = QStringLiteral( "CASE " );
for ( int i = 0; i < stops.length() - 1; ++i )
{
// bottom zoom and value
const QVariant bz = stops.value( i ).toList().value( 0 );
const QVariant bv = stops.value( i ).toList().value( 1 );
if ( bz.type() == QVariant::List || bz.type() == QVariant::StringList )
{
context.pushWarning( QObject::tr( "%1: Expressions in interpolation function are not supported, skipping." ).arg( context.layerId() ) );
return QString();
}
// top zoom and value
const QVariant tz = stops.value( i + 1 ).toList().value( 0 );
const QVariant tv = stops.value( i + 1 ).toList().value( 1 );
if ( tz.type() == QVariant::List || tz.type() == QVariant::StringList )
{
context.pushWarning( QObject::tr( "%1: Expressions in interpolation function are not supported, skipping." ).arg( context.layerId() ) );
return QString();
}
caseString += QStringLiteral( "WHEN @vector_tile_zoom > %1 AND @vector_tile_zoom <= %2 "
"THEN %3 " ).arg( bz.toString(),
tz.toString(),
interpolateExpression( bz.toDouble(), tz.toDouble(), bv.toDouble(), tv.toDouble(), base, multiplier ) );
}
const QVariant z = stops.last().toList().value( 0 );
const QVariant v = stops.last().toList().value( 1 );
caseString += QStringLiteral( "WHEN @vector_tile_zoom > %1 "
"THEN %2 END" ).arg( z.toString() ).arg( v.toDouble() * multiplier );
return caseString;
}
QString QgsMapBoxGlStyleConverter::parseStringStops( const QVariantList &stops, QgsMapBoxGlStyleConversionContext &context, const QVariantMap &conversionMap, QString *defaultString )
{
QString caseString = QStringLiteral( "CASE " );
for ( int i = 0; i < stops.length() - 1; ++i )
{
// bottom zoom and value
const QVariant bz = stops.value( i ).toList().value( 0 );
const QString bv = stops.value( i ).toList().value( 1 ).toString();
if ( bz.type() == QVariant::List || bz.type() == QVariant::StringList )
{
context.pushWarning( QObject::tr( "%1: Expressions in interpolation function are not supported, skipping." ).arg( context.layerId() ) );
return QString();
}
// top zoom
const QVariant tz = stops.value( i + 1 ).toList().value( 0 );
if ( tz.type() == QVariant::List || tz.type() == QVariant::StringList )
{
context.pushWarning( QObject::tr( "%1: Expressions in interpolation function are not supported, skipping." ).arg( context.layerId() ) );
return QString();
}
caseString += QStringLiteral( "WHEN @vector_tile_zoom > %1 AND @vector_tile_zoom <= %2 "
"THEN %3 " ).arg( bz.toString(),
tz.toString(),
QgsExpression::quotedValue( conversionMap.value( bv, bv ) ) );
}
caseString += QStringLiteral( "ELSE %1 END" ).arg( QgsExpression::quotedValue( conversionMap.value( stops.constLast().toList().value( 1 ).toString(),
stops.constLast().toList().value( 1 ) ) ) );
if ( defaultString )
*defaultString = stops.constLast().toList().value( 1 ).toString();
return caseString;
}
QgsProperty QgsMapBoxGlStyleConverter::parseValueList( const QVariantList &json, QgsMapBoxGlStyleConverter::PropertyType type, QgsMapBoxGlStyleConversionContext &context, double multiplier, int maxOpacity, QColor *defaultColor, double *defaultNumber )
{
const QString method = json.value( 0 ).toString();
if ( method == QLatin1String( "interpolate" ) )
{
return parseInterpolateListByZoom( json, type, context, multiplier, maxOpacity, defaultColor, defaultNumber );
}
else if ( method == QLatin1String( "match" ) )
{
return parseMatchList( json, type, context, multiplier, maxOpacity, defaultColor, defaultNumber );
}
else
{
context.pushWarning( QObject::tr( "%1: Could not interpret value list with method %2" ).arg( context.layerId(), method ) );
return QgsProperty();
}
}
QgsProperty QgsMapBoxGlStyleConverter::parseMatchList( const QVariantList &json, QgsMapBoxGlStyleConverter::PropertyType type, QgsMapBoxGlStyleConversionContext &context, double multiplier, int maxOpacity, QColor *defaultColor, double *defaultNumber )
{
const QString attribute = parseExpression( json.value( 1 ).toList(), context );
if ( attribute.isEmpty() )
{
context.pushWarning( QObject::tr( "%1: Could not interpret match list" ).arg( context.layerId() ) );
return QgsProperty();
}
QString caseString = QStringLiteral( "CASE " );
for ( int i = 2; i < json.length() - 1; i += 2 )
{
const QVariantList keys = json.value( i ).toList();
QStringList matchString;
for ( const QVariant &key : keys )
{
matchString << QgsExpression::quotedValue( key );
}
const QVariant value = json.value( i + 1 );
QString valueString;
switch ( type )
{
case Color:
{
const QColor color = parseColor( value, context );
valueString = QgsExpression::quotedString( color.name() );
break;
}
case Numeric:
{
const double v = value.toDouble() * multiplier;
valueString = QString::number( v );
break;
}
case Opacity:
{
const double v = value.toDouble() * maxOpacity;
valueString = QString::number( v );
break;
}
case Point:
{
valueString = QStringLiteral( "array(%1,%2)" ).arg( value.toList().value( 0 ).toDouble() * multiplier,
value.toList().value( 0 ).toDouble() * multiplier );
break;
}
}
caseString += QStringLiteral( "WHEN %1 IN (%2) THEN %3 " ).arg( attribute,
matchString.join( ',' ), valueString );
}
QString elseValue;
switch ( type )
{
case Color:
{
const QColor color = parseColor( json.constLast(), context );
if ( defaultColor )
*defaultColor = color;
elseValue = QgsExpression::quotedString( color.name() );
break;
}
case Numeric:
{
const double v = json.constLast().toDouble() * multiplier;
if ( defaultNumber )
*defaultNumber = v;
elseValue = QString::number( v );
break;
}
case Opacity:
{
const double v = json.constLast().toDouble() * maxOpacity;
if ( defaultNumber )
*defaultNumber = v;
elseValue = QString::number( v );
break;
}
case Point:
{
elseValue = QStringLiteral( "array(%1,%2)" ).arg( json.constLast().toList().value( 0 ).toDouble() * multiplier,
json.constLast().toList().value( 0 ).toDouble() * multiplier );
break;
}
}
caseString += QStringLiteral( "ELSE %1 END" ).arg( elseValue );
return QgsProperty::fromExpression( caseString );
}
QgsProperty QgsMapBoxGlStyleConverter::parseInterpolateListByZoom( const QVariantList &json, PropertyType type, QgsMapBoxGlStyleConversionContext &context, double multiplier, int maxOpacity, QColor *defaultColor, double *defaultNumber )
{
if ( json.value( 0 ).toString() != QLatin1String( "interpolate" ) )
{
context.pushWarning( QObject::tr( "%1: Could not interpret value list" ).arg( context.layerId() ) );
return QgsProperty();
}
double base = 1;
const QString technique = json.value( 1 ).toList().value( 0 ).toString();
if ( technique == QLatin1String( "linear" ) )
base = 1;
else if ( technique == QLatin1String( "exponential" ) )
base = json.value( 1 ).toList(). value( 1 ).toDouble();
else if ( technique == QLatin1String( "cubic-bezier" ) )
{
context.pushWarning( QObject::tr( "%1: Cubic-bezier interpolation is not supported, linear used instead." ).arg( context.layerId() ) );
base = 1;
}
else
{
context.pushWarning( QObject::tr( "%1: Skipping not implemented interpolation method %2" ).arg( context.layerId(), technique ) );
return QgsProperty();
}
if ( json.value( 2 ).toList().value( 0 ).toString() != QLatin1String( "zoom" ) )
{
context.pushWarning( QObject::tr( "%1: Skipping not implemented interpolation input %2" ).arg( context.layerId(), json.value( 2 ).toString() ) );
return QgsProperty();
}
// Convert stops into list of lists
QVariantList stops;
for ( int i = 3; i < json.length(); i += 2 )
{
stops.push_back( QVariantList() << json.value( i ).toString() << json.value( i + 1 ).toString() );
}
QVariantMap props;
props.insert( QStringLiteral( "stops" ), stops );
props.insert( QStringLiteral( "base" ), base );
switch ( type )
{
case PropertyType::Color:
return parseInterpolateColorByZoom( props, context, defaultColor );
case PropertyType::Numeric:
return parseInterpolateByZoom( props, context, multiplier, defaultNumber );
case PropertyType::Opacity:
return parseInterpolateOpacityByZoom( props, maxOpacity );
case PropertyType::Point:
return parseInterpolatePointByZoom( props, context, multiplier );
}
return QgsProperty();
}
QColor QgsMapBoxGlStyleConverter::parseColor( const QVariant &color, QgsMapBoxGlStyleConversionContext &context )
{
if ( color.type() != QVariant::String )
{
context.pushWarning( QObject::tr( "%1: Could not parse non-string color %2, skipping" ).arg( context.layerId(), color.toString() ) );
return QColor();
}
return QgsSymbolLayerUtils::parseColor( color.toString() );
}
void QgsMapBoxGlStyleConverter::colorAsHslaComponents( const QColor &color, int &hue, int &saturation, int &lightness, int &alpha )
{
hue = std::max( 0, color.hslHue() );
saturation = color.hslSaturation() / 255.0 * 100;
lightness = color.lightness() / 255.0 * 100;
alpha = color.alpha();
}
QString QgsMapBoxGlStyleConverter::interpolateExpression( double zoomMin, double zoomMax, double valueMin, double valueMax, double base, double multiplier )
{
// special case!
if ( qgsDoubleNear( valueMin, valueMax ) )
return QString::number( valueMin * multiplier );
QString expression;
if ( base == 1 )
{
expression = QStringLiteral( "scale_linear(@vector_tile_zoom,%1,%2,%3,%4)" ).arg( zoomMin )
.arg( zoomMax )
.arg( valueMin )
.arg( valueMax );
}
else
{
expression = QStringLiteral( "scale_exp(@vector_tile_zoom,%1,%2,%3,%4,%5)" ).arg( zoomMin )
.arg( zoomMax )
.arg( valueMin )
.arg( valueMax )
.arg( base );
}
if ( multiplier != 1 )
return QStringLiteral( "%1 * %2" ).arg( expression ).arg( multiplier );
else
return expression;
}
Qt::PenCapStyle QgsMapBoxGlStyleConverter::parseCapStyle( const QString &style )
{
if ( style == QLatin1String( "round" ) )
return Qt::RoundCap;
else if ( style == QLatin1String( "square" ) )
return Qt::SquareCap;
else
return Qt::FlatCap; // "butt" is default
}
Qt::PenJoinStyle QgsMapBoxGlStyleConverter::parseJoinStyle( const QString &style )
{
if ( style == QLatin1String( "bevel" ) )
return Qt::BevelJoin;
else if ( style == QLatin1String( "round" ) )
return Qt::RoundJoin;
else
return Qt::MiterJoin; // "miter" is default
}
QString QgsMapBoxGlStyleConverter::parseExpression( const QVariantList &expression, QgsMapBoxGlStyleConversionContext &context )
{
QString op = expression.value( 0 ).toString();
if ( op == QLatin1String( "all" )
|| op == QLatin1String( "any" )
|| op == QLatin1String( "none" ) )
{
QStringList parts;
for ( int i = 1; i < expression.size(); ++i )
{
QString part = parseValue( expression.at( i ), context );
if ( part.isEmpty() )
{
context.pushWarning( QObject::tr( "%1: Skipping unsupported expression" ).arg( context.layerId() ) );
return QString();
}
parts << part;
}
if ( op == QLatin1String( "none" ) )
return QStringLiteral( "NOT (%1)" ).arg( parts.join( QLatin1String( ") AND NOT (" ) ) );
QString operatorString;
if ( op == QLatin1String( "all" ) )
operatorString = QStringLiteral( ") AND (" );
else if ( op == QLatin1String( "any" ) )
operatorString = QStringLiteral( ") OR (" );
return QStringLiteral( "(%1)" ).arg( parts.join( operatorString ) );
}
else if ( op == '!' )
{
// ! inverts next expression's meaning
QVariantList contraJsonExpr = expression.value( 1 ).toList();
contraJsonExpr[0] = QString( op + contraJsonExpr[0].toString() );
// ['!', ['has', 'level']] -> ['!has', 'level']
return parseKey( contraJsonExpr );
}
else if ( op == QLatin1String( "==" )
|| op == QLatin1String( "!=" )
|| op == QLatin1String( ">=" )
|| op == '>'
|| op == QLatin1String( "<=" )
|| op == '<' )
{
// use IS and NOT IS instead of = and != because they can deal with NULL values
if ( op == QLatin1String( "==" ) )
op = QStringLiteral( "IS" );
else if ( op == QLatin1String( "!=" ) )
op = QStringLiteral( "IS NOT" );
return QStringLiteral( "%1 %2 %3" ).arg( parseKey( expression.value( 1 ) ),
op, parseValue( expression.value( 2 ), context ) );
}
else if ( op == QLatin1String( "has" ) )
{
return parseKey( expression.value( 1 ) ) + QStringLiteral( " IS NOT NULL" );
}
else if ( op == QLatin1String( "!has" ) )
{
return parseKey( expression.value( 1 ) ) + QStringLiteral( " IS NULL" );
}
else if ( op == QLatin1String( "in" ) || op == QLatin1String( "!in" ) )
{
const QString key = parseKey( expression.value( 1 ) );
QStringList parts;
for ( int i = 2; i < expression.size(); ++i )
{
QString part = parseValue( expression.at( i ), context );
if ( part.isEmpty() )
{
context.pushWarning( QObject::tr( "%1: Skipping unsupported expression" ).arg( context.layerId() ) );
return QString();
}
parts << part;
}
if ( op == QLatin1String( "in" ) )
return QStringLiteral( "%1 IN (%2)" ).arg( key, parts.join( QLatin1String( ", " ) ) );
else
return QStringLiteral( "(%1 IS NULL OR %1 NOT IN (%2))" ).arg( key, parts.join( QLatin1String( ", " ) ) );
}
else if ( op == QLatin1String( "get" ) )
{
return parseKey( expression.value( 1 ) );
}
else if ( op == QLatin1String( "match" ) )
{
const QString attribute = expression.value( 1 ).toList().value( 1 ).toString();
if ( expression.size() == 5
&& expression.at( 3 ).type() == QVariant::Bool && expression.at( 3 ).toBool() == true
&& expression.at( 4 ).type() == QVariant::Bool && expression.at( 4 ).toBool() == false )
{
// simple case, make a nice simple expression instead of a CASE statement
if ( expression.at( 2 ).type() == QVariant::List || expression.at( 2 ).type() == QVariant::StringList )
{
QStringList parts;
for ( const QVariant &p : expression.at( 2 ).toList() )
{
parts << QgsExpression::quotedValue( p );
}
if ( parts.size() > 1 )
return QStringLiteral( "%1 IN (%2)" ).arg( QgsExpression::quotedColumnRef( attribute ), parts.join( ", " ) );
else
return QgsExpression::createFieldEqualityExpression( attribute, expression.at( 2 ).toList().value( 0 ) );
}
else if ( expression.at( 2 ).type() == QVariant::String || expression.at( 2 ).type() == QVariant::Int
|| expression.at( 2 ).type() == QVariant::Double )
{
return QgsExpression::createFieldEqualityExpression( attribute, expression.at( 2 ) );
}
else
{
context.pushWarning( QObject::tr( "%1: Skipping unsupported expression" ).arg( context.layerId() ) );
return QString();
}
}
else
{
QString caseString = QStringLiteral( "CASE " );
for ( int i = 2; i < expression.size() - 2; i += 2 )
{
if ( expression.at( i ).type() == QVariant::List || expression.at( i ).type() == QVariant::StringList )
{
QStringList parts;
for ( const QVariant &p : expression.at( i ).toList() )
{
parts << QgsExpression::quotedValue( p );
}
if ( parts.size() > 1 )
caseString += QStringLiteral( "WHEN %1 IN (%2) " ).arg( QgsExpression::quotedColumnRef( attribute ), parts.join( ", " ) );
else
caseString += QStringLiteral( "WHEN %1 " ).arg( QgsExpression::createFieldEqualityExpression( attribute, expression.at( i ).toList().value( 0 ) ) );
}
else if ( expression.at( i ).type() == QVariant::String || expression.at( i ).type() == QVariant::Int
|| expression.at( i ).type() == QVariant::Double )
{
caseString += QStringLiteral( "WHEN (%1) " ).arg( QgsExpression::createFieldEqualityExpression( attribute, expression.at( i ) ) );
}
caseString += QStringLiteral( "THEN %1 " ).arg( QgsExpression::quotedValue( expression.at( i + 1 ) ) );
}
caseString += QStringLiteral( "ELSE %1 END" ).arg( QgsExpression::quotedValue( expression.last() ) );
return caseString;
}
}
else if ( op == QLatin1String( "to-string" ) )
{
return QStringLiteral( "to_string(%1)" ).arg( parseExpression( expression.value( 1 ).toList(), context ) );
}
else
{
context.pushWarning( QObject::tr( "%1: Skipping unsupported expression" ).arg( context.layerId() ) );
return QString();
}
}
QImage QgsMapBoxGlStyleConverter::retrieveSprite( const QString &name, QgsMapBoxGlStyleConversionContext &context, QSize &spriteSize )
{
if ( context.spriteImage().isNull() )
{
context.pushWarning( QObject::tr( "%1: Could not retrieve sprite '%2'" ).arg( context.layerId(), name ) );
return QImage();
}
const QVariantMap spriteDefinition = context.spriteDefinitions().value( name ).toMap();
if ( spriteDefinition.size() == 0 )
{
context.pushWarning( QObject::tr( "%1: Could not retrieve sprite '%2'" ).arg( context.layerId(), name ) );
return QImage();
}
const QImage sprite = context.spriteImage().copy( spriteDefinition.value( QStringLiteral( "x" ) ).toInt(),
spriteDefinition.value( QStringLiteral( "y" ) ).toInt(),
spriteDefinition.value( QStringLiteral( "width" ) ).toInt(),
spriteDefinition.value( QStringLiteral( "height" ) ).toInt() );
if ( sprite.isNull() )
{
context.pushWarning( QObject::tr( "%1: Could not retrieve sprite '%2'" ).arg( context.layerId(), name ) );
return QImage();
}
spriteSize = sprite.size() / spriteDefinition.value( QStringLiteral( "pixelRatio" ) ).toDouble() * context.pixelSizeConversionFactor();
return sprite;
}
QString QgsMapBoxGlStyleConverter::retrieveSpriteAsBase64( const QVariant &value, QgsMapBoxGlStyleConversionContext &context, QSize &spriteSize, QString &spriteProperty, QString &spriteSizeProperty )
{
QString spritePath;
auto prepareBase64 = []( const QImage & sprite )
{
QString path;
if ( !sprite.isNull() )
{
QByteArray blob;
QBuffer buffer( &blob );
buffer.open( QIODevice::WriteOnly );
sprite.save( &buffer, "PNG" );
buffer.close();
QByteArray encoded = blob.toBase64();
path = QString( encoded );
path.prepend( QLatin1String( "base64:" ) );
}
return path;
};
switch ( value.type() )
{
case QVariant::String:
{
QString spriteName = value.toString();
QRegularExpression fieldNameMatch( QStringLiteral( "{([^}]+)}" ) );
QRegularExpressionMatch match = fieldNameMatch.match( spriteName );
if ( match.hasMatch() )
{
const QString fieldName = match.captured( 1 );
spriteProperty = QStringLiteral( "CASE" );
spriteSizeProperty = QStringLiteral( "CASE" );
spriteName.replace( "(", QLatin1String( "\\(" ) );
spriteName.replace( ")", QLatin1String( "\\)" ) );
spriteName.replace( fieldNameMatch, QStringLiteral( "([^\\/\\\\]+)" ) );
QRegularExpression fieldValueMatch( spriteName );
const QStringList spriteNames = context.spriteDefinitions().keys();
for ( const QString &name : spriteNames )
{
match = fieldValueMatch.match( name );
if ( match.hasMatch() )
{
QSize size;
QString path;
const QString fieldValue = match.captured( 1 );
const QImage sprite = retrieveSprite( name, context, size );
path = prepareBase64( sprite );
if ( spritePath.isEmpty() && !path.isEmpty() )
{
spritePath = path;
spriteSize = size;
}
spriteProperty += QStringLiteral( " WHEN \"%1\" = '%2' THEN '%3'" )
.arg( fieldName, fieldValue, path );
spriteSizeProperty += QStringLiteral( " WHEN \"%1\" = '%2' THEN %3" )
.arg( fieldName ).arg( fieldValue ).arg( size.width() );
}
}
spriteProperty += QLatin1String( " END" );
spriteSizeProperty += QLatin1String( " END" );
}
else
{
spriteProperty.clear();
spriteSizeProperty.clear();
const QImage sprite = retrieveSprite( spriteName, context, spriteSize );
spritePath = prepareBase64( sprite );
}
break;
}
case QVariant::Map:
{
const QVariantList stops = value.toMap().value( QStringLiteral( "stops" ) ).toList();
if ( stops.size() == 0 )
break;
QString path;
QSize size;
QImage sprite;
sprite = retrieveSprite( stops.value( 0 ).toList().value( 1 ).toString(), context, spriteSize );
spritePath = prepareBase64( sprite );
spriteProperty = QStringLiteral( "CASE WHEN @vector_tile_zoom < %1 THEN '%2'" )
.arg( stops.value( 0 ).toList().value( 0 ).toString() )
.arg( spritePath );
spriteSizeProperty = QStringLiteral( "CASE WHEN @vector_tile_zoom < %1 THEN %2" )
.arg( stops.value( 0 ).toList().value( 0 ).toString() )
.arg( spriteSize.width() );
for ( int i = 0; i < stops.size() - 1; ++i )
{
;
sprite = retrieveSprite( stops.value( 0 ).toList().value( 1 ).toString(), context, size );
path = prepareBase64( sprite );
spriteProperty += QStringLiteral( " WHEN @vector_tile_zoom >= %1 AND @vector_tile_zoom < %2 "
"THEN '%3'" )
.arg( stops.value( i ).toList().value( 0 ).toString(),
stops.value( i + 1 ).toList().value( 0 ).toString(),
path );
spriteSizeProperty += QStringLiteral( " WHEN @vector_tile_zoom >= %1 AND @vector_tile_zoom < %2 "
"THEN %3" )
.arg( stops.value( i ).toList().value( 0 ).toString(),
stops.value( i + 1 ).toList().value( 0 ).toString() )
.arg( size.width() );
}
sprite = retrieveSprite( stops.last().toList().value( 1 ).toString(), context, size );
path = prepareBase64( sprite );
spriteProperty += QStringLiteral( " WHEN @vector_tile_zoom >= %1 "
"THEN '%2' END" )
.arg( stops.last().toList().value( 0 ).toString() )
.arg( path );
spriteSizeProperty += QStringLiteral( " WHEN @vector_tile_zoom >= %1 "
"THEN %2 END" )
.arg( stops.last().toList().value( 0 ).toString() )
.arg( size.width() );
break;
}
case QVariant::List:
{
const QVariantList json = value.toList();
const QString method = json.value( 0 ).toString();
if ( method != QLatin1String( "match" ) )
{
context.pushWarning( QObject::tr( "%1: Could not interpret sprite value list with method %2" ).arg( context.layerId(), method ) );
break;
}
const QString attribute = parseExpression( json.value( 1 ).toList(), context );
if ( attribute.isEmpty() )
{
context.pushWarning( QObject::tr( "%1: Could not interpret match list" ).arg( context.layerId() ) );
break;
}
spriteProperty = QStringLiteral( "CASE " );
spriteSizeProperty = QStringLiteral( "CASE " );
for ( int i = 2; i < json.length() - 1; i += 2 )
{
const QVariantList keys = json.value( i ).toList();
QStringList matchString;
for ( const QVariant &key : keys )
{
matchString << QgsExpression::quotedValue( key );
}
const QVariant value = json.value( i + 1 );
const QImage sprite = retrieveSprite( value.toString(), context, spriteSize );
spritePath = prepareBase64( sprite );
spriteProperty += QStringLiteral( " WHEN %1 IN (%2) "
"THEN '%3' " ).arg( attribute,
matchString.join( ',' ),
spritePath );
spriteSizeProperty += QStringLiteral( " WHEN %1 IN (%2) "
"THEN %3 " ).arg( attribute,
matchString.join( ',' ) ).arg( spriteSize.width() );
}
const QImage sprite = retrieveSprite( json.constLast().toString(), context, spriteSize );
spritePath = prepareBase64( sprite );
spriteProperty += QStringLiteral( "ELSE %1 END" ).arg( spritePath );
spriteSizeProperty += QStringLiteral( "ELSE %3 END" ).arg( spriteSize.width() );
break;
}
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported sprite type (%2)." ).arg( context.layerId(), QMetaType::typeName( value.type() ) ) );
break;
}
return spritePath;
}
QString QgsMapBoxGlStyleConverter::parseValue( const QVariant &value, QgsMapBoxGlStyleConversionContext &context )
{
switch ( value.type() )
{
case QVariant::List:
case QVariant::StringList:
return parseExpression( value.toList(), context );
case QVariant::String:
return QgsExpression::quotedValue( value.toString() );
case QVariant::Int:
case QVariant::Double:
return value.toString();
default:
context.pushWarning( QObject::tr( "%1: Skipping unsupported expression part" ).arg( context.layerId() ) );
break;
}
return QString();
}
QString QgsMapBoxGlStyleConverter::parseKey( const QVariant &value )
{
if ( value.toString() == QLatin1String( "$type" ) )
return QStringLiteral( "_geom_type" );
else if ( value.type() == QVariant::List || value.type() == QVariant::StringList )
{
if ( value.toList().size() > 1 )
return value.toList().at( 1 ).toString();
else
return value.toList().value( 0 ).toString();
}
return QgsExpression::quotedColumnRef( value.toString() );
}
QgsVectorTileRenderer *QgsMapBoxGlStyleConverter::renderer() const
{
return mRenderer ? mRenderer->clone() : nullptr;
}
QgsVectorTileLabeling *QgsMapBoxGlStyleConverter::labeling() const
{
return mLabeling ? mLabeling->clone() : nullptr;
}
//
// QgsMapBoxGlStyleConversionContext
//
void QgsMapBoxGlStyleConversionContext::pushWarning( const QString &warning )
{
QgsDebugMsg( warning );
mWarnings << warning;
}
QgsUnitTypes::RenderUnit QgsMapBoxGlStyleConversionContext::targetUnit() const
{
return mTargetUnit;
}
void QgsMapBoxGlStyleConversionContext::setTargetUnit( QgsUnitTypes::RenderUnit targetUnit )
{
mTargetUnit = targetUnit;
}
double QgsMapBoxGlStyleConversionContext::pixelSizeConversionFactor() const
{
return mSizeConversionFactor;
}
void QgsMapBoxGlStyleConversionContext::setPixelSizeConversionFactor( double sizeConversionFactor )
{
mSizeConversionFactor = sizeConversionFactor;
}
QImage QgsMapBoxGlStyleConversionContext::spriteImage() const
{
return mSpriteImage;
}
QVariantMap QgsMapBoxGlStyleConversionContext::spriteDefinitions() const
{
return mSpriteDefinitions;
}
void QgsMapBoxGlStyleConversionContext::setSprites( const QImage &image, const QVariantMap &definitions )
{
mSpriteImage = image;
mSpriteDefinitions = definitions;
}
void QgsMapBoxGlStyleConversionContext::setSprites( const QImage &image, const QString &definitions )
{
setSprites( image, QgsJsonUtils::parseJson( definitions ).toMap() );
}
QString QgsMapBoxGlStyleConversionContext::layerId() const
{
return mLayerId;
}
void QgsMapBoxGlStyleConversionContext::setLayerId( const QString &value )
{
mLayerId = value;
}
|
JamesShaeffer/QGIS
|
src/core/vectortile/qgsmapboxglstyleconverter.cpp
|
C++
|
gpl-2.0
| 118,139
|
/*
* Copyright (C) 2008 - 2011 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2011 - 2012 ArkCORE <http://www.arkania.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, see <http://www.gnu.org/licenses/>.
*/
#include "Group.h"
#include "GroupReference.h"
void GroupReference::targetObjectBuildLink()
{
// called from link()
getTarget()->LinkMember(this);
}
void GroupReference::targetObjectDestroyLink()
{
// called from unlink()
//getTarget()->DelinkMember(this);
}
void GroupReference::sourceObjectDestroyLink()
{
// called from invalidate()
//getTarget()->DelinkMember(this);
}
|
avalonfr/ArkCORE-4.3.4
|
src/server/game/Groups/GroupReference.cpp
|
C++
|
gpl-2.0
| 1,190
|
<?php
/*----------------------------------------------------------------------
# R3D Floater Module 1.5.1.1 for Joomla 1.5
# ----------------------------------------------------------------------
# Copyright (C) 2009 R3D Internet Dienstleistungen. All Rights Reserved.
# Coded by: r3d & a3g
# Copyright: GNU/GPL
# Website: http://www.r3d.de
------------------------------------------------------------------------*/
defined('_JEXEC') or die('Restricted access');
/////////////////////////////// PARAMS //////////////////////////////////
$module_name = $params->get( 'module_name', 'newsflash' );
$module_title = $params->get( 'module_title', 'Floater Newsflash' );
$direction = 'left';
$initdir = 'slideDR';
$timeout = $params->get( 'timeout', '10000' );
$oncepersession = $params->get( 'oncepersession', 'false' );
// Box Parameters
$boxwidth = $params->get( 'boxwidth', '300px' );
$boxheight = $params->get( 'boxheight', '300px' );
$boxleft = $params->get( 'boxleft', '-400px' );
$boxtop = $params->get( 'boxtop', '190px' );
$bgcolor = $params->get( 'bgcolor', '#f5f5f5' );
$border = $params->get( 'border', '7px solid #135CAE' );
$opacity = $params->get( 'opacity', '90' );
$talign = $params->get( 'talign', 'right' );
// inside positions
$iwidth = $params->get( 'iwidth', '270px' );
$iheight = $params->get( 'iheight', '250px' );
$ileft = $params->get( 'ileft', '10px' );
$itop = $params->get( 'itop', '0px' );
$ibgcolor = $params->get( 'ibgcolor', 'transparent' );
$iborder = $params->get( 'iborder', 'none' );
$italign = $params->get( 'italign', 'center' );
$ioverflow = $params->get( 'ioverflow', 'auto' );
// startpositions
$startpos = $params->get ( 'startpos', '-400' );
$rightpos = $params->get ( 'rightpos', '100' );
$rightspeed = $params->get ( 'rightspeed', '20' );
$leftpos = $params->get ( 'leftpos', '-400' );
$leftspeed = $params->get ( 'leftspeed', '20' );
$line1 = JText :: _('CLOSE WINDOW');
//////////////////////////// END PARAMS //////////////////////////////
jimport('joomla.application.module.helper');
$modname = JModuleHelper::getModule($module_name,$module_title);
// Init
// Set opacity
if($opacity>99){
$opacityie = 100;
$opacity = 1;
}else{
$opacityie = $opacity;
$opacity = '0.'.$opacity;
}
// Get session
$session = JFactory::getSession();
// Time for the once-per-day cookie.
$expire = time()+mktime(24,0,0);
if($oncepersession=='oncepersession'){
if(!$session->get('mod_floaterpersession')){
$check = true;
}else{
$check = false;
}
}elseif($oncepersession=='onceperday'){
if(!$_COOKIE['mod_floaterperday']){
$check = true;
}else{
$check = false;
}
}else{
$check = false;
}
if($check or $oncepersession == 'false'){
?>
<style type="text/css"><!--
#floaterDiv
{
position: absolute;
width:<?php echo $boxwidth; ?>;
height:<?php echo $boxheight; ?>;
left:<?php echo $boxleft; ?>;
top:<?php echo $boxtop; ?>;
background-color:<?php echo $bgcolor; ?>;
border:<?php echo $border; ?>;
text-align:<?php echo $talign; ?>;
z-index: 9999;
}
.translucent {-moz-opacity:<?php echo $opacity; ?>; opacity:<?php echo $opacity; ?>; filter:alpha(opacity=<?php echo $opacityie; ?>);}
#floaterDiv div.box
{
position:absolute;
left:5px;
top:5px;
text-align: right;
}
#insideDiv
{
position: relative;
width:<?php echo $iwidth; ?>;
height:<?php echo $iheight; ?>;
left:<?php echo $ileft; ?>;
top:<?php echo $itop; ?>;
background-color:<?php echo $ibgcolor; ?>;
border:<?php echo $iborder; ?>;
z-index: 10000;
text-align:<?php echo $italign; ?>;
overflow: <?php echo $ioverflow; ?>;
}
-->
</style>
<div style="left: <?php echo $startpos;?>px;" id="floaterDiv" class="translucent">
<div class="box"><a onfocus="this.blur()" href="javascript:goaway()" title="Exit"> <strong> <?php echo $line1;?> X</strong></a><br>
<div>
<br>
<div id="insideDiv"><?php echo JModuleHelper::renderModule($modname,array('style'=> 'raw')); ?></div>
</div>
</div>
<script type="text/javascript">
<?php
echo "var direction = \"$direction\"; \n";
echo "var initdir = \"$initdir\"; \n";
echo "var startpos = $startpos; \n";
echo "var timeout = $timeout; \n";
echo "var rightpos = $rightpos; \n";
echo "var rightspeed = $rightspeed; \n";
echo "var leftpos = $leftpos; \n";
echo "var leftspeed = $leftspeed; \n";
?>
function moveTo(obj, x, y) {
if (document.getElementById) {
document.getElementById('floaterDiv').style.left = x;
document.getElementById('floaterDiv').style.top = y;
}
}
if (direction == 'top'){
var udlr = "top";
} else {
var udlr = "left";
}
function init(){
if(document.getElementById){
obj = document.getElementById("floaterDiv");
obj.style[udlr] = parseInt(startpos) + "px";
}
}
function slideDR(){
if(document.getElementById){
if(parseInt(obj.style[udlr]) < rightpos){
obj.style[udlr] = parseInt(obj.style[udlr]) + 20 + "px";
setTimeout("slideDR()",rightspeed);
}
}
}
function slideUL(){
if(document.getElementById){
if(parseInt(obj.style[udlr]) > leftpos){
obj.style[udlr] = parseInt(obj.style[udlr]) - 30 + "px";
setTimeout("slideUL()",leftspeed);
}
}
}
function ShowHide(id, visibility) {
divs = document.getElementsByTagName("div");
divs[id].style.visibility = visibility;
}
function goaway()
{
if (initdir == 'slideDR' ){
slideUL();
}
else{
slideDR();
}
}
function selection()
{
if (initdir == 'slideDR' ){
slideDR();
}
else{
slideUL();
}
}
function start()
{
init();
selection();
}
window.onload = start;
if (initdir == 'slideDR' ){
setTimeout('slideUL();',timeout);
}
else{
setTimeout('slideDR();',timeout);
}
</script>
<?php
}
if($oncepersession == 'oncepersession'){
// Session
$session->set('mod_floaterpersession', 'true');
}elseif($oncepersession == 'onceperday' && !$_COOKIE['mod_floaterperday']){
// Cookie
setcookie("mod_floaterperday", "true", $expire);
}
?>
|
viollarr/alab
|
modules/mod_floater/mod_floater.php
|
PHP
|
gpl-2.0
| 6,323
|
<?php
/****************************************************/
/* TrinityCore 4.3.4 CMS */
/****************************************************/
/* repo: https://github.com/Bender103/tc434cms */
/****************************************************/
/* Main Developer: Bender Gabor */
/* https://github.com/Bender103 */
/****************************************************/
?>
<span>Change your avatar</span>
<p>You can change your avatar.</p>
</div>
<br />
<style type="text/css">
.avatar {
padding:15px;
}
.service {
width:600px; padding:0 0 0 28px; padding-bottom:70px; float:left; min-height:183px;
}
.submit {
height:38px;
width:128px;
background:url('wow/static/images/services/button.png') no-repeat;
border:0px;
color:#E0BB00;
text-shadow:0px 0px 2px #000;
font-size:15px;
font-weight:bold;
}
.submit:hover {
background-position:0 -41;
}
.submit:active{
background-position:0 -82;
}
.portrait-b img{ -moz-box-shadow:0 0 10px #000; -webkit-box-shadow:0 0 10px #000; box-shadow:0 0 10px #000; }
.loader {
width:24px;
height:24px;
background: url("wow/static/images/loaders/canvas-loader.gif") no-repeat;
}
</style>
<center>
<?php
if(isset($_SESSION['username'])){
if($_POST['avatar'] != ""){
if($_POST['avatar'] == "blizzard.png"){
echo '
<div class="service" align="left">
<center>
<h3>Changing Avatar</h3><br />
<div class="loader"></div>
<br />
<font color="red">Error</font>
<meta http-equiv="refresh" content="2;url=services.php"/>
</center>
</div>';
}else{
$change_avatar = mysql_real_escape_string(mysql_query("UPDATE users SET avatar = '".mysql_real_escape_string($_POST['avatar'])."' WHERE id = '".$account_information['id']."'"));
echo '
<div class="service" align="left">
<center>
<h3>Changing Avatar</h3><br />
<div class="loader"></div>
<br />
<font color="aqua">Your avatar has been changed.</font>
<meta http-equiv="refresh" content="2;url=services.php"/>
</center>
</div>';
}
}else{
?>
<script>
function colors (color){
document.getElementById("image").src="images/avatars/2d/"+color;
}
</script>
<table border="0" width="500">
<tr>
<form method="POST">
<td class="avatar">
<center>
<div class="avatar portrait-b"><img id="image" src="images/avatars/2d/1-0.jpg" /></div>
<select onchange="colors(this.options[this.selectedIndex].value)" name="avatar">
<option value="1-0.jpg" selected>Human</option>
<option value="2-0.jpg">Orc</option>
<option value="3-0.jpg">Dwarf</option>
<option value="4-0.jpg">Night Elf</option>
<option value="5-0.jpg">Undead</option>
<option value="6-0.jpg">Tauren</option>
<option value="7-0.jpg">Gnome</option>
<option value="8-0.jpg">Troll</option>
<option value="9-0.jpg">Goblin</option>
<option value="10-0.jpg">Blood Elf</option>
<option value="11-0.jpg">Draenei</option>
<option value="22-0.jpg">Worgen</option>
</select>
</center>
</td>
</tr>
</table>
<br />
<input type="submit" class="submit" name="submit" value="Submit"/>
</form>
<?php }
}else{
echo '
<div class="service" align="left">
<center>
<h3>You need to be logged in to use this service.</h3>
<br />
<div class="loader"></div>
<br />
<meta http-equiv="refresh" content="2;url=services.php"/>
</center>
</div>
';
}
?>
</center>
|
Bender103/tc434cms
|
services/avatar.php
|
PHP
|
gpl-2.0
| 3,342
|
<?php
namespace georgynet\loginzabb\model;
/**
* Класс LoginzaUserProfile предназначен для генерации некоторых полей профиля пользователя сайта,
* на основе полученного профиля от Loginza API (http://loginza.ru/api-overview).
*
* При генерации используются несколько полей данных, что позволяет сгенерировать непереданные
* данные профиля, на основе имеющихся.
*
* Например: Если в профиле пользователя не передано значение nickname, то это значение может быть
* сгенерированно на основе email или full_name полей.
*
* Данный класс - это рабочий пример, который можно использовать как есть,
* а так же заимствовать в собственном коде или расширять текущую версию под свои задачи.
*
* @link http://loginza.ru/api-overview
* @author Sergey Arsenichev, PRO-Technologies Ltd.
* @version 1.0
*/
class LoginzaUserProfile
{
/**
* @var \stdClass
*/
private $profile;
private $translate = [
'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ж' => 'g', 'з' => 'z',
'и' => 'i', 'й' => 'y', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p',
'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'ы' => 'i', 'э' => 'e', 'А' => 'A',
'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D', 'Е' => 'E', 'Ж' => 'G', 'З' => 'Z', 'И' => 'I',
'Й' => 'Y', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O', 'П' => 'P', 'Р' => 'R',
'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F', 'Ы' => 'I', 'Э' => 'E', 'ё' => "yo", 'х' => "h",
'ц' => "ts", 'ч' => "ch", 'ш' => "sh", 'щ' => "shch", 'ъ' => "", 'ь' => "", 'ю' => "yu", 'я' => "ya",
'Ё' => "YO", 'Х' => "H", 'Ц' => "TS", 'Ч' => "CH", 'Ш' => "SH", 'Щ' => "SHCH", 'Ъ' => "", 'Ь' => "",
'Ю' => "YU", 'Я' => "YA"
];
function __construct($profile)
{
$this->profile = $profile;
}
public function getNickname()
{
if ($this->profile->nickname) {
return $this->profile->nickname;
}
if (!empty($this->profile->email) && preg_match('/^(.+)\@/i', $this->profile->email, $nickname)) {
return $nickname[1];
}
if (($fullName = $this->getFullName())) {
return $this->normalize($fullName, '.');
}
$patterns = [
'([^\.]+)\.ya\.ru',
'openid\.mail\.ru\/[^\/]+\/([^\/?]+)',
'openid\.yandex\.ru\/([^\/?]+)',
'([^\.]+)\.myopenid\.com'
];
foreach ($patterns as $pattern) {
if (preg_match('/^https?\:\/\/' . $pattern . '/i', $this->profile->identity, $result)) {
return $result[1];
}
}
return false;
}
public function genUserSite()
{
if (!empty($this->profile->web->blog)) {
return $this->profile->web->blog;
}
if (!empty($this->profile->web->default)) {
return $this->profile->web->default;
}
return $this->profile->identity;
}
public function getDisplayName()
{
if (($fullName = $this->getFullName())) {
return $fullName;
}
if (($nickname = $this->getNickname())) {
return $nickname;
}
$identity_component = parse_url($this->profile->identity);
$result = $identity_component['host'];
if ($identity_component['path'] != '/') {
$result .= $identity_component['path'];
}
return $result . $identity_component['query'];
}
public function getFullName()
{
if ($this->profile->name->full_name) {
return $this->profile->name->full_name;
}
if ($this->profile->name->first_name || $this->profile->name->last_name) {
return trim($this->profile->name->first_name . ' ' . $this->profile->name->last_name);
}
return false;
}
/**
* Генератор случайных паролей
* @param int $len Длина пароля
* @param string $char_list Список наборов символов, используемых для генерации, через запятую. Например: a-z,0-9,~
* @return string
*/
public function genRandomPassword($len = 6, $char_list = 'a-z,0-9')
{
$chars = [];
// предустановленные наборы символов
$chars['a-z'] = 'qwertyuiopasdfghjklzxcvbnm';
$chars['A-Z'] = strtoupper($chars['a-z']);
$chars['0-9'] = '0123456789';
$chars['~'] = '~!@#$%^&*()_+=-:";\'/\\?><,.|{}[]';
// набор символов для генерации
$charset = '';
// пароль
$password = '';
if (!empty($char_list)) {
$char_types = explode(',', $char_list);
foreach ($char_types as $type) {
if (array_key_exists($type, $chars)) {
$charset .= $chars[$type];
} else {
$charset .= $type;
}
}
}
for ($i = 0; $i < $len; $i++) {
$password .= $charset[rand(0, strlen($charset) - 1)];
}
return $password;
}
/**
* Транслит + убирает все лишние символы заменяя на символ $delimiter
* @param string $string
* @param string $delimiter
* @return string
*/
private function normalize($string, $delimiter = '-')
{
$string = strtr($string, $this->translate);
return trim(
preg_replace('/[^\w]+/i', $delimiter, $string),
$delimiter
);
}
}
|
Georgynet/loginzabb
|
model/LoginzaUserProfile.php
|
PHP
|
gpl-2.0
| 6,216
|
<?php
/*
// "K2" Component by JoomlaWorks for Joomla! 1.5.x - Version 2.1
// Copyright (c) 2006 - 2009 JoomlaWorks Ltd. All rights reserved.
// Released under the GNU/GPL license: http://www.gnu.org/copyleft/gpl.html
// More info at http://www.joomlaworks.gr and http://k2.joomlaworks.gr
// Designed and developed by the JoomlaWorks team
// *** Last update: September 9th, 2009 ***
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.controller');
class K2ControllerInfo extends JController {
function display() {
JRequest::setVar('view', 'info');
parent::display();
}
}
|
ASirik/vostok
|
administrator/components/com_k2/controllers/info.php
|
PHP
|
gpl-2.0
| 638
|
<?php
/**
* Core Design Lock Article plugin for Joomla! 2.5
* @author Daniel Rataj, <info@greatjoomla.com>
* @package Joomla
* @subpackage Content
* @category Plugin
* @version 2.5.x.2.0.5
* @copyright Copyright (C) 2007 - 2013 Great Joomla!, http://www.greatjoomla.com
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL 3
*
* This file is part of Great Joomla! extension.
* This extension 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 extension 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/>.
*/
// no direct access
defined('_JEXEC') or die;
class plgContentCDLockArticle_context_com_content
{
/**
* Article info
* @var null
*/
private $source = null;
/**
* Constructor
* @param null $source
*/
public function __construct($source = null)
{
$this->source = $source;
}
/**
* Instance
* @param null $source
*/
public function getInstance($source = null)
{
return new plgContentCDLockArticle_context_com_content($source);
}
/**
* Get article id
* @return int
*/
public function article_get_sourceid()
{
return (int)$this->source->id;
}
/**
* Get id article in category view
* @return int
*/
public function category_get_sourceid()
{
/*
if (JFactory::getApplication()->input->getCmd('view', '') === 'category')
{
return 0;
}
*/
return (int)$this->source->id;
}
}
|
bundocba/ccas
|
plugins/content/cdlockarticle/context/com_content.php
|
PHP
|
gpl-2.0
| 2,048
|
<div class="blog-lists-blog clearfix">
<div id="themepacific_infinite" class="blogposts-tp-site-wrap clearfix">
<?php if (have_posts()) : while (have_posts()) : the_post();
get_template_part( 'content');
endwhile;
?>
<?php else: ?>
<h2 class="noposts"><?php _e('Sorry, no posts to display!', 'silvermag'); ?></h2>
<?php endif;?>
</div>
</div> <?php wp_reset_query();?>
<div class="pagination clearfix">
<?php silvermag_themepacific_tpcrn_pagination(); ?>
</div>
|
delfintrinidadIV/firstproject
|
wp-content/themes/sliver-mag-lite/includes/blog-loop.php
|
PHP
|
gpl-2.0
| 526
|
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Monopoly - Room List</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/bootstrap.min.css">
</style>
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/new.css">
<script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
</head>
<?php
$toname = "";
require './database.php';
require './config.php';
session_start();
$dname = $_SESSION['dname'];
$room = new Room($db);
if(isset($_POST['username']) && !empty($_POST['username'])){
$user=new User($db);
$uid=$user->login($_POST['username'], $_POST['password']);
}else{
$uid=0;
}
if($uid || isset($_SESSION['uid'])){
$toname = $_SESSION['name'];
if(!isset($_SESSION['uid'])){
$_SESSION['uid']=$uid;
$_SESSION['name']=$_POST['username'];
$toname = $_SESSION['name'];
}
?>
<div class="three_col">
<div class="left">
<div class="left_header">
Profile
</div>
<div class="left_content">
<?php
$user=new User($db);
$userinfo=$user->userinfo($_SESSION['uid']);
?>
<ul>
<li class="avatar"><img id="toavatar" src="./data/<?=$toname;?>.png"><br/><br/>
<b><?=$_SESSION['dname'];?></b></li>
<li>You are in:<b id="p_stop"></b></li>
<li>Money:<b id="p_money"><?=$settings['start_money']?></b></li>
<li><button id="dicebutton" onclick="pDice()" class="function_button orangebg"><i class="fa fa-envelope"></i> Dice</button></li>
<li><button onclick="cDice()" class="function_button orangebg"><i class="fa fa-envelope"></i> Dice</button></li>
<li><button onclick="checkProp()" class="function_button bluebg"><i class="fa fa-credit-card"></i> Property</button></li>
<li><button onclick="test()" class="function_button orangebg" id="testbutton"><i class="fa fa-envelope"></i> Quickcash</button></li>
<li><button onclick="inchance()" class="function_button orangebg" id="chancebutton"><i class="fa fa-envelope"></i> Chance now</button></li>
<li><button onclick="outjail()" class="function_button orangebg" id="jailbutton"><i class="fa fa-envelope"></i> Out jail now</button></li>
<li>You still have <b id="show-time"><?=$settings["round_time"];?></b> seconds<br /><button onclick="finishRound()" id="finishbutton" class="function_button greenbg"><i class="fa fa-sign-out"></i> Finish this round</button></li>
</ul>
</div>
</div>
<div class="middle">
<div class="middle_header">
Players
</div>
<div class="room_players_other">
<div class="room_players_other_indiv">
<svg class="miniload" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="512px" height="512px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve">
<path id="loading-12-icon" d="M291,82.219c0,16.568-13.432,30-30,30s-30-13.432-30-30s13.432-30,30-30S291,65.65,291,82.219z
M261,404.781c-15.188,0-27.5,12.312-27.5,27.5s12.312,27.5,27.5,27.5s27.5-12.312,27.5-27.5S276.188,404.781,261,404.781z
M361.504,113.167c-4.142,7.173-13.314,9.631-20.487,5.489c-7.173-4.141-9.631-13.313-5.49-20.487
c4.142-7.173,13.314-9.631,20.488-5.489C363.188,96.821,365.645,105.994,361.504,113.167z M188.484,382.851
c-14.348-8.284-32.697-3.368-40.98,10.98c-8.285,14.349-3.367,32.696,10.98,40.981c14.35,8.283,32.697,3.367,40.98-10.981
C207.75,409.482,202.834,391.135,188.484,382.851z M421.33,184.888c-8.368,4.831-19.07,1.965-23.901-6.404
c-4.832-8.368-1.965-19.07,6.404-23.902c8.368-4.831,19.069-1.964,23.9,6.405C432.566,169.354,429.699,180.056,421.33,184.888z
M135.399,329.767c-8.285-14.35-26.633-19.266-40.982-10.982c-14.348,8.285-19.264,26.633-10.979,40.982
c8.284,14.348,26.632,19.264,40.981,10.98C138.767,362.462,143.683,344.114,135.399,329.767z M436.031,277.249
c-11.044,0-20-8.953-20-19.999c0-11.045,8.955-20.001,20.001-20.001c11.044,0,19.999,8.955,19.999,20.002
C456.031,268.295,447.078,277.249,436.031,277.249z M115.97,257.251c-0.001-16.57-13.433-30.001-30.001-30.002
c-16.568,0.001-29.999,13.432-30,30.002c0.001,16.566,13.433,29.998,30.001,30C102.538,287.249,115.969,273.817,115.97,257.251z
M401.333,364.248c-10.759-6.212-14.446-19.97-8.234-30.73c6.212-10.759,19.971-14.446,30.731-8.233
c10.759,6.211,14.445,19.971,8.232,30.73C425.852,366.774,412.094,370.46,401.333,364.248z M135.398,184.736
c8.285-14.352,3.368-32.698-10.98-40.983c-14.349-8.283-32.695-3.367-40.981,10.982c-8.282,14.348-3.366,32.696,10.981,40.981
C108.768,204,127.115,199.082,135.398,184.736z M326.869,421.328c-6.902-11.953-2.807-27.242,9.148-34.145
s27.243-2.806,34.146,9.149c6.902,11.954,2.806,27.243-9.15,34.145C349.059,437.381,333.771,433.284,326.869,421.328z
M188.482,131.649c14.352-8.286,19.266-26.633,10.982-40.982c-8.285-14.348-26.631-19.264-40.982-10.98
c-14.346,8.285-19.264,26.633-10.98,40.982C155.787,135.017,174.137,139.932,188.482,131.649z"/>
</div>
<div class="room_players_other_indiv">
<svg class="miniload" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="512px" height="512px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve">
<path id="loading-12-icon" d="M291,82.219c0,16.568-13.432,30-30,30s-30-13.432-30-30s13.432-30,30-30S291,65.65,291,82.219z
M261,404.781c-15.188,0-27.5,12.312-27.5,27.5s12.312,27.5,27.5,27.5s27.5-12.312,27.5-27.5S276.188,404.781,261,404.781z
M361.504,113.167c-4.142,7.173-13.314,9.631-20.487,5.489c-7.173-4.141-9.631-13.313-5.49-20.487
c4.142-7.173,13.314-9.631,20.488-5.489C363.188,96.821,365.645,105.994,361.504,113.167z M188.484,382.851
c-14.348-8.284-32.697-3.368-40.98,10.98c-8.285,14.349-3.367,32.696,10.98,40.981c14.35,8.283,32.697,3.367,40.98-10.981
C207.75,409.482,202.834,391.135,188.484,382.851z M421.33,184.888c-8.368,4.831-19.07,1.965-23.901-6.404
c-4.832-8.368-1.965-19.07,6.404-23.902c8.368-4.831,19.069-1.964,23.9,6.405C432.566,169.354,429.699,180.056,421.33,184.888z
M135.399,329.767c-8.285-14.35-26.633-19.266-40.982-10.982c-14.348,8.285-19.264,26.633-10.979,40.982
c8.284,14.348,26.632,19.264,40.981,10.98C138.767,362.462,143.683,344.114,135.399,329.767z M436.031,277.249
c-11.044,0-20-8.953-20-19.999c0-11.045,8.955-20.001,20.001-20.001c11.044,0,19.999,8.955,19.999,20.002
C456.031,268.295,447.078,277.249,436.031,277.249z M115.97,257.251c-0.001-16.57-13.433-30.001-30.001-30.002
c-16.568,0.001-29.999,13.432-30,30.002c0.001,16.566,13.433,29.998,30.001,30C102.538,287.249,115.969,273.817,115.97,257.251z
M401.333,364.248c-10.759-6.212-14.446-19.97-8.234-30.73c6.212-10.759,19.971-14.446,30.731-8.233
c10.759,6.211,14.445,19.971,8.232,30.73C425.852,366.774,412.094,370.46,401.333,364.248z M135.398,184.736
c8.285-14.352,3.368-32.698-10.98-40.983c-14.349-8.283-32.695-3.367-40.981,10.982c-8.282,14.348-3.366,32.696,10.981,40.981
C108.768,204,127.115,199.082,135.398,184.736z M326.869,421.328c-6.902-11.953-2.807-27.242,9.148-34.145
s27.243-2.806,34.146,9.149c6.902,11.954,2.806,27.243-9.15,34.145C349.059,437.381,333.771,433.284,326.869,421.328z
M188.482,131.649c14.352-8.286,19.266-26.633,10.982-40.982c-8.285-14.348-26.631-19.264-40.982-10.98
c-14.346,8.285-19.264,26.633-10.98,40.982C155.787,135.017,174.137,139.932,188.482,131.649z"/>
</svg>
</div>
<div class="room_players_other_indiv">
<svg class="miniload" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="512px" height="512px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve">
<path id="loading-12-icon" d="M291,82.219c0,16.568-13.432,30-30,30s-30-13.432-30-30s13.432-30,30-30S291,65.65,291,82.219z
M261,404.781c-15.188,0-27.5,12.312-27.5,27.5s12.312,27.5,27.5,27.5s27.5-12.312,27.5-27.5S276.188,404.781,261,404.781z
M361.504,113.167c-4.142,7.173-13.314,9.631-20.487,5.489c-7.173-4.141-9.631-13.313-5.49-20.487
c4.142-7.173,13.314-9.631,20.488-5.489C363.188,96.821,365.645,105.994,361.504,113.167z M188.484,382.851
c-14.348-8.284-32.697-3.368-40.98,10.98c-8.285,14.349-3.367,32.696,10.98,40.981c14.35,8.283,32.697,3.367,40.98-10.981
C207.75,409.482,202.834,391.135,188.484,382.851z M421.33,184.888c-8.368,4.831-19.07,1.965-23.901-6.404
c-4.832-8.368-1.965-19.07,6.404-23.902c8.368-4.831,19.069-1.964,23.9,6.405C432.566,169.354,429.699,180.056,421.33,184.888z
M135.399,329.767c-8.285-14.35-26.633-19.266-40.982-10.982c-14.348,8.285-19.264,26.633-10.979,40.982
c8.284,14.348,26.632,19.264,40.981,10.98C138.767,362.462,143.683,344.114,135.399,329.767z M436.031,277.249
c-11.044,0-20-8.953-20-19.999c0-11.045,8.955-20.001,20.001-20.001c11.044,0,19.999,8.955,19.999,20.002
C456.031,268.295,447.078,277.249,436.031,277.249z M115.97,257.251c-0.001-16.57-13.433-30.001-30.001-30.002
c-16.568,0.001-29.999,13.432-30,30.002c0.001,16.566,13.433,29.998,30.001,30C102.538,287.249,115.969,273.817,115.97,257.251z
M401.333,364.248c-10.759-6.212-14.446-19.97-8.234-30.73c6.212-10.759,19.971-14.446,30.731-8.233
c10.759,6.211,14.445,19.971,8.232,30.73C425.852,366.774,412.094,370.46,401.333,364.248z M135.398,184.736
c8.285-14.352,3.368-32.698-10.98-40.983c-14.349-8.283-32.695-3.367-40.981,10.982c-8.282,14.348-3.366,32.696,10.981,40.981
C108.768,204,127.115,199.082,135.398,184.736z M326.869,421.328c-6.902-11.953-2.807-27.242,9.148-34.145
s27.243-2.806,34.146,9.149c6.902,11.954,2.806,27.243-9.15,34.145C349.059,437.381,333.771,433.284,326.869,421.328z
M188.482,131.649c14.352-8.286,19.266-26.633,10.982-40.982c-8.285-14.348-26.631-19.264-40.982-10.98
c-14.346,8.285-19.264,26.633-10.98,40.982C155.787,135.017,174.137,139.932,188.482,131.649z"/>
</div>
</div>
</div>
<div class="right">
<div class="right_header">
Room:<?php echo $room->getroomname($_GET['rid']);?>
</div>
<div class="right_content r_fixed">
<div id="map-canvas" class="big_play_content">
</div>
</div>
<div class="gamewarn">
</div>
<div class="chat_header">
Chat
</div>
<div class="chat_box">
</div>
<div class="chat_send">
<input type="text" id="send_content">
<input class="sendsubmit" value="Send" type="submit" id="send_content_submit">
</div>
</div>
</div>
<div class="ingamepopup drawcard">
<div class="ingamepopup_header">
Draw a card
</div>
<div class="create_room_content">
<img src="./img/card.png"><br />
You are given a chance to draw a special card.<br />
<button class="drawbutton">Draw</button>
<button class="cancel_button">Cancel</button>
</div>
</div>
<div class="ingamepopup buybuilding">
<div class="ingamepopup_header">
Buy a building
</div>
<div class="create_room_content">
<img class="buybimg" src=""><br />
Name:<b class="building_name"></b><br />
Price:<b class="building_price">2000</b><br />
<button class="buybutton">Buy</button>
<button class="cancel_button">Cancel</button>
</div>
</div>
<div class="ingamepopup payrent">
<div class="ingamepopup_header">
Pay rent
</div>
<div class="create_room_content">
<img class="rentimg" src=""><br />
Owner:<b class="building_owner"></b><br />
Rent:$<b class="building_rent"></b><br />
<button class="paybutton">Pay</button>
</div>
</div>
<div class="ingamepopup mybuilding">
<div class="ingamepopup_header">
Property
</div>
<div class="create_room_content showmybuilding">
<div class="my_small_prop">
<img class="rentimg" src="./img/big/station.png"><br />Rent:$100</div>
</div>
<button class="cancel_button">Close</button>
</div> <!-- /container -->
<div class="ingamepopup verdict">
<div class="ingamepopup_header">
Verdict
</div>
<div class="create_room_content">
<ul class="verdict_player">
</ul>
<a href="./roomlist.php"><button class="cancel_button">Lobby</button></a>
</div>
</div> <!-- /container -->
<?php
}else{
$msg="Incorrect password";
?>
<div class="bg1">
<div class="login_form bmsg">
<div class="login_header">
Error
</div>
<h2 class="msg"><?=$msg;?></h2>
<a href="./index.php"><button class="warningbutton">Home</button></a>
</div>
</div>
</div> <!-- /container -->
<?php
}
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.1.min.js"><\/script>')</script>
<script src="js/vendor/bootstrap.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="js/main.js"></script>
<script>
$('#dicebutton').prop('disabled', true);
$('#finishbutton').prop('disabled', true);
var socket; // WebSocket
var jail = 0;
var gamenotice;
var payto;
var readyToFinish;
var myPlayerNo;
var MY_MAPTYPE_ID = 'custom_style';
var gameStopName = new Array();
gameStopName[0]="University Station";
gameStopName[1]="Chung Chi Administration Building";//CC admin
gameStopName[2]="Wong Fok Yuen Building";//王褔元
gameStopName[3]="Chen Kou Bun Building";//陳國本
gameStopName[4]="Sino building";//信和
gameStopName[5]="CC staff hostel";//CC staff hostel
gameStopName[6]="MMW Engineering Building";//new eng build
gameStopName[7]="Academic Builidng";//教研樓
gameStopName[8]="HSB";//HSB
gameStopName[9]="Shaw Science building";//逸夫科學
gameStopName[10]="Science Centre";//BMSB
gameStopName[11]="Sir Run Run Shaw Hall";//sir run run
gameStopName[12]="Pi Chiu Building"; //pi chu
gameStopName[13]="NA College"; //NA tower
gameStopName[14]="Cheng Ming College";
gameStopName[15]="UC Gym";
gameStopName[16]="UC College";
gameStopName[17]="Lee Shau Kee building";//lsk
gameStopName[18]="Leung Kao Kui building";//lkk
gameStopName[19]="WYS College";//wys
gameStopName[20]="Shaw College";//shaw
gameStopName[21]="Shaw Hostel";//shaw hostel
gameStopName[22]="Jail";//jail
gameStopName[23]="Staff hostel";//staff hostel
gameStopName[24]="Science Park";//science park
gameStopName[25]="AIT";//AIT
gameStopName[26]="YIA";//YIA
gameMarkName = new Array();
/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////
<?php
foreach($buildingArray as $building){
echo "var ".$building->name.";";
}
?>
/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////
var gameStop = new Array();
gameStop[0]=0;
gameStop[1]=3;//CC admin
gameStop[2]=5;//王褔元
gameStop[3]=6;//陳國本
gameStop[4]=6.5;//信和
gameStop[5]=8;//CC staff hostel
gameStop[6]=10.5;//new eng build
gameStop[7]=12.5;//教研樓
gameStop[8]=15.5;//HSB
gameStop[9]=17;//逸夫科學
gameStop[10]=19;//BMSB
gameStop[11]=24.5;//sir run run
gameStop[12]=26; //pi chu
gameStop[13]=31.5; //NA tower
gameStop[14]=33;
gameStop[15]=36;
gameStop[16]=38;
gameStop[17]=42.5;//lsk
gameStop[18]=43.5;//lkk
gameStop[19]=49;//wys
gameStop[20]=51;//shaw
gameStop[21]=55;//shaw hostel
gameStop[22]=66.5;//jail
gameStop[23]=71;//staff hostel
gameStop[24]=86;//science park
gameStop[25]=94.5;//AIT
gameStop[26]=95.5;//YIA
//initialize an array of four players with offset zero.
var count = new Array();
count[0] = 0;
count[1] = 0;
count[2] = 0;
count[3] = 0;
var playerOffset = new Array();
playerOffset[0] = 0;
playerOffset[1] = 0;
playerOffset[2] = 0;
playerOffset[3] = 0;
var playerStopNo = new Array();
playerStopNo[0] = 0;
playerStopNo[1] = 0;
playerStopNo[2] = 0;
playerStopNo[3] = 0;
var line;
var playerRound = new Array();
playerRound[0] = 0;
playerRound[1] = 0;
playerRound[2] = 0;
playerRound[3] = 0;
var map;
var movable = 0;
var payrent = 1;
var stopNoCoord = [
new google.maps.LatLng(22.41398668736628,114.20978419482708),//大學站
new google.maps.LatLng(22.41439581682375,114.20845784246922),//CC Admin
new google.maps.LatLng(22.414921484418553,114.20784629881382),//王褔元
new google.maps.LatLng(22.415366564624026,114.20760624110699) ,
new google.maps.LatLng(22.41561947864573,114.20752845704556) ,
new google.maps.LatLng(22.41627779680755,114.2077524214983) ,//CC
new google.maps.LatLng(22.417300601321244,114.2081319540739) ,//new eng build
new google.maps.LatLng(22.417162988061555,114.20722402632236) ,
new google.maps.LatLng(22.418334556046702,114.20744396746159) ,
new google.maps.LatLng(22.418633335295212,114.20802064239979) ,
new google.maps.LatLng(22.41893087415704,114.20898891985416) ,
new google.maps.LatLng(22.419840843220154,114.20710198581219) ,
new google.maps.LatLng(22.419840843220154,114.20629061758518) ,
new google.maps.LatLng(22.420642949970436,114.20820839703083), //NA tower
new google.maps.LatLng(22.421094210464293,114.20756734907627) ,
new google.maps.LatLng(22.420602038919093,114.20604787766933) ,
new google.maps.LatLng(22.420349133970557,114.20504473149776) ,
new google.maps.LatLng(22.419964816745452,114.2031229287386) ,
new google.maps.LatLng(22.419958618071814,114.20292042195797) , //LKK
new google.maps.LatLng(22.42188639223504,114.20258648693562) ,
new google.maps.LatLng(22.42207111002635,114.20151494443417) , //SHAW
new google.maps.LatLng(22.423088913046463,114.20101471245289) , //SHAW hostel
new google.maps.LatLng(22.42580632377871,114.20544371008873) , //jail
new google.maps.LatLng(22.425343921419284,114.20776315033436) ,
new google.maps.LatLng(22.41998093329562,114.21285666525364) , //science park
new google.maps.LatLng(22.416195972121077,114.21140559017658) ,//AIT
new google.maps.LatLng(22.415822801348867,114.21104215085506) , //YIA
new google.maps.LatLng(22.413976769061446,114.20978955924511)
];
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(22.4189136, 114.207623),
zoom: 16,
mapTypeId: MY_MAPTYPE_ID
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// INCLUDE MAP FILE
<?php echo file_get_contents('maps/cuhk.map.js'); ?>
// END
// Define the symbol, using one of the predefined paths ('CIRCLE')
// supplied by the Google Maps JavaScript API.
var lineSymbol = {
path: google.maps.SymbolPath.CIRCLE,
fillColor: '#000',
fillOpacity: 1.0,
scale: 12,
strokeColor: '#393',
strokeWeight: 8
};
var line2Symbol = {
path: google.maps.SymbolPath.CIRCLE,
fillColor: '#000',
fillOpacity: 1.0,
scale: 12,
strokeColor: '#eee',
strokeWeight: 8
};
var line3Symbol = {
path: google.maps.SymbolPath.CIRCLE,
fillColor: '#000',
fillOpacity: 1.0,
scale: 12,
strokeColor: '#ff0000',
strokeWeight: 8
};
var line4Symbol = {
path: google.maps.SymbolPath.CIRCLE,
fillColor: '#000',
fillOpacity: 1.0,
scale: 12,
strokeColor: '#0000ff',
strokeWeight: 8
};
// Create the polyline and add the symbol to it via the 'icons' property.
line = new google.maps.Polyline({
path: lineCoordinates,
geodesic: true,
strokeColor: '#5293C2',
strokeOpacity: 0.8,
strokeWeight: 8,
icons: [{
icon: lineSymbol,
offset: '0%'
},
{
icon: line2Symbol,
offset: '0%'
},
{
icon: line3Symbol,
offset: '0%'
},
{
icon: line4Symbol,
offset: '0%'
}],
map: map
});
var featureOpts = [
{
stylers: [
{ hue: '#2c3e50' }
]
}
];
var styledMapOptions = {
name: 'Custom Style'
};
var customMapType = new google.maps.StyledMapType(featureOpts, styledMapOptions);
map.mapTypes.set(MY_MAPTYPE_ID, customMapType);
animateCircle(0);
animateCircle(1);
animateCircle(2);
animateCircle(3);
google.maps.event.addListener(map, 'click', function(e) {
console.log('new google.maps.LatLng(' + e.latLng.A + ',' +e.latLng.k + ')' );
});
/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////
<?php
foreach($buildingArray as $building){
echo $building->name . " = new google.maps.Marker({";
echo " position: new google.maps.LatLng(" . $building->x ."," . $building->y . "),";
echo " map:map,";
echo ' icon: "./img/' . $building->img . '",';
echo ' visible: false';
echo "});";
echo "gameMarkName[".$building->stopNo."] = ". $building->name .';';
}
?>
/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////
}
function checkProp(playerno){
if(playerno == null){
playerno = myPlayerNo;
}
//alert(playerno); //for debugging
var msg={};
msg.playerno = playerno;
msg.act = "checkprop";
msg.rid = <?=$_GET['rid'];?>;
socket.send(JSON.stringify(msg));
}
function cDice(){
var msg = {};
msg.act = "dice";
msg.rid = <?=$_GET['rid'];?>;
msg.step = 13;
msg.playerno=myPlayerNo;
socket.send(JSON.stringify(msg));
}
function test(){
var msg = {};
msg.rid = <?=$_GET['rid'];?>;
msg.act = "test";
msg.playerno=myPlayerNo;
socket.send(JSON.stringify(msg));
alert("yes");
}
function inchance(){
var msg = {};
msg.rid = <?=$_GET['rid'];?>;
msg.act = "chance";
msg.playerno=myPlayerNo;
socket.send(JSON.stringify(msg));
}
function outjail(){
var msg = {};
msg.rid = <?=$_GET['rid'];?>;
msg.act = "jail";
msg.playerno=myPlayerNo;
socket.send(JSON.stringify(msg));
jail = 0;
}
//finish this round
function finishRound() {
if(movable == 0 && payrent==1){
readyToFinish = 1;
var msg = {};
msg.rid = <?=$_GET['rid'];?>;
msg.act = "finishround";
msg.playerno=myPlayerNo;
socket.send(JSON.stringify(msg));
$('#finishbutton').prop('disabled', true);
$("b[id=show-time]").html(<?=$settings["round_time"];?>);
}else{
if(movable == 1){
if(jail == 1){
jail++;
readyToFinish = 1;
var msg = {};
msg.rid = <?=$_GET['rid'];?>;
msg.act = "finishround";
msg.playerno=myPlayerNo;
socket.send(JSON.stringify(msg));
$('#finishbutton').prop('disabled', true);
$("b[id=show-time]").html(<?=$settings["round_time"];?>);
}else{
gameshowmsg('You did not dice!');
}
}else{
if(payrent!=1){
gameshowmsg('You did not pay rent!');
}else{
alert('It is not your turn now');
}
}
}
}
//dice
function pDice(){
if(movable == 1 && payrent==1 && jail != 1){
var msg = {};
msg.act = "dice";
msg.rid = <?=$_GET['rid'];?>;
var random = Math.random();
random = random*6;
random = parseInt(random)+1;
msg.step = random;
msg.playerno = myPlayerNo;
socket.send(JSON.stringify(msg));
movable = 0;
$('#dicebutton').prop('disabled', true);
$('.ingamepopup').hide();
}else{
if(payrent!=1){
gameshowmsg('You did not pay rent!');
}else if(jail == 1){
gameshowmsg('You are jailed');
jail++;
movable = 0;
$('#dicebutton').prop('disabled', true);
$('.ingamepopup').hide();
}else{
alert('It is not your turn now');
}
}
}
//for animation of circle in the googlem ap
function animateCircle(playerNo) {
window.setInterval(function() {
playerOffset[playerNo]=playerOffset[playerNo]%100;
if(count[playerNo]<playerOffset[playerNo]){
count[playerNo] = (count[playerNo] + 0.5);
}
var icons = line.get('icons');
icons[playerNo].offset = (count[playerNo]) + '%';
line.set('icons', icons);
if(count[playerNo]>playerOffset[playerNo]){
count[playerNo] = (count[playerNo] + 0.5);
if(count[playerNo]==100){
count[playerNo]=0;
}
icons[playerNo].offset = (count[playerNo]) + '%';
line.set('icons', icons);
}
}, 20);
}
function gameshowmsg(msg){
$('.gamewarn').html(msg);
$('.gamewarn').show(300);
clearTimeout(gamenotice); //clear timer
gamenotice = setTimeout(function(){
$('.gamewarn').hide(300);
},3000); //hide the game message after 3seconds
}
function updatemoney(tempplayerno,tempmoney){ //update user money on the user info area
$('.room_players_other_indiv').each(function(){
if($(this).hasClass(''+tempplayerno+'')){ //check if it is the targeted user
$(this).find('.opmoney').html(eval(tempmoney));
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
$(document).ready(function(){
$('svg.bigload').fadeOut(500); //loading animation
$('.bg1').fadeIn(300);
$("#p_stop").html(gameStopName[playerOffset[0]]); //initialize the layout only
SetupWebSocket();
/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////
<?php
if(isset($_SESSION['name'])){
?>
/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////
$('#send_content_submit').click(function(){
if($('#send_content').val()==''){ //empty message
alert('Your message is empty!');
$('#send_content').focus();
}else{
var msg = {};
msg.act = "sendmsg";
msg.rid = <?=$_GET['rid'];?>;
msg.uname = '<?= $_SESSION['name'];?>';
msg.dname = '<?= $_SESSION['dname'];?>';
msg.sendcontent=$('#send_content').val();
socket.send(JSON.stringify(msg));
$('#send_content').val('');
}
});
/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////
<?php
}
?>
/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////PHP/////
$('#send_content').bind('keydown', function(e) {
if(e.keyCode==13){
$('#send_content_submit').click();
}
});
$('.cancel_button').click(function(){
$('.ingamepopup').hide();
});
$(window).on('beforeunload', function(){
var msg = {};
msg.act="leavegame";
msg.uname = '<?= $_SESSION['name'];?>';
msg.rid = <?=$_GET['rid'];?>;
socket.send(JSON.stringify(msg));
});
$(document).on("keydown", disableF5);
var settimmer = 0;
$(function(){
window.setInterval(function() {
var timeCounter = $("b[id=show-time]").html();
if(readyToFinish == 0){
var updateTime = eval(timeCounter)- eval(1);
}
$("b[id=show-time]").html(updateTime);
if(updateTime == 0){
//event to be sent
if(payrent == 0){
var msg = {};
msg.act = "payrent";
msg.payto = payto;
msg.rid = <?=$_GET['rid'];?>;
msg.rent = parseInt($('.building_rent').html());
socket.send(JSON.stringify(msg));
}
//TODO: if jail, reduce money, and if money < 0, then he/she loses
if(movable != 0){
pDice();
}
readyToFinish = 1; //stop the count down
finishRound();
$("b[id=show-time]").html(<?=$settings["round_time"];?>);
}
}, 1000);
});
$('.drawbutton').click(function(){
$('.ingamepopup').hide();
var msg = {};
msg.act = "drawcard";
msg.playerno = myPlayerNo;
var random=Math.random()*6; //needed to be modified
random = parseInt(random)+1;
msg.cardno = random;
msg.rid = <?=$_GET['rid'];?>;
socket.send(JSON.stringify(msg));
});
});
$('.buybutton').click(function(){
var msg = {};
msg.act = "buybuilding";
msg.stopno = playerStopNo[myPlayerNo-1];
socket.send(JSON.stringify(msg));
$('.buybuilding').hide();
});
$('.paybutton').click(function(){
var msg = {};
msg.act = "payrent";
msg.payto = payto;
msg.rid = <?=$_GET['rid'];?>;
msg.rent = parseInt($('.building_rent').html());
socket.send(JSON.stringify(msg));
})
function disableF5(e) { if ((e.which || e.keyCode) == 116) e.preventDefault(); };
function SetupWebSocket()
{
var host = 'ws://<?=$SERVER_ADDR?>:9876/mono/server.php';
socket = new WebSocket(host);
socket.onopen = function(e) {
var msg = {};
msg.act = "getplayerno";
msg.uname = '<?= $_SESSION['name'];?>';
msg.dname = '<?= $_SESSION['dname'];?>';
msg.rid = <?=$_GET['rid'];?>;
socket.send(JSON.stringify(msg));
};
socket.onmessage = function(e) {
var retData=$.parseJSON(e.data);
//console.log(retData["roomlist"].length);
console.log(retData);
if(retData['act']=='playerno'){
myPlayerNo = retData['playerno'];
movable = retData['movable'];
if(myPlayerNo == 1){
$('#toavatar').css("border-color","#393");
}else if(myPlayerNo == 2){
$('#toavatar').css("border-color","#eee");
}else if(myPlayerNo == 3){
$('#toavatar').css("border-color","#ff0000");
}else if(myPlayerNo == 4){
$('#toavatar').css("border-color","#0000ff");
}
$('#dicebutton').prop('disabled', true);
$('#finishbutton').prop('disabled', true);
$('#testbutton').prop('disabled',true);
$('#chancebutton').prop('disabled',true);
$('#jailbutton').prop('disabled', true);
if(retData['movable']){
$('#dicebutton').prop('disabled', false);
$('#finishbutton').prop('disabled', false);
$('#testbutton').prop('disabled',false);
$('#chancebutton').prop('disabled',false);
readyToFinish = 0;
gameshowmsg('It is your turn now!');
alert('It is your turn now!');
}
}else if(retData['act'] == 'initinfo'){
var tempplayerno = 0;
for(i=0;i<retData['players'].length;i++){
var tempplayer = retData['players'][i];
if(tempplayer['playerno'] != myPlayerNo){
$('.room_players_other_indiv:eq('+tempplayerno+')').html('');
$('.room_players_other_indiv:eq('+tempplayerno+')').addClass(''+tempplayer["playerno"]+'');
$('.room_players_other_indiv:eq('+tempplayerno+')').html('<img src="./data/'+tempplayer['name']+'.png">'+tempplayer['dname']+'<br />Money: <b class="opmoney">'+tempplayer['money']+'</b> <button onclick="checkProp('+tempplayer['playerno']+')" value="'+ tempplayer['playerno'] +'"class="checkprop">Property</button>');
tempplayerno++;
}
}
}
if(retData['act']=='transfer'){
var tempno=parseInt(retData.playerno)-1; //remember to -1= =
playerOffset[tempno]=parseFloat(retData.offset);
var thisround=Math.floor(retData.offset/27);
if(tempno==myPlayerNo-1){ //to be edited
if(thisround>playerRound[tempno]){
//gameshowmsg('You pass one round'); //to be edited
playerRound[tempno]++;
var msg = {};
msg.act = "addround";
msg.rid = <?=$_GET['rid'];?>;
msg.playround = playerRound[tempno];
msg.playerno = myPlayerNo;
socket.send(JSON.stringify(msg));
//$("#p_money").html(eval($("#p_money").html())+eval(<?=$settings["round_money"];?>)); //add money
}
}
playerOffset[tempno] = playerOffset[tempno]%27;
var stopNo = playerOffset[tempno];
playerStopNo[tempno] = stopNo;
map.panTo(stopNoCoord[stopNo]);
//send back the stopNO to server//
if(tempno==myPlayerNo-1){
var msg = {};
msg.act = "recordstopno";
msg.playerno = myPlayerNo;
msg.stopno = stopNo;
msg.rid = <?=$_GET['rid'];?>;
socket.send(JSON.stringify(msg));
}
var tempstop = playerOffset[tempno]%27;
playerOffset[tempno] = gameStop[playerOffset[tempno]];
//alert(playerOffset[tempno]);
//console.log(retData.uname);
if(tempno == myPlayerNo-1){
$("#p_stop").html(gameStopName[tempstop]); //update the stop name
}
gameshowmsg(retData['uname'] +' moves to '+ gameStopName[tempstop]);
$('.chat_box').append('<b class="systemmsg">[SYSTEM] : '+retData['uname'] +' moves to '+ gameStopName[tempstop]+'.</b><br />');
$('.chat_box').scrollTop($('.chat_box')[0].scrollHeight);
if(playerOffset[tempno]==66.5 && tempno==myPlayerNo-1){//to be edited(same playerno)
var msg = {};
msg.act = "jail";
msg.playerno = myPlayerNo;
socket.send(JSON.stringify(msg));
gameshowmsg('You are jailed');
jail = 1;
$('#jailbutton').prop('disabled',false);
}
}else if(retData['act']=='getoffnow'){
alert('Get out now');
window.location.href = './roomlist.php';
}else if(retData['act']=='getcard'){
if(retData['playerno'] == myPlayerNo){
gameshowmsg('You ' + retData['cardmsg']);
$("#p_money").html(eval(retData['money'])); //add money
}else{
alert(retData['cardpname'] +' '+ retData['cardmsg']);
updatemoney(retData['playerno'],retData['money']);
}
gameshowmsg(retData['cardpname'] +' '+ retData['cardmsg']);
$('.chat_box').append('<b class="systemmsg">[SYSTEM] : '+retData['cardpname'] +' '+ retData['cardmsg']+'</b><br />');
$('.chat_box').scrollTop($('.chat_box')[0].scrollHeight);
}else if(retData["act"]=="chatroommsg"){
$('.chat_box').append(retData["uname"]+" : "+retData["sendcontent"]+" ["+retData["stime"]+"]<br />");
$('.chat_box').scrollTop($('.chat_box')[0].scrollHeight);
}else if(retData["act"]=="recordstopno"){
//console.log('here'+ retData["marker"]);
if(retData["playerno"] == myPlayerNo){
$('.building_name').html(retData["bname"]);
$('.building_price').html(retData["money"]);
$('.buybimg').attr('src', "./img/big/"+retData['img']);
$('.buybuilding').show();
}
}else if(retData["act"] == "nextmovable"){
if(myPlayerNo == retData["nextplayerno"]){
movable = 1;
$('#dicebutton').prop('disabled', false);
gameshowmsg('It is your turn now!');
alert('It is your turn now!');
$('#finishbutton').prop('disabled', false);
readyToFinish = 0;
}
}else if(retData["act"] == "notice"){
tempMN = null;
if(retData['playerno'] == myPlayerNo){
$("#p_money").html(eval(retData['money']));
}else{
updatemoney(retData['playerno'],retData['money']);
}
if(retData['bought']==1){
tempMN = gameMarkName[playerStopNo[retData['playerno']-1]];
}
if(tempMN){
tempMN.visible=true;
tempMN.setMap(map);
}
if(retData["sendcontent"]){
gameshowmsg(retData["sendcontent"]);
$('.chat_box').append('<b class="systemmsg">[SYSTEM] : ' + retData["sendcontent"] + "</b><br />");
$('.chat_box').scrollTop($('.chat_box')[0].scrollHeight);
}
}else if(retData["act"] == "takerent"){
payrent = 0;
console.log(retData);
payto = retData["payto"];
$('.building_rent').html(retData["rent"]);
$('.building_owner').html(retData["dname"]);
$('.rentimg').attr('src', "./img/big/"+retData['img']);
$('.payrent').show();
}else if(retData["act"] == "mybuilding"){
if(retData["mybuilding"].length == 0){
alert("No property");
}else{
$('.mybuilding').show();
myprops = retData["mybuilding"];
$('.showmybuilding').html('');
for(i=0;i<myprops.length;i++){
$('.showmybuilding').append('<div class="my_small_prop"><img class="rentimg" src="./img/big/'+myprops[i]['img']+'"><br />Rent:$'+myprops[i]['rent']+'</div>');
}
}
}else if(retData["act"] == "getchance"){
$('.drawcard').show(); //get a chance to draw a card.
}else if(retData["act"] == "payrentsucceed"){
if(myPlayerNo == retData['playerno']){
$('.payrent').hide();
$('#p_money').html(eval(retData['money']));
payrent = 1;
}else{
updatemoney(retData['playerno'],eval(retData['money']));
}
if(myPlayerNo == retData['otherplayerno']){
$('.payrent').hide();
$('#p_money').html(eval(retData['othermoney']));
payrent = 1;
}else{
updatemoney(retData['otherplayerno'],eval(retData['othermoney']));
}
}else if(retData["act"] == "selfwarn"){
gameshowmsg(retData["sendcontent"]);
}else if(retData["act"] == "endgame"){
console.log(retData);
$('.verdict').show();
$('.verdict_player').html('');
var p = 1;
for(i=retData["players"].length-1;i>=0;i--){
$('.verdict_player').append('<li>'+(p++)+' <img src="./data/'+retData["players"][i]["name"]+'.png"> '+retData["players"][i]["dname"]+' $'+retData["players"][i]["money"]+'</li>');
}
$('#dicebutton').prop('disabled', true);
$('#finishbutton').prop('disabled', true);
readyToFinish = 1;
}else if(retData["act"] == "test2"){
if(movable == 1){
if(retData['id'] == myPlayerNo){
$("#p_money").html(eval(retData['money']));
}else{
updatemoney(retData['id'],retData['money']);
}
}
}else if(retData["act"] == "test1"){
if(retData['id'] == myPlayerNo){
alert('You do not have enough tools. Please buy it.');
}
}else if(retData["act"] == "chance1"){
if(retData['id'] == myPlayerNo){
alert('You do not have enough tools. Please buy it.');
}
}else if(retData["act"] == "chance2"){
if(retData['id'] == myPlayerNo){
alert('chance2');
$('.drawcard').show();
}
}else if(retData["act"] == "jail1"){
if(retData['id'] == myPlayerNo){
alert('You do not have enough tools. Please buy it.');
}
}
else if(retData["act"] == "jail2"){
if(retData['id'] == myPlayerNo){
jail = 0;
alert(jail);
$('#jailbutton').prop('disabled', true);
}
}
};
socket.onclose = function(e) {
gameshowmsg('Disconnected - status ' + this.readyState);
//alert('Disconnected - status ' + this.readyState);
};
}
</script>
</body>
</html>
|
CSCI3100/monopoly
|
play_1.php
|
PHP
|
gpl-2.0
| 41,655
|
<?php
/**
* The template for displaying the home page.
*
* @package Spike
*/
get_header(); ?>
<?php
$thumb_id = get_post_thumbnail_id();
$thumb_url = wp_get_attachment_image_src($thumb_id, 'thumbnail-size', true)[0];
$fields = get_fields();
?>
<div class="hero" style="background-image: url('<?= $thumb_url; ?>')"></div>
<div class="caption-wrapper constrain">
<div class="caption">
<?= $fields['photo_caption']; ?>
</div>
</div>
<main id="main" class="site-main" role="main">
<div class="constrain">
<section class="welcome text-centered">
<?= $fields['welcome_message']; ?>
</section>
</div>
<section class="grid constrain">
<div class="row">
<div class="middle grunge">
<div class="grid-content contain-50 contain-right">
<?= $fields['middle_school']; ?>
</div>
</div>
<div class="high change-collage">
<div class="grid-content contain-50 contain-left">
<?= $fields['high_school']; ?>
</div>
</div>
</div>
<div class="row">
<div class="video change-collage">
<div class="grid-content contain-25 contain-right">
<div class="video-wrapper">
<iframe
frameborder="0"
webkitallowfullscreen
mozallowfullscreen
allowfullscreen
src="https://player.vimeo.com/video/<?= $fields['video_id']; ?>?color=00A7D0&byline=0&portrait=0&badge=0">
</iframe>
</div>
</div>
</div>
<div class="stat grunge">
<div class="grid-content contain-75 contain-left brush">
<div class="cf">
<?= $fields['stat']; ?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="lauren grunge">
<div class="grid-content contain-75 contain-right flex-center">
<div class="fifty">
<?= $fields['lauren']; ?>
</div>
<div class="fifty lauren-contain"><div class="lauren-image"></div></div>
</div>
</div>
<div class="video-2 change-collage">
<div class="grid-content contain-25 contain-left">
<div class="video-wrapper">
<iframe
frameborder="0"
webkitallowfullscreen
mozallowfullscreen
allowfullscreen
src="https://player.vimeo.com/video/<?= $fields['video_id_2']; ?>?color=00A7D0&byline=0&portrait=0&badge=0">
</iframe>
</div>
</div>
</div>
</div>
<div class="row">
<div class="order change-collage">
<div class="grid-content contain-25 contain-right">
<?= $fields['order']; ?>
</div>
</div>
<div class="about grunge">
<div class="grid-content contain-75 contain-left">
<?= $fields['about']; ?>
</div>
</div>
</div>
</section>
<?php if (is_user_logged_in()): ?>
<footer class="entry-footer">
<?php edit_post_link( __( 'Edit', 'spike' ), '<span class="edit-link">', '</span>' ); ?>
</footer><!-- .entry-footer -->
<?php endif; ?>
</main> <!-- #main -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
|
gp6shc/sst
|
wp-content/themes/sst/front-page.php
|
PHP
|
gpl-2.0
| 2,912
|
/*
* Definitions for a Sony interface CDROM drive.
*
* Corey Minyard (minyard@wf-rch.cirr.com)
*
* Copyright (C) 1993 Corey Minyard
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
/*
* Offsets (from the base address) and bits for the various write registers
* of the drive.
*/
#define SONY_CMD_REG_OFFSET 0
#define SONY_PARAM_REG_OFFSET 1
#define SONY_WRITE_REG_OFFSET 2
#define SONY_CONTROL_REG_OFFSET 3
# define SONY_ATTN_CLR_BIT 0x01
# define SONY_RES_RDY_CLR_BIT 0x02
# define SONY_DATA_RDY_CLR_BIT 0x04
# define SONY_ATTN_INT_EN_BIT 0x08
# define SONY_RES_RDY_INT_EN_BIT 0x10
# define SONY_DATA_RDY_INT_EN_BIT 0x20
# define SONY_PARAM_CLR_BIT 0x40
# define SONY_DRIVE_RESET_BIT 0x80
/*
* Offsets (from the base address) and bits for the various read registers
* of the drive.
*/
#define SONY_STATUS_REG_OFFSET 0
# define SONY_ATTN_BIT 0x01
# define SONY_RES_RDY_BIT 0x02
# define SONY_DATA_RDY_BIT 0x04
# define SONY_ATTN_INT_ST_BIT 0x08
# define SONY_RES_RDY_INT_ST_BIT 0x10
# define SONY_DATA_RDY_INT_ST_BIT 0x20
# define SONY_DATA_REQUEST_BIT 0x40
# define SONY_BUSY_BIT 0x80
#define SONY_RESULT_REG_OFFSET 1
#define SONY_READ_REG_OFFSET 2
#define SONY_FIFOST_REG_OFFSET 3
# define SONY_PARAM_WRITE_RDY_BIT 0x01
# define SONY_PARAM_REG_EMPTY_BIT 0x02
# define SONY_RES_REG_NOT_EMP_BIT 0x04
# define SONY_RES_REG_FULL_BIT 0x08
#define LOG_START_OFFSET 150 /* Offset of first logical sector */
#define SONY_DETECT_TIMEOUT 80 /* Maximum amount of time
that drive detection code
will wait for response
from drive (in 1/100th's
of seconds). */
#define SONY_JIFFIES_TIMEOUT 500 /* Maximum number of times the
drive will wait/try for an
operation */
#define SONY_RESET_TIMEOUT 100 /* Maximum number of times the
drive will wait/try a reset
operation */
#define SONY_READY_RETRIES 20000 /* How many times to retry a
spin waiting for a register
to come ready */
#define MAX_CDU31A_RETRIES 3 /* How many times to retry an
operation */
/* Commands to request or set drive control parameters and disc information */
#define SONY_REQ_DRIVE_CONFIG_CMD 0x00 /* Returns s_sony_drive_config */
#define SONY_REQ_DRIVE_MODE_CMD 0x01
#define SONY_REQ_DRIVE_PARAM_CMD 0x02
#define SONY_REQ_MECH_STATUS_CMD 0x03
#define SONY_REQ_AUDIO_STATUS_CMD 0x04
#define SONY_SET_DRIVE_PARAM_CMD 0x10
#define SONY_REQ_TOC_DATA_CMD 0x20 /* Returns s_sony_toc */
#define SONY_REQ_SUBCODE_ADDRESS_CMD 0x21 /* Returns s_sony_subcode */
#define SONY_REQ_UPC_EAN_CMD 0x22
#define SONY_REQ_ISRC_CMD 0x23
#define SONY_REQ_TOC_DATA_SPEC_CMD 0x24
/* Commands to request information from the drive */
#define SONY_READ_TOC_CMD 0x30
#define SONY_SEEK_CMD 0x31
#define SONY_READ_CMD 0x32
#define SONY_READ_BLKERR_STAT_CMD 0x34
#define SONY_ABORT_CMD 0x35
#define SONY_READ_TOC_SPEC_CMD 0x36
/* Commands to control audio */
#define SONY_AUDIO_PLAYBACK_CMD 0x40
#define SONY_AUDIO_STOP_CMD 0x41
#define SONY_AUDIO_SCAN_CMD 0x42
/* Miscellaneous control commands */
#define SONY_EJECT_CMD 0x50
#define SONY_SPIN_UP_CMD 0x51
#define SONY_SPIN_DOWN_CMD 0x52
/* Diagnostic commands */
#define SONY_WRITE_BUFFER_CMD 0x60
#define SONY_READ_BUFFER_CMD 0x61
#define SONY_DIAGNOSTICS_CMD 0x62
/*
* The following are command parameters for the set drive parameter command
*/
#define SONY_SD_DECODE_PARAM 0x00
#define SONY_SD_INTERFACE_PARAM 0x01
#define SONY_SD_BUFFERING_PARAM 0x02
#define SONY_SD_AUDIO_PARAM 0x03
#define SONY_SD_AUDIO_VOLUME 0x04
#define SONY_SD_MECH_CONTROL 0x05
#define SONY_SD_AUTO_SPIN_DOWN_TIME 0x06
/*
* The following extract information from the drive configuration about
* the drive itself.
*/
#define SONY_HWC_GET_LOAD_MECH(c) (c.hw_config[0] & 0x03)
#define SONY_HWC_EJECT(c) (c.hw_config[0] & 0x04)
#define SONY_HWC_LED_SUPPORT(c) (c.hw_config[0] & 0x08)
#define SONY_HWC_DOUBLE_SPEED(c) (c.hw_config[0] & 0x10)
#define SONY_HWC_GET_BUF_MEM_SIZE(c) ((c.hw_config[0] & 0xc0) >> 6)
#define SONY_HWC_AUDIO_PLAYBACK(c) (c.hw_config[1] & 0x01)
#define SONY_HWC_ELECTRIC_VOLUME(c) (c.hw_config[1] & 0x02)
#define SONY_HWC_ELECTRIC_VOLUME_CTL(c) (c.hw_config[1] & 0x04)
#define SONY_HWC_CADDY_LOAD_MECH 0x00
#define SONY_HWC_TRAY_LOAD_MECH 0x01
#define SONY_HWC_POPUP_LOAD_MECH 0x02
#define SONY_HWC_UNKWN_LOAD_MECH 0x03
#define SONY_HWC_8KB_BUFFER 0x00
#define SONY_HWC_32KB_BUFFER 0x01
#define SONY_HWC_64KB_BUFFER 0x02
#define SONY_HWC_UNKWN_BUFFER 0x03
/*
* This is the complete status returned from the drive configuration request
* command.
*/
struct s_sony_drive_config
{
unsigned char exec_status[2];
char vendor_id[8];
char product_id[16];
char product_rev_level[8];
unsigned char hw_config[2];
};
/* The following is returned from the request subcode address command */
struct s_sony_subcode
{
unsigned char exec_status[2];
unsigned char address :4;
unsigned char control :4;
unsigned char track_num;
unsigned char index_num;
unsigned char rel_msf[3];
unsigned char reserved1;
unsigned char abs_msf[3];
};
/*
* The following is returned from the request TOC (Table Of Contents) command.
* (last_track_num-first_track_num+1) values are valid in tracks.
*/
struct s_sony_toc
{
unsigned char exec_status[2];
unsigned char address0 :4;
unsigned char control0 :4;
unsigned char point0;
unsigned char first_track_num;
unsigned char disk_type;
unsigned char dummy0;
unsigned char address1 :4;
unsigned char control1 :4;
unsigned char point1;
unsigned char last_track_num;
unsigned char dummy1;
unsigned char dummy2;
unsigned char address2 :4;
unsigned char control2 :4;
unsigned char point2;
unsigned char lead_out_start_msf[3];
struct
{
unsigned char address :4;
unsigned char control :4;
unsigned char track;
unsigned char track_start_msf[3];
} tracks[100];
unsigned int lead_out_start_lba;
};
/*
* The following are errors returned from the drive.
*/
/* Command error group */
#define SONY_ILL_CMD_ERR 0x10
#define SONY_ILL_PARAM_ERR 0x11
/* Mechanism group */
#define SONY_NOT_LOAD_ERR 0x20
#define SONY_NO_DISK_ERR 0x21
#define SONY_NOT_SPIN_ERR 0x22
#define SONY_SPIN_ERR 0x23
#define SONY_SPINDLE_SERVO_ERR 0x25
#define SONY_FOCUS_SERVO_ERR 0x26
#define SONY_EJECT_MECH_ERR 0x29
#define SONY_AUDIO_PLAYING_ERR 0x2a
#define SONY_EMERGENCY_EJECT_ERR 0x2c
/* Seek error group */
#define SONY_FOCUS_ERR 0x30
#define SONY_FRAME_SYNC_ERR 0x31
#define SONY_SUBCODE_ADDR_ERR 0x32
#define SONY_BLOCK_SYNC_ERR 0x33
#define SONY_HEADER_ADDR_ERR 0x34
/* Read error group */
#define SONY_ILL_TRACK_R_ERR 0x40
#define SONY_MODE_0_R_ERR 0x41
#define SONY_ILL_MODE_R_ERR 0x42
#define SONY_ILL_BLOCK_SIZE_R_ERR 0x43
#define SONY_MODE_R_ERR 0x44
#define SONY_FORM_R_ERR 0x45
#define SONY_LEAD_OUT_R_ERR 0x46
#define SONY_BUFFER_OVERRUN_R_ERR 0x47
/* Data error group */
#define SONY_UNREC_CIRC_ERR 0x53
#define SONY_UNREC_LECC_ERR 0x57
/* Subcode error group */
#define SONY_NO_TOC_ERR 0x60
#define SONY_SUBCODE_DATA_NVAL_ERR 0x61
#define SONY_FOCUS_ON_TOC_READ_ERR 0x63
#define SONY_FRAME_SYNC_ON_TOC_READ_ERR 0x64
#define SONY_TOC_DATA_ERR 0x65
/* Hardware failure group */
#define SONY_HW_FAILURE_ERR 0x70
#define SONY_LEAD_IN_A_ERR 0x91
#define SONY_LEAD_OUT_A_ERR 0x92
#define SONY_DATA_TRACK_A_ERR 0x93
/*
* The following are returned from the Read With Block Error Status command.
* They are not errors but information (Errors from the 0x5x group above may
* also be returned
*/
#define SONY_NO_CIRC_ERR_BLK_STAT 0x50
#define SONY_NO_LECC_ERR_BLK_STAT 0x54
#define SONY_RECOV_LECC_ERR_BLK_STAT 0x55
#define SONY_NO_ERR_DETECTION_STAT 0x59
/*
* The following is not an error returned by the drive, but by the code
* that talks to the drive. It is returned because of a timeout.
*/
#define SONY_TIMEOUT_OP_ERR 0x01
#define SONY_SIGNAL_OP_ERR 0x02
/*
* The following are attention code for asynchronous events from the drive.
*/
/* Standard attention group */
#define SONY_EMER_EJECT_ATTN 0x2c
#define SONY_HW_FAILURE_ATTN 0x70
#define SONY_MECH_LOADED_ATTN 0x80
#define SONY_EJECT_PUSHED_ATTN 0x81
/* Audio attention group */
#define SONY_AUDIO_PLAY_DONE_ATTN 0x90
#define SONY_LEAD_IN_ERR_ATTN 0x91
#define SONY_LEAD_OUT_ERR_ATTN 0x92
#define SONY_DATA_TRACK_ERR_ATTN 0x93
#define SONY_AUDIO_PLAYBACK_ERR_ATTN 0x94
/* Auto spin up group */
#define SONY_SPIN_UP_COMPLETE_ATTN 0x24
#define SONY_SPINDLE_SERVO_ERR_ATTN 0x25
#define SONY_FOCUS_SERVO_ERR_ATTN 0x26
#define SONY_TOC_READ_DONE_ATTN 0x62
#define SONY_FOCUS_ON_TOC_READ_ERR_ATTN 0x63
#define SONY_SYNC_ON_TOC_READ_ERR_ATTN 0x65
/* Auto eject group */
#define SONY_SPIN_DOWN_COMPLETE_ATTN 0x27
#define SONY_EJECT_COMPLETE_ATTN 0x28
#define SONY_EJECT_MECH_ERR_ATTN 0x29
|
Lakshmipathi/Linux-historic
|
include/linux/cdu31a.h
|
C
|
gpl-2.0
| 9,549
|
"C:\Program Files\Java\jre1.5.0_11\bin\java" -jar dist\mw.jar local
|
concord-consortium/mw
|
run5.bat
|
Batchfile
|
gpl-2.0
| 69
|
/*******************************************************************************
* Copyright (c) 2012 Benet Joan Darder.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* Benet Joan Darder - initial API and implementation
******************************************************************************/
package com.pim.missatges;
import rice.p2p.commonapi.NodeHandle;
import rice.p2p.scribe.ScribeContent;
/**
* Classe que modela un missatge de tipus <pre>rice.p2p.scribe.ScribeContent</pre>.
*
* @author Benet Joan Darder
*
*/
public class MissatgeScribe implements ScribeContent{
private static final long serialVersionUID = -6424703050299263807L;
/**
* L'origen del contingut
*/
protected NodeHandle from;
/**
* Num de seqüència del contingut
*/
protected int seq;
/**
* Constructor MissatgeScribe
*
* @param from Qui ha enviat el missatge
* @param seq Num de seqüència del contingut
*/
public MissatgeScribe(NodeHandle from, int seq) {
this.from = from;
this.seq = seq;
}
public String toString() {
return "PIM MissatgeScribe #"+this.seq+" amb origen "+this.from;
}
/**
* Qui ha enviat el missatge
* @return objecte nodeHandle
*/
public NodeHandle getSender() {
return this.from;
}
}
|
kuratowsky/pim-pastyinstantmessenger
|
src/com/pim/missatges/MissatgeScribe.java
|
Java
|
gpl-2.0
| 1,574
|
<section ng-controller=ExampleController>
<div data-ng-show="!authentication.user">
<a href="/signup">Crear Cuenta</a>
<a href="/signin">Identificarse</a>
</div>
<div data-ng-show="authentication.user">
<img src="{{authentication.user.providerData.picture}}" >
<h1>Hello <span data-ng-bind="authentication.user.providerData.name"></span> </h1>
<a href="/signout">Cerrar sesión</a>
<ul>
<li><a href="/#!/articles">Listar artículos</a> </li>
<li><a href="/#!/articles/create">Crear Artículo</a> </li>
</ul>
</div>
</section>
|
CarlosLM-NCC/mean
|
public/example/views/example.client.view.html
|
HTML
|
gpl-2.0
| 623
|
/*
* @Author: Alec Thompson
* @Date: 2014-02-25 10:16:11
* @Last Modified by: ajthompson
* @Last Modified time: 2014-03-03 16:39:25
*/
#include <iostream>
#include <vector>
#include <cstdlib>
#include <iomanip>
#include "Field.h"
using std::cout;
using std::endl;
using std::vector;
using std::exit;
using namespace std;
/**
* @Author: Alec Thompson
*
* Field constructor
*
* @param dim Dimension of the field read into the program
* @param dMax Maximum router ID
*/
Field::Field(int dim, int dMax) {
// set the max amount of digits for a source id
this->setMaxDigits(dMax);
this->setWidth(dim);
this->setHeight(dim);
// sets the field to dimensions of DIMENSION +2, DIMENSION
this->field.resize(dim + 2);
for (int i = 0; i < dim + 2; ++i) {
this->field[i].resize(dim);
}
}
////////////////////////
/// SETTER FUNCTIONS ///
////////////////////////
/**
* @Author: Alec Thompson
*
* Sets the maximum number of digits a router ID has to control printing
* of the field.
*
* @param dMax Maximum router ID
*/
void Field::setMaxDigits(int dMax) {
if (dMax >= 10000) {
maxDigits = 5;
} else if (dMax >= 1000) {
maxDigits = 4;
} else if (dMax >= 100) {
maxDigits = 3;
} else if (dMax >= 10) {
maxDigits = 2;
} else {
maxDigits = 1;
}
}
/**
* @Author: Alec Thompson
*
* Sets the width of the field given the dimension input into the program.
* This adds 2 to account for the sender and receiver columns
*
* @param dimension Dimension of the field entered as a program argument
*/
void Field::setWidth(int dimension) {
width = dimension + 2;
}
/**
* @Author: Alec Thompson
*
* Sets the height of the field given the dimension
*
* @param dimension Dimension argument of the program
*/
void Field::setHeight(int dimension) {
height = dimension;
}
/**
* @Author: Alec Thompson
*
* Sets the position specified to the given value. If no value is
* given, sets the position to 0.
*
* @param x X position
* @param y Y position
* @param newVal New value to insert
*/
void Field::setPos(int x, int y, int newVal) {
if (DEBUG) {
cout << "adding value " << newVal << " at position";
cout << " (" << x << "," << y << ")" << endl;
}
field[x][y] = newVal;
if (DEBUG) {
cout << "added value " << newVal << " at position";
cout << " (" << x << "," << y << ")" << endl;
}
}
/**
* @Author: Alec Thompson
*
* Updates the size of the 2D vector to be consistent with the height
* and width settings.
*
* WARNING: WHEN DECREASING SIZE, HIGHER INDICES WILL BE TRUNCATED
*/
void Field::updateSize() {
this->field.resize(getWidth());
for (int i = 0; i < getWidth(); ++i) {
this->field[i].resize(getHeight());
}
}
////////////////////////
/// GETTER FUNCTIONS ///
////////////////////////
// @author Alec Thompson
// I don't feel like breaking my inline comments to sign them, so you get this instead
/** Gets the maximum router id digits */
int Field::getMaxDigits() {
return maxDigits;
}
/** Gets the width of the field */
int Field::getWidth() {
return width;
}
/** Gets the height of the field */
int Field::getHeight() {
return height;
}
/** Gets the value at the given point */
int Field::getVal(int x, int y) {
return field[x][y];
}
/**
* @Author: Alec Thompson
*
* Returns the position of the given value by reference.
* Exits the program if a val of less than 1 is used, as
* 0 is the empty space specifier, and negative values
* are not supported
*
* @param val Value to be found
* @param x x position of val
* @param y y position of val
*/
void Field::getPos(int val, int &x, int &y) {
if (val < 1) {
cout << "Value is less than 1. This could be an invalid input ";
cout << "or any unused point." << endl;
} else {
for (int j = 0; j < getHeight(); ++j) {
for (int i = 0; i < getWidth(); ++i) {
if (field[i][j] == val) {
x = i;
y = j;
goto finish;
}
}
}
}
cout << "Value is not found in array." << endl;
cout << "Setting X and Y to 0" << endl;
x = 0;
y = 0;
finish:;
}
//////////////////////
/// PRINT FUNCTION ///
//////////////////////
/**
* @Author: Alec Thompson
*
* Prints the field
*/
void Field::printField() {
/** Print out the top border of the field */
cout << endl << "/";
for (int w = 0; w < getWidth(); ++w) {
for (int m = 0; m < getMaxDigits(); ++m) {
cout << "-";
}
}
cout << "\\" << endl;
/** Print out the main body of the field */
for (int h = 0; h < getHeight(); ++h) {
cout << "|";
for (int w = 0; w < getWidth(); ++w) {
if (getVal(w, h) == 0) {
for (int m = 0; m < getMaxDigits(); ++m) {
cout << ".";
}
} else {
cout << setfill('0') << setw(getMaxDigits());
cout << getVal(w, h);
}
cout << setw(1);
}
cout << "|" << endl;
}
/** Print out the bottom border of the field */
cout << "\\";
for (int w = 0; w < getWidth(); ++w) {
for (int m = 0; m < getMaxDigits(); ++m) {
cout << "-";
}
}
cout << "/" << endl << endl;
}
|
ajthompson/cs2303-prog5
|
Field.cpp
|
C++
|
gpl-2.0
| 4,984
|
'use strict';
angular
.module('scruman')
.controller('LoginController', LoginController);
LoginController.$inject = ['$http', '$auth', '$location'];
function LoginController($http, $auth, $location) {
var vm = this;
vm.authenticate = authenticate;
isAuthenticated();
function authenticate(provider) {
$auth.authenticate(provider).then(authSuccess).catch(loginError);
function authSuccess(response) {
console.log(response);
isAuthenticated();
}
function loginError(errors) {
console.log(errors);
}
}
function isAuthenticated() {
if ($auth.isAuthenticated()) {
$location.path('/dashboard');
}
return false;
}
}
|
rcdigital/kanban-client
|
app/components/login/LoginController.js
|
JavaScript
|
gpl-2.0
| 690
|
from django.db import models
from django.contrib.auth import models as auth
import datetime
from application import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
typeChoices = (
('task', 'Task'),
('userStory', 'User Story'),
)
statusChoices = (
('toDo', 'To do'),
('inProgress', 'in progress'),
('done', 'Done'),
)
categoryChoices = (
('frontend', 'Frontend'),
('backend', 'Backend'),
('design', 'Design'),
)
purposeChoices = (
('bugfix', 'Bugfix'),
('feature', 'Feature'),
)
class WorkGroup(models.Model):
name = models.CharField(
max_length=200,
unique = True,
)
def __unicode__(self):
return u'%s' % (self.name)
class TaskCard(models.Model):
creator = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name='createdTasks',
on_delete=models.PROTECT,
)
processor = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name='processingTasks',
blank=True,
null=True,
)
createTime = models.DateTimeField(
auto_now_add=True,
)
startTime = models.DateField(
null=True,
blank=True,
)
#endTime = models.DateTimeField()
#sprint = models.ForeignKey(Sprint)
title = models.CharField(
max_length=200,
)
taskType = models.CharField(
max_length=15,
choices=typeChoices,
default='task',
)
taskPurpose = models.CharField(
max_length=15,
choices=purposeChoices,
blank=True,
null=True,
)
taskCategory = models.CharField(
max_length=15,
choices=categoryChoices,
blank=True,
null=True,
)
description = models.TextField()
status = models.CharField(
max_length=15,
choices=statusChoices,
blank=True,
null=True,
)
group = models.ForeignKey(
WorkGroup,
null=True,
blank=True,
)
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
if self.startTime is None and self.processor is not None:
self.startTime = datetime.date.today()
self.status = 'in progress'
if self.status is None:
self.status = statusChoices[0][1]
if self.group is None:
self.group = self.creator.taskCardUser.workGroup
super(TaskCard, self).save(*args, **kwargs)
def commentsDescending(self, *args, **kwargs):
return self.comments.order_by('-published',)
class TaskCardUser(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
related_name='taskCardUser'
)
workGroup = models.ForeignKey(
WorkGroup,
related_name='taskCardUser'
)
def __unicode__(self):
return u'%s' % (self.user)
#@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def connectTaskCardUser(sender, instance, created, **kwargs):
if created:
TaskCardUser.objects.create(user=instance, workGroup=WorkGroup.objects.get(id=1))
post_save.connect(connectTaskCardUser, sender=settings.AUTH_USER_MODEL)
class Comment(models.Model):
taskCard = models.ForeignKey(
TaskCard,
related_name = 'comments',
)
author = models.ForeignKey(
settings.AUTH_USER_MODEL
)
published = models.DateTimeField(
null=True,
blank=True,
)
text = models.CharField(
max_length=255,
)
def save(self, *args, **kwargs):
self.published = datetime.datetime.now()
super(Comment, self).save(*args, **kwargs)
class Meta:
unique_together = ('taskCard', 'published')
#class Sprint(models.Model):
# startTime = models.DateTimeField()
# endTime = models.DateTimeField()
|
Die-Turtles/application
|
taskCards/models.py
|
Python
|
gpl-2.0
| 3,381
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\ConfigurableProduct\Test\Unit\Model\Plugin;
use Magento\ConfigurableProduct\Model\Plugin\ProductIdentitiesExtender;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
/**
* Class ProductIdentitiesExtenderTest
*/
class ProductIdentitiesExtenderTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject|Configurable
*/
private $configurableTypeMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|ProductRepositoryInterface
*/
private $productRepositoryMock;
/**
* @var ProductIdentitiesExtender
*/
private $plugin;
protected function setUp()
{
$this->configurableTypeMock = $this->getMockBuilder(Configurable::class)
->disableOriginalConstructor()
->getMock();
$this->productRepositoryMock = $this->getMockBuilder(ProductRepositoryInterface::class)
->getMock();
$this->plugin = new ProductIdentitiesExtender($this->configurableTypeMock, $this->productRepositoryMock);
}
public function testAfterGetIdentities()
{
$productId = 1;
$productIdentity = 'cache_tag_1';
$productMock = $this->getMockBuilder(Product::class)
->disableOriginalConstructor()
->getMock();
$parentProductId = 2;
$parentProductIdentity = 'cache_tag_2';
$parentProductMock = $this->getMockBuilder(Product::class)
->disableOriginalConstructor()
->getMock();
$productMock->expects($this->once())
->method('getId')
->willReturn($productId);
$this->configurableTypeMock->expects($this->once())
->method('getParentIdsByChild')
->with($productId)
->willReturn([$parentProductId]);
$this->productRepositoryMock->expects($this->once())
->method('getById')
->with($parentProductId)
->willReturn($parentProductMock);
$parentProductMock->expects($this->once())
->method('getIdentities')
->willReturn([$parentProductIdentity]);
$productIdentities = $this->plugin->afterGetIdentities($productMock, [$productIdentity]);
$this->assertEquals([$productIdentity, $parentProductIdentity], $productIdentities);
}
}
|
kunj1988/Magento2
|
app/code/Magento/ConfigurableProduct/Test/Unit/Model/Plugin/ProductIdentitiesExtenderTest.php
|
PHP
|
gpl-2.0
| 2,567
|
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source 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 for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*
** QGL.H
*/
#ifndef __QGL_EXTRA_H__
#define __QGL_EXTRA_H__
#ifdef USE_GLES
# include <GLES/gl.h>
# include <GLES/glext.h>
typedef GLchar GLcharARB;
typedef double GLdouble;
typedef unsigned int GLhandleARB;
#else
#ifdef USE_LOCAL_HEADERS
# include "SDL_opengl.h"
#else
# include <SDL_opengl.h>
#endif
#endif
// GL_ARB_shader_objects
extern GLvoid (APIENTRYP qglDeleteObjectARB) (GLhandleARB obj);
extern GLhandleARB (APIENTRYP qglGetHandleARB) (GLenum pname);
extern GLvoid (APIENTRYP qglDetachObjectARB) (GLhandleARB containerObj, GLhandleARB attachedObj);
extern GLhandleARB (APIENTRYP qglCreateShaderObjectARB) (GLenum shaderType);
extern GLvoid (APIENTRYP qglShaderSourceARB) (GLhandleARB shaderObj, GLsizei count, const GLcharARB **string,
const GLint *length);
extern GLvoid (APIENTRYP qglCompileShaderARB) (GLhandleARB shaderObj);
extern GLhandleARB (APIENTRYP qglCreateProgramObjectARB) (void);
extern GLvoid (APIENTRYP qglAttachObjectARB) (GLhandleARB containerObj, GLhandleARB obj);
extern GLvoid (APIENTRYP qglLinkProgramARB) (GLhandleARB programObj);
extern GLvoid (APIENTRYP qglUseProgramObjectARB) (GLhandleARB programObj);
extern GLvoid (APIENTRYP qglValidateProgramARB) (GLhandleARB programObj);
extern GLvoid (APIENTRYP qglUniform1fARB) (GLint location, GLfloat v0);
extern GLvoid (APIENTRYP qglUniform2fARB) (GLint location, GLfloat v0, GLfloat v1);
extern GLvoid (APIENTRYP qglUniform3fARB) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
extern GLvoid (APIENTRYP qglUniform4fARB) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
extern GLvoid (APIENTRYP qglUniform1iARB) (GLint location, GLint v0);
extern GLvoid (APIENTRYP qglUniform2iARB) (GLint location, GLint v0, GLint v1);
extern GLvoid (APIENTRYP qglUniform3iARB) (GLint location, GLint v0, GLint v1, GLint v2);
extern GLvoid (APIENTRYP qglUniform4iARB) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
extern GLvoid (APIENTRYP qglUniform1fvARB) (GLint location, GLsizei count, const GLfloat *value);
extern GLvoid (APIENTRYP qglUniform2fvARB) (GLint location, GLsizei count, const GLfloat *value);
extern GLvoid (APIENTRYP qglUniform3fvARB) (GLint location, GLsizei count, const GLfloat *value);
extern GLvoid (APIENTRYP qglUniform4fvARB) (GLint location, GLsizei count, const GLfloat *value);
extern GLvoid (APIENTRYP qglUniform1ivARB) (GLint location, GLsizei count, const GLint *value);
extern GLvoid (APIENTRYP qglUniform2ivARB) (GLint location, GLsizei count, const GLint *value);
extern GLvoid (APIENTRYP qglUniform3ivARB) (GLint location, GLsizei count, const GLint *value);
extern GLvoid (APIENTRYP qglUniform4ivARB) (GLint location, GLsizei count, const GLint *value);
extern GLvoid (APIENTRYP qglUniformMatrix2fvARB) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
extern GLvoid (APIENTRYP qglUniformMatrix3fvARB) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
extern GLvoid (APIENTRYP qglUniformMatrix4fvARB) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
extern GLvoid (APIENTRYP qglGetObjectParameterfvARB) (GLhandleARB obj, GLenum pname, GLfloat *params);
extern GLvoid (APIENTRYP qglGetObjectParameterivARB) (GLhandleARB obj, GLenum pname, GLint *params);
extern GLvoid (APIENTRYP qglGetInfoLogARB) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog);
extern GLvoid (APIENTRYP qglGetAttachedObjectsARB) (GLhandleARB containerObj, GLsizei maxCount, GLsizei *count,
GLhandleARB *obj);
extern GLint (APIENTRYP qglGetUniformLocationARB) (GLhandleARB programObj, const GLcharARB *name);
extern GLvoid (APIENTRYP qglGetActiveUniformARB) (GLhandleARB programObj, GLuint index, GLsizei maxLength,
GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);
extern GLvoid (APIENTRYP qglGetUniformfvARB) (GLhandleARB programObj, GLint location, GLfloat *params);
extern GLvoid (APIENTRYP qglGetUniformivARB) (GLhandleARB programObj, GLint location, GLint *params);
extern GLvoid (APIENTRYP qglGetShaderSourceARB) (GLhandleARB obj, GLsizei maxLength, GLsizei *length,
GLcharARB *source);
extern GLvoid (APIENTRYP qglVertexAttrib1fARB) (GLuint index, GLfloat v0);
extern GLvoid (APIENTRYP qglVertexAttrib1sARB) (GLuint index, GLshort v0);
extern GLvoid (APIENTRYP qglVertexAttrib1dARB) (GLuint index, GLdouble v0);
extern GLvoid (APIENTRYP qglVertexAttrib2fARB) (GLuint index, GLfloat v0, GLfloat v1);
extern GLvoid (APIENTRYP qglVertexAttrib2sARB) (GLuint index, GLshort v0, GLshort v1);
extern GLvoid (APIENTRYP qglVertexAttrib2dARB) (GLuint index, GLdouble v0, GLdouble v1);
extern GLvoid (APIENTRYP qglVertexAttrib3fARB) (GLuint index, GLfloat v0, GLfloat v1, GLfloat v2);
extern GLvoid (APIENTRYP qglVertexAttrib3sARB) (GLuint index, GLshort v0, GLshort v1, GLshort v2);
extern GLvoid (APIENTRYP qglVertexAttrib3dARB) (GLuint index, GLdouble v0, GLdouble v1, GLdouble v2);
extern GLvoid (APIENTRYP qglVertexAttrib4fARB) (GLuint index, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
extern GLvoid (APIENTRYP qglVertexAttrib4sARB) (GLuint index, GLshort v0, GLshort v1, GLshort v2, GLshort v3);
extern GLvoid (APIENTRYP qglVertexAttrib4dARB) (GLuint index, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3);
extern GLvoid (APIENTRYP qglVertexAttrib4NubARB) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
extern GLvoid (APIENTRYP qglVertexAttrib1fvARB) (GLuint index, GLfloat *v);
extern GLvoid (APIENTRYP qglVertexAttrib1svARB) (GLuint index, GLshort *v);
extern GLvoid (APIENTRYP qglVertexAttrib1dvARB) (GLuint index, GLdouble *v);
extern GLvoid (APIENTRYP qglVertexAttrib2fvARB) (GLuint index, GLfloat *v);
extern GLvoid (APIENTRYP qglVertexAttrib2svARB) (GLuint index, GLshort *v);
extern GLvoid (APIENTRYP qglVertexAttrib2dvARB) (GLuint index, GLdouble *v);
extern GLvoid (APIENTRYP qglVertexAttrib3fvARB) (GLuint index, GLfloat *v);
extern GLvoid (APIENTRYP qglVertexAttrib3svARB) (GLuint index, GLshort *v);
extern GLvoid (APIENTRYP qglVertexAttrib3dvARB) (GLuint index, GLdouble *v);
extern GLvoid (APIENTRYP qglVertexAttrib4fvARB) (GLuint index, GLfloat *v);
extern GLvoid (APIENTRYP qglVertexAttrib4svARB) (GLuint index, GLshort *v);
extern GLvoid (APIENTRYP qglVertexAttrib4dvARB) (GLuint index, GLdouble *v);
extern GLvoid (APIENTRYP qglVertexAttrib4ivARB) (GLuint index, GLint *v);
extern GLvoid (APIENTRYP qglVertexAttrib4bvARB) (GLuint index, GLbyte *v);
extern GLvoid (APIENTRYP qglVertexAttrib4ubvARB) (GLuint index, GLubyte *v);
extern GLvoid (APIENTRYP qglVertexAttrib4usvARB) (GLuint index, GLushort *v);
extern GLvoid (APIENTRYP qglVertexAttrib4uivARB) (GLuint index, GLuint *v);
extern GLvoid (APIENTRYP qglVertexAttrib4NbvARB) (GLuint index, const GLbyte *v);
extern GLvoid (APIENTRYP qglVertexAttrib4NsvARB) (GLuint index, const GLshort *v);
extern GLvoid (APIENTRYP qglVertexAttrib4NivARB) (GLuint index, const GLint *v);
extern GLvoid (APIENTRYP qglVertexAttrib4NubvARB) (GLuint index, const GLubyte *v);
extern GLvoid (APIENTRYP qglVertexAttrib4NusvARB) (GLuint index, const GLushort *v);
extern GLvoid (APIENTRYP qglVertexAttrib4NuivARB) (GLuint index, const GLuint *v);
extern GLvoid (APIENTRYP qglVertexAttribPointerARB) (GLuint index, GLint size, GLenum type, GLboolean normalized,
GLsizei stride, const GLvoid *pointer);
extern GLvoid (APIENTRYP qglEnableVertexAttribArrayARB) (GLuint index);
extern GLvoid (APIENTRYP qglDisableVertexAttribArrayARB) (GLuint index);
extern GLvoid (APIENTRYP qglBindAttribLocationARB) (GLhandleARB programObj, GLuint index, const GLcharARB *name);
extern GLvoid (APIENTRYP qglGetActiveAttribARB) (GLhandleARB programObj, GLuint index, GLsizei maxLength,
GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);
extern GLint (APIENTRYP qglGetAttribLocationARB) (GLhandleARB programObj, const GLcharARB *name);
extern GLvoid (APIENTRYP qglGetVertexAttribdvARB) (GLuint index, GLenum pname, GLdouble *params);
extern GLvoid (APIENTRYP qglGetVertexAttribfvARB) (GLuint index, GLenum pname, GLfloat *params);
extern GLvoid (APIENTRYP qglGetVertexAttribivARB) (GLuint index, GLenum pname, GLint *params);
extern GLvoid (APIENTRYP qglGetVertexAttribPointervARB) (GLuint index, GLenum pname, GLvoid **pointer);
#endif
|
pelya/openarena-engine
|
code/renderer_oa/qgl_extra.h
|
C
|
gpl-2.0
| 9,257
|
define([
'taoQtiItem/qtiCreator/widgets/states/factory',
'taoQtiItem/qtiCreator/widgets/interactions/states/Answer',
'taoQtiItem/qtiCreator/widgets/interactions/helpers/answerState'
], function(stateFactory, Answer, answerStateHelper){
var ChoiceInteractionStateAnswer = stateFactory.extend(Answer, function(){
//forward to one of the available sub state, according to the response processing template
answerStateHelper.forward(this.widget);
}, function(){
});
return ChoiceInteractionStateAnswer;
});
|
swapnilaptara/tao-aptara-assess
|
taoQtiItem/views/js/qtiCreator/widgets/interactions/choiceInteraction/states/Answer.js
|
JavaScript
|
gpl-2.0
| 578
|
@extends('Home._main')
@section('content')
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
论坛
<small>Forum</small>
</h1>
</section>
<!-- Main content -->
<section class="content">
<!-- Main row -->
<div class="row">
<!-- Left col -->
<div class="col-md-8">
<!-- TABLE: LATEST ITEMS -->
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title">{{$topic->title}}</h3>
</div><!-- /.box-header -->
<div class="box-body">
<p>作者: {{ $topic->belongsToUser['name'] }}
节点 <a href="{{ url('/forum/node/'.$topic->belongsToNode['id'] ) }}">{{ $topic->belongsToNode['name'] }}</a>
</p>
<p>{{ $topic->body }}</p>
</div><!-- /.box-body -->
<div class="box-footer clearfix">
@foreach ($topic->Posts as $post)
<p><a href="{{ URL('/user/show/'.$post->user_id) }}" >{{ $post->belongsToUser['name'] }} </a>发表于:{{ $post->created_at }}</p>
<p>{{ $post->body }}</p>
@endforeach
@if(Auth::guest())
<p>请<a href="{{ URL('/auth/login') }}">登录</a>后回帖</p>
@else
<form action="{{ URL('forum/post') }}" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="topic_id" value="{{ $topic->id }}">
<div class="form-group">
<label>回帖</label>
<textarea class="form-control" name="body" rows="3"></textarea>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">回帖</button>
</div>
</form>
@endif
</div><!-- /.box-footer -->
</div><!-- /.box -->
</div><!-- /.col -->
<div class="col-md-4">
<!-- PRODUCT LIST -->
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">其他信息</h3>
</div><!-- /.box-header -->
<div class="box-body">
<p>点击量{{$topic->view_count}}</p>
</div><!-- /.box-body -->
</div><!-- /.box -->
</div><!-- /.col -->
</div><!-- /.row -->
</section>
@endsection
|
orvice/xoDown
|
resources/views/Forum/show.blade.php
|
PHP
|
gpl-2.0
| 3,066
|
#ifndef DIV_H_
#define DIV_H_
#include "DoubleOperandQuadruple.h"
namespace codegen {
class Div: public DoubleOperandQuadruple {
public:
Div(std::string leftOperand, std::string rightOperand, std::string result);
virtual ~Div() = default;
void generateCode(AssemblyGenerator& generator) const override;
private:
void print(std::ostream& stream) const override;
};
} // namespace codegen
#endif // DIV_H_
|
rieske/trans
|
src/codegen/quadruples/Div.h
|
C
|
gpl-2.0
| 427
|
package org.quantumlabs.manicraft.state;
import org.apache.log4j.Logger;
import org.quantumlabs.manicraft.CoreEventLoop;
import org.quantumlabs.manicraft.ITransitionErrorHandler;
/**
* Created by quintus on 4/26/15.
*/
public class TransitionErrorState extends CoreEventLoop.State implements ITransitionErrorHandler {
public TransitionErrorState(CoreEventLoop eventLoop) {
super(eventLoop);
}
final static private Logger LOG = Logger.getLogger(TransitionErrorState.class);
@Override
public void handleTransitionError(CoreEventLoop eventLoop, Exception e) {
LOG.error("Transition error happen", e);
System.exit(-1);
}
@Override
public void run() {
//TODO
}
}
|
YudingZhou/Yo-Fatty
|
manicraft/src/main/java/org/quantumlabs/manicraft/state/TransitionErrorState.java
|
Java
|
gpl-2.0
| 733
|
/* Solution by Colin Barker (colin.barker@wanadoo.fr)
* using the driver from the solution by Paul Griffiths.
*/
/*
EX3_1.C
=======
Suggested solution to Exercise 3-1
*/
#include <stdio.h>
#include <time.h>
int binsearch(int x, int v[], int n); /* Original K&R function */
int binsearch2(int x, int v[], int n); /* Our new function */
#define MAX_ELEMENT 20000
/* Outputs approximation of processor time required
for our two binary search functions. We search for
the element -1, to time the functions' worst case
performance (i.e. element not found in test data) */
int main(void) {
int testdata[MAX_ELEMENT];
int index; /* Index of found element in test data */
int n = -1; /* Element to search for */
int i;
clock_t time_taken;
/* Initialize test data */
for ( i = 0; i < MAX_ELEMENT; ++i )
testdata[i] = i;
/* Output approximation of time taken for
100,000 iterations of binsearch() */
for ( i = 0, time_taken = clock(); i < 100000; ++i ) {
index = binsearch(n, testdata, MAX_ELEMENT);
}
time_taken = clock() - time_taken;
if ( index < 0 )
printf("Element %d not found.\n", n);
else
printf("Element %d found at index %d.\n", n, index);
printf("binsearch() took %lu clocks (%lu seconds)\n",
(unsigned long) time_taken,
(unsigned long) time_taken / CLOCKS_PER_SEC);
/* Output approximation of time taken for
100,000 iterations of binsearch2() */
for ( i = 0, time_taken = clock(); i < 100000; ++i ) {
index = binsearch2(n, testdata, MAX_ELEMENT);
}
time_taken = clock() - time_taken;
if ( index < 0 )
printf("Element %d not found.\n", n);
else
printf("Element %d found at index %d.\n", n, index);
printf("binsearch2() took %lu clocks (%lu seconds)\n",
(unsigned long) time_taken,
(unsigned long) time_taken / CLOCKS_PER_SEC);
return 0;
}
/* Performs a binary search for element x
in array v[], which has n elements */
int binsearch(int x, int v[], int n) {
int low, mid, high;
low = 0;
high = n - 1;
while ( low <= high ) {
mid = (low+high) / 2;
if ( x < v[mid] )
high = mid - 1;
else if ( x > v[mid] )
low = mid + 1;
else
return mid;
}
return -1;
}
int binsearch2(int x, int v[], int n)
{
int low, high, mid;
low = -1;
high = n;
while (low + 1 < high) {
mid = (low + high) / 2;
if (v[mid] < x)
low = mid;
else
high = mid;
}
if (high == n || v[high] != x)
return -1;
else
return high;
}
|
mikephp/basic_data_struct
|
example/C Programming Code/krx30101.c
|
C
|
gpl-2.0
| 2,822
|
<?php
//////////////////////////////////
// UserApplePie Version: 1.1.1 //
// http://www.userapplepie.com //
// UserCake Version: 2.0.2 //
// http://usercake.com //
//////////////////////////////////
// Security Feature to Disallow File to be opened directly.
// Only allows this file to be include by index.php
if(!defined('Page_Protection')){header("Location: ../");exit();}
// Check to make sure current user is logged in and a site admin
if(isUserLoggedIn() && is_admin()){
// Page header
echo "
<!-- Page Heading -->
<div class='row'>
<div class='col-lg-12'>
<h1 class='page-header'>
$websiteName - Support Tickets
</h1>
<ol class='breadcrumb'>
<li>
<i class='glyphicon glyphicon-cog'></i> Admin Panel
</li>
<li class='active'>
<i class='glyphicon glyphicon-info-sign'></i> Support Tickets
</li>
</ol>
</div>
</div>
<!-- /.row -->
";
//Check to see is site is demo site. If so disable editing.
if($cur_server_name_dc == $demo_server_name_dc){
err_message("Demo Site : Editing Disabled");
}
$query = "SELECT * FROM ".$db_table_prefix."report";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $query)
or die ("Couldn't ececute query. Reports 43666");
//HTML Stuff
while ($row = mysqli_fetch_array($result))
{
$bgcolor = "epboxa";
extract($row);
$report_msg = stripslashes($report_msg);
echo "<div class='panel panel-body panel-default'>";
echo "<b>Reporter</b>: $report_user ($report_userID) - <b>Type</b>: $report_type";
echo "<br><a href='$report_pageURL' target='_blank'>$report_pageURL</a>";
echo "<div class='well well-sm'>$report_msg</div>";
echo "
<form method=\"post\" action=\"${site_url_link}UAP_Admin_Panel/delete_report/ \">
<input type=\"hidden\" name=\"report_id\" value=\"$report_id\">
<input type=\"submit\" value=\"Delete!\" class='btn btn-danger btn-sm'/>
</form>
";
echo "</div>";
}
}
?>
|
davarravad/UserApplePie
|
external/admin/reports.php
|
PHP
|
gpl-2.0
| 2,213
|
/*
* Asterisk -- An open source telephony toolkit.
*
* Copyright (C) 1999 - 2006, Digium, Inc.
*
* Mark Spencer <markster@digium.com>
*
* See http://www.asterisk.org for more information about
* the Asterisk project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, mailing lists and IRC
* channels for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*! \file
* \brief String manipulation functions
*/
#ifndef _ASTERISK_STRINGS_H
#define _ASTERISK_STRINGS_H
#include "asterisk/inline_api.h"
#include "asterisk/utils.h"
#include "asterisk/threadstorage.h"
/* You may see casts in this header that may seem useless but they ensure this file is C++ clean */
#ifdef AST_DEVMODE
#define ast_strlen_zero(foo) _ast_strlen_zero(foo, __FILE__, __PRETTY_FUNCTION__, __LINE__)
static force_inline int _ast_strlen_zero(const char *s, const char *file, const char *function, int line)
{
if (!s || (*s == '\0')) {
return 1;
}
if (!strcmp(s, "(null)")) {
ast_log(__LOG_WARNING, file, line, function, "Possible programming error: \"(null)\" is not NULL!\n");
}
return 0;
}
#else
static force_inline int ast_strlen_zero(const char *s)
{
return (!s || (*s == '\0'));
}
#endif
/*! \brief returns the equivalent of logic or for strings:
* first one if not empty, otherwise second one.
*/
#define S_OR(a, b) (!ast_strlen_zero(a) ? (a) : (b))
/*! \brief returns the equivalent of logic or for strings, with an additional boolean check:
* second one if not empty and first one is true, otherwise third one.
* example: S_COR(usewidget, widget, "<no widget>")
*/
#define S_COR(a, b, c) ((a && !ast_strlen_zero(b)) ? (b) : (c))
/*!
\brief Gets a pointer to the first non-whitespace character in a string.
\param ast_skip_blanks function being used
\arg str the input string
\return a pointer to the first non-whitespace character
*/
AST_INLINE_API(
char *ast_skip_blanks(const char *str),
{
while (*str && ((unsigned char) *str) < 33)
str++;
return (char *)str;
}
)
/*!
\brief Trims trailing whitespace characters from a string.
\param ast_skip_blanks function being used
\arg str the input string
\return a pointer to the modified string
*/
AST_INLINE_API(
char *ast_trim_blanks(char *str),
{
char *work = str;
if (work) {
work += strlen(work) - 1;
/* It's tempting to only want to erase after we exit this loop,
but since ast_trim_blanks *could* receive a constant string
(which we presumably wouldn't have to touch), we shouldn't
actually set anything unless we must, and it's easier just
to set each position to \0 than to keep track of a variable
for it */
while ((work >= str) && ((unsigned char) *work) < 33)
*(work--) = '\0';
}
return str;
}
)
/*!
\brief Gets a pointer to first whitespace character in a string.
\param ast_skip_noblanks function being used
\arg str the input string
\return a pointer to the first whitespace character
*/
AST_INLINE_API(
char *ast_skip_nonblanks(char *str),
{
while (*str && ((unsigned char) *str) > 32)
str++;
return str;
}
)
/*!
\brief Strip leading/trailing whitespace from a string.
\param ast_strip function ast_strip being used.
\arg s The string to be stripped (will be modified).
\return The stripped string.
This functions strips all leading and trailing whitespace
characters from the input string, and returns a pointer to
the resulting string. The string is modified in place.
*/
AST_INLINE_API(
char *ast_strip(char *s),
{
s = ast_skip_blanks(s);
if (s)
ast_trim_blanks(s);
return s;
}
)
/*!
\brief Strip leading/trailing whitespace and quotes from a string.
\param s The string to be stripped (will be modified).
\param beg_quotes The list of possible beginning quote characters.
\param end_quotes The list of matching ending quote characters.
\return The stripped string.
This functions strips all leading and trailing whitespace
characters from the input string, and returns a pointer to
the resulting string. The string is modified in place.
It can also remove beginning and ending quote (or quote-like)
characters, in matching pairs. If the first character of the
string matches any character in beg_quotes, and the last
character of the string is the matching character in
end_quotes, then they are removed from the string.
Examples:
\code
ast_strip_quoted(buf, "\"", "\"");
ast_strip_quoted(buf, "'", "'");
ast_strip_quoted(buf, "[{(", "]})");
\endcode
*/
char *ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes);
/*!
\brief Strip backslash for "escaped" semicolons,
the string to be stripped (will be modified).
\return The stripped string.
*/
char *ast_unescape_semicolon(char *s);
/*!
\brief Convert some C escape sequences \verbatim (\b\f\n\r\t) \endverbatim into the
equivalent characters. The string to be converted (will be modified).
\return The converted string.
*/
char *ast_unescape_c(char *s);
/*!
\brief Size-limited null-terminating string copy.
\arg dst The destination buffer.
\arg src The source string
\arg size The size of the destination buffer
\return Nothing.
This is similar to \a strncpy, with two important differences:
- the destination buffer will \b always be null-terminated
- the destination buffer is not filled with zeros past the copied string length
These differences make it slightly more efficient, and safer to use since it will
not leave the destination buffer unterminated. There is no need to pass an artificially
reduced buffer size to this function (unlike \a strncpy), and the buffer does not need
to be initialized to zeroes prior to calling this function.
*/
AST_INLINE_API(
void ast_copy_string(char *dst, const char *src, size_t size),
{
while (*src && size) {
*dst++ = *src++;
size--;
}
if (__builtin_expect(!size, 0))
dst--;
*dst = '\0';
}
)
/*!
\brief Build a string in a buffer, designed to be called repeatedly
\note This method is not recommended. New code should use ast_str_*() instead.
This is a wrapper for snprintf, that properly handles the buffer pointer
and buffer space available.
\arg buffer current position in buffer to place string into (will be updated on return)
\arg space remaining space in buffer (will be updated on return)
\arg fmt printf-style format string
\retval 0 on success
\retval non-zero on failure.
*/
int ast_build_string(char **buffer, size_t *space, const char *fmt, ...) __attribute__ ((format (printf, 3, 4)));
/*!
\brief Build a string in a buffer, designed to be called repeatedly
This is a wrapper for snprintf, that properly handles the buffer pointer
and buffer space available.
\return 0 on success, non-zero on failure.
\param buffer current position in buffer to place string into (will be updated on return)
\param space remaining space in buffer (will be updated on return)
\param fmt printf-style format string
\param ap varargs list of arguments for format
*/
int ast_build_string_va(char **buffer, size_t *space, const char *fmt, va_list ap) __attribute__((format (printf, 3, 0)));
/*!
* \brief Make sure something is true.
* Determine if a string containing a boolean value is "true".
* This function checks to see whether a string passed to it is an indication of an "true" value.
* It checks to see if the string is "yes", "true", "y", "t", "on" or "1".
*
* \retval 0 if val is a NULL pointer.
* \retval -1 if "true".
* \retval 0 otherwise.
*/
int ast_true(const char *val);
/*!
* \brief Make sure something is false.
* Determine if a string containing a boolean value is "false".
* This function checks to see whether a string passed to it is an indication of an "false" value.
* It checks to see if the string is "no", "false", "n", "f", "off" or "0".
*
* \retval 0 if val is a NULL pointer.
* \retval -1 if "true".
* \retval 0 otherwise.
*/
int ast_false(const char *val);
/*
* \brief Join an array of strings into a single string.
* \param s the resulting string buffer
* \param len the length of the result buffer, s
* \param w an array of strings to join.
*
* This function will join all of the strings in the array 'w' into a single
* string. It will also place a space in the result buffer in between each
* string from 'w'.
*/
void ast_join(char *s, size_t len, char * const w[]);
/*
\brief Parse a time (integer) string.
\param src String to parse
\param dst Destination
\param _default Value to use if the string does not contain a valid time
\param consumed The number of characters 'consumed' in the string by the parse (see 'man sscanf' for details)
\retval 0 on success
\retval non-zero on failure.
*/
int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed);
/*
\brief Parse a time (float) string.
\param src String to parse
\param dst Destination
\param _default Value to use if the string does not contain a valid time
\param consumed The number of characters 'consumed' in the string by the parse (see 'man sscanf' for details)
\return zero on success, non-zero on failure
*/
int ast_get_timeval(const char *src, struct timeval *tv, struct timeval _default, int *consumed);
/*!
* Support for dynamic strings.
*
* A dynamic string is just a C string prefixed by a few control fields
* that help setting/appending/extending it using a printf-like syntax.
*
* One should never declare a variable with this type, but only a pointer
* to it, e.g.
*
* struct ast_str *ds;
*
* The pointer can be initialized with the following:
*
* ds = ast_str_create(init_len);
* creates a malloc()'ed dynamic string;
*
* ds = ast_str_alloca(init_len);
* creates a string on the stack (not very dynamic!).
*
* ds = ast_str_thread_get(ts, init_len)
* creates a malloc()'ed dynamic string associated to
* the thread-local storage key ts
*
* Finally, the string can be manipulated with the following:
*
* ast_str_set(&buf, max_len, fmt, ...)
* ast_str_append(&buf, max_len, fmt, ...)
*
* and their varargs variant
*
* ast_str_set_va(&buf, max_len, ap)
* ast_str_append_va(&buf, max_len, ap)
*
* \arg max_len The maximum allowed length, reallocating if needed.
* 0 means unlimited, -1 means "at most the available space"
*
* \return All the functions return <0 in case of error, or the
* length of the string added to the buffer otherwise.
*/
/*! \brief The descriptor of a dynamic string
* XXX storage will be optimized later if needed
* We use the ts field to indicate the type of storage.
* Three special constants indicate malloc, alloca() or static
* variables, all other values indicate a
* struct ast_threadstorage pointer.
*/
struct ast_str {
size_t len; /*!< The current maximum length of the string */
size_t used; /*!< Amount of space used */
struct ast_threadstorage *ts; /*!< What kind of storage is this ? */
#define DS_MALLOC ((struct ast_threadstorage *)1)
#define DS_ALLOCA ((struct ast_threadstorage *)2)
#define DS_STATIC ((struct ast_threadstorage *)3) /* not supported yet */
char str[0]; /*!< The string buffer */
};
/*!
* \brief Create a malloc'ed dynamic length string
*
* \arg init_len This is the initial length of the string buffer
*
* \return This function returns a pointer to the dynamic string length. The
* result will be NULL in the case of a memory allocation error.
*
* \note The result of this function is dynamically allocated memory, and must
* be free()'d after it is no longer needed.
*/
AST_INLINE_API(
struct ast_str * attribute_malloc ast_str_create(size_t init_len),
{
struct ast_str *buf;
buf = (struct ast_str *)ast_calloc(1, sizeof(*buf) + init_len);
if (buf == NULL)
return NULL;
buf->len = init_len;
buf->used = 0;
buf->ts = DS_MALLOC;
return buf;
}
)
/*! \brief Reset the content of a dynamic string.
* Useful before a series of ast_str_append.
*/
AST_INLINE_API(
void ast_str_reset(struct ast_str *buf),
{
if (buf) {
buf->used = 0;
if (buf->len)
buf->str[0] = '\0';
}
}
)
/*
* AST_INLINE_API() is a macro that takes a block of code as an argument.
* Using preprocessor #directives in the argument is not supported by all
* compilers, and it is a bit of an obfuscation anyways, so avoid it.
* As a workaround, define a macro that produces either its argument
* or nothing, and use that instead of #ifdef/#endif within the
* argument to AST_INLINE_API().
*/
#if defined(DEBUG_THREADLOCALS)
#define _DB1(x) x
#else
#define _DB1(x)
#endif
/*!
* Make space in a new string (e.g. to read in data from a file)
*/
AST_INLINE_API(
int ast_str_make_space(struct ast_str **buf, size_t new_len),
{
_DB1(struct ast_str *old_buf = *buf;)
if (new_len <= (*buf)->len)
return 0; /* success */
if ((*buf)->ts == DS_ALLOCA || (*buf)->ts == DS_STATIC)
return -1; /* cannot extend */
*buf = (struct ast_str *)ast_realloc(*buf, new_len + sizeof(struct ast_str));
if (*buf == NULL) /* XXX watch out, we leak memory here */
return -1;
if ((*buf)->ts != DS_MALLOC) {
pthread_setspecific((*buf)->ts->key, *buf);
_DB1(__ast_threadstorage_object_replace(old_buf, *buf, new_len + sizeof(struct ast_str));)
}
(*buf)->len = new_len;
return 0;
}
)
#define ast_str_alloca(init_len) \
({ \
struct ast_str *buf; \
buf = alloca(sizeof(*buf) + init_len); \
buf->len = init_len; \
buf->used = 0; \
buf->ts = DS_ALLOCA; \
buf->str[0] = '\0'; \
(buf); \
})
/*!
* \brief Retrieve a thread locally stored dynamic string
*
* \arg ts This is a pointer to the thread storage structure declared by using
* the AST_THREADSTORAGE macro. If declared with
* AST_THREADSTORAGE(my_buf, my_buf_init), then this argument would be
* (&my_buf).
* \arg init_len This is the initial length of the thread's dynamic string. The
* current length may be bigger if previous operations in this thread have
* caused it to increase.
*
* \return This function will return the thread locally stored dynamic string
* associated with the thread storage management variable passed as the
* first argument.
* The result will be NULL in the case of a memory allocation error.
*
* Example usage:
* \code
* AST_THREADSTORAGE(my_str, my_str_init);
* #define MY_STR_INIT_SIZE 128
* ...
* void my_func(const char *fmt, ...)
* {
* struct ast_str *buf;
*
* if (!(buf = ast_str_thread_get(&my_str, MY_STR_INIT_SIZE)))
* return;
* ...
* }
* \endcode
*/
#if !defined(DEBUG_THREADLOCALS)
AST_INLINE_API(
struct ast_str *ast_str_thread_get(struct ast_threadstorage *ts,
size_t init_len),
{
struct ast_str *buf;
buf = (struct ast_str *)ast_threadstorage_get(ts, sizeof(*buf) + init_len);
if (buf == NULL)
return NULL;
if (!buf->len) {
buf->len = init_len;
buf->used = 0;
buf->ts = ts;
}
return buf;
}
)
#else /* defined(DEBUG_THREADLOCALS) */
AST_INLINE_API(
struct ast_str *__ast_str_thread_get(struct ast_threadstorage *ts,
size_t init_len, const char *file, const char *function, unsigned int line),
{
struct ast_str *buf;
buf = (struct ast_str *)__ast_threadstorage_get(ts, sizeof(*buf) + init_len, file, function, line);
if (buf == NULL)
return NULL;
if (!buf->len) {
buf->len = init_len;
buf->used = 0;
buf->ts = ts;
}
return buf;
}
)
#define ast_str_thread_get(ts, init_len) __ast_str_thread_get(ts, init_len, __FILE__, __PRETTY_FUNCTION__, __LINE__)
#endif /* defined(DEBUG_THREADLOCALS) */
/*!
* \brief Error codes from __ast_str_helper()
* The undelying processing to manipulate dynamic string is done
* by __ast_str_helper(), which can return a success, a
* permanent failure (e.g. no memory), or a temporary one (when
* the string needs to be reallocated, and we must run va_start()
* again; XXX this convoluted interface is only here because
* FreeBSD 4 lacks va_copy, but this will be fixed and the
* interface simplified).
*/
enum {
/*! An error has occured and the contents of the dynamic string
* are undefined */
AST_DYNSTR_BUILD_FAILED = -1,
/*! The buffer size for the dynamic string had to be increased, and
* __ast_str_helper() needs to be called again after
* a va_end() and va_start().
*/
AST_DYNSTR_BUILD_RETRY = -2
};
/*!
* \brief Set a dynamic string from a va_list
*
* \arg buf This is the address of a pointer to a struct ast_str.
* If it is retrieved using ast_str_thread_get, the
struct ast_threadstorage pointer will need to
* be updated in the case that the buffer has to be reallocated to
* accommodate a longer string than what it currently has space for.
* \arg max_len This is the maximum length to allow the string buffer to grow
* to. If this is set to 0, then there is no maximum length.
* \arg fmt This is the format string (printf style)
* \arg ap This is the va_list
*
* \return The return value of this function is the same as that of the printf
* family of functions.
*
* Example usage (the first part is only for thread-local storage)
* \code
* AST_THREADSTORAGE(my_str, my_str_init);
* #define MY_STR_INIT_SIZE 128
* ...
* void my_func(const char *fmt, ...)
* {
* struct ast_str *buf;
* va_list ap;
*
* if (!(buf = ast_str_thread_get(&my_str, MY_STR_INIT_SIZE)))
* return;
* ...
* va_start(fmt, ap);
* ast_str_set_va(&buf, 0, fmt, ap);
* va_end(ap);
*
* printf("This is the string we just built: %s\n", buf->str);
* ...
* }
* \endcode
*
* \note: the following two functions must be implemented as macros
* because we must do va_end()/va_start() on the original arguments.
*/
#define ast_str_set_va(buf, max_len, fmt, ap) \
({ \
int __res; \
while ((__res = __ast_str_helper(buf, max_len, \
0, fmt, ap)) == AST_DYNSTR_BUILD_RETRY) { \
va_end(ap); \
va_start(ap, fmt); \
} \
(__res); \
})
/*!
* \brief Append to a dynamic string using a va_list
*
* Same as ast_str_set_va(), but append to the current content.
*/
#define ast_str_append_va(buf, max_len, fmt, ap) \
({ \
int __res; \
while ((__res = __ast_str_helper(buf, max_len, \
1, fmt, ap)) == AST_DYNSTR_BUILD_RETRY) { \
va_end(ap); \
va_start(ap, fmt); \
} \
(__res); \
})
/*!
* \brief Core functionality of ast_str_(set|append)_va
*
* The arguments to this function are the same as those described for
* ast_str_set_va except for an addition argument, append.
* If append is non-zero, this will append to the current string instead of
* writing over it.
*
* In the case that this function is called and the buffer was not large enough
* to hold the result, the partial write will be truncated, and the result
* AST_DYNSTR_BUILD_RETRY will be returned to indicate that the buffer size
* was increased, and the function should be called a second time.
*
* A return of AST_DYNSTR_BUILD_FAILED indicates a memory allocation error.
*
* A return value greater than or equal to zero indicates the number of
* characters that have been written, not including the terminating '\0'.
* In the append case, this only includes the number of characters appended.
*
* \note This function should never need to be called directly. It should
* through calling one of the other functions or macros defined in this
* file.
*/
int __ast_str_helper(struct ast_str **buf, size_t max_len,
int append, const char *fmt, va_list ap);
/*!
* \brief Set a dynamic string using variable arguments
*
* \arg buf This is the address of a pointer to a struct ast_str which should
* have been retrieved using ast_str_thread_get. It will need to
* be updated in the case that the buffer has to be reallocated to
* accomodate a longer string than what it currently has space for.
* \arg max_len This is the maximum length to allow the string buffer to grow
* to. If this is set to 0, then there is no maximum length.
* If set to -1, we are bound to the current maximum length.
* \arg fmt This is the format string (printf style)
*
* \return The return value of this function is the same as that of the printf
* family of functions.
*
* All the rest is the same as ast_str_set_va()
*/
AST_INLINE_API(
int __attribute__ ((format (printf, 3, 4))) ast_str_set(
struct ast_str **buf, size_t max_len, const char *fmt, ...),
{
int res;
va_list ap;
va_start(ap, fmt);
res = ast_str_set_va(buf, max_len, fmt, ap);
va_end(ap);
return res;
}
)
/*!
* \brief Append to a thread local dynamic string
*
* The arguments, return values, and usage of this function are the same as
* ast_str_set(), but the new data is appended to the current value.
*/
AST_INLINE_API(
int __attribute__ ((format (printf, 3, 4))) ast_str_append(
struct ast_str **buf, size_t max_len, const char *fmt, ...),
{
int res;
va_list ap;
va_start(ap, fmt);
res = ast_str_append_va(buf, max_len, fmt, ap);
va_end(ap);
return res;
}
)
/*!
* \brief Compute a hash value on a string
*
* This famous hash algorithm was written by Dan Bernstein and is
* commonly used.
*
* http://www.cse.yorku.ca/~oz/hash.html
*/
static force_inline int ast_str_hash(const char *str)
{
int hash = 5381;
while (*str)
hash = hash * 33 ^ *str++;
return abs(hash);
}
#endif /* _ASTERISK_STRINGS_H */
|
nicwolff/asterisk-agi-mp3
|
include/asterisk/strings.h
|
C
|
gpl-2.0
| 21,633
|
#!/bin/bash
ps auxw | grep start-pigtail | grep -v grep | awk '{print $2}' | xargs kill -9
|
pauloangelo/hogzilla
|
scripts/hz-utils/stop-pigtail.sh
|
Shell
|
gpl-2.0
| 93
|
using System;
using System.Linq;
using System.Collections.Generic;
using CrimeMap.Core.Domain;
namespace CrimeMap.Domain.Model.Users {
public class User : AggregateRoot {
private ICollection<Account> _externalAccounts;
public string Name { get; private set; }
public string Password { get; private set; }
public string PasswordSalt { get; private set; }
public string Email { get; private set; }
public ICollection<Account> Accounts {
get { return _externalAccounts ?? (_externalAccounts = new List<Account>()); }
private set { _externalAccounts = value; }
}
public User() {
RegisterEvents();
}
public User(Guid id, string name, string email, string password, string passwordSalt, string passwordFormat) {
RegisterEvents();
var @event = new UserCreatedEvent(id, name, email, password, passwordSalt);
RaiseEvent(@event);
}
public User(Guid id, string name, string email, string provider, string providerKey) {
RegisterEvents();
var @event = new ExternalUserCreatedEvent(id, name, email, provider, providerKey);
RaiseEvent(@event);
}
public void AddExternalLogin(string provider, string providerKey) {
if (string.IsNullOrEmpty(provider))
throw new ArgumentNullException("provider");
if (string.IsNullOrEmpty(providerKey))
throw new ArgumentNullException("providerKey");
if (Accounts != null && Accounts.Any() && Accounts.Any(x => x.Provider.Equals(provider) && x.ProviderKey.Equals(providerKey))) {
throw new DomainException("User already contains a login for provider {0}.", provider);
}
var @event = new ExternalAccountAddedEvent(provider, providerKey);
RaiseEvent(@event);
}
private void RegisterEvents() {
RegisterEvent<UserCreatedEvent>(OnCreated);
RegisterEvent<ExternalUserCreatedEvent>(OnExternalCreated);
RegisterEvent<ExternalAccountAddedEvent>(OnExternalAccountAdded);
}
void OnCreated(UserCreatedEvent @event) {
Id = @event.Id;
Name = @event.Name;
Email = @event.Email;
Password = @event.Password;
PasswordSalt = @event.PasswordSalt;
Accounts = new List<Account>();
}
void OnExternalCreated(ExternalUserCreatedEvent @event) {
Id = @event.Id;
Name = @event.Name;
Email = @event.Email;
var account = new Account(@event.Provider, @event.ProviderKey);
Accounts.Add(account);
}
void OnExternalAccountAdded(ExternalAccountAddedEvent @event) {
var account = new Account(@event.Provider, @event.ProviderKey);
Accounts.Add(account);
}
}
}
|
vitorsalgado/crap
|
cqrs/crime-map/src/CrimeMap.Domain/Users/User.cs
|
C#
|
gpl-2.0
| 2,521
|
<?php
namespace Hosteam\Bundle\ExtranetBundle\Controller;
#use Hosteam\Bundle\ExtranetBundle\Entity\Customer;
#use Hosteam\Bundle\ExtranetBundle\Entity\User;
#use Hosteam\Bundle\ExtranetBundle\Entity\Service;
#use Doctrine\Common\Collections\ArrayCollection;
#use LdapTools\Configuration;
#use LdapTools\Exception\LdapBindException;
#use LdapTools\LdapManager;
#use LdapTools\Object\LdapObjectType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
#use Symfony\Component\Intl\Intl;
class BackofficeController extends Controller
{
/**
* @Route("/backoffice/", name="backoffice")
* @Template()
*/
public function indexAction()
{
return array();
}
}
|
hlepesant/miniextranet
|
extranet/src/Hosteam/Bundle/ExtranetBundle/Controller/BackofficeController.php
|
PHP
|
gpl-2.0
| 873
|
<!DOCTYPE html>
<html>
<!-- Mirrored from www.w3schools.com/php/demo_func_math_round2.php by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:36:10 GMT -->
<body>
4.97<br>7.05<br>7.06
</body>
<!-- Mirrored from www.w3schools.com/php/demo_func_math_round2.php by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:36:10 GMT -->
</html>
|
platinhom/ManualHom
|
Coding/W3School/W3Schools_Offline_2015/www.w3schools.com/php/demo_func_math_round2.html
|
HTML
|
gpl-2.0
| 359
|
$packageName = 'ut-launcher'
$url = 'https://ut.rushbase.net/rush/UTLauncher/UTLauncher-0.3.0.zip'
$unzipLocation = $(Split-Path -parent $MyInvocation.MyCommand.Definition)
$executable = "UTLauncher.exe"
$shortcut_to_modify = "$Home\Desktop\UTLauncher.exe.lnk"
$shortcut_modified = "$Home\Desktop\UTLauncher.lnk"
Install-ChocolateyZipPackage $packageName $url $unzipLocation
$targetFilePath = "$unzipLocation\$executable"
Install-ChocolateyDesktopLink $targetFilePath
Rename-Item $shortcut_to_modify $shortcut_modified
|
dtgm/chocolatey-packages-adgellida
|
_output/ut-launcher/0.3.0/tools/chocolateyInstall.ps1
|
PowerShell
|
gpl-2.0
| 567
|
/**
* Copyright (C) 2002-2022 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol 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.
*
* FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.client.gui.panel;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import javax.swing.AbstractCellEditor;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.ListCellRenderer;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.control.PreGameController;
import net.sf.freecol.client.gui.GUI;
import net.sf.freecol.client.gui.action.ColopediaAction.PanelType;
import net.sf.freecol.client.gui.plaf.FreeColComboBoxRenderer;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.EuropeanNationType;
import net.sf.freecol.common.model.Nation;
import net.sf.freecol.common.model.NationOptions;
import net.sf.freecol.common.model.NationOptions.Advantages;
import net.sf.freecol.common.model.NationOptions.NationState;
import net.sf.freecol.common.model.NationType;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Specification;
import net.sf.freecol.common.model.StringTemplate;
import static net.sf.freecol.common.util.CollectionUtils.*;
/**
* The table of players.
*/
public final class PlayersTable extends JTable {
/**
* A table cell editor that can be used to select a nation.
*/
private static class AdvantageCellEditor extends DefaultCellEditor {
private final JComboBox<EuropeanNationType> box;
/**
* Internal constructor.
*
* @param box The {@code JComboBox} to edit.
*/
private AdvantageCellEditor(JComboBox<EuropeanNationType> box) {
super(box);
this.box = box;
}
/**
* A standard constructor.
*
* @param nationTypes The list of {@code EuropeanNationType}s.
*/
public AdvantageCellEditor(List<EuropeanNationType> nationTypes) {
this(new JComboBox<>(nationTypes
.toArray(new EuropeanNationType[0])));
this.box.setRenderer(new FreeColComboBoxRenderer<EuropeanNationType>());
}
// Implement DefaultCellEditor
/**
* {@inheritDoc}
*/
@Override
public Object getCellEditorValue() {
return ((JComboBox)getComponent()).getSelectedItem();
}
}
private static class AdvantageCellRenderer extends JLabel
implements TableCellRenderer {
/** The national advantages type. */
private final Advantages advantages;
/**
* The default constructor.
*
* @param advantages The type of national {@code Advantages}.
*/
public AdvantageCellRenderer(Advantages advantages) {
this.advantages = advantages;
}
// Implement TableCellRenderer
/**
* {@inheritDoc}
*/
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
final Player player = (Player)table.getValueAt(row,
PlayersTable.PLAYER_COLUMN);
final NationType nationType = ((Nation)table.getValueAt(row,
PlayersTable.NATION_COLUMN)).getType();
JLabel label;
switch (advantages) {
case SELECTABLE:
return Utility.localizedLabel(Messages.nameKey((player == null)
? nationType
: player.getNationType()));
case FIXED:
label = Utility.localizedLabel(Messages.nameKey(nationType));
break;
case NONE:
default:
label = Utility.localizedLabel("none");
break;
}
label.setForeground((player != null && player.isReady())
? Color.GRAY
: table.getForeground());
label.setBackground(table.getBackground());
Utility.localizeToolTip(this, StringTemplate
.key(advantages.getShortDescriptionKey()));
return label;
}
}
private static class AvailableCellRenderer extends JLabel
implements TableCellRenderer {
private final JComboBox<NationState> box
= new JComboBox<>(NationState.values());
/**
* The default constructor.
*/
public AvailableCellRenderer() {
box.setRenderer(new NationStateRenderer());
}
// Implement TableCellRenderer
/**
* {@inheritDoc}
*/
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
if (value != null) { // FIXME: Why does this happen?
box.setSelectedItem(value);
final NationState nationState = (NationState)value;
Utility.localizeToolTip(box, StringTemplate
.key(nationState.getShortDescriptionKey()));
}
return box;
}
}
private final class AvailableCellEditor extends AbstractCellEditor
implements TableCellEditor {
private final JComboBox<NationState> aiStateBox
= new JComboBox<>(new NationState[] {
NationState.AI_ONLY,
NationState.NOT_AVAILABLE
});
private final JComboBox<NationState> allStateBox
= new JComboBox<>(NationState.values());
private JComboBox<NationState> activeBox = null;
public AvailableCellEditor() {
ActionListener listener = (ActionEvent ae) -> {
stopCellEditing();
};
aiStateBox.setRenderer(new NationStateRenderer());
aiStateBox.addActionListener(listener);
allStateBox.setRenderer(new NationStateRenderer());
allStateBox.addActionListener(listener);
}
private JComboBox<NationState> getActiveBox(int row) {
NationType nationType = ((Nation) getValueAt(row, NATION_COLUMN))
.getType();
this.activeBox = (nationType instanceof EuropeanNationType)
? this.allStateBox
: this.aiStateBox;
return this.activeBox;
}
// Implement AbstractCellEditor
/**
* {@inheritDoc}
*/
@Override
public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int column) {
return getActiveBox(row);
}
/**
* {@inheritDoc}
*/
@Override
public Object getCellEditorValue() {
return (this.activeBox == null) ? null
: this.activeBox.getSelectedItem();
}
}
private static class HeaderListener extends MouseAdapter {
private final JTableHeader header;
private final HeaderRenderer renderer;
public HeaderListener(JTableHeader header, HeaderRenderer renderer) {
this.header = header;
this.renderer = renderer;
}
@Override
public void mousePressed(MouseEvent e) {
int col = header.columnAtPoint(e.getPoint());
renderer.setPressedColumn(col);
header.repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
renderer.setPressedColumn(HeaderRenderer.NO_COLUMN);
header.repaint();
}
}
private static class HeaderRenderer implements TableCellRenderer {
private static final int NO_COLUMN = -1;
private int pressedColumn = NO_COLUMN;
private final Component[] components;
public HeaderRenderer(Component... components) {
this.components = components;
}
// Implement TableCellEditor
/**
* {@inheritDoc}
*/
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
if (components[column] instanceof JButton) {
boolean isPressed = (column == pressedColumn);
((JButton)components[column]).getModel().setPressed(isPressed);
((JButton)components[column]).getModel().setArmed(isPressed);
}
return components[column];
}
public void setPressedColumn(int column) {
pressedColumn = column;
}
}
private class NationCellRenderer extends JLabel
implements TableCellRenderer {
// Implement TableCellEditor
/**
* {@inheritDoc}
*/
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
Nation nation = (Nation) value;
setText(Messages.message(StringTemplate.template("countryName")
.add("%nation%", Messages.nameKey(nation.getId()))));
setIcon(new ImageIcon(gui.getFixedImageLibrary()
.getUnscaledSmallerNationImage(nation)));
return this;
}
}
private static class NationStateRenderer extends JLabel
implements ListCellRenderer<NationState> {
// Implement ListCellEditor<NationState>
/**
* {@inheritDoc}
*/
@Override
public Component getListCellRendererComponent(JList<? extends NationState> list,
NationState value,
int index,
boolean isSelected,
boolean cellHasFocus) {
setText(Messages.getName(value));
return this;
}
}
private static class PlayerCellRenderer implements TableCellRenderer {
private final JLabel label = new JLabel();
private final JButton button = Utility.localizedButton("select");
public PlayerCellRenderer() {
label.setHorizontalAlignment(JLabel.CENTER);
Utility.padBorder(button, 5, 10, 5, 10);
}
// Implement TableCellRenderer
/**
* {@inheritDoc}
*/
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
Player player = (Player)value;
if (player == null) {
NationType nationType
= (NationType)table.getValueAt(row, ADVANTAGE_COLUMN);
if (nationType instanceof EuropeanNationType) {
NationState nationState = (NationState)table
.getValueAt(row, AVAILABILITY_COLUMN);
if (nationState == NationState.AVAILABLE) {
return button;
}
}
Nation nation = (Nation) table.getValueAt(row, NATION_COLUMN);
label.setText(nation.getRulerName());
} else {
label.setText(player.getName());
}
return label;
}
}
private static final class PlayerCellEditor extends AbstractCellEditor
implements TableCellEditor {
private final JButton button = Utility.localizedButton("select");
public PlayerCellEditor() {
button.addActionListener((ActionEvent ae) -> {
fireEditingStopped();
});
}
/**
* {@inheritDoc}
*/
@Override
public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int column) {
return button;
}
@Override
public Object getCellEditorValue() {
return Boolean.TRUE;
}
}
/**
* The TableModel for the players table.
*/
private static class PlayersTableModel extends AbstractTableModel {
private final PreGameController preGameController;
private final NationOptions nationOptions;
private final Player thisPlayer;
private final List<Nation> nations;
private final Map<Nation, Player> nationMap;
/**
* Create a new PlayersTableModel.
*
* @param preGameController The {@code PreGameController}
* to use notify of updates.
* @param nationOptions The current {@code NationOptions}.
* @param thisPlayer The {@code Player} that owns the client.
*/
public PlayersTableModel(PreGameController preGameController,
NationOptions nationOptions,
Player thisPlayer) {
final Specification spec = thisPlayer.getSpecification();
this.preGameController = preGameController;
this.nationOptions = nationOptions;
this.thisPlayer = thisPlayer;
final Predicate<Nation> nationPred = n -> !n.isUnknownEnemy()
&& nationOptions.getNations().get(n) != null;
this.nations = transform(spec.getNations(), nationPred);
this.nationMap = new HashMap<>(this.nations.size());
for (Nation n : this.nations) this.nationMap.put(n, null);
this.nationMap.put(thisPlayer.getNation(), thisPlayer);
}
/**
* Update the nation map following any change.
*/
public void update() {
for (Nation n : this.nations) nationMap.put(n, null);
for (Player p : thisPlayer.getGame().getLivePlayerList()) {
nationMap.put(p.getNation(), p);
}
fireTableDataChanged();
}
/**
* Gets the class of the objects in the given column.
*
* @param column The column to return the class of.
* @return The {@code Class} of the objects in the given column.
*/
@Override
public Class<?> getColumnClass(int column) {
switch (column) {
case NATION_COLUMN:
return Nation.class;
case AVAILABILITY_COLUMN:
return NationOptions.NationState.class;
case ADVANTAGE_COLUMN:
return NationType.class;
case COLOR_COLUMN:
return Color.class;
case PLAYER_COLUMN:
return Player.class;
}
return String.class;
}
/**
* Get the number of columns in this table.
*
* @return The number of columns.
*/
@Override
public int getColumnCount() {
return columnNames.length;
}
/**
* Get the name of a column.
*
* @param column The column number to look up.
* @return The name of the specified column.
*/
@Override
public String getColumnName(int column) {
return columnNames[column];
}
/**
* Get the number of rows in this table.
*
* @return The number of rows.
*/
@Override
public int getRowCount() {
return nations.size();
}
/**
* Get the value at the requested location.
*
* @param row The requested row.
* @param column The requested column.
* @return The value at the requested location.
*/
@Override
public Object getValueAt(int row, int column) {
if (row >= 0 && row < getRowCount()
&& column >= 0 && column < getColumnCount()) {
Nation nation = nations.get(row);
switch (column) {
case NATION_COLUMN:
return nation;
case AVAILABILITY_COLUMN:
return nationOptions.getNationState(nation);
case ADVANTAGE_COLUMN:
return (nationMap.get(nation) == null) ? nation.getType()
: nationMap.get(nation).getNationType();
case COLOR_COLUMN:
return nation.getColor();
case PLAYER_COLUMN:
return nationMap.get(nation);
}
}
return null;
}
/**
* Is a cell editable?
*
* @param row The specified row.
* @param column The specified column.
* @return True if the specified cell is editable.
*/
@Override
public boolean isCellEditable(int row, int column) {
if (row >= 0 && row < getRowCount()) {
Nation nation = nations.get(row);
boolean ownRow = thisPlayer == nationMap.get(nation)
&& !thisPlayer.isReady();
switch (column) {
case AVAILABILITY_COLUMN:
return !ownRow && thisPlayer.isAdmin();
case ADVANTAGE_COLUMN:
return nation.getType() instanceof EuropeanNationType
&& ownRow;
case COLOR_COLUMN:
// Allow a player to change all the colors.
// This is an accessibility issue for users with a
// colour vision deficiency. Better to support them
// and just admit that if someone wants to be a pain
// and set all the colours the same, they can.
return nation.getType() instanceof EuropeanNationType;
case PLAYER_COLUMN:
return nation.getType() instanceof EuropeanNationType
&& nationMap.get(nation) == null;
}
}
return false;
}
/**
* Sets the value at the specified location.
*
* @param value The new value.
* @param row The specified row.
* @param column The specified column.
*/
@Override
public void setValueAt(Object value, int row, int column) {
if (row >= 0 && row < getRowCount()
&& column > 0 && column < getColumnCount()) {
// Column 0 can't be updated.
Nation nation = nations.get(row);
switch (column) {
case ADVANTAGE_COLUMN:
preGameController.setNationType((NationType)value);
update();
break;
case AVAILABILITY_COLUMN:
preGameController.setAvailable(nations.get(row),
(NationState)value);
update();
break;
case COLOR_COLUMN:
preGameController.setColor(nation, (Color)value);
update();
break;
case PLAYER_COLUMN:
if (nationOptions.getNationState(nation)
== NationState.AVAILABLE) {
preGameController.setNation(nation);
preGameController.setNationType(nation.getType());
update();
}
break;
default:
break;
}
fireTableCellUpdated(row, column);
}
}
}
public static final int NATION_COLUMN = 0,
AVAILABILITY_COLUMN = 1,
ADVANTAGE_COLUMN = 2,
COLOR_COLUMN = 3,
PLAYER_COLUMN = 4;
private static final String[] columnNames = {
Messages.message("nation"),
Messages.message("playersTable.availability"),
Messages.message("playersTable.advantage"),
Messages.message("color"),
Messages.message("player")
};
/** A link to the gui. */
private final GUI gui;
/**
* Creates a players table.
*
* @param freeColClient The {@code FreeColClient} for the game.
* @param nationOptions The {@code NationOptions} for this game.
* @param myPlayer The client {@code Player}.
*/
public PlayersTable(final FreeColClient freeColClient,
NationOptions nationOptions, Player myPlayer) {
super();
gui = freeColClient.getGUI();
final Specification spec = freeColClient.getGame().getSpecification();
setModel(new PlayersTableModel(freeColClient.getPreGameController(),
nationOptions, myPlayer));
setRowHeight(47);
JButton nationButton = Utility.localizedButton("nation");
nationButton.addActionListener((ActionEvent ae) -> {
gui.showColopediaPanel(PanelType.NATIONS.getKey());
});
JLabel availabilityLabel = Utility.localizedLabel("playersTable.availability");
JButton advantageButton = Utility.localizedButton("playersTable.advantage");
advantageButton.addActionListener((ActionEvent ae) -> {
gui.showColopediaPanel(PanelType.NATION_TYPES.getKey());
});
JLabel colorLabel = Utility.localizedLabel("color");
JLabel playerLabel = Utility.localizedLabel("player");
DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
dtcr.setOpaque(false);
HeaderRenderer renderer = new HeaderRenderer(nationButton,
availabilityLabel, advantageButton, colorLabel, playerLabel);
JTableHeader header = getTableHeader();
header.addMouseListener(new HeaderListener(header, renderer));
final TableColumnModel tcm = getColumnModel();
TableColumn nationColumn = tcm.getColumn(NATION_COLUMN);
nationColumn.setCellRenderer(new NationCellRenderer());
nationColumn.setHeaderRenderer(renderer);
nationColumn.setPreferredWidth(2 * tcm.getTotalColumnWidth()
/ tcm.getColumnCount());
TableColumn availableColumn = tcm.getColumn(AVAILABILITY_COLUMN);
availableColumn.setCellRenderer(new AvailableCellRenderer());
availableColumn.setCellEditor(new AvailableCellEditor());
TableColumn advantagesColumn = tcm.getColumn(ADVANTAGE_COLUMN);
switch (nationOptions.getNationalAdvantages()) {
case SELECTABLE:
advantagesColumn.setCellEditor(new AdvantageCellEditor(spec
.getEuropeanNationTypes()));
break;
case FIXED:
break; // Do nothing
case NONE:
spec.clearEuropeanNationalAdvantages();
break;
default:
break;
}
advantagesColumn.setCellRenderer(new AdvantageCellRenderer(nationOptions.getNationalAdvantages()));
advantagesColumn.setHeaderRenderer(renderer);
TableColumn colorsColumn = tcm.getColumn(COLOR_COLUMN);
colorsColumn.setCellRenderer(new ColorCellRenderer(true));
colorsColumn.setCellEditor(new ColorCellEditor(freeColClient));
TableColumn playerColumn = tcm.getColumn(PLAYER_COLUMN);
playerColumn.setCellEditor(new PlayerCellEditor());
playerColumn.setCellRenderer(new PlayerCellRenderer());
}
public void update() {
((PlayersTableModel)getModel()).update();
}
}
|
FreeCol/freecol
|
src/net/sf/freecol/client/gui/panel/PlayersTable.java
|
Java
|
gpl-2.0
| 25,105
|
/*
Copyright (C) 2016- The University of Notre Dame
This software is distributed under the GNU General Public License.
See the file COPYING for details.
*/
/** @file jx_match.h Unwrap JX types
*
* The functions in this header are intended to make JX types more usable
* from C code. All unwrap JX values in some manner, allowing access to
* native C types. For the arrays, the match function can be
* used to destructure its arguments, extracting and type-checking
* components in a single call.
* The match functions for single values return an int indicating the
* result of the match. On match failure, 0 is returned, or 1 on success.
* The match functions can also give the caller a copy of
* the matched value. For heap-allocated types, the caller is responsible
* for free()ing/jx_delete()ing the copied values. In the case that the
* caller requested a heap-allocated copy but malloc() fails, the match
* as a whole will fail. This ensures that it is always safe to dereference
* the copy given back, but might falsely indicate an incorrect type. Code
* that needs to run in out of memory conditions must not request copies.
*
* The common use case is that programs will have some stack allocated
* variables for local use, and would like to read the value in a JX struct.
*
* @code
* double val;
* if (jx_match_double(j, &val)) {
* printf("got value %f\n", val);
* } else {
* printf("not a valid double\n");
* }
* @endcode
*
* Here, the return value is used to check that the given JX struct was
* in fact a double, and to copy the value onto the local function's
* stack. If a function needs to modify the JX structure, it must
* access the struct fields directly.
*
* There is also a matching function to extract multiple positional
* values from an array and validate types in a single call.
* This function has a scanf()-like interface.
* The array matching function takes a JX struct
* and a sequence of item specifications. Each item
* spec includes a JX type and the location of a pointer that will reference
* the extracted value. The match function
* processes each specification in turn, stopping on an invalid spec,
* or NULL, and returning the number of items succesfully matched.
*
* @code
* jx_int_t a;
* double b;
* switch (jx_match_array(j, &a, JX_INTEGER, &b, JX_DOUBLE, NULL)) {
* case 1:
* printf("got int %d\n", a);
* case 2:
* printf("got %d and %f\n", a, b)
* default:
* printf("bad match\n");
* }
* @endcode
*
* It's also possible to match on a position without looking at the
* type of the matched value. The pseudo-type JX_ANY is provided
* for this purpose. Since the type of the value matched by JX_ANY is
* unknown, the caller might want to use the other match functions to
* handle whatever cases they're interested in. The following example
* uses most of the matching functionality.
*
* @code
* struct jx *a;
* struct jx *b;
* if (jx_match_array(j, &a, JX_ARRAY, &b, JX_ANY, NULL) == 2) {
* printf("got JX_ARRAY at %p\n", a);
* if (jx_istype(b, JX_STRING)) {
* printf("no longer supported\n");
* return 0;
* }
* jx_int_t val;
* if (jx_match_integer(b, &val)) {
* return val % 8;
* }
* }
* @endcode
*/
#ifndef JX_MATCH_H
#define JX_MATCH_H
#ifndef JX_ANY
#define JX_ANY -1
#endif
/*
* Macro to test if we're using a GNU C compiler of a specific vintage
* or later, for e.g. features that appeared in a particular version
* of GNU C. Usage:
*
* #if __GNUC_PREREQ__(major, minor)
* ...cool feature...
* #else
* ...delete feature...
* #endif
*/
#ifndef __GNUC_PREREQ__
#ifdef __GNUC__
#define __GNUC_PREREQ__(x, y) \
((__GNUC__ == (x) && __GNUC_MINOR__ >= (y)) || \
(__GNUC__ > (x)))
#else
#define __GNUC_PREREQ__(x, y) 0
#endif
#endif
#ifndef __wur
#if __GNUC_PREREQ__(3, 4)
#define __wur __attribute__((warn_unused_result))
#else
#define __wur
#endif
#endif
#ifndef __sentinel
#if __GNUC_PREREQ__(4, 0)
#define __sentinel __attribute__((sentinel))
#else
#define __sentinel
#endif
#endif
/** Unwrap a boolean value.
* @param j The JX structure to match.
* @param v An address to copy the boolean value to, or NULL if copying
* the value is unnecessary.
* @return A truth value indicating the result of the match.
*/
int jx_match_boolean(struct jx *j, int *v) __wur;
/** Unwrap an integer value.
* @param j The JX structure to match.
* @param v An address to copy the integer value to, or NULL if copying
* the value is unnecessary.
* @return A truth value indicating the result of the match.
*/
int jx_match_integer(struct jx *j, jx_int_t *v) __wur;
/** Unwrap a double value.
* @param j The JX structure to match.
* @param v An address to copy the double value to, or NULL if copying
* the value is unnecessary.
* @return A truth value indicating the result of the match.
*/
int jx_match_double(struct jx *j, double *v) __wur;
/** Unwrap a string value.
* Since C strings are just pointers to char arrays, the interface
* here is a little awkward. If the caller has a stack-allocated
* (char *), this function can allocate a copy of the string value
* and store the address in the caller's pointer variable, e.g.
*
* @code
* char *val;
* if (jx_match_string(j, &val)) {
* printf("got value %s\n", val);
* }
* @endcode
*
* @param j The JX structure to match.
* @param v The address of a (char *) in which to store the address of
* the newly malloc()ed string, or NULL if copying the value is unnecessary.
* @return A truth value indicating the result of the match.
*/
int jx_match_string(struct jx *j, char **v) __wur;
/** Unwrap a symbol value.
* This function accesses the symbol name as a string.
* See @ref jx_match_string for details.
*
* @param j The JX structure to match.
* @param v The address of a (char *) in which to store the address of
* the newly malloc()ed symbol name, or NULL
* if copying the value is unnecessary.
* @return A truth value indicating the result of the match.
*/
int jx_match_symbol(struct jx *j, char **v) __wur;
/** Destructure an array.
* This function accepts an arbitrary number of positional specifications
* to attempt to match. Each specification is of the form
*
* <address>, <jx type>
*
* where <jx type> is JX_INTEGER, JX_ANY, etc. and <address> is the address
* to store the matched value. The last argument must be NULL to mark the
* end of the specifications. The specifications will be matched
* in the order given, and matching ends on the first failure. If the JX
* value passed in was not an array, this is considered a failure before
* any matches succeed, so 0 is returned.
* @param j The JX structure to match.
* @return The number of elements successfully matched.
*/
int jx_match_array(struct jx *j, ...) __wur __sentinel;
#endif
|
hmeng-19/cctools
|
dttools/src/jx_match.h
|
C
|
gpl-2.0
| 6,991
|
Zabbix Community Dockerfiles
============================
[Zabbix Github repo](https://github.com/zabbix/zabbix-community-docker) is
intended as a source for [Zabbix Docker registry](https://registry.hub.docker.com/repos/zabbix/).
Please use these community Zabbix Docker images, if you want to
[build/ship your own Zabbix Docker image](https://github.com/zabbix/zabbix-community-docker#how-to-build-own-docker-image).
zabbix-server-2.4 [](https://imagelayers.io/?images=zabbix/zabbix-server-2.4:latest) [](https://circleci.com/gh/zabbix/zabbix-community-docker/tree/master)
=================
Compiled zabbix-server with almost all features (MySQL support, Java, SNMP,
Curl, IPMI, IPv6, Jabber, fping) and Zabbix web UI based on CentOS 7,
Supervisor, Nginx, PHP. Image requires external MySQL/MariaDB database (you can
run MySQL/MariaDB also as Docker container).
#### Standard Dockerized Zabbix server deployement
```
# create /var/lib/mysql as persistent volume storage
docker run -d -v /var/lib/mysql --name zabbix-db-storage busybox:latest
# start DB for zabbix server - default 1GB innodb_buffer_pool_size is used
docker run \
-d \
--name zabbix-db \
-v /backups:/backups \
--volumes-from zabbix-db-storage \
--env="MARIADB_USER=zabbix" \
--env="MARIADB_PASS=my_password" \
zabbix/zabbix-db-mariadb
# start Zabbix server linked to started DB
docker run \
-d \
--name zabbix-server \
-p 80:80 \
-p 10051:10051 \
--link zabbix-db:zabbix.db \
--env="ZS_DBHost=zabbix.db" \
--env="ZS_DBUser=zabbix" \
--env="ZS_DBPassword=my_password" \
zabbix/zabbix-server-2.4
# wait ~60 seconds for Zabbix server initialization
# Zabbix web will be available on the port 80, Zabbix server on the port 10051
# Backup of Zabbix configuration data only
docker exec \
-ti zabbix-db \
/zabbix-backup/zabbix-mariadb-dump -u zabbix -p my_password -o /backups
# Full DB backup of Zabbix
docker exec \
-ti zabbix-db \
bash -c "\
mysqldump -u zabbix -pmy_password zabbix | \
bzip2 -cq9 > /backups/zabbix_db_dump_$(date +%Y-%m-%d-%H.%M.%S).sql.bz2"
```
#### Up and Running with Docker Compose
```
docker-compose up -d
```
### Zabbix database as Docker container
To be able to connect to database we would need one to be running first.
Easiest way to do that is to use another docker image. For this purpose you
can use [zabbix/zabbix-db-mariadb]
(https://registry.hub.docker.com/u/zabbix/zabbix-db-mariadb) image as database.
For more information about zabbix/zabbix-db-mariadb see
[README of zabbix-db-mariadb]
(https://github.com/zabbix/zabbix-community-docker/tree/master/Dockerfile/zabbix-db-mariadb).
Example:
docker run \
-d \
--name zabbix-db \
-p 3306:3306 \
--env="MARIADB_USER=zabbix" \
--env="MARIADB_PASS=my_password" \
zabbix/zabbix-db-mariadb
Remember to use the same credentials when deploying zabbix-server image.
#### Environmental variables
You can use environmental variables to config Zabbix server and PHP. Available
variables:
| Variable | Default value |
| -------- | ------------- |
| PHP_date_timezone | UTC |
| PHP_max_execution_time | 300 |
| PHP_max_input_time | 300 |
| PHP_memory_limit | 128M |
| PHP_error_reporting | E_ALL |
| ZS_ListenPort | 10051 |
| ZS_SourceIP | |
| ZS_LogFile | /tmp/zabbix_server.log |
| ZS_LogFileSize | 10 |
| ZS_DebugLevel | 3 |
| ZS_PidFile | /var/run/zabbix_server.pid |
| ZS_DBHost | zabbix.db |
| ZS_DBName | zabbix |
| ZS_DBSchema | |
| ZS_DBUser | zabbix |
| ZS_DBPassword | zabbix |
| ZS_DBSocket | /tmp/mysql.sock |
| ZS_DBPort | 3306 |
| ZS_StartPollers | 5 |
| ZS_StartPollersUnreachable | 1 |
| ZS_StartTrappers | 5 |
| ZS_StartPingers | 1 |
| ZS_StartDiscoverers | 1 |
| ZS_StartHTTPPollers | 1 |
| ZS_StartTimers | 1 |
| ZS_JavaGateway | 127.0.0.1 |
| ZS_JavaGatewayPort | 10052 |
| ZS_StartJavaPollers | 0 |
| ZS_StartVMwareCollectors | 0 |
| ZS_VMwareFrequency | 60 |
| ZS_VMwarePerfFrequency | 60 |
| ZS_VMwareCacheSize | 8M |
| ZS_VMwareTimeout | 10 |
| ZS_SNMPTrapperFile | /tmp/zabbix_traps.tmp |
| ZS_StartSNMPTrapper | 0 |
| ZS_ListenIP | 0.0.0.0 |
| ZS_HousekeepingFrequency | 1 |
| ZS_MaxHousekeeperDelete | 500 |
| ZS_SenderFrequency | 30 |
| ZS_CacheSize | 8M |
| ZS_CacheUpdateFrequency | 60 |
| ZS_StartDBSyncers | 4 |
| ZS_HistoryCacheSize | 8M |
| ZS_TrendCacheSize | 4M |
| ZS_HistoryTextCacheSize | 16M |
| ZS_ValueCacheSize | 8M |
| ZS_Timeout | 3 |
| ZS_TrapperTimeout | 300 |
| ZS_UnreachablePeriod | 45 |
| ZS_UnavailableDelay | 60 |
| ZS_UnreachableDelay | 15 |
| ZS_AlertScriptsPath | /usr/local/share/zabbix/alertscripts |
| ZS_ExternalScripts | /usr/local/share/zabbix/externalscripts |
| ZS_FpingLocation | /usr/sbin/fping |
| ZS_Fping6Location | /usr/sbin/fping6 |
| ZS_SSHKeyLocation | |
| ZS_LogSlowQueries | 0 |
| ZS_TmpDir | /tmp |
| ZS_StartProxyPollers | 1 |
| ZS_ProxyConfigFrequency | 3600 |
| ZS_ProxyDataFrequency | 1 |
| ZS_AllowRoot | 0 |
| ZS_User | zabbix |
| ZS_Include | |
| ZS_SSLCertLocation | /usr/local/share/zabbix/ssl/certs |
| ZS_SSLKeyLocation | /usr/local/share/zabbix/ssl/keys |
| ZS_SSLCALocation | |
| ZS_LoadModulePath | /usr/lib/zabbix/modules |
| ZS_LoadModule | |
#### Configuration from volume
Full config files can be also used. Environment configs will be overriden by
values from config files in this case. You need only to add */etc/custom-config/*
volume:
```
-v /host/custom-config/:/etc/custom-config/
```
Available files:
| File | Description |
| ---- | ----------- |
| php-zabbix.ini | PHP configuration file |
| zabbix_server.conf | Zabbix server configuration file |
#### Zabbix server deployment
Now when we have Zabbix database running we can deploy zabbix-server image with
appropriate environmental variables set.
Example:
docker run \
-d \
--name zabbix-server \
-p 80:80 \
-p 10051:10051 \
--link zabbix-db:zabbix.db \
--env="ZS_DBHost=zabbix.db" \
--env="ZS_DBUser=zabbix" \
--env="ZS_DBPassword=my_password" \
zabbix/zabbix-server-2.4
#### Access to Zabbix web interface
To log in into zabbix web interface for the first time use credentials
`Admin:zabbix`.
Access web interface under [http://docker_host_ip]()
Docker troubleshooting
======================
Use docker command to see if all required containers are up and running:
```
$ docker ps
```
Check logs of Zabbix server container:
```
$ docker logs zabbix-server
```
Sometimes you might just want to review how things are deployed inside a running
container, you can do this by executing a _bash shell_ through _docker's
exec_ command:
```
docker exec -ti zabbix-server /bin/bash
```
History of an image and size of layers:
```
docker history --no-trunc=true zabbix/zabbix-server-2.4 | tr -s ' ' | tail -n+2 | awk -F " ago " '{print $2}'
```
Run specific Zabbix server version, e.g. 2.4.4 - just specify 2.4.4 tag for image:
```
docker run \
-d \
--name zabbix-server \
-p 80:80 \
-p 10051:10051 \
--link zabbix-db:zabbix.db \
--env="ZS_DBHost=zabbix.db" \
--env="ZS_DBUser=zabbix" \
--env="ZS_DBPassword=my_password" \
zabbix/zabbix-server-2.4:2.4.4
```
|
thejordanclark/zabbix-community-docker
|
Dockerfile/zabbix-server-2.4/README.md
|
Markdown
|
gpl-2.0
| 7,355
|
<?php
/*
* @version $Id: ldapdaterestriction.php 20129 2013-02-04 16:53:59Z moyo $
-------------------------------------------------------------------------
GLPI - Gestionnaire Libre de Parc Informatique
Copyright (C) 2003-2013 by the INDEPNET Development Team.
http://indepnet.net/ http://glpi-project.org
-------------------------------------------------------------------------
LICENSE
This file is part of GLPI.
GLPI 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.
GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
/** @file
* @brief
*/
if (strpos($_SERVER['PHP_SELF'],"ldapdaterestriction.php")) {
include ('../inc/includes.php');
header("Content-Type: text/html; charset=UTF-8");
Html::header_nocache();
}
if (!defined('GLPI_ROOT')) {
die("Can not acces directly to this file");
}
Session::checkLoginUser();
AuthLdap::showDateRestrictionForm($_POST);
?>
|
opusappteam/PLGLPI0842
|
ajax/ldapdaterestriction.php
|
PHP
|
gpl-2.0
| 1,464
|
package Module4.Task1;
public abstract class Figure {
public abstract double getSquare();
}
|
tinneua/GoJavaOnline
|
src/main/java/Module4/Task1/Figure.java
|
Java
|
gpl-2.0
| 98
|
/**
*
*/
package com.jasperb.citybuilder.util;
/**
* Simple object to track the average frame draw time
*/
public class PerfTools {
private static final int MAXSAMPLES = 75;
private static int mIndex = 0;
private static int mSum = 0;
private static int mTickList[] = new int[MAXSAMPLES];
public static double CalcAverageTick(int newTick) {
mSum -= mTickList[mIndex];
mSum += newTick;
mTickList[mIndex] = newTick;
if (++mIndex == MAXSAMPLES) {
mIndex = 0;
}
return ((double) mSum / MAXSAMPLES);
}
}
|
JasperBerrington/CityBuilder
|
Project/src/com/jasperb/citybuilder/util/PerfTools.java
|
Java
|
gpl-2.0
| 590
|
<html>
<body>
<noscript>Your browser does not support JavaScript!</noscript>
</body>
</html>
|
eyoung-father/eyoung
|
libdecoder/html/testsuite/case/tag-noscript.html
|
HTML
|
gpl-2.0
| 97
|
<%include file="header-jquery.html" />
<%include file="css_style.html" />
<script type="text/javascript">
<%include file="js/createlinkedslider.js" />
</script>
<script type="text/javascript">
function selectAbs() {
document.getElementById("divAbs").style.display = 'block'
document.getElementById("divRel").style.display = 'none'
}
function selectRel() {
document.getElementById("divAbs").style.display = 'none'
document.getElementById("divRel").style.display = 'block'
}
</script>
<%
paradic = app.cfg['param']['paradic']
hght = int(app.cfg['param']['hght'])
wdth = int(app.cfg['param']['wdth'])
def rnd():
import random
return random.randint(0,100000)
%>
%if wdth >1200:
<p> Please note that this demo is optimized for image widths smaller than 1200px. </p>
%endif
<form action="${app.base_url + 'wait'}" method="get">
<div style="position:fixed;border:1px solid lightgray;background:white;padding:10px;top:0px;right:0px;z-index:102">
<input type="hidden" name="key" value="${app.key}">
<input type="hidden" name="action" value="cust_sift_matching">
<h2> Anatomy of the SIFT Method </h2>
<ul>
<li> <button type="submit" style="width:100%" name="show" value="antmy_detect"> Examine the SIFT method. </button> </li>
</ul>
</div>
</form>
<div>
<p>
Matching result:
</p>
</div>
<div>
<input type="image" width=100% src="${app.work_url + 'OUTmatches.png'}?rnd=${rnd()}" alt="matches.png">
</div>
<!-- MATCHING -->
<form action="${app.base_url + 'wait'}" method="get">
<div class="toggleable" id="ress" style="max-height:30em; overflow:auto;">
<fieldset style="padding-top:0.0ex" >
<legend style="font-weight:bold;"> Matching </legend>
<%
if ( int(paradic['flag_match']) == 1):
radioRelative = "checked"
radioAbsolute = "unchecked"
C_match_MAX = 1
else:
radioRelative = "unchecked"
radioAbsolute= "checked"
C_match_MAX = 500
endif
%>
<label for="flag_match"> Matching (Absolute or Relative): </label> </br>
<input type="radio" name="flag_match" value="1" ${radioRelative} onclick="selectRel()"> Relative matching threshold </br>
<input type="radio" name="flag_match" value="0" ${radioAbsolute} onclick="selectAbs()"> Absolute matching threshold </br>
<%try:
C_match = float(paradic['C_match'])
except Exception:
C_match = 0.6
%>
<!-- Matching Relative Distance -->
%if ( int(paradic['flag_match']) == 1):
<div id="divRel" class="desc" >
%endif
%if ( int(paradic['flag_match']) == 0):
<div id="divRel" class="desc" style="display:none">
%endif
<div style="float:left;padding-right:5px;width:6em;"> C_match </div>
<input type="text" style="float:left;font-family:monospace;text-align:right" size="4" id="C_match" name="C_match" value="${C_match}" />
<div id="C_match_slider" name="C_match_slider" style="width:250px;margin-left:5px;margin-right:1em;float:left;margin-top:4px;font-size:10pt"></div>
<script type="text/javascript">
$(document).ready(function(){
createLinkedSlider('#C_match', '#C_match_slider',0, 1 , 0.01);
});
</script>
<div>
Threshold on distance ratio (distance to nearest neighbor / distance to second nearest neighbor)
</div>
<div style="clear:both;margin-bottom:5px;"> </div>
</div>
<!-- Matching Absolute Distance -->
%if ( int(paradic['flag_match']) == 0):
<div id="divAbs" class="desc" >
%endif
%if ( int(paradic['flag_match']) == 1):
<div id="divAbs" class="desc" style="display:none">
%endif
<div style="float:left;padding-right:5px;width:6em;"> C_match </div>
<input type="text" style="float:left;font-family:monospace;text-align:right" size="4" id="C_match2" name="C_match2" value="200" />
<div id="C_match_slider2" name="C_match_slider2" style="width:250px;margin-left:5px;margin-right:1em;float:left;margin-top:4px;font-size:10pt"></div>
<script type="text/javascript">
$(document).ready(function(){
createLinkedSlider('#C_match2', '#C_match_slider2',10, 400, 3);
});
</script>
<div>
Threshold on distance to nearest neighbor
</div>
<div style="clear:both;margin-bottom:5px;"> </div>
</div>
<input type="hidden" name="key" value="${app.key}">
<tr><td><button type="submit" name="action" value="cust_matching"> Match keypoints </button></td></tr>
</fieldset>
</div></form>
<!-- END MATCHING -->
<form action="${app.base_url}" method="get">
<div class="toggleable" id="ress" style="max-height:30em; overflow:auto;">
<fieldset style="padding-top:0.0ex" >
<legend style="font-weight:bold;"> Change input </legend>
<tr><td><button type="submit"> Run SIFT with another input images</button></td></tr>
</fieldset>
</div>
</form>
<form action="${app.base_url + 'wait'}" method="get">
<div class="toggleable" id="param.matching" style="max-height:30em; overflow:auto;">
<fieldset style="padding-top:0.0ex" >
<legend style="font-weight:bold;"> Anatomy of SIFT </legend>
<input type="hidden" name="key" value="${app.key}">
<input type="hidden" name="show" value="antmy_detect">
<tr><td><button type="submit" name="action" value="cust_sift_matching"> Examine SIFT with the same images</button></td></tr>
</fieldset>
</div>
</form>
Detected and Matching keypoints:
<div class="gallerytab" style="height:${str(hght+100)}px; width:100%;">
<ul class="index">
<li style="width:50%"><a> Keys 1
<span>
<p> SIFT keypoints in first image </p>
<img src="${app.work_url + 'keys_im0.png'}?rnd=${rnd()}" style="width:100%;" />
</span></a> </li>
<li style="width:50%"><a> Keys 2
<span>
<p> SIFT keypoints in second image </p>
<img src="${app.work_url + 'keys_im1.png'}?rnd=${rnd()}" style="width:100%;" />
</span></a> </li>
<li style="width:50%"><a> Matching 1
<span>
<p> The subset of SIFT keypoints that find a match. </p>
<img src="${app.work_url + 'matching_keys_im0.png'}?rnd=${rnd()}" style="width:100%;" />
</span></a> </li>
<li style="width:50%"><a> Matching 2
<span>
<p> The subset of SIFT keypoints that find a match. </p>
<img src="${app.work_url + 'matching_keys_im1.png'}?rnd=${rnd()}" style="width:100%;" />
</span></a> </li>
</ul>
</div>
<h2> Algorithm output </h2>
<ul>
<li>First image: <a href="${app.work_url}input_0.png">input_0.png</a></li>
<li>Second image: <a href="${app.work_url}input_1.png">input_1.png</a></li>
<li>Detected keypoint in the first image: <a href="${app.work_url}keys_im0.txt">keys_im0.txt</a></li>
<li>Detected keypoint in the second image: <a href="${app.work_url}keys_im1.txt">keys_im1.txt</a></li>
<li>List of matching keypoints: <a href="${app.work_url}matches.txt">matches.txt</a></li>
</ul>
<%include file="footer.html" />
|
juan-cardelino/matlab_demos
|
ipol_demo-light-1025b85/app_available/82/template/result.html
|
HTML
|
gpl-2.0
| 6,836
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.