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 |
|---|---|---|---|---|---|
/*
* =========================================================
* =========================================================
* ColorPicker
* =========================================================
* =========================================================
*
*/
#editor {
margin-top: 250px;
margin-left: 50px;
}
#example {
display: block;
position: absolute;
top: 100px;
left: 100px;
width: 300px;
}
.inlet_slider {
opacity: 0.85;
z-index: 10;
width: 24%;
display: block;
border-radius: 3px;
height: 14px;
-webkit-box-shadow: inset 0px 0px 5px 0px rgba(4, 4, 4, 0.5);
box-shadow: inset 0px 0px 5px 0px rgba(4, 4, 4, 0.5);
background-color: #d6d6d6;
background-image: -webkit-gradient(linear, left top, left bottom, from(#d6d6d6), to(#ebebeb));
background-image: -webkit-linear-gradient(top, #d6d6d6, #ebebeb);
background-image: -moz-linear-gradient(top, #d6d6d6, #ebebeb);
background-image: -o-linear-gradient(top, #d6d6d6, #ebebeb);
background-image: -ms-linear-gradient(top, #d6d6d6, #ebebeb);
background-image: linear-gradient(top, #d6d6d6, #ebebeb);
filter: progid:dximagetransform.microsoft.gradient(GradientType=0, StartColorStr='#d6d6d6', EndColorStr='#ebebeb');
}
.inlet_slider:hover {
opacity: 0.98;
}
.inlet_slider .range {
width: 90%;
margin-left: 5%;
margin-top: 0px;
}
input[type="range"] {
-webkit-appearance: none;
-moz-appearance: none;
}
.inlet_slider input::-webkit-slider-thumb {
cursor: col-resize;
-webkit-appearance: none;
-moz-apperance: none;
width: 12px;
height: 12px;
margin-top: -13px;
border-radius: 6px;
border: 1px solid black;
background-color: red;
-webkit-box-shadow: 0px 0px 3px 0px rgba(4, 4, 4, 0.4);
box-shadow: 0px 0px 3px 0px rgba(4, 4, 4, 0.4);
background-color: #424242;
background-image: -webkit-gradient(linear, left top, left bottom, from(#424242), to(#212121));
background-image: -webkit-linear-gradient(top, #424242, #212121);
background-image: -moz-linear-gradient(top, #424242, #212121);
background-image: -o-linear-gradient(top, #424242, #212121);
background-image: -ms-linear-gradient(top, #424242, #212121);
background-image: linear-gradient(top, #424242, #212121);
filter: progid:dximagetransform.microsoft.gradient(GradientType=0, StartColorStr='#424242', EndColorStr='#212121');
}
/*
* =========================================================
* =========================================================
* ColorPicker
* =========================================================
* =========================================================
*
*/
#ColorPicker {
border: 1px solid rgba(0,0,0,0.5);
border-radius: 6px;
background: #0d0d0d;
background: -webkit-gradient(linear, left top, left bottom, from(#333), color-stop(0.1, #111), to(#000000));
box-shadow: 2px 2px 5px 2px rgba(0,0,0,0.35);
text-shadow: 1px 1px 1px #000;
color:#AAA;
cursor:default;
display:block;
font-family:'arial',helvetica,sans-serif;
font-size:20px;
padding:7px 8px 20px;
position:absolute;
top: 100px;
left: 700px;
width:229px;
z-index:100;
}
#ColorPicker br {
clear:both;
margin:0;
padding:0;
}
#ColorPicker input.hexInput:hover,
#ColorPicker input.hexInput:focus {
color: #FFD000
}
#ColorPicker input.hexInput {
-webkit-transition-property: color;
-webkit-transition-duration: .5s;
background: none;
border: 0;
margin: 0;
font-family:courier,monospace;
font-size:20px;
position: relative;
top: -2px;
float:left;
color:#fff;
cursor: text;
}
#ColorPicker div.hexBox {
border: 1px solid rgba(255,255,255,0.5);
border-radius: 2px;
background:#FFF;
float:left;
font-size:1px;
height:20px;
margin: 0 5px 0 2px;
width:20px;
cursor: pointer;
}
#ColorPicker div.hexBox div {
width: inherit;
height: inherit;
}
#ColorPicker div.hexClose {
-webkit-transition-property: color, text-shadow;
-webkit-transition-duration: .5s;
position: relative;
top: -1px;
left: -1px;
color:#FFF;
cursor:pointer;
float:right;
padding: 0 5px;
margin:0 4px 3px;
user-select:none;
-webkit-user-select: none;
}
#ColorPicker div.hexClose:hover {
text-shadow: 0 0 20px #fff;
color:#FF1100;
}
| georules/Inlet | src/style.css | CSS | mit | 4,160 |
/**
* The MIT License (MIT)
*
* Copyright (c) 2011-2016 Incapture Technologies LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reflex.node.io;
import reflex.IReflexIOHandler;
import reflex.value.ReflexStreamValue;
import reflex.value.ReflexValue;
import com.google.common.net.MediaType;
/*
* Used to adapt a line from a file into something else.
*/
public interface FileReadAdapter {
ReflexValue readContent(ReflexStreamValue fVal, IReflexIOHandler ioHandler);
MediaType getMimeType();
}
| scarabus/Rapture | Libs/Reflex/src/main/java/reflex/node/io/FileReadAdapter.java | Java | mit | 1,549 |
#include "i_explosion_component.h"
#include <portable_iarchive.hpp>
#include <portable_oarchive.hpp>
REAPING2_CLASS_EXPORT_IMPLEMENT( IExplosionComponent, IExplosionComponent );
| HalalUr/Reaping2 | src/core/i_explosion_component.cpp | C++ | mit | 179 |
/*
* @brief LPC8xx System & Control driver
*
* @note
* Copyright(C) NXP Semiconductors, 2012
* All rights reserved.
*
* @par
* Software that is described herein is for illustrative purposes only
* which provides customers with programming information regarding the
* LPC products. This software is supplied "AS IS" without any warranties of
* any kind, and NXP Semiconductors and its licenser disclaim any and
* all warranties, express or implied, including all implied warranties of
* merchantability, fitness for a particular purpose and non-infringement of
* intellectual property rights. NXP Semiconductors assumes no responsibility
* or liability for the use of the software, conveys no license or rights under any
* patent, copyright, mask work right, or any other intellectual property rights in
* or to any products. NXP Semiconductors reserves the right to make changes
* in the software without notification. NXP Semiconductors also makes no
* representation or warranty that such application will be suitable for the
* specified use without further testing or modification.
*
* @par
* Permission to use, copy, modify, and distribute this software and its
* documentation is hereby granted, under NXP Semiconductors' and its
* licensor's relevant copyrights in the software, without fee, provided that it
* is used in conjunction with NXP Semiconductors microcontrollers. This
* copyright, permission, and disclaimer notice must appear in all copies of
* this code.
*/
#include "chip.h"
/*****************************************************************************
* Private types/enumerations/variables
****************************************************************************/
/* PDSLEEPCFG register mask */
#define PDSLEEPWRMASK (0x0000FFB7)
#define PDSLEEPDATMASK (0x00000048)
#if defined(CHIP_LPC82X)
/* PDWAKECFG and PDRUNCFG register masks */
#define PDWAKEUPWRMASK (0x00006D00)
#define PDWAKEUPDATMASK (0x000080FF)
#else
/* PDWAKECFG and PDRUNCFG register masks */
#define PDWAKEUPWRMASK (0x00006D10)
#define PDWAKEUPDATMASK (0x000080EF)
#endif
/*****************************************************************************
* Public types/enumerations/variables
****************************************************************************/
/*****************************************************************************
* Private functions
****************************************************************************/
/*****************************************************************************
* Public functions
****************************************************************************/
/* Setup deep sleep behaviour for power down */
void Chip_SYSCTL_SetDeepSleepPD(uint32_t sleepmask)
{
/* Update new value */
LPC_SYSCTL->PDSLEEPCFG = PDSLEEPWRMASK | (sleepmask & PDSLEEPDATMASK);
}
/* Setup wakeup behaviour from deep sleep */
void Chip_SYSCTL_SetWakeup(uint32_t wakeupmask)
{
/* Update new value */
LPC_SYSCTL->PDAWAKECFG = PDWAKEUPWRMASK | (wakeupmask & PDWAKEUPDATMASK);
}
/* Power down one or more blocks or peripherals */
void Chip_SYSCTL_PowerDown(uint32_t powerdownmask)
{
uint32_t pdrun;
/* Get current power states */
pdrun = LPC_SYSCTL->PDRUNCFG & PDWAKEUPDATMASK;
/* Disable peripheral states by setting high */
pdrun |= (powerdownmask & PDWAKEUPDATMASK);
/* Update power states with required register bits */
LPC_SYSCTL->PDRUNCFG = (PDWAKEUPWRMASK | pdrun);
}
/* Power up one or more blocks or peripherals */
void Chip_SYSCTL_PowerUp(uint32_t powerupmask)
{
uint32_t pdrun;
/* Get current power states */
pdrun = LPC_SYSCTL->PDRUNCFG & PDWAKEUPDATMASK;
/* Enable peripheral states by setting low */
pdrun &= ~(powerupmask & PDWAKEUPDATMASK);
/* Update power states with required register bits */
LPC_SYSCTL->PDRUNCFG = (PDWAKEUPWRMASK | pdrun);
}
| Defconbots/2015_target | sw/driver_lib/src/syscon_8xx.c | C | mit | 3,978 |
require_relative 'test_helper'
class TurbolinksController < ActionController::Base
def simple_action
render text: ' '
end
def redirect_to_same_origin
redirect_to "#{request.protocol}#{request.host}/path"
end
def redirect_to_different_host
redirect_to "#{request.protocol}foo.#{request.host}/path"
end
def redirect_to_different_protocol
redirect_to "#{request.protocol == 'http://' ? 'https://' : 'http://'}#{request.host}/path"
end
def redirect_to_back
redirect_to :back
end
def redirect_to_unescaped_path
redirect_to "#{request.protocol}#{request.host}/foo bar"
end
end
class TurbolinksTest < ActionController::TestCase
tests TurbolinksController
def test_request_referer_returns_xhr_referer_or_standard_referer
@request.env['HTTP_REFERER'] = 'referer'
assert_equal 'referer', @request.referer
@request.env['HTTP_X_XHR_REFERER'] = 'xhr-referer'
assert_equal 'xhr-referer', @request.referer
end
def test_url_for_with_back_uses_xhr_referer_when_available
@request.env['HTTP_REFERER'] = 'referer'
assert_equal 'referer', @controller.view_context.url_for(:back)
@request.env['HTTP_X_XHR_REFERER'] = 'xhr-referer'
assert_equal 'xhr-referer', @controller.view_context.url_for(:back)
end
def test_redirect_to_back_uses_xhr_referer_when_available
@request.env['HTTP_REFERER'] = 'http://test.host/referer'
get :redirect_to_back
assert_redirected_to 'http://test.host/referer'
@request.env['HTTP_X_XHR_REFERER'] = 'http://test.host/xhr-referer'
get :redirect_to_back
assert_redirected_to 'http://test.host/xhr-referer'
end
def test_sets_request_method_cookie_on_non_get_requests
post :simple_action
assert_equal 'POST', cookies[:request_method]
put :simple_action
assert_equal 'PUT', cookies[:request_method]
end
def test_pops_request_method_cookie_on_get_request
cookies[:request_method] = 'TEST'
get :simple_action
assert_nil cookies[:request_method]
end
def test_sets_xhr_redirected_to_header_on_redirect_requests_coming_from_turbolinks
get :redirect_to_same_origin
get :simple_action
assert_nil @response.headers['X-XHR-Redirected-To']
@request.env['HTTP_X_XHR_REFERER'] = 'http://test.host/'
get :redirect_to_same_origin
@request.env['HTTP_X_XHR_REFERER'] = nil
get :simple_action
assert_equal 'http://test.host/path', @response.headers['X-XHR-Redirected-To']
end
def test_changes_status_to_403_on_turbolinks_requests_redirecting_to_different_origin
get :redirect_to_different_host
assert_response :redirect
get :redirect_to_different_protocol
assert_response :redirect
@request.env['HTTP_X_XHR_REFERER'] = 'http://test.host'
get :redirect_to_different_host
assert_response :forbidden
get :redirect_to_different_protocol
assert_response :forbidden
get :redirect_to_same_origin
assert_response :redirect
end
def test_handles_invalid_xhr_referer_on_redirection
@request.env['HTTP_X_XHR_REFERER'] = ':'
get :redirect_to_same_origin
assert_response :redirect
end
def test_handles_unescaped_same_origin_location_on_redirection
@request.env['HTTP_X_XHR_REFERER'] = 'http://test.host/'
get :redirect_to_unescaped_path
assert_response :redirect
end
def test_handles_unescaped_different_origin_location_on_redirection
@request.env['HTTP_X_XHR_REFERER'] = 'https://test.host/'
get :redirect_to_unescaped_path
assert_response :forbidden
end
end
class TurbolinksIntegrationTest < ActionDispatch::IntegrationTest
setup do
@session = open_session
end
def test_sets_xhr_redirected_to_header_on_redirect_requests_coming_from_turbolinks
get '/redirect_hash'
get response.location
assert_nil response.headers['X-XHR-Redirected-To']
get '/redirect_hash', nil, { 'HTTP_X_XHR_REFERER' => 'http://www.example.com/' }
assert_response :redirect
assert_nil response.headers['X-XHR-Redirected-To']
get response.location, nil, { 'HTTP_X_XHR_REFERER' => nil }
assert_equal 'http://www.example.com/turbolinks/simple_action', response.headers['X-XHR-Redirected-To']
assert_response :ok
get '/redirect_path', nil, { 'HTTP_X_XHR_REFERER' => 'http://www.example.com/' }
assert_response :redirect
assert_nil response.headers['X-XHR-Redirected-To']
get response.location, nil, { 'HTTP_X_XHR_REFERER' => nil }
assert_equal 'http://www.example.com/turbolinks/simple_action', response.headers['X-XHR-Redirected-To']
assert_response :ok
end
end
| peterjm/turbolinks | test/turbolinks/turbolinks_test.rb | Ruby | mit | 4,592 |
body {
background-color : #000;
margin : 0px;
padding : 0px;
color : #fff;
overflow: hidden;
} | Kike-Ramirez/canoaGame | public/css/style.css | CSS | mit | 99 |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Original Code: Copyright (c) 2009-2014 The Bitcoin Core Developers
// Modified Code: Copyright (c) 2014 Project Bitmark
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITMARK_SERIALIZE_H
#define BITMARK_SERIALIZE_H
#include "allocators.h"
#include <algorithm>
#include <assert.h>
#include <limits>
#include <ios>
#include <map>
#include <set>
#include <stdint.h>
#include <string>
#include <string.h>
#include <utility>
#include <vector>
#include <boost/tuple/tuple.hpp>
#include <boost/type_traits/is_fundamental.hpp>
class CAutoFile;
class CDataStream;
class CScript;
static const unsigned int MAX_SIZE = 0x02000000;
// Used to bypass the rule against non-const reference to temporary
// where it makes sense with wrappers such as CFlatData or CTxDB
template<typename T>
inline T& REF(const T& val)
{
return const_cast<T&>(val);
}
/////////////////////////////////////////////////////////////////
//
// Templates for serializing to anything that looks like a stream,
// i.e. anything that supports .read(char*, int) and .write(char*, int)
//
enum
{
// primary actions
SER_NETWORK = (1 << 0),
SER_DISK = (1 << 1),
SER_GETHASH = (1 << 2),
};
#define IMPLEMENT_SERIALIZE(statements) \
unsigned int GetSerializeSize(int nType, int nVersion) const \
{ \
CSerActionGetSerializeSize ser_action; \
const bool fGetSize = true; \
const bool fWrite = false; \
const bool fRead = false; \
unsigned int nSerSize = 0; \
ser_streamplaceholder s; \
assert(fGetSize||fWrite||fRead); /* suppress warning */ \
s.nType = nType; \
s.nVersion = nVersion; \
{statements} \
return nSerSize; \
} \
template<typename Stream> \
void Serialize(Stream& s, int nType, int nVersion) const \
{ \
CSerActionSerialize ser_action; \
const bool fGetSize = false; \
const bool fWrite = true; \
const bool fRead = false; \
unsigned int nSerSize = 0; \
assert(fGetSize||fWrite||fRead); /* suppress warning */ \
{statements} \
} \
template<typename Stream> \
void Unserialize(Stream& s, int nType, int nVersion) \
{ \
CSerActionUnserialize ser_action; \
const bool fGetSize = false; \
const bool fWrite = false; \
const bool fRead = true; \
unsigned int nSerSize = 0; \
assert(fGetSize||fWrite||fRead); /* suppress warning */ \
{statements} \
}
#define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
//
// Basic types
//
#define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))
#define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))
inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(signed long long a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(unsigned long long a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, signed long long a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, unsigned long long a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, signed long long& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, unsigned long long& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
//
// Compact size
// size < 253 -- 1 byte
// size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
// size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
// size > UINT_MAX -- 9 bytes (255 + 8 bytes)
//
inline unsigned int GetSizeOfCompactSize(uint64_t nSize)
{
if (nSize < 253) return sizeof(unsigned char);
else if (nSize <= std::numeric_limits<unsigned short>::max()) return sizeof(unsigned char) + sizeof(unsigned short);
else if (nSize <= std::numeric_limits<unsigned int>::max()) return sizeof(unsigned char) + sizeof(unsigned int);
else return sizeof(unsigned char) + sizeof(uint64_t);
}
template<typename Stream>
void WriteCompactSize(Stream& os, uint64_t nSize)
{
if (nSize < 253)
{
unsigned char chSize = nSize;
WRITEDATA(os, chSize);
}
else if (nSize <= std::numeric_limits<unsigned short>::max())
{
unsigned char chSize = 253;
unsigned short xSize = nSize;
WRITEDATA(os, chSize);
WRITEDATA(os, xSize);
}
else if (nSize <= std::numeric_limits<unsigned int>::max())
{
unsigned char chSize = 254;
unsigned int xSize = nSize;
WRITEDATA(os, chSize);
WRITEDATA(os, xSize);
}
else
{
unsigned char chSize = 255;
uint64_t xSize = nSize;
WRITEDATA(os, chSize);
WRITEDATA(os, xSize);
}
return;
}
template<typename Stream>
uint64_t ReadCompactSize(Stream& is)
{
unsigned char chSize;
READDATA(is, chSize);
uint64_t nSizeRet = 0;
if (chSize < 253)
{
nSizeRet = chSize;
}
else if (chSize == 253)
{
unsigned short xSize;
READDATA(is, xSize);
nSizeRet = xSize;
if (nSizeRet < 253)
throw std::ios_base::failure("non-canonical ReadCompactSize()");
}
else if (chSize == 254)
{
unsigned int xSize;
READDATA(is, xSize);
nSizeRet = xSize;
if (nSizeRet < 0x10000u)
throw std::ios_base::failure("non-canonical ReadCompactSize()");
}
else
{
uint64_t xSize;
READDATA(is, xSize);
nSizeRet = xSize;
if (nSizeRet < 0x100000000LLu)
throw std::ios_base::failure("non-canonical ReadCompactSize()");
}
if (nSizeRet > (uint64_t)MAX_SIZE)
throw std::ios_base::failure("ReadCompactSize() : size too large");
return nSizeRet;
}
// Variable-length integers: bytes are a MSB base-128 encoding of the number.
// The high bit in each byte signifies whether another digit follows. To make
// the encoding is one-to-one, one is subtracted from all but the last digit.
// Thus, the byte sequence a[] with length len, where all but the last byte
// has bit 128 set, encodes the number:
//
// (a[len-1] & 0x7F) + sum(i=1..len-1, 128^i*((a[len-i-1] & 0x7F)+1))
//
// Properties:
// * Very small (0-127: 1 byte, 128-16511: 2 bytes, 16512-2113663: 3 bytes)
// * Every integer has exactly one encoding
// * Encoding does not depend on size of original integer type
// * No redundancy: every (infinite) byte sequence corresponds to a list
// of encoded integers.
//
// 0: [0x00] 256: [0x81 0x00]
// 1: [0x01] 16383: [0xFE 0x7F]
// 127: [0x7F] 16384: [0xFF 0x00]
// 128: [0x80 0x00] 16511: [0x80 0xFF 0x7F]
// 255: [0x80 0x7F] 65535: [0x82 0xFD 0x7F]
// 2^32: [0x8E 0xFE 0xFE 0xFF 0x00]
template<typename I>
inline unsigned int GetSizeOfVarInt(I n)
{
int nRet = 0;
while(true) {
nRet++;
if (n <= 0x7F)
break;
n = (n >> 7) - 1;
}
return nRet;
}
template<typename Stream, typename I>
void WriteVarInt(Stream& os, I n)
{
unsigned char tmp[(sizeof(n)*8+6)/7];
int len=0;
while(true) {
tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
if (n <= 0x7F)
break;
n = (n >> 7) - 1;
len++;
}
do {
WRITEDATA(os, tmp[len]);
} while(len--);
}
template<typename Stream, typename I>
I ReadVarInt(Stream& is)
{
I n = 0;
while(true) {
unsigned char chData;
READDATA(is, chData);
n = (n << 7) | (chData & 0x7F);
if (chData & 0x80)
n++;
else
return n;
}
}
#define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
#define VARINT(obj) REF(WrapVarInt(REF(obj)))
#define LIMITED_STRING(obj,n) REF(LimitedString< n >(REF(obj)))
/** Wrapper for serializing arrays and POD.
*/
class CFlatData
{
protected:
char* pbegin;
char* pend;
public:
CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
char* begin() { return pbegin; }
const char* begin() const { return pbegin; }
char* end() { return pend; }
const char* end() const { return pend; }
unsigned int GetSerializeSize(int, int=0) const
{
return pend - pbegin;
}
template<typename Stream>
void Serialize(Stream& s, int, int=0) const
{
s.write(pbegin, pend - pbegin);
}
template<typename Stream>
void Unserialize(Stream& s, int, int=0)
{
s.read(pbegin, pend - pbegin);
}
};
template<typename I>
class CVarInt
{
protected:
I &n;
public:
CVarInt(I& nIn) : n(nIn) { }
unsigned int GetSerializeSize(int, int) const {
return GetSizeOfVarInt<I>(n);
}
template<typename Stream>
void Serialize(Stream &s, int, int) const {
WriteVarInt<Stream,I>(s, n);
}
template<typename Stream>
void Unserialize(Stream& s, int, int) {
n = ReadVarInt<Stream,I>(s);
}
};
template<size_t Limit>
class LimitedString
{
protected:
std::string& string;
public:
LimitedString(std::string& string) : string(string) {}
template<typename Stream>
void Unserialize(Stream& s, int, int=0)
{
size_t size = ReadCompactSize(s);
if (size > Limit) {
throw std::ios_base::failure("String length limit exceeded");
}
string.resize(size);
if (size != 0)
s.read((char*)&string[0], size);
}
template<typename Stream>
void Serialize(Stream& s, int, int=0) const
{
WriteCompactSize(s, string.size());
if (!string.empty())
s.write((char*)&string[0], string.size());
}
unsigned int GetSerializeSize(int, int=0) const
{
return GetSizeOfCompactSize(string.size()) + string.size();
}
};
template<typename I>
CVarInt<I> WrapVarInt(I& n) { return CVarInt<I>(n); }
//
// Forward declarations
//
// string
template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
// vector
template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion);
template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion);
template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion);
// others derived from vector
extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion);
template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion);
template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion);
// pair
template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion);
template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion);
template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion);
// 3 tuple
template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
template<typename Stream, typename T0, typename T1, typename T2> void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
// 4 tuple
template<typename T0, typename T1, typename T2, typename T3> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
template<typename Stream, typename T0, typename T1, typename T2, typename T3> void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
template<typename Stream, typename T0, typename T1, typename T2, typename T3> void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
// map
template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion);
template<typename Stream, typename K, typename T, typename Pred, typename A> void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion);
template<typename Stream, typename K, typename T, typename Pred, typename A> void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion);
// set
template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion);
template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion);
template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion);
//
// If none of the specialized versions above matched, default to calling member function.
// "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
// The compiler will only cast int to long if none of the other templates matched.
// Thanks to Boost serialization for this idea.
//
template<typename T>
inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion)
{
return a.GetSerializeSize((int)nType, nVersion);
}
template<typename Stream, typename T>
inline void Serialize(Stream& os, const T& a, long nType, int nVersion)
{
a.Serialize(os, (int)nType, nVersion);
}
template<typename Stream, typename T>
inline void Unserialize(Stream& is, T& a, long nType, int nVersion)
{
a.Unserialize(is, (int)nType, nVersion);
}
//
// string
//
template<typename C>
unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
{
return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
}
template<typename Stream, typename C>
void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
{
WriteCompactSize(os, str.size());
if (!str.empty())
os.write((char*)&str[0], str.size() * sizeof(str[0]));
}
template<typename Stream, typename C>
void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
{
unsigned int nSize = ReadCompactSize(is);
str.resize(nSize);
if (nSize != 0)
is.read((char*)&str[0], nSize * sizeof(str[0]));
}
//
// vector
//
template<typename T, typename A>
unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
{
return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
}
template<typename T, typename A>
unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
{
unsigned int nSize = GetSizeOfCompactSize(v.size());
for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
nSize += GetSerializeSize((*vi), nType, nVersion);
return nSize;
}
template<typename T, typename A>
inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
{
return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
}
template<typename Stream, typename T, typename A>
void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
{
WriteCompactSize(os, v.size());
if (!v.empty())
os.write((char*)&v[0], v.size() * sizeof(T));
}
template<typename Stream, typename T, typename A>
void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
{
WriteCompactSize(os, v.size());
for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
::Serialize(os, (*vi), nType, nVersion);
}
template<typename Stream, typename T, typename A>
inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
{
Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
}
template<typename Stream, typename T, typename A>
void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
{
// Limit size per read so bogus size value won't cause out of memory
v.clear();
unsigned int nSize = ReadCompactSize(is);
unsigned int i = 0;
while (i < nSize)
{
unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
v.resize(i + blk);
is.read((char*)&v[i], blk * sizeof(T));
i += blk;
}
}
template<typename Stream, typename T, typename A>
void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
{
v.clear();
unsigned int nSize = ReadCompactSize(is);
unsigned int i = 0;
unsigned int nMid = 0;
while (nMid < nSize)
{
nMid += 5000000 / sizeof(T);
if (nMid > nSize)
nMid = nSize;
v.resize(nMid);
for (; i < nMid; i++)
Unserialize(is, v[i], nType, nVersion);
}
}
template<typename Stream, typename T, typename A>
inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
{
Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
}
//
// others derived from vector
//
inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
{
return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
}
template<typename Stream>
void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
{
Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
}
template<typename Stream>
void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
{
Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
}
//
// pair
//
template<typename K, typename T>
unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
{
return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
}
template<typename Stream, typename K, typename T>
void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
{
Serialize(os, item.first, nType, nVersion);
Serialize(os, item.second, nType, nVersion);
}
template<typename Stream, typename K, typename T>
void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
{
Unserialize(is, item.first, nType, nVersion);
Unserialize(is, item.second, nType, nVersion);
}
//
// 3 tuple
//
template<typename T0, typename T1, typename T2>
unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
{
unsigned int nSize = 0;
nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
return nSize;
}
template<typename Stream, typename T0, typename T1, typename T2>
void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
{
Serialize(os, boost::get<0>(item), nType, nVersion);
Serialize(os, boost::get<1>(item), nType, nVersion);
Serialize(os, boost::get<2>(item), nType, nVersion);
}
template<typename Stream, typename T0, typename T1, typename T2>
void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
{
Unserialize(is, boost::get<0>(item), nType, nVersion);
Unserialize(is, boost::get<1>(item), nType, nVersion);
Unserialize(is, boost::get<2>(item), nType, nVersion);
}
//
// 4 tuple
//
template<typename T0, typename T1, typename T2, typename T3>
unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
{
unsigned int nSize = 0;
nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
return nSize;
}
template<typename Stream, typename T0, typename T1, typename T2, typename T3>
void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
{
Serialize(os, boost::get<0>(item), nType, nVersion);
Serialize(os, boost::get<1>(item), nType, nVersion);
Serialize(os, boost::get<2>(item), nType, nVersion);
Serialize(os, boost::get<3>(item), nType, nVersion);
}
template<typename Stream, typename T0, typename T1, typename T2, typename T3>
void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
{
Unserialize(is, boost::get<0>(item), nType, nVersion);
Unserialize(is, boost::get<1>(item), nType, nVersion);
Unserialize(is, boost::get<2>(item), nType, nVersion);
Unserialize(is, boost::get<3>(item), nType, nVersion);
}
//
// map
//
template<typename K, typename T, typename Pred, typename A>
unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
{
unsigned int nSize = GetSizeOfCompactSize(m.size());
for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
nSize += GetSerializeSize((*mi), nType, nVersion);
return nSize;
}
template<typename Stream, typename K, typename T, typename Pred, typename A>
void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
{
WriteCompactSize(os, m.size());
for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
Serialize(os, (*mi), nType, nVersion);
}
template<typename Stream, typename K, typename T, typename Pred, typename A>
void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
{
m.clear();
unsigned int nSize = ReadCompactSize(is);
typename std::map<K, T, Pred, A>::iterator mi = m.begin();
for (unsigned int i = 0; i < nSize; i++)
{
std::pair<K, T> item;
Unserialize(is, item, nType, nVersion);
mi = m.insert(mi, item);
}
}
//
// set
//
template<typename K, typename Pred, typename A>
unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
{
unsigned int nSize = GetSizeOfCompactSize(m.size());
for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
nSize += GetSerializeSize((*it), nType, nVersion);
return nSize;
}
template<typename Stream, typename K, typename Pred, typename A>
void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
{
WriteCompactSize(os, m.size());
for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
Serialize(os, (*it), nType, nVersion);
}
template<typename Stream, typename K, typename Pred, typename A>
void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
{
m.clear();
unsigned int nSize = ReadCompactSize(is);
typename std::set<K, Pred, A>::iterator it = m.begin();
for (unsigned int i = 0; i < nSize; i++)
{
K key;
Unserialize(is, key, nType, nVersion);
it = m.insert(it, key);
}
}
//
// Support for IMPLEMENT_SERIALIZE and READWRITE macro
//
class CSerActionGetSerializeSize { };
class CSerActionSerialize { };
class CSerActionUnserialize { };
template<typename Stream, typename T>
inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
{
return ::GetSerializeSize(obj, nType, nVersion);
}
template<typename Stream, typename T>
inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
{
::Serialize(s, obj, nType, nVersion);
return 0;
}
template<typename Stream, typename T>
inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
{
::Unserialize(s, obj, nType, nVersion);
return 0;
}
struct ser_streamplaceholder
{
int nType;
int nVersion;
};
typedef std::vector<char, zero_after_free_allocator<char> > CSerializeData;
/** Double ended buffer combining vector and stream-like interfaces.
*
* >> and << read and write unformatted data using the above serialization templates.
* Fills with data in linear time; some stringstream implementations take N^2 time.
*/
class CDataStream
{
protected:
typedef CSerializeData vector_type;
vector_type vch;
unsigned int nReadPos;
short state;
short exceptmask;
public:
int nType;
int nVersion;
typedef vector_type::allocator_type allocator_type;
typedef vector_type::size_type size_type;
typedef vector_type::difference_type difference_type;
typedef vector_type::reference reference;
typedef vector_type::const_reference const_reference;
typedef vector_type::value_type value_type;
typedef vector_type::iterator iterator;
typedef vector_type::const_iterator const_iterator;
typedef vector_type::reverse_iterator reverse_iterator;
explicit CDataStream(int nTypeIn, int nVersionIn)
{
Init(nTypeIn, nVersionIn);
}
CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
{
Init(nTypeIn, nVersionIn);
}
#if !defined(_MSC_VER) || _MSC_VER >= 1300
CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
{
Init(nTypeIn, nVersionIn);
}
#endif
CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
{
Init(nTypeIn, nVersionIn);
}
CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
{
Init(nTypeIn, nVersionIn);
}
CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])
{
Init(nTypeIn, nVersionIn);
}
void Init(int nTypeIn, int nVersionIn)
{
nReadPos = 0;
nType = nTypeIn;
nVersion = nVersionIn;
state = 0;
exceptmask = std::ios::badbit | std::ios::failbit;
}
CDataStream& operator+=(const CDataStream& b)
{
vch.insert(vch.end(), b.begin(), b.end());
return *this;
}
friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
{
CDataStream ret = a;
ret += b;
return (ret);
}
std::string str() const
{
return (std::string(begin(), end()));
}
//
// Vector subset
//
const_iterator begin() const { return vch.begin() + nReadPos; }
iterator begin() { return vch.begin() + nReadPos; }
const_iterator end() const { return vch.end(); }
iterator end() { return vch.end(); }
size_type size() const { return vch.size() - nReadPos; }
bool empty() const { return vch.size() == nReadPos; }
void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
void reserve(size_type n) { vch.reserve(n + nReadPos); }
const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
reference operator[](size_type pos) { return vch[pos + nReadPos]; }
void clear() { vch.clear(); nReadPos = 0; }
iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
{
assert(last - first >= 0);
if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
{
// special case for inserting at the front when there's room
nReadPos -= (last - first);
memcpy(&vch[nReadPos], &first[0], last - first);
}
else
vch.insert(it, first, last);
}
#if !defined(_MSC_VER) || _MSC_VER >= 1300
void insert(iterator it, const char* first, const char* last)
{
assert(last - first >= 0);
if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
{
// special case for inserting at the front when there's room
nReadPos -= (last - first);
memcpy(&vch[nReadPos], &first[0], last - first);
}
else
vch.insert(it, first, last);
}
#endif
iterator erase(iterator it)
{
if (it == vch.begin() + nReadPos)
{
// special case for erasing from the front
if (++nReadPos >= vch.size())
{
// whenever we reach the end, we take the opportunity to clear the buffer
nReadPos = 0;
return vch.erase(vch.begin(), vch.end());
}
return vch.begin() + nReadPos;
}
else
return vch.erase(it);
}
iterator erase(iterator first, iterator last)
{
if (first == vch.begin() + nReadPos)
{
// special case for erasing from the front
if (last == vch.end())
{
nReadPos = 0;
return vch.erase(vch.begin(), vch.end());
}
else
{
nReadPos = (last - vch.begin());
return last;
}
}
else
return vch.erase(first, last);
}
inline void Compact()
{
vch.erase(vch.begin(), vch.begin() + nReadPos);
nReadPos = 0;
}
bool Rewind(size_type n)
{
// Rewind by n characters if the buffer hasn't been compacted yet
if (n > nReadPos)
return false;
nReadPos -= n;
return true;
}
//
// Stream subset
//
void setstate(short bits, const char* psz)
{
state |= bits;
if (state & exceptmask)
throw std::ios_base::failure(psz);
}
bool eof() const { return size() == 0; }
bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
bool good() const { return !eof() && (state == 0); }
void clear(short n) { state = n; } // name conflict with vector clear()
short exceptions() { return exceptmask; }
short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
CDataStream* rdbuf() { return this; }
int in_avail() { return size(); }
void SetType(int n) { nType = n; }
int GetType() { return nType; }
void SetVersion(int n) { nVersion = n; }
int GetVersion() { return nVersion; }
void ReadVersion() { *this >> nVersion; }
void WriteVersion() { *this << nVersion; }
CDataStream& read(char* pch, int nSize)
{
// Read from the beginning of the buffer
assert(nSize >= 0);
unsigned int nReadPosNext = nReadPos + nSize;
if (nReadPosNext >= vch.size())
{
if (nReadPosNext > vch.size())
{
setstate(std::ios::failbit, "CDataStream::read() : end of data");
memset(pch, 0, nSize);
nSize = vch.size() - nReadPos;
}
memcpy(pch, &vch[nReadPos], nSize);
nReadPos = 0;
vch.clear();
return (*this);
}
memcpy(pch, &vch[nReadPos], nSize);
nReadPos = nReadPosNext;
return (*this);
}
CDataStream& ignore(int nSize)
{
// Ignore from the beginning of the buffer
assert(nSize >= 0);
unsigned int nReadPosNext = nReadPos + nSize;
if (nReadPosNext >= vch.size())
{
if (nReadPosNext > vch.size())
setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
nReadPos = 0;
vch.clear();
return (*this);
}
nReadPos = nReadPosNext;
return (*this);
}
CDataStream& write(const char* pch, int nSize)
{
// Write to the end of the buffer
assert(nSize >= 0);
vch.insert(vch.end(), pch, pch + nSize);
return (*this);
}
template<typename Stream>
void Serialize(Stream& s, int nType, int nVersion) const
{
// Special case: stream << stream concatenates like stream += stream
if (!vch.empty())
s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
}
template<typename T>
unsigned int GetSerializeSize(const T& obj)
{
// Tells the size of the object if serialized to this stream
return ::GetSerializeSize(obj, nType, nVersion);
}
template<typename T>
CDataStream& operator<<(const T& obj)
{
// Serialize to this stream
::Serialize(*this, obj, nType, nVersion);
return (*this);
}
template<typename T>
CDataStream& operator>>(T& obj)
{
// Unserialize from this stream
::Unserialize(*this, obj, nType, nVersion);
return (*this);
}
void GetAndClear(CSerializeData &data) {
data.insert(data.end(), begin(), end());
clear();
}
};
/** RAII wrapper for FILE*.
*
* Will automatically close the file when it goes out of scope if not null.
* If you're returning the file pointer, return file.release().
* If you need to close the file early, use file.fclose() instead of fclose(file).
*/
class CAutoFile
{
protected:
FILE* file;
short state;
short exceptmask;
public:
int nType;
int nVersion;
CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn)
{
file = filenew;
nType = nTypeIn;
nVersion = nVersionIn;
state = 0;
exceptmask = std::ios::badbit | std::ios::failbit;
}
~CAutoFile()
{
fclose();
}
void fclose()
{
if (file != NULL && file != stdin && file != stdout && file != stderr)
::fclose(file);
file = NULL;
}
FILE* release() { FILE* ret = file; file = NULL; return ret; }
operator FILE*() { return file; }
FILE* operator->() { return file; }
FILE& operator*() { return *file; }
FILE** operator&() { return &file; }
FILE* operator=(FILE* pnew) { return file = pnew; }
bool operator!() { return (file == NULL); }
//
// Stream subset
//
void setstate(short bits, const char* psz)
{
state |= bits;
if (state & exceptmask)
throw std::ios_base::failure(psz);
}
bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
bool good() const { return state == 0; }
void clear(short n = 0) { state = n; }
short exceptions() { return exceptmask; }
short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
void SetType(int n) { nType = n; }
int GetType() { return nType; }
void SetVersion(int n) { nVersion = n; }
int GetVersion() { return nVersion; }
void ReadVersion() { *this >> nVersion; }
void WriteVersion() { *this << nVersion; }
CAutoFile& read(char* pch, size_t nSize)
{
if (!file)
throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
if (fread(pch, 1, nSize, file) != nSize)
setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
return (*this);
}
CAutoFile& write(const char* pch, size_t nSize)
{
if (!file)
throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
if (fwrite(pch, 1, nSize, file) != nSize)
setstate(std::ios::failbit, "CAutoFile::write : write failed");
return (*this);
}
template<typename T>
unsigned int GetSerializeSize(const T& obj)
{
// Tells the size of the object if serialized to this stream
return ::GetSerializeSize(obj, nType, nVersion);
}
template<typename T>
CAutoFile& operator<<(const T& obj)
{
// Serialize to this stream
if (!file)
throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
::Serialize(*this, obj, nType, nVersion);
return (*this);
}
template<typename T>
CAutoFile& operator>>(T& obj)
{
// Unserialize from this stream
if (!file)
throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
::Unserialize(*this, obj, nType, nVersion);
return (*this);
}
};
/** Wrapper around a FILE* that implements a ring buffer to
* deserialize from. It guarantees the ability to rewind
* a given number of bytes. */
class CBufferedFile
{
private:
FILE *src; // source file
uint64_t nSrcPos; // how many bytes have been read from source
uint64_t nReadPos; // how many bytes have been read from this
uint64_t nReadLimit; // up to which position we're allowed to read
uint64_t nRewind; // how many bytes we guarantee to rewind
std::vector<char> vchBuf; // the buffer
short state;
short exceptmask;
protected:
void setstate(short bits, const char *psz) {
state |= bits;
if (state & exceptmask)
throw std::ios_base::failure(psz);
}
// read data from the source to fill the buffer
bool Fill() {
unsigned int pos = nSrcPos % vchBuf.size();
unsigned int readNow = vchBuf.size() - pos;
unsigned int nAvail = vchBuf.size() - (nSrcPos - nReadPos) - nRewind;
if (nAvail < readNow)
readNow = nAvail;
if (readNow == 0)
return false;
size_t read = fread((void*)&vchBuf[pos], 1, readNow, src);
if (read == 0) {
setstate(std::ios_base::failbit, feof(src) ? "CBufferedFile::Fill : end of file" : "CBufferedFile::Fill : fread failed");
return false;
} else {
nSrcPos += read;
return true;
}
}
public:
int nType;
int nVersion;
CBufferedFile(FILE *fileIn, uint64_t nBufSize, uint64_t nRewindIn, int nTypeIn, int nVersionIn) :
src(fileIn), nSrcPos(0), nReadPos(0), nReadLimit((uint64_t)(-1)), nRewind(nRewindIn), vchBuf(nBufSize, 0),
state(0), exceptmask(std::ios_base::badbit | std::ios_base::failbit), nType(nTypeIn), nVersion(nVersionIn) {
}
// check whether no error occurred
bool good() const {
return state == 0;
}
// check whether we're at the end of the source file
bool eof() const {
return nReadPos == nSrcPos && feof(src);
}
// read a number of bytes
CBufferedFile& read(char *pch, size_t nSize) {
if (nSize + nReadPos > nReadLimit)
throw std::ios_base::failure("Read attempted past buffer limit");
if (nSize + nRewind > vchBuf.size())
throw std::ios_base::failure("Read larger than buffer size");
while (nSize > 0) {
if (nReadPos == nSrcPos)
Fill();
unsigned int pos = nReadPos % vchBuf.size();
size_t nNow = nSize;
if (nNow + pos > vchBuf.size())
nNow = vchBuf.size() - pos;
if (nNow + nReadPos > nSrcPos)
nNow = nSrcPos - nReadPos;
memcpy(pch, &vchBuf[pos], nNow);
nReadPos += nNow;
pch += nNow;
nSize -= nNow;
}
return (*this);
}
// return the current reading position
uint64_t GetPos() {
return nReadPos;
}
// rewind to a given reading position
bool SetPos(uint64_t nPos) {
nReadPos = nPos;
if (nReadPos + nRewind < nSrcPos) {
nReadPos = nSrcPos - nRewind;
return false;
} else if (nReadPos > nSrcPos) {
nReadPos = nSrcPos;
return false;
} else {
return true;
}
}
bool Seek(uint64_t nPos) {
long nLongPos = nPos;
if (nPos != (uint64_t)nLongPos)
return false;
if (fseek(src, nLongPos, SEEK_SET))
return false;
nLongPos = ftell(src);
nSrcPos = nLongPos;
nReadPos = nLongPos;
state = 0;
return true;
}
// prevent reading beyond a certain position
// no argument removes the limit
bool SetLimit(uint64_t nPos = (uint64_t)(-1)) {
if (nPos < nReadPos)
return false;
nReadLimit = nPos;
return true;
}
template<typename T>
CBufferedFile& operator>>(T& obj) {
// Unserialize from this stream
::Unserialize(*this, obj, nType, nVersion);
return (*this);
}
// search for a given byte in the stream, and remain positioned on it
void FindByte(char ch) {
while (true) {
if (nReadPos == nSrcPos)
Fill();
if (vchBuf[nReadPos % vchBuf.size()] == ch)
break;
nReadPos++;
}
}
};
#endif
| coinkeeper/2015-04-19_21-08_bitmark | src/serialize.h | C | mit | 47,783 |
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System.Collections;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// Containing all necessary information originated from
/// the parameters of <see cref="RemoveCimInstanceCommand"/>
/// </summary>
internal class CimRemoveCimInstanceContext : XOperationContextBase
{
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
/// <param name="theNamespace"></param>
/// <param name="theProxy"></param>
internal CimRemoveCimInstanceContext(string theNamespace,
CimSessionProxy theProxy)
{
this.proxy = theProxy;
this.nameSpace = theNamespace;
}
}
/// <summary>
/// <para>
/// Implements operations of remove-ciminstance cmdlet.
/// </para>
/// </summary>
internal sealed class CimRemoveCimInstance : CimGetInstance
{
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
public CimRemoveCimInstance()
: base()
{
}
/// <summary>
/// <para>
/// Base on parametersetName to retrieve ciminstances
/// </para>
/// </summary>
/// <param name="cmdlet"><see cref="GetCimInstanceCommand"/> object</param>
public void RemoveCimInstance(RemoveCimInstanceCommand cmdlet)
{
DebugHelper.WriteLogEx();
IEnumerable<string> computerNames = ConstValue.GetComputerNames(
GetComputerName(cmdlet));
List<CimSessionProxy> proxys = new List<CimSessionProxy>();
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.CimInstanceComputerSet:
foreach (string computerName in computerNames)
{
proxys.Add(CreateSessionProxy(computerName, cmdlet.CimInstance, cmdlet));
}
break;
case CimBaseCommand.CimInstanceSessionSet:
foreach (CimSession session in GetCimSession(cmdlet))
{
proxys.Add(CreateSessionProxy(session, cmdlet));
}
break;
default:
break;
}
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.CimInstanceComputerSet:
case CimBaseCommand.CimInstanceSessionSet:
string nameSpace = null;
if(cmdlet.ResourceUri != null )
{
nameSpace = GetCimInstanceParameter(cmdlet).CimSystemProperties.Namespace;
}
else
{
nameSpace = ConstValue.GetNamespace(GetCimInstanceParameter(cmdlet).CimSystemProperties.Namespace);
}
string target = cmdlet.CimInstance.ToString();
foreach (CimSessionProxy proxy in proxys)
{
if (!cmdlet.ShouldProcess(target, action))
{
return;
}
proxy.DeleteInstanceAsync(nameSpace, cmdlet.CimInstance);
}
break;
case CimBaseCommand.QueryComputerSet:
case CimBaseCommand.QuerySessionSet:
GetCimInstanceInternal(cmdlet);
break;
default:
break;
}
}
/// <summary>
/// <para>
/// Remove <see cref="CimInstance"/> from namespace specified in cmdlet
/// </para>
/// </summary>
/// <param name="cimInstance"></param>
internal void RemoveCimInstance(CimInstance cimInstance, XOperationContextBase context, CmdletOperationBase cmdlet)
{
DebugHelper.WriteLogEx();
string target = cimInstance.ToString();
if (!cmdlet.ShouldProcess(target, action))
{
return;
}
CimRemoveCimInstanceContext removeContext = context as CimRemoveCimInstanceContext;
Debug.Assert(removeContext != null, "CimRemoveCimInstance::RemoveCimInstance should has CimRemoveCimInstanceContext != NULL.");
CimSessionProxy proxy = CreateCimSessionProxy(removeContext.Proxy);
proxy.DeleteInstanceAsync(removeContext.Namespace, cimInstance);
}
#region const strings
/// <summary>
/// action
/// </summary>
private const string action = @"Remove-CimInstance";
#endregion
}//End Class
}//End namespace
| KarolKaczmarek/PowerShell | src/Microsoft.Management.Infrastructure.CimCmdlets/CimRemoveCimInstance.cs | C# | mit | 5,165 |
# -*- coding: utf-8 -*-
from __future__ import print_function, division
from qsrlib_qsrs.qsr_rcc_abstractclass import QSR_RCC_Abstractclass
class QSR_RCC8(QSR_RCC_Abstractclass):
"""Symmetrical RCC5 relations.
Values of the abstract properties
* **_unique_id** = "rcc8"
* **_all_possible_relations** = ("dc", "ec", "po", "eq", "tpp", "ntpp", "tppi", "ntppi")
* **_dtype** = "bounding_boxes_2d"
QSR specific `dynamic_args`
* **'quantisation_factor'** (*float*) = 0.0: Threshold that determines whether two rectangle regions are disconnected.
.. seealso:: For further details about RCC8, refer to its :doc:`description. <../handwritten/qsrs/rcc8>`
"""
_unique_id = "rcc8"
"""str: Unique identifier name of the QSR."""
_all_possible_relations = ("dc", "ec", "po", "eq", "tpp", "ntpp", "tppi", "ntppi")
"""tuple: All possible relations of the QSR."""
def __init__(self):
"""Constructor."""
super(QSR_RCC8, self).__init__()
def _convert_to_requested_rcc_type(self, qsr):
"""No need for remapping.
:param qsr: RCC8 value.
:type qsr: str
:return: RCC8 value.
:rtype: str
"""
return qsr
| cdondrup/strands_qsr_lib | qsr_lib/src/qsrlib_qsrs/qsr_rcc8.py | Python | mit | 1,237 |
/*
* F21Handler.cpp
*
* Created on: 15 maj 2014
* Author: MattLech
*/
#include "F21Handler.h"
static F21Handler *instance;
F21Handler *F21Handler::getInstance()
{
if (!instance)
{
instance = new F21Handler();
};
return instance;
};
F21Handler::F21Handler()
{
}
int F21Handler::execute(Command *command)
{
ParameterList::getInstance()->readValue(command->getP());
return 0;
}
| FarmBot/farmbot-arduino-firmware | src/F21Handler.cpp | C++ | mit | 409 |
/*
* /MathJax/jax/output/HTML-CSS/fonts/STIX/IntegralsUpSm/Regular/All.js
*
* Copyright (c) 2009-2016 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS.STIXIntegralsUpSm,{32:[0,0,250,0,0],160:[0,0,250,0,0],8748:[690,189,587,52,605],8749:[690,189,817,52,835],8751:[690,189,682,52,642],8752:[690,189,909,52,869],8753:[690,189,480,52,447],8754:[690,189,480,52,448],8755:[690,189,480,52,470],10763:[694,190,556,41,515],10764:[694,190,1044,68,1081],10765:[694,190,420,68,391],10766:[694,190,420,68,391],10767:[694,190,520,39,482],10768:[694,190,324,41,380],10769:[694,190,480,52,447],10770:[694,190,450,68,410],10771:[690,189,450,68,412],10772:[690,189,550,68,512],10773:[690,189,450,50,410],10774:[694,191,450,50,410],10775:[694,190,611,12,585],10776:[694,190,450,48,412],10777:[694,190,450,59,403],10778:[694,190,450,59,403],10779:[784,189,379,68,416],10780:[690,283,357,52,400]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/IntegralsUpSm/Regular/All.js");
| masterfish2015/my_project | 半导体物理/js/mathjax/jax/output/HTML-CSS/fonts/STIX/IntegralsUpSm/Regular/All.js | JavaScript | mit | 1,609 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.catalina.valves.rewrite;
import java.util.ArrayList;
import java.util.Map;
import java.util.regex.Matcher;
public class Substitution {
public abstract class SubstitutionElement {
public abstract String evaluate(Matcher rule, Matcher cond, Resolver resolver);
}
public class StaticElement extends SubstitutionElement {
public String value;
@Override
public String evaluate
(Matcher rule, Matcher cond, Resolver resolver) {
return value;
}
}
public class RewriteRuleBackReferenceElement extends SubstitutionElement {
public int n;
@Override
public String evaluate(Matcher rule, Matcher cond, Resolver resolver) {
return rule.group(n);
}
}
public class RewriteCondBackReferenceElement extends SubstitutionElement {
public int n;
@Override
public String evaluate(Matcher rule, Matcher cond, Resolver resolver) {
return cond.group(n);
}
}
public class ServerVariableElement extends SubstitutionElement {
public String key;
@Override
public String evaluate(Matcher rule, Matcher cond, Resolver resolver) {
return resolver.resolve(key);
}
}
public class ServerVariableEnvElement extends SubstitutionElement {
public String key;
@Override
public String evaluate(Matcher rule, Matcher cond, Resolver resolver) {
return resolver.resolveEnv(key);
}
}
public class ServerVariableSslElement extends SubstitutionElement {
public String key;
@Override
public String evaluate(Matcher rule, Matcher cond, Resolver resolver) {
return resolver.resolveSsl(key);
}
}
public class ServerVariableHttpElement extends SubstitutionElement {
public String key;
@Override
public String evaluate(Matcher rule, Matcher cond, Resolver resolver) {
return resolver.resolveHttp(key);
}
}
public class MapElement extends SubstitutionElement {
public RewriteMap map = null;
public String key;
public String defaultValue = null;
@Override
public String evaluate(Matcher rule, Matcher cond, Resolver resolver) {
String result = map.lookup(key);
if (result == null) {
result = defaultValue;
}
return result;
}
}
protected SubstitutionElement[] elements = null;
protected String sub = null;
public String getSub() { return sub; }
public void setSub(String sub) { this.sub = sub; }
public void parse(Map<String, RewriteMap> maps) {
ArrayList<SubstitutionElement> elements = new ArrayList<>();
int pos = 0;
int percentPos = 0;
int dollarPos = 0;
while (pos < sub.length()) {
percentPos = sub.indexOf('%', pos);
dollarPos = sub.indexOf('$', pos);
if (percentPos == -1 && dollarPos == -1) {
// Static text
StaticElement newElement = new StaticElement();
newElement.value = sub.substring(pos, sub.length());
pos = sub.length();
elements.add(newElement);
} else if (percentPos == -1 || ((dollarPos != -1) && (dollarPos < percentPos))) {
// $: back reference to rule or map lookup
if (dollarPos + 1 == sub.length()) {
throw new IllegalArgumentException(sub);
}
if (pos < dollarPos) {
// Static text
StaticElement newElement = new StaticElement();
newElement.value = sub.substring(pos, dollarPos);
pos = dollarPos;
elements.add(newElement);
}
if (Character.isDigit(sub.charAt(dollarPos + 1))) {
// $: back reference to rule
RewriteRuleBackReferenceElement newElement = new RewriteRuleBackReferenceElement();
newElement.n = Character.digit(sub.charAt(dollarPos + 1), 10);
pos = dollarPos + 2;
elements.add(newElement);
} else {
// $: map lookup as ${mapname:key|default}
MapElement newElement = new MapElement();
int open = sub.indexOf('{', dollarPos);
int colon = sub.indexOf(':', dollarPos);
int def = sub.indexOf('|', dollarPos);
int close = sub.indexOf('}', dollarPos);
if (!(-1 < open && open < colon && colon < close)) {
throw new IllegalArgumentException(sub);
}
newElement.map = maps.get(sub.substring(open + 1, colon));
if (newElement.map == null) {
throw new IllegalArgumentException(sub + ": No map: " + sub.substring(open + 1, colon));
}
if (def > -1) {
if (!(colon < def && def < close)) {
throw new IllegalArgumentException(sub);
}
newElement.key = sub.substring(colon + 1, def);
newElement.defaultValue = sub.substring(def + 1, close);
} else {
newElement.key = sub.substring(colon + 1, close);
}
pos = close + 1;
elements.add(newElement);
}
} else {
// %: back reference to condition or server variable
if (percentPos + 1 == sub.length()) {
throw new IllegalArgumentException(sub);
}
if (pos < percentPos) {
// Static text
StaticElement newElement = new StaticElement();
newElement.value = sub.substring(pos, percentPos);
pos = percentPos;
elements.add(newElement);
}
if (Character.isDigit(sub.charAt(percentPos + 1))) {
// %: back reference to condition
RewriteCondBackReferenceElement newElement = new RewriteCondBackReferenceElement();
newElement.n = Character.digit(sub.charAt(percentPos + 1), 10);
pos = percentPos + 2;
elements.add(newElement);
} else {
// %: server variable as %{variable}
SubstitutionElement newElement = null;
int open = sub.indexOf('{', percentPos);
int colon = sub.indexOf(':', percentPos);
int close = sub.indexOf('}', percentPos);
if (!(-1 < open && open < close)) {
throw new IllegalArgumentException(sub);
}
if (colon > -1) {
if (!(open < colon && colon < close)) {
throw new IllegalArgumentException(sub);
}
String type = sub.substring(open + 1, colon);
if (type.equals("ENV")) {
newElement = new ServerVariableEnvElement();
((ServerVariableEnvElement) newElement).key = sub.substring(colon + 1, close);
} else if (type.equals("SSL")) {
newElement = new ServerVariableSslElement();
((ServerVariableSslElement) newElement).key = sub.substring(colon + 1, close);
} else if (type.equals("HTTP")) {
newElement = new ServerVariableHttpElement();
((ServerVariableHttpElement) newElement).key = sub.substring(colon + 1, close);
} else {
throw new IllegalArgumentException(sub + ": Bad type: " + type);
}
} else {
newElement = new ServerVariableElement();
((ServerVariableElement) newElement).key = sub.substring(open + 1, close);
}
pos = close + 1;
elements.add(newElement);
}
}
}
this.elements = elements.toArray(new SubstitutionElement[0]);
}
/**
* Evaluate the substitution based on the context
*
* @param rule corresponding matched rule
* @param cond last matched condition
*/
public String evaluate(Matcher rule, Matcher cond, Resolver resolver) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < elements.length; i++) {
buf.append(elements[i].evaluate(rule, cond, resolver));
}
return buf.toString();
}
}
| plumer/codana | tomcat_files/8.0.21/Substitution.java | Java | mit | 9,922 |
//-*****************************************************************************
//
// Copyright (c) 2009-2011,
// Sony Pictures Imageworks, Inc. and
// Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Sony Pictures Imageworks, nor
// Industrial Light & Magic nor the names of their contributors may be used
// to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//-*****************************************************************************
#include <Alembic/Abc/ICompoundProperty.h>
namespace Alembic {
namespace Abc {
namespace ALEMBIC_VERSION_NS {
//-*****************************************************************************
ICompoundProperty::~ICompoundProperty()
{
// Here for debug support
}
//-*****************************************************************************
size_t ICompoundProperty::getNumProperties() const
{
ALEMBIC_ABC_SAFE_CALL_BEGIN( "ICompoundProperty::getNumProperties()" );
return m_property->getNumProperties();
ALEMBIC_ABC_SAFE_CALL_END();
// Not all error handlers throw, have a default.
return 0;
}
//-*****************************************************************************
const AbcA::PropertyHeader &ICompoundProperty::getPropertyHeader( size_t iIdx ) const
{
ALEMBIC_ABC_SAFE_CALL_BEGIN( "ICompoundProperty::getPropertyHeader()" );
return m_property->getPropertyHeader( iIdx );
ALEMBIC_ABC_SAFE_CALL_END();
// Not all error handlers throw, have a default.
static const AbcA::PropertyHeader hd;
return hd;
}
//-*****************************************************************************
const AbcA::PropertyHeader *
ICompoundProperty::getPropertyHeader( const std::string &iName ) const
{
ALEMBIC_ABC_SAFE_CALL_BEGIN( "ICompoundProperty::getPropertyHeader()" );
return m_property->getPropertyHeader( iName );
ALEMBIC_ABC_SAFE_CALL_END();
// Not all error handlers throw, have a default.
return NULL;
}
//-*****************************************************************************
ICompoundProperty ICompoundProperty::getParent() const
{
ALEMBIC_ABC_SAFE_CALL_BEGIN( "ICompoundProperty::getParent()" );
return ICompoundProperty( m_property->getParent(),
kWrapExisting,
getErrorHandlerPolicy() );
ALEMBIC_ABC_SAFE_CALL_END();
// Not all error handlers throw. Have a default.
return ICompoundProperty();
}
//-*****************************************************************************
void ICompoundProperty::init( AbcA::CompoundPropertyReaderPtr iParent,
const std::string &iName,
ErrorHandler::Policy iParentPolicy,
const Argument &iArg0 )
{
Arguments args( iParentPolicy );
iArg0.setInto( args );
getErrorHandler().setPolicy( args.getErrorHandlerPolicy() );
ALEMBIC_ABC_SAFE_CALL_BEGIN( "ICompoundProperty::init()" );
ABCA_ASSERT( iParent, "invalid parent" );
const AbcA::PropertyHeader *pheader =
iParent->getPropertyHeader( iName );
ABCA_ASSERT( pheader != NULL,
"Nonexistent compound property: " << iName );
m_property = iParent->getCompoundProperty( iName );
ALEMBIC_ABC_SAFE_CALL_END_RESET();
}
} // End namespace ALEMBIC_VERSION_NS
} // End namespace Abc
} // End namespace Alembic
| uimac/walker | lib/alembic/include/Alembic/Abc/ICompoundProperty.cpp | C++ | mit | 4,822 |
namespace Nancy.Routing
{
using System;
using System.Collections.Generic;
/// <summary>
/// Represents the various parts of a route lambda.
/// </summary>
public sealed class RouteDescription
{
/// <summary>
/// Initializes a new instance of the <see cref="RouteDescription"/> class.
/// </summary>
/// <param name="name">Route name</param>
/// <param name="method">The request method of the route.</param>
/// <param name="path">The path that the route will be invoked for.</param>
/// <param name="condition">The condition that has to be fulfilled for the route to be a valid match.</param>
public RouteDescription(string name, string method, string path, Func<NancyContext, bool> condition)
{
if (String.IsNullOrEmpty(method))
{
throw new ArgumentException("Method must be specified", method);
}
if (String.IsNullOrEmpty(path))
{
throw new ArgumentException("Path must be specified", method);
}
this.Name = name ?? string.Empty;
this.Method = method;
this.Path = path;
this.Condition = condition;
}
/// <summary>
/// The name of the route
/// </summary>
public string Name { get; set; }
/// <summary>
/// The condition that has to be fulfilled inorder for the route to be a valid match.
/// </summary>
/// <value>A function that evaluates the condition when a <see cref="NancyContext"/> instance is passed in.</value>
public Func<NancyContext, bool> Condition { get; private set; }
/// <summary>
/// The description of what the route is for.
/// </summary>
/// <value>A <see cref="string"/> containing the description of the route.</value>
public string Description { get; set; }
/// <summary>
/// Gets or sets the metadata information for a route.
/// </summary>
/// <value>A <see cref="RouteMetadata"/> instance.</value>
public RouteMetadata Metadata { get; set; }
/// <summary>
/// Gets the method of the route.
/// </summary>
/// <value>A <see cref="string"/> containing the method of the route.</value>
public string Method { get; private set; }
/// <summary>
/// Gets the path that the route will be invoked for.
/// </summary>
/// <value>A <see cref="string"/> containing the path of the route.</value>
public string Path { get; private set; }
/// <summary>
/// Gets or set the segments, for the route, that was returned by the <see cref="IRouteSegmentExtractor"/>.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/>, containing the segments for the route.</value>
public IEnumerable<string> Segments { get; set; }
}
} | yannisgu/Nancy | src/Nancy/Routing/RouteDescription.cs | C# | mit | 3,057 |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using Microsoft.Azure.WebJobs.Host.Converters;
using Microsoft.Azure.WebJobs.Host.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Blob;
namespace Microsoft.Azure.WebJobs.Host.Blobs
{
internal class StorageBlobToCloudBlockBlobConverter : IConverter<IStorageBlob, CloudBlockBlob>
{
public CloudBlockBlob Convert(IStorageBlob input)
{
if (input == null)
{
return null;
}
IStorageBlockBlob blockBlob = input as IStorageBlockBlob;
if (blockBlob == null)
{
throw new InvalidOperationException("The blob is not a block blob.");
}
return blockBlob.SdkObject;
}
}
}
| brendankowitz/azure-webjobs-sdk | src/Microsoft.Azure.WebJobs.Host/Blobs/StorageBlobToCloudBlockBlobConverter.cs | C# | mit | 923 |
<!doctype html>
<html lang="en" ng-app="docsApp" ng-strict-di ng-controller="DocsController">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="Description"
content="AngularJS is what HTML would have been, had it been designed for building web-apps.
Declarative templates with data-binding, MVC, dependency injection and great
testability story all implemented with pure client-side JavaScript!">
<meta name="fragment" content="!">
<title ng-bind-template="AngularJS: {{ currentArea.name }}: {{ currentPage.name || 'Error: Page not found'}}">AngularJS</title>
<script type="text/javascript">
// dynamically add base tag as well as css and javascript files.
// we can't add css/js the usual way, because some browsers (FF) eagerly prefetch resources
// before the base attribute is added, causing 404 and terribly slow loading of the docs app.
(function() {
var indexFile = (location.pathname.match(/\/(index[^\.]*\.html)/) || ['', ''])[1],
rUrl = /(#!\/|api|guide|misc|tutorial|error|index[^\.]*\.html).*$/,
baseUrl = location.href.replace(rUrl, indexFile),
production = location.hostname === 'docs.angularjs.org',
headEl = document.getElementsByTagName('head')[0],
sync = true;
addTag('base', {href: baseUrl});
addTag('link', {rel: 'stylesheet', href: 'components/bootstrap-3.1.1/css/bootstrap.min.css', type: 'text/css'});
addTag('link', {rel: 'stylesheet', href: 'components/open-sans-fontface-1.0.4/open-sans.css', type: 'text/css'});
addTag('link', {rel: 'stylesheet', href: 'css/prettify-theme.css', type: 'text/css'});
addTag('link', {rel: 'stylesheet', href: 'css/docs.css', type: 'text/css'});
addTag('link', {rel: 'stylesheet', href: 'css/animations.css', type: 'text/css'});
addTag('script', {src: '//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js' }, sync);
addTag('script', {src: '//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular-resource.min.js' }, sync);
addTag('script', {src: '//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular-route.min.js' }, sync);
addTag('script', {src: '//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular-cookies.min.js' }, sync);
addTag('script', {src: '//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular-sanitize.min.js' }, sync);
addTag('script', {src: '//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular-touch.min.js' }, sync);
addTag('script', {src: '//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular-animate.min.js' }, sync);
addTag('script', {src: 'components/marked-0.3.2/lib/marked.js' }, sync);
addTag('script', {src: 'js/angular-bootstrap/bootstrap.min.js' }, sync);
addTag('script', {src: 'js/angular-bootstrap/dropdown-toggle.min.js' }, sync);
addTag('script', {src: 'components/lunr.js-0.4.2/lunr.min.js' }, sync);
addTag('script', {src: 'components/google-code-prettify-1.0.1/src/prettify.js' }, sync);
addTag('script', {src: 'components/google-code-prettify-1.0.1/src/lang-css.js' }, sync);
addTag('script', {src: 'js/versions-data.js' }, sync);
addTag('script', {src: 'js/pages-data.js' }, sync);
addTag('script', {src: 'js/nav-data.js' }, sync);
addTag('script', {src: 'js/docs.min.js' }, sync);
function addTag(name, attributes, sync) {
var el = document.createElement(name),
attrName;
for (attrName in attributes) {
el.setAttribute(attrName, attributes[attrName]);
}
sync ? document.write(outerHTML(el)) : headEl.appendChild(el);
}
function outerHTML(node){
// if IE, Chrome take the internal method otherwise build one
return node.outerHTML || (
function(n){
var div = document.createElement('div'), h;
div.appendChild(n);
h = div.innerHTML;
div = null;
return h;
})(node);
}
})();
// GA asynchronous tracker
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-8594346-3']);
_gaq.push(['_setDomainName', '.angularjs.org']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<div id="wrapper">
<header scroll-y-offset-element class="header header-fixed">
<section class="navbar navbar-inverse docs-navbar-primary" ng-controller="DocsSearchCtrl">
<div class="container">
<div class="row">
<div class="col-md-9 header-branding">
<a class="brand navbar-brand" href="http://angularjs.org">
<img width="117" height="30" class="logo" ng-src="img/angularjs-for-header-only.svg">
</a>
<ul class="nav navbar-nav">
<li class="divider-vertical"></li>
<li><a href="http://angularjs.org"><i class="icon-home icon-white"></i> Home</a></li>
<li class="divider-vertical"></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-eye-open icon-white"></i> Learn <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li class="disabled"><a href="http://angularjs.org/">Why AngularJS?</a></li>
<li><a href="http://www.youtube.com/user/angularjs">Watch</a></li>
<li><a href="tutorial">Tutorial</a></li>
<li><a href="http://builtwith.angularjs.org/">Case Studies</a></li>
<li><a href="https://github.com/angular/angular-seed">Seed App project template</a></li>
<li><a href="misc/faq">FAQ</a></li>
</ul>
</li>
<li class="divider-vertical"></li>
<li class="dropdown active">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-book icon-white"></i> Develop <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="tutorial">Tutorial</a></li>
<li><a href="guide">Developer Guide</a></li>
<li><a href="api">API Reference</a></li>
<li><a href="error">Error Reference</a></li>
<li><a href="misc/contribute">Contribute</a></li>
<li><a href="http://code.angularjs.org/">Download</a></li>
</ul>
</li>
<li class="divider-vertical"></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-comment icon-white"></i> Discuss <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="http://blog.angularjs.org">Blog</a></li>
<li><a href="http://groups.google.com/group/angular">Mailing List</a></li>
<li><a href="http://webchat.freenode.net/?channels=angularjs&uio=d4">Chat Room</a></li>
<li class="divider"></li>
<li><a href="https://twitter.com/#!/angularjs">Twitter</a></li>
<li><a href="https://plus.google.com/110323587230527980117">Google+</a></li>
<li class="divider"></li>
<li><a href="https://github.com/angular/angular.js">GitHub</a></li>
<li><a href="https://github.com/angular/angular.js/issues">Issue Tracker</a></li>
</ul>
</li>
<li class="divider-vertical"></li>
</ul>
</div>
<form ng-class="{focus:focus}" class="navbar-search col-md-3 docs-search" ng-submit="submit()">
<span class="glyphicon glyphicon-search search-icon"></span>
<input type="text"
name="as_q"
class="search-query"
placeholder="Click or press / to search"
ng-focus="focus=true"
ng-blur="focus=false"
ng-change="search(q)"
ng-model="q"
docs-search-input
autocomplete="off" />
</form>
</div>
</div>
<div class="search-results-container" ng-show="hasResults">
<div class="container">
<div class="search-results-frame">
<div ng-repeat="(key, value) in results" class="search-results-group" ng-class="colClassName + ' col-group-' + key">
<h4 class="search-results-group-heading">{{ key }}</h4>
<div class="search-results">
<div ng-repeat="item in value" class="search-result">
- <a ng-click="hideResults()" ng-href="{{ item.path }}">{{ item.name }}</a>
</div>
</div>
</div>
</div>
<a href="" ng-click="hideResults()" class="search-close">
<span class="glyphicon glyphicon-remove search-close-icon"></span> Close
</a>
</div>
</div>
</section>
<section class="sup-header">
<div class="container main-grid main-header-grid">
<div class="grid-left">
<div ng-controller="DocsVersionsCtrl" class="picker version-picker">
<select ng-options="v as ('v' + v.version + (v.isSnapshot ? ' (snapshot)' : '')) group by getGroupName(v) for v in docs_versions"
ng-model="docs_version"
ng-change="jumpToDocsVersion(docs_version)"
class="docs-version-jump">
</select>
</div>
</div>
<div class="grid-right">
<ul class="nav-breadcrumb">
<li ng-repeat="crumb in breadcrumb" class="nav-breadcrumb-entry naked-list">
<span class="divider"> /</span>
<a ng-href="{{crumb.url}}">{{crumb.name}}</a>
</li>
</ul>
</div>
</div>
</section>
</header>
<section role="main" class="container main-body">
<div class="main-grid main-body-grid">
<div class="grid-left">
<a class="btn toc-toggle visible-xs" ng-click="toc=!toc">Show / Hide Table of Contents</a>
<div class="side-navigation" ng-show="toc==true">
<ul class="nav-list naked-list">
<li ng-repeat="navGroup in currentArea.navGroups track by navGroup.name" class="nav-index-group">
<a href="{{ navGroup.href }}" ng-class="navClass(navGroup)" class="nav-index-group-heading">{{ navGroup.name }}</a>
<ul class="aside-nav">
<li ng-repeat="navItem in navGroup.navItems" ng-class="navClass(navItem)" class="nav-index-listing">
<a ng-if="navItem.extra.href" ng-class="navClass(navItem.extra)" href="{{navItem.extra.href}}">
{{navItem.extra.text}}<i ng-if="navItem.extra.icon" class="icon-{{navItem.extra.icon}}"></i>
</a>
<a tabindex="2" ng-class="linkClass(navItem)" href="{{navItem.href}}">{{navItem.name}}</a>
</li>
</ul>
</li>
</ul>
<a href="" ng-click="toc=false" class="toc-close visible-xs">
<span class="glyphicon glyphicon-remove toc-close-icon"></span> Close
</a>
</div>
</div>
<div class="grid-right">
<div id="loading" ng-show="loading">Loading...</div>
<div ng-hide="loading" ng-include="partialPath" autoscroll></div>
</div>
</div>
</section>
<footer class="footer">
<div class="container">
<p class="pull-right"><a back-to-top>Back to top</a></p>
<p>
Super-powered by Google ©2010-2014
( <a id="version"
ng-href="https://github.com/angular/angular.js/blob/master/CHANGELOG.md#{{versionNumber}}"
ng-bind-template="v{{version}}">
</a>
)
</p>
<p>
Code licensed under the
<a href="https://github.com/angular/angular.js/blob/master/LICENSE" target="_blank">The
MIT License</a>. Documentation licensed under <a
href="http://creativecommons.org/licenses/by/3.0/">CC BY 3.0</a>.
</p>
</div>
</footer>
</div>
</body>
</html>
| viral810/ngSimpleCMS | web/bundles/sunraangular/js/angular/angular-1.3.3/docs/index-production.html | HTML | mit | 13,105 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="robots" content="index, follow, all" />
<title>Thelia\Model\Base\Order | Thelia 2 API</title>
<link rel="stylesheet" type="text/css" href="../../../css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="../../../css/bootstrap-theme.min.css">
<link rel="stylesheet" type="text/css" href="../../../css/sami.css">
<script src="../../../js/jquery-1.11.1.min.js"></script>
<script src="../../../js/bootstrap.min.js"></script>
<script src="../../../js/typeahead.min.js"></script>
<script src="../../../sami.js"></script>
<meta name="MobileOptimized" content="width">
<meta name="HandheldFriendly" content="true">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
</head>
<body id="class" data-name="class:Thelia_Model_Base_Order" data-root-path="../../../">
<div id="content">
<div id="left-column">
<div id="control-panel">
<form id="search-form" action="../../../search.html" method="GET">
<span class="glyphicon glyphicon-search"></span>
<input name="search"
class="typeahead form-control"
type="search"
placeholder="Search">
</form>
</div>
<div id="api-tree"></div>
</div>
<div id="right-column">
<nav id="site-nav" class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-elements">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../../../index.html">Thelia 2 API</a>
</div>
<div class="collapse navbar-collapse" id="navbar-elements">
<ul class="nav navbar-nav">
<li><a href="../../../classes.html">Classes</a></li>
<li><a href="../../../namespaces.html">Namespaces</a></li>
<li><a href="../../../interfaces.html">Interfaces</a></li>
<li><a href="../../../traits.html">Traits</a></li>
<li><a href="../../../doc-index.html">Index</a></li>
<li><a href="../../../search.html">Search</a></li>
</ul>
</div>
</div>
</nav>
<div class="namespace-breadcrumbs">
<ol class="breadcrumb">
<li><span class="label label-default">class</span></li>
<li><a href="../../../Thelia.html">Thelia</a></li>
<li><a href="../../../Thelia/Model.html">Model</a></li>
<li><a href="../../../Thelia/Model/Base.html">Base</a></li>
<li>Order</li>
</ol>
</div>
<div id="page-content">
<div class="page-header">
<h1>Order</h1>
</div>
<p> class
<strong>Order</strong> implements
<abbr title="Propel\Runtime\ActiveRecord\ActiveRecordInterface">ActiveRecordInterface</abbr>
</p>
<h2>Constants</h2>
<table class="table table-condensed">
<tr>
<td>TABLE_MAP</td>
<td class="last">
<p><em>TableMap class name</em></p>
<p></p>
</td>
</tr>
</table>
<h2>Methods</h2>
<div class="container-fluid underlined">
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_applyDefaultValues">applyDefaultValues</a>()
<p>Applies default values to this object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method___construct">__construct</a>()
<p>Initializes internal state of Thelia\Model\Base\Order object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
boolean
</div>
<div class="col-md-8 type">
<a href="#method_isModified">isModified</a>()
<p>Returns whether the object has been modified.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
boolean
</div>
<div class="col-md-8 type">
<a href="#method_isColumnModified">isColumnModified</a>(
string $col)
<p>Has specified column been modified?</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
array
</div>
<div class="col-md-8 type">
<a href="#method_getModifiedColumns">getModifiedColumns</a>()
<p>Get the columns that have been modified in this object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
boolean
</div>
<div class="col-md-8 type">
<a href="#method_isNew">isNew</a>()
<p>Returns whether the object has ever been saved. This will
be false, if the object was retrieved from storage or was created
and then saved.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_setNew">setNew</a>(
boolean $b)
<p>Setter for the isNew attribute. This method will be called
by Propel-generated children and objects.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
boolean
</div>
<div class="col-md-8 type">
<a href="#method_isDeleted">isDeleted</a>()
<p>Whether this object has been deleted.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
void
</div>
<div class="col-md-8 type">
<a href="#method_setDeleted">setDeleted</a>(
boolean $b)
<p>Specify whether this object has been deleted.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
void
</div>
<div class="col-md-8 type">
<a href="#method_resetModified">resetModified</a>(
string $col = null)
<p>Sets the modified state for the object to be false.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
boolean
</div>
<div class="col-md-8 type">
<a href="#method_equals">equals</a>(
mixed $obj)
<p>Compares this with another <code>Order</code> instance. If
<code>obj</code> is an instance of <code>Order</code>, delegates to
<code>equals(Order)</code>. Otherwise, returns <code>false</code>.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
int
</div>
<div class="col-md-8 type">
<a href="#method_hashCode">hashCode</a>()
<p>If the primary key is not null, return the hashcode of the
primary key. Otherwise, return the hash code of the object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
array
</div>
<div class="col-md-8 type">
<a href="#method_getVirtualColumns">getVirtualColumns</a>()
<p>Get the associative array of the virtual columns in this object</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
boolean
</div>
<div class="col-md-8 type">
<a href="#method_hasVirtualColumn">hasVirtualColumn</a>(
string $name)
<p>Checks the existence of a virtual column in this object</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
mixed
</div>
<div class="col-md-8 type">
<a href="#method_getVirtualColumn">getVirtualColumn</a>(
string $name)
<p>Get the value of a virtual column in this object</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Base/Order.html"><abbr title="Thelia\Model\Base\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setVirtualColumn">setVirtualColumn</a>(
string $name,
mixed $value)
<p>Set the value of a virtual column in this object</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Base/Order.html"><abbr title="Thelia\Model\Base\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_importFrom">importFrom</a>(
mixed $parser,
string $data)
<p>Populate the current object from a string, using a given parser format
<code>
$book = new Book();
$book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}');
</code></p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
string
</div>
<div class="col-md-8 type">
<a href="#method_exportTo">exportTo</a>(
mixed $parser,
boolean $includeLazyLoadColumns = true)
<p>Export the current object properties to a string, using a given parser format
<code>
$book = BookQuery::create()->findPk(9012);
echo $book->exportTo('JSON');
=> {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}');
</code></p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method___sleep">__sleep</a>()
<p>Clean up internal collections prior to serializing
Avoids recursive loops that turn into segmentation faults when serializing</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
int
</div>
<div class="col-md-8 type">
<a href="#method_getId">getId</a>()
<p>Get the [id] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
string
</div>
<div class="col-md-8 type">
<a href="#method_getRef">getRef</a>()
<p>Get the [ref] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
int
</div>
<div class="col-md-8 type">
<a href="#method_getCustomerId">getCustomerId</a>()
<p>Get the [customer_id] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
int
</div>
<div class="col-md-8 type">
<a href="#method_getInvoiceOrderAddressId">getInvoiceOrderAddressId</a>()
<p>Get the [invoice<em>order</em>address_id] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
int
</div>
<div class="col-md-8 type">
<a href="#method_getDeliveryOrderAddressId">getDeliveryOrderAddressId</a>()
<p>Get the [delivery<em>order</em>address_id] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
mixed
</div>
<div class="col-md-8 type">
<a href="#method_getInvoiceDate">getInvoiceDate</a>(
string $format = NULL)
<p>Get the [optionally formatted] temporal [invoice_date] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
int
</div>
<div class="col-md-8 type">
<a href="#method_getCurrencyId">getCurrencyId</a>()
<p>Get the [currency_id] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
double
</div>
<div class="col-md-8 type">
<a href="#method_getCurrencyRate">getCurrencyRate</a>()
<p>Get the [currency_rate] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
string
</div>
<div class="col-md-8 type">
<a href="#method_getTransactionRef">getTransactionRef</a>()
<p>Get the [transaction_ref] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
string
</div>
<div class="col-md-8 type">
<a href="#method_getDeliveryRef">getDeliveryRef</a>()
<p>Get the [delivery_ref] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
string
</div>
<div class="col-md-8 type">
<a href="#method_getInvoiceRef">getInvoiceRef</a>()
<p>Get the [invoice_ref] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
string
</div>
<div class="col-md-8 type">
<a href="#method_getDiscount">getDiscount</a>()
<p>Get the [discount] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
string
</div>
<div class="col-md-8 type">
<a href="#method_getPostage">getPostage</a>()
<p>Get the [postage] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
string
</div>
<div class="col-md-8 type">
<a href="#method_getPostageTax">getPostageTax</a>()
<p>Get the [postage_tax] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
string
</div>
<div class="col-md-8 type">
<a href="#method_getPostageTaxRuleTitle">getPostageTaxRuleTitle</a>()
<p>Get the [postage<em>tax</em>rule_title] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
int
</div>
<div class="col-md-8 type">
<a href="#method_getPaymentModuleId">getPaymentModuleId</a>()
<p>Get the [payment<em>module</em>id] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
int
</div>
<div class="col-md-8 type">
<a href="#method_getDeliveryModuleId">getDeliveryModuleId</a>()
<p>Get the [delivery<em>module</em>id] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
int
</div>
<div class="col-md-8 type">
<a href="#method_getStatusId">getStatusId</a>()
<p>Get the [status_id] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
int
</div>
<div class="col-md-8 type">
<a href="#method_getLangId">getLangId</a>()
<p>Get the [lang_id] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
int
</div>
<div class="col-md-8 type">
<a href="#method_getCartId">getCartId</a>()
<p>Get the [cart_id] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
mixed
</div>
<div class="col-md-8 type">
<a href="#method_getCreatedAt">getCreatedAt</a>(
string $format = NULL)
<p>Get the [optionally formatted] temporal [created_at] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
mixed
</div>
<div class="col-md-8 type">
<a href="#method_getUpdatedAt">getUpdatedAt</a>(
string $format = NULL)
<p>Get the [optionally formatted] temporal [updated_at] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
int
</div>
<div class="col-md-8 type">
<a href="#method_getVersion">getVersion</a>()
<p>Get the [version] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
mixed
</div>
<div class="col-md-8 type">
<a href="#method_getVersionCreatedAt">getVersionCreatedAt</a>(
string $format = NULL)
<p>Get the [optionally formatted] temporal [version<em>created</em>at] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
string
</div>
<div class="col-md-8 type">
<a href="#method_getVersionCreatedBy">getVersionCreatedBy</a>()
<p>Get the [version<em>created</em>by] column value.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setId">setId</a>(
int $v)
<p>Set the value of [id] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setRef">setRef</a>(
string $v)
<p>Set the value of [ref] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setCustomerId">setCustomerId</a>(
int $v)
<p>Set the value of [customer_id] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setInvoiceOrderAddressId">setInvoiceOrderAddressId</a>(
int $v)
<p>Set the value of [invoice<em>order</em>address_id] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setDeliveryOrderAddressId">setDeliveryOrderAddressId</a>(
int $v)
<p>Set the value of [delivery<em>order</em>address_id] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setInvoiceDate">setInvoiceDate</a>(
mixed $v)
<p>Sets the value of [invoice_date] column to a normalized version of the date/time value specified.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setCurrencyId">setCurrencyId</a>(
int $v)
<p>Set the value of [currency_id] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setCurrencyRate">setCurrencyRate</a>(
double $v)
<p>Set the value of [currency_rate] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setTransactionRef">setTransactionRef</a>(
string $v)
<p>Set the value of [transaction_ref] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setDeliveryRef">setDeliveryRef</a>(
string $v)
<p>Set the value of [delivery_ref] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setInvoiceRef">setInvoiceRef</a>(
string $v)
<p>Set the value of [invoice_ref] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setDiscount">setDiscount</a>(
string $v)
<p>Set the value of [discount] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setPostage">setPostage</a>(
string $v)
<p>Set the value of [postage] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setPostageTax">setPostageTax</a>(
string $v)
<p>Set the value of [postage_tax] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setPostageTaxRuleTitle">setPostageTaxRuleTitle</a>(
string $v)
<p>Set the value of [postage<em>tax</em>rule_title] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setPaymentModuleId">setPaymentModuleId</a>(
int $v)
<p>Set the value of [payment<em>module</em>id] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setDeliveryModuleId">setDeliveryModuleId</a>(
int $v)
<p>Set the value of [delivery<em>module</em>id] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setStatusId">setStatusId</a>(
int $v)
<p>Set the value of [status_id] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setLangId">setLangId</a>(
int $v)
<p>Set the value of [lang_id] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setCartId">setCartId</a>(
int $v)
<p>Set the value of [cart_id] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setCreatedAt">setCreatedAt</a>(
mixed $v)
<p>Sets the value of [created_at] column to a normalized version of the date/time value specified.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setUpdatedAt">setUpdatedAt</a>(
mixed $v)
<p>Sets the value of [updated_at] column to a normalized version of the date/time value specified.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setVersion">setVersion</a>(
int $v)
<p>Set the value of [version] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setVersionCreatedAt">setVersionCreatedAt</a>(
mixed $v)
<p>Sets the value of [version<em>created</em>at] column to a normalized version of the date/time value specified.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setVersionCreatedBy">setVersionCreatedBy</a>(
string $v)
<p>Set the value of [version<em>created</em>by] column.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
boolean
</div>
<div class="col-md-8 type">
<a href="#method_hasOnlyDefaultValues">hasOnlyDefaultValues</a>()
<p>Indicates whether the columns in this object are only set to default values.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
int
</div>
<div class="col-md-8 type">
<a href="#method_hydrate">hydrate</a>(
array $row,
int $startcol,
boolean $rehydrate = false,
string $indexType = TableMap::TYPE_NUM)
<p>Hydrates (populates) the object variables with values from the database resultset.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_ensureConsistency">ensureConsistency</a>()
<p>Checks and repairs the internal consistency of the object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
void
</div>
<div class="col-md-8 type">
<a href="#method_reload">reload</a>(
boolean $deep = false,
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Reloads this object from datastore based on primary key and (optionally) resets all associated objects.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
void
</div>
<div class="col-md-8 type">
<a href="#method_delete">delete</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Removes this object from datastore and sets delete attribute.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
int
</div>
<div class="col-md-8 type">
<a href="#method_save">save</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Persists this object to the database.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
mixed
</div>
<div class="col-md-8 type">
<a href="#method_getByName">getByName</a>(
string $name,
string $type = TableMap::TYPE_PHPNAME)
<p>Retrieves a field from the object by name passed in as a string.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
mixed
</div>
<div class="col-md-8 type">
<a href="#method_getByPosition">getByPosition</a>(
int $pos)
<p>Retrieves a field from the object by Position as specified in the xml schema.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
array
</div>
<div class="col-md-8 type">
<a href="#method_toArray">toArray</a>(
string $keyType = TableMap::TYPE_PHPNAME,
boolean $includeLazyLoadColumns = true,
array $alreadyDumpedObjects = array(),
boolean $includeForeignObjects = false)
<p>Exports the object as an array.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
void
</div>
<div class="col-md-8 type">
<a href="#method_setByName">setByName</a>(
string $name,
mixed $value,
string $type = TableMap::TYPE_PHPNAME)
<p>Sets a field from the object by name passed in as a string.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
void
</div>
<div class="col-md-8 type">
<a href="#method_setByPosition">setByPosition</a>(
int $pos,
mixed $value)
<p>Sets a field from the object by Position as specified in the xml schema.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
void
</div>
<div class="col-md-8 type">
<a href="#method_fromArray">fromArray</a>(
array $arr,
string $keyType = TableMap::TYPE_PHPNAME)
<p>Populates the object using an array.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr>
</div>
<div class="col-md-8 type">
<a href="#method_buildCriteria">buildCriteria</a>()
<p>Build a Criteria object containing the values of all modified columns in this object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr>
</div>
<div class="col-md-8 type">
<a href="#method_buildPkeyCriteria">buildPkeyCriteria</a>()
<p>Builds a Criteria object containing the primary key for this object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
int
</div>
<div class="col-md-8 type">
<a href="#method_getPrimaryKey">getPrimaryKey</a>()
<p>Returns the primary key for this object (row).</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
void
</div>
<div class="col-md-8 type">
<a href="#method_setPrimaryKey">setPrimaryKey</a>(
int $key)
<p>Generic method to set the primary key (id column).</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
boolean
</div>
<div class="col-md-8 type">
<a href="#method_isPrimaryKeyNull">isPrimaryKeyNull</a>()
<p>Returns true if the primary key for this object is null.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_copyInto">copyInto</a>(
object $copyObj,
boolean $deepCopy = false,
boolean $makeNew = true)
<p>Sets contents of passed object to values from current object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_copy">copy</a>(
boolean $deepCopy = false)
<p>Makes a copy of this object that will be inserted as a new row in table when saved.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setCurrency">setCurrency</a>(
<abbr title="Thelia\Model\Base\Thelia\Model\Currency">Currency</abbr> $v = null)
<p>Declares an association between this object and a ChildCurrency object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Currency.html"><abbr title="Thelia\Model\Currency">Currency</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_getCurrency">getCurrency</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Get the associated ChildCurrency object</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setCustomer">setCustomer</a>(
<abbr title="Thelia\Model\Base\Thelia\Model\Customer">Customer</abbr> $v = null)
<p>Declares an association between this object and a ChildCustomer object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Customer.html"><abbr title="Thelia\Model\Customer">Customer</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_getCustomer">getCustomer</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Get the associated ChildCustomer object</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setOrderAddressRelatedByInvoiceOrderAddressId">setOrderAddressRelatedByInvoiceOrderAddressId</a>(
<abbr title="Thelia\Model\Base\Thelia\Model\OrderAddress">OrderAddress</abbr> $v = null)
<p>Declares an association between this object and a ChildOrderAddress object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/OrderAddress.html"><abbr title="Thelia\Model\OrderAddress">OrderAddress</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_getOrderAddressRelatedByInvoiceOrderAddressId">getOrderAddressRelatedByInvoiceOrderAddressId</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Get the associated ChildOrderAddress object</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setOrderAddressRelatedByDeliveryOrderAddressId">setOrderAddressRelatedByDeliveryOrderAddressId</a>(
<abbr title="Thelia\Model\Base\Thelia\Model\OrderAddress">OrderAddress</abbr> $v = null)
<p>Declares an association between this object and a ChildOrderAddress object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/OrderAddress.html"><abbr title="Thelia\Model\OrderAddress">OrderAddress</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_getOrderAddressRelatedByDeliveryOrderAddressId">getOrderAddressRelatedByDeliveryOrderAddressId</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Get the associated ChildOrderAddress object</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setOrderStatus">setOrderStatus</a>(
<abbr title="Thelia\Model\Base\Thelia\Model\OrderStatus">OrderStatus</abbr> $v = null)
<p>Declares an association between this object and a ChildOrderStatus object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/OrderStatus.html"><abbr title="Thelia\Model\OrderStatus">OrderStatus</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_getOrderStatus">getOrderStatus</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Get the associated ChildOrderStatus object</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setModuleRelatedByPaymentModuleId">setModuleRelatedByPaymentModuleId</a>(
<abbr title="Thelia\Model\Base\Thelia\Model\Module">Module</abbr> $v = null)
<p>Declares an association between this object and a ChildModule object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Module.html"><abbr title="Thelia\Model\Module">Module</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_getModuleRelatedByPaymentModuleId">getModuleRelatedByPaymentModuleId</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Get the associated ChildModule object</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setModuleRelatedByDeliveryModuleId">setModuleRelatedByDeliveryModuleId</a>(
<abbr title="Thelia\Model\Base\Thelia\Model\Module">Module</abbr> $v = null)
<p>Declares an association between this object and a ChildModule object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Module.html"><abbr title="Thelia\Model\Module">Module</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_getModuleRelatedByDeliveryModuleId">getModuleRelatedByDeliveryModuleId</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Get the associated ChildModule object</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setLang">setLang</a>(
<abbr title="Thelia\Model\Base\Thelia\Model\Lang">Lang</abbr> $v = null)
<p>Declares an association between this object and a ChildLang object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Lang.html"><abbr title="Thelia\Model\Lang">Lang</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_getLang">getLang</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Get the associated ChildLang object</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
void
</div>
<div class="col-md-8 type">
<a href="#method_initRelation">initRelation</a>(
string $relationName)
<p>Initializes a collection based on the name of a relation.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
void
</div>
<div class="col-md-8 type">
<a href="#method_clearOrderProducts">clearOrderProducts</a>()
<p>Clears out the collOrderProducts collection</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_resetPartialOrderProducts">resetPartialOrderProducts</a>($v = true)
<p>Reset is the collOrderProducts collection loaded partially.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
void
</div>
<div class="col-md-8 type">
<a href="#method_initOrderProducts">initOrderProducts</a>(
boolean $overrideExisting = true)
<p>Initializes the collOrderProducts collection.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Propel\Runtime\Collection\Collection">Collection</abbr>|<a href="../../../Thelia/Model/OrderProduct.html"><abbr title="Thelia\Model\OrderProduct">OrderProduct</abbr></a>[]
</div>
<div class="col-md-8 type">
<a href="#method_getOrderProducts">getOrderProducts</a>(
<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr> $criteria = null,
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Gets an array of ChildOrderProduct objects which contain a foreign key that references this object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setOrderProducts">setOrderProducts</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Collection\Collection">Collection</abbr> $orderProducts,
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Sets a collection of OrderProduct objects related by a one-to-many relationship
to the current object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
int
</div>
<div class="col-md-8 type">
<a href="#method_countOrderProducts">countOrderProducts</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr> $criteria = null,
boolean $distinct = false,
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Returns the number of related OrderProduct objects.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_addOrderProduct">addOrderProduct</a>(
<abbr title="Thelia\Model\Base\Thelia\Model\OrderProduct">OrderProduct</abbr> $l)
<p>Method called to associate a ChildOrderProduct object to this object
through the ChildOrderProduct foreign key attribute.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_removeOrderProduct">removeOrderProduct</a>(
<a href="../../../Thelia/Model/Base/OrderProduct.html"><abbr title="Thelia\Model\Base\OrderProduct">OrderProduct</abbr></a> $orderProduct)
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
void
</div>
<div class="col-md-8 type">
<a href="#method_clearOrderCoupons">clearOrderCoupons</a>()
<p>Clears out the collOrderCoupons collection</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_resetPartialOrderCoupons">resetPartialOrderCoupons</a>($v = true)
<p>Reset is the collOrderCoupons collection loaded partially.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
void
</div>
<div class="col-md-8 type">
<a href="#method_initOrderCoupons">initOrderCoupons</a>(
boolean $overrideExisting = true)
<p>Initializes the collOrderCoupons collection.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Propel\Runtime\Collection\Collection">Collection</abbr>|<a href="../../../Thelia/Model/OrderCoupon.html"><abbr title="Thelia\Model\OrderCoupon">OrderCoupon</abbr></a>[]
</div>
<div class="col-md-8 type">
<a href="#method_getOrderCoupons">getOrderCoupons</a>(
<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr> $criteria = null,
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Gets an array of ChildOrderCoupon objects which contain a foreign key that references this object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setOrderCoupons">setOrderCoupons</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Collection\Collection">Collection</abbr> $orderCoupons,
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Sets a collection of OrderCoupon objects related by a one-to-many relationship
to the current object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
int
</div>
<div class="col-md-8 type">
<a href="#method_countOrderCoupons">countOrderCoupons</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr> $criteria = null,
boolean $distinct = false,
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Returns the number of related OrderCoupon objects.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_addOrderCoupon">addOrderCoupon</a>(
<abbr title="Thelia\Model\Base\Thelia\Model\OrderCoupon">OrderCoupon</abbr> $l)
<p>Method called to associate a ChildOrderCoupon object to this object
through the ChildOrderCoupon foreign key attribute.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_removeOrderCoupon">removeOrderCoupon</a>(
<a href="../../../Thelia/Model/Base/OrderCoupon.html"><abbr title="Thelia\Model\Base\OrderCoupon">OrderCoupon</abbr></a> $orderCoupon)
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
void
</div>
<div class="col-md-8 type">
<a href="#method_clearOrderVersions">clearOrderVersions</a>()
<p>Clears out the collOrderVersions collection</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_resetPartialOrderVersions">resetPartialOrderVersions</a>($v = true)
<p>Reset is the collOrderVersions collection loaded partially.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
void
</div>
<div class="col-md-8 type">
<a href="#method_initOrderVersions">initOrderVersions</a>(
boolean $overrideExisting = true)
<p>Initializes the collOrderVersions collection.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Propel\Runtime\Collection\Collection">Collection</abbr>|<a href="../../../Thelia/Model/OrderVersion.html"><abbr title="Thelia\Model\OrderVersion">OrderVersion</abbr></a>[]
</div>
<div class="col-md-8 type">
<a href="#method_getOrderVersions">getOrderVersions</a>(
<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr> $criteria = null,
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Gets an array of ChildOrderVersion objects which contain a foreign key that references this object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_setOrderVersions">setOrderVersions</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Collection\Collection">Collection</abbr> $orderVersions,
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Sets a collection of OrderVersion objects related by a one-to-many relationship
to the current object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
int
</div>
<div class="col-md-8 type">
<a href="#method_countOrderVersions">countOrderVersions</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr> $criteria = null,
boolean $distinct = false,
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Returns the number of related OrderVersion objects.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_addOrderVersion">addOrderVersion</a>(
<abbr title="Thelia\Model\Base\Thelia\Model\OrderVersion">OrderVersion</abbr> $l)
<p>Method called to associate a ChildOrderVersion object to this object
through the ChildOrderVersion foreign key attribute.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_removeOrderVersion">removeOrderVersion</a>(
<a href="../../../Thelia/Model/Base/OrderVersion.html"><abbr title="Thelia\Model\Base\OrderVersion">OrderVersion</abbr></a> $orderVersion)
<p class="no-description">No description</p>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_clear">clear</a>()
<p>Clears the current object and sets all attributes to their default values</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_clearAllReferences">clearAllReferences</a>(
boolean $deep = false)
<p>Resets all references to other model objects or collections of model objects.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
string
</div>
<div class="col-md-8 type">
<a href="#method___toString">__toString</a>()
<p>Return the string representation of this object</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_keepUpdateDateUnchanged">keepUpdateDateUnchanged</a>()
<p>Mark the current object so that the update date doesn't get updated during next save</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_enforceVersioning">enforceVersioning</a>()
<p>Enforce a new Version of this object upon next save.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
boolean
</div>
<div class="col-md-8 type">
<a href="#method_isVersioningNecessary">isVersioningNecessary</a>($con = null)
<p>Checks whether the current state must be recorded as a version</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/OrderVersion.html"><abbr title="Thelia\Model\OrderVersion">OrderVersion</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_addVersion">addVersion</a>(
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Creates a version of the current object and saves it.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_toVersion">toVersion</a>(
integer $versionNumber,
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Sets the properties of the current object to the value they had at a specific version</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_populateFromVersion">populateFromVersion</a>(
<a href="../../../Thelia/Model/OrderVersion.html"><abbr title="Thelia\Model\OrderVersion">OrderVersion</abbr></a> $version,
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null,
array $loadedObjects = array())
<p>Sets the properties of the current object to the value they had at a specific version</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
integer
</div>
<div class="col-md-8 type">
<a href="#method_getLastVersionNumber">getLastVersionNumber</a>(
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Gets the latest persisted version number for the current object</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
Boolean
</div>
<div class="col-md-8 type">
<a href="#method_isLastVersion">isLastVersion</a>(
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Checks whether the current object is the latest one</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<a href="../../../Thelia/Model/OrderVersion.html"><abbr title="Thelia\Model\OrderVersion">OrderVersion</abbr></a>
</div>
<div class="col-md-8 type">
<a href="#method_getOneVersion">getOneVersion</a>(
integer $versionNumber,
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Retrieves a version object for this entity and a version number</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Propel\Runtime\Collection\ObjectCollection">ObjectCollection</abbr>
</div>
<div class="col-md-8 type">
<a href="#method_getAllVersions">getAllVersions</a>(
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Gets all the versions of this object, in incremental order</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
array
</div>
<div class="col-md-8 type">
<a href="#method_compareVersion">compareVersion</a>(
integer $versionNumber,
string $keys = 'columns',
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null,
array $ignoredColumns = array())
<p>Compares the current object with another of its version.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
array
</div>
<div class="col-md-8 type">
<a href="#method_compareVersions">compareVersions</a>(
integer $fromVersionNumber,
integer $toVersionNumber,
string $keys = 'columns',
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null,
array $ignoredColumns = array())
<p>Compares two versions of the current object.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
<abbr title="Thelia\Model\Base\PropelCollection">PropelCollection</abbr>|array
</div>
<div class="col-md-8 type">
<a href="#method_getLastVersions">getLastVersions</a>($number = 10, $criteria = null, $con = null)
<p>retrieve the last $number versions.</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
boolean
</div>
<div class="col-md-8 type">
<a href="#method_preSave">preSave</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Code to be run before persisting the object</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_postSave">postSave</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Code to be run after persisting the object</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
boolean
</div>
<div class="col-md-8 type">
<a href="#method_preInsert">preInsert</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Code to be run before inserting to database</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_postInsert">postInsert</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Code to be run after inserting to database</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
boolean
</div>
<div class="col-md-8 type">
<a href="#method_preUpdate">preUpdate</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Code to be run before updating the object in database</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_postUpdate">postUpdate</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Code to be run after updating the object in database</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
boolean
</div>
<div class="col-md-8 type">
<a href="#method_preDelete">preDelete</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Code to be run before deleting the object in database</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
</div>
<div class="col-md-8 type">
<a href="#method_postDelete">postDelete</a>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Code to be run after deleting the object in database</p> </div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2 type">
array|string
</div>
<div class="col-md-8 type">
<a href="#method___call">__call</a>(
string $name,
mixed $params)
<p>Derived method to catches calls to undefined methods.</p> </div>
<div class="col-md-2"></div>
</div>
</div>
<h2>Details</h2>
<div id="method-details">
<div class="method-item">
<h3 id="method_applyDefaultValues">
<div class="location">at line 330</div>
<code>
<strong>applyDefaultValues</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Applies default values to this object.</p> <p>This method should be called from the object's constructor (or
equivalent initialization method).</p> </div>
<div class="tags">
<h4>See also</h4>
<table class="table table-condensed">
<tr>
<td>__construct()</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method___construct">
<div class="location">at line 342</div>
<code>
<strong>__construct</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Initializes internal state of Thelia\Model\Base\Order object.</p> </div>
<div class="tags">
<h4>See also</h4>
<table class="table table-condensed">
<tr>
<td>applyDefaults()</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_isModified">
<div class="location">at line 352</div>
<code>
boolean
<strong>isModified</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Returns whether the object has been modified.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td>True if the object has been modified.</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_isColumnModified">
<div class="location">at line 363</div>
<code>
boolean
<strong>isColumnModified</strong>(
string $col)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Has specified column been modified?</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$col</td>
<td>column fully qualified name (TableMap::TYPE<em>COLNAME), e.g. Book::AUTHOR</em>ID</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td>True if $col has been modified.</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getModifiedColumns">
<div class="location">at line 372</div>
<code>
array
<strong>getModifiedColumns</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the columns that have been modified in this object.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
array</td>
<td>A unique list of the modified column names for this object.</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_isNew">
<div class="location">at line 384</div>
<code>
boolean
<strong>isNew</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Returns whether the object has ever been saved. This will
be false, if the object was retrieved from storage or was created
and then saved.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td>true, if the object has never been persisted.</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setNew">
<div class="location">at line 395</div>
<code>
<strong>setNew</strong>(
boolean $b)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Setter for the isNew attribute. This method will be called
by Propel-generated children and objects.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td>$b</td>
<td>the state of the object.</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_isDeleted">
<div class="location">at line 404</div>
<code>
boolean
<strong>isDeleted</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Whether this object has been deleted.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td>The deleted state of this object.</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setDeleted">
<div class="location">at line 414</div>
<code>
void
<strong>setDeleted</strong>(
boolean $b)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Specify whether this object has been deleted.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td>$b</td>
<td>The deleted state of this object.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
void</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_resetModified">
<div class="location">at line 424</div>
<code>
void
<strong>resetModified</strong>(
string $col = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Sets the modified state for the object to be false.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$col</td>
<td>If supplied, only the specified column is reset.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
void</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_equals">
<div class="location">at line 443</div>
<code>
boolean
<strong>equals</strong>(
mixed $obj)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Compares this with another <code>Order</code> instance. If
<code>obj</code> is an instance of <code>Order</code>, delegates to
<code>equals(Order)</code>. Otherwise, returns <code>false</code>.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
mixed</td>
<td>$obj</td>
<td>The object to compare to.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td>Whether equal to the object specified.</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_hashCode">
<div class="location">at line 468</div>
<code>
int
<strong>hashCode</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>If the primary key is not null, return the hashcode of the
primary key. Otherwise, return the hash code of the object.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td>Hashcode</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getVirtualColumns">
<div class="location">at line 482</div>
<code>
array
<strong>getVirtualColumns</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the associative array of the virtual columns in this object</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
array</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_hasVirtualColumn">
<div class="location">at line 493</div>
<code>
boolean
<strong>hasVirtualColumn</strong>(
string $name)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Checks the existence of a virtual column in this object</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$name</td>
<td>The virtual column name</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getVirtualColumn">
<div class="location">at line 506</div>
<code>
mixed
<strong>getVirtualColumn</strong>(
string $name)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the value of a virtual column in this object</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$name</td>
<td>The virtual column name</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
mixed</td>
<td></td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setVirtualColumn">
<div class="location">at line 523</div>
<code>
<a href="../../../Thelia/Model/Base/Order.html"><abbr title="Thelia\Model\Base\Order">Order</abbr></a>
<strong>setVirtualColumn</strong>(
string $name,
mixed $value)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of a virtual column in this object</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$name</td>
<td>The virtual column name</td>
</tr>
<tr>
<td>
mixed</td>
<td>$value</td>
<td>The value to give to the virtual column</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Base/Order.html"><abbr title="Thelia\Model\Base\Order">Order</abbr></a></td>
<td>The current object, for fluid interface</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_importFrom">
<div class="location">at line 555</div>
<code>
<a href="../../../Thelia/Model/Base/Order.html"><abbr title="Thelia\Model\Base\Order">Order</abbr></a>
<strong>importFrom</strong>(
mixed $parser,
string $data)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Populate the current object from a string, using a given parser format
<code>
$book = new Book();
$book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}');
</code></p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
mixed</td>
<td>$parser</td>
<td>A AbstractParser instance,
or a format name ('XML', 'YAML', 'JSON', 'CSV')</td>
</tr>
<tr>
<td>
string</td>
<td>$data</td>
<td>The source data to import from</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Base/Order.html"><abbr title="Thelia\Model\Base\Order">Order</abbr></a></td>
<td>The current object, for fluid interface</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_exportTo">
<div class="location">at line 578</div>
<code>
string
<strong>exportTo</strong>(
mixed $parser,
boolean $includeLazyLoadColumns = true)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Export the current object properties to a string, using a given parser format
<code>
$book = BookQuery::create()->findPk(9012);
echo $book->exportTo('JSON');
=> {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}');
</code></p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
mixed</td>
<td>$parser</td>
<td>A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV')</td>
</tr>
<tr>
<td>
boolean</td>
<td>$includeLazyLoadColumns</td>
<td>(optional) Whether to include lazy load(ed) columns. Defaults to TRUE.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>The exported data</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method___sleep">
<div class="location">at line 591</div>
<code>
<strong>__sleep</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Clean up internal collections prior to serializing
Avoids recursive loops that turn into segmentation faults when serializing</p> </div>
<div class="tags">
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getId">
<div class="location">at line 603</div>
<code>
int
<strong>getId</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [id] column value.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getRef">
<div class="location">at line 614</div>
<code>
string
<strong>getRef</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [ref] column value.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getCustomerId">
<div class="location">at line 625</div>
<code>
int
<strong>getCustomerId</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [customer_id] column value.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getInvoiceOrderAddressId">
<div class="location">at line 636</div>
<code>
int
<strong>getInvoiceOrderAddressId</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [invoice<em>order</em>address_id] column value.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getDeliveryOrderAddressId">
<div class="location">at line 647</div>
<code>
int
<strong>getDeliveryOrderAddressId</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [delivery<em>order</em>address_id] column value.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getInvoiceDate">
<div class="location">at line 664</div>
<code>
mixed
<strong>getInvoiceDate</strong>(
string $format = NULL)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [optionally formatted] temporal [invoice_date] column value.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$format</td>
<td>The date/time format string (either date()-style or strftime()-style).
If format is NULL, then the raw \DateTime object will be returned.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
mixed</td>
<td>Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td><ul>
<li>if unable to parse/validate the date/time value.</li>
</ul>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getCurrencyId">
<div class="location">at line 678</div>
<code>
int
<strong>getCurrencyId</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [currency_id] column value.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getCurrencyRate">
<div class="location">at line 689</div>
<code>
double
<strong>getCurrencyRate</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [currency_rate] column value.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
double</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getTransactionRef">
<div class="location">at line 700</div>
<code>
string
<strong>getTransactionRef</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [transaction_ref] column value.</p> <p>transaction reference - usually use to identify a transaction with banking modules</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getDeliveryRef">
<div class="location">at line 711</div>
<code>
string
<strong>getDeliveryRef</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [delivery_ref] column value.</p> <p>delivery reference - usually use to identify a delivery progress on a distant delivery tracker website</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getInvoiceRef">
<div class="location">at line 722</div>
<code>
string
<strong>getInvoiceRef</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [invoice_ref] column value.</p> <p>the invoice reference</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getDiscount">
<div class="location">at line 733</div>
<code>
string
<strong>getDiscount</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [discount] column value.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getPostage">
<div class="location">at line 744</div>
<code>
string
<strong>getPostage</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [postage] column value.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getPostageTax">
<div class="location">at line 755</div>
<code>
string
<strong>getPostageTax</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [postage_tax] column value.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getPostageTaxRuleTitle">
<div class="location">at line 766</div>
<code>
string
<strong>getPostageTaxRuleTitle</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [postage<em>tax</em>rule_title] column value.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getPaymentModuleId">
<div class="location">at line 777</div>
<code>
int
<strong>getPaymentModuleId</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [payment<em>module</em>id] column value.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getDeliveryModuleId">
<div class="location">at line 788</div>
<code>
int
<strong>getDeliveryModuleId</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [delivery<em>module</em>id] column value.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getStatusId">
<div class="location">at line 799</div>
<code>
int
<strong>getStatusId</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [status_id] column value.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getLangId">
<div class="location">at line 810</div>
<code>
int
<strong>getLangId</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [lang_id] column value.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getCartId">
<div class="location">at line 821</div>
<code>
int
<strong>getCartId</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [cart_id] column value.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getCreatedAt">
<div class="location">at line 838</div>
<code>
mixed
<strong>getCreatedAt</strong>(
string $format = NULL)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [optionally formatted] temporal [created_at] column value.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$format</td>
<td>The date/time format string (either date()-style or strftime()-style).
If format is NULL, then the raw \DateTime object will be returned.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
mixed</td>
<td>Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td><ul>
<li>if unable to parse/validate the date/time value.</li>
</ul>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getUpdatedAt">
<div class="location">at line 858</div>
<code>
mixed
<strong>getUpdatedAt</strong>(
string $format = NULL)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [optionally formatted] temporal [updated_at] column value.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$format</td>
<td>The date/time format string (either date()-style or strftime()-style).
If format is NULL, then the raw \DateTime object will be returned.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
mixed</td>
<td>Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td><ul>
<li>if unable to parse/validate the date/time value.</li>
</ul>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getVersion">
<div class="location">at line 872</div>
<code>
int
<strong>getVersion</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [version] column value.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getVersionCreatedAt">
<div class="location">at line 889</div>
<code>
mixed
<strong>getVersionCreatedAt</strong>(
string $format = NULL)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [optionally formatted] temporal [version<em>created</em>at] column value.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$format</td>
<td>The date/time format string (either date()-style or strftime()-style).
If format is NULL, then the raw \DateTime object will be returned.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
mixed</td>
<td>Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td><ul>
<li>if unable to parse/validate the date/time value.</li>
</ul>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getVersionCreatedBy">
<div class="location">at line 903</div>
<code>
string
<strong>getVersionCreatedBy</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the [version<em>created</em>by] column value.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setId">
<div class="location">at line 915</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setId</strong>(
int $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [id] column.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setRef">
<div class="location">at line 936</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setRef</strong>(
string $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [ref] column.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setCustomerId">
<div class="location">at line 957</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setCustomerId</strong>(
int $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [customer_id] column.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setInvoiceOrderAddressId">
<div class="location">at line 982</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setInvoiceOrderAddressId</strong>(
int $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [invoice<em>order</em>address_id] column.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setDeliveryOrderAddressId">
<div class="location">at line 1007</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setDeliveryOrderAddressId</strong>(
int $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [delivery<em>order</em>address_id] column.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setInvoiceDate">
<div class="location">at line 1033</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setInvoiceDate</strong>(
mixed $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Sets the value of [invoice_date] column to a normalized version of the date/time value specified.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
mixed</td>
<td>$v</td>
<td>string, integer (timestamp), or \DateTime value.
Empty strings are treated as NULL.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setCurrencyId">
<div class="location">at line 1053</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setCurrencyId</strong>(
int $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [currency_id] column.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setCurrencyRate">
<div class="location">at line 1078</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setCurrencyRate</strong>(
double $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [currency_rate] column.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
double</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setTransactionRef">
<div class="location">at line 1099</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setTransactionRef</strong>(
string $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [transaction_ref] column.</p> <p>transaction reference - usually use to identify a transaction with banking modules</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setDeliveryRef">
<div class="location">at line 1120</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setDeliveryRef</strong>(
string $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [delivery_ref] column.</p> <p>delivery reference - usually use to identify a delivery progress on a distant delivery tracker website</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setInvoiceRef">
<div class="location">at line 1141</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setInvoiceRef</strong>(
string $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [invoice_ref] column.</p> <p>the invoice reference</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setDiscount">
<div class="location">at line 1162</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setDiscount</strong>(
string $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [discount] column.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setPostage">
<div class="location">at line 1183</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setPostage</strong>(
string $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [postage] column.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setPostageTax">
<div class="location">at line 1204</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setPostageTax</strong>(
string $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [postage_tax] column.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setPostageTaxRuleTitle">
<div class="location">at line 1225</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setPostageTaxRuleTitle</strong>(
string $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [postage<em>tax</em>rule_title] column.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setPaymentModuleId">
<div class="location">at line 1246</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setPaymentModuleId</strong>(
int $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [payment<em>module</em>id] column.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setDeliveryModuleId">
<div class="location">at line 1271</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setDeliveryModuleId</strong>(
int $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [delivery<em>module</em>id] column.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setStatusId">
<div class="location">at line 1296</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setStatusId</strong>(
int $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [status_id] column.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setLangId">
<div class="location">at line 1321</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setLangId</strong>(
int $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [lang_id] column.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setCartId">
<div class="location">at line 1346</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setCartId</strong>(
int $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [cart_id] column.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setCreatedAt">
<div class="location">at line 1368</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setCreatedAt</strong>(
mixed $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Sets the value of [created_at] column to a normalized version of the date/time value specified.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
mixed</td>
<td>$v</td>
<td>string, integer (timestamp), or \DateTime value.
Empty strings are treated as NULL.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setUpdatedAt">
<div class="location">at line 1389</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setUpdatedAt</strong>(
mixed $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Sets the value of [updated_at] column to a normalized version of the date/time value specified.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
mixed</td>
<td>$v</td>
<td>string, integer (timestamp), or \DateTime value.
Empty strings are treated as NULL.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setVersion">
<div class="location">at line 1409</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setVersion</strong>(
int $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [version] column.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setVersionCreatedAt">
<div class="location">at line 1431</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setVersionCreatedAt</strong>(
mixed $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Sets the value of [version<em>created</em>at] column to a normalized version of the date/time value specified.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
mixed</td>
<td>$v</td>
<td>string, integer (timestamp), or \DateTime value.
Empty strings are treated as NULL.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setVersionCreatedBy">
<div class="location">at line 1451</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setVersionCreatedBy</strong>(
string $v)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Set the value of [version<em>created</em>by] column.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_hasOnlyDefaultValues">
<div class="location">at line 1474</div>
<code>
boolean
<strong>hasOnlyDefaultValues</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Indicates whether the columns in this object are only set to default values.</p> <p>This method can be used in conjunction with isModified() to indicate whether an object is both
modified <em>and</em> has some values set which are non-default.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td>Whether the columns in this object are only been set with default values.</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_hydrate">
<div class="location">at line 1514</div>
<code>
int
<strong>hydrate</strong>(
array $row,
int $startcol,
boolean $rehydrate = false,
string $indexType = TableMap::TYPE_NUM)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Hydrates (populates) the object variables with values from the database resultset.</p> <p>An offset (0-based "start column") is specified so that objects can be hydrated
with a subset of the columns in the resultset rows. This is needed, for example,
for results of JOIN queries where the resultset row includes columns from two or
more tables.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
array</td>
<td>$row</td>
<td>The row returned by DataFetcher->fetch().</td>
</tr>
<tr>
<td>
int</td>
<td>$startcol</td>
<td>0-based offset column which indicates which restultset column to start with.</td>
</tr>
<tr>
<td>
boolean</td>
<td>$rehydrate</td>
<td>Whether this object is being re-hydrated from the database.</td>
</tr>
<tr>
<td>
string</td>
<td>$indexType</td>
<td>The index type of $row. Mostly DataFetcher->getIndexType().
One of the class type constants TableMap::TYPE<em>PHPNAME, TableMap::TYPE</em>STUDLYPHPNAME
TableMap::TYPE<em>COLNAME, TableMap::TYPE</em>FIELDNAME, TableMap::TYPE_NUM.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td>next starting column</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td><ul>
<li>Any caught Exception will be rewrapped as a PropelException.</li>
</ul>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_ensureConsistency">
<div class="location">at line 1633</div>
<code>
<strong>ensureConsistency</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Checks and repairs the internal consistency of the object.</p> <p>This method is executed after an already-instantiated object is re-hydrated
from the database. It exists to check any foreign keys to make sure that
the objects related to the current object are correct based on foreign key.</p>
<p>You can override this method in the stub class, but you should always invoke
the base method from the overridden method (i.e. parent::ensureConsistency()),
in case your model changes.</p> </div>
<div class="tags">
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_reload">
<div class="location">at line 1671</div>
<code>
void
<strong>reload</strong>(
boolean $deep = false,
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Reloads this object from datastore based on primary key and (optionally) resets all associated objects.</p> <p>This will only work if the object has been saved and has a valid primary key set.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td>$deep</td>
<td>(optional) Whether to also de-associated any related objects.</td>
</tr>
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>(optional) The ConnectionInterface connection to use.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
void</td>
<td></td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td><ul>
<li>if this object is deleted, unsaved or doesn't have pk match in db</li>
</ul>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_delete">
<div class="location">at line 1724</div>
<code>
void
<strong>delete</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Removes this object from datastore and sets delete attribute.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td></td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
void</td>
<td></td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
<h4>See also</h4>
<table class="table table-condensed">
<tr>
<td>Order::setDeleted()</td>
<td></td>
</tr>
<tr>
<td>Order::isDeleted()</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_save">
<div class="location">at line 1766</div>
<code>
int
<strong>save</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Persists this object to the database.</p> <p>If the object is new, it inserts it; otherwise an update is performed.
All modified related objects will also be persisted in the doSave()
method. This method wraps all precipitate database operations in a
single transaction.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td></td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td>The number of rows affected by this insert/update and any referring fk objects' save() operations.</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
<h4>See also</h4>
<table class="table table-condensed">
<tr>
<td>doSave()</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getByName">
<div class="location">at line 2200</div>
<code>
mixed
<strong>getByName</strong>(
string $name,
string $type = TableMap::TYPE_PHPNAME)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Retrieves a field from the object by name passed in as a string.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$name</td>
<td>name</td>
</tr>
<tr>
<td>
string</td>
<td>$type</td>
<td>The type of fieldname the $name is of:
one of the class type constants TableMap::TYPE<em>PHPNAME, TableMap::TYPE</em>STUDLYPHPNAME
TableMap::TYPE<em>COLNAME, TableMap::TYPE</em>FIELDNAME, TableMap::TYPE<em>NUM.
Defaults to TableMap::TYPE</em>PHPNAME.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
mixed</td>
<td>Value of field.</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getByPosition">
<div class="location">at line 2215</div>
<code>
mixed
<strong>getByPosition</strong>(
int $pos)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Retrieves a field from the object by Position as specified in the xml schema.</p> <p>Zero-based.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td>$pos</td>
<td>position in xml schema</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
mixed</td>
<td>Value of field at $pos</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_toArray">
<div class="location">at line 2314</div>
<code>
array
<strong>toArray</strong>(
string $keyType = TableMap::TYPE_PHPNAME,
boolean $includeLazyLoadColumns = true,
array $alreadyDumpedObjects = array(),
boolean $includeForeignObjects = false)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Exports the object as an array.</p> <p>You can specify the key type of the array by passing one of the class
type constants.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$keyType</td>
<td>(optional) One of the class type constants TableMap::TYPE<em>PHPNAME, TableMap::TYPE</em>STUDLYPHPNAME,
TableMap::TYPE<em>COLNAME, TableMap::TYPE</em>FIELDNAME, TableMap::TYPE<em>NUM.
Defaults to TableMap::TYPE</em>PHPNAME.</td>
</tr>
<tr>
<td>
boolean</td>
<td>$includeLazyLoadColumns</td>
<td>(optional) Whether to include lazy loaded columns. Defaults to TRUE.</td>
</tr>
<tr>
<td>
array</td>
<td>$alreadyDumpedObjects</td>
<td>List of objects to skip to avoid recursion</td>
</tr>
<tr>
<td>
boolean</td>
<td>$includeForeignObjects</td>
<td>(optional) Whether to include hydrated related objects. Default to FALSE.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
array</td>
<td>an associative array containing the field names (as keys) and field values</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setByName">
<div class="location">at line 2403</div>
<code>
void
<strong>setByName</strong>(
string $name,
mixed $value,
string $type = TableMap::TYPE_PHPNAME)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Sets a field from the object by name passed in as a string.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$name</td>
<td></td>
</tr>
<tr>
<td>
mixed</td>
<td>$value</td>
<td>field value</td>
</tr>
<tr>
<td>
string</td>
<td>$type</td>
<td>The type of fieldname the $name is of:
one of the class type constants TableMap::TYPE<em>PHPNAME, TableMap::TYPE</em>STUDLYPHPNAME
TableMap::TYPE<em>COLNAME, TableMap::TYPE</em>FIELDNAME, TableMap::TYPE<em>NUM.
Defaults to TableMap::TYPE</em>PHPNAME.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
void</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setByPosition">
<div class="location">at line 2418</div>
<code>
void
<strong>setByPosition</strong>(
int $pos,
mixed $value)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Sets a field from the object by Position as specified in the xml schema.</p> <p>Zero-based.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td>$pos</td>
<td>position in xml schema</td>
</tr>
<tr>
<td>
mixed</td>
<td>$value</td>
<td>field value</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
void</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_fromArray">
<div class="location">at line 2516</div>
<code>
void
<strong>fromArray</strong>(
array $arr,
string $keyType = TableMap::TYPE_PHPNAME)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Populates the object using an array.</p> <p>This is particularly useful when populating an object from one of the
request arrays (e.g. $_POST). This method goes through the column
names, checking to see whether a matching key exists in populated
array. If so the setByName() method is called for that column.</p>
<p>You can specify the key type of the array by additionally passing one
of the class type constants TableMap::TYPE<em>PHPNAME, TableMap::TYPE</em>STUDLYPHPNAME,
TableMap::TYPE<em>COLNAME, TableMap::TYPE</em>FIELDNAME, TableMap::TYPE<em>NUM.
The default key type is the column's TableMap::TYPE</em>PHPNAME.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
array</td>
<td>$arr</td>
<td>An array to populate the object from.</td>
</tr>
<tr>
<td>
string</td>
<td>$keyType</td>
<td>The type of keys the array uses.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
void</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_buildCriteria">
<div class="location">at line 2552</div>
<code>
<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr>
<strong>buildCriteria</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Build a Criteria object containing the values of all modified columns in this object.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr></td>
<td>The Criteria object containing all modified values.</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_buildPkeyCriteria">
<div class="location">at line 2593</div>
<code>
<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr>
<strong>buildPkeyCriteria</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Builds a Criteria object containing the primary key for this object.</p> <p>Unlike buildCriteria() this method includes the primary key values regardless
of whether or not they have been modified.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr></td>
<td>The Criteria object containing value(s) for primary key(s).</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getPrimaryKey">
<div class="location">at line 2605</div>
<code>
int
<strong>getPrimaryKey</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Returns the primary key for this object (row).</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setPrimaryKey">
<div class="location">at line 2616</div>
<code>
void
<strong>setPrimaryKey</strong>(
int $key)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Generic method to set the primary key (id column).</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td>$key</td>
<td>Primary key.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
void</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_isPrimaryKeyNull">
<div class="location">at line 2625</div>
<code>
boolean
<strong>isPrimaryKeyNull</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Returns true if the primary key for this object is null.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_copyInto">
<div class="location">at line 2642</div>
<code>
<strong>copyInto</strong>(
object $copyObj,
boolean $deepCopy = false,
boolean $makeNew = true)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Sets contents of passed object to values from current object.</p> <p>If desired, this method can also make copies of all associated (fkey referrers)
objects.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
object</td>
<td>$copyObj</td>
<td>An object of \Thelia\Model\Order (or compatible) type.</td>
</tr>
<tr>
<td>
boolean</td>
<td>$deepCopy</td>
<td>Whether to also copy all rows that refer (by fkey) to the current row.</td>
</tr>
<tr>
<td>
boolean</td>
<td>$makeNew</td>
<td>Whether to reset autoincrement PKs and make the object new.</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_copy">
<div class="location">at line 2712</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>copy</strong>(
boolean $deepCopy = false)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Makes a copy of this object that will be inserted as a new row in table when saved.</p> <p>It creates a new object filling in the simple attributes, but skipping any primary
keys that are defined for the table.</p>
<p>If desired, this method can also make copies of all associated (fkey referrers)
objects.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td>$deepCopy</td>
<td>Whether to also copy all rows that refer (by fkey) to the current row.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>Clone of current object.</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setCurrency">
<div class="location">at line 2729</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setCurrency</strong>(
<abbr title="Thelia\Model\Base\Thelia\Model\Currency">Currency</abbr> $v = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Declares an association between this object and a ChildCurrency object.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Thelia\Model\Currency">Currency</abbr></td>
<td>$v</td>
<td></td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getCurrency">
<div class="location">at line 2757</div>
<code>
<a href="../../../Thelia/Model/Currency.html"><abbr title="Thelia\Model\Currency">Currency</abbr></a>
<strong>getCurrency</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the associated ChildCurrency object</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>Optional Connection object.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Currency.html"><abbr title="Thelia\Model\Currency">Currency</abbr></a></td>
<td>The associated ChildCurrency object.</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setCustomer">
<div class="location">at line 2780</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setCustomer</strong>(
<abbr title="Thelia\Model\Base\Thelia\Model\Customer">Customer</abbr> $v = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Declares an association between this object and a ChildCustomer object.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Thelia\Model\Customer">Customer</abbr></td>
<td>$v</td>
<td></td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getCustomer">
<div class="location">at line 2808</div>
<code>
<a href="../../../Thelia/Model/Customer.html"><abbr title="Thelia\Model\Customer">Customer</abbr></a>
<strong>getCustomer</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the associated ChildCustomer object</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>Optional Connection object.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Customer.html"><abbr title="Thelia\Model\Customer">Customer</abbr></a></td>
<td>The associated ChildCustomer object.</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setOrderAddressRelatedByInvoiceOrderAddressId">
<div class="location">at line 2831</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setOrderAddressRelatedByInvoiceOrderAddressId</strong>(
<abbr title="Thelia\Model\Base\Thelia\Model\OrderAddress">OrderAddress</abbr> $v = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Declares an association between this object and a ChildOrderAddress object.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Thelia\Model\OrderAddress">OrderAddress</abbr></td>
<td>$v</td>
<td></td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getOrderAddressRelatedByInvoiceOrderAddressId">
<div class="location">at line 2859</div>
<code>
<a href="../../../Thelia/Model/OrderAddress.html"><abbr title="Thelia\Model\OrderAddress">OrderAddress</abbr></a>
<strong>getOrderAddressRelatedByInvoiceOrderAddressId</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the associated ChildOrderAddress object</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>Optional Connection object.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/OrderAddress.html"><abbr title="Thelia\Model\OrderAddress">OrderAddress</abbr></a></td>
<td>The associated ChildOrderAddress object.</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setOrderAddressRelatedByDeliveryOrderAddressId">
<div class="location">at line 2882</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setOrderAddressRelatedByDeliveryOrderAddressId</strong>(
<abbr title="Thelia\Model\Base\Thelia\Model\OrderAddress">OrderAddress</abbr> $v = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Declares an association between this object and a ChildOrderAddress object.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Thelia\Model\OrderAddress">OrderAddress</abbr></td>
<td>$v</td>
<td></td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getOrderAddressRelatedByDeliveryOrderAddressId">
<div class="location">at line 2910</div>
<code>
<a href="../../../Thelia/Model/OrderAddress.html"><abbr title="Thelia\Model\OrderAddress">OrderAddress</abbr></a>
<strong>getOrderAddressRelatedByDeliveryOrderAddressId</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the associated ChildOrderAddress object</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>Optional Connection object.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/OrderAddress.html"><abbr title="Thelia\Model\OrderAddress">OrderAddress</abbr></a></td>
<td>The associated ChildOrderAddress object.</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setOrderStatus">
<div class="location">at line 2933</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setOrderStatus</strong>(
<abbr title="Thelia\Model\Base\Thelia\Model\OrderStatus">OrderStatus</abbr> $v = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Declares an association between this object and a ChildOrderStatus object.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Thelia\Model\OrderStatus">OrderStatus</abbr></td>
<td>$v</td>
<td></td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getOrderStatus">
<div class="location">at line 2961</div>
<code>
<a href="../../../Thelia/Model/OrderStatus.html"><abbr title="Thelia\Model\OrderStatus">OrderStatus</abbr></a>
<strong>getOrderStatus</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the associated ChildOrderStatus object</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>Optional Connection object.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/OrderStatus.html"><abbr title="Thelia\Model\OrderStatus">OrderStatus</abbr></a></td>
<td>The associated ChildOrderStatus object.</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setModuleRelatedByPaymentModuleId">
<div class="location">at line 2984</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setModuleRelatedByPaymentModuleId</strong>(
<abbr title="Thelia\Model\Base\Thelia\Model\Module">Module</abbr> $v = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Declares an association between this object and a ChildModule object.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Thelia\Model\Module">Module</abbr></td>
<td>$v</td>
<td></td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getModuleRelatedByPaymentModuleId">
<div class="location">at line 3012</div>
<code>
<a href="../../../Thelia/Model/Module.html"><abbr title="Thelia\Model\Module">Module</abbr></a>
<strong>getModuleRelatedByPaymentModuleId</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the associated ChildModule object</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>Optional Connection object.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Module.html"><abbr title="Thelia\Model\Module">Module</abbr></a></td>
<td>The associated ChildModule object.</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setModuleRelatedByDeliveryModuleId">
<div class="location">at line 3035</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setModuleRelatedByDeliveryModuleId</strong>(
<abbr title="Thelia\Model\Base\Thelia\Model\Module">Module</abbr> $v = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Declares an association between this object and a ChildModule object.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Thelia\Model\Module">Module</abbr></td>
<td>$v</td>
<td></td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getModuleRelatedByDeliveryModuleId">
<div class="location">at line 3063</div>
<code>
<a href="../../../Thelia/Model/Module.html"><abbr title="Thelia\Model\Module">Module</abbr></a>
<strong>getModuleRelatedByDeliveryModuleId</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the associated ChildModule object</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>Optional Connection object.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Module.html"><abbr title="Thelia\Model\Module">Module</abbr></a></td>
<td>The associated ChildModule object.</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setLang">
<div class="location">at line 3086</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setLang</strong>(
<abbr title="Thelia\Model\Base\Thelia\Model\Lang">Lang</abbr> $v = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Declares an association between this object and a ChildLang object.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Thelia\Model\Lang">Lang</abbr></td>
<td>$v</td>
<td></td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getLang">
<div class="location">at line 3114</div>
<code>
<a href="../../../Thelia/Model/Lang.html"><abbr title="Thelia\Model\Lang">Lang</abbr></a>
<strong>getLang</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Get the associated ChildLang object</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>Optional Connection object.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Lang.html"><abbr title="Thelia\Model\Lang">Lang</abbr></a></td>
<td>The associated ChildLang object.</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_initRelation">
<div class="location">at line 3139</div>
<code>
void
<strong>initRelation</strong>(
string $relationName)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Initializes a collection based on the name of a relation.</p> <p>Avoids crafting an 'init[$relationName]s' method name
that wouldn't work when StandardEnglishPluralizer is used.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$relationName</td>
<td>The name of the relation to initialize</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
void</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_clearOrderProducts">
<div class="location">at line 3161</div>
<code>
void
<strong>clearOrderProducts</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Clears out the collOrderProducts collection</p> <p>This does not modify the database; however, it will remove any associated objects, causing
them to be refetched by subsequent calls to accessor method.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
void</td>
<td></td>
</tr>
</table>
<h4>See also</h4>
<table class="table table-condensed">
<tr>
<td>addOrderProducts()</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_resetPartialOrderProducts">
<div class="location">at line 3169</div>
<code>
<strong>resetPartialOrderProducts</strong>($v = true)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Reset is the collOrderProducts collection loaded partially.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td></td>
<td>$v</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_initOrderProducts">
<div class="location">at line 3186</div>
<code>
void
<strong>initOrderProducts</strong>(
boolean $overrideExisting = true)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Initializes the collOrderProducts collection.</p> <p>By default this just sets the collOrderProducts collection to an empty array (like clearcollOrderProducts());
however, you may wish to override this method in your stub class to provide setting appropriate
to your application -- for example, setting the initial array to the values stored in database.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td>$overrideExisting</td>
<td>If set to true, the method call initializes
the collection even if it is not empty</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
void</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getOrderProducts">
<div class="location">at line 3209</div>
<code>
<abbr title="Propel\Runtime\Collection\Collection">Collection</abbr>|<a href="../../../Thelia/Model/OrderProduct.html"><abbr title="Thelia\Model\OrderProduct">OrderProduct</abbr></a>[]
<strong>getOrderProducts</strong>(
<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr> $criteria = null,
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Gets an array of ChildOrderProduct objects which contain a foreign key that references this object.</p> <p>If the $criteria is not null, it is used to always fetch the results from the database.
Otherwise the results are fetched from the database the first time, then cached.
Next time the same method is called without $criteria, the cached collection is returned.
If this ChildOrder is new, it will return
an empty collection or the current collection; the criteria is ignored on a new object.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr></td>
<td>$criteria</td>
<td>optional Criteria object to narrow the query</td>
</tr>
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>optional connection object</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Propel\Runtime\Collection\Collection">Collection</abbr>|<a href="../../../Thelia/Model/OrderProduct.html"><abbr title="Thelia\Model\OrderProduct">OrderProduct</abbr></a>[]</td>
<td>List of ChildOrderProduct objects</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setOrderProducts">
<div class="location">at line 3265</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setOrderProducts</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Collection\Collection">Collection</abbr> $orderProducts,
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Sets a collection of OrderProduct objects related by a one-to-many relationship
to the current object.</p> <p>It will also schedule objects for deletion based on a diff between old objects (aka persisted)
and new objects from the given Propel collection.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Collection\Collection">Collection</abbr></td>
<td>$orderProducts</td>
<td>A Propel collection.</td>
</tr>
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>Optional connection object</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_countOrderProducts">
<div class="location">at line 3296</div>
<code>
int
<strong>countOrderProducts</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr> $criteria = null,
boolean $distinct = false,
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Returns the number of related OrderProduct objects.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr></td>
<td>$criteria</td>
<td></td>
</tr>
<tr>
<td>
boolean</td>
<td>$distinct</td>
<td></td>
</tr>
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td></td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td>Count of related OrderProduct objects.</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_addOrderProduct">
<div class="location">at line 3328</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>addOrderProduct</strong>(
<abbr title="Thelia\Model\Base\Thelia\Model\OrderProduct">OrderProduct</abbr> $l)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Method called to associate a ChildOrderProduct object to this object
through the ChildOrderProduct foreign key attribute.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Thelia\Model\OrderProduct">OrderProduct</abbr></td>
<td>$l</td>
<td>ChildOrderProduct</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_removeOrderProduct">
<div class="location">at line 3355</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>removeOrderProduct</strong>(
<a href="../../../Thelia/Model/Base/OrderProduct.html"><abbr title="Thelia\Model\Base\OrderProduct">OrderProduct</abbr></a> $orderProduct)</code>
</h3>
<div class="details">
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Base/OrderProduct.html"><abbr title="Thelia\Model\Base\OrderProduct">OrderProduct</abbr></a></td>
<td>$orderProduct</td>
<td>The orderProduct object to remove.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_clearOrderCoupons">
<div class="location">at line 3379</div>
<code>
void
<strong>clearOrderCoupons</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Clears out the collOrderCoupons collection</p> <p>This does not modify the database; however, it will remove any associated objects, causing
them to be refetched by subsequent calls to accessor method.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
void</td>
<td></td>
</tr>
</table>
<h4>See also</h4>
<table class="table table-condensed">
<tr>
<td>addOrderCoupons()</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_resetPartialOrderCoupons">
<div class="location">at line 3387</div>
<code>
<strong>resetPartialOrderCoupons</strong>($v = true)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Reset is the collOrderCoupons collection loaded partially.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td></td>
<td>$v</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_initOrderCoupons">
<div class="location">at line 3404</div>
<code>
void
<strong>initOrderCoupons</strong>(
boolean $overrideExisting = true)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Initializes the collOrderCoupons collection.</p> <p>By default this just sets the collOrderCoupons collection to an empty array (like clearcollOrderCoupons());
however, you may wish to override this method in your stub class to provide setting appropriate
to your application -- for example, setting the initial array to the values stored in database.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td>$overrideExisting</td>
<td>If set to true, the method call initializes
the collection even if it is not empty</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
void</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getOrderCoupons">
<div class="location">at line 3427</div>
<code>
<abbr title="Propel\Runtime\Collection\Collection">Collection</abbr>|<a href="../../../Thelia/Model/OrderCoupon.html"><abbr title="Thelia\Model\OrderCoupon">OrderCoupon</abbr></a>[]
<strong>getOrderCoupons</strong>(
<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr> $criteria = null,
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Gets an array of ChildOrderCoupon objects which contain a foreign key that references this object.</p> <p>If the $criteria is not null, it is used to always fetch the results from the database.
Otherwise the results are fetched from the database the first time, then cached.
Next time the same method is called without $criteria, the cached collection is returned.
If this ChildOrder is new, it will return
an empty collection or the current collection; the criteria is ignored on a new object.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr></td>
<td>$criteria</td>
<td>optional Criteria object to narrow the query</td>
</tr>
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>optional connection object</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Propel\Runtime\Collection\Collection">Collection</abbr>|<a href="../../../Thelia/Model/OrderCoupon.html"><abbr title="Thelia\Model\OrderCoupon">OrderCoupon</abbr></a>[]</td>
<td>List of ChildOrderCoupon objects</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setOrderCoupons">
<div class="location">at line 3483</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setOrderCoupons</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Collection\Collection">Collection</abbr> $orderCoupons,
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Sets a collection of OrderCoupon objects related by a one-to-many relationship
to the current object.</p> <p>It will also schedule objects for deletion based on a diff between old objects (aka persisted)
and new objects from the given Propel collection.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Collection\Collection">Collection</abbr></td>
<td>$orderCoupons</td>
<td>A Propel collection.</td>
</tr>
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>Optional connection object</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_countOrderCoupons">
<div class="location">at line 3514</div>
<code>
int
<strong>countOrderCoupons</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr> $criteria = null,
boolean $distinct = false,
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Returns the number of related OrderCoupon objects.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr></td>
<td>$criteria</td>
<td></td>
</tr>
<tr>
<td>
boolean</td>
<td>$distinct</td>
<td></td>
</tr>
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td></td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td>Count of related OrderCoupon objects.</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_addOrderCoupon">
<div class="location">at line 3546</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>addOrderCoupon</strong>(
<abbr title="Thelia\Model\Base\Thelia\Model\OrderCoupon">OrderCoupon</abbr> $l)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Method called to associate a ChildOrderCoupon object to this object
through the ChildOrderCoupon foreign key attribute.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Thelia\Model\OrderCoupon">OrderCoupon</abbr></td>
<td>$l</td>
<td>ChildOrderCoupon</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_removeOrderCoupon">
<div class="location">at line 3573</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>removeOrderCoupon</strong>(
<a href="../../../Thelia/Model/Base/OrderCoupon.html"><abbr title="Thelia\Model\Base\OrderCoupon">OrderCoupon</abbr></a> $orderCoupon)</code>
</h3>
<div class="details">
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Base/OrderCoupon.html"><abbr title="Thelia\Model\Base\OrderCoupon">OrderCoupon</abbr></a></td>
<td>$orderCoupon</td>
<td>The orderCoupon object to remove.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_clearOrderVersions">
<div class="location">at line 3597</div>
<code>
void
<strong>clearOrderVersions</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Clears out the collOrderVersions collection</p> <p>This does not modify the database; however, it will remove any associated objects, causing
them to be refetched by subsequent calls to accessor method.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
void</td>
<td></td>
</tr>
</table>
<h4>See also</h4>
<table class="table table-condensed">
<tr>
<td>addOrderVersions()</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_resetPartialOrderVersions">
<div class="location">at line 3605</div>
<code>
<strong>resetPartialOrderVersions</strong>($v = true)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Reset is the collOrderVersions collection loaded partially.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td></td>
<td>$v</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_initOrderVersions">
<div class="location">at line 3622</div>
<code>
void
<strong>initOrderVersions</strong>(
boolean $overrideExisting = true)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Initializes the collOrderVersions collection.</p> <p>By default this just sets the collOrderVersions collection to an empty array (like clearcollOrderVersions());
however, you may wish to override this method in your stub class to provide setting appropriate
to your application -- for example, setting the initial array to the values stored in database.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td>$overrideExisting</td>
<td>If set to true, the method call initializes
the collection even if it is not empty</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
void</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getOrderVersions">
<div class="location">at line 3645</div>
<code>
<abbr title="Propel\Runtime\Collection\Collection">Collection</abbr>|<a href="../../../Thelia/Model/OrderVersion.html"><abbr title="Thelia\Model\OrderVersion">OrderVersion</abbr></a>[]
<strong>getOrderVersions</strong>(
<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr> $criteria = null,
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Gets an array of ChildOrderVersion objects which contain a foreign key that references this object.</p> <p>If the $criteria is not null, it is used to always fetch the results from the database.
Otherwise the results are fetched from the database the first time, then cached.
Next time the same method is called without $criteria, the cached collection is returned.
If this ChildOrder is new, it will return
an empty collection or the current collection; the criteria is ignored on a new object.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr></td>
<td>$criteria</td>
<td>optional Criteria object to narrow the query</td>
</tr>
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>optional connection object</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Propel\Runtime\Collection\Collection">Collection</abbr>|<a href="../../../Thelia/Model/OrderVersion.html"><abbr title="Thelia\Model\OrderVersion">OrderVersion</abbr></a>[]</td>
<td>List of ChildOrderVersion objects</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_setOrderVersions">
<div class="location">at line 3701</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>setOrderVersions</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Collection\Collection">Collection</abbr> $orderVersions,
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Sets a collection of OrderVersion objects related by a one-to-many relationship
to the current object.</p> <p>It will also schedule objects for deletion based on a diff between old objects (aka persisted)
and new objects from the given Propel collection.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Collection\Collection">Collection</abbr></td>
<td>$orderVersions</td>
<td>A Propel collection.</td>
</tr>
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>Optional connection object</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_countOrderVersions">
<div class="location">at line 3735</div>
<code>
int
<strong>countOrderVersions</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr> $criteria = null,
boolean $distinct = false,
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Returns the number of related OrderVersion objects.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr></td>
<td>$criteria</td>
<td></td>
</tr>
<tr>
<td>
boolean</td>
<td>$distinct</td>
<td></td>
</tr>
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td></td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
int</td>
<td>Count of related OrderVersion objects.</td>
</tr>
</table>
<h4>Exceptions</h4>
<table class="table table-condensed">
<tr>
<td><abbr title="Propel\Runtime\Exception\PropelException">PropelException</abbr></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_addOrderVersion">
<div class="location">at line 3767</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>addOrderVersion</strong>(
<abbr title="Thelia\Model\Base\Thelia\Model\OrderVersion">OrderVersion</abbr> $l)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Method called to associate a ChildOrderVersion object to this object
through the ChildOrderVersion foreign key attribute.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Thelia\Model\OrderVersion">OrderVersion</abbr></td>
<td>$l</td>
<td>ChildOrderVersion</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_removeOrderVersion">
<div class="location">at line 3794</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>removeOrderVersion</strong>(
<a href="../../../Thelia/Model/Base/OrderVersion.html"><abbr title="Thelia\Model\Base\OrderVersion">OrderVersion</abbr></a> $orderVersion)</code>
</h3>
<div class="details">
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Base/OrderVersion.html"><abbr title="Thelia\Model\Base\OrderVersion">OrderVersion</abbr></a></td>
<td>$orderVersion</td>
<td>The orderVersion object to remove.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_clear">
<div class="location">at line 3812</div>
<code>
<strong>clear</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Clears the current object and sets all attributes to their default values</p> </div>
<div class="tags">
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_clearAllReferences">
<div class="location">at line 3856</div>
<code>
<strong>clearAllReferences</strong>(
boolean $deep = false)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Resets all references to other model objects or collections of model objects.</p> <p>This method is a user-space workaround for PHP's inability to garbage collect
objects with circular references (even in PHP 5.3). This is currently necessary
when using Propel in certain daemon or large-volume/high-memory operations.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td>$deep</td>
<td>Whether to also clear the references on all referrer objects.</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method___toString">
<div class="location">at line 3894</div>
<code>
string
<strong>__toString</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Return the string representation of this object</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_keepUpdateDateUnchanged">
<div class="location">at line 3906</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>keepUpdateDateUnchanged</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Mark the current object so that the update date doesn't get updated during next save</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_enforceVersioning">
<div class="location">at line 3920</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>enforceVersioning</strong>()</code>
</h3>
<div class="details">
<div class="method-description">
<p>Enforce a new Version of this object upon next save.</p> </div>
<div class="tags">
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_isVersioningNecessary">
<div class="location">at line 3932</div>
<code>
boolean
<strong>isVersioningNecessary</strong>($con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Checks whether the current state must be recorded as a version</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td></td>
<td>$con</td>
<td></td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_addVersion">
<div class="location">at line 3960</div>
<code>
<a href="../../../Thelia/Model/OrderVersion.html"><abbr title="Thelia\Model\OrderVersion">OrderVersion</abbr></a>
<strong>addVersion</strong>(
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Creates a version of the current object and saves it.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>the connection to use</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/OrderVersion.html"><abbr title="Thelia\Model\OrderVersion">OrderVersion</abbr></a></td>
<td>A version object</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_toVersion">
<div class="location">at line 4007</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>toVersion</strong>(
integer $versionNumber,
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Sets the properties of the current object to the value they had at a specific version</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
integer</td>
<td>$versionNumber</td>
<td>The version number to read</td>
</tr>
<tr>
<td>
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>The connection to use</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_populateFromVersion">
<div class="location">at line 4027</div>
<code>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a>
<strong>populateFromVersion</strong>(
<a href="../../../Thelia/Model/OrderVersion.html"><abbr title="Thelia\Model\OrderVersion">OrderVersion</abbr></a> $version,
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null,
array $loadedObjects = array())</code>
</h3>
<div class="details">
<div class="method-description">
<p>Sets the properties of the current object to the value they had at a specific version</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/OrderVersion.html"><abbr title="Thelia\Model\OrderVersion">OrderVersion</abbr></a></td>
<td>$version</td>
<td>The version object to use</td>
</tr>
<tr>
<td>
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>the connection to use</td>
</tr>
<tr>
<td>
array</td>
<td>$loadedObjects</td>
<td>objects that been loaded in a chain of populateFromVersion calls on referrer or fk objects.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/Order.html"><abbr title="Thelia\Model\Order">Order</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getLastVersionNumber">
<div class="location">at line 4080</div>
<code>
integer
<strong>getLastVersionNumber</strong>(
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Gets the latest persisted version number for the current object</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>the connection to use</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
integer</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_isLastVersion">
<div class="location">at line 4100</div>
<code>
Boolean
<strong>isLastVersion</strong>(
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Checks whether the current object is the latest one</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>the connection to use</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
Boolean</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getOneVersion">
<div class="location">at line 4113</div>
<code>
<a href="../../../Thelia/Model/OrderVersion.html"><abbr title="Thelia\Model\OrderVersion">OrderVersion</abbr></a>
<strong>getOneVersion</strong>(
integer $versionNumber,
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Retrieves a version object for this entity and a version number</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
integer</td>
<td>$versionNumber</td>
<td>The version number to read</td>
</tr>
<tr>
<td>
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>the connection to use</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<a href="../../../Thelia/Model/OrderVersion.html"><abbr title="Thelia\Model\OrderVersion">OrderVersion</abbr></a></td>
<td>A version object</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getAllVersions">
<div class="location">at line 4128</div>
<code>
<abbr title="Propel\Runtime\Collection\ObjectCollection">ObjectCollection</abbr>
<strong>getAllVersions</strong>(
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Gets all the versions of this object, in incremental order</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>the connection to use</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Propel\Runtime\Collection\ObjectCollection">ObjectCollection</abbr></td>
<td>A list of ChildOrderVersion objects</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_compareVersion">
<div class="location">at line 4153</div>
<code>
array
<strong>compareVersion</strong>(
integer $versionNumber,
string $keys = 'columns',
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null,
array $ignoredColumns = array())</code>
</h3>
<div class="details">
<div class="method-description">
<p>Compares the current object with another of its version.</p> <p><code>
print_r($book->compareVersion(1));
=> array(
'1' => array('Title' => 'Book title at version 1'),
'2' => array('Title' => 'Book title at version 2')
);
</code></p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
integer</td>
<td>$versionNumber</td>
<td></td>
</tr>
<tr>
<td>
string</td>
<td>$keys</td>
<td>Main key used for the result diff (versions|columns)</td>
</tr>
<tr>
<td>
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>the connection to use</td>
</tr>
<tr>
<td>
array</td>
<td>$ignoredColumns</td>
<td>The columns to exclude from the diff.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
array</td>
<td>A list of differences</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_compareVersions">
<div class="location">at line 4179</div>
<code>
array
<strong>compareVersions</strong>(
integer $fromVersionNumber,
integer $toVersionNumber,
string $keys = 'columns',
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null,
array $ignoredColumns = array())</code>
</h3>
<div class="details">
<div class="method-description">
<p>Compares two versions of the current object.</p> <p><code>
print_r($book->compareVersions(1, 2));
=> array(
'1' => array('Title' => 'Book title at version 1'),
'2' => array('Title' => 'Book title at version 2')
);
</code></p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
integer</td>
<td>$fromVersionNumber</td>
<td></td>
</tr>
<tr>
<td>
integer</td>
<td>$toVersionNumber</td>
<td></td>
</tr>
<tr>
<td>
string</td>
<td>$keys</td>
<td>Main key used for the result diff (versions|columns)</td>
</tr>
<tr>
<td>
<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>the connection to use</td>
</tr>
<tr>
<td>
array</td>
<td>$ignoredColumns</td>
<td>The columns to exclude from the diff.</td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
array</td>
<td>A list of differences</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_getLastVersions">
<div class="location">at line 4242</div>
<code>
<abbr title="Thelia\Model\Base\PropelCollection">PropelCollection</abbr>|array
<strong>getLastVersions</strong>($number = 10, $criteria = null, $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>retrieve the last $number versions.</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td></td>
<td>$number</td>
<td></td>
</tr>
<tr>
<td></td>
<td>$criteria</td>
<td></td>
</tr>
<tr>
<td></td>
<td>$con</td>
<td></td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\PropelCollection">PropelCollection</abbr>|array</td>
<td>\Thelia\Model\OrderVersion[] List of \Thelia\Model\OrderVersion objects</td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_preSave">
<div class="location">at line 4255</div>
<code>
boolean
<strong>preSave</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Code to be run before persisting the object</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td></td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_postSave">
<div class="location">at line 4264</div>
<code>
<strong>postSave</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Code to be run after persisting the object</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_preInsert">
<div class="location">at line 4274</div>
<code>
boolean
<strong>preInsert</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Code to be run before inserting to database</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td></td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_postInsert">
<div class="location">at line 4283</div>
<code>
<strong>postInsert</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Code to be run after inserting to database</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_preUpdate">
<div class="location">at line 4293</div>
<code>
boolean
<strong>preUpdate</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Code to be run before updating the object in database</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td></td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_postUpdate">
<div class="location">at line 4302</div>
<code>
<strong>postUpdate</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Code to be run after updating the object in database</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_preDelete">
<div class="location">at line 4312</div>
<code>
boolean
<strong>preDelete</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Code to be run before deleting the object in database</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td></td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
boolean</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method_postDelete">
<div class="location">at line 4321</div>
<code>
<strong>postDelete</strong>(
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Code to be run after deleting the object in database</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
<abbr title="Thelia\Model\Base\Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div class="method-item">
<h3 id="method___call">
<div class="location">at line 4338</div>
<code>
array|string
<strong>__call</strong>(
string $name,
mixed $params)</code>
</h3>
<div class="details">
<div class="method-description">
<p>Derived method to catches calls to undefined methods.</p> <p>Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.).
Allows to define default __call() behavior if you overwrite __call()</p> </div>
<div class="tags">
<h4>Parameters</h4>
<table class="table table-condensed">
<tr>
<td>
string</td>
<td>$name</td>
<td></td>
</tr>
<tr>
<td>
mixed</td>
<td>$params</td>
<td></td>
</tr>
</table>
<h4>Return Value</h4>
<table class="table table-condensed">
<tr>
<td>
array|string</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
Generated by <a href="http://sami.sensiolabs.org/">Sami, the API Documentation Generator</a>.
</div>
</div>
</div>
</body>
</html>
| thelia/thelia.github.io | api/2.2/Thelia/Model/Base/Order.html | HTML | mit | 300,163 |
Translations = Class.new
class Locale < Struct.new(:code)
ENGLISH_LOCALE_CODE = :en
extend ActiveModel::Naming
include ActiveModel::Conversion
def initialize(code)
super(code.to_sym)
end
def self.model_name
ActiveModel::Name.new(Translations)
end
def self.current
new(I18n.locale)
end
def self.all
I18n.available_locales.map do |l|
new(l)
end
end
def self.non_english
all.reject(&:english?)
end
def self.right_to_left
all.select(&:rtl?)
end
def self.find_by_language_name(native_language_name)
all.detect { |l| l.native_language_name == native_language_name }
end
def self.find_by_code(code)
all.detect { |l| l.code == code.to_sym }
end
def self.coerce(value)
case value
when Symbol, String
Locale.new(value)
when Locale
value
else
raise ArgumentError.new("Could not coerce #{value.inspect} to a Locale")
end
end
def english?
code == ENGLISH_LOCALE_CODE
end
def native_language_name
I18n.t("language_names.#{code}", locale: code)
end
def english_language_name
I18n.t("language_names.#{code}", locale: ENGLISH_LOCALE_CODE)
end
def native_and_english_language_name
"#{native_language_name} (#{english_language_name})"
end
def rtl?
I18n.t("i18n.direction", locale: code, default: "ltr") == "rtl"
end
def to_param
code.to_s
end
def persisted?
true
end
end
| YOTOV-LIMITED/whitehall | lib/locale.rb | Ruby | mit | 1,447 |
<?php
namespace Kunstmaan\LeadGenerationBundle\Form\Rule;
use Kunstmaan\AdminBundle\Helper\DomainConfigurationInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
class LocaleWhiteListAdminType extends AbstractRuleAdminType
{
private $locales;
public function __construct(DomainConfigurationInterface $domainConfiguration)
{
$locales = $domainConfiguration->getFrontendLocales();
$this->locales = array_combine($locales, $locales);
}
/**
* Builds the form.
*
* This method is called for each type in the hierarchy starting form the
* top most type. Type extensions can further modify the form.
*
* @see FormTypeExtensionInterface::buildForm()
*
* @param FormBuilderInterface $builder The form builder
* @param array $options The options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('locale', ChoiceType::class, array(
'label' => 'kuma_lead_generation.form.locale_white_list.locale.label',
'attr' => array(
'info_text' => 'kuma_lead_generation.form.locale_white_list.locale.info_text',
),
'choices' => $this->locales,
));
}
/**
* Returns the name of this type.
*
* @return string The name of this type
*/
public function getBlockPrefix()
{
return 'locale_whitelist_form';
}
}
| mwoynarski/KunstmaanBundlesCMS | src/Kunstmaan/LeadGenerationBundle/Form/Rule/LocaleWhiteListAdminType.php | PHP | mit | 1,531 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<HTML style="overflow:auto;">
<HEAD>
<meta name="generator" content="JDiff v1.1.0">
<!-- Generated by the JDiff Javadoc doclet -->
<!-- (http://www.jdiff.org) -->
<meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.">
<meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet">
<TITLE>
android.net.SSLCertificateSocketFactory
</TITLE>
<link href="../../../../assets/android-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../stylesheet-jdiff.css" rel="stylesheet" type="text/css" />
<noscript>
<style type="text/css">
body{overflow:auto;}
#body-content{position:relative; top:0;}
#doc-content{overflow:visible;border-left:3px solid #666;}
#side-nav{padding:0;}
#side-nav .toggle-list ul {display:block;}
#resize-packages-nav{border-bottom:3px solid #666;}
</style>
</noscript>
<style type="text/css">
</style>
</HEAD>
<BODY>
<!-- Start of nav bar -->
<a name="top"></a>
<div id="header" style="margin-bottom:0;padding-bottom:0;">
<div id="headerLeft">
<a href="../../../../index.html" tabindex="-1" target="_top"><img src="../../../../assets/images/bg_logo.png" alt="Android Developers" /></a>
</div>
<div id="headerRight">
<div id="headerLinks">
<!-- <img src="/assets/images/icon_world.jpg" alt="" /> -->
<span class="text">
<!-- <a href="#">English</a> | -->
<nobr><a href="http://developer.android.com" target="_top">Android Developers</a> | <a href="http://www.android.com" target="_top">Android.com</a></nobr>
</span>
</div>
<div class="and-diff-id" style="margin-top:6px;margin-right:8px;">
<table class="diffspectable">
<tr>
<td colspan="2" class="diffspechead">API Diff Specification</td>
</tr>
<tr>
<td class="diffspec" style="padding-top:.25em">To Level:</td>
<td class="diffvaluenew" style="padding-top:.25em">17</td>
</tr>
<tr>
<td class="diffspec">From Level:</td>
<td class="diffvalueold">16</td>
</tr>
<tr>
<td class="diffspec">Generated</td>
<td class="diffvalue">2012.11.12 19:50</td>
</tr>
</table>
</div><!-- End and-diff-id -->
<div class="and-diff-id" style="margin-right:8px;">
<table class="diffspectable">
<tr>
<td class="diffspec" colspan="2"><a href="jdiff_statistics.html">Statistics</a>
</tr>
</table>
</div> <!-- End and-diff-id -->
</div> <!-- End headerRight -->
</div> <!-- End header -->
<div id="body-content" xstyle="padding:12px;padding-right:18px;">
<div id="doc-content" style="position:relative;">
<div id="mainBodyFluid">
<H2>
Class android.net.<A HREF="../../../../reference/android/net/SSLCertificateSocketFactory.html" target="_top"><font size="+2"><code>SSLCertificateSocketFactory</code></font></A>
</H2>
<a NAME="constructors"></a>
<a NAME="methods"></a>
<p>
<a NAME="Added"></a>
<TABLE summary="Added Methods" WIDTH="100%">
<TR>
<TH VALIGN="TOP" COLSPAN=2>Added Methods</FONT></TD>
</TH>
<TR BGCOLOR="#FFFFFF" CLASS="TableRowColor">
<TD VALIGN="TOP" WIDTH="25%">
<A NAME="android.net.SSLCertificateSocketFactory.setHostname_added(java.net.Socket, java.lang.String)"></A>
<nobr><code>void</code> <A HREF="../../../../reference/android/net/SSLCertificateSocketFactory.html#setHostname(java.net.Socket, java.lang.String)" target="_top"><code>setHostname</code></A>(<code>Socket,</nobr> String<nobr><nobr></code>)</nobr>
</TD>
<TD> </TD>
</TR>
<TR BGCOLOR="#FFFFFF" CLASS="TableRowColor">
<TD VALIGN="TOP" WIDTH="25%">
<A NAME="android.net.SSLCertificateSocketFactory.setUseSessionTickets_added(java.net.Socket, boolean)"></A>
<nobr><code>void</code> <A HREF="../../../../reference/android/net/SSLCertificateSocketFactory.html#setUseSessionTickets(java.net.Socket, boolean)" target="_top"><code>setUseSessionTickets</code></A>(<code>Socket,</nobr> boolean<nobr><nobr></code>)</nobr>
</TD>
<TD> </TD>
</TR>
</TABLE>
<a NAME="fields"></a>
</div>
<div id="footer">
<div id="copyright">
Except as noted, this content is licensed under
<a href="http://creativecommons.org/licenses/by/2.5/"> Creative Commons Attribution 2.5</a>.
For details and restrictions, see the <a href="/license.html">Content License</a>.
</div>
<div id="footerlinks">
<p>
<a href="http://www.android.com/terms.html">Site Terms of Service</a> -
<a href="http://www.android.com/privacy.html">Privacy Policy</a> -
<a href="http://www.android.com/branding.html">Brand Guidelines</a>
</p>
</div>
</div> <!-- end footer -->
</div><!-- end doc-content -->
</div> <!-- end body-content -->
<script src="//www.google-analytics.com/ga.js" type="text/javascript">
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-5831155-1");
pageTracker._setAllowAnchor(true);
pageTracker._initData();
pageTracker._trackPageview();
} catch(e) {}
</script>
</BODY>
</HTML>
| AzureZhao/android-developer-cn | sdk/api_diff/17/changes/android.net.SSLCertificateSocketFactory.html | HTML | mit | 5,363 |
require "spec_helper"
describe Mongoid::Extensions::Time do
describe ".demongoize" do
after(:all) do
Mongoid.use_utc = false
Mongoid.use_activesupport_time_zone = true
end
let!(:time) do
Time.local(2010, 11, 19)
end
context "when the time zone is not defined" do
before do
Mongoid.use_utc = false
end
context "when the local time is not observing daylight saving" do
let(:time) do
Time.utc(2010, 11, 19)
end
it "returns the local time" do
expect(Time.demongoize(time).utc_offset).to eq(
Time.local(2010, 11, 19).utc_offset
)
end
end
context "when the local time is observing daylight saving" do
let(:time) do
Time.utc(2010, 9, 19)
end
it "returns the local time" do
expect(Time.demongoize(time)).to eq(time.getlocal)
end
end
context "when we have a time close to midnight" do
let(:time) do
Time.local(2010, 11, 19, 0, 30).utc
end
it "changes it back to the equivalent local time" do
expect(Time.demongoize(time)).to eq(time)
end
end
context "when using the ActiveSupport time zone" do
before do
Mongoid.use_activesupport_time_zone = true
Time.zone = "Stockholm"
end
after do
Time.zone = nil
Mongoid.use_activesupport_time_zone = false
end
it "returns an ActiveSupport::TimeWithZone" do
expect(Time.demongoize(time).class).to eq(ActiveSupport::TimeWithZone)
end
context "when the local time is not observing daylight saving" do
let(:new_time) do
Time.utc(2010, 11, 19, 12)
end
it "returns the local time" do
expect(Time.demongoize(new_time)).to eq(
Time.zone.local(2010, 11, 19, 13)
)
end
end
context "when the local time is observing daylight saving" do
let(:new_time) do
Time.utc(2010, 9, 19, 12)
end
it "returns the local time" do
expect(Time.demongoize(new_time)).to eq(
Time.zone.local(2010, 9, 19, 14)
)
end
end
context "when we have a time close to midnight" do
let(:new_time) do
Time.utc(2010, 11, 19, 0, 30)
end
it "change it back to the equivalent local time" do
expect(Time.demongoize(new_time)).to eq(
Time.zone.local(2010, 11, 19, 1, 30)
)
end
end
end
end
context "when the time zone is defined as UTC" do
before do
Mongoid.use_utc = true
end
after do
Mongoid.use_utc = false
end
it "returns utc" do
expect(Time.demongoize(time.dup.utc).utc_offset).to eq(0)
end
context "when using the ActiveSupport time zone" do
let(:time) do
Time.utc(2010, 11, 19, 0, 30)
end
before do
Mongoid.use_activesupport_time_zone = true
Time.zone = "Stockholm"
end
after do
Time.zone = nil
Mongoid.use_activesupport_time_zone = false
end
it "returns utc" do
expect(Time.demongoize(time)).to eq(
ActiveSupport::TimeZone['UTC'].local(2010, 11, 19, 0, 30)
)
end
it "returns an ActiveSupport::TimeWithZone" do
expect(Time.demongoize(time).class).to eq(
ActiveSupport::TimeWithZone
)
end
end
end
context "when time is nil" do
it "returns nil" do
expect(Time.demongoize(nil)).to be_nil
end
end
end
describe ".mongoize" do
let!(:time) do
Time.local(2010, 11, 19)
end
context "when given nil" do
it "returns nil" do
expect(Time.mongoize(nil)).to be_nil
end
end
context "when string is empty" do
it "returns nil" do
expect(Time.mongoize("")).to be_nil
end
end
context "when given a string" do
context "when the string is a valid time" do
it "converts to a utc time" do
expect(Time.mongoize(time.to_s).utc_offset).to eq(0)
end
it "serializes with time parsing" do
expect(Time.mongoize(time.to_s)).to eq(Time.parse(time.to_s).utc)
end
it "returns a local date from the string" do
expect(Time.mongoize(time.to_s)).to eq(
Time.local(time.year, time.month, time.day, time.hour, time.min, time.sec)
)
end
end
context "when the string is an invalid time" do
it "converts the time to nil" do
expect(Time.mongoize("time")).to eq(nil)
end
end
context "when using the ActiveSupport time zone" do
before do
Mongoid.use_activesupport_time_zone = true
# if this is actually your time zone, the following tests are useless
Time.zone = "Stockholm"
end
after do
Time.zone = nil
Mongoid.use_activesupport_time_zone = false
end
context "when the local time is not observing daylight saving" do
it "returns the local time" do
expect(Time.mongoize('2010-11-19 5:00:00')).to eq(
Time.utc(2010, 11, 19, 4)
)
end
end
context "when the local time is observing daylight saving" do
it "returns the local time" do
expect(Time.mongoize('2010-9-19 5:00:00')).to eq(
Time.utc(2010, 9, 19, 3)
)
end
end
end
end
context "when given a DateTime" do
let!(:time) do
DateTime.now
end
let!(:eom_time) do
DateTime.parse("2012-11-30T23:59:59.999999999-05:00")
end
let!(:eom_time_mongoized) do
eom_time.mongoize
end
it "doesn't strip milli- or microseconds" do
expect(Time.mongoize(time).to_f).to eq(time.to_time.to_f)
end
it "doesn't round up the hour at end of month" do
expect(eom_time_mongoized.hour).to eq(eom_time.utc.hour)
end
it "doesn't round up the minute" do
expect(eom_time_mongoized.min).to eq(eom_time.utc.min)
end
it "doesn't round up the seconds" do
expect(eom_time_mongoized.sec).to eq(eom_time.utc.sec)
end
it "does not alter seconds" do
expect((eom_time_mongoized.usec)).to eq(999999)
end
it "does not alter seconds with fractions" do
expect(DateTime.mongoize(1.11).to_f).to eq(1.11)
end
context "when using the ActiveSupport time zone" do
let(:datetime) do
DateTime.new(2010, 11, 19)
end
before do
Mongoid.use_activesupport_time_zone = true
# if this is actually your time zone, the following tests are useless
Time.zone = "Stockholm"
end
after do
Time.zone = nil
Mongoid.use_activesupport_time_zone = false
end
it "assumes the given time is local" do
expect(Time.mongoize(datetime)).to eq(
Time.utc(2010, 11, 19)
)
end
it "doesn't round up the hour" do
expect(eom_time_mongoized.hour).to eq(eom_time.utc.hour)
end
it "doesn't round up the minutes" do
expect(eom_time_mongoized.min).to eq(eom_time.utc.min)
end
it "doesn't round up the seconds" do
expect(eom_time_mongoized.sec).to eq(eom_time.utc.sec)
end
it "does not alter the seconds" do
expect((eom_time_mongoized.usec)).to eq(999999)
end
end
end
context "when given a Time" do
it "converts to a utc time" do
expect(Time.mongoize(time).utc_offset).to eq(0)
end
it "returns utc times unchanged" do
expect(Time.mongoize(time.utc)).to eq(time.utc)
end
it "returns the time as utc" do
expect(Time.mongoize(time)).to eq(time.utc)
end
it "doesn't strip milli- or microseconds" do
expect(Time.mongoize(time).to_f).to eq(time.to_f)
end
it "does not alter seconds with fractions" do
expect(Time.mongoize(102.25).to_f).to eq(102.25)
end
end
context "when given an ActiveSupport::TimeWithZone" do
before do
1.hour.ago
end
it "converts it to utc" do
expect(Time.mongoize(time.in_time_zone("Alaska"))).to eq(
Time.at(time.to_i).utc
)
end
end
context "when given a Date" do
let(:date) do
Date.today
end
it "converts to a utc time" do
expect(Time.mongoize(date)).to eq(Time.local(date.year, date.month, date.day))
end
it "has a zero utc offset" do
expect(Time.mongoize(date).utc_offset).to eq(0)
end
context "when using the ActiveSupport time zone" do
let(:date) do
Date.new(2010, 11, 19)
end
before do
Mongoid.use_activesupport_time_zone = true
# if this is actually your time zone, the following tests are useless
Time.zone = "Stockholm"
end
after do
Time.zone = nil
Mongoid.use_activesupport_time_zone = false
end
it "assumes the given time is local" do
expect(Time.mongoize(date)).to eq(Time.utc(2010, 11, 18, 23))
end
end
end
context "when given an array" do
let(:array) do
[ 2010, 11, 19, 00, 24, 49 ]
end
it "returns a time" do
expect(Time.mongoize(array)).to eq(Time.local(*array))
end
context "when using the ActiveSupport time zone" do
before do
Mongoid.use_activesupport_time_zone = true
# if this is actually your time zone, the following tests are useless
Time.zone = "Stockholm"
end
after do
Time.zone = nil
Mongoid.use_activesupport_time_zone = false
end
it "assumes the given time is local" do
expect(Time.mongoize(array)).to eq(
Time.utc(2010, 11, 18, 23, 24, 49)
)
end
end
end
end
describe "#mongoize" do
let!(:time) do
Time.local(2010, 11, 19)
end
let!(:eom_time) do
Time.local(2012, 11, 30, 23, 59, 59, 999999.999)
end
let!(:eom_time_mongoized) do
eom_time.mongoize
end
it "converts to a utc time" do
expect(time.mongoize.utc_offset).to eq(0)
end
it "returns the time as utc" do
expect(time.mongoize).to eq(time.utc)
end
it "doesn't strip milli- or microseconds" do
expect(time.mongoize.to_f).to eq(time.to_f)
end
it "doesn't round up at end of month" do
expect(eom_time_mongoized.hour).to eq(eom_time.utc.hour)
expect(eom_time_mongoized.min).to eq(eom_time.utc.min)
expect(eom_time_mongoized.sec).to eq(eom_time.utc.sec)
expect(eom_time_mongoized.usec).to eq(eom_time.utc.usec)
expect(eom_time_mongoized.subsec.to_f.round(3)).to eq(eom_time.utc.subsec.to_f.round(3))
end
end
end
| Zhomart/mongoid | spec/mongoid/extensions/time_spec.rb | Ruby | mit | 11,359 |
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
Imports Microsoft.CodeAnalysis.Host.Mef
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.InlineRename
<ExportLanguageService(GetType(IEditorInlineRenameService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicEditorInlineRenameService
Inherits AbstractEditorInlineRenameService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New(
<ImportMany> refactorNotifyServices As IEnumerable(Of IRefactorNotifyService))
MyBase.New(refactorNotifyServices)
End Sub
Protected Overrides Function CheckLanguageSpecificIssues(semanticModel As SemanticModel, symbol As ISymbol, triggerToken As SyntaxToken, ByRef langError As String) As Boolean
Return False
End Function
End Class
End Namespace
| CyrusNajmabadi/roslyn | src/EditorFeatures/VisualBasic/InlineRename/VisualBasicEditorInlineRenameService.vb | Visual Basic | mit | 1,148 |
//===-- CGValue.h - LLVM CodeGen wrappers for llvm::Value* ------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// These classes implement wrappers around llvm::Value in order to
// fully represent the range of values for C L- and R- values.
//
//===----------------------------------------------------------------------===//
#ifndef CLANG_CODEGEN_CGVALUE_H
#define CLANG_CODEGEN_CGVALUE_H
#include "clang/AST/ASTContext.h"
#include "clang/AST/CharUnits.h"
#include "clang/AST/Type.h"
#include "llvm/IR/Value.h"
namespace llvm {
class Constant;
class MDNode;
}
namespace clang {
namespace CodeGen {
class AggValueSlot;
struct CGBitFieldInfo;
/// RValue - This trivial value class is used to represent the result of an
/// expression that is evaluated. It can be one of three things: either a
/// simple LLVM SSA value, a pair of SSA values for complex numbers, or the
/// address of an aggregate value in memory.
class RValue {
enum Flavor { Scalar, Complex, Aggregate };
// Stores first value and flavor.
llvm::PointerIntPair<llvm::Value *, 2, Flavor> V1;
// Stores second value and volatility.
llvm::PointerIntPair<llvm::Value *, 1, bool> V2;
public:
bool isScalar() const { return V1.getInt() == Scalar; }
bool isComplex() const { return V1.getInt() == Complex; }
bool isAggregate() const { return V1.getInt() == Aggregate; }
bool isVolatileQualified() const { return V2.getInt(); }
/// getScalarVal() - Return the Value* of this scalar value.
llvm::Value *getScalarVal() const {
assert(isScalar() && "Not a scalar!");
return V1.getPointer();
}
/// getComplexVal - Return the real/imag components of this complex value.
///
std::pair<llvm::Value *, llvm::Value *> getComplexVal() const {
return std::make_pair(V1.getPointer(), V2.getPointer());
}
/// getAggregateAddr() - Return the Value* of the address of the aggregate.
llvm::Value *getAggregateAddr() const {
assert(isAggregate() && "Not an aggregate!");
return V1.getPointer();
}
static RValue get(llvm::Value *V) {
RValue ER;
ER.V1.setPointer(V);
ER.V1.setInt(Scalar);
ER.V2.setInt(false);
return ER;
}
static RValue getComplex(llvm::Value *V1, llvm::Value *V2) {
RValue ER;
ER.V1.setPointer(V1);
ER.V2.setPointer(V2);
ER.V1.setInt(Complex);
ER.V2.setInt(false);
return ER;
}
static RValue getComplex(const std::pair<llvm::Value *, llvm::Value *> &C) {
return getComplex(C.first, C.second);
}
// FIXME: Aggregate rvalues need to retain information about whether they are
// volatile or not. Remove default to find all places that probably get this
// wrong.
static RValue getAggregate(llvm::Value *V, bool Volatile = false) {
RValue ER;
ER.V1.setPointer(V);
ER.V1.setInt(Aggregate);
ER.V2.setInt(Volatile);
return ER;
}
};
/// Does an ARC strong l-value have precise lifetime?
enum ARCPreciseLifetime_t {
ARCImpreciseLifetime, ARCPreciseLifetime
};
/// LValue - This represents an lvalue references. Because C/C++ allow
/// bitfields, this is not a simple LLVM pointer, it may be a pointer plus a
/// bitrange.
class LValue {
enum {
Simple, // This is a normal l-value, use getAddress().
VectorElt, // This is a vector element l-value (V[i]), use getVector*
BitField, // This is a bitfield l-value, use getBitfield*.
ExtVectorElt // This is an extended vector subset, use getExtVectorComp
} LVType;
llvm::Value *V;
union {
// Index into a vector subscript: V[i]
llvm::Value *VectorIdx;
// ExtVector element subset: V.xyx
llvm::Constant *VectorElts;
// BitField start bit and size
const CGBitFieldInfo *BitFieldInfo;
};
QualType Type;
// 'const' is unused here
Qualifiers Quals;
// The alignment to use when accessing this lvalue. (For vector elements,
// this is the alignment of the whole vector.)
int64_t Alignment;
// objective-c's ivar
bool Ivar:1;
// objective-c's ivar is an array
bool ObjIsArray:1;
// LValue is non-gc'able for any reason, including being a parameter or local
// variable.
bool NonGC: 1;
// Lvalue is a global reference of an objective-c object
bool GlobalObjCRef : 1;
// Lvalue is a thread local reference
bool ThreadLocalRef : 1;
// Lvalue has ARC imprecise lifetime. We store this inverted to try
// to make the default bitfield pattern all-zeroes.
bool ImpreciseLifetime : 1;
Expr *BaseIvarExp;
/// Used by struct-path-aware TBAA.
QualType TBAABaseType;
/// Offset relative to the base type.
uint64_t TBAAOffset;
/// TBAAInfo - TBAA information to attach to dereferences of this LValue.
llvm::MDNode *TBAAInfo;
private:
void Initialize(QualType Type, Qualifiers Quals,
CharUnits Alignment,
llvm::MDNode *TBAAInfo = 0) {
this->Type = Type;
this->Quals = Quals;
this->Alignment = Alignment.getQuantity();
assert(this->Alignment == Alignment.getQuantity() &&
"Alignment exceeds allowed max!");
// Initialize Objective-C flags.
this->Ivar = this->ObjIsArray = this->NonGC = this->GlobalObjCRef = false;
this->ImpreciseLifetime = false;
this->ThreadLocalRef = false;
this->BaseIvarExp = 0;
// Initialize fields for TBAA.
this->TBAABaseType = Type;
this->TBAAOffset = 0;
this->TBAAInfo = TBAAInfo;
}
public:
bool isSimple() const { return LVType == Simple; }
bool isVectorElt() const { return LVType == VectorElt; }
bool isBitField() const { return LVType == BitField; }
bool isExtVectorElt() const { return LVType == ExtVectorElt; }
bool isVolatileQualified() const { return Quals.hasVolatile(); }
bool isRestrictQualified() const { return Quals.hasRestrict(); }
unsigned getVRQualifiers() const {
return Quals.getCVRQualifiers() & ~Qualifiers::Const;
}
QualType getType() const { return Type; }
Qualifiers::ObjCLifetime getObjCLifetime() const {
return Quals.getObjCLifetime();
}
bool isObjCIvar() const { return Ivar; }
void setObjCIvar(bool Value) { Ivar = Value; }
bool isObjCArray() const { return ObjIsArray; }
void setObjCArray(bool Value) { ObjIsArray = Value; }
bool isNonGC () const { return NonGC; }
void setNonGC(bool Value) { NonGC = Value; }
bool isGlobalObjCRef() const { return GlobalObjCRef; }
void setGlobalObjCRef(bool Value) { GlobalObjCRef = Value; }
bool isThreadLocalRef() const { return ThreadLocalRef; }
void setThreadLocalRef(bool Value) { ThreadLocalRef = Value;}
ARCPreciseLifetime_t isARCPreciseLifetime() const {
return ARCPreciseLifetime_t(!ImpreciseLifetime);
}
void setARCPreciseLifetime(ARCPreciseLifetime_t value) {
ImpreciseLifetime = (value == ARCImpreciseLifetime);
}
bool isObjCWeak() const {
return Quals.getObjCGCAttr() == Qualifiers::Weak;
}
bool isObjCStrong() const {
return Quals.getObjCGCAttr() == Qualifiers::Strong;
}
bool isVolatile() const {
return Quals.hasVolatile();
}
Expr *getBaseIvarExp() const { return BaseIvarExp; }
void setBaseIvarExp(Expr *V) { BaseIvarExp = V; }
QualType getTBAABaseType() const { return TBAABaseType; }
void setTBAABaseType(QualType T) { TBAABaseType = T; }
uint64_t getTBAAOffset() const { return TBAAOffset; }
void setTBAAOffset(uint64_t O) { TBAAOffset = O; }
llvm::MDNode *getTBAAInfo() const { return TBAAInfo; }
void setTBAAInfo(llvm::MDNode *N) { TBAAInfo = N; }
const Qualifiers &getQuals() const { return Quals; }
Qualifiers &getQuals() { return Quals; }
unsigned getAddressSpace() const { return Quals.getAddressSpace(); }
CharUnits getAlignment() const { return CharUnits::fromQuantity(Alignment); }
void setAlignment(CharUnits A) { Alignment = A.getQuantity(); }
// simple lvalue
llvm::Value *getAddress() const { assert(isSimple()); return V; }
void setAddress(llvm::Value *address) {
assert(isSimple());
V = address;
}
// vector elt lvalue
llvm::Value *getVectorAddr() const { assert(isVectorElt()); return V; }
llvm::Value *getVectorIdx() const { assert(isVectorElt()); return VectorIdx; }
// extended vector elements.
llvm::Value *getExtVectorAddr() const { assert(isExtVectorElt()); return V; }
llvm::Constant *getExtVectorElts() const {
assert(isExtVectorElt());
return VectorElts;
}
// bitfield lvalue
llvm::Value *getBitFieldAddr() const {
assert(isBitField());
return V;
}
const CGBitFieldInfo &getBitFieldInfo() const {
assert(isBitField());
return *BitFieldInfo;
}
static LValue MakeAddr(llvm::Value *address, QualType type,
CharUnits alignment, ASTContext &Context,
llvm::MDNode *TBAAInfo = 0) {
Qualifiers qs = type.getQualifiers();
qs.setObjCGCAttr(Context.getObjCGCAttrKind(type));
LValue R;
R.LVType = Simple;
R.V = address;
R.Initialize(type, qs, alignment, TBAAInfo);
return R;
}
static LValue MakeVectorElt(llvm::Value *Vec, llvm::Value *Idx,
QualType type, CharUnits Alignment) {
LValue R;
R.LVType = VectorElt;
R.V = Vec;
R.VectorIdx = Idx;
R.Initialize(type, type.getQualifiers(), Alignment);
return R;
}
static LValue MakeExtVectorElt(llvm::Value *Vec, llvm::Constant *Elts,
QualType type, CharUnits Alignment) {
LValue R;
R.LVType = ExtVectorElt;
R.V = Vec;
R.VectorElts = Elts;
R.Initialize(type, type.getQualifiers(), Alignment);
return R;
}
/// \brief Create a new object to represent a bit-field access.
///
/// \param Addr - The base address of the bit-field sequence this
/// bit-field refers to.
/// \param Info - The information describing how to perform the bit-field
/// access.
static LValue MakeBitfield(llvm::Value *Addr,
const CGBitFieldInfo &Info,
QualType type, CharUnits Alignment) {
LValue R;
R.LVType = BitField;
R.V = Addr;
R.BitFieldInfo = &Info;
R.Initialize(type, type.getQualifiers(), Alignment);
return R;
}
RValue asAggregateRValue() const {
// FIMXE: Alignment
return RValue::getAggregate(getAddress(), isVolatileQualified());
}
};
/// An aggregate value slot.
class AggValueSlot {
/// The address.
llvm::Value *Addr;
// Qualifiers
Qualifiers Quals;
unsigned short Alignment;
/// DestructedFlag - This is set to true if some external code is
/// responsible for setting up a destructor for the slot. Otherwise
/// the code which constructs it should push the appropriate cleanup.
bool DestructedFlag : 1;
/// ObjCGCFlag - This is set to true if writing to the memory in the
/// slot might require calling an appropriate Objective-C GC
/// barrier. The exact interaction here is unnecessarily mysterious.
bool ObjCGCFlag : 1;
/// ZeroedFlag - This is set to true if the memory in the slot is
/// known to be zero before the assignment into it. This means that
/// zero fields don't need to be set.
bool ZeroedFlag : 1;
/// AliasedFlag - This is set to true if the slot might be aliased
/// and it's not undefined behavior to access it through such an
/// alias. Note that it's always undefined behavior to access a C++
/// object that's under construction through an alias derived from
/// outside the construction process.
///
/// This flag controls whether calls that produce the aggregate
/// value may be evaluated directly into the slot, or whether they
/// must be evaluated into an unaliased temporary and then memcpy'ed
/// over. Since it's invalid in general to memcpy a non-POD C++
/// object, it's important that this flag never be set when
/// evaluating an expression which constructs such an object.
bool AliasedFlag : 1;
/// ValueOfAtomicFlag - This is set to true if the slot is the value
/// subobject of an object the size of an _Atomic(T). The specific
/// guarantees this makes are:
/// - the address is guaranteed to be a getelementptr into the
/// padding struct and
/// - it is okay to store something the width of an _Atomic(T)
/// into the address.
/// Tracking this allows us to avoid some obviously unnecessary
/// memcpys.
bool ValueOfAtomicFlag : 1;
public:
enum IsAliased_t { IsNotAliased, IsAliased };
enum IsDestructed_t { IsNotDestructed, IsDestructed };
enum IsZeroed_t { IsNotZeroed, IsZeroed };
enum NeedsGCBarriers_t { DoesNotNeedGCBarriers, NeedsGCBarriers };
enum IsValueOfAtomic_t { IsNotValueOfAtomic, IsValueOfAtomic };
/// ignored - Returns an aggregate value slot indicating that the
/// aggregate value is being ignored.
static AggValueSlot ignored() {
return forAddr(0, CharUnits(), Qualifiers(), IsNotDestructed,
DoesNotNeedGCBarriers, IsNotAliased);
}
/// forAddr - Make a slot for an aggregate value.
///
/// \param quals - The qualifiers that dictate how the slot should
/// be initialied. Only 'volatile' and the Objective-C lifetime
/// qualifiers matter.
///
/// \param isDestructed - true if something else is responsible
/// for calling destructors on this object
/// \param needsGC - true if the slot is potentially located
/// somewhere that ObjC GC calls should be emitted for
static AggValueSlot forAddr(llvm::Value *addr, CharUnits align,
Qualifiers quals,
IsDestructed_t isDestructed,
NeedsGCBarriers_t needsGC,
IsAliased_t isAliased,
IsZeroed_t isZeroed = IsNotZeroed,
IsValueOfAtomic_t isValueOfAtomic
= IsNotValueOfAtomic) {
AggValueSlot AV;
AV.Addr = addr;
AV.Alignment = align.getQuantity();
AV.Quals = quals;
AV.DestructedFlag = isDestructed;
AV.ObjCGCFlag = needsGC;
AV.ZeroedFlag = isZeroed;
AV.AliasedFlag = isAliased;
AV.ValueOfAtomicFlag = isValueOfAtomic;
return AV;
}
static AggValueSlot forLValue(const LValue &LV,
IsDestructed_t isDestructed,
NeedsGCBarriers_t needsGC,
IsAliased_t isAliased,
IsZeroed_t isZeroed = IsNotZeroed,
IsValueOfAtomic_t isValueOfAtomic
= IsNotValueOfAtomic) {
return forAddr(LV.getAddress(), LV.getAlignment(),
LV.getQuals(), isDestructed, needsGC, isAliased, isZeroed,
isValueOfAtomic);
}
IsDestructed_t isExternallyDestructed() const {
return IsDestructed_t(DestructedFlag);
}
void setExternallyDestructed(bool destructed = true) {
DestructedFlag = destructed;
}
Qualifiers getQualifiers() const { return Quals; }
bool isVolatile() const {
return Quals.hasVolatile();
}
void setVolatile(bool flag) {
Quals.setVolatile(flag);
}
Qualifiers::ObjCLifetime getObjCLifetime() const {
return Quals.getObjCLifetime();
}
NeedsGCBarriers_t requiresGCollection() const {
return NeedsGCBarriers_t(ObjCGCFlag);
}
llvm::Value *getAddr() const {
return Addr;
}
IsValueOfAtomic_t isValueOfAtomic() const {
return IsValueOfAtomic_t(ValueOfAtomicFlag);
}
llvm::Value *getPaddedAtomicAddr() const;
bool isIgnored() const {
return Addr == 0;
}
CharUnits getAlignment() const {
return CharUnits::fromQuantity(Alignment);
}
IsAliased_t isPotentiallyAliased() const {
return IsAliased_t(AliasedFlag);
}
// FIXME: Alignment?
RValue asRValue() const {
return RValue::getAggregate(getAddr(), isVolatile());
}
void setZeroed(bool V = true) { ZeroedFlag = V; }
IsZeroed_t isZeroed() const {
return IsZeroed_t(ZeroedFlag);
}
};
} // end namespace CodeGen
} // end namespace clang
#endif
| dbrumley/recfi | llvm-3.3/tools/clang/lib/CodeGen/CGValue.h | C | mit | 16,268 |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
namespace Lucene.Net.Support
{
internal class SmallObject
{
public int i = 0;
public SmallObject(int i)
{
this.i = i;
}
}
}
| joshball/Lucene.In.Action.NET | vendor/lucene.net/test/core/Support/SmallObject.cs | C# | mit | 995 |
### Theme assets
# helps create a theme asset
def create_plain_text_asset(name, type)
asset = FactoryGirl.build(:theme_asset, {
:site => @site,
:plain_text_name => name,
:plain_text => 'Lorem ipsum',
:plain_text_type => type,
:performing_plain_text => true
})
# asset.should be_valid
asset.save!
end
# creates various theme assets
Given /^a javascript asset named "([^"]*)"$/ do |name|
@asset = create_plain_text_asset(name, 'javascript')
end
Given /^a stylesheet asset named "([^"]*)"$/ do |name|
@asset = create_plain_text_asset(name, 'stylesheet')
end
Given /^I have an image theme asset named "([^"]*)"$/ do |name|
@asset = FactoryGirl.create(:theme_asset, :site => @site, :source => File.open(Rails.root.join('spec', 'fixtures', 'assets', '5k.png')))
@asset.source_filename = name
@asset.save!
end
# other stuff
Then /^I should see "([^"]*)" as theme asset code$/ do |code|
find(:css, "#theme_asset_plain_text").text.should == code
end
Then /^I should see a delete image button$/ do
page.has_css?("ul.theme-assets li .more a.remove").should be_true
end
Then /^I should not see a delete image button$/ do
page.has_css?("ul.theme-assets li .more a.remove").should be_false
end
| travis-repos/engine | features/step_definitions/theme_asset_steps.rb | Ruby | mit | 1,235 |
//******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//******************************************************************************
// WindowsGlobalizationDateTimeFormatting.h
// Generated from winmd2objc
#pragma once
#include <UWP/interopBase.h>
@class WGDDateTimeFormatter;
@protocol WGDIDateTimeFormatter
, WGDIDateTimeFormatterFactory, WGDIDateTimeFormatterStatics, WGDIDateTimeFormatter2;
// Windows.Globalization.DateTimeFormatting.YearFormat
enum _WGDYearFormat {
WGDYearFormatNone = 0,
WGDYearFormatDefault = 1,
WGDYearFormatAbbreviated = 2,
WGDYearFormatFull = 3,
};
typedef unsigned WGDYearFormat;
// Windows.Globalization.DateTimeFormatting.MonthFormat
enum _WGDMonthFormat {
WGDMonthFormatNone = 0,
WGDMonthFormatDefault = 1,
WGDMonthFormatAbbreviated = 2,
WGDMonthFormatFull = 3,
WGDMonthFormatNumeric = 4,
};
typedef unsigned WGDMonthFormat;
// Windows.Globalization.DateTimeFormatting.DayOfWeekFormat
enum _WGDDayOfWeekFormat {
WGDDayOfWeekFormatNone = 0,
WGDDayOfWeekFormatDefault = 1,
WGDDayOfWeekFormatAbbreviated = 2,
WGDDayOfWeekFormatFull = 3,
};
typedef unsigned WGDDayOfWeekFormat;
// Windows.Globalization.DateTimeFormatting.DayFormat
enum _WGDDayFormat {
WGDDayFormatNone = 0,
WGDDayFormatDefault = 1,
};
typedef unsigned WGDDayFormat;
// Windows.Globalization.DateTimeFormatting.HourFormat
enum _WGDHourFormat {
WGDHourFormatNone = 0,
WGDHourFormatDefault = 1,
};
typedef unsigned WGDHourFormat;
// Windows.Globalization.DateTimeFormatting.MinuteFormat
enum _WGDMinuteFormat {
WGDMinuteFormatNone = 0,
WGDMinuteFormatDefault = 1,
};
typedef unsigned WGDMinuteFormat;
// Windows.Globalization.DateTimeFormatting.SecondFormat
enum _WGDSecondFormat {
WGDSecondFormatNone = 0,
WGDSecondFormatDefault = 1,
};
typedef unsigned WGDSecondFormat;
#include "WindowsFoundation.h"
#import <Foundation/Foundation.h>
// Windows.Globalization.DateTimeFormatting.DateTimeFormatter
#ifndef __WGDDateTimeFormatter_DEFINED__
#define __WGDDateTimeFormatter_DEFINED__
WINRT_EXPORT
@interface WGDDateTimeFormatter : RTObject
+ (WGDDateTimeFormatter*)makeDateTimeFormatter:(NSString*)formatTemplate ACTIVATOR;
+ (WGDDateTimeFormatter*)makeDateTimeFormatterLanguages:(NSString*)formatTemplate
languages:(id<NSFastEnumeration> /* NSString * */)languages ACTIVATOR;
+ (WGDDateTimeFormatter*)makeDateTimeFormatterContext:(NSString*)formatTemplate
languages:(id<NSFastEnumeration> /* NSString * */)languages
geographicRegion:(NSString*)geographicRegion
calendar:(NSString*)calendar
clock:(NSString*)clock ACTIVATOR;
+ (WGDDateTimeFormatter*)makeDateTimeFormatterDate:(WGDYearFormat)yearFormat
monthFormat:(WGDMonthFormat)monthFormat
dayFormat:(WGDDayFormat)dayFormat
dayOfWeekFormat:(WGDDayOfWeekFormat)dayOfWeekFormat ACTIVATOR;
+ (WGDDateTimeFormatter*)makeDateTimeFormatterTime:(WGDHourFormat)hourFormat
minuteFormat:(WGDMinuteFormat)minuteFormat
secondFormat:(WGDSecondFormat)secondFormat ACTIVATOR;
+ (WGDDateTimeFormatter*)makeDateTimeFormatterDateTimeLanguages:(WGDYearFormat)yearFormat
monthFormat:(WGDMonthFormat)monthFormat
dayFormat:(WGDDayFormat)dayFormat
dayOfWeekFormat:(WGDDayOfWeekFormat)dayOfWeekFormat
hourFormat:(WGDHourFormat)hourFormat
minuteFormat:(WGDMinuteFormat)minuteFormat
secondFormat:(WGDSecondFormat)secondFormat
languages:(id<NSFastEnumeration> /* NSString * */)languages ACTIVATOR;
+ (WGDDateTimeFormatter*)makeDateTimeFormatterDateTimeContext:(WGDYearFormat)yearFormat
monthFormat:(WGDMonthFormat)monthFormat
dayFormat:(WGDDayFormat)dayFormat
dayOfWeekFormat:(WGDDayOfWeekFormat)dayOfWeekFormat
hourFormat:(WGDHourFormat)hourFormat
minuteFormat:(WGDMinuteFormat)minuteFormat
secondFormat:(WGDSecondFormat)secondFormat
languages:(id<NSFastEnumeration> /* NSString * */)languages
geographicRegion:(NSString*)geographicRegion
calendar:(NSString*)calendar
clock:(NSString*)clock ACTIVATOR;
@property (retain) NSString* numeralSystem;
@property (readonly) NSString* clock;
@property (readonly) NSString* geographicRegion;
@property (readonly) WGDDayFormat includeDay;
@property (readonly) WGDDayOfWeekFormat includeDayOfWeek;
@property (readonly) WGDHourFormat includeHour;
@property (readonly) WGDMinuteFormat includeMinute;
@property (readonly) WGDMonthFormat includeMonth;
@property (readonly) WGDSecondFormat includeSecond;
@property (readonly) WGDYearFormat includeYear;
@property (readonly) NSArray* /* NSString * */ languages;
@property (readonly) NSString* calendar;
@property (readonly) NSArray* /* NSString * */ patterns;
@property (readonly) NSString* resolvedGeographicRegion;
@property (readonly) NSString* resolvedLanguage;
@property (readonly) NSString* Template;
+ (WGDDateTimeFormatter*)longDate;
+ (WGDDateTimeFormatter*)longTime;
+ (WGDDateTimeFormatter*)shortDate;
+ (WGDDateTimeFormatter*)shortTime;
- (NSString*)format:(WFDateTime*)value;
- (NSString*)formatUsingTimeZone:(WFDateTime*)datetime timeZoneId:(NSString*)timeZoneId;
@end
#endif // __WGDDateTimeFormatter_DEFINED__
| rajsesh-msft/WinObjC | include/Platform/Universal Windows/UWP/WindowsGlobalizationDateTimeFormatting.h | C | mit | 6,945 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using Azure.Core;
namespace Azure.ResourceManager.Network.Models
{
/// <summary> Common resource representation. </summary>
public partial class Resource
{
/// <summary> Initializes a new instance of Resource. </summary>
public Resource()
{
Tags = new ChangeTrackingDictionary<string, string>();
}
/// <summary> Initializes a new instance of Resource. </summary>
/// <param name="id"> Resource ID. </param>
/// <param name="name"> Resource name. </param>
/// <param name="type"> Resource type. </param>
/// <param name="location"> Resource location. </param>
/// <param name="tags"> Resource tags. </param>
internal Resource(string id, string name, string type, string location, IDictionary<string, string> tags)
{
Id = id;
Name = name;
Type = type;
Location = location;
Tags = tags;
}
/// <summary> Resource ID. </summary>
public string Id { get; set; }
/// <summary> Resource name. </summary>
public string Name { get; }
/// <summary> Resource type. </summary>
public string Type { get; }
/// <summary> Resource location. </summary>
public string Location { get; set; }
/// <summary> Resource tags. </summary>
public IDictionary<string, string> Tags { get; }
}
}
| ayeletshpigelman/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/Models/Resource.cs | C# | mit | 1,612 |
<!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_80) on Tue Feb 09 12:58:22 EST 2016 -->
<title>LaunchActivityConstantsList</title>
<meta name="date" content="2016-02-09">
<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="LaunchActivityConstantsList";
}
//-->
</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="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../com/qualcomm/ftccommon/FtcWifiChannelSelectorActivity.html" title="class in com.qualcomm.ftccommon"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../com/qualcomm/ftccommon/Restarter.html" title="interface in com.qualcomm.ftccommon"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?com/qualcomm/ftccommon/LaunchActivityConstantsList.html" target="_top">Frames</a></li>
<li><a href="LaunchActivityConstantsList.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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#methods_inherited_from_class_java.lang.Object">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.qualcomm.ftccommon</div>
<h2 title="Class LaunchActivityConstantsList" class="title">Class LaunchActivityConstantsList</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>com.qualcomm.ftccommon.LaunchActivityConstantsList</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="strong">LaunchActivityConstantsList</span>
extends java.lang.Object</pre>
<div class="block">List of RobotCore Robocol commands used by the FIRST apps</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><strong><a href="../../../com/qualcomm/ftccommon/LaunchActivityConstantsList.html#FTC_ROBOT_CONTROLLER_ACTIVITY_CONFIGURE_ROBOT">FTC_ROBOT_CONTROLLER_ACTIVITY_CONFIGURE_ROBOT</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../com/qualcomm/ftccommon/LaunchActivityConstantsList.html#VIEW_LOGS_ACTIVITY_FILENAME">VIEW_LOGS_ACTIVITY_FILENAME</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../com/qualcomm/ftccommon/LaunchActivityConstantsList.html#ZTE_WIFI_CHANNEL_EDITOR_PACKAGE">ZTE_WIFI_CHANNEL_EDITOR_PACKAGE</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../com/qualcomm/ftccommon/LaunchActivityConstantsList.html#LaunchActivityConstantsList()">LaunchActivityConstantsList</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="ZTE_WIFI_CHANNEL_EDITOR_PACKAGE">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>ZTE_WIFI_CHANNEL_EDITOR_PACKAGE</h4>
<pre>public static final java.lang.String ZTE_WIFI_CHANNEL_EDITOR_PACKAGE</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../constant-values.html#com.qualcomm.ftccommon.LaunchActivityConstantsList.ZTE_WIFI_CHANNEL_EDITOR_PACKAGE">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="VIEW_LOGS_ACTIVITY_FILENAME">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>VIEW_LOGS_ACTIVITY_FILENAME</h4>
<pre>public static final java.lang.String VIEW_LOGS_ACTIVITY_FILENAME</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../constant-values.html#com.qualcomm.ftccommon.LaunchActivityConstantsList.VIEW_LOGS_ACTIVITY_FILENAME">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="FTC_ROBOT_CONTROLLER_ACTIVITY_CONFIGURE_ROBOT">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>FTC_ROBOT_CONTROLLER_ACTIVITY_CONFIGURE_ROBOT</h4>
<pre>public static final int FTC_ROBOT_CONTROLLER_ACTIVITY_CONFIGURE_ROBOT</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../constant-values.html#com.qualcomm.ftccommon.LaunchActivityConstantsList.FTC_ROBOT_CONTROLLER_ACTIVITY_CONFIGURE_ROBOT">Constant Field Values</a></dd></dl>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="LaunchActivityConstantsList()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>LaunchActivityConstantsList</h4>
<pre>public LaunchActivityConstantsList()</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= 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="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../com/qualcomm/ftccommon/FtcWifiChannelSelectorActivity.html" title="class in com.qualcomm.ftccommon"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../com/qualcomm/ftccommon/Restarter.html" title="interface in com.qualcomm.ftccommon"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?com/qualcomm/ftccommon/LaunchActivityConstantsList.html" target="_top">Frames</a></li>
<li><a href="LaunchActivityConstantsList.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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#methods_inherited_from_class_java.lang.Object">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| TeamTorch5942/ftc_app | docs-FTC/javadoc/com/qualcomm/ftccommon/LaunchActivityConstantsList.html | HTML | mit | 10,556 |
package com.uuzuche.lib_zxing;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | DarkYeahs/QRCodeAndroid | lib-zxing/src/test/java/com/uuzuche/lib_zxing/ExampleUnitTest.java | Java | mit | 399 |
/*************************************************************
*
* MathJax/jax/output/HTML-CSS/fonts/STIX/General/BoldItalic/BoxDrawing.js
*
* Copyright (c) 2009-2016 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
MathJax.Hub.Insert(
MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['STIXGeneral-bold-italic'],
{
0x2500: [340,-267,708,-11,719], // BOX DRAWINGS LIGHT HORIZONTAL
0x2502: [910,303,696,312,385], // BOX DRAWINGS LIGHT VERTICAL
0x250C: [340,303,708,318,720], // BOX DRAWINGS LIGHT DOWN AND RIGHT
0x2510: [340,303,708,-11,390], // BOX DRAWINGS LIGHT DOWN AND LEFT
0x2514: [910,-267,708,318,720], // BOX DRAWINGS LIGHT UP AND RIGHT
0x2518: [910,-267,708,-11,390], // BOX DRAWINGS LIGHT UP AND LEFT
0x251C: [910,303,708,318,720], // BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x2524: [910,303,708,-11,390], // BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x252C: [340,303,708,-11,719], // BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x2534: [910,-267,708,-11,719], // BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x253C: [910,303,708,-11,719], // BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x2550: [433,-174,708,-11,719], // BOX DRAWINGS DOUBLE HORIZONTAL
0x2551: [910,303,708,225,484], // BOX DRAWINGS DOUBLE VERTICAL
0x2552: [433,303,708,318,720], // BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x2553: [340,303,708,225,720], // BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x2554: [433,303,708,225,719], // BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x2555: [433,303,708,-11,390], // BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x2556: [340,303,708,-11,483], // BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x2557: [433,303,708,-11,483], // BOX DRAWINGS DOUBLE DOWN AND LEFT
0x2558: [910,-174,708,318,720], // BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x2559: [910,-267,708,225,720], // BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x255A: [910,-174,708,225,719], // BOX DRAWINGS DOUBLE UP AND RIGHT
0x255B: [910,-174,708,-11,390], // BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x255C: [910,-267,708,-11,483], // BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x255D: [910,-174,708,-11,483], // BOX DRAWINGS DOUBLE UP AND LEFT
0x255E: [910,303,708,318,720], // BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x255F: [910,303,708,225,720], // BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x2560: [910,303,708,225,720], // BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x2561: [910,303,708,-11,390], // BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x2562: [910,303,708,-11,483], // BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x2563: [910,303,708,-11,483], // BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x2564: [433,303,708,-11,719], // BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x2565: [340,303,708,-11,719], // BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x2566: [433,303,708,-11,719], // BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x2567: [910,-174,708,-11,719], // BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x2568: [910,-267,708,-11,719], // BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x2569: [910,-174,708,-11,719], // BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x256A: [910,303,708,-11,719], // BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x256B: [910,303,708,-11,719], // BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x256C: [910,303,708,-11,719] // BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
}
);
MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir + "/General/BoldItalic/BoxDrawing.js");
| masterfish2015/my_project | 半导体物理/js/mathjax/unpacked/jax/output/HTML-CSS/fonts/STIX/General/BoldItalic/BoxDrawing.js | JavaScript | mit | 4,295 |
FROM node:argon
# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install
# Bundle app source
COPY laravel-echo-server.json /usr/src/app/laravel-echo-server.json
EXPOSE 3000
CMD [ "npm", "start" ] | NewbMiao/laradock | laravel-echo-server/Dockerfile | Dockerfile | mit | 291 |
// This file is part of the uSTL library, an STL implementation.
//
// Copyright (c) 2005-2009 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.
#ifndef UPREDALGO_H_2CB058AE0807A01A2F6A51BA5D5820A5
#define UPREDALGO_H_2CB058AE0807A01A2F6A51BA5D5820A5
namespace ustl {
/// Copy_if copies elements from the range [first, last) to the range
/// [result, result + (last - first)) if pred(*i) returns true.
/// \ingroup MutatingAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename InputIterator, typename OutputIterator, typename Predicate>
inline OutputIterator copy_if (InputIterator first, InputIterator last, OutputIterator result, Predicate pred)
{
for (; first != last; ++first) {
if (pred(*first)) {
*result = *first;
++ result;
}
}
return (result);
}
/// Returns the first iterator i in the range [first, last) such that
/// pred(*i) is true. Returns last if no such iterator exists.
/// \ingroup SearchingAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename InputIterator, typename Predicate>
inline InputIterator find_if (InputIterator first, InputIterator last, Predicate pred)
{
while (first != last && !pred (*first))
++ first;
return (first);
}
/// Returns the first iterator such that p(*i, *(i + 1)) == true.
/// \ingroup SearchingAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename ForwardIterator, typename BinaryPredicate>
inline ForwardIterator adjacent_find (ForwardIterator first, ForwardIterator last, BinaryPredicate p)
{
if (first != last)
for (ForwardIterator prev = first; ++first != last; ++ prev)
if (p (*prev, *first))
return (prev);
return (last);
}
/// Returns the pointer to the first pair of unequal elements.
/// \ingroup SearchingAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename InputIterator, typename BinaryPredicate>
inline pair<InputIterator,InputIterator>
mismatch (InputIterator first1, InputIterator last1, InputIterator first2, BinaryPredicate comp)
{
while (first1 != last1 && comp(*first1, *first2))
++ first1, ++ first2;
return (make_pair (first1, first2));
}
/// Returns true if two ranges are equal.
/// This is an extension, present in uSTL and SGI STL.
/// \ingroup ConditionAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename InputIterator, typename BinaryPredicate>
inline bool equal (InputIterator first1, InputIterator last1, InputIterator first2, BinaryPredicate comp)
{
return (mismatch (first1, last1, first2, comp).first == last1);
}
/// Count_if finds the number of elements in [first, last) that satisfy the
/// predicate pred. More precisely, the first version of count_if returns the
/// number of iterators i in [first, last) such that pred(*i) is true.
/// \ingroup ConditionAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename InputIterator, typename Predicate>
inline size_t count_if (InputIterator first, InputIterator last, Predicate pred)
{
size_t total = 0;
for (; first != last; ++first)
if (pred (*first))
++ total;
return (total);
}
/// Replace_if replaces every element in the range [first, last) for which
/// pred returns true with new_value. That is: for every iterator i, if
/// pred(*i) is true then it performs the assignment *i = new_value.
/// \ingroup MutatingAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename ForwardIterator, typename Predicate, typename T>
inline void replace_if (ForwardIterator first, ForwardIterator last, Predicate pred, const T& new_value)
{
for (; first != last; ++first)
if (pred (*first))
*first = new_value;
}
/// Replace_copy_if copies elements from the range [first, last) to the range
/// [result, result + (last-first)), except that any element for which pred is
/// true is not copied; new_value is copied instead. More precisely, for every
/// integer n such that 0 <= n < last-first, replace_copy_if performs the
/// assignment *(result+n) = new_value if pred(*(first+n)),
/// and *(result+n) = *(first+n) otherwise.
/// \ingroup MutatingAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename InputIterator, typename OutputIterator, typename Predicate, typename T>
inline OutputIterator replace_copy_if (InputIterator first, InputIterator last, OutputIterator result, Predicate pred, const T& new_value)
{
for (; first != last; ++result, ++first)
*result = pred(*first) ? new_value : *first;
}
/// Remove_copy_if copies elements from the range [first, last) to a range
/// beginning at result, except that elements for which pred is true are not
/// copied. The return value is the end of the resulting range. This operation
/// is stable, meaning that the relative order of the elements that are copied
/// is the same as in the range [first, last).
/// \ingroup MutatingAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename InputIterator, typename OutputIterator, typename Predicate>
inline OutputIterator remove_copy_if (InputIterator first, InputIterator last, OutputIterator result, Predicate pred)
{
for (; first != last; ++first)
if (pred (*first))
*result++ = *first;
return (result);
}
/// Remove_if removes from the range [first, last) every element x such that
/// pred(x) is true. That is, remove_if returns an iterator new_last such that
/// the range [first, new_last) contains no elements for which pred is true.
/// The iterators in the range [new_last, last) are all still dereferenceable,
/// but the elements that they point to are unspecified. Remove_if is stable,
/// meaning that the relative order of elements that are not removed is
/// unchanged.
/// \ingroup MutatingAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename ForwardIterator, typename Predicate>
inline ForwardIterator remove_if (ForwardIterator first, ForwardIterator last, Predicate pred)
{
return (remove_copy_if (first, last, first, pred));
}
/// The reason there are two different versions of unique_copy is that there
/// are two different definitions of what it means for a consecutive group of
/// elements to be duplicates. In the first version, the test is simple
/// equality: the elements in a range [f, l) are duplicates if, for every
/// iterator i in the range, either i == f or else *i == *(i-1). In the second,
/// the test is an arbitrary Binary Predicate binary_pred: the elements in
/// [f, l) are duplicates if, for every iterator i in the range, either
/// i == f or else binary_pred(*i, *(i-1)) is true.
/// \ingroup MutatingAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename InputIterator, typename OutputIterator, typename BinaryPredicate>
OutputIterator unique_copy (InputIterator first, InputIterator last, OutputIterator result, BinaryPredicate binary_pred)
{
if (first != last) {
*result = *first;
while (++first != last)
if (!binary_pred (*first, *result))
*++result = *first;
++ result;
}
return (result);
}
/// Every time a consecutive group of duplicate elements appears in the range
/// [first, last), the algorithm unique removes all but the first element.
/// That is, unique returns an iterator new_last such that the range [first,
/// new_last) contains no two consecutive elements that are duplicates.
/// The iterators in the range [new_last, last) are all still dereferenceable,
/// but the elements that they point to are unspecified. Unique is stable,
/// meaning that the relative order of elements that are not removed is
/// unchanged.
/// \ingroup MutatingAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename ForwardIterator, typename BinaryPredicate>
inline ForwardIterator unique (ForwardIterator first, ForwardIterator last, BinaryPredicate binary_pred)
{
return (unique_copy (first, last, first, binary_pred));
}
/// Returns the furthermost iterator i in [first, last) such that,
/// for every iterator j in [first, i), comp(*j, value) is true.
/// Assumes the range is sorted.
/// \ingroup SearchingAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename ForwardIterator, typename T, typename StrictWeakOrdering>
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& value, StrictWeakOrdering comp)
{
ForwardIterator mid;
while (first != last) {
mid = advance (first, distance (first,last) / 2);
if (comp (*mid, value))
first = mid + 1;
else
last = mid;
}
return (first);
}
/// Performs a binary search inside the sorted range.
/// \ingroup SearchingAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename ForwardIterator, typename T, typename StrictWeakOrdering>
inline bool binary_search (ForwardIterator first, ForwardIterator last, const T& value, StrictWeakOrdering comp)
{
ForwardIterator found = lower_bound (first, last, value, comp);
return (found != last && !comp(*found, value));
}
/// Returns the furthermost iterator i in [first,last) such that for
/// every iterator j in [first,i), comp(value,*j) is false.
/// \ingroup SearchingAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename ForwardIterator, typename T, typename StrictWeakOrdering>
ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last, const T& value, StrictWeakOrdering comp)
{
ForwardIterator mid;
while (first != last) {
mid = advance (first, distance (first,last) / 2);
if (comp (value, *mid))
last = mid;
else
first = mid + 1;
}
return (last);
}
/// Returns pair<lower_bound,upper_bound>
/// \ingroup SearchingAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename ForwardIterator, typename T, typename StrictWeakOrdering>
inline pair<ForwardIterator,ForwardIterator> equal_range (ForwardIterator first, ForwardIterator last, const T& value, StrictWeakOrdering comp)
{
pair<ForwardIterator,ForwardIterator> rv;
rv.second = rv.first = lower_bound (first, last, value, comp);
while (rv.second != last && !comp(value, *(rv.second)))
++ rv.second;
return (rv);
}
/// \brief Puts \p nth element into its sorted position.
/// In this implementation, the entire array is sorted. The performance difference is
/// so small and the function use is so rare, there is no need to have code for it.
/// \ingroup SortingAlgorithms
/// \ingroup SearchingAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename RandomAccessIterator, typename Compare>
inline void nth_element (RandomAccessIterator first, RandomAccessIterator, RandomAccessIterator last, Compare comp)
{
sort (first, last, comp);
}
/// \brief Searches for the first subsequence [first2,last2) in [first1,last1)
/// \ingroup SearchingAlgorithms
/// \ingroup PredicateAlgorithms
template <typename ForwardIterator1, typename ForwardIterator2, typename BinaryPredicate>
ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate comp)
{
const ForwardIterator1 slast = last1 - distance(first2, last2) + 1;
for (; first1 < slast; ++first1) {
ForwardIterator2 i = first2;
ForwardIterator1 j = first1;
for (; i != last2 && comp(*j, *i); ++i, ++j) ;
if (i == last2)
return (first1);
}
return (last1);
}
/// \brief Searches for the last subsequence [first2,last2) in [first1,last1)
/// \ingroup SearchingAlgorithms
/// \ingroup PredicateAlgorithms
template <typename ForwardIterator1, typename ForwardIterator2, typename BinaryPredicate>
ForwardIterator1 find_end (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate comp)
{
ForwardIterator1 s = last1 - distance(first2, last2);
for (; first1 < s; --s) {
ForwardIterator2 i = first2, j = s;
for (; i != last2 && comp(*j, *i); ++i, ++j) ;
if (i == last2)
return (s);
}
return (last1);
}
/// \brief Searches for the first occurence of \p count \p values in [first, last)
/// \ingroup SearchingAlgorithms
/// \ingroup PredicateAlgorithms
template <typename Iterator, typename T, typename BinaryPredicate>
Iterator search_n (Iterator first, Iterator last, size_t count, const T& value, BinaryPredicate comp)
{
size_t n = 0;
for (; first != last; ++first) {
if (!comp (*first, value))
n = 0;
else if (++n == count)
return (first - --n);
}
return (last);
}
/// \brief Searches [first1,last1) for the first occurrence of an element from [first2,last2)
/// \ingroup SearchingAlgorithms
/// \ingroup PredicateAlgorithms
template <typename InputIterator, typename ForwardIterator, typename BinaryPredicate>
InputIterator find_first_of (InputIterator first1, InputIterator last1, ForwardIterator first2, ForwardIterator last2, BinaryPredicate comp)
{
for (; first1 != last1; ++first1)
for (ForwardIterator i = first2; i != last2; ++i)
if (comp (*first1, *i))
return (first1);
return (first1);
}
/// \brief Returns true if [first2,last2) is a subset of [first1,last1)
/// \ingroup ConditionAlgorithms
/// \ingroup SetAlgorithms
/// \ingroup PredicateAlgorithms
template <typename InputIterator1, typename InputIterator2, typename StrictWeakOrdering>
bool includes (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, StrictWeakOrdering comp)
{
for (; (first1 != last1) & (first2 != last2); ++first1) {
if (comp (*first2, *first1))
return (false);
first2 += !comp (*first1, *first2);
}
return (first2 == last2);
}
/// \brief Merges [first1,last1) with [first2,last2)
///
/// Result will contain every element that is in either set. If duplicate
/// elements are present, max(n,m) is placed in the result.
///
/// \ingroup SetAlgorithms
/// \ingroup PredicateAlgorithms
template <typename InputIterator1, typename InputIterator2, typename OutputIterator, typename StrictWeakOrdering>
OutputIterator set_union (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, StrictWeakOrdering comp)
{
for (; (first1 != last1) & (first2 != last2); ++result) {
if (comp (*first2, *first1))
*result = *first2++;
else {
first2 += !comp (*first1, *first2);
*result = *first1++;
}
}
return (copy (first2, last2, copy (first1, last1, result)));
}
/// \brief Creates a set containing elements shared by the given ranges.
/// \ingroup SetAlgorithms
/// \ingroup PredicateAlgorithms
template <typename InputIterator1, typename InputIterator2, typename OutputIterator, typename StrictWeakOrdering>
OutputIterator set_intersection (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, StrictWeakOrdering comp)
{
while ((first1 != last1) & (first2 != last2)) {
bool b1ge2 = !comp (*first1, *first2), b2ge1 = !comp (*first2, *first1);
if (b1ge2 & b2ge1)
*result++ = *first1;
first1 += b2ge1;
first2 += b1ge2;
}
return (result);
}
/// \brief Removes from [first1,last1) elements present in [first2,last2)
/// \ingroup SetAlgorithms
/// \ingroup PredicateAlgorithms
template <typename InputIterator1, typename InputIterator2, typename OutputIterator, typename StrictWeakOrdering>
OutputIterator set_difference (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, StrictWeakOrdering comp)
{
while ((first1 != last1) & (first2 != last2)) {
bool b1ge2 = !comp (*first1, *first2), b2ge1 = !comp (*first2, *first1);
if (!b1ge2)
*result++ = *first1;
first1 += b2ge1;
first2 += b1ge2;
}
return (copy (first1, last1, result));
}
/// \brief Performs union of sets A-B and B-A.
/// \ingroup SetAlgorithms
/// \ingroup PredicateAlgorithms
template <typename InputIterator1, typename InputIterator2, typename OutputIterator, typename StrictWeakOrdering>
OutputIterator set_symmetric_difference (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, StrictWeakOrdering comp)
{
while ((first1 != last1) & (first2 != last2)) {
bool b1l2 = comp (*first1, *first2), b2l1 = comp (*first2, *first1);
if (b1l2)
*result++ = *first1;
else if (b2l1)
*result++ = *first2;
first1 += !b2l1;
first2 += !b1l2;
}
return (copy (first2, last2, copy (first1, last1, result)));
}
/// \brief Returns true if the given range is sorted.
/// \ingroup ConditionAlgorithms
/// \ingroup PredicateAlgorithms
template <typename ForwardIterator, typename StrictWeakOrdering>
bool is_sorted (ForwardIterator first, ForwardIterator last, StrictWeakOrdering comp)
{
for (ForwardIterator i = first; ++i < last; ++first)
if (comp (*i, *first))
return (false);
return (true);
}
/// \brief Compares two given containers like strcmp compares strings.
/// \ingroup ConditionAlgorithms
/// \ingroup PredicateAlgorithms
template <typename InputIterator1, typename InputIterator2, typename BinaryPredicate>
bool lexicographical_compare (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, BinaryPredicate comp)
{
for (; (first1 != last1) & (first2 != last2); ++first1, ++first2) {
if (comp (*first1, *first2))
return (true);
if (comp (*first2, *first1))
return (false);
}
return ((first1 == last1) & (first2 != last2));
}
/// \brief Creates the next lexicographical permutation of [first,last).
/// Returns false if no further permutations can be created.
/// \ingroup GeneratorAlgorithms
/// \ingroup PredicateAlgorithms
template <typename BidirectionalIterator, typename StrictWeakOrdering>
bool next_permutation (BidirectionalIterator first, BidirectionalIterator last, StrictWeakOrdering comp)
{
if (distance (first, last) < 2)
return (false);
BidirectionalIterator i = last;
for (--i; i != first; ) {
--i;
if (comp (i[0], i[1])) {
BidirectionalIterator j = last;
while (!comp (*i, *--j)) ;
iter_swap (i, j);
reverse (i + 1, last);
return (true);
}
}
reverse (first, last);
return (false);
}
/// \brief Creates the previous lexicographical permutation of [first,last).
/// Returns false if no further permutations can be created.
/// \ingroup GeneratorAlgorithms
/// \ingroup PredicateAlgorithms
template <typename BidirectionalIterator, typename StrictWeakOrdering>
bool prev_permutation (BidirectionalIterator first, BidirectionalIterator last, StrictWeakOrdering comp)
{
if (distance (first, last) < 2)
return (false);
BidirectionalIterator i = last;
for (--i; i != first; ) {
--i;
if (comp(i[1], i[0])) {
BidirectionalIterator j = last;
while (!comp (*--j, *i)) ;
iter_swap (i, j);
reverse (i + 1, last);
return (true);
}
}
reverse (first, last);
return (false);
}
/// \brief Returns iterator to the max element in [first,last)
/// \ingroup SearchingAlgorithms
/// \ingroup PredicateAlgorithms
template <typename ForwardIterator, typename BinaryPredicate>
inline ForwardIterator max_element (ForwardIterator first, ForwardIterator last, BinaryPredicate comp)
{
ForwardIterator result = first;
for (; first != last; ++first)
if (comp (*result, *first))
result = first;
return (result);
}
/// \brief Returns iterator to the min element in [first,last)
/// \ingroup SearchingAlgorithms
/// \ingroup PredicateAlgorithms
template <typename ForwardIterator, typename BinaryPredicate>
inline ForwardIterator min_element (ForwardIterator first, ForwardIterator last, BinaryPredicate comp)
{
ForwardIterator result = first;
for (; first != last; ++first)
if (comp (*first, *result))
result = first;
return (result);
}
/// \brief Makes [first,middle) a part of the sorted array.
/// Contents of [middle,last) is undefined. This implementation just calls stable_sort.
/// \ingroup SortingAlgorithms
/// \ingroup PredicateAlgorithms
template <typename RandomAccessIterator, typename StrictWeakOrdering>
inline void partial_sort (RandomAccessIterator first, RandomAccessIterator, RandomAccessIterator last, StrictWeakOrdering comp)
{
stable_sort (first, last, comp);
}
/// \brief Like partial_sort, but outputs to [result_first,result_last)
/// \ingroup SortingAlgorithms
/// \ingroup PredicateAlgorithms
template <typename InputIterator, typename RandomAccessIterator, typename StrictWeakOrdering>
RandomAccessIterator partial_sort_copy (InputIterator first, InputIterator last, RandomAccessIterator result_first, RandomAccessIterator result_last, StrictWeakOrdering comp)
{
RandomAccessIterator rend = result_first;
for (; first != last; ++first) {
RandomAccessIterator i = result_first;
for (; i != rend && comp (*i, *first); ++i) ;
if (i == result_last)
continue;
rend += (rend < result_last);
copy_backward (i, rend - 1, rend);
*i = *first;
}
return (rend);
}
/// \brief Like partition, but preserves equal element order.
/// \ingroup SortingAlgorithms
/// \ingroup PredicateAlgorithms
template <typename ForwardIterator, typename Predicate>
ForwardIterator stable_partition (ForwardIterator first, ForwardIterator last, Predicate pred)
{
if (first == last)
return (first);
ForwardIterator l, r, m = advance (first, distance (first, last) / 2);
if (first == m)
return (pred(*first) ? last : first);
l = stable_partition (first, m, pred);
r = stable_partition (m, last, pred);
rotate (l, m, r);
return (advance (l, distance (m, r)));
}
/// \brief Splits [first,last) in two by \p pred.
///
/// Creates two ranges [first,middle) and [middle,last), where every element
/// in the former is less than every element in the latter.
/// The return value is middle.
///
/// \ingroup SortingAlgorithms
/// \ingroup PredicateAlgorithms
template <typename ForwardIterator, typename Predicate>
inline ForwardIterator partition (ForwardIterator first, ForwardIterator last, Predicate pred)
{
return (stable_partition (first, last, pred));
}
} // namespace ustl
#endif
| Arty89/avrstl | upredalgo.h | C | mit | 22,015 |
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, brackets, window, $, Mustache */
define(function (require, exports, module) {
"use strict";
// Brackets modules
var ProjectManager = brackets.getModule("project/ProjectManager"),
SidebarView = brackets.getModule("project/SidebarView"),
PreferencesManager = brackets.getModule("preferences/PreferencesManager"),
Commands = brackets.getModule("command/Commands"),
CommandManager = brackets.getModule("command/CommandManager"),
KeyBindingManager = brackets.getModule("command/KeyBindingManager"),
Menus = brackets.getModule("command/Menus"),
MainViewManager = brackets.getModule("view/MainViewManager"),
ExtensionUtils = brackets.getModule("utils/ExtensionUtils"),
FileSystem = brackets.getModule("filesystem/FileSystem"),
AppInit = brackets.getModule("utils/AppInit"),
KeyEvent = brackets.getModule("utils/KeyEvent"),
FileUtils = brackets.getModule("file/FileUtils"),
PopUpManager = brackets.getModule("widgets/PopUpManager"),
Strings = brackets.getModule("strings"),
ProjectsMenuTemplate = require("text!htmlContent/projects-menu.html");
var KeyboardPrefs = JSON.parse(require("text!keyboard.json"));
/** @const {string} Recent Projects commands ID */
var TOGGLE_DROPDOWN = "recentProjects.toggle";
/** @const {number} Maximum number of displayed recent projects */
var MAX_PROJECTS = 20;
/** @type {$.Element} jQuery elements used for the dropdown menu */
var $dropdownItem,
$dropdown,
$links;
/**
* Get the stored list of recent projects, fixing up paths as appropriate.
* Warning: unlike most paths in Brackets, these lack a trailing "/"
*/
function getRecentProjects() {
var recentProjects = PreferencesManager.getViewState("recentProjects") || [],
i;
for (i = 0; i < recentProjects.length; i++) {
// We have to canonicalize & then de-canonicalize the path here, since our pref format uses no trailing "/"
recentProjects[i] = FileUtils.stripTrailingSlash(ProjectManager.updateWelcomeProjectPath(recentProjects[i] + "/"));
}
return recentProjects;
}
/**
* Add a project to the stored list of recent projects, up to MAX_PROJECTS.
*/
function add() {
var root = FileUtils.stripTrailingSlash(ProjectManager.getProjectRoot().fullPath),
recentProjects = getRecentProjects(),
index = recentProjects.indexOf(root);
if (index !== -1) {
recentProjects.splice(index, 1);
}
recentProjects.unshift(root);
if (recentProjects.length > MAX_PROJECTS) {
recentProjects = recentProjects.slice(0, MAX_PROJECTS);
}
PreferencesManager.setViewState("recentProjects", recentProjects);
}
/**
* Check the list of items to see if any of them are hovered, and if so trigger a mouseenter.
* Normally the mouseenter event handles this, but when a previous item is deleted and the next
* item moves up to be underneath the mouse, we don't get a mouseenter event for that item.
*/
function checkHovers(pageX, pageY) {
$dropdown.children().each(function () {
var offset = $(this).offset(),
width = $(this).outerWidth(),
height = $(this).outerHeight();
if (pageX >= offset.left && pageX <= offset.left + width &&
pageY >= offset.top && pageY <= offset.top + height) {
$(".recent-folder-link", this).triggerHandler("mouseenter");
}
});
}
/**
* Create the "delete" button that shows up when you hover over a project.
*/
function renderDelete() {
return $("<div id='recent-folder-delete' class='trash-icon'>×</div>")
.mouseup(function (e) {
// Don't let the click bubble upward.
e.stopPropagation();
// Remove the project from the preferences.
var recentProjects = getRecentProjects(),
index = recentProjects.indexOf($(this).parent().data("path")),
newProjects = [],
i;
for (i = 0; i < recentProjects.length; i++) {
if (i !== index) {
newProjects.push(recentProjects[i]);
}
}
PreferencesManager.setViewState("recentProjects", newProjects);
$(this).closest("li").remove();
checkHovers(e.pageX, e.pageY);
if (newProjects.length === 1) {
$dropdown.find(".divider").remove();
}
});
}
/**
* Hide the delete button.
*/
function removeDeleteButton() {
$("#recent-folder-delete").remove();
}
/**
* Show the delete button over a given target.
*/
function addDeleteButton($target) {
removeDeleteButton();
renderDelete()
.css("top", $target.position().top + 6)
.appendTo($target);
}
/**
* Selects the next or previous item in the list
* @param {number} direction +1 for next, -1 for prev
*/
function selectNextItem(direction) {
var $links = $dropdown.find("a"),
index = $dropdownItem ? $links.index($dropdownItem) : (direction > 0 ? -1 : 0),
$newItem = $links.eq((index + direction) % $links.length);
if ($dropdownItem) {
$dropdownItem.removeClass("selected");
}
$newItem.addClass("selected");
$dropdownItem = $newItem;
removeDeleteButton();
}
/**
* Deletes the selected item and
* move the focus to next item in list.
*
* @return {boolean} TRUE if project is removed
*/
function removeSelectedItem(e) {
var recentProjects = getRecentProjects(),
$cacheItem = $dropdownItem,
index = recentProjects.indexOf($cacheItem.data("path"));
// When focus is not on project item
if (index === -1) {
return false;
}
// remove project
recentProjects.splice(index, 1);
PreferencesManager.setViewState("recentProjects", recentProjects);
checkHovers(e.pageX, e.pageY);
if (recentProjects.length === 1) {
$dropdown.find(".divider").remove();
}
selectNextItem(+1);
$cacheItem.closest("li").remove();
return true;
}
/**
* Handles the Key Down events
* @param {KeyboardEvent} event
* @return {boolean} True if the key was handled
*/
function keydownHook(event) {
var keyHandled = false;
switch (event.keyCode) {
case KeyEvent.DOM_VK_UP:
selectNextItem(-1);
keyHandled = true;
break;
case KeyEvent.DOM_VK_DOWN:
selectNextItem(+1);
keyHandled = true;
break;
case KeyEvent.DOM_VK_ENTER:
case KeyEvent.DOM_VK_RETURN:
if ($dropdownItem) {
$dropdownItem.trigger("click");
}
keyHandled = true;
break;
case KeyEvent.DOM_VK_BACK_SPACE:
case KeyEvent.DOM_VK_DELETE:
if ($dropdownItem) {
removeSelectedItem(event);
keyHandled = true;
}
break;
}
if (keyHandled) {
event.stopImmediatePropagation();
event.preventDefault();
}
return keyHandled;
}
/**
* Close the dropdown.
*/
function closeDropdown() {
// Since we passed "true" for autoRemove to addPopUp(), this will
// automatically remove the dropdown from the DOM. Also, PopUpManager
// will call cleanupDropdown().
if ($dropdown) {
PopUpManager.removePopUp($dropdown);
}
}
/**
* Remove the various event handlers that close the dropdown. This is called by the
* PopUpManager when the dropdown is closed.
*/
function cleanupDropdown() {
$("html").off("click", closeDropdown);
$("#project-files-container").off("scroll", closeDropdown);
$(SidebarView).off("hide", closeDropdown);
$("#titlebar .nav").off("click", closeDropdown);
$dropdown = null;
MainViewManager.focusActivePane();
$(window).off("keydown", keydownHook);
}
/**
* Adds the click and mouse enter/leave events to the dropdown
*/
function _handleListEvents() {
$dropdown
.on("click", "a", function () {
var $link = $(this),
id = $link.attr("id"),
path = $link.data("path");
if (path) {
ProjectManager.openProject(path)
.fail(function () {
// Remove the project from the list only if it does not exist on disk
var recentProjects = getRecentProjects(),
index = recentProjects.indexOf(path);
if (index !== -1) {
FileSystem.resolve(path, function (err, item) {
if (err) {
recentProjects.splice(index, 1);
}
});
}
});
closeDropdown();
} else if (id === "open-folder-link") {
CommandManager.execute(Commands.FILE_OPEN_FOLDER);
}
})
.on("mouseenter", "a", function () {
if ($dropdownItem) {
$dropdownItem.removeClass("selected");
}
$dropdownItem = $(this).addClass("selected");
if ($dropdownItem.hasClass("recent-folder-link")) {
// Note: we can't depend on the event here because this can be triggered
// manually from checkHovers().
addDeleteButton($(this));
}
})
.on("mouseleave", "a", function () {
var $link = $(this).removeClass("selected");
if ($link.get(0) === $dropdownItem.get(0)) {
$dropdownItem = null;
}
if ($link.hasClass("recent-folder-link")) {
removeDeleteButton();
}
});
}
/**
* Parses the path and returns an object with the full path, the folder name and the path without the folder.
* @param {string} path The full path to the folder.
* @return {{path: string, folder: string, rest: string}}
*/
function parsePath(path) {
var lastSlash = path.lastIndexOf("/"), folder, rest;
if (lastSlash === path.length - 1) {
lastSlash = path.slice(0, path.length - 1).lastIndexOf("/");
}
if (lastSlash >= 0) {
rest = " - " + (lastSlash ? path.slice(0, lastSlash) : "/");
folder = path.slice(lastSlash + 1);
} else {
rest = "/";
folder = path;
}
return {path: path, folder: folder, rest: rest};
}
/**
* Create the list of projects in the dropdown menu.
* @return {string} The html content
*/
function renderList() {
var recentProjects = getRecentProjects(),
currentProject = FileUtils.stripTrailingSlash(ProjectManager.getProjectRoot().fullPath),
templateVars = {
projectList : [],
Strings : Strings
};
recentProjects.forEach(function (root) {
if (root !== currentProject) {
templateVars.projectList.push(parsePath(root));
}
});
return Mustache.render(ProjectsMenuTemplate, templateVars);
}
/**
* Show or hide the recent projects dropdown.
*
* @param {{pageX:number, pageY:number}} position - the absolute position where to open the dropdown
*/
function showDropdown(position) {
// If the dropdown is already visible, just return (so the root click handler on html
// will close it).
if ($dropdown) {
return;
}
Menus.closeAll();
$dropdown = $(renderList())
.css({
left: position.pageX,
top: position.pageY
})
.appendTo($("body"));
PopUpManager.addPopUp($dropdown, cleanupDropdown, true);
// TODO: should use capture, otherwise clicking on the menus doesn't close it. More fallout
// from the fact that we can't use the Boostrap (1.4) dropdowns.
$("html").on("click", closeDropdown);
// Hide the menu if the user scrolls in the project tree. Otherwise the Lion scrollbar
// overlaps it.
// TODO: This duplicates logic that's already in ProjectManager (which calls Menus.close()).
// We should fix this when the popup handling is centralized in PopupManager, as well
// as making Esc close the dropdown. See issue #1381.
$("#project-files-container").on("scroll", closeDropdown);
// Hide the menu if the sidebar is hidden.
// TODO: Is there some more general way we could handle this for dropdowns?
$(SidebarView).on("hide", closeDropdown);
// Hacky: if we detect a click in the menubar, close ourselves.
// TODO: again, we should have centralized popup management.
$("#titlebar .nav").on("click", closeDropdown);
_handleListEvents();
$(window).on("keydown", keydownHook);
}
/**
* Show or hide the recent projects dropdown from the toogle command.
*/
function handleKeyEvent() {
if (!$dropdown) {
if (!SidebarView.isVisible()) {
SidebarView.show();
}
$("#project-dropdown-toggle").trigger("click");
$dropdown.focus();
$links = $dropdown.find("a");
// By default, select the most recent project (which is at the top of the list underneath Open Folder),
// but if there are none, select Open Folder instead.
$dropdownItem = $links.eq($links.length > 1 ? 1 : 0);
$dropdownItem.addClass("selected");
// If focusing the dropdown caused a modal bar to close, we need to refocus the dropdown
window.setTimeout(function () {
$dropdown.focus();
}, 0);
}
}
PreferencesManager.convertPreferences(module, {"recentProjects": "user"}, true);
// Register command handlers
CommandManager.register(Strings.CMD_TOGGLE_RECENT_PROJECTS, TOGGLE_DROPDOWN, handleKeyEvent);
KeyBindingManager.addBinding(TOGGLE_DROPDOWN, KeyboardPrefs.recentProjects);
// Initialize extension
AppInit.appReady(function () {
ExtensionUtils.loadStyleSheet(module, "styles/styles.less");
$(ProjectManager).on("projectOpen", add);
$(ProjectManager).on("beforeProjectClose", add);
});
AppInit.htmlReady(function () {
$("#project-title")
.wrap("<div id='project-dropdown-toggle' class='btn-alt-quiet'></div>")
.after("<span class='dropdown-arrow'></span>");
var cmenuAdapter = {
open: showDropdown,
close: closeDropdown,
isOpen: function () {
return !!$dropdown;
}
};
Menus.ContextMenu.assignContextMenuToSelector("#project-dropdown-toggle", cmenuAdapter);
});
});
| bglassy/brackets | src/extensions/default/RecentProjects/main.js | JavaScript | mit | 17,380 |
const BaseChecker = require('./../base-checker')
const ruleId = 'imports-on-top'
const meta = {
type: 'order',
docs: {
description: `Import statements must be on top.`,
category: 'Style Guide Rules'
},
isDefault: false,
recommended: true,
defaultSetup: 'warn',
schema: null
}
class ImportsOnTopChecker extends BaseChecker {
constructor(reporter) {
super(reporter, ruleId, meta)
}
SourceUnit(node) {
let hasContractDef = false
for (let i = 0; node.children && i < node.children.length; i += 1) {
const curItem = node.children[i]
if (curItem.type === 'ContractDefinition') {
hasContractDef = true
}
if (hasContractDef && curItem.type === 'ImportDirective') {
this._error(curItem)
}
}
}
_error(node) {
this.error(node, 'Import statements must be on top')
}
}
module.exports = ImportsOnTopChecker
| protofire/solhint | lib/rules/order/imports-on-top.js | JavaScript | mit | 903 |
//
// ColumnArtistCellText.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
// Frank Ziegler <funtastix@googlemail.com>
//
// Copyright (C) 2007 Novell, Inc.
// Copyright (C) 2013 Frank Ziegler
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using Gtk;
using Hyena.Data.Gui;
using Banshee.I18n;
namespace Banshee.Collection.Gui
{
public class ColumnCellArtistText : ColumnCellText, IArtistListRenderer
{
private readonly ColumnController column_controller;
private readonly string name = Catalog.GetString ("Default Text Artist List");
public ColumnCellArtistText () : base ("DisplayName", true)
{
column_controller = new ColumnController ();
var current_layout = new Column ("Artist", this, 1.0);
column_controller.Add (current_layout);
}
public string Name {
get { return name; }
}
public ColumnController ColumnController {
get { return column_controller; }
}
public int ComputeRowHeight (Widget widget)
{
int w_width, row_height;
using (var layout = new Pango.Layout (widget.PangoContext)) {
layout.SetText ("W");
layout.GetPixelSize (out w_width, out row_height);
return row_height + 8;
}
}
}
}
| GNOME/banshee | src/Core/Banshee.ThickClient/Banshee.Collection.Gui/ColumnCellArtistText.cs | C# | mit | 2,406 |
---
title: 'Skin for Skin: The Battle Continues'
date: 10/10/2016
---
Job 2:1–3 begins almost repeating some of Job 1:6–8. The big change is the last part of Job 2:3, where the Lord Himself talks about how faithful Job remained despite the calamities that befell him. Thus, by the time we get to Job 2:3, it looks as if Satan’s accusations have been shown as false. Job stayed faithful to God and didn’t curse Him, as Satan said he would.
```Read Job 2. What happens in these texts? Also, what is the significance of the fact that in both Job 1 and 2 these “sons of God” are there to witness the dialogue between God and Satan?```
The phrase “skin for skin” is an idiomatic expression that has baffled commentators. The idea, though, is this: let something happen to Job’s own person, and that will cause him to show where his loyalty really is. Ruin Job’s body, his health, and see what happens.
And interestingly enough, what happens does not happen in a vac- uum, either. Both instances of the controversy in heaven, as revealed here in the book of Job, take place in the context of some sort of meet- ing between these heavenly intelligences and God. Satan is making his accusations “publicly”; that is, he is doing it before these other beings. This idea fits in perfectly with what we know about the great contro- versy. It is something that is unfolding before the whole universe. (See 1 Cor. 4:9, Dan. 7:10, Rev. 12:7–9.)
“But the plan of redemption had a yet broader and deeper purpose than the salvation of man. It was not for this alone that Christ came to the earth; it was not merely that the inhabitants of this little world might regard the law of God as it should be regarded; but it was to vindicate the character of God before the universe. . . . The act of Christ in dying for the salvation of man would not only make heaven accessible to men, but before all the universe it would justify God and His Son in their dealing with the rebellion of Satan. It would establish the perpetuity of the law of God and would reveal the nature and the results of sin.” —Ellen G. White, Patriarchs and Prophets, pp. 68, 69. | PrJared/sabbath-school-lessons | src/en/2016-04/03/03.md | Markdown | mit | 2,172 |
<?php
namespace TypiCMS\Modules\Blocks\Repositories;
use App;
use Illuminate\Database\Eloquent\Collection;
use TypiCMS\Repositories\CacheAbstractDecorator;
use TypiCMS\Services\Cache\CacheInterface;
class CacheDecorator extends CacheAbstractDecorator implements BlockInterface
{
public function __construct(BlockInterface $repo, CacheInterface $cache)
{
$this->repo = $repo;
$this->cache = $cache;
}
/**
* Get all models
*
* @param boolean $all Show published or all
* @param array $with Eager load related models
* @return Collection
*/
public function getAll(array $with = array(), $all = false)
{
$cacheKey = md5(App::getLocale() . 'all' . $all . implode('.', $with));
if ($this->cache->has($cacheKey)) {
return $this->cache->get($cacheKey);
}
// Item not cached, retrieve it
$models = $this->repo->getAll($with, $all);
// Store in cache for next request
$this->cache->put($cacheKey, $models);
return $models;
}
/**
* Get the content of a block
*
* @param string $name unique name of the block
* @param array $with linked
* @return string html
*/
public function build($name = null, array $with = array('translations'))
{
$cacheKey = md5(App::getLocale() . 'build' . $name . implode('.', $with));
if ($this->cache->has($cacheKey)) {
return $this->cache->get($cacheKey);
}
// Item not cached, retrieve it
$model = $this->repo->build($name, $with);
// Store in cache for next request
$this->cache->put($cacheKey, $model);
return $model;
}
}
| laravelproject2016/project | app/TypiCMS/Modules/Blocks/Repositories/CacheDecorator.php | PHP | mit | 1,743 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Search — dlib documentation</title>
<link rel="stylesheet" href="_static/default.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '',
VERSION: '',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/searchtools.js"></script>
<link rel="top" title="dlib documentation" href="index.html" />
<script type="text/javascript">
jQuery(function() { Search.loadIndex("searchindex.js"); });
</script>
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li><a href="index.html">dlib documentation</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<h1 id="search-documentation">Search</h1>
<div id="fallback" class="admonition warning">
<script type="text/javascript">$('#fallback').hide();</script>
<p>
Please activate JavaScript to enable the search
functionality.
</p>
</div>
<p>
From here you can search these documents. Enter your search
words into the box below and click "search". Note that the search
function will automatically search for all of the words. Pages
containing fewer words won't appear in the result list.
</p>
<form action="" method="get">
<input type="text" name="q" value="" />
<input type="submit" value="search" />
<span id="search-progress" style="padding-left: 10px"></span>
</form>
<div id="search-results">
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li><a href="index.html">dlib documentation</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2013, Davis E. King.
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3.
</div>
</body>
</html> | eldilibra/mudsling | include/dlib-18.9/docs/python/search.html | HTML | mit | 3,323 |
require File.join(File.dirname(__FILE__), 'lib', 'image_spec')
| edgerunner/merttorun.com | vendor/extensions/paperclipped/vendor/plugins/imagespec/init.rb | Ruby | mit | 63 |
---
sponsors: true
type: sponsors
---
| vuejs-kr/kr.vuejs.org | src/support-vuejs/index.md | Markdown | mit | 38 |
/*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.tests.queries;
import org.eclipse.persistence.testing.models.employee.domain.*;
import org.eclipse.persistence.testing.framework.*;
import org.eclipse.persistence.queries.*;
import org.eclipse.persistence.expressions.*;
import java.util.Vector;
/**
* Test for bug 2612366: Conform results in UnitOfWork extremely slow.
* <p><b>Test Description:<b>
* <ul>
* <li>Conform results test using a wrapper policy.
* <li>Insure that the number of times unwrap is called is linear to the
* number of objects read in.
* <li>The test input is small to allow this to be run as a short
* regression test. The relationship between input size and calls to unwrap is
* the key.
* </ul>
* @author Stephen McRitchie
*/
public class ConformResultsPerformanceTest extends ConformResultsInUnitOfWorkTest {
public long startTime;
public ConformResultsPerformanceTest() {
setShouldUseWrapperPolicy(true);
}
public void buildConformQuery() {
conformedQuery = new ReadAllQuery(Employee.class);
conformedQuery.conformResultsInUnitOfWork();
conformedQuery.setSelectionCriteria(new ExpressionBuilder().get("lastName").notEqual("test"));
}
public void prepareTest() {
EmployeeWrapperPolicy.timesUnwrapCalled = 0;
startTime = System.currentTimeMillis();
}
/**
* Insure that the conforming worked and that unwrap was called a liner number
* of times.
*/
public void verify() {
long testTime = System.currentTimeMillis() - startTime;
int size = ((Vector)result).size();
if (EmployeeWrapperPolicy.timesUnwrapCalled > (2 * size)) {// Give some leeway
throw new TestErrorException("Unwrap was called " + EmployeeWrapperPolicy.timesUnwrapCalled + " times on a result of size " + size);
}
}
}
| RallySoftware/eclipselink.runtime | foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/queries/ConformResultsPerformanceTest.java | Java | epl-1.0 | 2,586 |
/**
* Copyright (c) 2014,2019 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.smarthome.binding.onewire.internal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
/**
* The {@link SensorId} provides a sensorID for the Onewire bus.
*
* @author Jan N. Klug - Initial contribution
*/
@NonNullByDefault
public class SensorId {
public static final Pattern SENSOR_ID_PATTERN = Pattern
.compile("^\\/?((?:(?:1F\\.[0-9A-Fa-f]{12})\\/(?:main|aux)\\/)+)?([0-9A-Fa-f]{2}\\.[0-9A-Fa-f]{12})$");
private final String sensorId;
private final String path;
private final String fullPath;
/**
* construct a new SensorId object
*
* allowed formats:
* - "28.0123456789ab"
* - "1F.1234566890ab/main/28.0123456789ab"
* - "1F.1234566890ab/aux/28.0123456789ab"
* - leading "/" characters are allowed but not required
* - characters are case-insensitive
* - hubs ("1F.xxxxxxxxxxxx/aux/") may be repeated
*/
public SensorId(String fullPath) {
Matcher matcher = SENSOR_ID_PATTERN.matcher(fullPath);
if (matcher.matches() && matcher.groupCount() == 2) {
path = matcher.group(1) == null ? "" : matcher.group(1);
sensorId = matcher.group(2);
this.fullPath = "/" + path + sensorId;
} else {
throw new IllegalArgumentException();
}
}
/**
* get the full path to the sensor
*
* @return full path (including hub parts, separated by "/" characters)
*/
public String getFullPath() {
return fullPath;
}
/**
* get the sensor id
*
* @return sensor id without leading "/" character
*/
public String getId() {
return sensorId;
}
/**
* get the path of this sensorId
*
* @return path without sensor id (including hub parts, separated by "/" characters)
*/
public String getPath() {
return path;
}
/**
* get family id (first to characters of sensor id)
*
* @return the family id
*/
public String getFamilyId() {
return sensorId.substring(0, 2);
}
@Override
public String toString() {
return fullPath;
}
@Override
public int hashCode() {
return this.fullPath.hashCode();
}
@Override
public boolean equals(@Nullable Object o) {
if (o == this) {
return true;
}
if (!(o instanceof SensorId)) {
return false;
}
return ((SensorId) o).fullPath.equals(fullPath);
}
}
| Snickermicker/smarthome | extensions/binding/org.eclipse.smarthome.binding.onewire/src/main/java/org/eclipse/smarthome/binding/onewire/internal/SensorId.java | Java | epl-1.0 | 3,046 |
/*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.tools.workbench.test.uitools;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.persistence.tools.workbench.uitools.SwitcherPanel;
import org.eclipse.persistence.tools.workbench.uitools.app.PropertyAspectAdapter;
import org.eclipse.persistence.tools.workbench.uitools.app.PropertyValueModel;
import org.eclipse.persistence.tools.workbench.uitools.app.TransformationPropertyValueModel;
import org.eclipse.persistence.tools.workbench.utility.AbstractModel;
/**
*
*/
public class SwitcherPanelTests extends TestCase
{
public static Test suite() {
return new TestSuite(SwitcherPanelTests.class);
}
public SwitcherPanelTests(String name)
{
super(name);
}
private PropertyValueModel buildPropertyAdapter(ModelTest modelTest)
{
return new PropertyAspectAdapter(ModelTest.NAME_PROPERTY, modelTest)
{
protected Object getValueFromSubject()
{
return ((ModelTest) this.subject).getName();
}
};
}
private TransformationPropertyValueModel buildTransformationPropertyAdapter1(ModelTest modelTest)
{
return new TransformationPropertyValueModel(buildPropertyAdapter(modelTest))
{
protected Object transform(Object value)
{
if (value == null)
return null;
if ("label".equals(value))
return new JLabel("A label");
if ("button".equals(value))
return new JButton("A button");
throw new IllegalArgumentException("The value is unknown");
}
};
}
private TransformationPropertyValueModel buildTransformationPropertyAdapter2(ModelTest modelTest)
{
final JLabel label = new JLabel("A label");
final JButton button = new JButton("A button");
return new TransformationPropertyValueModel(buildPropertyAdapter(modelTest))
{
protected Object transform(Object value)
{
if (value == null)
return null;
if ("label".equals(value))
return label;
if ("button".equals(value))
return button;
throw new IllegalArgumentException("The value is unknown");
}
};
}
public void testNestedSwitching1()
{
ModelTest modelTest = new ModelTest();
TransformationPropertyValueModel holder = buildTransformationPropertyAdapter2(modelTest);
new SwitcherPanel(holder);
}
public void testNullPropertyHolder()
{
try
{
new SwitcherPanel(null);
assertTrue("The property holder cannot be null and no exception was thrown", false);
}
catch (NullPointerException e)
{
// Good
}
}
public void testSwitching1()
{
ModelTest modelTest = new ModelTest();
TransformationPropertyValueModel holder = buildTransformationPropertyAdapter1(modelTest);
SwitcherPanel panel = new SwitcherPanel(holder);
// First there is no children since the panel is not a child of any component
assertTrue(panel.getComponentCount() == 0);
// This will engage the listeners on the model
JPanel container = new JPanel();
container.add(panel);
// The value that is been listened is still null
assertTrue(panel.getComponentCount() == 0);
}
public void testSwitching2()
{
ModelTest modelTest = new ModelTest();
TransformationPropertyValueModel holder = buildTransformationPropertyAdapter1(modelTest);
SwitcherPanel panel = new SwitcherPanel(holder);
// First there is no children since the panel is not a child of any component
assertTrue(panel.getComponentCount() == 0);
modelTest.setName("label");
// This will engage the listener on the model and should add a children
JPanel container = new JPanel();
// We need a peer in order for addNotify() to be called
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.getContentPane().add(container);
frame.setVisible(true);
// Now we can do the test
container.add(panel);
assertTrue(panel.getComponentCount() == 1);
assertTrue(panel.getComponent(0) instanceof JLabel);
// This should switch the children
modelTest.setName("button");
assertTrue(panel.getComponentCount() == 1);
assertTrue(panel.getComponent(0) instanceof JButton);
// This should simply remove the children
modelTest.setName(null);
assertTrue(panel.getComponentCount() == 0);
frame.setVisible(false);
}
public void testSwitching3()
{
ModelTest modelTest = new ModelTest();
TransformationPropertyValueModel holder = buildTransformationPropertyAdapter2(modelTest);
SwitcherPanel panel = new SwitcherPanel(holder);
// First there is no children since the panel is not a child of any component
assertTrue(panel.getComponentCount() == 0);
// Changing the value in the model should not affect the PanelSwitcherAdapter
// yet since it does not have a parent yet
modelTest.setName("label");
// This will engage the listener on the model and should add a children
JPanel container = new JPanel();
// We need a peer in order for addNotify() to be called
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.getContentPane().add(container);
frame.setVisible(true);
// Now we can do the test
container.add(panel);
assertEquals(1, panel.getComponentCount());
assertTrue(panel.getComponent(0) instanceof JLabel);
JLabel label = (JLabel) panel.getComponent(0);
// This should switch the children
modelTest.setName("button");
assertTrue(panel.getComponentCount() == 1);
assertTrue(panel.getComponent(0) instanceof JButton);
JButton button = (JButton) panel.getComponent(0);
// This should simply remove the children
modelTest.setName(null);
assertTrue(panel.getComponentCount() == 0);
// Switch again
modelTest.setName("label");
assertTrue(panel.getComponentCount() == 1);
assertTrue(panel.getComponent(0) == label);
// Switch again
modelTest.setName("button");
assertTrue(panel.getComponentCount() == 1);
assertTrue(panel.getComponent(0) == button);
// Switch again
modelTest.setName("label");
assertTrue(panel.getComponentCount() == 1);
assertTrue(panel.getComponent(0) == label);
// Switch again
modelTest.setName(null);
assertTrue(panel.getComponentCount() == 0);
frame.setVisible(false);
}
private static class ModelTest extends AbstractModel
{
private String name;
public static final String NAME_PROPERTY = "name";
public String getName()
{
return this.name;
}
public void setName(String name)
{
String oldName = getName();
this.name = name;
firePropertyChanged(NAME_PROPERTY, oldName, name);
}
}
}
| RallySoftware/eclipselink.runtime | utils/eclipselink.utils.workbench.test/uitools/source/org/eclipse/persistence/tools/workbench/test/uitools/SwitcherPanelTests.java | Java | epl-1.0 | 8,480 |
package org.intalio.tempo.workflow.wds.core.xforms;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.regex.Pattern;
import org.junit.runner.RunWith;
import com.googlecode.instinct.expect.ExpectThat;
import com.googlecode.instinct.expect.ExpectThatImpl;
import com.googlecode.instinct.integrate.junit4.InstinctRunner;
import com.googlecode.instinct.marker.annotate.Specification;
@RunWith(InstinctRunner.class)
public class XFormConversionTest {
String[] RESOURCES = new String[] { "/personnel.xform" };
final static ExpectThat expect = new ExpectThatImpl();
Pattern[] patterns = new Pattern[] { Pattern.compile(".*width:.*px;"), Pattern.compile(".*height:.*px;"), Pattern.compile(".*top:.*px;") };
@Specification
public void runTheXFormConversionWithReader() throws Exception {
for (String r : RESOURCES) {
URL url = XFormConversionTest.class.getResource(r);
String sb = new String(XFormsConverter.fixStyle(new FileReader(url.getFile())));
matchesPatterns(sb);
}
}
@Specification
public void runTheXFormConversionWithByteArray() throws Exception {
for (String r : RESOURCES)
matchesPatterns(convert(r));
}
@Specification
public void runConversionOnCustomStyleForm() throws Exception {
String converted = convert("/selectItem.xform");
matchesPatterns(converted);
}
@Specification
public void runXFromAndCheckForVerticalAlign() throws Exception {
expect.that(convert("/personnel.xform").toString().contains("vertical-align:40%")).isTrue();
}
private void matchesPatterns(String sb) {
for (Pattern p : patterns)
expect.that(p.matcher(sb));
}
private String convert(String r) throws FileNotFoundException, IOException {
URL url = XFormConversionTest.class.getResource(r);
BufferedReader reader = new BufferedReader(new FileReader(url.getFile()));
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return new String(XFormsConverter.fixStyle(sb.toString().getBytes()));
}
}
| ray-dong/tempo | wds-service/src/test/java/org/intalio/tempo/workflow/wds/core/xforms/XFormConversionTest.java | Java | epl-1.0 | 2,325 |
/*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* mmacivor - 2010-03-09 - initial implementation
******************************************************************************/
package org.eclipse.persistence.testing.jaxb.xmlelementref.duplicatename;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementRef;
public class BeanA {
@XmlElementRef(name="value")
public JAXBElement<byte[]> value;
}
| gameduell/eclipselink.runtime | moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/xmlelementref/duplicatename/BeanA.java | Java | epl-1.0 | 965 |
/*
* Copyright © 2014 Red Hat.
*
* Permission to use, copy, modify, distribute, and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting documentation, and
* that the name of the copyright holders not be used in advertising or
* publicity pertaining to distribution of the software without specific,
* written prior permission. The copyright holders make no representations
* about the suitability of this software for any purpose. It is provided "as
* is" without express or implied warranty.
*
* THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
* EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
#ifndef _DRM_DP_MST_HELPER_H_
#define _DRM_DP_MST_HELPER_H_
#include <linux/types.h>
#include <drm/drm_dp_helper.h>
struct drm_dp_mst_branch;
/**
* struct drm_dp_vcpi - Virtual Channel Payload Identifier
* @vcpi: Virtual channel ID.
* @pbn: Payload Bandwidth Number for this channel
* @aligned_pbn: PBN aligned with slot size
* @num_slots: number of slots for this PBN
*/
struct drm_dp_vcpi {
int vcpi;
int pbn;
int aligned_pbn;
int num_slots;
};
/**
* struct drm_dp_mst_port - MST port
* @kref: reference count for this port.
* @port_num: port number
* @input: if this port is an input port.
* @mcs: message capability status - DP 1.2 spec.
* @ddps: DisplayPort Device Plug Status - DP 1.2
* @pdt: Peer Device Type
* @ldps: Legacy Device Plug Status
* @dpcd_rev: DPCD revision of device on this port
* @num_sdp_streams: Number of simultaneous streams
* @num_sdp_stream_sinks: Number of stream sinks
* @available_pbn: Available bandwidth for this port.
* @next: link to next port on this branch device
* @mstb: branch device attach below this port
* @aux: i2c aux transport to talk to device connected to this port.
* @parent: branch device parent of this port
* @vcpi: Virtual Channel Payload info for this port.
* @connector: DRM connector this port is connected to.
* @mgr: topology manager this port lives under.
*
* This structure represents an MST port endpoint on a device somewhere
* in the MST topology.
*/
struct drm_dp_mst_port {
struct kref kref;
u8 port_num;
bool input;
bool mcs;
bool ddps;
u8 pdt;
bool ldps;
u8 dpcd_rev;
u8 num_sdp_streams;
u8 num_sdp_stream_sinks;
uint16_t available_pbn;
struct list_head next;
struct drm_dp_mst_branch *mstb; /* pointer to an mstb if this port has one */
struct drm_dp_aux aux; /* i2c bus for this port? */
struct drm_dp_mst_branch *parent;
struct drm_dp_vcpi vcpi;
struct drm_connector *connector;
struct drm_dp_mst_topology_mgr *mgr;
struct edid *cached_edid; /* for DP logical ports - make tiling work */
bool has_audio;
};
/**
* struct drm_dp_mst_branch - MST branch device.
* @kref: reference count for this port.
* @rad: Relative Address to talk to this branch device.
* @lct: Link count total to talk to this branch device.
* @num_ports: number of ports on the branch.
* @msg_slots: one bit per transmitted msg slot.
* @ports: linked list of ports on this branch.
* @port_parent: pointer to the port parent, NULL if toplevel.
* @mgr: topology manager for this branch device.
* @tx_slots: transmission slots for this device.
* @last_seqno: last sequence number used to talk to this.
* @link_address_sent: if a link address message has been sent to this device yet.
* @guid: guid for DP 1.2 branch device. port under this branch can be
* identified by port #.
*
* This structure represents an MST branch device, there is one
* primary branch device at the root, along with any other branches connected
* to downstream port of parent branches.
*/
struct drm_dp_mst_branch {
struct kref kref;
u8 rad[8];
u8 lct;
int num_ports;
int msg_slots;
struct list_head ports;
/* list of tx ops queue for this port */
struct drm_dp_mst_port *port_parent;
struct drm_dp_mst_topology_mgr *mgr;
/* slots are protected by mstb->mgr->qlock */
struct drm_dp_sideband_msg_tx *tx_slots[2];
int last_seqno;
bool link_address_sent;
/* global unique identifier to identify branch devices */
u8 guid[16];
};
/* sideband msg header - not bit struct */
struct drm_dp_sideband_msg_hdr {
u8 lct;
u8 lcr;
u8 rad[8];
bool broadcast;
bool path_msg;
u8 msg_len;
bool somt;
bool eomt;
bool seqno;
};
struct drm_dp_nak_reply {
u8 guid[16];
u8 reason;
u8 nak_data;
};
struct drm_dp_link_address_ack_reply {
u8 guid[16];
u8 nports;
struct drm_dp_link_addr_reply_port {
bool input_port;
u8 peer_device_type;
u8 port_number;
bool mcs;
bool ddps;
bool legacy_device_plug_status;
u8 dpcd_revision;
u8 peer_guid[16];
u8 num_sdp_streams;
u8 num_sdp_stream_sinks;
} ports[16];
};
struct drm_dp_remote_dpcd_read_ack_reply {
u8 port_number;
u8 num_bytes;
u8 bytes[255];
};
struct drm_dp_remote_dpcd_write_ack_reply {
u8 port_number;
};
struct drm_dp_remote_dpcd_write_nak_reply {
u8 port_number;
u8 reason;
u8 bytes_written_before_failure;
};
struct drm_dp_remote_i2c_read_ack_reply {
u8 port_number;
u8 num_bytes;
u8 bytes[255];
};
struct drm_dp_remote_i2c_read_nak_reply {
u8 port_number;
u8 nak_reason;
u8 i2c_nak_transaction;
};
struct drm_dp_remote_i2c_write_ack_reply {
u8 port_number;
};
struct drm_dp_sideband_msg_rx {
u8 chunk[48];
u8 msg[256];
u8 curchunk_len;
u8 curchunk_idx; /* chunk we are parsing now */
u8 curchunk_hdrlen;
u8 curlen; /* total length of the msg */
bool have_somt;
bool have_eomt;
struct drm_dp_sideband_msg_hdr initial_hdr;
};
#define DRM_DP_MAX_SDP_STREAMS 16
struct drm_dp_allocate_payload {
u8 port_number;
u8 number_sdp_streams;
u8 vcpi;
u16 pbn;
u8 sdp_stream_sink[DRM_DP_MAX_SDP_STREAMS];
};
struct drm_dp_allocate_payload_ack_reply {
u8 port_number;
u8 vcpi;
u16 allocated_pbn;
};
struct drm_dp_connection_status_notify {
u8 guid[16];
u8 port_number;
bool legacy_device_plug_status;
bool displayport_device_plug_status;
bool message_capability_status;
bool input_port;
u8 peer_device_type;
};
struct drm_dp_remote_dpcd_read {
u8 port_number;
u32 dpcd_address;
u8 num_bytes;
};
struct drm_dp_remote_dpcd_write {
u8 port_number;
u32 dpcd_address;
u8 num_bytes;
u8 *bytes;
};
#define DP_REMOTE_I2C_READ_MAX_TRANSACTIONS 4
struct drm_dp_remote_i2c_read {
u8 num_transactions;
u8 port_number;
struct {
u8 i2c_dev_id;
u8 num_bytes;
u8 *bytes;
u8 no_stop_bit;
u8 i2c_transaction_delay;
} transactions[DP_REMOTE_I2C_READ_MAX_TRANSACTIONS];
u8 read_i2c_device_id;
u8 num_bytes_read;
};
struct drm_dp_remote_i2c_write {
u8 port_number;
u8 write_i2c_device_id;
u8 num_bytes;
u8 *bytes;
};
/* this covers ENUM_RESOURCES, POWER_DOWN_PHY, POWER_UP_PHY */
struct drm_dp_port_number_req {
u8 port_number;
};
struct drm_dp_enum_path_resources_ack_reply {
u8 port_number;
u16 full_payload_bw_number;
u16 avail_payload_bw_number;
};
/* covers POWER_DOWN_PHY, POWER_UP_PHY */
struct drm_dp_port_number_rep {
u8 port_number;
};
struct drm_dp_query_payload {
u8 port_number;
u8 vcpi;
};
struct drm_dp_resource_status_notify {
u8 port_number;
u8 guid[16];
u16 available_pbn;
};
struct drm_dp_query_payload_ack_reply {
u8 port_number;
u8 allocated_pbn;
};
struct drm_dp_sideband_msg_req_body {
u8 req_type;
union ack_req {
struct drm_dp_connection_status_notify conn_stat;
struct drm_dp_port_number_req port_num;
struct drm_dp_resource_status_notify resource_stat;
struct drm_dp_query_payload query_payload;
struct drm_dp_allocate_payload allocate_payload;
struct drm_dp_remote_dpcd_read dpcd_read;
struct drm_dp_remote_dpcd_write dpcd_write;
struct drm_dp_remote_i2c_read i2c_read;
struct drm_dp_remote_i2c_write i2c_write;
} u;
};
struct drm_dp_sideband_msg_reply_body {
u8 reply_type;
u8 req_type;
union ack_replies {
struct drm_dp_nak_reply nak;
struct drm_dp_link_address_ack_reply link_addr;
struct drm_dp_port_number_rep port_number;
struct drm_dp_enum_path_resources_ack_reply path_resources;
struct drm_dp_allocate_payload_ack_reply allocate_payload;
struct drm_dp_query_payload_ack_reply query_payload;
struct drm_dp_remote_dpcd_read_ack_reply remote_dpcd_read_ack;
struct drm_dp_remote_dpcd_write_ack_reply remote_dpcd_write_ack;
struct drm_dp_remote_dpcd_write_nak_reply remote_dpcd_write_nack;
struct drm_dp_remote_i2c_read_ack_reply remote_i2c_read_ack;
struct drm_dp_remote_i2c_read_nak_reply remote_i2c_read_nack;
struct drm_dp_remote_i2c_write_ack_reply remote_i2c_write_ack;
} u;
};
/* msg is queued to be put into a slot */
#define DRM_DP_SIDEBAND_TX_QUEUED 0
/* msg has started transmitting on a slot - still on msgq */
#define DRM_DP_SIDEBAND_TX_START_SEND 1
/* msg has finished transmitting on a slot - removed from msgq only in slot */
#define DRM_DP_SIDEBAND_TX_SENT 2
/* msg has received a response - removed from slot */
#define DRM_DP_SIDEBAND_TX_RX 3
#define DRM_DP_SIDEBAND_TX_TIMEOUT 4
struct drm_dp_sideband_msg_tx {
u8 msg[256];
u8 chunk[48];
u8 cur_offset;
u8 cur_len;
struct drm_dp_mst_branch *dst;
struct list_head next;
int seqno;
int state;
bool path_msg;
struct drm_dp_sideband_msg_reply_body reply;
};
/* sideband msg handler */
struct drm_dp_mst_topology_mgr;
struct drm_dp_mst_topology_cbs {
/* create a connector for a port */
struct drm_connector *(*add_connector)(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port, const char *path);
void (*register_connector)(struct drm_connector *connector);
void (*destroy_connector)(struct drm_dp_mst_topology_mgr *mgr,
struct drm_connector *connector);
void (*hotplug)(struct drm_dp_mst_topology_mgr *mgr);
};
#define DP_MAX_PAYLOAD (sizeof(unsigned long) * 8)
#define DP_PAYLOAD_LOCAL 1
#define DP_PAYLOAD_REMOTE 2
#define DP_PAYLOAD_DELETE_LOCAL 3
struct drm_dp_payload {
int payload_state;
int start_slot;
int num_slots;
int vcpi;
};
/**
* struct drm_dp_mst_topology_mgr - DisplayPort MST manager
* @dev: device pointer for adding i2c devices etc.
* @cbs: callbacks for connector addition and destruction.
* @max_dpcd_transaction_bytes - maximum number of bytes to read/write in one go.
* @aux: aux channel for the DP connector.
* @max_payloads: maximum number of payloads the GPU can generate.
* @conn_base_id: DRM connector ID this mgr is connected to.
* @down_rep_recv: msg receiver state for down replies.
* @up_req_recv: msg receiver state for up requests.
* @lock: protects mst state, primary, dpcd.
* @mst_state: if this manager is enabled for an MST capable port.
* @mst_primary: pointer to the primary branch device.
* @dpcd: cache of DPCD for primary port.
* @pbn_div: PBN to slots divisor.
*
* This struct represents the toplevel displayport MST topology manager.
* There should be one instance of this for every MST capable DP connector
* on the GPU.
*/
struct drm_dp_mst_topology_mgr {
struct device *dev;
struct drm_dp_mst_topology_cbs *cbs;
int max_dpcd_transaction_bytes;
struct drm_dp_aux *aux; /* auxch for this topology mgr to use */
int max_payloads;
int conn_base_id;
/* only ever accessed from the workqueue - which should be serialised */
struct drm_dp_sideband_msg_rx down_rep_recv;
struct drm_dp_sideband_msg_rx up_req_recv;
/* pointer to info about the initial MST device */
struct mutex lock; /* protects mst_state + primary + dpcd */
bool mst_state;
struct drm_dp_mst_branch *mst_primary;
u8 dpcd[DP_RECEIVER_CAP_SIZE];
u8 sink_count;
int pbn_div;
int total_slots;
int avail_slots;
int total_pbn;
/* messages to be transmitted */
/* qlock protects the upq/downq and in_progress,
the mstb tx_slots and txmsg->state once they are queued */
struct mutex qlock;
struct list_head tx_msg_downq;
bool tx_down_in_progress;
/* payload info + lock for it */
struct mutex payload_lock;
struct drm_dp_vcpi **proposed_vcpis;
struct drm_dp_payload *payloads;
unsigned long payload_mask;
unsigned long vcpi_mask;
wait_queue_head_t tx_waitq;
struct work_struct work;
struct work_struct tx_work;
struct list_head destroy_connector_list;
struct mutex destroy_connector_lock;
struct work_struct destroy_connector_work;
};
int drm_dp_mst_topology_mgr_init(struct drm_dp_mst_topology_mgr *mgr, struct device *dev, struct drm_dp_aux *aux, int max_dpcd_transaction_bytes, int max_payloads, int conn_base_id);
void drm_dp_mst_topology_mgr_destroy(struct drm_dp_mst_topology_mgr *mgr);
int drm_dp_mst_topology_mgr_set_mst(struct drm_dp_mst_topology_mgr *mgr, bool mst_state);
int drm_dp_mst_hpd_irq(struct drm_dp_mst_topology_mgr *mgr, u8 *esi, bool *handled);
enum drm_connector_status drm_dp_mst_detect_port(struct drm_connector *connector, struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port);
bool drm_dp_mst_port_has_audio(struct drm_dp_mst_topology_mgr *mgr,
struct drm_dp_mst_port *port);
struct edid *drm_dp_mst_get_edid(struct drm_connector *connector, struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port);
int drm_dp_calc_pbn_mode(int clock, int bpp);
bool drm_dp_mst_allocate_vcpi(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port, int pbn, int *slots);
int drm_dp_mst_get_vcpi_slots(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port);
void drm_dp_mst_reset_vcpi_slots(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port);
void drm_dp_mst_deallocate_vcpi(struct drm_dp_mst_topology_mgr *mgr,
struct drm_dp_mst_port *port);
int drm_dp_find_vcpi_slots(struct drm_dp_mst_topology_mgr *mgr,
int pbn);
int drm_dp_update_payload_part1(struct drm_dp_mst_topology_mgr *mgr);
int drm_dp_update_payload_part2(struct drm_dp_mst_topology_mgr *mgr);
int drm_dp_check_act_status(struct drm_dp_mst_topology_mgr *mgr);
void drm_dp_mst_dump_topology(struct seq_file *m,
struct drm_dp_mst_topology_mgr *mgr);
void drm_dp_mst_topology_mgr_suspend(struct drm_dp_mst_topology_mgr *mgr);
int drm_dp_mst_topology_mgr_resume(struct drm_dp_mst_topology_mgr *mgr);
#endif
| parheliamm/T440p-kernel | include/drm/drm_dp_mst_helper.h | C | gpl-2.0 | 14,494 |
/* Copyright (c) 2009-2011, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
//FIXME: most allocations need not be GFP_ATOMIC
/* FIXME: management of mutexes */
/* FIXME: msm_pmem_region_lookup return values */
/* FIXME: way too many copy to/from user */
/* FIXME: does region->active mean free */
/* FIXME: check limits on command lenghts passed from userspace */
/* FIXME: __msm_release: which queues should we flush when opencnt != 0 */
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <mach/board.h>
#include <linux/uaccess.h>
#include <linux/fs.h>
#include <linux/list.h>
#include <linux/uaccess.h>
#include <linux/android_pmem.h>
#include <linux/poll.h>
#include <media/msm_camera-liteon.h>
#include <mach/camera-liteon.h>
#include <linux/syscalls.h>
#include <linux/hrtimer.h>
DEFINE_MUTEX(ctrl_cmd_lock);
#define CAMERA_STOP_VIDEO 58
spinlock_t pp_prev_spinlock;
spinlock_t pp_snap_spinlock;
spinlock_t pp_thumb_spinlock;
spinlock_t pp_stereocam_spinlock;
spinlock_t st_frame_spinlock;
#define ERR_USER_COPY(to) pr_err("%s(%d): copy %s user\n", \
__func__, __LINE__, ((to) ? "to" : "from"))
#define ERR_COPY_FROM_USER() ERR_USER_COPY(0)
#define ERR_COPY_TO_USER() ERR_USER_COPY(1)
#define MAX_PMEM_CFG_BUFFERS 10
static struct class *msm_class;
static dev_t msm_devno;
static LIST_HEAD(msm_sensors);
struct msm_control_device *g_v4l2_control_device;
int g_v4l2_opencnt;
static int camera_node;
static enum msm_camera_type camera_type[MSM_MAX_CAMERA_SENSORS];
static uint32_t sensor_mount_angle[MSM_MAX_CAMERA_SENSORS];
#ifdef CONFIG_MSM_CAMERA_DEBUG
static const char *vfe_config_cmd[] = {
"CMD_GENERAL", /* 0 */
"CMD_AXI_CFG_OUT1",
"CMD_AXI_CFG_SNAP_O1_AND_O2",
"CMD_AXI_CFG_OUT2",
"CMD_PICT_T_AXI_CFG",
"CMD_PICT_M_AXI_CFG", /* 5 */
"CMD_RAW_PICT_AXI_CFG",
"CMD_FRAME_BUF_RELEASE",
"CMD_PREV_BUF_CFG",
"CMD_SNAP_BUF_RELEASE",
"CMD_SNAP_BUF_CFG", /* 10 */
"CMD_STATS_DISABLE",
"CMD_STATS_AEC_AWB_ENABLE",
"CMD_STATS_AF_ENABLE",
"CMD_STATS_AEC_ENABLE",
"CMD_STATS_AWB_ENABLE", /* 15 */
"CMD_STATS_ENABLE",
"CMD_STATS_AXI_CFG",
"CMD_STATS_AEC_AXI_CFG",
"CMD_STATS_AF_AXI_CFG",
"CMD_STATS_AWB_AXI_CFG", /* 20 */
"CMD_STATS_RS_AXI_CFG",
"CMD_STATS_CS_AXI_CFG",
"CMD_STATS_IHIST_AXI_CFG",
"CMD_STATS_SKIN_AXI_CFG",
"CMD_STATS_BUF_RELEASE", /* 25 */
"CMD_STATS_AEC_BUF_RELEASE",
"CMD_STATS_AF_BUF_RELEASE",
"CMD_STATS_AWB_BUF_RELEASE",
"CMD_STATS_RS_BUF_RELEASE",
"CMD_STATS_CS_BUF_RELEASE", /* 30 */
"CMD_STATS_IHIST_BUF_RELEASE",
"CMD_STATS_SKIN_BUF_RELEASE",
"UPDATE_STATS_INVALID",
"CMD_AXI_CFG_SNAP_GEMINI",
"CMD_AXI_CFG_SNAP", /* 35 */
"CMD_AXI_CFG_PREVIEW",
"CMD_AXI_CFG_VIDEO",
"CMD_STATS_IHIST_ENABLE",
"CMD_STATS_RS_ENABLE",
"CMD_STATS_CS_ENABLE", /* 40 */
"CMD_VPE",
"CMD_AXI_CFG_VPE",
"CMD_AXI_CFG_SNAP_VPE",
"CMD_AXI_CFG_SNAP_THUMB_VPE",
};
#endif
#define __CONTAINS(r, v, l, field) ({ \
typeof(r) __r = r; \
typeof(v) __v = v; \
typeof(v) __e = __v + l; \
int res = __v >= __r->field && \
__e <= __r->field + __r->len; \
res; \
})
#define CONTAINS(r1, r2, field) ({ \
typeof(r2) __r2 = r2; \
__CONTAINS(r1, __r2->field, __r2->len, field); \
})
#define IN_RANGE(r, v, field) ({ \
typeof(r) __r = r; \
typeof(v) __vv = v; \
int res = ((__vv >= __r->field) && \
(__vv < (__r->field + __r->len))); \
res; \
})
#define OVERLAPS(r1, r2, field) ({ \
typeof(r1) __r1 = r1; \
typeof(r2) __r2 = r2; \
typeof(__r2->field) __v = __r2->field; \
typeof(__v) __e = __v + __r2->len - 1; \
int res = (IN_RANGE(__r1, __v, field) || \
IN_RANGE(__r1, __e, field)); \
res; \
})
static inline void free_qcmd(struct msm_queue_cmd *qcmd)
{
if (!qcmd || !atomic_read(&qcmd->on_heap))
return;
if (!atomic_sub_return(1, &qcmd->on_heap))
kfree(qcmd);
}
static void msm_region_init(struct msm_sync *sync)
{
INIT_HLIST_HEAD(&sync->pmem_frames);
INIT_HLIST_HEAD(&sync->pmem_stats);
spin_lock_init(&sync->pmem_frame_spinlock);
spin_lock_init(&sync->pmem_stats_spinlock);
}
static void msm_queue_init(struct msm_device_queue *queue, const char *name)
{
spin_lock_init(&queue->lock);
spin_lock_init(&queue->wait_lock);
queue->len = 0;
queue->max = 0;
queue->name = name;
INIT_LIST_HEAD(&queue->list);
init_waitqueue_head(&queue->wait);
}
static void msm_enqueue(struct msm_device_queue *queue,
struct list_head *entry)
{
unsigned long flags;
spin_lock_irqsave(&queue->lock, flags);
queue->len++;
if (queue->len > queue->max) {
queue->max = queue->len;
CDBG("%s: queue %s new max is %d\n", __func__,
queue->name, queue->max);
}
list_add_tail(entry, &queue->list);
wake_up(&queue->wait);
CDBG("%s: woke up %s\n", __func__, queue->name);
spin_unlock_irqrestore(&queue->lock, flags);
}
static void msm_enqueue_vpe(struct msm_device_queue *queue,
struct list_head *entry)
{
unsigned long flags;
spin_lock_irqsave(&queue->lock, flags);
queue->len++;
if (queue->len > queue->max) {
queue->max = queue->len;
CDBG("%s: queue %s new max is %d\n", __func__,
queue->name, queue->max);
}
list_add_tail(entry, &queue->list);
CDBG("%s: woke up %s\n", __func__, queue->name);
spin_unlock_irqrestore(&queue->lock, flags);
}
#define msm_dequeue(queue, member) ({ \
unsigned long flags; \
struct msm_device_queue *__q = (queue); \
struct msm_queue_cmd *qcmd = 0; \
spin_lock_irqsave(&__q->lock, flags); \
if (!list_empty(&__q->list)) { \
__q->len--; \
qcmd = list_first_entry(&__q->list, \
struct msm_queue_cmd, member); \
if ((qcmd) && (&qcmd->member) && (&qcmd->member.next)) \
list_del_init(&qcmd->member); \
} \
spin_unlock_irqrestore(&__q->lock, flags); \
qcmd; \
})
#define msm_delete_entry(queue, member, q_cmd) ({ \
unsigned long __flags; \
struct msm_device_queue *__q = (queue); \
struct msm_queue_cmd *__qcmd = 0; \
pr_info("msm_delete_entry\n"); \
spin_lock_irqsave(&__q->lock, __flags); \
if (!list_empty(&__q->list)) { \
list_for_each_entry(__qcmd, &__q->list, member) \
if (__qcmd == q_cmd) { \
__q->len--; \
list_del_init(&__qcmd->member); \
pr_info("msm_delete_entry, match found\n");\
kfree(q_cmd); \
q_cmd = NULL; \
break; \
} \
} \
spin_unlock_irqrestore(&__q->lock, __flags); \
q_cmd; \
})
#define msm_queue_drain(queue, member) do { \
unsigned long flags; \
struct msm_device_queue *__q = (queue); \
struct msm_queue_cmd *qcmd; \
spin_lock_irqsave(&__q->lock, flags); \
while (!list_empty(&__q->list)) { \
__q->len--; \
qcmd = list_first_entry(&__q->list, \
struct msm_queue_cmd, member); \
if (qcmd) { \
if ((&qcmd->member) && (&qcmd->member.next)) \
list_del_init(&qcmd->member); \
free_qcmd(qcmd); \
} \
} \
spin_unlock_irqrestore(&__q->lock, flags); \
} while (0)
static int check_overlap(struct hlist_head *ptype,
unsigned long paddr,
unsigned long len)
{
struct msm_pmem_region *region;
struct msm_pmem_region t = { .paddr = paddr, .len = len };
struct hlist_node *node;
hlist_for_each_entry(region, node, ptype, list) {
if (CONTAINS(region, &t, paddr) ||
CONTAINS(&t, region, paddr) ||
OVERLAPS(region, &t, paddr)) {
CDBG(" region (PHYS %p len %ld)"
" clashes with registered region"
" (paddr %p len %ld)\n",
(void *)t.paddr, t.len,
(void *)region->paddr, region->len);
return -1;
}
}
return 0;
}
static int check_pmem_info(struct msm_pmem_info *info, int len)
{
if (info->offset < len &&
info->offset + info->len <= len &&
info->y_off < len &&
info->cbcr_off < len)
return 0;
pr_err("%s: check failed: off %d len %d y %d cbcr %d (total len %d)\n",
__func__,
info->offset,
info->len,
info->y_off,
info->cbcr_off,
len);
return -EINVAL;
}
static int msm_pmem_table_add(struct hlist_head *ptype,
struct msm_pmem_info *info, spinlock_t* pmem_spinlock,
struct msm_sync *sync)
{
struct file *file;
unsigned long paddr;
unsigned long kvstart;
unsigned long len;
int rc;
struct msm_pmem_region *region;
unsigned long flags;
rc = get_pmem_file(info->fd, &paddr, &kvstart, &len, &file);
if (rc < 0) {
pr_err("%s: get_pmem_file fd %d error %d\n",
__func__,
info->fd, rc);
return rc;
}
if (!info->len)
info->len = len;
rc = check_pmem_info(info, len);
if (rc < 0)
return rc;
paddr += info->offset;
len = info->len;
spin_lock_irqsave(pmem_spinlock, flags);
if (check_overlap(ptype, paddr, len) < 0) {
spin_unlock_irqrestore(pmem_spinlock, flags);
return -EINVAL;
}
spin_unlock_irqrestore(pmem_spinlock, flags);
region = kmalloc(sizeof(struct msm_pmem_region), GFP_KERNEL);
if (!region)
return -ENOMEM;
spin_lock_irqsave(pmem_spinlock, flags);
INIT_HLIST_NODE(®ion->list);
region->paddr = paddr;
region->len = len;
region->file = file;
memcpy(®ion->info, info, sizeof(region->info));
hlist_add_head(&(region->list), ptype);
spin_unlock_irqrestore(pmem_spinlock, flags);
pr_err("%s: type %d, paddr 0x%lx, vaddr 0x%lx fd %d cbcr_off 0x%x\n",
__func__, info->type, paddr, (unsigned long)info->vaddr, info->fd, info->cbcr_off);
return 0;
}
/* return of 0 means failure */
static uint8_t msm_pmem_region_lookup(struct hlist_head *ptype,
int pmem_type, struct msm_pmem_region *reg, uint8_t maxcount,
spinlock_t *pmem_spinlock)
{
struct msm_pmem_region *region;
struct msm_pmem_region *regptr;
struct hlist_node *node, *n;
unsigned long flags = 0;
uint8_t rc = 0;
regptr = reg;
spin_lock_irqsave(pmem_spinlock, flags);
hlist_for_each_entry_safe(region, node, n, ptype, list) {
if (region->info.type == pmem_type && region->info.active) {
*regptr = *region;
rc += 1;
if (rc >= maxcount)
break;
regptr++;
}
}
spin_unlock_irqrestore(pmem_spinlock, flags);
/* After lookup failure, dump all the list entries...*/
if (rc == 0) {
pr_err("%s: pmem_type = %d\n", __func__, pmem_type);
hlist_for_each_entry_safe(region, node, n, ptype, list) {
pr_err("listed region->info.type = %d, active = %d",
region->info.type, region->info.active);
}
}
return rc;
}
static uint8_t msm_pmem_region_lookup_2(struct hlist_head *ptype,
int pmem_type,
struct msm_pmem_region *reg,
uint8_t maxcount,
spinlock_t *pmem_spinlock)
{
struct msm_pmem_region *region;
struct msm_pmem_region *regptr;
struct hlist_node *node, *n;
uint8_t rc = 0;
unsigned long flags = 0;
regptr = reg;
spin_lock_irqsave(pmem_spinlock, flags);
hlist_for_each_entry_safe(region, node, n, ptype, list) {
CDBG("%s:info.type=%d, pmem_type = %d,"
"info.active = %d\n",
__func__, region->info.type, pmem_type, region->info.active);
if (region->info.type == pmem_type && region->info.active) {
CDBG("%s:info.type=%d, pmem_type = %d,"
"info.active = %d,\n",
__func__, region->info.type, pmem_type,
region->info.active);
*regptr = *region;
region->info.type = MSM_PMEM_VIDEO;
rc += 1;
if (rc >= maxcount)
break;
regptr++;
}
}
spin_unlock_irqrestore(pmem_spinlock, flags);
return rc;
}
static int msm_pmem_frame_ptov_lookup(struct msm_sync *sync,
unsigned long pyaddr,
unsigned long pcbcraddr,
struct msm_pmem_info *pmem_info,
int clear_active)
{
struct msm_pmem_region *region;
struct hlist_node *node, *n;
unsigned long flags = 0;
spin_lock_irqsave(&sync->pmem_frame_spinlock, flags);
hlist_for_each_entry_safe(region, node, n, &sync->pmem_frames, list) {
if (pyaddr == (region->paddr + region->info.y_off) &&
pcbcraddr == (region->paddr +
region->info.cbcr_off) &&
region->info.active) {
/* offset since we could pass vaddr inside
* a registerd pmem buffer
*/
memcpy(pmem_info, ®ion->info, sizeof(*pmem_info));
if (clear_active)
region->info.active = 0;
spin_unlock_irqrestore(&sync->pmem_frame_spinlock,
flags);
return 0;
}
}
/* After lookup failure, dump all the list entries... */
pr_err("%s, for pyaddr 0x%lx, pcbcraddr 0x%lx\n",
__func__, pyaddr, pcbcraddr);
hlist_for_each_entry_safe(region, node, n, &sync->pmem_frames, list) {
pr_err("listed pyaddr 0x%lx, pcbcraddr 0x%lx, active = %d",
(region->paddr + region->info.y_off),
(region->paddr + region->info.cbcr_off),
region->info.active);
}
spin_unlock_irqrestore(&sync->pmem_frame_spinlock, flags);
return -EINVAL;
}
static int msm_pmem_frame_ptov_lookup2(struct msm_sync *sync,
unsigned long pyaddr,
struct msm_pmem_info *pmem_info,
int clear_active)
{
struct msm_pmem_region *region;
struct hlist_node *node, *n;
unsigned long flags = 0;
spin_lock_irqsave(&sync->pmem_frame_spinlock, flags);
hlist_for_each_entry_safe(region, node, n, &sync->pmem_frames, list) {
if (pyaddr == (region->paddr + region->info.y_off) &&
region->info.active) {
/* offset since we could pass vaddr inside
* a registerd pmem buffer
*/
memcpy(pmem_info, ®ion->info, sizeof(*pmem_info));
if (clear_active)
region->info.active = 0;
spin_unlock_irqrestore(&sync->pmem_frame_spinlock,
flags);
return 0;
}
}
spin_unlock_irqrestore(&sync->pmem_frame_spinlock, flags);
return -EINVAL;
}
static unsigned long msm_pmem_stats_ptov_lookup(struct msm_sync *sync,
unsigned long addr, int *fd)
{
struct msm_pmem_region *region;
struct hlist_node *node, *n;
unsigned long flags = 0;
spin_lock_irqsave(&sync->pmem_stats_spinlock, flags);
hlist_for_each_entry_safe(region, node, n, &sync->pmem_stats, list) {
if (addr == region->paddr && region->info.active) {
/* offset since we could pass vaddr inside a
* registered pmem buffer */
*fd = region->info.fd;
region->info.active = 0;
spin_unlock_irqrestore(&sync->pmem_stats_spinlock,
flags);
return (unsigned long)(region->info.vaddr);
}
}
/* After lookup failure, dump all the list entries... */
pr_err("%s, for paddr 0x%lx\n",
__func__, addr);
hlist_for_each_entry_safe(region, node, n, &sync->pmem_stats, list) {
pr_err("listed paddr 0x%lx, active = %d",
region->paddr,
region->info.active);
}
spin_unlock_irqrestore(&sync->pmem_stats_spinlock, flags);
return 0;
}
static unsigned long msm_pmem_frame_vtop_lookup(struct msm_sync *sync,
unsigned long buffer,
uint32_t yoff, uint32_t cbcroff, int fd, int change_flag)
{
struct msm_pmem_region *region;
struct hlist_node *node, *n;
unsigned long flags = 0;
spin_lock_irqsave(&sync->pmem_frame_spinlock, flags);
hlist_for_each_entry_safe(region,
node, n, &sync->pmem_frames, list) {
if (((unsigned long)(region->info.vaddr) == buffer) &&
(region->info.y_off == yoff) &&
(region->info.cbcr_off == cbcroff) &&
(region->info.fd == fd) &&
(region->info.active == 0)) {
if (change_flag)
region->info.active = 1;
spin_unlock_irqrestore(&sync->pmem_frame_spinlock,
flags);
return region->paddr;
}
}
/* After lookup failure, dump all the list entries... */
pr_err("%s, failed for vaddr 0x%lx, yoff %d cbcroff %d\n",
__func__, buffer, yoff, cbcroff);
hlist_for_each_entry_safe(region, node, n, &sync->pmem_frames, list) {
pr_err("listed vaddr 0x%p, cbcroff %d, active = %d",
(region->info.vaddr),
(region->info.cbcr_off),
region->info.active);
}
spin_unlock_irqrestore(&sync->pmem_frame_spinlock, flags);
return 0;
}
static unsigned long msm_pmem_stats_vtop_lookup(
struct msm_sync *sync,
unsigned long buffer,
int fd)
{
struct msm_pmem_region *region;
struct hlist_node *node, *n;
unsigned long flags = 0;
spin_lock_irqsave(&sync->pmem_stats_spinlock, flags);
hlist_for_each_entry_safe(region, node, n, &sync->pmem_stats, list) {
if (((unsigned long)(region->info.vaddr) == buffer) &&
(region->info.fd == fd) &&
region->info.active == 0) {
region->info.active = 1;
spin_unlock_irqrestore(&sync->pmem_stats_spinlock,
flags);
return region->paddr;
}
}
/* After lookup failure, dump all the list entries... */
pr_err("%s, for vaddr %ld\n",
__func__, buffer);
hlist_for_each_entry_safe(region, node, n, &sync->pmem_stats, list) {
pr_err("listed vaddr 0x%p, active = %d",
region->info.vaddr,
region->info.active);
}
spin_unlock_irqrestore(&sync->pmem_stats_spinlock, flags);
return 0;
}
static int __msm_pmem_table_del(struct msm_sync *sync,
struct msm_pmem_info *pinfo)
{
int rc = 0;
struct msm_pmem_region *region;
struct hlist_node *node, *n;
unsigned long flags = 0;
switch (pinfo->type) {
case MSM_PMEM_VIDEO:
case MSM_PMEM_PREVIEW:
case MSM_PMEM_THUMBNAIL:
case MSM_PMEM_MAINIMG:
case MSM_PMEM_RAW_MAINIMG:
case MSM_PMEM_VIDEO_VPE:
case MSM_PMEM_C2D:
case MSM_PMEM_MAINIMG_VPE:
case MSM_PMEM_THUMBNAIL_VPE:
spin_lock_irqsave(&sync->pmem_frame_spinlock, flags);
hlist_for_each_entry_safe(region, node, n,
&sync->pmem_frames, list) {
if (pinfo->type == region->info.type &&
pinfo->vaddr == region->info.vaddr &&
pinfo->fd == region->info.fd) {
hlist_del(node);
put_pmem_file(region->file);
kfree(region);
CDBG("%s: type %d, vaddr 0x%p\n",
__func__, pinfo->type, pinfo->vaddr);
}
}
spin_unlock_irqrestore(&sync->pmem_frame_spinlock, flags);
break;
case MSM_PMEM_AEC_AWB:
case MSM_PMEM_AF:
spin_lock_irqsave(&sync->pmem_stats_spinlock, flags);
hlist_for_each_entry_safe(region, node, n,
&sync->pmem_stats, list) {
if (pinfo->type == region->info.type &&
pinfo->vaddr == region->info.vaddr &&
pinfo->fd == region->info.fd) {
hlist_del(node);
put_pmem_file(region->file);
kfree(region);
CDBG("%s: type %d, vaddr 0x%p\n",
__func__, pinfo->type, pinfo->vaddr);
}
}
spin_unlock_irqrestore(&sync->pmem_stats_spinlock, flags);
break;
default:
rc = -EINVAL;
break;
}
return rc;
}
static int msm_pmem_table_del(struct msm_sync *sync, void __user *arg)
{
struct msm_pmem_info info;
if (copy_from_user(&info, arg, sizeof(info))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
return __msm_pmem_table_del(sync, &info);
}
static int __msm_get_frame(struct msm_sync *sync,
struct msm_frame *frame)
{
int rc = 0;
struct msm_pmem_info pmem_info;
struct msm_queue_cmd *qcmd = NULL;
struct msm_vfe_resp *vdata;
struct msm_vfe_phy_info *pphy;
qcmd = msm_dequeue(&sync->frame_q, list_frame);
if (!qcmd) {
pr_err("%s: no preview frame.\n", __func__);
return -EAGAIN;
}
if ((!qcmd->command) && (qcmd->error_code & MSM_CAMERA_ERR_MASK)) {
frame->error_code = qcmd->error_code;
pr_err("%s: fake frame with camera error code = %d\n",
__func__, frame->error_code);
goto err;
}
vdata = (struct msm_vfe_resp *)(qcmd->command);
pphy = &vdata->phy;
/* HTC_START Glenn 20110721 For klockwork issue */
if (!pphy) {
rc = -EFAULT;
pr_err("%s: Avoid accessing NULL pointer!\n", __func__);
goto err;
}
/* HTC_END */
rc = msm_pmem_frame_ptov_lookup(sync,
pphy->y_phy,
pphy->cbcr_phy,
&pmem_info,
1); /* Clear the active flag */
if (rc < 0) {
pr_err("%s: cannot get frame, invalid lookup address "
"y %x cbcr %x\n",
__func__,
pphy->y_phy,
pphy->cbcr_phy);
goto err;
}
frame->ts = qcmd->ts;
frame->buffer = (unsigned long)pmem_info.vaddr;
frame->y_off = pmem_info.y_off;
frame->cbcr_off = pmem_info.cbcr_off;
frame->fd = pmem_info.fd;
frame->path = vdata->phy.output_id;
frame->frame_id = vdata->phy.frame_id;
CDBG("%s: y %x, cbcr %x, qcmd %x, virt_addr %x\n",
__func__,
pphy->y_phy, pphy->cbcr_phy, (int) qcmd, (int) frame->buffer);
err:
free_qcmd(qcmd);
return rc;
}
static int msm_get_frame(struct msm_sync *sync, void __user *arg)
{
int rc = 0;
struct msm_frame frame;
if (copy_from_user(&frame,
arg,
sizeof(struct msm_frame))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
rc = __msm_get_frame(sync, &frame);
if (rc < 0)
return rc;
mutex_lock(&sync->lock);
if (sync->croplen && (!sync->stereocam_enabled)) {
if (frame.croplen != sync->croplen) {
pr_err("%s: invalid frame croplen %d,"
"expecting %d\n",
__func__,
frame.croplen,
sync->croplen);
mutex_unlock(&sync->lock);
return -EINVAL;
}
if (copy_to_user((void *)frame.cropinfo,
sync->cropinfo,
sync->croplen)) {
ERR_COPY_TO_USER();
mutex_unlock(&sync->lock);
return -EFAULT;
}
}
if (sync->fdroiinfo.info) {
if (copy_to_user((void *)frame.roi_info.info,
sync->fdroiinfo.info,
sync->fdroiinfo.info_len)) {
ERR_COPY_TO_USER();
mutex_unlock(&sync->lock);
return -EFAULT;
}
}
if (sync->stereocam_enabled) {
frame.stcam_conv_value = sync->stcam_conv_value;
frame.stcam_quality_ind = sync->stcam_quality_ind;
}
if (copy_to_user((void *)arg,
&frame, sizeof(struct msm_frame))) {
ERR_COPY_TO_USER();
rc = -EFAULT;
}
mutex_unlock(&sync->lock);
CDBG("%s: got frame\n", __func__);
return rc;
}
static int msm_enable_vfe(struct msm_sync *sync, void __user *arg)
{
int rc = -EIO;
struct camera_enable_cmd cfg;
if (copy_from_user(&cfg,
arg,
sizeof(struct camera_enable_cmd))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
if (sync->vfefn.vfe_enable)
rc = sync->vfefn.vfe_enable(&cfg);
return rc;
}
static int msm_disable_vfe(struct msm_sync *sync, void __user *arg)
{
int rc = -EIO;
struct camera_enable_cmd cfg;
if (copy_from_user(&cfg,
arg,
sizeof(struct camera_enable_cmd))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
if (sync->vfefn.vfe_disable)
rc = sync->vfefn.vfe_disable(&cfg, NULL);
return rc;
}
static struct msm_queue_cmd *__msm_control(struct msm_sync *sync,
struct msm_device_queue *queue,
struct msm_queue_cmd *qcmd,
int timeout)
{
int rc;
int loop = 0;
unsigned long flags = 0;
// get the command type first - prevent NULL pointer after wait_event_interruptible_timeout
int16_t ignore_qcmd_type = (int16_t)((struct msm_ctrl_cmd *)
(qcmd->command))->type;
CDBG("Inside __msm_control\n");
if (sync->event_q.len <= 100 && sync->frame_q.len <= 100) {
/* wake up config thread */
msm_enqueue(&sync->event_q, &qcmd->list_config);
} else {
pr_err("%s, Error Queue limit exceeded e_q = %d, f_q = %d\n",
__func__, sync->event_q.len, sync->frame_q.len);
free_qcmd(qcmd);
return NULL;
}
if (!queue)
return NULL;
wait_event:
/* wait for config status */
CDBG("Waiting for config status \n");
rc = wait_event_interruptible_timeout(
queue->wait,
!list_empty_careful(&queue->list),
timeout);
CDBG("Waiting over for config status\n");
if (list_empty_careful(&queue->list)) {
if (!rc) {
rc = -ETIMEDOUT;
pr_err("%s: wait_event error %d\n", __func__, rc);
return ERR_PTR(rc);
}
else if (rc < 0) {
spin_lock_irqsave(&queue->wait_lock, flags);
if (sync->qcmd_done) {
pr_info("%s: qcmd_done, continue to wait\n",
__func__);
spin_unlock_irqrestore(&queue->wait_lock, flags);
goto wait_event;
} else if (rc == -512 && loop < 20) {
/* loop 20 times if rc is - 512,
* to avoid ignoring command */
spin_unlock_irqrestore(&queue->wait_lock,
flags);
loop++;
msleep(5);
pr_info("%s: wait_event err %d\n",
__func__, rc);
pr_info("in loop %d time\n", loop);
goto wait_event;
} else {
pr_info("%s: wait_event err %d\n",
__func__, rc);
pr_info("%s: ignore cmd %d\n",
__func__, ignore_qcmd_type);
if (msm_delete_entry(&sync->event_q,
list_config, qcmd)) {
sync->ignore_qcmd = true;
sync->ignore_qcmd_type = ignore_qcmd_type;
}
spin_unlock_irqrestore(&queue->wait_lock, flags);
return ERR_PTR(rc);
}
}
}
sync->qcmd_done = false;
qcmd = msm_dequeue(queue, list_control);
BUG_ON(!qcmd);
CDBG("__msm_control done \n");
return qcmd;
}
static struct msm_queue_cmd *__msm_control_nb(struct msm_sync *sync,
struct msm_queue_cmd *qcmd_to_copy)
{
/* Since this is a non-blocking command, we cannot use qcmd_to_copy and
* its data, since they are on the stack. We replicate them on the heap
* and mark them on_heap so that they get freed when the config thread
* dequeues them.
*/
struct msm_ctrl_cmd *udata;
struct msm_ctrl_cmd *udata_to_copy = qcmd_to_copy->command;
struct msm_queue_cmd *qcmd =
kmalloc(sizeof(*qcmd_to_copy) +
sizeof(*udata_to_copy) +
udata_to_copy->length,
GFP_KERNEL);
if (!qcmd) {
pr_err("%s: out of memory\n", __func__);
return ERR_PTR(-ENOMEM);
}
*qcmd = *qcmd_to_copy;
udata = qcmd->command = qcmd + 1;
memcpy(udata, udata_to_copy, sizeof(*udata));
udata->value = udata + 1;
memcpy(udata->value, udata_to_copy->value, udata_to_copy->length);
atomic_set(&qcmd->on_heap, 1);
/* qcmd_resp will be set to NULL */
return __msm_control(sync, NULL, qcmd, 0);
}
static int msm_control(struct msm_control_device *ctrl_pmsm,
int block,
void __user *arg)
{
int rc = 0;
struct msm_sync *sync = ctrl_pmsm->pmsm->sync;
void __user *uptr;
struct msm_ctrl_cmd udata_resp;
struct msm_queue_cmd *qcmd_resp = NULL;
uint8_t data[max_control_command_size];
struct msm_ctrl_cmd *udata;
struct msm_queue_cmd *qcmd =
kmalloc(sizeof(struct msm_queue_cmd) +
sizeof(struct msm_ctrl_cmd), GFP_ATOMIC);
if (!qcmd) {
pr_err("%s: out of memory\n", __func__);
return -ENOMEM;
}
udata = (struct msm_ctrl_cmd *)(qcmd + 1);
atomic_set(&(qcmd->on_heap), 1);
CDBG("Inside msm_control\n");
if (copy_from_user(udata, arg, sizeof(struct msm_ctrl_cmd))) {
ERR_COPY_FROM_USER();
rc = -EFAULT;
goto end;
}
uptr = udata->value;
udata->value = data;
qcmd->type = MSM_CAM_Q_CTRL;
qcmd->command = udata;
if (udata->length) {
if (udata->length > sizeof(data)) {
pr_err("%s: user data too large (%d, max is %d)\n",
__func__,
udata->length,
sizeof(data));
rc = -EIO;
goto end;
}
if (copy_from_user(udata->value, uptr, udata->length)) {
ERR_COPY_FROM_USER();
rc = -EFAULT;
goto end;
}
}
if (unlikely(!block)) {
qcmd_resp = __msm_control_nb(sync, qcmd);
goto end;
}
qcmd_resp = __msm_control(sync,
&ctrl_pmsm->ctrl_q,
qcmd, msecs_to_jiffies(10000));
/* ownership of qcmd will be transfered to event queue */
qcmd = NULL;
if (!qcmd_resp || IS_ERR(qcmd_resp)) {
/* Do not free qcmd_resp here. If the config thread read it,
* then it has already been freed, and we timed out because
* we did not receive a MSM_CAM_IOCTL_CTRL_CMD_DONE. If the
* config thread itself is blocked and not dequeueing commands,
* then it will either eventually unblock and process them,
* or when it is killed, qcmd will be freed in
* msm_release_config.
*/
rc = PTR_ERR(qcmd_resp);
qcmd_resp = NULL;
goto end;
}
if (qcmd_resp->command) {
udata_resp = *(struct msm_ctrl_cmd *)qcmd_resp->command;
if (udata_resp.length > 0) {
if (copy_to_user(uptr,
udata_resp.value,
udata_resp.length)) {
ERR_COPY_TO_USER();
rc = -EFAULT;
goto end;
}
}
udata_resp.value = uptr;
if (copy_to_user((void *)arg, &udata_resp,
sizeof(struct msm_ctrl_cmd))) {
ERR_COPY_TO_USER();
rc = -EFAULT;
goto end;
}
}
end:
free_qcmd(qcmd);
CDBG("%s: done rc = %d\n", __func__, rc);
return rc;
}
/* Divert frames for post-processing by delivering them to the config thread;
* when post-processing is done, it will return the frame to the frame thread.
*/
static int msm_divert_frame(struct msm_sync *sync,
struct msm_vfe_resp *data,
struct msm_stats_event_ctrl *se)
{
struct msm_pmem_info pinfo;
struct msm_postproc buf;
int rc;
CDBG("%s: Frame PP sync->pp_mask %d\n", __func__, sync->pp_mask);
if (!(sync->pp_mask & PP_PREV) && !(sync->pp_mask & PP_SNAP)) {
pr_err("%s: diverting frame, not in PP_PREV or PP_SNAP!\n",
__func__);
return -EINVAL;
}
rc = msm_pmem_frame_ptov_lookup(sync, data->phy.y_phy,
data->phy.cbcr_phy, &pinfo,
0); /* do not clear the active flag */
if (rc < 0) {
pr_err("%s: msm_pmem_frame_ptov_lookup failed\n", __func__);
return rc;
}
buf.fmain.buffer = (unsigned long)pinfo.vaddr;
buf.fmain.y_off = pinfo.y_off;
buf.fmain.cbcr_off = pinfo.cbcr_off;
buf.fmain.fd = pinfo.fd;
CDBG("%s: buf 0x%x fd %d\n", __func__, (unsigned int)buf.fmain.buffer,
buf.fmain.fd);
if (copy_to_user((void *)(se->stats_event.data),
&(buf.fmain), sizeof(struct msm_frame))) {
ERR_COPY_TO_USER();
return -EFAULT;
}
return 0;
}
/* Divert stereo frames for post-processing by delivering
* them to the config thread.
*/
static int msm_divert_st_frame(struct msm_sync *sync,
struct msm_vfe_resp *data, struct msm_stats_event_ctrl *se, int path)
{
struct msm_pmem_info pinfo;
struct msm_st_frame buf;
struct video_crop_t *crop = NULL;
int rc = 0;
/* HTC_START Glenn 20110721 For klockwork issue */
memset(&pinfo, 0x00, sizeof(struct msm_pmem_info));
memset(&buf, 0x00, sizeof(struct msm_st_frame));
/* HTC_END */
if (se->stats_event.msg_id == OUTPUT_TYPE_ST_L) {
buf.type = OUTPUT_TYPE_ST_L;
} else if (se->stats_event.msg_id == OUTPUT_TYPE_ST_R) {
buf.type = OUTPUT_TYPE_ST_R;
} else {
if (se->resptype == MSM_CAM_RESP_STEREO_OP_1) {
rc = msm_pmem_frame_ptov_lookup(sync, data->phy.y_phy,
data->phy.cbcr_phy, &pinfo,
1); /* do clear the active flag */
buf.buf_info.path = path;
} else if (se->resptype == MSM_CAM_RESP_STEREO_OP_2) {
rc = msm_pmem_frame_ptov_lookup(sync, data->phy.y_phy,
data->phy.cbcr_phy, &pinfo,
0); /* do not clear the active flag */
buf.buf_info.path = path;
} else
pr_err("%s: Invalid resptype = %d\n", __func__,
se->resptype);
if (rc < 0) {
pr_err("%s: msm_pmem_frame_ptov_lookup failed\n",
__func__);
return rc;
}
buf.type = OUTPUT_TYPE_ST_D;
if (sync->cropinfo != NULL) {
crop = sync->cropinfo;
switch (path) {
case OUTPUT_TYPE_P:
case OUTPUT_TYPE_T: {
buf.L.stCropInfo.in_w = crop->in1_w;
buf.L.stCropInfo.in_h = crop->in1_h;
buf.L.stCropInfo.out_w = crop->out1_w;
buf.L.stCropInfo.out_h = crop->out1_h;
buf.R.stCropInfo = buf.L.stCropInfo;
break;
}
case OUTPUT_TYPE_V:
case OUTPUT_TYPE_S: {
buf.L.stCropInfo.in_w = crop->in2_w;
buf.L.stCropInfo.in_h = crop->in2_h;
buf.L.stCropInfo.out_w = crop->out2_w;
buf.L.stCropInfo.out_h = crop->out2_h;
buf.R.stCropInfo = buf.L.stCropInfo;
break;
}
default: {
pr_warning("%s: invalid frame path %d\n",
__func__, path);
break;
}
}
} else {
buf.L.stCropInfo.in_w = 0;
buf.L.stCropInfo.in_h = 0;
buf.L.stCropInfo.out_w = 0;
buf.L.stCropInfo.out_h = 0;
buf.R.stCropInfo = buf.L.stCropInfo;
}
/* hardcode for now. */
if ((path == OUTPUT_TYPE_S) || (path == OUTPUT_TYPE_T))
buf.packing = sync->sctrl.s_snap_packing;
else
buf.packing = sync->sctrl.s_video_packing;
buf.buf_info.buffer = (unsigned long)pinfo.vaddr;
buf.buf_info.phy_offset = pinfo.offset;
buf.buf_info.y_off = pinfo.y_off;
buf.buf_info.cbcr_off = pinfo.cbcr_off;
buf.buf_info.fd = pinfo.fd;
CDBG("%s: buf 0x%x fd %d\n", __func__,
(unsigned int)buf.buf_info.buffer, buf.buf_info.fd);
}
if (copy_to_user((void *)(se->stats_event.data),
&buf, sizeof(struct msm_st_frame))) {
ERR_COPY_TO_USER();
return -EFAULT;
}
return 0;
}
static int msm_get_stats(struct msm_sync *sync, void __user *arg)
{
int rc = 0;
struct msm_stats_event_ctrl se;
struct msm_queue_cmd *qcmd = NULL;
struct msm_ctrl_cmd *ctrl = NULL;
struct msm_vfe_resp *data = NULL;
struct msm_vpe_resp *vpe_data = NULL;
struct msm_stats_buf stats;
if (copy_from_user(&se, arg,
sizeof(struct msm_stats_event_ctrl))) {
ERR_COPY_FROM_USER();
pr_err("%s, ERR_COPY_FROM_USER\n", __func__);
return -EFAULT;
}
rc = 0;
qcmd = msm_dequeue(&sync->event_q, list_config);
if (!qcmd) {
/* Should be associated with wait_event
error -512 from __msm_control*/
pr_err("%s, qcmd is Null\n", __func__);
rc = -ETIMEDOUT;
return rc;
}
CDBG("%s: received from DSP %d\n", __func__, qcmd->type);
switch (qcmd->type) {
case MSM_CAM_Q_VPE_MSG:
/* Complete VPE response. */
vpe_data = (struct msm_vpe_resp *)(qcmd->command);
se.resptype = MSM_CAM_RESP_STEREO_OP_2;
se.stats_event.type = vpe_data->evt_msg.type;
se.stats_event.msg_id = vpe_data->evt_msg.msg_id;
se.stats_event.len = vpe_data->evt_msg.len;
if (vpe_data->type == VPE_MSG_OUTPUT_ST_L) {
CDBG("%s: Change msg_id to OUTPUT_TYPE_ST_L\n",
__func__);
se.stats_event.msg_id = OUTPUT_TYPE_ST_L;
rc = msm_divert_st_frame(sync, data, &se,
OUTPUT_TYPE_V);
} else if (vpe_data->type == VPE_MSG_OUTPUT_ST_R) {
CDBG("%s: Change msg_id to OUTPUT_TYPE_ST_R\n",
__func__);
se.stats_event.msg_id = OUTPUT_TYPE_ST_R;
rc = msm_divert_st_frame(sync, data, &se,
OUTPUT_TYPE_V);
} else {
pr_warning("%s: invalid vpe_data->type = %d\n",
__func__, vpe_data->type);
}
break;
case MSM_CAM_Q_VFE_EVT:
case MSM_CAM_Q_VFE_MSG:
data = (struct msm_vfe_resp *)(qcmd->command);
/* adsp event and message */
se.resptype = MSM_CAM_RESP_STAT_EVT_MSG;
/* 0 - msg from aDSP, 1 - event from mARM */
se.stats_event.type = data->evt_msg.type;
se.stats_event.msg_id = data->evt_msg.msg_id;
se.stats_event.len = data->evt_msg.len;
se.stats_event.frame_id = data->evt_msg.frame_id;
CDBG("%s: qcmd->type %d length %d msd_id %d\n", __func__,
qcmd->type,
se.stats_event.len,
se.stats_event.msg_id);
if ((data->type >= VFE_MSG_STATS_AEC) &&
(data->type <= VFE_MSG_STATS_WE)) {
/* the check above includes all stats type. */
stats.buffer =
msm_pmem_stats_ptov_lookup(sync,
data->phy.sbuf_phy,
&(stats.fd));
if (!stats.buffer) {
pr_err("%s: msm_pmem_stats_ptov_lookup error\n",
__func__);
rc = -EINVAL;
goto failure;
}
if (copy_to_user((void *)(se.stats_event.data),
&stats,
sizeof(struct msm_stats_buf))) {
ERR_COPY_TO_USER();
rc = -EFAULT;
goto failure;
}
} else if ((data->evt_msg.len > 0) &&
(data->type == VFE_MSG_GENERAL)) {
if (copy_to_user((void *)(se.stats_event.data),
data->evt_msg.data,
data->evt_msg.len)) {
ERR_COPY_TO_USER();
rc = -EFAULT;
goto failure;
}
} else {
if (sync->stereocam_enabled) {
if (data->type == VFE_MSG_OUTPUT_P) {
CDBG("%s: Preview mark as st op 1\n",
__func__);
se.resptype = MSM_CAM_RESP_STEREO_OP_1;
rc = msm_divert_st_frame(sync, data,
&se, OUTPUT_TYPE_P);
break;
} else if (data->type == VFE_MSG_OUTPUT_V) {
CDBG("%s: Video mark as st op 2\n",
__func__);
se.resptype = MSM_CAM_RESP_STEREO_OP_2;
rc = msm_divert_st_frame(sync, data,
&se, OUTPUT_TYPE_V);
break;
} else if (data->type == VFE_MSG_OUTPUT_S) {
pr_err("%s: Main img mark as st op 2\n",
__func__);
se.resptype = MSM_CAM_RESP_STEREO_OP_2;
rc = msm_divert_st_frame(sync, data,
&se, OUTPUT_TYPE_S);
break;
} else if (data->type == VFE_MSG_OUTPUT_T) {
pr_err("%s: Thumb img mark as st op 2\n",
__func__);
se.resptype = MSM_CAM_RESP_STEREO_OP_2;
rc = msm_divert_st_frame(sync, data,
&se, OUTPUT_TYPE_T);
break;
} else
CDBG("%s: VFE_MSG Fall Through\n",
__func__);
}
if ((sync->pp_frame_avail == 1) &&
(sync->pp_mask & PP_PREV) &&
(data->type == VFE_MSG_OUTPUT_P)) {
CDBG("%s:%d:preiew PP\n",
__func__, __LINE__);
rc = msm_divert_frame(sync, data, &se);
sync->pp_frame_avail = 0;
} else {
if ((sync->pp_mask & PP_PREV) &&
(data->type == VFE_MSG_OUTPUT_P)) {
free_qcmd(qcmd);
return 0;
} else
CDBG("%s:indication type is %d\n",
__func__, data->type);
}
if (sync->pp_mask & PP_SNAP)
if (data->type == VFE_MSG_OUTPUT_S ||
data->type == VFE_MSG_OUTPUT_T)
rc = msm_divert_frame(sync, data, &se);
}
break;
case MSM_CAM_Q_CTRL:
/* control command from control thread */
ctrl = (struct msm_ctrl_cmd *)(qcmd->command);
CDBG("%s: qcmd->type %d length %d\n", __func__,
qcmd->type, ctrl->length);
if (ctrl->length > 0) {
if (copy_to_user((void *)(se.ctrl_cmd.value),
ctrl->value,
ctrl->length)) {
ERR_COPY_TO_USER();
rc = -EFAULT;
goto failure;
}
}
se.resptype = MSM_CAM_RESP_CTRL;
/* what to control */
se.ctrl_cmd.type = ctrl->type;
se.ctrl_cmd.length = ctrl->length;
se.ctrl_cmd.resp_fd = ctrl->resp_fd;
break;
case MSM_CAM_Q_V4L2_REQ:
/* control command from v4l2 client */
ctrl = (struct msm_ctrl_cmd *)(qcmd->command);
if (ctrl->length > 0) {
if (copy_to_user((void *)(se.ctrl_cmd.value),
ctrl->value, ctrl->length)) {
ERR_COPY_TO_USER();
rc = -EFAULT;
goto failure;
}
}
/* 2 tells config thread this is v4l2 request */
se.resptype = MSM_CAM_RESP_V4L2;
/* what to control */
se.ctrl_cmd.type = ctrl->type;
se.ctrl_cmd.length = ctrl->length;
break;
default:
rc = -EFAULT;
goto failure;
} /* switch qcmd->type */
if (copy_to_user((void *)arg, &se, sizeof(se))) {
ERR_COPY_TO_USER();
rc = -EFAULT;
goto failure;
}
failure:
free_qcmd(qcmd);
CDBG("%s: %d\n", __func__, rc);
return rc;
}
static int msm_ctrl_cmd_done(struct msm_control_device *ctrl_pmsm,
void __user *arg)
{
void __user *uptr;
struct msm_queue_cmd *qcmd = &ctrl_pmsm->qcmd;
struct msm_ctrl_cmd *command = &ctrl_pmsm->ctrl;
unsigned long flags = 0;
struct msm_device_queue *queue = &ctrl_pmsm->ctrl_q;
if (copy_from_user(command, arg, sizeof(*command))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
atomic_set(&qcmd->on_heap, 0);
qcmd->command = command;
uptr = command->value;
if (command->length > 0) {
command->value = ctrl_pmsm->ctrl_data;
if (command->length > sizeof(ctrl_pmsm->ctrl_data)) {
pr_err("%s: user data %d is too big (max %d)\n",
__func__, command->length,
sizeof(ctrl_pmsm->ctrl_data));
return -EINVAL;
}
if (copy_from_user(command->value,
uptr,
command->length)) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
} else
command->value = NULL;
spin_lock_irqsave(&queue->wait_lock, flags);
/* wake up control thread */
/*msm_enqueue(&ctrl_pmsm->ctrl_q, &qcmd->list_control);*/
/* Ignore the command if the ctrl cmd has
return back due to signaling */
/* Should be associated with wait_event
error -512 from __msm_control*/
if (ctrl_pmsm->pmsm->sync->ignore_qcmd == true &&
ctrl_pmsm->pmsm->sync->ignore_qcmd_type == (int16_t)command->type) {
printk("%s: ignore this command %d\n", __func__, command->type);
ctrl_pmsm->pmsm->sync->ignore_qcmd = false;
ctrl_pmsm->pmsm->sync->ignore_qcmd_type = -1;
spin_unlock_irqrestore(&queue->wait_lock, flags);
} else /* wake up control thread */{
ctrl_pmsm->pmsm->sync->qcmd_done = true;
spin_unlock_irqrestore(&queue->wait_lock, flags);
msm_enqueue(&ctrl_pmsm->ctrl_q, &qcmd->list_control);
}
return 0;
}
static int msm_config_vpe(struct msm_sync *sync, void __user *arg)
{
struct msm_vpe_cfg_cmd cfgcmd;
if (copy_from_user(&cfgcmd, arg, sizeof(cfgcmd))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
CDBG("%s: cmd_type %s\n", __func__, vfe_config_cmd[cfgcmd.cmd_type]);
switch (cfgcmd.cmd_type) {
case CMD_VPE:
return sync->vpefn.vpe_config(&cfgcmd, NULL);
default:
pr_err("%s: unknown command type %d\n",
__func__, cfgcmd.cmd_type);
}
return -EINVAL;
}
static int msm_config_vfe(struct msm_sync *sync, void __user *arg)
{
struct msm_vfe_cfg_cmd cfgcmd;
struct msm_pmem_region region[8];
struct axidata axi_data;
if (!sync->vfefn.vfe_config) {
pr_err("%s: no vfe_config!\n", __func__);
return -EIO;
}
if (copy_from_user(&cfgcmd, arg, sizeof(cfgcmd))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
memset(&axi_data, 0, sizeof(axi_data));
CDBG("%s: cmd_type %s\n", __func__, vfe_config_cmd[cfgcmd.cmd_type]);
switch (cfgcmd.cmd_type) {
case CMD_STATS_ENABLE:
axi_data.bufnum1 =
msm_pmem_region_lookup(&sync->pmem_stats,
MSM_PMEM_AEC_AWB, ®ion[0],
NUM_STAT_OUTPUT_BUFFERS,
&sync->pmem_stats_spinlock);
axi_data.bufnum2 =
msm_pmem_region_lookup(&sync->pmem_stats,
MSM_PMEM_AF, ®ion[axi_data.bufnum1],
NUM_STAT_OUTPUT_BUFFERS,
&sync->pmem_stats_spinlock);
if (!axi_data.bufnum1 || !axi_data.bufnum2) {
pr_err("%s: pmem region lookup error\n", __func__);
return -EINVAL;
}
axi_data.region = ®ion[0];
return sync->vfefn.vfe_config(&cfgcmd, &axi_data);
case CMD_STATS_AF_ENABLE:
axi_data.bufnum1 =
msm_pmem_region_lookup(&sync->pmem_stats,
MSM_PMEM_AF, ®ion[0],
NUM_STAT_OUTPUT_BUFFERS,
&sync->pmem_stats_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
axi_data.region = ®ion[0];
return sync->vfefn.vfe_config(&cfgcmd, &axi_data);
case CMD_STATS_AEC_AWB_ENABLE:
axi_data.bufnum1 =
msm_pmem_region_lookup(&sync->pmem_stats,
MSM_PMEM_AEC_AWB, ®ion[0],
NUM_STAT_OUTPUT_BUFFERS,
&sync->pmem_stats_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
axi_data.region = ®ion[0];
return sync->vfefn.vfe_config(&cfgcmd, &axi_data);
case CMD_STATS_AEC_ENABLE:
axi_data.bufnum1 =
msm_pmem_region_lookup(&sync->pmem_stats,
MSM_PMEM_AEC, ®ion[0],
NUM_STAT_OUTPUT_BUFFERS,
&sync->pmem_stats_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
axi_data.region = ®ion[0];
return sync->vfefn.vfe_config(&cfgcmd, &axi_data);
case CMD_STATS_AWB_ENABLE:
axi_data.bufnum1 =
msm_pmem_region_lookup(&sync->pmem_stats,
MSM_PMEM_AWB, ®ion[0],
NUM_STAT_OUTPUT_BUFFERS,
&sync->pmem_stats_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
axi_data.region = ®ion[0];
return sync->vfefn.vfe_config(&cfgcmd, &axi_data);
case CMD_STATS_IHIST_ENABLE:
axi_data.bufnum1 =
msm_pmem_region_lookup(&sync->pmem_stats,
MSM_PMEM_IHIST, ®ion[0],
NUM_STAT_OUTPUT_BUFFERS,
&sync->pmem_stats_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
axi_data.region = ®ion[0];
return sync->vfefn.vfe_config(&cfgcmd, &axi_data);
case CMD_STATS_RS_ENABLE:
axi_data.bufnum1 =
msm_pmem_region_lookup(&sync->pmem_stats,
MSM_PMEM_RS, ®ion[0],
NUM_STAT_OUTPUT_BUFFERS,
&sync->pmem_stats_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
axi_data.region = ®ion[0];
return sync->vfefn.vfe_config(&cfgcmd, &axi_data);
case CMD_STATS_CS_ENABLE:
axi_data.bufnum1 =
msm_pmem_region_lookup(&sync->pmem_stats,
MSM_PMEM_CS, ®ion[0],
NUM_STAT_OUTPUT_BUFFERS,
&sync->pmem_stats_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
axi_data.region = ®ion[0];
return sync->vfefn.vfe_config(&cfgcmd, &axi_data);
case CMD_GENERAL:
case CMD_STATS_DISABLE:
return sync->vfefn.vfe_config(&cfgcmd, NULL);
default:
pr_err("%s: unknown command type %d\n",
__func__, cfgcmd.cmd_type);
}
return -EINVAL;
}
static int msm_vpe_frame_cfg(struct msm_sync *sync,
void *cfgcmdin)
{
int rc = -EIO;
struct axidata axi_data;
void *data = &axi_data;
struct msm_pmem_region region[8];
int pmem_type;
struct msm_vpe_cfg_cmd *cfgcmd;
cfgcmd = (struct msm_vpe_cfg_cmd *)cfgcmdin;
memset(&axi_data, 0, sizeof(axi_data));
CDBG("In vpe_frame_cfg cfgcmd->cmd_type = %s\n",
vfe_config_cmd[cfgcmd->cmd_type]);
switch (cfgcmd->cmd_type) {
case CMD_AXI_CFG_VPE:
pmem_type = MSM_PMEM_VIDEO_VPE;
axi_data.bufnum1 =
msm_pmem_region_lookup_2(&sync->pmem_frames, pmem_type,
®ion[0], 8, &sync->pmem_frame_spinlock);
CDBG("axi_data.bufnum1 = %d\n", axi_data.bufnum1);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
pmem_type = MSM_PMEM_VIDEO;
break;
case CMD_AXI_CFG_SNAP_THUMB_VPE:
CDBG("%s: CMD_AXI_CFG_SNAP_THUMB_VPE", __func__);
pmem_type = MSM_PMEM_THUMBNAIL_VPE;
axi_data.bufnum1 =
msm_pmem_region_lookup(&sync->pmem_frames, pmem_type,
®ion[0], 8, &sync->pmem_frame_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s: THUMBNAIL_VPE pmem region lookup error\n",
__func__);
return -EINVAL;
}
break;
case CMD_AXI_CFG_SNAP_VPE:
CDBG("%s: CMD_AXI_CFG_SNAP_VPE", __func__);
pmem_type = MSM_PMEM_MAINIMG_VPE;
axi_data.bufnum1 =
msm_pmem_region_lookup(&sync->pmem_frames, pmem_type,
®ion[0], 8, &sync->pmem_frame_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s: MAINIMG_VPE pmem region lookup error\n",
__func__);
return -EINVAL;
}
break;
default:
pr_err("%s: unknown command type %d\n",
__func__, cfgcmd->cmd_type);
break;
}
axi_data.region = ®ion[0];
CDBG("out vpe_frame_cfg cfgcmd->cmd_type = %s\n",
vfe_config_cmd[cfgcmd->cmd_type]);
/* send the AXI configuration command to driver */
if (sync->vpefn.vpe_config)
rc = sync->vpefn.vpe_config(cfgcmd, data);
return rc;
}
static int msm_frame_axi_cfg(struct msm_sync *sync,
struct msm_vfe_cfg_cmd *cfgcmd)
{
int rc = -EIO;
struct axidata axi_data;
void *data = &axi_data;
/* HTC Glenn 20110721 For klockwork issue */
struct msm_pmem_region region[MAX_PMEM_CFG_BUFFERS + 1];
int pmem_type;
memset(&axi_data, 0, sizeof(axi_data));
switch (cfgcmd->cmd_type) {
case CMD_AXI_CFG_PREVIEW:
pmem_type = MSM_PMEM_PREVIEW;
axi_data.bufnum2 =
msm_pmem_region_lookup(&sync->pmem_frames, pmem_type,
®ion[0], MAX_PMEM_CFG_BUFFERS,
&sync->pmem_frame_spinlock);
if (!axi_data.bufnum2) {
pr_err("%s %d: pmem region lookup error (empty %d)\n",
__func__, __LINE__,
hlist_empty(&sync->pmem_frames));
return -EINVAL;
}
break;
case CMD_AXI_CFG_VIDEO:
pmem_type = MSM_PMEM_PREVIEW;
axi_data.bufnum1 =
msm_pmem_region_lookup(&sync->pmem_frames, pmem_type,
®ion[0], MAX_PMEM_CFG_BUFFERS,
&sync->pmem_frame_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
pmem_type = MSM_PMEM_VIDEO;
axi_data.bufnum2 =
msm_pmem_region_lookup(&sync->pmem_frames, pmem_type,
®ion[axi_data.bufnum1],
(MAX_PMEM_CFG_BUFFERS-(axi_data.bufnum1)),
&sync->pmem_frame_spinlock);
if (!axi_data.bufnum2) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
break;
case CMD_AXI_CFG_SNAP:
CDBG("%s, CMD_AXI_CFG_SNAP, type=%d\n", __func__,
cfgcmd->cmd_type);
pmem_type = MSM_PMEM_THUMBNAIL;
axi_data.bufnum1 =
msm_pmem_region_lookup(&sync->pmem_frames, pmem_type,
®ion[0], MAX_PMEM_CFG_BUFFERS,
&sync->pmem_frame_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
pmem_type = MSM_PMEM_MAINIMG;
axi_data.bufnum2 =
msm_pmem_region_lookup(&sync->pmem_frames, pmem_type,
®ion[axi_data.bufnum1],
(MAX_PMEM_CFG_BUFFERS-(axi_data.bufnum1)),
&sync->pmem_frame_spinlock);
if (!axi_data.bufnum2) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
break;
case CMD_AXI_CFG_ZSL:
CDBG("%s, CMD_AXI_CFG_ZSL, type = %d\n", __func__,
cfgcmd->cmd_type);
pmem_type = MSM_PMEM_PREVIEW;
axi_data.bufnum1 =
msm_pmem_region_lookup(&sync->pmem_frames, pmem_type,
®ion[0], MAX_PMEM_CFG_BUFFERS,
&sync->pmem_frame_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
pmem_type = MSM_PMEM_THUMBNAIL;
axi_data.bufnum2 =
msm_pmem_region_lookup(&sync->pmem_frames, pmem_type,
®ion[axi_data.bufnum1],
(MAX_PMEM_CFG_BUFFERS-(axi_data.bufnum1)),
&sync->pmem_frame_spinlock);
if (!axi_data.bufnum2) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
pmem_type = MSM_PMEM_MAINIMG;
axi_data.bufnum3 =
msm_pmem_region_lookup(&sync->pmem_frames, pmem_type,
®ion[axi_data.bufnum1 + axi_data.bufnum2],
(MAX_PMEM_CFG_BUFFERS - axi_data.bufnum1 -
axi_data.bufnum2), &sync->pmem_frame_spinlock);
if (!axi_data.bufnum3) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
break;
case CMD_RAW_PICT_AXI_CFG:
pmem_type = MSM_PMEM_RAW_MAINIMG;
axi_data.bufnum2 =
msm_pmem_region_lookup(&sync->pmem_frames, pmem_type,
®ion[0], MAX_PMEM_CFG_BUFFERS,
&sync->pmem_frame_spinlock);
if (!axi_data.bufnum2) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
break;
case CMD_GENERAL:
data = NULL;
break;
default:
pr_err("%s: unknown command type %d\n",
__func__, cfgcmd->cmd_type);
return -EINVAL;
}
axi_data.region = ®ion[0];
/* send the AXI configuration command to driver */
if (sync->vfefn.vfe_config)
rc = sync->vfefn.vfe_config(cfgcmd, data);
return rc;
}
static int msm_get_sensor_info(struct msm_sync *sync, void __user *arg)
{
int rc = 0;
struct msm_camsensor_info info;
struct msm_camera_sensor_info *sdata;
if (copy_from_user(&info,
arg,
sizeof(struct msm_camsensor_info))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
sdata = sync->pdev->dev.platform_data;
if (sync->sctrl.s_camera_type == BACK_CAMERA_3D)
info.support_3d = true;
else
info.support_3d = false;
memcpy(&info.name[0],
sdata->sensor_name,
MAX_SENSOR_NAME);
info.flash_enabled = sdata->flash_data->flash_type !=
MSM_CAMERA_FLASH_NONE;
/* copy back to user space */
if (copy_to_user((void *)arg,
&info,
sizeof(struct msm_camsensor_info))) {
ERR_COPY_TO_USER();
rc = -EFAULT;
}
return rc;
}
static int msm_get_camera_info(void __user *arg)
{
int rc = 0;
int i = 0;
struct msm_camera_info info;
if (copy_from_user(&info, arg, sizeof(struct msm_camera_info))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
CDBG("%s: camera_node %d\n", __func__, camera_node);
info.num_cameras = camera_node;
for (i = 0; i < camera_node; i++) {
info.has_3d_support[i] = 0;
info.is_internal_cam[i] = 0;
info.s_mount_angle[i] = sensor_mount_angle[i];
switch (camera_type[i]) {
case FRONT_CAMERA_2D:
info.is_internal_cam[i] = 1;
break;
case BACK_CAMERA_3D:
info.has_3d_support[i] = 1;
break;
case BACK_CAMERA_2D:
default:
break;
}
}
/* copy back to user space */
if (copy_to_user((void *)arg, &info, sizeof(struct msm_camera_info))) {
ERR_COPY_TO_USER();
rc = -EFAULT;
}
return rc;
}
static int __msm_put_frame_buf(struct msm_sync *sync,
struct msm_frame *pb)
{
unsigned long pphy;
struct msm_vfe_cfg_cmd cfgcmd;
int rc = -EIO;
/* Change the active flag. */
pphy = msm_pmem_frame_vtop_lookup(sync,
pb->buffer,
pb->y_off, pb->cbcr_off, pb->fd, 1);
if (pphy != 0) {
CDBG("%s: rel: vaddr %lx, paddr %lx\n",
__func__,
pb->buffer, pphy);
cfgcmd.cmd_type = CMD_FRAME_BUF_RELEASE;
cfgcmd.value = (void *)pb;
if (sync->vfefn.vfe_config)
rc = sync->vfefn.vfe_config(&cfgcmd, &pphy);
} else {
pr_err("%s: msm_pmem_frame_vtop_lookup failed\n",
__func__);
rc = -EINVAL;
}
return rc;
}
static int __msm_put_pic_buf(struct msm_sync *sync,
struct msm_frame *pb)
{
unsigned long pphy;
struct msm_vfe_cfg_cmd cfgcmd;
int rc = -EIO;
pphy = msm_pmem_frame_vtop_lookup(sync,
pb->buffer,
pb->y_off, pb->cbcr_off, pb->fd, 1);
if (pphy != 0) {
CDBG("%s: rel: vaddr %lx, paddr %lx\n",
__func__,
pb->buffer, pphy);
cfgcmd.cmd_type = CMD_SNAP_BUF_RELEASE;
cfgcmd.value = (void *)pb;
if (sync->vfefn.vfe_config)
rc = sync->vfefn.vfe_config(&cfgcmd, &pphy);
} else {
pr_err("%s: msm_pmem_frame_vtop_lookup failed\n",
__func__);
rc = -EINVAL;
}
return rc;
}
static int msm_put_frame_buffer(struct msm_sync *sync, void __user *arg)
{
struct msm_frame buf_t;
if (copy_from_user(&buf_t,
arg,
sizeof(struct msm_frame))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
return __msm_put_frame_buf(sync, &buf_t);
}
static int msm_put_pic_buffer(struct msm_sync *sync, void __user *arg)
{
struct msm_frame buf_t;
if (copy_from_user(&buf_t,
arg,
sizeof(struct msm_frame))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
return __msm_put_pic_buf(sync, &buf_t);
}
static int __msm_register_pmem(struct msm_sync *sync,
struct msm_pmem_info *pinfo)
{
int rc = 0;
switch (pinfo->type) {
case MSM_PMEM_VIDEO:
case MSM_PMEM_PREVIEW:
case MSM_PMEM_THUMBNAIL:
case MSM_PMEM_MAINIMG:
case MSM_PMEM_RAW_MAINIMG:
case MSM_PMEM_VIDEO_VPE:
case MSM_PMEM_C2D:
case MSM_PMEM_MAINIMG_VPE:
case MSM_PMEM_THUMBNAIL_VPE:
rc = msm_pmem_table_add(&sync->pmem_frames, pinfo,
&sync->pmem_frame_spinlock, sync);
break;
case MSM_PMEM_AEC_AWB:
case MSM_PMEM_AF:
case MSM_PMEM_AEC:
case MSM_PMEM_AWB:
case MSM_PMEM_RS:
case MSM_PMEM_CS:
case MSM_PMEM_IHIST:
case MSM_PMEM_SKIN:
rc = msm_pmem_table_add(&sync->pmem_stats, pinfo,
&sync->pmem_stats_spinlock, sync);
break;
default:
rc = -EINVAL;
break;
}
return rc;
}
static int msm_register_pmem(struct msm_sync *sync, void __user *arg)
{
struct msm_pmem_info info;
if (copy_from_user(&info, arg, sizeof(info))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
return __msm_register_pmem(sync, &info);
}
static int msm_stats_axi_cfg(struct msm_sync *sync,
struct msm_vfe_cfg_cmd *cfgcmd)
{
int rc = -EIO;
struct axidata axi_data;
void *data = &axi_data;
struct msm_pmem_region region[3];
int pmem_type = MSM_PMEM_MAX;
memset(&axi_data, 0, sizeof(axi_data));
switch (cfgcmd->cmd_type) {
case CMD_STATS_AXI_CFG:
pmem_type = MSM_PMEM_AEC_AWB;
break;
case CMD_STATS_AF_AXI_CFG:
pmem_type = MSM_PMEM_AF;
break;
case CMD_GENERAL:
data = NULL;
break;
default:
pr_err("%s: unknown command type %d\n",
__func__, cfgcmd->cmd_type);
return -EINVAL;
}
if (cfgcmd->cmd_type != CMD_GENERAL) {
axi_data.bufnum1 =
msm_pmem_region_lookup(&sync->pmem_stats, pmem_type,
®ion[0], NUM_STAT_OUTPUT_BUFFERS,
&sync->pmem_stats_spinlock);
if (!axi_data.bufnum1) {
pr_err("%s %d: pmem region lookup error\n",
__func__, __LINE__);
return -EINVAL;
}
axi_data.region = ®ion[0];
}
/* send the AEC/AWB STATS configuration command to driver */
if (sync->vfefn.vfe_config)
rc = sync->vfefn.vfe_config(cfgcmd, &axi_data);
return rc;
}
static int msm_put_stats_buffer(struct msm_sync *sync, void __user *arg)
{
int rc = -EIO;
struct msm_stats_buf buf;
unsigned long pphy;
struct msm_vfe_cfg_cmd cfgcmd;
if (copy_from_user(&buf, arg,
sizeof(struct msm_stats_buf))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
CDBG("%s\n", __func__);
pphy = msm_pmem_stats_vtop_lookup(sync, buf.buffer, buf.fd);
if (pphy != 0) {
if (buf.type == STAT_AEAW)
cfgcmd.cmd_type = CMD_STATS_BUF_RELEASE;
else if (buf.type == STAT_AF)
cfgcmd.cmd_type = CMD_STATS_AF_BUF_RELEASE;
else if (buf.type == STAT_AEC)
cfgcmd.cmd_type = CMD_STATS_AEC_BUF_RELEASE;
else if (buf.type == STAT_AWB)
cfgcmd.cmd_type = CMD_STATS_AWB_BUF_RELEASE;
else if (buf.type == STAT_IHIST)
cfgcmd.cmd_type = CMD_STATS_IHIST_BUF_RELEASE;
else if (buf.type == STAT_RS)
cfgcmd.cmd_type = CMD_STATS_RS_BUF_RELEASE;
else if (buf.type == STAT_CS)
cfgcmd.cmd_type = CMD_STATS_CS_BUF_RELEASE;
else {
pr_err("%s: invalid buf type %d\n",
__func__,
buf.type);
rc = -EINVAL;
goto put_done;
}
cfgcmd.value = (void *)&buf;
if (sync->vfefn.vfe_config) {
rc = sync->vfefn.vfe_config(&cfgcmd, &pphy);
if (rc < 0)
pr_err("%s: vfe_config error %d\n",
__func__, rc);
} else
pr_err("%s: vfe_config is NULL\n", __func__);
} else {
pr_err("%s: NULL physical address\n", __func__);
rc = -EINVAL;
}
put_done:
return rc;
}
static int msm_axi_config(struct msm_sync *sync, void __user *arg)
{
struct msm_vfe_cfg_cmd cfgcmd;
if (copy_from_user(&cfgcmd, arg, sizeof(cfgcmd))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
switch (cfgcmd.cmd_type) {
case CMD_AXI_CFG_VIDEO:
case CMD_AXI_CFG_PREVIEW:
case CMD_AXI_CFG_SNAP:
case CMD_RAW_PICT_AXI_CFG:
case CMD_AXI_CFG_ZSL:
CDBG("%s, cfgcmd.cmd_type = %d\n", __func__, cfgcmd.cmd_type);
return msm_frame_axi_cfg(sync, &cfgcmd);
case CMD_AXI_CFG_VPE:
case CMD_AXI_CFG_SNAP_VPE:
case CMD_AXI_CFG_SNAP_THUMB_VPE:
return msm_vpe_frame_cfg(sync, (void *)&cfgcmd);
case CMD_STATS_AXI_CFG:
case CMD_STATS_AF_AXI_CFG:
return msm_stats_axi_cfg(sync, &cfgcmd);
default:
pr_err("%s: unknown command type %d\n",
__func__,
cfgcmd.cmd_type);
return -EINVAL;
}
return 0;
}
static int __msm_get_pic(struct msm_sync *sync,
struct msm_frame *frame)
{
int rc = 0;
struct msm_queue_cmd *qcmd = NULL;
struct msm_vfe_resp *vdata;
struct msm_vfe_phy_info *pphy;
struct msm_pmem_info pmem_info;
qcmd = msm_dequeue(&sync->pict_q, list_pict);
if (!qcmd) {
pr_err("%s: no pic frame.\n", __func__);
return -EAGAIN;
}
vdata = (struct msm_vfe_resp *)(qcmd->command);
pphy = &vdata->phy;
rc = msm_pmem_frame_ptov_lookup2(sync,
pphy->y_phy,
&pmem_info,
1); /* mark pic frame in use */
if (rc < 0) {
pr_err("%s: cannot get pic frame, invalid lookup address y %x"
" cbcr %x\n", __func__, pphy->y_phy, pphy->cbcr_phy);
goto err;
}
frame->ts = qcmd->ts;
frame->buffer = (unsigned long)pmem_info.vaddr;
frame->y_off = pmem_info.y_off;
frame->cbcr_off = pmem_info.cbcr_off;
frame->fd = pmem_info.fd;
if (sync->stereocam_enabled &&
sync->stereo_state != STEREO_RAW_SNAP_STARTED) {
if (pmem_info.type == MSM_PMEM_THUMBNAIL_VPE)
frame->path = OUTPUT_TYPE_T;
else
frame->path = OUTPUT_TYPE_S;
} else
frame->path = vdata->phy.output_id;
CDBG("%s: y %x, cbcr %x, qcmd %x, virt_addr %x\n",
__func__,
pphy->y_phy, pphy->cbcr_phy, (int) qcmd, (int) frame->buffer);
err:
free_qcmd(qcmd);
return rc;
}
static int msm_get_pic(struct msm_sync *sync, void __user *arg)
{
int rc = 0;
struct msm_frame frame;
if (copy_from_user(&frame,
arg,
sizeof(struct msm_frame))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
rc = __msm_get_pic(sync, &frame);
if (rc < 0)
return rc;
if (sync->croplen && (!sync->stereocam_enabled)) {
if (frame.croplen != sync->croplen) {
pr_err("%s: invalid frame croplen %d,"
"expecting %d\n",
__func__,
frame.croplen,
sync->croplen);
return -EINVAL;
}
if (copy_to_user((void *)frame.cropinfo,
sync->cropinfo,
sync->croplen)) {
ERR_COPY_TO_USER();
return -EFAULT;
}
}
CDBG("%s: copy snapshot frame to user\n", __func__);
if (copy_to_user((void *)arg,
&frame, sizeof(struct msm_frame))) {
ERR_COPY_TO_USER();
rc = -EFAULT;
}
CDBG("%s: got pic frame\n", __func__);
return rc;
}
static int msm_set_crop(struct msm_sync *sync, void __user *arg)
{
struct crop_info crop;
mutex_lock(&sync->lock);
if (copy_from_user(&crop,
arg,
sizeof(struct crop_info))) {
ERR_COPY_FROM_USER();
mutex_unlock(&sync->lock);
return -EFAULT;
}
if (crop.len != CROP_LEN) {
mutex_unlock(&sync->lock);
return -EINVAL;
}
if (!sync->croplen) {
sync->cropinfo = kmalloc(crop.len, GFP_KERNEL);
if (!sync->cropinfo) {
mutex_unlock(&sync->lock);
return -ENOMEM;
}
}
if (copy_from_user(sync->cropinfo,
crop.info,
crop.len)) {
ERR_COPY_FROM_USER();
sync->croplen = 0;
kfree(sync->cropinfo);
mutex_unlock(&sync->lock);
return -EFAULT;
}
sync->croplen = crop.len;
mutex_unlock(&sync->lock);
return 0;
}
static int msm_error_config(struct msm_sync *sync, void __user *arg)
{
struct msm_queue_cmd *qcmd =
kmalloc(sizeof(struct msm_queue_cmd), GFP_KERNEL);
/* HTC_START Glenn 20110721 For klockwork issue */
if (!qcmd) {
pr_info("%s: kmalloc for qcmd failed.\n", __func__);
return -EFAULT;
}
/* HTC_END */
qcmd->command = NULL;
if (qcmd)
atomic_set(&(qcmd->on_heap), 1);
if (copy_from_user(&(qcmd->error_code), arg, sizeof(uint32_t))) {
ERR_COPY_FROM_USER();
free_qcmd(qcmd);
return -EFAULT;
}
pr_err("%s: Enqueue Fake Frame with error code = %d\n", __func__,
qcmd->error_code);
msm_enqueue(&sync->frame_q, &qcmd->list_frame);
return 0;
}
static int msm_set_fd_roi(struct msm_sync *sync, void __user *arg)
{
struct fd_roi_info fd_roi;
mutex_lock(&sync->lock);
if (copy_from_user(&fd_roi,
arg,
sizeof(struct fd_roi_info))) {
ERR_COPY_FROM_USER();
mutex_unlock(&sync->lock);
return -EFAULT;
}
if (fd_roi.info_len <= 0) {
mutex_unlock(&sync->lock);
return -EFAULT;
}
if (!sync->fdroiinfo.info) {
sync->fdroiinfo.info = kmalloc(fd_roi.info_len, GFP_KERNEL);
if (!sync->fdroiinfo.info) {
mutex_unlock(&sync->lock);
return -ENOMEM;
}
sync->fdroiinfo.info_len = fd_roi.info_len;
} else if (sync->fdroiinfo.info_len < fd_roi.info_len) {
mutex_unlock(&sync->lock);
return -EINVAL;
}
if (copy_from_user(sync->fdroiinfo.info,
fd_roi.info,
fd_roi.info_len)) {
ERR_COPY_FROM_USER();
kfree(sync->fdroiinfo.info);
sync->fdroiinfo.info = NULL;
mutex_unlock(&sync->lock);
return -EFAULT;
}
mutex_unlock(&sync->lock);
return 0;
}
static int msm_pp_grab(struct msm_sync *sync, void __user *arg)
{
uint32_t enable;
if (copy_from_user(&enable, arg, sizeof(enable))) {
ERR_COPY_FROM_USER();
return -EFAULT;
} else {
enable &= PP_MASK;
if (enable & (enable - 1)) {
pr_err("%s: error: more than one PP request!\n",
__func__);
return -EINVAL;
}
if (sync->pp_mask) {
if (enable) {
pr_err("%s: postproc %x is already enabled\n",
__func__, sync->pp_mask & enable);
return -EINVAL;
} else {
sync->pp_mask &= enable;
CDBG("%s: sync->pp_mask %d enable %d\n",
__func__, sync->pp_mask, enable);
return 0;
}
}
CDBG("%s: sync->pp_mask %d enable %d\n", __func__,
sync->pp_mask, enable);
sync->pp_mask |= enable;
}
return 0;
}
static int msm_put_st_frame(struct msm_sync *sync, void __user *arg)
{
unsigned long flags;
unsigned long st_pphy;
if (sync->stereocam_enabled) {
/* Make stereo frame ready for VPE. */
struct msm_st_frame stereo_frame_half;
if (copy_from_user(&stereo_frame_half, arg,
sizeof(stereo_frame_half))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
if (stereo_frame_half.type == OUTPUT_TYPE_ST_L) {
struct msm_vfe_resp *vfe_rp;
struct msm_queue_cmd *qcmd;
spin_lock_irqsave(&pp_stereocam_spinlock, flags);
if (!sync->pp_stereocam) {
pr_warning("%s: no stereo frame to deliver!\n",
__func__);
spin_unlock_irqrestore(&pp_stereocam_spinlock,
flags);
return -EINVAL;
}
CDBG("%s: delivering left frame to VPE\n", __func__);
qcmd = sync->pp_stereocam;
sync->pp_stereocam = NULL;
spin_unlock_irqrestore(&pp_stereocam_spinlock, flags);
vfe_rp = (struct msm_vfe_resp *)qcmd->command;
CDBG("%s: Left Py = 0x%x y_off = %d cbcr_off = %d\n",
__func__, vfe_rp->phy.y_phy,
stereo_frame_half.L.buf_y_off,
stereo_frame_half.L.buf_cbcr_off);
sync->vpefn.vpe_cfg_offset(stereo_frame_half.packing,
vfe_rp->phy.y_phy + stereo_frame_half.L.buf_y_off,
vfe_rp->phy.y_phy + stereo_frame_half.L.buf_cbcr_off,
&(qcmd->ts), OUTPUT_TYPE_ST_L, stereo_frame_half.L,
stereo_frame_half.frame_id);
free_qcmd(qcmd);
} else if (stereo_frame_half.type == OUTPUT_TYPE_ST_R) {
CDBG("%s: delivering right frame to VPE\n", __func__);
spin_lock_irqsave(&st_frame_spinlock, flags);
sync->stcam_conv_value =
stereo_frame_half.buf_info.stcam_conv_value;
sync->stcam_quality_ind =
stereo_frame_half.buf_info.stcam_quality_ind;
st_pphy = msm_pmem_frame_vtop_lookup(sync,
stereo_frame_half.buf_info.buffer,
stereo_frame_half.buf_info.y_off,
stereo_frame_half.buf_info.cbcr_off,
stereo_frame_half.buf_info.fd,
0); /* Do not change the active flag. */
sync->vpefn.vpe_cfg_offset(stereo_frame_half.packing,
st_pphy + stereo_frame_half.R.buf_y_off,
st_pphy + stereo_frame_half.R.buf_cbcr_off,
NULL, OUTPUT_TYPE_ST_R, stereo_frame_half.R,
stereo_frame_half.frame_id);
spin_unlock_irqrestore(&st_frame_spinlock, flags);
} else {
pr_info("%s: Invalid Msg\n", __func__);
}
}
return 0;
}
static int msm_pp_release(struct msm_sync *sync, void __user *arg)
{
unsigned long flags;
if (!sync->pp_mask) {
pr_warning("%s: pp not in progress for\n", __func__);
return -EINVAL;
}
if (sync->pp_mask & PP_PREV) {
spin_lock_irqsave(&pp_prev_spinlock, flags);
if (!sync->pp_prev) {
pr_err("%s: no preview frame to deliver!\n",
__func__);
spin_unlock_irqrestore(&pp_prev_spinlock,
flags);
return -EINVAL;
}
CDBG("%s: delivering pp_prev\n", __func__);
if (sync->frame_q.len <= 100 &&
sync->event_q.len <= 100) {
msm_enqueue(&sync->frame_q,
&sync->pp_prev->list_frame);
} else {
pr_err("%s, Error Queue limit exceeded f_q=%d,\
e_q = %d\n",
__func__, sync->frame_q.len,
sync->event_q.len);
free_qcmd(sync->pp_prev);
goto done;
}
sync->pp_prev = NULL;
spin_unlock_irqrestore(&pp_prev_spinlock, flags);
goto done;
}
if ((sync->pp_mask & PP_SNAP) ||
(sync->pp_mask & PP_RAW_SNAP)) {
spin_lock_irqsave(&pp_snap_spinlock, flags);
if (!sync->pp_snap) {
pr_err("%s: no snapshot to deliver!\n", __func__);
spin_unlock_irqrestore(&pp_snap_spinlock, flags);
return -EINVAL;
}
CDBG("%s: delivering pp_snap\n", __func__);
msm_enqueue(&sync->pict_q, &sync->pp_snap->list_pict);
msm_enqueue(&sync->pict_q, &sync->pp_thumb->list_pict);
sync->pp_snap = NULL;
sync->pp_thumb = NULL;
spin_unlock_irqrestore(&pp_snap_spinlock, flags);
}
done:
return 0;
}
static long msm_ioctl_common(struct msm_cam_device *pmsm,
unsigned int cmd,
void __user *argp)
{
switch (cmd) {
case MSM_CAM_IOCTL_REGISTER_PMEM:
CDBG("%s cmd = MSM_CAM_IOCTL_REGISTER_PMEM\n", __func__);
return msm_register_pmem(pmsm->sync, argp);
case MSM_CAM_IOCTL_UNREGISTER_PMEM:
CDBG("%s cmd = MSM_CAM_IOCTL_UNREGISTER_PMEM\n", __func__);
return msm_pmem_table_del(pmsm->sync, argp);
case MSM_CAM_IOCTL_RELEASE_FRAME_BUFFER:
CDBG("%s cmd = MSM_CAM_IOCTL_RELEASE_FRAME_BUFFER\n", __func__);
return msm_put_frame_buffer(pmsm->sync, argp);
break;
default:
CDBG("%s cmd invalid\n", __func__);
return -EINVAL;
}
}
static long msm_ioctl_config(struct file *filep, unsigned int cmd,
unsigned long arg)
{
int rc = -EINVAL;
void __user *argp = (void __user *)arg;
struct msm_cam_device *pmsm = filep->private_data;
CDBG("%s: cmd %d\n", __func__, _IOC_NR(cmd));
switch (cmd) {
case MSM_CAM_IOCTL_GET_SENSOR_INFO:
rc = msm_get_sensor_info(pmsm->sync, argp);
break;
case MSM_CAM_IOCTL_CONFIG_VFE:
/* Coming from config thread for update */
rc = msm_config_vfe(pmsm->sync, argp);
break;
case MSM_CAM_IOCTL_CONFIG_VPE:
/* Coming from config thread for update */
rc = msm_config_vpe(pmsm->sync, argp);
break;
case MSM_CAM_IOCTL_GET_STATS:
/* Coming from config thread wait
* for vfe statistics and control requests */
rc = msm_get_stats(pmsm->sync, argp);
break;
case MSM_CAM_IOCTL_ENABLE_VFE:
/* This request comes from control thread:
* enable either QCAMTASK or VFETASK */
rc = msm_enable_vfe(pmsm->sync, argp);
break;
case MSM_CAM_IOCTL_DISABLE_VFE:
/* This request comes from control thread:
* disable either QCAMTASK or VFETASK */
rc = msm_disable_vfe(pmsm->sync, argp);
break;
case MSM_CAM_IOCTL_VFE_APPS_RESET:
msm_camio_vfe_blk_reset();
rc = 0;
break;
case MSM_CAM_IOCTL_RELEASE_STATS_BUFFER:
rc = msm_put_stats_buffer(pmsm->sync, argp);
break;
case MSM_CAM_IOCTL_AXI_CONFIG:
case MSM_CAM_IOCTL_AXI_VPE_CONFIG:
rc = msm_axi_config(pmsm->sync, argp);
break;
case MSM_CAM_IOCTL_SET_CROP:
rc = msm_set_crop(pmsm->sync, argp);
break;
case MSM_CAM_IOCTL_SET_FD_ROI:
rc = msm_set_fd_roi(pmsm->sync, argp);
break;
case MSM_CAM_IOCTL_PICT_PP:
/* Grab one preview frame or one snapshot
* frame.
*/
rc = msm_pp_grab(pmsm->sync, argp);
break;
case MSM_CAM_IOCTL_PICT_PP_DONE:
/* Release the preview of snapshot frame
* that was grabbed.
*/
rc = msm_pp_release(pmsm->sync, argp);
break;
case MSM_CAM_IOCTL_PUT_ST_FRAME:
/* Release the left or right frame
* that was sent for stereo processing.
*/
rc = msm_put_st_frame(pmsm->sync, argp);
break;
case MSM_CAM_IOCTL_SENSOR_IO_CFG:
rc = pmsm->sync->sctrl.s_config(argp);
break;
case MSM_CAM_IOCTL_FLASH_LED_CFG: {
uint32_t led_state;
if (copy_from_user(&led_state, argp, sizeof(led_state))) {
ERR_COPY_FROM_USER();
rc = -EFAULT;
} else
rc = msm_camera_flash_set_led_state(pmsm->sync->
sdata->flash_data, led_state);
break;
}
case MSM_CAM_IOCTL_STROBE_FLASH_CFG: {
uint32_t flash_type;
if (copy_from_user(&flash_type, argp, sizeof(flash_type))) {
pr_err("msm_strobe_flash_init failed");
ERR_COPY_FROM_USER();
rc = -EFAULT;
} else {
CDBG("msm_strobe_flash_init enter");
rc = msm_strobe_flash_init(pmsm->sync, flash_type);
}
break;
}
case MSM_CAM_IOCTL_STROBE_FLASH_RELEASE:
if (pmsm->sync->sdata->strobe_flash_data) {
rc = pmsm->sync->sfctrl.strobe_flash_release(
pmsm->sync->sdata->strobe_flash_data, 0);
}
break;
case MSM_CAM_IOCTL_STROBE_FLASH_CHARGE: {
uint32_t charge_en;
if (copy_from_user(&charge_en, argp, sizeof(charge_en))) {
ERR_COPY_FROM_USER();
rc = -EFAULT;
} else
rc = pmsm->sync->sfctrl.strobe_flash_charge(
pmsm->sync->sdata->strobe_flash_data->flash_charge,
charge_en, pmsm->sync->sdata->strobe_flash_data->
flash_recharge_duration);
break;
}
case MSM_CAM_IOCTL_FLASH_CTRL: {
struct flash_ctrl_data flash_info;
if (copy_from_user(&flash_info, argp, sizeof(flash_info))) {
ERR_COPY_FROM_USER();
rc = -EFAULT;
} else
rc = msm_flash_ctrl(pmsm->sync->sdata, &flash_info);
break;
}
case MSM_CAM_IOCTL_ERROR_CONFIG:
rc = msm_error_config(pmsm->sync, argp);
break;
case MSM_CAM_IOCTL_ABORT_CAPTURE: {
unsigned long flags = 0;
CDBG("get_pic:MSM_CAM_IOCTL_ABORT_CAPTURE\n");
spin_lock_irqsave(&pmsm->sync->abort_pict_lock, flags);
pmsm->sync->get_pic_abort = 1;
spin_unlock_irqrestore(&pmsm->sync->abort_pict_lock, flags);
wake_up(&(pmsm->sync->pict_q.wait));
rc = 0;
break;
}
default:
rc = msm_ioctl_common(pmsm, cmd, argp);
break;
}
CDBG("%s: cmd %d DONE\n", __func__, _IOC_NR(cmd));
return rc;
}
static int msm_unblock_poll_frame(struct msm_sync *);
static long msm_ioctl_frame(struct file *filep, unsigned int cmd,
unsigned long arg)
{
int rc = -EINVAL;
void __user *argp = (void __user *)arg;
struct msm_cam_device *pmsm = filep->private_data;
switch (cmd) {
case MSM_CAM_IOCTL_GETFRAME:
/* Coming from frame thread to get frame
* after SELECT is done */
rc = msm_get_frame(pmsm->sync, argp);
break;
case MSM_CAM_IOCTL_RELEASE_FRAME_BUFFER:
rc = msm_put_frame_buffer(pmsm->sync, argp);
break;
case MSM_CAM_IOCTL_UNBLOCK_POLL_FRAME:
rc = msm_unblock_poll_frame(pmsm->sync);
break;
default:
break;
}
return rc;
}
static int msm_unblock_poll_pic(struct msm_sync *sync);
static long msm_ioctl_pic(struct file *filep, unsigned int cmd,
unsigned long arg)
{
int rc = -EINVAL;
void __user *argp = (void __user *)arg;
struct msm_cam_device *pmsm = filep->private_data;
switch (cmd) {
case MSM_CAM_IOCTL_GET_PICTURE:
rc = msm_get_pic(pmsm->sync, argp);
break;
case MSM_CAM_IOCTL_RELEASE_PIC_BUFFER:
rc = msm_put_pic_buffer(pmsm->sync, argp);
break;
case MSM_CAM_IOCTL_UNBLOCK_POLL_PIC_FRAME:
rc = msm_unblock_poll_pic(pmsm->sync);
break;
default:
break;
}
return rc;
}
static long msm_ioctl_control(struct file *filep, unsigned int cmd,
unsigned long arg)
{
int rc = -EINVAL;
void __user *argp = (void __user *)arg;
struct msm_control_device *ctrl_pmsm = filep->private_data;
struct msm_cam_device *pmsm = ctrl_pmsm->pmsm;
switch (cmd) {
case MSM_CAM_IOCTL_CTRL_COMMAND:
/* Coming from control thread, may need to wait for
* command status */
CDBG("calling msm_control kernel msm_ioctl_control\n");
mutex_lock(&ctrl_cmd_lock);
rc = msm_control(ctrl_pmsm, 1, argp);
mutex_unlock(&ctrl_cmd_lock);
break;
case MSM_CAM_IOCTL_CTRL_COMMAND_2:
/* Sends a message, returns immediately */
rc = msm_control(ctrl_pmsm, 0, argp);
break;
case MSM_CAM_IOCTL_CTRL_CMD_DONE:
/* Config thread calls the control thread to notify it
* of the result of a MSM_CAM_IOCTL_CTRL_COMMAND.
*/
rc = msm_ctrl_cmd_done(ctrl_pmsm, argp);
break;
case MSM_CAM_IOCTL_GET_SENSOR_INFO:
rc = msm_get_sensor_info(pmsm->sync, argp);
break;
case MSM_CAM_IOCTL_GET_CAMERA_INFO:
rc = msm_get_camera_info(argp);
break;
default:
rc = msm_ioctl_common(pmsm, cmd, argp);
break;
}
return rc;
}
static int __msm_release(struct msm_sync *sync)
{
struct msm_pmem_region *region;
struct hlist_node *hnode;
struct hlist_node *n;
mutex_lock(&sync->lock);
if (sync->opencnt)
sync->opencnt--;
pr_info("%s, open count =%d\n", __func__, sync->opencnt);
if (!sync->opencnt) {
/* need to clean up system resource */
pr_info("%s, release VFE\n", __func__);
if (sync->core_powered_on) {
if (sync->vfefn.vfe_release)
sync->vfefn.vfe_release(sync->pdev);
/*sensor release */
pr_info("%s, release Sensor\n", __func__);
sync->sctrl.s_release();
CDBG("%s, msm_camio_sensor_clk_off\n", __func__);
msm_camio_sensor_clk_off(sync->pdev);
if (sync->sfctrl.strobe_flash_release) {
CDBG("%s, strobe_flash_release\n", __func__);
sync->sfctrl.strobe_flash_release(
sync->sdata->strobe_flash_data, 1);
}
}
kfree(sync->cropinfo);
sync->cropinfo = NULL;
sync->croplen = 0;
/*re-init flag*/
sync->ignore_qcmd = false;
sync->ignore_qcmd_type = -1;
sync->qcmd_done = false;
CDBG("%s, free frame pmem region\n", __func__);
hlist_for_each_entry_safe(region, hnode, n,
&sync->pmem_frames, list) {
hlist_del(hnode);
put_pmem_file(region->file);
kfree(region);
}
CDBG("%s, free stats pmem region\n", __func__);
hlist_for_each_entry_safe(region, hnode, n,
&sync->pmem_stats, list) {
hlist_del(hnode);
put_pmem_file(region->file);
kfree(region);
}
msm_queue_drain(&sync->pict_q, list_pict);
wake_unlock(&sync->wake_lock);
sync->apps_id = NULL;
sync->core_powered_on = 0;
}
mutex_unlock(&sync->lock);
return 0;
}
static int msm_release_config(struct inode *node, struct file *filep)
{
int rc;
struct msm_cam_device *pmsm = filep->private_data;
pr_info("%s: %s\n", __func__, filep->f_path.dentry->d_name.name);
rc = __msm_release(pmsm->sync);
if (!rc) {
msm_queue_drain(&pmsm->sync->event_q, list_config);
atomic_set(&pmsm->opened, 0);
}
return rc;
}
static int msm_release_control(struct inode *node, struct file *filep)
{
int rc;
struct msm_control_device *ctrl_pmsm = filep->private_data;
struct msm_cam_device *pmsm = ctrl_pmsm->pmsm;
pr_info("%s: %s\n", __func__, filep->f_path.dentry->d_name.name);
g_v4l2_opencnt--;
mutex_lock(&pmsm->sync->lock);
if (pmsm->sync->core_powered_on && pmsm->sync->vfefn.vfe_stop) {
pr_info("%s, stop vfe if active\n", __func__);
pmsm->sync->vfefn.vfe_stop();
}
mutex_unlock(&pmsm->sync->lock);
rc = __msm_release(pmsm->sync);
if (!rc) {
msm_queue_drain(&ctrl_pmsm->ctrl_q, list_control);
kfree(ctrl_pmsm);
}
return rc;
}
static int msm_release_frame(struct inode *node, struct file *filep)
{
int rc;
struct msm_cam_device *pmsm = filep->private_data;
pr_info("%s: %s\n", __func__, filep->f_path.dentry->d_name.name);
rc = __msm_release(pmsm->sync);
if (!rc) {
msm_queue_drain(&pmsm->sync->frame_q, list_frame);
atomic_set(&pmsm->opened, 0);
}
return rc;
}
static int msm_release_pic(struct inode *node, struct file *filep)
{
int rc;
struct msm_cam_device *pmsm = filep->private_data;
CDBG("%s: %s\n", __func__, filep->f_path.dentry->d_name.name);
rc = __msm_release(pmsm->sync);
if (!rc) {
msm_queue_drain(&pmsm->sync->pict_q, list_pict);
atomic_set(&pmsm->opened, 0);
}
return rc;
}
static int msm_unblock_poll_pic(struct msm_sync *sync)
{
unsigned long flags;
CDBG("%s\n", __func__);
spin_lock_irqsave(&sync->pict_q.lock, flags);
sync->unblock_poll_pic_frame = 1;
wake_up(&sync->pict_q.wait);
spin_unlock_irqrestore(&sync->pict_q.lock, flags);
return 0;
}
static int msm_unblock_poll_frame(struct msm_sync *sync)
{
unsigned long flags;
CDBG("%s\n", __func__);
spin_lock_irqsave(&sync->frame_q.lock, flags);
sync->unblock_poll_frame = 1;
wake_up(&sync->frame_q.wait);
spin_unlock_irqrestore(&sync->frame_q.lock, flags);
return 0;
}
static unsigned int __msm_poll_frame(struct msm_sync *sync,
struct file *filep,
struct poll_table_struct *pll_table)
{
int rc = 0;
unsigned long flags;
poll_wait(filep, &sync->frame_q.wait, pll_table);
spin_lock_irqsave(&sync->frame_q.lock, flags);
if (!list_empty_careful(&sync->frame_q.list))
/* frame ready */
rc = POLLIN | POLLRDNORM;
if (sync->unblock_poll_frame) {
CDBG("%s: sync->unblock_poll_frame is true\n", __func__);
rc |= POLLPRI;
sync->unblock_poll_frame = 0;
}
spin_unlock_irqrestore(&sync->frame_q.lock, flags);
return rc;
}
static unsigned int __msm_poll_pic(struct msm_sync *sync,
struct file *filep,
struct poll_table_struct *pll_table)
{
int rc = 0;
unsigned long flags;
poll_wait(filep, &sync->pict_q.wait , pll_table);
spin_lock_irqsave(&sync->abort_pict_lock, flags);
if (sync->get_pic_abort == 1) {
/* TODO: need to pass an error case */
sync->get_pic_abort = 0;
}
spin_unlock_irqrestore(&sync->abort_pict_lock, flags);
spin_lock_irqsave(&sync->pict_q.lock, flags);
if (!list_empty_careful(&sync->pict_q.list))
/* frame ready */
rc = POLLIN | POLLRDNORM;
if (sync->unblock_poll_pic_frame) {
CDBG("%s: sync->unblock_poll_pic_frame is true\n", __func__);
rc |= POLLPRI;
sync->unblock_poll_pic_frame = 0;
}
spin_unlock_irqrestore(&sync->pict_q.lock, flags);
return rc;
}
static unsigned int msm_poll_frame(struct file *filep,
struct poll_table_struct *pll_table)
{
struct msm_cam_device *pmsm = filep->private_data;
return __msm_poll_frame(pmsm->sync, filep, pll_table);
}
static unsigned int msm_poll_pic(struct file *filep,
struct poll_table_struct *pll_table)
{
struct msm_cam_device *pmsm = filep->private_data;
return __msm_poll_pic(pmsm->sync, filep, pll_table);
}
static unsigned int __msm_poll_config(struct msm_sync *sync,
struct file *filep,
struct poll_table_struct *pll_table)
{
int rc = 0;
unsigned long flags;
poll_wait(filep, &sync->event_q.wait, pll_table);
spin_lock_irqsave(&sync->event_q.lock, flags);
if (!list_empty_careful(&sync->event_q.list))
/* event ready */
rc = POLLIN | POLLRDNORM;
spin_unlock_irqrestore(&sync->event_q.lock, flags);
return rc;
}
static unsigned int msm_poll_config(struct file *filep,
struct poll_table_struct *pll_table)
{
struct msm_cam_device *pmsm = filep->private_data;
return __msm_poll_config(pmsm->sync, filep, pll_table);
}
/*
* This function executes in interrupt context.
*/
static void *msm_vfe_sync_alloc(int size,
void *syncdata __attribute__((unused)),
gfp_t gfp)
{
struct msm_queue_cmd *qcmd =
kmalloc(sizeof(struct msm_queue_cmd) + size, gfp);
if (qcmd) {
atomic_set(&qcmd->on_heap, 1);
return qcmd + 1;
}
return NULL;
}
static void *msm_vpe_sync_alloc(int size,
void *syncdata __attribute__((unused)),
gfp_t gfp)
{
struct msm_queue_cmd *qcmd =
kzalloc(sizeof(struct msm_queue_cmd) + size, gfp);
if (qcmd) {
atomic_set(&qcmd->on_heap, 1);
return qcmd + 1;
}
return NULL;
}
static void msm_vfe_sync_free(void *ptr)
{
if (ptr) {
struct msm_queue_cmd *qcmd =
(struct msm_queue_cmd *)ptr;
qcmd--;
if (atomic_read(&qcmd->on_heap))
kfree(qcmd);
}
}
static void msm_vpe_sync_free(void *ptr)
{
if (ptr) {
struct msm_queue_cmd *qcmd =
(struct msm_queue_cmd *)ptr;
qcmd--;
if (atomic_read(&qcmd->on_heap))
kfree(qcmd);
}
}
/*
* This function executes in interrupt context.
*/
static void msm_vfe_sync(struct msm_vfe_resp *vdata,
enum msm_queue qtype, void *syncdata,
gfp_t gfp)
{
struct msm_queue_cmd *qcmd = NULL;
struct msm_sync *sync = (struct msm_sync *)syncdata;
unsigned long flags;
if (!sync) {
pr_err("%s: no context in dsp callback.\n", __func__);
return;
}
qcmd = ((struct msm_queue_cmd *)vdata) - 1;
qcmd->type = qtype;
qcmd->command = vdata;
ktime_get_ts(&(qcmd->ts));
if (qtype != MSM_CAM_Q_VFE_MSG)
goto vfe_for_config;
CDBG("%s: vdata->type %d\n", __func__, vdata->type);
switch (vdata->type) {
case VFE_MSG_OUTPUT_P:
if (sync->pp_mask & PP_PREV) {
CDBG("%s: PP_PREV in progress: phy_y %x phy_cbcr %x\n",
__func__,
vdata->phy.y_phy,
vdata->phy.cbcr_phy);
spin_lock_irqsave(&pp_prev_spinlock, flags);
if (sync->pp_prev)
CDBG("%s: overwriting pp_prev!\n",
__func__);
CDBG("%s: sending preview to config\n", __func__);
sync->pp_prev = qcmd;
spin_unlock_irqrestore(&pp_prev_spinlock, flags);
sync->pp_frame_avail = 1;
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
break;
}
CDBG("%s: msm_enqueue frame_q\n", __func__);
if (sync->stereocam_enabled)
CDBG("%s: Enqueue VFE_MSG_OUTPUT_P to event_q for "
"stereo processing\n", __func__);
else {
if (sync->frame_q.len <= 100 &&
sync->event_q.len <= 100) {
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
msm_enqueue(&sync->frame_q, &qcmd->list_frame);
} else {
pr_err("%s, Error Queue limit exceeded "
"f_q = %d, e_q = %d\n", __func__,
sync->frame_q.len, sync->event_q.len);
free_qcmd(qcmd);
return;
}
}
break;
case VFE_MSG_OUTPUT_T:
if (sync->stereocam_enabled) {
spin_lock_irqsave(&pp_stereocam_spinlock, flags);
/* if out1/2 is currently in progress, save the qcmd
and issue only ionce the 1st one completes the 3D
pipeline */
if (STEREO_SNAP_BUFFER1_PROCESSING ==
sync->stereo_state) {
sync->pp_stereocam2 = qcmd;
spin_unlock_irqrestore(&pp_stereocam_spinlock,
flags);
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
pr_err("%s: snapshot stereo in progress\n",
__func__);
return;
}
if (sync->pp_stereocam)
CDBG("%s: overwriting pp_stereocam!\n",
__func__);
pr_err("%s: sending stereo frame to config\n", __func__);
sync->pp_stereocam = qcmd;
sync->stereo_state =
STEREO_SNAP_BUFFER1_PROCESSING;
spin_unlock_irqrestore(&pp_stereocam_spinlock, flags);
/* Increament on_heap by one because the same qcmd will
be used for VPE in msm_pp_release. */
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
pr_err("%s: Enqueue VFE_MSG_OUTPUT_T to event_q for "
"stereo processing.\n", __func__);
break;
}
if (sync->pp_mask & PP_SNAP) {
spin_lock_irqsave(&pp_thumb_spinlock, flags);
sync->thumb_count--;
if (!sync->pp_thumb && (0 >= sync->thumb_count)) {
CDBG("%s: pp sending thumbnail to config\n",
__func__);
sync->pp_thumb = qcmd;
spin_unlock_irqrestore(&pp_thumb_spinlock,
flags);
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
} else {
spin_unlock_irqrestore(&pp_thumb_spinlock,
flags);
}
break;
} else {
msm_enqueue(&sync->pict_q, &qcmd->list_pict);
return;
}
case VFE_MSG_OUTPUT_S:
if (sync->stereocam_enabled &&
sync->stereo_state != STEREO_RAW_SNAP_STARTED) {
spin_lock_irqsave(&pp_stereocam_spinlock, flags);
/* if out1/2 is currently in progress, save the qcmd
and issue only once the 1st one completes the 3D
pipeline */
if (STEREO_SNAP_BUFFER1_PROCESSING ==
sync->stereo_state) {
sync->pp_stereocam2 = qcmd;
spin_unlock_irqrestore(&pp_stereocam_spinlock,
flags);
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
pr_err("%s: snapshot stereo in progress\n",
__func__);
return;
}
if (sync->pp_stereocam)
CDBG("%s: overwriting pp_stereocam!\n",
__func__);
pr_err("%s: sending stereo frame to config\n", __func__);
sync->pp_stereocam = qcmd;
sync->stereo_state =
STEREO_SNAP_BUFFER1_PROCESSING;
spin_unlock_irqrestore(&pp_stereocam_spinlock, flags);
/* Increament on_heap by one because the same qcmd will
be used for VPE in msm_pp_release. */
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
pr_err("%s: Enqueue VFE_MSG_OUTPUT_S to event_q for "
"stereo processing.\n", __func__);
break;
}
if (sync->pp_mask & PP_SNAP) {
spin_lock_irqsave(&pp_snap_spinlock, flags);
sync->snap_count--;
if (!sync->pp_snap && (0 >= sync->snap_count)) {
CDBG("%s: pp sending main image to config\n",
__func__);
sync->pp_snap = qcmd;
spin_unlock_irqrestore(&pp_snap_spinlock,
flags);
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
} else {
spin_unlock_irqrestore(&pp_snap_spinlock,
flags);
}
break;
} else {
CDBG("%s: enqueue to picture queue\n", __func__);
msm_enqueue(&sync->pict_q, &qcmd->list_pict);
return;
}
break;
case VFE_MSG_OUTPUT_V:
if (sync->stereocam_enabled) {
spin_lock_irqsave(&pp_stereocam_spinlock, flags);
if (sync->pp_stereocam)
CDBG("%s: overwriting pp_stereocam!\n",
__func__);
CDBG("%s: sending stereo frame to config\n", __func__);
sync->pp_stereocam = qcmd;
spin_unlock_irqrestore(&pp_stereocam_spinlock, flags);
/* Increament on_heap by one because the same qcmd will
be used for VPE in msm_pp_release. */
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
CDBG("%s: Enqueue VFE_MSG_OUTPUT_V to event_q for "
"stereo processing.\n", __func__);
break;
}
if (sync->vpefn.vpe_cfg_update) {
CDBG("dis_en = %d\n", *sync->vpefn.dis);
if (*(sync->vpefn.dis)) {
memset(&(vdata->vpe_bf), 0,
sizeof(vdata->vpe_bf));
if (sync->cropinfo != NULL)
vdata->vpe_bf.vpe_crop =
*(struct video_crop_t *)(sync->cropinfo);
vdata->vpe_bf.y_phy = vdata->phy.y_phy;
vdata->vpe_bf.cbcr_phy = vdata->phy.cbcr_phy;
vdata->vpe_bf.ts = (qcmd->ts);
vdata->vpe_bf.frame_id = vdata->phy.frame_id;
qcmd->command = vdata;
msm_enqueue_vpe(&sync->vpe_q,
&qcmd->list_vpe_frame);
return;
} else if (sync->vpefn.vpe_cfg_update(sync->cropinfo)) {
CDBG("%s: msm_enqueue video frame to vpe time "
"= %ld\n", __func__, qcmd->ts.tv_nsec);
sync->vpefn.send_frame_to_vpe(
vdata->phy.y_phy,
vdata->phy.cbcr_phy,
&(qcmd->ts), OUTPUT_TYPE_V);
free_qcmd(qcmd);
return;
} else {
CDBG("%s: msm_enqueue video frame_q\n",
__func__);
if (sync->liveshot_enabled) {
CDBG("%s: msm_enqueue liveshot\n",
__func__);
vdata->phy.output_id |= OUTPUT_TYPE_L;
sync->liveshot_enabled = false;
}
if (sync->frame_q.len <= 100 &&
sync->event_q.len <= 100) {
msm_enqueue(&sync->frame_q,
&qcmd->list_frame);
} else {
pr_err("%s, Error Queue limit exceeded\
f_q = %d, e_q = %d\n",
__func__, sync->frame_q.len,
sync->event_q.len);
free_qcmd(qcmd);
}
return;
}
} else {
CDBG("%s: msm_enqueue video frame_q\n", __func__);
if (sync->frame_q.len <= 100 &&
sync->event_q.len <= 100) {
msm_enqueue(&sync->frame_q, &qcmd->list_frame);
} else {
pr_err("%s, Error Queue limit exceeded\
f_q = %d, e_q = %d\n",
__func__, sync->frame_q.len,
sync->event_q.len);
free_qcmd(qcmd);
}
return;
}
case VFE_MSG_SNAPSHOT:
if (sync->pp_mask & (PP_SNAP | PP_RAW_SNAP)) {
CDBG("%s: PP_SNAP in progress: pp_mask %x\n",
__func__, sync->pp_mask);
spin_lock_irqsave(&pp_snap_spinlock, flags);
if (sync->pp_snap)
pr_warning("%s: overwriting pp_snap!\n",
__func__);
CDBG("%s: sending snapshot to config\n",
__func__);
spin_unlock_irqrestore(&pp_snap_spinlock, flags);
} else {
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
CDBG("%s: VFE_MSG_SNAPSHOT store\n",
__func__);
if (sync->stereocam_enabled &&
sync->stereo_state != STEREO_RAW_SNAP_STARTED) {
sync->pp_stereosnap = qcmd;
return;
}
}
break;
case VFE_MSG_STATS_AWB:
CDBG("%s: qtype %d, AWB stats, enqueue event_q.\n",
__func__, vdata->type);
break;
case VFE_MSG_STATS_AEC:
CDBG("%s: qtype %d, AEC stats, enqueue event_q.\n",
__func__, vdata->type);
break;
case VFE_MSG_STATS_IHIST:
CDBG("%s: qtype %d, ihist stats, enqueue event_q.\n",
__func__, vdata->type);
break;
case VFE_MSG_STATS_RS:
CDBG("%s: qtype %d, rs stats, enqueue event_q.\n",
__func__, vdata->type);
break;
case VFE_MSG_STATS_CS:
CDBG("%s: qtype %d, cs stats, enqueue event_q.\n",
__func__, vdata->type);
break;
case VFE_MSG_GENERAL:
CDBG("%s: qtype %d, general msg, enqueue event_q.\n",
__func__, vdata->type);
break;
default:
CDBG("%s: qtype %d not handled\n", __func__, vdata->type);
/* fall through, send to config. */
}
vfe_for_config:
CDBG("%s: msm_enqueue event_q\n", __func__);
if (sync->frame_q.len <= 100 && sync->event_q.len <= 100) {
msm_enqueue(&sync->event_q, &qcmd->list_config);
} else {
pr_err("%s, Error Queue limit exceeded f_q = %d, e_q = %d\n",
__func__, sync->frame_q.len, sync->event_q.len);
free_qcmd(qcmd);
}
}
static void msm_vpe_sync(struct msm_vpe_resp *vdata,
enum msm_queue qtype, void *syncdata, void *ts, gfp_t gfp)
{
struct msm_queue_cmd *qcmd = NULL;
unsigned long flags;
struct msm_sync *sync = (struct msm_sync *)syncdata;
if (!sync) {
pr_err("%s: no context in dsp callback.\n", __func__);
return;
}
qcmd = ((struct msm_queue_cmd *)vdata) - 1;
qcmd->type = qtype;
qcmd->command = vdata;
qcmd->ts = *((struct timespec *)ts);
if (qtype != MSM_CAM_Q_VPE_MSG) {
pr_err("%s: Invalid qcmd type = %d.\n", __func__, qcmd->type);
free_qcmd(qcmd);
return;
}
CDBG("%s: vdata->type %d\n", __func__, vdata->type);
switch (vdata->type) {
case VPE_MSG_OUTPUT_V:
if (sync->liveshot_enabled) {
CDBG("%s: msm_enqueue liveshot %d\n", __func__,
sync->liveshot_enabled);
vdata->phy.output_id |= OUTPUT_TYPE_L;
sync->liveshot_enabled = false;
}
if (sync->frame_q.len <= 100 && sync->event_q.len <= 100) {
CDBG("%s: enqueue to frame_q from VPE\n", __func__);
msm_enqueue(&sync->frame_q, &qcmd->list_frame);
} else {
pr_err("%s, Error Queue limit exceeded f_q = %d, "
"e_q = %d\n", __func__, sync->frame_q.len,
sync->event_q.len);
free_qcmd(qcmd);
}
return;
case VPE_MSG_OUTPUT_ST_L:
CDBG("%s: enqueue left frame done msg to event_q from VPE\n",
__func__);
msm_enqueue(&sync->event_q, &qcmd->list_config);
return;
case VPE_MSG_OUTPUT_ST_R:
spin_lock_irqsave(&pp_stereocam_spinlock, flags);
CDBG("%s: received VPE_MSG_OUTPUT_ST_R state %d\n", __func__,
sync->stereo_state);
if (STEREO_SNAP_BUFFER1_PROCESSING == sync->stereo_state) {
msm_enqueue(&sync->pict_q, &qcmd->list_pict);
qcmd = sync->pp_stereocam2;
sync->pp_stereocam = sync->pp_stereocam2;
sync->pp_stereocam2 = NULL;
msm_enqueue(&sync->event_q, &qcmd->list_config);
sync->stereo_state =
STEREO_SNAP_BUFFER2_PROCESSING;
} else if (STEREO_SNAP_BUFFER2_PROCESSING ==
sync->stereo_state) {
sync->stereo_state = STEREO_SNAP_IDLE;
/* Send snapshot DONE */
msm_enqueue(&sync->pict_q, &qcmd->list_pict);
qcmd = sync->pp_stereosnap;
sync->pp_stereosnap = NULL;
CDBG("%s: send SNAPSHOT_DONE message\n", __func__);
msm_enqueue(&sync->event_q, &qcmd->list_config);
} else {
if (atomic_read(&qcmd->on_heap))
atomic_add(1, &qcmd->on_heap);
msm_enqueue(&sync->event_q, &qcmd->list_config);
if (sync->stereo_state == STEREO_VIDEO_ACTIVE) {
CDBG("%s: st frame to frame_q from VPE\n",
__func__);
msm_enqueue(&sync->frame_q, &qcmd->list_frame);
}
}
spin_unlock_irqrestore(&pp_stereocam_spinlock, flags);
return;
default:
pr_err("%s: qtype %d not handled\n", __func__, vdata->type);
}
pr_err("%s: Should not come here. Error.\n", __func__);
}
static struct msm_vpe_callback msm_vpe_s = {
.vpe_resp = msm_vpe_sync,
.vpe_alloc = msm_vpe_sync_alloc,
.vpe_free = msm_vpe_sync_free,
};
static struct msm_vfe_callback msm_vfe_s = {
.vfe_resp = msm_vfe_sync,
.vfe_alloc = msm_vfe_sync_alloc,
.vfe_free = msm_vfe_sync_free,
};
static int __msm_open(struct msm_sync *sync, const char *const apps_id,
int is_controlnode)
{
int rc = 0;
mutex_lock(&sync->lock);
if (sync->apps_id && strcmp(sync->apps_id, apps_id)
&& (!strcmp(MSM_APPS_ID_V4L2, apps_id))) {
pr_err("%s(%s): sensor %s is already opened for %s\n",
__func__,
apps_id,
sync->sdata->sensor_name,
sync->apps_id);
rc = -EBUSY;
goto msm_open_done;
}
sync->apps_id = apps_id;
if (!sync->core_powered_on && !is_controlnode) {
wake_lock(&sync->wake_lock);
msm_camvfe_fn_init(&sync->vfefn, sync);
if (sync->vfefn.vfe_init) {
sync->pp_frame_avail = 0;
sync->get_pic_abort = 0;
rc = msm_camio_sensor_clk_on(sync->pdev);
if (rc < 0) {
pr_err("%s: setting sensor clocks failed: %d\n",
__func__, rc);
goto msm_open_done;
}
rc = sync->sctrl.s_init(sync->sdata);
if (rc < 0) {
pr_err("%s: sensor init failed: %d\n",
__func__, rc);
goto msm_open_done;
}
rc = sync->vfefn.vfe_init(&msm_vfe_s,
sync->pdev);
if (rc < 0) {
pr_err("%s: vfe_init failed at %d\n",
__func__, rc);
goto msm_open_done;
}
} else {
pr_err("%s: no sensor init func\n", __func__);
rc = -ENODEV;
goto msm_open_done;
}
msm_camvpe_fn_init(&sync->vpefn, sync);
spin_lock_init(&sync->abort_pict_lock);
if (rc >= 0) {
msm_region_init(sync);
if (sync->vpefn.vpe_reg)
sync->vpefn.vpe_reg(&msm_vpe_s);
sync->unblock_poll_frame = 0;
sync->unblock_poll_pic_frame = 0;
}
sync->core_powered_on = 1;
}
sync->opencnt++;
msm_open_done:
mutex_unlock(&sync->lock);
return rc;
}
static int msm_open_common(struct inode *inode, struct file *filep,
int once, int is_controlnode)
{
int rc;
struct msm_cam_device *pmsm =
container_of(inode->i_cdev, struct msm_cam_device, cdev);
CDBG("%s: open %s\n", __func__, filep->f_path.dentry->d_name.name);
if (atomic_cmpxchg(&pmsm->opened, 0, 1) && once) {
pr_err("%s: %s is already opened.\n",
__func__,
filep->f_path.dentry->d_name.name);
return -EBUSY;
}
rc = nonseekable_open(inode, filep);
if (rc < 0) {
pr_err("%s: nonseekable_open error %d\n", __func__, rc);
return rc;
}
rc = __msm_open(pmsm->sync, MSM_APPS_ID_PROP, is_controlnode);
if (rc < 0)
return rc;
filep->private_data = pmsm;
CDBG("%s: rc %d\n", __func__, rc);
return rc;
}
static int msm_open(struct inode *inode, struct file *filep)
{
return msm_open_common(inode, filep, 1, 0);
}
static int msm_open_control(struct inode *inode, struct file *filep)
{
int rc;
struct msm_control_device *ctrl_pmsm =
kmalloc(sizeof(struct msm_control_device), GFP_KERNEL);
if (!ctrl_pmsm)
return -ENOMEM;
rc = msm_open_common(inode, filep, 0, 1);
if (rc < 0) {
kfree(ctrl_pmsm);
return rc;
}
ctrl_pmsm->pmsm = filep->private_data;
filep->private_data = ctrl_pmsm;
msm_queue_init(&ctrl_pmsm->ctrl_q, "control");
if (!g_v4l2_opencnt)
g_v4l2_control_device = ctrl_pmsm;
g_v4l2_opencnt++;
CDBG("%s: rc %d\n", __func__, rc);
return rc;
}
static const struct file_operations msm_fops_config = {
.owner = THIS_MODULE,
.open = msm_open,
.unlocked_ioctl = msm_ioctl_config,
.release = msm_release_config,
.poll = msm_poll_config,
};
static const struct file_operations msm_fops_control = {
.owner = THIS_MODULE,
.open = msm_open_control,
.unlocked_ioctl = msm_ioctl_control,
.release = msm_release_control,
};
static const struct file_operations msm_fops_frame = {
.owner = THIS_MODULE,
.open = msm_open,
.unlocked_ioctl = msm_ioctl_frame,
.release = msm_release_frame,
.poll = msm_poll_frame,
};
static const struct file_operations msm_fops_pic = {
.owner = THIS_MODULE,
.open = msm_open,
.unlocked_ioctl = msm_ioctl_pic,
.release = msm_release_pic,
.poll = msm_poll_pic,
};
static int msm_setup_cdev(struct msm_cam_device *msm,
int node,
dev_t devno,
const char *suffix,
const struct file_operations *fops)
{
int rc = -ENODEV;
struct device *device =
device_create(msm_class, NULL,
devno, NULL,
"%s%d", suffix, node);
if (IS_ERR(device)) {
rc = PTR_ERR(device);
pr_err("%s: error creating device: %d\n", __func__, rc);
return rc;
}
cdev_init(&msm->cdev, fops);
msm->cdev.owner = THIS_MODULE;
rc = cdev_add(&msm->cdev, devno, 1);
if (rc < 0) {
pr_err("%s: error adding cdev: %d\n", __func__, rc);
device_destroy(msm_class, devno);
return rc;
}
return rc;
}
static int msm_tear_down_cdev(struct msm_cam_device *msm, dev_t devno)
{
cdev_del(&msm->cdev);
device_destroy(msm_class, devno);
return 0;
}
static uint32_t led_ril_status_value;
static uint32_t led_wimax_status_value;
static uint32_t led_hotspot_status_value;
static uint16_t led_low_temp_limit;
static uint16_t led_low_cap_limit;
static struct kobject *led_status_obj;
static ssize_t led_ril_status_get(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t length;
length = sprintf(buf, "%d\n", led_ril_status_value);
return length;
}
static ssize_t led_ril_status_set(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
uint32_t tmp = 0;
if (buf[1] == '\n')
tmp = buf[0] - 0x30;
led_ril_status_value = tmp;
pr_info("[CAM]led_ril_status_value = %d\n", led_ril_status_value);
return count;
}
static ssize_t led_wimax_status_get(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t length;
length = sprintf(buf, "%d\n", led_wimax_status_value);
return length;
}
static ssize_t led_wimax_status_set(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
uint32_t tmp = 0;
if (buf[1] == '\n')
tmp = buf[0] - 0x30;
led_wimax_status_value = tmp;
pr_info("[CAM]led_wimax_status_value = %d\n", led_wimax_status_value);
return count;
}
static ssize_t led_hotspot_status_get(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t length;
length = sprintf(buf, "%d\n", led_hotspot_status_value);
return length;
}
static ssize_t led_hotspot_status_set(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
uint32_t tmp = 0;
tmp = buf[0] - 0x30; /* only get the first char */
led_hotspot_status_value = tmp;
pr_info("[CAM]led_hotspot_status_value = %d\n", led_hotspot_status_value);
return count;
}
static ssize_t low_temp_limit_get(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t length;
length = sprintf(buf, "%d\n", led_low_temp_limit);
return length;
}
static ssize_t low_cap_limit_get(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t length;
length = sprintf(buf, "%d\n", led_low_cap_limit);
return length;
}
static DEVICE_ATTR(led_ril_status, 0644,
led_ril_status_get,
led_ril_status_set);
static DEVICE_ATTR(led_wimax_status, 0644,
led_wimax_status_get,
led_wimax_status_set);
static DEVICE_ATTR(led_hotspot_status, 0644,
led_hotspot_status_get,
led_hotspot_status_set);
static DEVICE_ATTR(low_temp_limit, 0444,
low_temp_limit_get,
NULL);
static DEVICE_ATTR(low_cap_limit, 0444,
low_cap_limit_get,
NULL);
static int msm_camera_sysfs_init(struct msm_sync *sync)
{
int ret = 0;
CDBG("msm_camera:kobject creat and add\n");
led_status_obj = kobject_create_and_add("camera_led_status", NULL);
if (led_status_obj == NULL) {
pr_info("[CAM]msm_camera: subsystem_register failed\n");
ret = -ENOMEM;
goto error;
}
ret = sysfs_create_file(led_status_obj,
&dev_attr_led_ril_status.attr);
if (ret) {
pr_info("[CAM]msm_camera: sysfs_create_file ril failed\n");
ret = -EFAULT;
goto error;
}
ret = sysfs_create_file(led_status_obj,
&dev_attr_led_wimax_status.attr);
if (ret) {
pr_info("[CAM]msm_camera: sysfs_create_file wimax failed\n");
ret = -EFAULT;
goto error;
}
ret = sysfs_create_file(led_status_obj,
&dev_attr_led_hotspot_status.attr);
if (ret) {
pr_info("[CAM]msm_camera: sysfs_create_file hotspot failed\n");
ret = -EFAULT;
goto error;
}
ret = sysfs_create_file(led_status_obj,
&dev_attr_low_temp_limit.attr);
if (ret) {
pr_info("[CAM]msm_camera:sysfs_create_file low_temp_limit failed\n");
ret = -EFAULT;
goto error;
}
ret = sysfs_create_file(led_status_obj,
&dev_attr_low_cap_limit.attr);
if (ret) {
pr_info("[CAM]msm_camera: sysfs_create_file low_cap_limit failed\n");
ret = -EFAULT;
goto error;
}
led_low_temp_limit = sync->sdata->flash_cfg->low_temp_limit;
led_low_cap_limit = sync->sdata->flash_cfg->low_cap_limit;
return ret;
error:
kobject_del(led_status_obj);
return ret;
}
static int msm_sync_init(struct msm_sync *sync,
struct platform_device *pdev,
int (*sensor_probe)( struct msm_camera_sensor_info *,
struct msm_sensor_ctrl *))
{
int rc = 0;
struct msm_sensor_ctrl sctrl;
sync->sdata = pdev->dev.platform_data;
msm_queue_init(&sync->event_q, "event");
msm_queue_init(&sync->frame_q, "frame");
msm_queue_init(&sync->pict_q, "pict");
msm_queue_init(&sync->vpe_q, "vpe");
wake_lock_init(&sync->wake_lock, WAKE_LOCK_IDLE, "msm_camera");
rc = msm_camio_probe_on(pdev);
if (rc < 0) {
wake_lock_destroy(&sync->wake_lock);
return rc;
}
rc = sensor_probe(sync->sdata, &sctrl);
if (rc >= 0) {
sync->pdev = pdev;
sync->sctrl = sctrl;
}
msm_camio_probe_off(pdev);
if (rc < 0) {
pr_err("%s: failed to initialize %s\n",
__func__,
sync->sdata->sensor_name);
wake_lock_destroy(&sync->wake_lock);
return rc;
}
camera_node = sync->sdata->dev_node;
sync->opencnt = 0;
sync->core_powered_on = 0;
sync->ignore_qcmd = false;
sync->ignore_qcmd_type = -1;
sync->qcmd_done = false;
mutex_init(&sync->lock);
if (sync->sdata->strobe_flash_data) {
sync->sdata->strobe_flash_data->state = 0;
spin_lock_init(&sync->sdata->strobe_flash_data->spin_lock);
}
CDBG("%s: initialized %s\n", __func__, sync->sdata->sensor_name);
return rc;
}
static int msm_sync_destroy(struct msm_sync *sync)
{
wake_lock_destroy(&sync->wake_lock);
return 0;
}
static int msm_device_init(struct msm_cam_device *pmsm,
struct msm_sync *sync,
int node)
{
int dev_num = 4 * node;
int rc = msm_setup_cdev(pmsm, node,
MKDEV(MAJOR(msm_devno), dev_num),
"control", &msm_fops_control);
if (rc < 0) {
pr_err("%s: error creating control node: %d\n", __func__, rc);
return rc;
}
rc = msm_setup_cdev(pmsm + 1, node,
MKDEV(MAJOR(msm_devno), dev_num + 1),
"config", &msm_fops_config);
if (rc < 0) {
pr_err("%s: error creating config node: %d\n", __func__, rc);
msm_tear_down_cdev(pmsm, MKDEV(MAJOR(msm_devno),
dev_num));
return rc;
}
rc = msm_setup_cdev(pmsm + 2, node,
MKDEV(MAJOR(msm_devno), dev_num + 2),
"frame", &msm_fops_frame);
if (rc < 0) {
pr_err("%s: error creating frame node: %d\n", __func__, rc);
msm_tear_down_cdev(pmsm,
MKDEV(MAJOR(msm_devno), dev_num));
msm_tear_down_cdev(pmsm + 1,
MKDEV(MAJOR(msm_devno), dev_num + 1));
return rc;
}
rc = msm_setup_cdev(pmsm + 3, node,
MKDEV(MAJOR(msm_devno), dev_num + 3),
"pic", &msm_fops_pic);
if (rc < 0) {
pr_err("%s: error creating pic node: %d\n", __func__, rc);
msm_tear_down_cdev(pmsm,
MKDEV(MAJOR(msm_devno), dev_num));
msm_tear_down_cdev(pmsm + 1,
MKDEV(MAJOR(msm_devno), dev_num + 1));
msm_tear_down_cdev(pmsm + 2,
MKDEV(MAJOR(msm_devno), dev_num + 2));
return rc;
}
atomic_set(&pmsm[0].opened, 0);
atomic_set(&pmsm[1].opened, 0);
atomic_set(&pmsm[2].opened, 0);
atomic_set(&pmsm[3].opened, 0);
pmsm[0].sync = sync;
pmsm[1].sync = sync;
pmsm[2].sync = sync;
pmsm[3].sync = sync;
return rc;
}
int msm_camera_drv_start_liteon(struct platform_device *dev,
int (*sensor_probe)(struct msm_camera_sensor_info *,
struct msm_sensor_ctrl *))
{
struct msm_cam_device *pmsm = NULL;
struct msm_sync *sync;
int rc = -ENODEV;
if (camera_node >= MSM_MAX_CAMERA_SENSORS) {
pr_err("%s: too many camera sensors\n", __func__);
return rc;
}
if (!msm_class) {
/* There are three device nodes per sensor */
rc = alloc_chrdev_region(&msm_devno, 0,
4 * MSM_MAX_CAMERA_SENSORS,
"msm_camera");
if (rc < 0) {
pr_err("%s: failed to allocate chrdev: %d\n", __func__,
rc);
return rc;
}
msm_class = class_create(THIS_MODULE, "msm_camera");
if (IS_ERR(msm_class)) {
rc = PTR_ERR(msm_class);
pr_err("%s: create device class failed: %d\n",
__func__, rc);
return rc;
}
}
pmsm = kzalloc(sizeof(struct msm_cam_device) * 4 +
sizeof(struct msm_sync), GFP_ATOMIC);
if (!pmsm)
return -ENOMEM;
sync = (struct msm_sync *)(pmsm + 4);
rc = msm_sync_init(sync, dev, sensor_probe);
if (rc < 0) {
kfree(pmsm);
return rc;
}
CDBG("%s: setting camera node %d\n", __func__, camera_node);
rc = msm_device_init(pmsm, sync, camera_node);
if (rc < 0) {
msm_sync_destroy(sync);
kfree(pmsm);
return rc;
}
if (!!sync->sdata->flash_cfg)
{
msm_camera_sysfs_init(sync);
}
camera_type[camera_node] = sync->sctrl.s_camera_type;
sensor_mount_angle[camera_node] = sync->sctrl.s_mount_angle;
camera_node++;
list_add(&sync->list, &msm_sensors);
return rc;
}
EXPORT_SYMBOL(msm_camera_drv_start_liteon);
| bcnice20/Shooter-2.6.35_mr | drivers/media/video/msm/msm_camera.c | C | gpl-2.0 | 106,421 |
/*
Copyright (c) 2005-2009 by Jakob Schroeter <js@camaya.net>
This file is part of the gloox library. http://camaya.net/gloox
This software is distributed under a license. The full license
agreement can be found in the file LICENSE in this distribution.
This software may not be copied, modified, sold or distributed
other than expressed in the named license agreement.
This software is distributed without any warranty.
*/
#include "messageeventfilter.h"
#include "messageeventhandler.h"
#include "messagesession.h"
#include "message.h"
#include "messageevent.h"
#include "error.h"
namespace gloox
{
MessageEventFilter::MessageEventFilter( MessageSession* parent )
: MessageFilter( parent ), m_messageEventHandler( 0 ), m_requestedEvents( 0 ),
m_lastSent( MessageEventCancel ), m_disable( false )
{
}
MessageEventFilter::~MessageEventFilter()
{
}
void MessageEventFilter::filter( Message& msg )
{
if( m_disable || !m_messageEventHandler )
return;
if( msg.subtype() == Message::Error )
{
if( msg.error() && msg.error()->error() == StanzaErrorFeatureNotImplemented )
m_disable = true;
return;
}
const MessageEvent* me = msg.findExtension<MessageEvent>( ExtMessageEvent );
if( !me )
{
m_requestedEvents = 0;
m_lastID = EmptyString;
return;
}
if( msg.body().empty() )
m_messageEventHandler->handleMessageEvent( msg.from(), (MessageEventType)me->event() );
else
{
m_lastID = msg.id();
m_requestedEvents = 0;
m_requestedEvents = me->event();
}
}
void MessageEventFilter::raiseMessageEvent( MessageEventType event )
{
if( m_disable || ( !( m_requestedEvents & event ) && ( event != MessageEventCancel ) ) )
return;
switch( event )
{
case MessageEventOffline:
case MessageEventDelivered:
case MessageEventDisplayed:
m_requestedEvents &= ~event;
break;
case MessageEventComposing:
if( m_lastSent == MessageEventComposing )
return;
break;
case MessageEventCancel:
default:
break;
}
m_lastSent = event;
Message m( Message::Normal, m_parent->target() );
m.addExtension( new MessageEvent( event, m_lastID ) );
send( m );
}
void MessageEventFilter::decorate( Message& msg )
{
if( m_disable )
return;
msg.addExtension( new MessageEvent( MessageEventOffline | MessageEventDelivered |
MessageEventDisplayed | MessageEventComposing ) );
m_lastSent = MessageEventCancel;
}
void MessageEventFilter::registerMessageEventHandler( MessageEventHandler* meh )
{
m_messageEventHandler = meh;
}
void MessageEventFilter::removeMessageEventHandler()
{
m_messageEventHandler = 0;
}
}
| segfault/gloox-clone | src/messageeventfilter.cpp | C++ | gpl-2.0 | 2,847 |
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* 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.
*
*/
#include "fullpipe/fullpipe.h"
#include "fullpipe/objectnames.h"
#include "fullpipe/constants.h"
#include "fullpipe/gameloader.h"
#include "fullpipe/motion.h"
#include "fullpipe/scenes.h"
#include "fullpipe/statics.h"
#include "fullpipe/interaction.h"
#include "fullpipe/behavior.h"
namespace Fullpipe {
struct Hanger {
StaticANIObject *ani;
int field_4;
int field_8;
int phase;
};
void scene09_setupGrit(Scene *sc) {
if (g_vars->scene09_grit->_statics->_staticsId == ST_GRT9_GRIT) {
if (!getGameLoaderInventory()->getCountItemsWithId(ANI_INV_COIN)) {
if (g_fp->getObjectState(sO_CoinSlot_1) == g_fp->getObjectEnumState(sO_CoinSlot_1, sO_Empty)
&& (g_vars->swallowedEgg1->_value.intValue == ANI_INV_EGGBOOT || g_vars->swallowedEgg2->_value.intValue == ANI_INV_EGGBOOT || g_vars->swallowedEgg3->_value.intValue == ANI_INV_EGGBOOT)) {
Scene *oldsc = g_fp->_currentScene;
g_fp->_currentScene = sc;
g_vars->scene09_grit->changeStatics2(ST_GRT9_NORM);
g_fp->_currentScene = oldsc;
}
}
}
}
void scene09_initScene(Scene *sc) {
g_vars->scene09_flyingBall = 0;
g_vars->scene09_numSwallenBalls = 0;
g_vars->scene09_gulper = sc->getStaticANIObject1ById(ANI_GLOTATEL, -1);
g_vars->scene09_spitter = sc->getStaticANIObject1ById(ANI_PLEVATEL, -1);
g_vars->scene09_grit = sc->getStaticANIObject1ById(ANI_GRIT_9, -1);
g_vars->scene09_gulperIsPresent = true;
g_vars->scene09_dudeIsOnLadder = false;
g_vars->scene09_interactingHanger = -1;
g_vars->scene09_intHangerPhase = -1;
g_vars->scene09_intHangerMaxPhase = -1000;
g_vars->scene09_flyingBalls.clear();
for (uint i = 0; i < g_vars->scene09_hangers.size(); i++)
delete g_vars->scene09_hangers[i];
g_vars->scene09_hangers.clear();
g_vars->scene09_numMovingHangers = 4;
StaticANIObject *hanger = sc->getStaticANIObject1ById(ANI_VISUNCHIK, -1);
Hanger *hng = new Hanger;
hng->ani = hanger;
hng->phase = 0;
hng->field_4 = 0;
hng->field_8 = 0;
g_vars->scene09_hangers.push_back(hng);
int x = 75;
for (int i = 1; x < 300; i++, x += 75) {
StaticANIObject *ani = new StaticANIObject(hanger);
ani->show1(x + hanger->_ox, hanger->_oy, MV_VSN_CYCLE2, 0);
sc->addStaticANIObject(ani, 1);
hng = new Hanger;
hng->ani = ani;
hng->phase = 0;
hng->field_4 = 0;
hng->field_8 = 0;
g_vars->scene09_hangers.push_back(hng);
}
g_vars->scene09_sceneBalls.clear();
StaticANIObject *newball1 = new StaticANIObject(sc->getStaticANIObject1ById(ANI_BALL9, -1));
newball1->setAlpha(0xc8);
for (int i = 0; i < 4; i++) {
StaticANIObject *newball = new StaticANIObject(newball1);
newball->setAlpha(0xc8);
g_vars->scene09_sceneBalls.push_back(newball);
sc->addStaticANIObject(newball, 1);
}
delete newball1;
g_fp->setObjectState(sO_RightStairs_9, g_fp->getObjectEnumState(sO_RightStairs_9, sO_IsClosed));
GameVar *eggvar = g_fp->getGameLoaderGameVar()->getSubVarByName("OBJSTATES")->getSubVarByName(sO_GulpedEggs);
g_vars->swallowedEgg1 = eggvar->getSubVarByName(sO_Egg1);
g_vars->swallowedEgg2 = eggvar->getSubVarByName(sO_Egg2);
g_vars->swallowedEgg3 = eggvar->getSubVarByName(sO_Egg3);
scene09_setupGrit(sc);
g_fp->initArcadeKeys("SC_9");
g_fp->lift_setButton(sO_Level1, ST_LBN_1N);
g_fp->setArcadeOverlay(PIC_CSR_ARCADE4);
}
int sceneHandler09_updateScreenCallback() {
int res = g_fp->drawArcadeOverlay(g_fp->_objectIdAtCursor == ANI_VISUNCHIK || g_vars->scene09_interactingHanger >= 0);
if (!res)
g_fp->_updateScreenCallback = 0;
return res;
}
int scene09_updateCursor() {
g_fp->updateCursorCommon();
if (g_vars->scene09_interactingHanger < 0) {
if (g_fp->_objectIdAtCursor == ANI_VISUNCHIK) {
if (g_fp->_cursorId == PIC_CSR_ITN)
g_fp->_updateScreenCallback = sceneHandler09_updateScreenCallback;
} else {
if (g_fp->_objectIdAtCursor == PIC_SC9_LADDER_R && g_fp->_cursorId == PIC_CSR_ITN)
g_fp->_cursorId = (g_vars->scene09_dudeY < 350) ? PIC_CSR_GOD : PIC_CSR_GOU;
}
} else {
g_fp->_cursorId = PIC_CSR_ITN;
}
return g_fp->_cursorId;
}
void sceneHandler09_winArcade() {
if (g_vars->scene09_gulper->_flags & 4) {
g_vars->scene09_gulper->changeStatics2(ST_GLT_SIT);
g_vars->scene09_gulper->startAnim(MV_GLT_FLYAWAY, 0, -1);
g_fp->setObjectState(sO_Jug, g_fp->getObjectEnumState(sO_Jug, sO_Unblocked));
g_fp->setObjectState(sO_RightStairs_9, g_fp->getObjectEnumState(sO_RightStairs_9, sO_IsOpened));
g_vars->scene09_gulperIsPresent = false;
}
}
void sceneHandler09_startAuntie() {
MessageQueue *mq = new MessageQueue(g_fp->_currentScene->getMessageQueueById(QU_TTA9_GOL), 0, 1);
mq->getExCommandByIndex(0)->_x = g_fp->_sceneRect.right + 30;
mq->chain(0);
}
void sceneHandler09_spitterClick() {
debugC(2, kDebugSceneLogic, "scene09: spitterClick");
if (g_vars->scene09_spitter->_flags & 4) {
PicAniInfo info;
g_vars->scene09_spitter->getPicAniInfo(&info);
g_vars->scene09_spitter->_messageQueueId = 0;
g_vars->scene09_spitter->changeStatics2(ST_PLV_SIT);
int x = g_vars->scene09_spitter->_ox - 10;
int y = g_vars->scene09_spitter->_oy + 145;
g_vars->scene09_spitter->setPicAniInfo(&info);
if (ABS(x - g_fp->_aniMan->_ox) > 1 || ABS(y - g_fp->_aniMan->_oy) > 1) {
MessageQueue *mq = getCurrSceneSc2MotionController()->startMove(g_fp->_aniMan, x, y, 1, ST_MAN_UP);
if (mq) {
ExCommand *ex = new ExCommand(0, 17, MSG_SC9_PLVCLICK, 0, 0, 0, 1, 0, 0, 0);
ex->_excFlags = 2;
mq->addExCommandToEnd(ex);
postExCommand(g_fp->_aniMan->_id, 2, x, y, 0, -1);
}
} else {
if (!g_fp->_aniMan->_movement) {
g_vars->scene09_spitter->changeStatics2(ST_PLV_SIT);
g_vars->scene09_spitter->hide();
g_fp->_aniMan->startAnim(MV_MAN9_SHOOT, 0, -1);
g_fp->stopAllSoundInstances(SND_9_006);
}
g_fp->_aniMan2 = 0;
if (g_fp->_sceneRect.left < 800)
g_fp->_currentScene->_x = 800 - g_fp->_sceneRect.left;
}
}
}
void sceneHandler09_eatBall() {
debugC(2, kDebugSceneLogic, "scene09: eatBall");
if (g_vars->scene09_flyingBall) {
g_vars->scene09_flyingBall->hide();
g_vars->scene09_flyingBalls.pop_back();
//g_vars->scene09_sceneBalls.pop_back();
g_vars->scene09_flyingBall = 0;
g_vars->scene09_numSwallenBalls++;
if (g_vars->scene09_numSwallenBalls >= 3) {
MessageQueue *mq = g_vars->scene09_gulper->getMessageQueue();
if (mq) {
ExCommand *ex = new ExCommand(ANI_GLOTATEL, 1, MV_GLT_FLYAWAY, 0, 0, 0, 1, 0, 0, 0);
ex->_excFlags |= 2;
mq->addExCommandToEnd(ex);
}
g_fp->setObjectState(sO_Jug, g_fp->getObjectEnumState(sO_Jug, sO_Unblocked));
g_fp->setObjectState(sO_RightStairs_9, g_fp->getObjectEnumState(sO_RightStairs_9, sO_IsOpened));
g_vars->scene09_gulperIsPresent = false;
}
}
}
void sceneHandler09_showBall() {
debugC(2, kDebugSceneLogic, "scene09: showBall");
if (g_vars->scene09_sceneBalls.size()) {
StaticANIObject *ani = g_vars->scene09_sceneBalls.front();
g_vars->scene09_sceneBalls.push_back(ani);
g_vars->scene09_sceneBalls.remove_at(0);
g_vars->scene09_flyingBalls.insert_at(0, ani);
ani->show1(g_fp->_aniMan->_ox + 94, g_fp->_aniMan->_oy - 162, MV_BALL9_EXPLODE, 0);
}
}
void sceneHandler09_cycleHangers() {
for (int i = 0; i < g_vars->scene09_numMovingHangers; i++) {
Movement *mov = g_vars->scene09_hangers[i]->ani->_movement;
if (mov && mov->_id == MV_VSN_CYCLE2) {
int idx;
if (g_vars->scene09_hangers[i]->phase >= 0)
idx = 18 - g_vars->scene09_hangers[i]->phase / 5;
else
idx = 18 - g_vars->scene09_hangers[i]->phase * 10 / 43;
if (idx > 38)
idx = 38;
if (idx < 1)
idx = 1;
mov->setDynamicPhaseIndex(idx);
}
}
}
void sceneHandler09_limitHangerPhase() {
for (int i = 0; i < g_vars->scene09_numMovingHangers; i++) {
if (i != g_vars->scene09_interactingHanger) {
g_vars->scene09_hangers[i]->phase += g_vars->scene09_hangers[i]->field_8;
if (g_vars->scene09_hangers[i]->phase > 85)
g_vars->scene09_hangers[i]->phase = 85;
if (g_vars->scene09_hangers[i]->phase < -85)
g_vars->scene09_hangers[i]->phase = -85;
if (g_vars->scene09_hangers[i]->phase < 0)
g_vars->scene09_hangers[i]->field_8++;
if (g_vars->scene09_hangers[i]->phase > 0)
g_vars->scene09_hangers[i]->field_8--;
}
}
}
void sceneHandler09_collideBall(uint num) {
debugC(2, kDebugSceneLogic, "scene09: collideBall");
if (g_vars->scene09_gulperIsPresent) {
g_vars->scene09_flyingBall = g_vars->scene09_flyingBalls[num];
if (g_vars->scene09_gulper) {
g_vars->scene09_gulper->changeStatics2(ST_GLT_SIT);
MessageQueue *mq = new MessageQueue(g_fp->_currentScene->getMessageQueueById(QU_SC9_EATBALL), 0, 0);
mq->setFlags(mq->getFlags() | 1);
if (!mq->chain(g_vars->scene09_gulper))
delete mq;
}
}
}
void sceneHandler09_ballExplode(uint num) {
debugC(2, kDebugSceneLogic, "scene09: ballExplode(%d) of %d", num, g_vars->scene09_flyingBalls.size());
StaticANIObject *ball = g_vars->scene09_flyingBalls[num];
g_vars->scene09_flyingBalls.remove_at(num);
MessageQueue *mq = new MessageQueue(g_fp->_currentScene->getMessageQueueById(QU_SC9_BALLEXPLODE), 0, 1);
mq->setParamInt(-1, ball->_odelay);
if (!mq->chain(ball))
delete mq;
}
void sceneHandler09_checkHangerCollide() {
for (uint b = 0; b < g_vars->scene09_flyingBalls.size(); b++) {
StaticANIObject *ball = g_vars->scene09_flyingBalls[b];
int newx = ball->_ox + 5;
ball->setOXY(newx, ball->_oy);
if (newx <= 1398 || g_vars->scene09_flyingBall) {
if (g_vars->scene09_gulperIsPresent)
goto LABEL_11;
} else if (g_vars->scene09_gulperIsPresent) {
sceneHandler09_collideBall(b);
continue;
}
if (newx > 1600) {
sceneHandler09_ballExplode(b);
continue;
}
LABEL_11:
bool hit;
for (int i = 0; i < g_vars->scene09_numMovingHangers; i++) {
for (int j = 0; j < 4; j++) {
int x1 = newx + g_vars->scene09_hangerOffsets[j].x;
int y1 = ball->_oy + g_vars->scene09_hangerOffsets[j].y;
// Check 2 pixels to compensate cord width
hit = g_vars->scene09_hangers[i]->ani->isPixelHitAtPos(x1, y1)
&& g_vars->scene09_hangers[i]->ani->isPixelHitAtPos(x1 + 10, y1);
if (hit) {
sceneHandler09_ballExplode(b);
break;
}
}
if (hit)
break;
}
}
}
void sceneHandler09_hangerStartCycle() {
StaticANIObject *ani = g_vars->scene09_hangers[g_vars->scene09_interactingHanger]->ani;
if (ani->_movement) {
ani->startAnim(MV_VSN_CYCLE2, 0, -1);
g_vars->scene09_hangers[g_vars->scene09_interactingHanger]->field_8 = 0;
g_vars->scene09_hangers[g_vars->scene09_interactingHanger]->phase = g_vars->scene09_intHangerPhase + (g_fp->_mouseScreenPos.y - g_vars->scene09_clickY) / 2;
if (g_vars->scene09_intHangerMaxPhase != -1000 && g_vars->scene09_hangers[g_vars->scene09_interactingHanger]->phase != g_vars->scene09_intHangerMaxPhase) {
ExCommand *ex = new ExCommand(0, 35, SND_9_019, 0, 0, 0, 1, 0, 0, 0);
ex->_field_14 = 1;
ex->_excFlags |= 2;
ex->postMessage();
g_vars->scene09_intHangerMaxPhase = -1000;
}
} else {
g_vars->scene09_interactingHanger = -1;
}
}
void scene09_visCallback(int *phase) {
// do nothing
}
int sceneHandler09(ExCommand *cmd) {
if (cmd->_messageKind != 17)
return 0;
switch (cmd->_messageNum) {
case MSG_CMN_WINARCADE:
sceneHandler09_winArcade();
break;
case MSG_SC9_STARTTIOTIA:
sceneHandler09_startAuntie();
break;
case MSG_SC9_FROMLADDER:
getCurrSceneSc2MotionController()->activate();
getGameLoaderInteractionController()->enableFlag24();
g_vars->scene09_dudeIsOnLadder = false;
break;
case MSG_SC9_TOLADDER:
getCurrSceneSc2MotionController()->deactivate();
getGameLoaderInteractionController()->disableFlag24();
g_vars->scene09_dudeIsOnLadder = true;
break;
case MSG_SC9_PLVCLICK:
sceneHandler09_spitterClick();
break;
case MSG_SC9_FLOWN:
g_vars->scene09_gulperIsPresent = false;
break;
case MSG_SC9_EATBALL:
sceneHandler09_eatBall();
break;
case MSG_SC9_SHOWBALL:
sceneHandler09_showBall();
break;
case 367:
if (g_fp->isDemo() && g_fp->getLanguage() == Common::RU_RUS) {
g_fp->_needRestart = true;
return 0;
}
break;
case 33:
{
int res = 0;
if (g_fp->_aniMan2) {
int x = g_fp->_aniMan2->_ox;
g_vars->scene09_dudeY = g_fp->_aniMan2->_oy;
if (x < g_fp->_sceneRect.left + 200)
g_fp->_currentScene->_x = x - g_fp->_sceneRect.left - 300;
if (x > g_fp->_sceneRect.right - 200)
g_fp->_currentScene->_x = x - g_fp->_sceneRect.right + 300;
res = 1;
g_fp->sceneAutoScrolling();
} else {
if (g_fp->_aniMan->_movement && g_fp->_aniMan->_movement->_id != MV_MAN9_SHOOT)
g_fp->_aniMan2 = g_fp->_aniMan;
}
sceneHandler09_cycleHangers();
sceneHandler09_limitHangerPhase();
sceneHandler09_checkHangerCollide();
if (g_vars->scene09_interactingHanger >= 0)
sceneHandler09_hangerStartCycle();
g_fp->_behaviorManager->updateBehaviors();
g_fp->startSceneTrack();
return res;
}
case 30:
if (g_vars->scene09_interactingHanger >= 0) {
if (ABS(g_vars->scene09_hangers[g_vars->scene09_interactingHanger]->phase) < 15) {
g_vars->scene09_hangers[g_vars->scene09_interactingHanger]->ani->_callback2 = 0; // Really NULL
g_vars->scene09_hangers[g_vars->scene09_interactingHanger]->ani->changeStatics2(ST_VSN_NORMAL);
}
}
g_vars->scene09_interactingHanger = -1;
break;
case 29:
{
StaticANIObject *ani = g_fp->_currentScene->getStaticANIObjectAtPos(g_fp->_sceneRect.left + cmd->_x, g_fp->_sceneRect.top + cmd->_y);
if (ani) {
if (ani->_id == ANI_PLEVATEL) {
sceneHandler09_spitterClick();
break;
}
if (ani->_id == ANI_VISUNCHIK) {
debugC(2, kDebugSceneLogic, "scene09: VISUNCHIK");
if (g_vars->scene09_numMovingHangers > 0) {
int hng = 0;
while (g_vars->scene09_hangers[hng]->ani != ani) {
++hng;
if (hng >= g_vars->scene09_numMovingHangers)
break;
}
g_vars->scene09_interactingHanger = hng;
g_vars->scene09_intHangerPhase = g_vars->scene09_hangers[hng]->phase;
g_vars->scene09_intHangerMaxPhase = g_vars->scene09_hangers[hng]->phase;
g_vars->scene09_clickY = cmd->_y;
if (!g_vars->scene09_hangers[hng]->ani->_movement || g_vars->scene09_hangers[hng]->ani->_movement->_id != MV_VSN_CYCLE2) {
g_vars->scene09_hangers[hng]->ani->changeStatics2(ST_VSN_NORMAL);
g_vars->scene09_hangers[hng]->ani->startAnim(MV_VSN_CYCLE2, 0, -1);
g_vars->scene09_hangers[hng]->ani->_callback2 = scene09_visCallback;
}
ExCommand *ex = new ExCommand(0, 35, SND_9_018, 0, 0, 0, 1, 0, 0, 0);
ex->_field_14 = 1;
ex->_excFlags |= 2;
ex->postMessage();
}
break;
}
}
if (g_vars->scene09_dudeIsOnLadder && g_fp->_currentScene->getPictureObjectIdAtPos(cmd->_sceneClickX, cmd->_sceneClickY) == PIC_SC9_LADDER_R
&& !cmd->_param && !g_fp->_aniMan->_movement) {
handleObjectInteraction(g_fp->_aniMan, g_fp->_currentScene->getPictureObjectById(PIC_SC9_LADDER_R, 0), 0);
}
if (!ani || !canInteractAny(g_fp->_aniMan, ani, cmd->_param)) {
int picId = g_fp->_currentScene->getPictureObjectIdAtPos(cmd->_sceneClickX, cmd->_sceneClickY);
PictureObject *pic = g_fp->_currentScene->getPictureObjectById(picId, 0);
if (!pic || !canInteractAny(g_fp->_aniMan, pic, cmd->_param)) {
if ((g_fp->_sceneRect.right - cmd->_sceneClickX < 47 && g_fp->_sceneRect.right < g_fp->_sceneWidth - 1) || (cmd->_sceneClickX - g_fp->_sceneRect.left < 47 && g_fp->_sceneRect.left > 0))
g_fp->processArcade(cmd);
}
}
break;
}
}
return 0;
}
} // End of namespace Fullpipe
| bSr43/scummvm | engines/fullpipe/scenes/scene09.cpp | C++ | gpl-2.0 | 16,585 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>matrix_cross_product.hpp Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<!-- Generated by Doxygen 1.7.4 -->
<div id="top">
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="logo-mini.png"/></td>
</tr>
</tbody>
</table>
</div>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
</ul>
</div>
<div class="header">
<div class="headertitle">
<div class="title">matrix_cross_product.hpp</div> </div>
</div>
<div class="contents">
<div class="fragment"><pre class="fragment"><a name="l00001"></a>00001
<a name="l00002"></a>00002 <span class="comment">// OpenGL Mathematics Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net)</span>
<a name="l00004"></a>00004 <span class="comment"></span><span class="comment">// Created : 2005-12-21</span>
<a name="l00005"></a>00005 <span class="comment">// Updated : 2006-11-13</span>
<a name="l00006"></a>00006 <span class="comment">// Licence : This source is under MIT License</span>
<a name="l00007"></a>00007 <span class="comment">// File : glm/gtx/matrix_cross_product.hpp</span>
<a name="l00009"></a>00009 <span class="comment"></span><span class="comment">// Dependency:</span>
<a name="l00010"></a>00010 <span class="comment">// - GLM core</span>
<a name="l00012"></a>00012 <span class="comment"></span>
<a name="l00013"></a>00013 <span class="preprocessor">#ifndef glm_gtx_matrix_cross_product</span>
<a name="l00014"></a>00014 <span class="preprocessor"></span><span class="preprocessor">#define glm_gtx_matrix_cross_product</span>
<a name="l00015"></a>00015 <span class="preprocessor"></span>
<a name="l00016"></a>00016 <span class="comment">// Dependency:</span>
<a name="l00017"></a>00017 <span class="preprocessor">#include "../glm.hpp"</span>
<a name="l00018"></a>00018
<a name="l00019"></a>00019 <span class="preprocessor">#if(defined(GLM_MESSAGES) && !defined(glm_ext))</span>
<a name="l00020"></a>00020 <span class="preprocessor"></span><span class="preprocessor"># pragma message("GLM: GLM_GTX_matrix_cross_product extension included")</span>
<a name="l00021"></a>00021 <span class="preprocessor"></span><span class="preprocessor">#endif</span>
<a name="l00022"></a>00022 <span class="preprocessor"></span>
<a name="l00023"></a>00023 <span class="keyword">namespace </span>glm{
<a name="l00024"></a>00024 <span class="keyword">namespace </span>gtx{
<a name="l00025"></a><a class="code" href="a00191.html">00025</a> <span class="keyword">namespace </span>matrix_cross_product
<a name="l00026"></a>00026 {
<a name="l00029"></a>00029
<a name="l00032"></a>00032 <span class="keyword">template</span> <<span class="keyword">typename</span> T>
<a name="l00033"></a>00033 <a class="code" href="a00014.html" title="Template for 3 * 3 matrix of floating-point numbers.">detail::tmat3x3<T></a> <a class="code" href="a00270.html#gaa153d0f2600403c659a81a39b59b0f2c" title="Build a cross product matrix.">matrixCross3</a>(
<a name="l00034"></a>00034 <a class="code" href="a00021.html" title="Basic 3D vector type.">detail::tvec3<T></a> <span class="keyword">const</span> & x);
<a name="l00035"></a>00035
<a name="l00038"></a>00038 <span class="keyword">template</span> <<span class="keyword">typename</span> T>
<a name="l00039"></a>00039 <a class="code" href="a00018.html" title="Template for 4 * 4 matrix of floating-point numbers.">detail::tmat4x4<T></a> <a class="code" href="a00270.html#ga8cb94c98874b9b3deff5ad590e0cac23" title="Build a cross product matrix.">matrixCross4</a>(
<a name="l00040"></a>00040 <a class="code" href="a00021.html" title="Basic 3D vector type.">detail::tvec3<T></a> <span class="keyword">const</span> & x);
<a name="l00041"></a>00041
<a name="l00043"></a>00043 }<span class="comment">//namespace matrix_cross_product</span>
<a name="l00044"></a>00044 }<span class="comment">//namespace gtx</span>
<a name="l00045"></a>00045 }<span class="comment">//namespace glm</span>
<a name="l00046"></a>00046
<a name="l00047"></a>00047 <span class="preprocessor">#include "matrix_cross_product.inl"</span>
<a name="l00048"></a>00048
<a name="l00049"></a>00049 <span class="keyword">namespace </span>glm{<span class="keyword">using namespace </span>gtx::matrix_cross_product;}
<a name="l00050"></a>00050
<a name="l00051"></a>00051 <span class="preprocessor">#endif//glm_gtx_matrix_cross_product</span>
</pre></div></div>
</div>
<hr class="footer"/><address class="footer"><small>Generated by 
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.4 </small></address>
</body>
</html>
| tuituji/184.1x-BerkeleyX-CG | hw2-linuxosx/glm-0.9.2.7/doc/api-0.9.2/a00072_source.html | HTML | gpl-2.0 | 5,723 |
/*
* Javassist, a Java-bytecode translator toolkit.
* Copyright (C) 1999- Shigeru Chiba. All Rights Reserved.
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. Alternatively, the contents of this file may be used under
* the terms of the GNU Lesser General Public License Version 2.1 or later,
* or the Apache License Version 2.0.
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*/
package org.hotswap.agent.javassist.tools.web;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
/**
* A web server for running sample programs.
* <p/>
* <p>This enables a Java program to instrument class files loaded by
* web browsers for applets. Since the (standard) security manager
* does not allow an applet to create and use a class loader,
* instrumenting class files must be done by this web server.
* <p/>
* <p><b>Note:</b> although this class is included in the Javassist API,
* it is provided as a sample implementation of the web server using
* Javassist. Especially, there might be security flaws in this server.
* Please use this with YOUR OWN RISK.
*/
public class Webserver {
private ServerSocket socket;
private org.hotswap.agent.javassist.ClassPool classPool;
protected org.hotswap.agent.javassist.Translator translator;
private final static byte[] endofline = {0x0d, 0x0a};
private final static int typeHtml = 1;
private final static int typeClass = 2;
private final static int typeGif = 3;
private final static int typeJpeg = 4;
private final static int typeText = 5;
/**
* If this field is not null, the class files taken from
* <code>ClassPool</code> are written out under the directory
* specified by this field. The directory name must not end
* with a directory separator.
*/
public String debugDir = null;
/**
* The top directory of html (and .gif, .class, ...) files.
* It must end with the directory separator such as "/".
* (For portability, "/" should be used as the directory separator.
* Javassist automatically translates "/" into a platform-dependent
* character.)
* If this field is null, the top directory is the current one where
* the JVM is running.
* <p/>
* <p>If the given URL indicates a class file and the class file
* is not found under the directory specified by this variable,
* then <code>Class.getResourceAsStream()</code> is called
* for searching the Java class paths.
*/
public String htmlfileBase = null;
/**
* Starts a web server.
* The port number is specified by the first argument.
*/
public static void main(String[] args) throws IOException {
if (args.length == 1) {
Webserver web = new Webserver(args[0]);
web.run();
} else
System.err.println(
"Usage: java Webserver <port number>");
}
/**
* Constructs a web server.
*
* @param port port number
*/
public Webserver(String port) throws IOException {
this(Integer.parseInt(port));
}
/**
* Constructs a web server.
*
* @param port port number
*/
public Webserver(int port) throws IOException {
socket = new ServerSocket(port);
classPool = null;
translator = null;
}
/**
* Requests the web server to use the specified
* <code>ClassPool</code> object for obtaining a class file.
*/
public void setClassPool(org.hotswap.agent.javassist.ClassPool loader) {
classPool = loader;
}
/**
* Adds a translator, which is called whenever a client requests
* a class file.
*
* @param cp the <code>ClassPool</code> object for obtaining
* a class file.
* @param t a translator.
*/
public void addTranslator(org.hotswap.agent.javassist.ClassPool cp, org.hotswap.agent.javassist.Translator t)
throws org.hotswap.agent.javassist.NotFoundException, org.hotswap.agent.javassist.CannotCompileException {
classPool = cp;
translator = t;
t.start(classPool);
}
/**
* Closes the socket.
*/
public void end() throws IOException {
socket.close();
}
/**
* Prints a log message.
*/
public void logging(String msg) {
System.out.println(msg);
}
/**
* Prints a log message.
*/
public void logging(String msg1, String msg2) {
System.out.print(msg1);
System.out.print(" ");
System.out.println(msg2);
}
/**
* Prints a log message.
*/
public void logging(String msg1, String msg2, String msg3) {
System.out.print(msg1);
System.out.print(" ");
System.out.print(msg2);
System.out.print(" ");
System.out.println(msg3);
}
/**
* Prints a log message with indentation.
*/
public void logging2(String msg) {
System.out.print(" ");
System.out.println(msg);
}
/**
* Begins the HTTP service.
*/
public void run() {
System.err.println("ready to service...");
for (; ; )
try {
ServiceThread th = new ServiceThread(this, socket.accept());
th.start();
} catch (IOException e) {
logging(e.toString());
}
}
final void process(Socket clnt) throws IOException {
InputStream in = new BufferedInputStream(clnt.getInputStream());
String cmd = readLine(in);
logging(clnt.getInetAddress().getHostName(),
new Date().toString(), cmd);
while (skipLine(in) > 0) {
}
OutputStream out = new BufferedOutputStream(clnt.getOutputStream());
try {
doReply(in, out, cmd);
} catch (BadHttpRequest e) {
replyError(out, e);
}
out.flush();
in.close();
out.close();
clnt.close();
}
private String readLine(InputStream in) throws IOException {
StringBuffer buf = new StringBuffer();
int c;
while ((c = in.read()) >= 0 && c != 0x0d)
buf.append((char) c);
in.read(); /* skip 0x0a (LF) */
return buf.toString();
}
private int skipLine(InputStream in) throws IOException {
int c;
int len = 0;
while ((c = in.read()) >= 0 && c != 0x0d)
++len;
in.read(); /* skip 0x0a (LF) */
return len;
}
/**
* Proceses a HTTP request from a client.
*
* @param out the output stream to a client
* @param cmd the command received from a client
*/
public void doReply(InputStream in, OutputStream out, String cmd)
throws IOException, BadHttpRequest {
int len;
int fileType;
String filename, urlName;
if (cmd.startsWith("GET /"))
filename = urlName = cmd.substring(5, cmd.indexOf(' ', 5));
else
throw new BadHttpRequest();
if (filename.endsWith(".class"))
fileType = typeClass;
else if (filename.endsWith(".html") || filename.endsWith(".htm"))
fileType = typeHtml;
else if (filename.endsWith(".gif"))
fileType = typeGif;
else if (filename.endsWith(".jpg"))
fileType = typeJpeg;
else
fileType = typeText; // or textUnknown
len = filename.length();
if (fileType == typeClass
&& letUsersSendClassfile(out, filename, len))
return;
checkFilename(filename, len);
if (htmlfileBase != null)
filename = htmlfileBase + filename;
if (File.separatorChar != '/')
filename = filename.replace('/', File.separatorChar);
File file = new File(filename);
if (file.canRead()) {
sendHeader(out, file.length(), fileType);
FileInputStream fin = new FileInputStream(file);
byte[] filebuffer = new byte[4096];
for (; ; ) {
len = fin.read(filebuffer);
if (len <= 0)
break;
else
out.write(filebuffer, 0, len);
}
fin.close();
return;
}
// If the file is not found under the html-file directory,
// then Class.getResourceAsStream() is tried.
if (fileType == typeClass) {
InputStream fin
= getClass().getResourceAsStream("/" + urlName);
if (fin != null) {
ByteArrayOutputStream barray = new ByteArrayOutputStream();
byte[] filebuffer = new byte[4096];
for (; ; ) {
len = fin.read(filebuffer);
if (len <= 0)
break;
else
barray.write(filebuffer, 0, len);
}
byte[] classfile = barray.toByteArray();
sendHeader(out, classfile.length, typeClass);
out.write(classfile);
fin.close();
return;
}
}
throw new BadHttpRequest();
}
private void checkFilename(String filename, int len)
throws BadHttpRequest {
for (int i = 0; i < len; ++i) {
char c = filename.charAt(i);
if (!Character.isJavaIdentifierPart(c) && c != '.' && c != '/')
throw new BadHttpRequest();
}
if (filename.indexOf("..") >= 0)
throw new BadHttpRequest();
}
private boolean letUsersSendClassfile(OutputStream out,
String filename, int length)
throws IOException, BadHttpRequest {
if (classPool == null)
return false;
byte[] classfile;
String classname
= filename.substring(0, length - 6).replace('/', '.');
try {
if (translator != null)
translator.onLoad(classPool, classname);
org.hotswap.agent.javassist.CtClass c = classPool.get(classname);
classfile = c.toBytecode();
if (debugDir != null)
c.writeFile(debugDir);
} catch (Exception e) {
throw new BadHttpRequest(e);
}
sendHeader(out, classfile.length, typeClass);
out.write(classfile);
return true;
}
private void sendHeader(OutputStream out, long dataLength, int filetype)
throws IOException {
out.write("HTTP/1.0 200 OK".getBytes());
out.write(endofline);
out.write("Content-Length: ".getBytes());
out.write(Long.toString(dataLength).getBytes());
out.write(endofline);
if (filetype == typeClass)
out.write("Content-Type: application/octet-stream".getBytes());
else if (filetype == typeHtml)
out.write("Content-Type: text/html".getBytes());
else if (filetype == typeGif)
out.write("Content-Type: image/gif".getBytes());
else if (filetype == typeJpeg)
out.write("Content-Type: image/jpg".getBytes());
else if (filetype == typeText)
out.write("Content-Type: text/plain".getBytes());
out.write(endofline);
out.write(endofline);
}
private void replyError(OutputStream out, BadHttpRequest e)
throws IOException {
logging2("bad request: " + e.toString());
out.write("HTTP/1.0 400 Bad Request".getBytes());
out.write(endofline);
out.write(endofline);
out.write("<H1>Bad Request</H1>".getBytes());
}
}
class ServiceThread extends Thread {
Webserver web;
Socket sock;
public ServiceThread(Webserver w, Socket s) {
web = w;
sock = s;
}
public void run() {
try {
web.process(sock);
} catch (IOException e) {
}
}
}
| HighTower1991/HotswapAgent | hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/tools/web/Webserver.java | Java | gpl-2.0 | 12,400 |
/* packet-rstat.c
* Stubs for Sun's remote statistics RPC service
*
* Guy Harris <guy@alum.mit.edu>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <gerald@wireshark.org>
* Copyright 1998 Gerald Combs
*
* 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.
*/
#include "config.h"
#include "packet-rpc.h"
void proto_register_rstat(void);
void proto_reg_handoff_rstat(void);
static int proto_rstat = -1;
static int hf_rstat_procedure_v1 = -1;
static int hf_rstat_procedure_v2 = -1;
static int hf_rstat_procedure_v3 = -1;
static int hf_rstat_procedure_v4 = -1;
static gint ett_rstat = -1;
#define RSTAT_PROGRAM 100001
#define RSTATPROC_NULL 0
#define RSTATPROC_STATS 1
#define RSTATPROC_HAVEDISK 2
/* proc number, "proc name", dissect_request, dissect_reply */
/* NULL as function pointer means: type of arguments is "void". */
static const vsff rstat1_proc[] = {
{ RSTATPROC_NULL, "NULL",
NULL, NULL },
{ RSTATPROC_STATS, "STATS",
NULL, NULL },
{ RSTATPROC_HAVEDISK, "HAVEDISK",
NULL, NULL },
{ 0, NULL, NULL, NULL }
};
static const value_string rstat1_proc_vals[] = {
{ RSTATPROC_NULL, "NULL" },
{ RSTATPROC_STATS, "STATS" },
{ RSTATPROC_HAVEDISK, "HAVEDISK" },
{ 0, NULL }
};
static const vsff rstat2_proc[] = {
{ RSTATPROC_NULL, "NULL",
NULL, NULL },
{ RSTATPROC_STATS, "STATS",
NULL, NULL },
{ RSTATPROC_HAVEDISK, "HAVEDISK",
NULL, NULL },
{ 0, NULL, NULL, NULL }
};
static const value_string rstat2_proc_vals[] = {
{ RSTATPROC_NULL, "NULL" },
{ RSTATPROC_STATS, "STATS" },
{ RSTATPROC_HAVEDISK, "HAVEDISK" },
{ 0, NULL }
};
static const vsff rstat3_proc[] = {
{ RSTATPROC_NULL, "NULL",
NULL, NULL },
{ RSTATPROC_STATS, "STATS",
NULL, NULL },
{ RSTATPROC_HAVEDISK, "HAVEDISK",
NULL, NULL },
{ 0, NULL, NULL, NULL }
};
static const value_string rstat3_proc_vals[] = {
{ RSTATPROC_NULL, "NULL" },
{ RSTATPROC_STATS, "STATS" },
{ RSTATPROC_HAVEDISK, "HAVEDISK" },
{ 0, NULL }
};
static const vsff rstat4_proc[] = {
{ RSTATPROC_NULL, "NULL",
NULL, NULL },
{ RSTATPROC_STATS, "STATS",
NULL, NULL },
{ RSTATPROC_HAVEDISK, "HAVEDISK",
NULL, NULL },
{ 0, NULL, NULL, NULL }
};
static const value_string rstat4_proc_vals[] = {
{ RSTATPROC_NULL, "NULL" },
{ RSTATPROC_STATS, "STATS" },
{ RSTATPROC_HAVEDISK, "HAVEDISK" },
{ 0, NULL }
};
void
proto_register_rstat(void)
{
static hf_register_info hf[] = {
{ &hf_rstat_procedure_v1, {
"V1 Procedure", "rstat.procedure_v1", FT_UINT32, BASE_DEC,
VALS(rstat1_proc_vals), 0, NULL, HFILL }},
{ &hf_rstat_procedure_v2, {
"V2 Procedure", "rstat.procedure_v2", FT_UINT32, BASE_DEC,
VALS(rstat2_proc_vals), 0, NULL, HFILL }},
{ &hf_rstat_procedure_v3, {
"V3 Procedure", "rstat.procedure_v3", FT_UINT32, BASE_DEC,
VALS(rstat3_proc_vals), 0, NULL, HFILL }},
{ &hf_rstat_procedure_v4, {
"V4 Procedure", "rstat.procedure_v4", FT_UINT32, BASE_DEC,
VALS(rstat4_proc_vals), 0, NULL, HFILL }}
};
static gint *ett[] = {
&ett_rstat,
};
proto_rstat = proto_register_protocol("RSTAT", "RSTAT", "rstat");
proto_register_field_array(proto_rstat, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
}
void
proto_reg_handoff_rstat(void)
{
/* Register the protocol as RPC */
rpc_init_prog(proto_rstat, RSTAT_PROGRAM, ett_rstat);
/* Register the procedure tables */
rpc_init_proc_table(RSTAT_PROGRAM, 1, rstat1_proc, hf_rstat_procedure_v1);
rpc_init_proc_table(RSTAT_PROGRAM, 2, rstat2_proc, hf_rstat_procedure_v2);
rpc_init_proc_table(RSTAT_PROGRAM, 3, rstat3_proc, hf_rstat_procedure_v3);
rpc_init_proc_table(RSTAT_PROGRAM, 4, rstat4_proc, hf_rstat_procedure_v4);
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: t
* End:
*
* vi: set shiftwidth=8 tabstop=8 noexpandtab:
* :indentSize=8:tabSize=8:noTabs=false:
*/
| MichaelQQ/Wireshark-PE | epan/dissectors/packet-rstat.c | C | gpl-2.0 | 4,569 |
/* Interface between GCC C++ FE and GDB
Copyright (C) 2014-2020 Free Software Foundation, Inc.
This file is part of GCC.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef GCC_CP_INTERFACE_H
#define GCC_CP_INTERFACE_H
#include "gcc-interface.h"
/* This header defines the interface to the GCC API. It must be both
valid C and valid C++, because it is included by both programs. */
#ifdef __cplusplus
extern "C" {
#endif
/* Forward declaration. */
struct gcc_cp_context;
/*
* Definitions and declarations for the C++ front end.
*/
/* Defined versions of the C++ front-end API. */
enum gcc_cp_api_version
{
GCC_CP_FE_VERSION_0 = 0
};
/* Qualifiers. */
enum gcc_cp_qualifiers
{
GCC_CP_QUALIFIER_CONST = 1,
GCC_CP_QUALIFIER_VOLATILE = 2,
GCC_CP_QUALIFIER_RESTRICT = 4
};
/* Ref qualifiers. */
enum gcc_cp_ref_qualifiers {
GCC_CP_REF_QUAL_NONE = 0,
GCC_CP_REF_QUAL_LVALUE = 1,
GCC_CP_REF_QUAL_RVALUE = 2
};
/* Opaque typedef for unbound class templates. They are used for
template arguments, and defaults for template template
parameters. */
typedef unsigned long long gcc_utempl;
/* Opaque typedef for expressions. They are used for template
arguments, defaults for non-type template parameters, and defaults
for function arguments. */
typedef unsigned long long gcc_expr;
typedef enum
{ GCC_CP_TPARG_VALUE, GCC_CP_TPARG_CLASS,
GCC_CP_TPARG_TEMPL, GCC_CP_TPARG_PACK }
gcc_cp_template_arg_kind;
typedef union
{ gcc_expr value; gcc_type type; gcc_utempl templ; gcc_type pack; }
gcc_cp_template_arg;
/* An array of template arguments. */
struct gcc_cp_template_args
{
/* Number of elements. */
int n_elements;
/* kind[i] indicates what kind of template argument type[i] is. */
char /* gcc_cp_template_arg_kind */ *kinds;
/* The template arguments. */
gcc_cp_template_arg *elements;
};
/* An array of (default) function arguments. */
struct gcc_cp_function_args
{
/* Number of elements. */
int n_elements;
/* The (default) values for each argument. */
gcc_expr *elements;
};
/* This enumerates the kinds of decls that GDB can create. */
enum gcc_cp_symbol_kind
{
/* A function. */
GCC_CP_SYMBOL_FUNCTION,
/* A variable. */
GCC_CP_SYMBOL_VARIABLE,
/* A typedef, or an alias declaration (including template ones). */
GCC_CP_SYMBOL_TYPEDEF,
/* A label. */
GCC_CP_SYMBOL_LABEL,
/* A class, forward declared in build_decl (to be later defined in
start_class_definition), or, in a template parameter list scope,
a declaration of a template class, closing the parameter
list. */
GCC_CP_SYMBOL_CLASS,
/* A union, forward declared in build_decl (to be later defined in
start_class_definition). */
GCC_CP_SYMBOL_UNION,
/* An enumeration type being introduced with start_new_enum_type. */
GCC_CP_SYMBOL_ENUM,
/* A nonstatic data member being introduced with new_field. */
GCC_CP_SYMBOL_FIELD,
/* A base class in a gcc_vbase_array. */
GCC_CP_SYMBOL_BASECLASS,
/* A using declaration in new_using_decl. */
GCC_CP_SYMBOL_USING,
/* A (lambda) closure class type. In many regards this is just like
a regular class, but it's not supposed to have base classes, some
of the member functions that are usually implicitly-defined are
deleted, and it should have an operator() member function that
holds the lambda body. We can't instantiate objects of lambda
types from the snippet, but we can interact with them in such
ways as passing them to functions that take their types, and
calling their body. */
GCC_CP_SYMBOL_LAMBDA_CLOSURE,
/* Marker to check that we haven't exceeded GCC_CP_SYMBOL_MASK. */
GCC_CP_SYMBOL_END,
GCC_CP_SYMBOL_MASK = 15,
/* When defining a class member, at least one of the
GCC_CP_ACCESS_MASK bits must be set; when defining a namespace-
or union-scoped symbol, none of them must be set. */
GCC_CP_ACCESS_PRIVATE,
GCC_CP_ACCESS_PUBLIC = GCC_CP_ACCESS_PRIVATE << 1,
GCC_CP_ACCESS_MASK = (GCC_CP_ACCESS_PUBLIC
| GCC_CP_ACCESS_PRIVATE),
GCC_CP_ACCESS_PROTECTED = GCC_CP_ACCESS_MASK,
GCC_CP_ACCESS_NONE = 0,
GCC_CP_FLAG_BASE = GCC_CP_ACCESS_PRIVATE << 2,
/* Flags to be used along with GCC_CP_SYMBOL_FUNCTION: */
/* This flag should be set for constructors, destructors and
operators. */
GCC_CP_FLAG_SPECIAL_FUNCTION = GCC_CP_FLAG_BASE,
/* We intentionally cannot express inline, constexpr, or virtual
override for functions. We can't inline or constexpr-replace
without a source-level body. The override keyword is only
meaningful within the definition of the containing class. */
/* This indicates a "virtual" member function, explicitly or
implicitly (due to a virtual function with the same name and
prototype in a base class) declared as such. */
GCC_CP_FLAG_VIRTUAL_FUNCTION = GCC_CP_FLAG_BASE << 1,
/* The following two flags should only be set when the flag above is
set. */
/* This indicates a pure virtual member function, i.e., one that is
declared with "= 0", even if a body is provided in the
definition. */
GCC_CP_FLAG_PURE_VIRTUAL_FUNCTION = GCC_CP_FLAG_BASE << 2,
/* This indicates a "final" virtual member function. */
GCC_CP_FLAG_FINAL_VIRTUAL_FUNCTION = GCC_CP_FLAG_BASE << 3,
/* This indicates a special member function should have its default
implementation. This either means the function declaration
contains the "= default" tokens, or that the member function was
implicitly generated by the compiler, although the latter use is
discouraged: just let the compiler implicitly introduce it.
A member function defaulted after its first declaration has
slightly different ABI implications from one implicitly generated
or explicitly defaulted at the declaration (and definition)
point. To avoid silent (possibly harmless) violation of the one
definition rule, it is recommended that this flag not be used for
such functions, and that the address of the definition be
supplied instead. */
GCC_CP_FLAG_DEFAULTED_FUNCTION = GCC_CP_FLAG_BASE << 4,
/* This indicates a deleted member function, i.e., one that has been
defined as "= delete" at its declaration point, or one that has
been implicitly defined as deleted (with or without an explicit
"= default" definition).
This should not be used for implicitly-declared member functions
that resolve to deleted definitions, as it may affect the
implicit declaration of other member functions. */
GCC_CP_FLAG_DELETED_FUNCTION = GCC_CP_FLAG_BASE << 5,
/* This indicates a constructor or type-conversion operator declared
as "explicit". */
GCC_CP_FLAG_EXPLICIT_FUNCTION = GCC_CP_FLAG_BASE << 6,
GCC_CP_FLAG_END_FUNCTION,
GCC_CP_FLAG_MASK_FUNCTION = (((GCC_CP_FLAG_END_FUNCTION - 1) << 1)
- GCC_CP_FLAG_BASE),
/* Flags to be used along with GCC_CP_SYMBOL_VARIABLE: */
/* This indicates a variable declared as "constexpr". */
GCC_CP_FLAG_CONSTEXPR_VARIABLE = GCC_CP_FLAG_BASE,
/* This indicates a variable declared as "thread_local". ??? What
should the ADDRESS be? */
GCC_CP_FLAG_THREAD_LOCAL_VARIABLE = GCC_CP_FLAG_BASE << 1,
GCC_CP_FLAG_END_VARIABLE,
GCC_CP_FLAG_MASK_VARIABLE = (((GCC_CP_FLAG_END_VARIABLE - 1) << 1)
- GCC_CP_FLAG_BASE),
/* Flags to be used when defining nonstatic data members of classes
with new_field. */
/* Use this when no flags are present. */
GCC_CP_FLAG_FIELD_NOFLAG = 0,
/* This indicates the field is declared as mutable. */
GCC_CP_FLAG_FIELD_MUTABLE = GCC_CP_FLAG_BASE,
GCC_CP_FLAG_END_FIELD,
GCC_CP_FLAG_MASK_FIELD = (((GCC_CP_FLAG_END_FIELD - 1) << 1)
- GCC_CP_FLAG_BASE),
/* Flags to be used when defining an enum with
start_new_enum_type. */
/* This indicates an enum type without any flags. */
GCC_CP_FLAG_ENUM_NOFLAG = 0,
/* This indicates a scoped enum type. */
GCC_CP_FLAG_ENUM_SCOPED = GCC_CP_FLAG_BASE,
GCC_CP_FLAG_END_ENUM,
GCC_CP_FLAG_MASK_ENUM = (((GCC_CP_FLAG_END_ENUM - 1) << 1)
- GCC_CP_FLAG_BASE),
/* Flags to be used when introducing a class or a class template
with build_decl. */
/* This indicates an enum type without any flags. */
GCC_CP_FLAG_CLASS_NOFLAG = 0,
/* This indicates the class is actually a struct. This has no
effect whatsoever on access control in this interface, since all
class members must have explicit access control bits set, but it
may affect error messages. */
GCC_CP_FLAG_CLASS_IS_STRUCT = GCC_CP_FLAG_BASE,
GCC_CP_FLAG_END_CLASS,
GCC_CP_FLAG_MASK_CLASS = (((GCC_CP_FLAG_END_CLASS - 1) << 1)
- GCC_CP_FLAG_BASE),
/* Flags to be used when introducing a virtual base class in a
gcc_vbase_array. */
/* This indicates an enum type without any flags. */
GCC_CP_FLAG_BASECLASS_NOFLAG = 0,
/* This indicates the class is actually a struct. This has no
effect whatsoever on access control in this interface, since all
class members must have explicit access control bits set, but it
may affect error messages. */
GCC_CP_FLAG_BASECLASS_VIRTUAL = GCC_CP_FLAG_BASE,
GCC_CP_FLAG_END_BASECLASS,
GCC_CP_FLAG_MASK_BASECLASS = (((GCC_CP_FLAG_END_BASECLASS - 1) << 1)
- GCC_CP_FLAG_BASE),
GCC_CP_FLAG_MASK = (GCC_CP_FLAG_MASK_FUNCTION
| GCC_CP_FLAG_MASK_VARIABLE
| GCC_CP_FLAG_MASK_FIELD
| GCC_CP_FLAG_MASK_ENUM
| GCC_CP_FLAG_MASK_CLASS
| GCC_CP_FLAG_MASK_BASECLASS
)
};
/* An array of types used for creating lists of base classes. */
struct gcc_vbase_array
{
/* Number of elements. */
int n_elements;
/* The base classes. */
gcc_type *elements;
/* Flags for each base class. Used to indicate access control and
virtualness. */
enum gcc_cp_symbol_kind *flags;
};
/* This enumerates the types of symbols that GCC might request from
GDB. */
enum gcc_cp_oracle_request
{
/* An identifier in namespace scope -- type, variable, function,
namespace, template. All namespace-scoped symbols with the
requested name, in any namespace (including the global
namespace), should be defined in response to this request. */
GCC_CP_ORACLE_IDENTIFIER
};
/* The type of the function called by GCC to ask GDB for a symbol's
definition. DATUM is an arbitrary value supplied when the oracle
function is registered. CONTEXT is the GCC context in which the
request is being made. REQUEST specifies what sort of symbol is
being requested, and IDENTIFIER is the name of the symbol. */
typedef void gcc_cp_oracle_function (void *datum,
struct gcc_cp_context *context,
enum gcc_cp_oracle_request request,
const char *identifier);
/* The type of the function called by GCC to ask GDB for a symbol's
address. This should return 0 if the address is not known. */
typedef gcc_address gcc_cp_symbol_address_function (void *datum,
struct gcc_cp_context *ctxt,
const char *identifier);
/* The type of the function called by GCC to ask GDB to enter or leave
the user expression scope. */
typedef void gcc_cp_enter_leave_user_expr_scope_function (void *datum,
struct gcc_cp_context
*context);
/* The vtable used by the C front end. */
struct gcc_cp_fe_vtable
{
/* The version of the C interface. The value is one of the
gcc_cp_api_version constants. */
unsigned int cp_version;
/* Set the callbacks for this context.
The binding oracle is called whenever the C++ parser needs to
look up a symbol. This gives the caller a chance to lazily
instantiate symbols using other parts of the gcc_cp_fe_interface
API. The symbol is looked up without a scope, and the oracle
must supply a definition for ALL namespace-scoped definitions
bound to the symbol.
The address oracle is called whenever the C++ parser needs to
look up a symbol. This may be called for symbols not provided by
the symbol oracle, such as built-in functions where GCC provides
the declaration; other internal symbols, such as those related
with thunks, rtti, and virtual tables are likely to be queried
through this interface too. The identifier is a mangled symbol
name.
DATUM is an arbitrary piece of data that is passed back verbatim
to the callbacks in requests. */
void (*set_callbacks) (struct gcc_cp_context *self,
gcc_cp_oracle_function *binding_oracle,
gcc_cp_symbol_address_function *address_oracle,
gcc_cp_enter_leave_user_expr_scope_function *enter_scope,
gcc_cp_enter_leave_user_expr_scope_function *leave_scope,
void *datum);
#define GCC_METHOD0(R, N) \
R (*N) (struct gcc_cp_context *);
#define GCC_METHOD1(R, N, A) \
R (*N) (struct gcc_cp_context *, A);
#define GCC_METHOD2(R, N, A, B) \
R (*N) (struct gcc_cp_context *, A, B);
#define GCC_METHOD3(R, N, A, B, C) \
R (*N) (struct gcc_cp_context *, A, B, C);
#define GCC_METHOD4(R, N, A, B, C, D) \
R (*N) (struct gcc_cp_context *, A, B, C, D);
#define GCC_METHOD5(R, N, A, B, C, D, E) \
R (*N) (struct gcc_cp_context *, A, B, C, D, E);
#define GCC_METHOD7(R, N, A, B, C, D, E, F, G) \
R (*N) (struct gcc_cp_context *, A, B, C, D, E, F, G);
#include "gcc-cp-fe.def"
#undef GCC_METHOD0
#undef GCC_METHOD1
#undef GCC_METHOD2
#undef GCC_METHOD3
#undef GCC_METHOD4
#undef GCC_METHOD5
#undef GCC_METHOD7
};
/* The C front end object. */
struct gcc_cp_context
{
/* Base class. */
struct gcc_base_context base;
/* Our vtable. This is a separate field because this is simpler
than implementing a vtable inheritance scheme in C. */
const struct gcc_cp_fe_vtable *cp_ops;
};
/* The name of the .so that the compiler builds. We dlopen this
later. */
#define GCC_CP_FE_LIBCC libcc1.so
/* The compiler exports a single initialization function. This macro
holds its name as a symbol. */
#define GCC_CP_FE_CONTEXT gcc_cp_fe_context
/* The type of the initialization function. The caller passes in the
desired base version and desired C-specific version. If the
request can be satisfied, a compatible gcc_context object will be
returned. Otherwise, the function returns NULL. */
typedef struct gcc_cp_context *gcc_cp_fe_context_function
(enum gcc_base_api_version,
enum gcc_cp_api_version);
#ifdef __cplusplus
}
#endif
#endif /* GCC_CP_INTERFACE_H */
| mattstock/binutils-bexkat1 | include/gcc-cp-interface.h | C | gpl-2.0 | 15,167 |
#ifndef _ASM_X86_APICDEF_H
#define _ASM_X86_APICDEF_H
/*
* Constants for various Intel APICs. (local APIC, IOAPIC, etc.)
*
* Alan Cox <Alan.Cox@linux.org>, 1995.
* Ingo Molnar <mingo@redhat.com>, 1999, 2000
*/
#define APIC_DEFAULT_PHYS_BASE 0xfee00000
#define APIC_ID 0x20
#define APIC_LVR 0x30
#define APIC_LVR_MASK 0xFF00FF
#define GET_APIC_VERSION(x) ((x) & 0xFFu)
#define GET_APIC_MAXLVT(x) (((x) >> 16) & 0xFFu)
#ifdef CONFIG_X86_32
# define APIC_INTEGRATED(x) ((x) & 0xF0u)
#else
# define APIC_INTEGRATED(x) (1)
#endif
#define APIC_XAPIC(x) ((x) >= 0x14)
#define APIC_TASKPRI 0x80
#define APIC_TPRI_MASK 0xFFu
#define APIC_ARBPRI 0x90
#define APIC_ARBPRI_MASK 0xFFu
#define APIC_PROCPRI 0xA0
#define APIC_EOI 0xB0
#define APIC_EIO_ACK 0x0
#define APIC_RRR 0xC0
#define APIC_LDR 0xD0
#define APIC_LDR_MASK (0xFFu << 24)
#define GET_APIC_LOGICAL_ID(x) (((x) >> 24) & 0xFFu)
#define SET_APIC_LOGICAL_ID(x) (((x) << 24))
#define APIC_ALL_CPUS 0xFFu
#define APIC_DFR 0xE0
#define APIC_DFR_CLUSTER 0x0FFFFFFFul
#define APIC_DFR_FLAT 0xFFFFFFFFul
#define APIC_SPIV 0xF0
#define APIC_SPIV_FOCUS_DISABLED (1 << 9)
#define APIC_SPIV_APIC_ENABLED (1 << 8)
#define APIC_ISR 0x100
#define APIC_ISR_NR 0x8 /* Number of 32 bit ISR registers. */
#define APIC_TMR 0x180
#define APIC_IRR 0x200
#define APIC_ESR 0x280
#define APIC_ESR_SEND_CS 0x00001
#define APIC_ESR_RECV_CS 0x00002
#define APIC_ESR_SEND_ACC 0x00004
#define APIC_ESR_RECV_ACC 0x00008
#define APIC_ESR_SENDILL 0x00020
#define APIC_ESR_RECVILL 0x00040
#define APIC_ESR_ILLREGA 0x00080
#define APIC_ICR 0x300
#define APIC_DEST_SELF 0x40000
#define APIC_DEST_ALLINC 0x80000
#define APIC_DEST_ALLBUT 0xC0000
#define APIC_ICR_RR_MASK 0x30000
#define APIC_ICR_RR_INVALID 0x00000
#define APIC_ICR_RR_INPROG 0x10000
#define APIC_ICR_RR_VALID 0x20000
#define APIC_INT_LEVELTRIG 0x08000
#define APIC_INT_ASSERT 0x04000
#define APIC_ICR_BUSY 0x01000
#define APIC_DEST_LOGICAL 0x00800
#define APIC_DEST_PHYSICAL 0x00000
#define APIC_DM_FIXED 0x00000
#define APIC_DM_LOWEST 0x00100
#define APIC_DM_SMI 0x00200
#define APIC_DM_REMRD 0x00300
#define APIC_DM_NMI 0x00400
#define APIC_DM_INIT 0x00500
#define APIC_DM_STARTUP 0x00600
#define APIC_DM_EXTINT 0x00700
#define APIC_VECTOR_MASK 0x000FF
#define APIC_ICR2 0x310
#define GET_APIC_DEST_FIELD(x) (((x) >> 24) & 0xFF)
#define SET_APIC_DEST_FIELD(x) ((x) << 24)
#define APIC_LVTT 0x320
#define APIC_LVTTHMR 0x330
#define APIC_LVTPC 0x340
#define APIC_LVT0 0x350
#define APIC_LVT_TIMER_BASE_MASK (0x3 << 18)
#define GET_APIC_TIMER_BASE(x) (((x) >> 18) & 0x3)
#define SET_APIC_TIMER_BASE(x) (((x) << 18))
#define APIC_TIMER_BASE_CLKIN 0x0
#define APIC_TIMER_BASE_TMBASE 0x1
#define APIC_TIMER_BASE_DIV 0x2
#define APIC_LVT_TIMER_PERIODIC (1 << 17)
#define APIC_LVT_MASKED (1 << 16)
#define APIC_LVT_LEVEL_TRIGGER (1 << 15)
#define APIC_LVT_REMOTE_IRR (1 << 14)
#define APIC_INPUT_POLARITY (1 << 13)
#define APIC_SEND_PENDING (1 << 12)
#define APIC_MODE_MASK 0x700
#define GET_APIC_DELIVERY_MODE(x) (((x) >> 8) & 0x7)
#define SET_APIC_DELIVERY_MODE(x, y) (((x) & ~0x700) | ((y) << 8))
#define APIC_MODE_FIXED 0x0
#define APIC_MODE_NMI 0x4
#define APIC_MODE_EXTINT 0x7
#define APIC_LVT1 0x360
#define APIC_LVTERR 0x370
#define APIC_TMICT 0x380
#define APIC_TMCCT 0x390
#define APIC_TDCR 0x3E0
#define APIC_SELF_IPI 0x3F0
#define APIC_TDR_DIV_TMBASE (1 << 2)
#define APIC_TDR_DIV_1 0xB
#define APIC_TDR_DIV_2 0x0
#define APIC_TDR_DIV_4 0x1
#define APIC_TDR_DIV_8 0x2
#define APIC_TDR_DIV_16 0x3
#define APIC_TDR_DIV_32 0x8
#define APIC_TDR_DIV_64 0x9
#define APIC_TDR_DIV_128 0xA
#define APIC_EILVT0 0x500
#define APIC_EILVT_NR_AMD_K8 1 /* # of extended interrupts */
#define APIC_EILVT_NR_AMD_10H 4
#define APIC_EILVT_LVTOFF(x) (((x) >> 4) & 0xF)
#define APIC_EILVT_MSG_FIX 0x0
#define APIC_EILVT_MSG_SMI 0x2
#define APIC_EILVT_MSG_NMI 0x4
#define APIC_EILVT_MSG_EXT 0x7
#define APIC_EILVT_MASKED (1 << 16)
#define APIC_EILVT1 0x510
#define APIC_EILVT2 0x520
#define APIC_EILVT3 0x530
#define APIC_BASE_MSR 0x800
#endif /* _ASM_X86_APICDEF_H */
| BCLinux/qga-bc | qemu-kvm-0.12.1.2/kvm/user/test/lib/x86/apic-defs.h | C | gpl-2.0 | 4,197 |
/***************************************************************************
qgspainteffectwidget.cpp
------------------------
begin : January 2015
copyright : (C) 2015 by Nyall Dawson
email : nyall dot dawson at gmail.com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgspainteffectwidget.h"
#include "qgslogger.h"
#include "qgspainteffect.h"
#include "qgsshadoweffect.h"
#include "qgsblureffect.h"
#include "qgsgloweffect.h"
#include "qgstransformeffect.h"
#include "qgscoloreffect.h"
#include "qgsstylev2.h"
#include "qgsvectorcolorrampv2.h"
//
// draw source
//
QgsDrawSourceWidget::QgsDrawSourceWidget( QWidget *parent )
: QgsPaintEffectWidget( parent )
, mEffect( nullptr )
{
setupUi( this );
initGui();
}
void QgsDrawSourceWidget::setPaintEffect( QgsPaintEffect *effect )
{
if ( !effect || effect->type() != "drawSource" )
return;
mEffect = static_cast<QgsDrawSourceEffect*>( effect );
initGui();
}
void QgsDrawSourceWidget::initGui()
{
if ( !mEffect )
{
return;
}
blockSignals( true );
mTransparencySpnBx->setValue( mEffect->transparency() * 100.0 );
mTransparencySlider->setValue( mEffect->transparency() * 1000.0 );
mBlendCmbBx->setBlendMode( mEffect->blendMode() );
mDrawModeComboBox->setDrawMode( mEffect->drawMode() );
blockSignals( false );
}
void QgsDrawSourceWidget::blockSignals( const bool block )
{
mTransparencySlider->blockSignals( block );
mTransparencySpnBx->blockSignals( block );
mBlendCmbBx->blockSignals( block );
mDrawModeComboBox->blockSignals( block );
}
void QgsDrawSourceWidget::on_mTransparencySpnBx_valueChanged( double value )
{
if ( !mEffect )
return;
mTransparencySlider->blockSignals( true );
mTransparencySlider->setValue( value * 10.0 );
mTransparencySlider->blockSignals( false );
mEffect->setTransparency( value / 100.0 );
emit changed();
}
void QgsDrawSourceWidget::on_mDrawModeComboBox_currentIndexChanged( int index )
{
Q_UNUSED( index );
if ( !mEffect )
return;
mEffect->setDrawMode( mDrawModeComboBox->drawMode() );
emit changed();
}
void QgsDrawSourceWidget::on_mBlendCmbBx_currentIndexChanged( int index )
{
Q_UNUSED( index );
if ( !mEffect )
return;
mEffect->setBlendMode( mBlendCmbBx->blendMode() );
emit changed();
}
void QgsDrawSourceWidget::on_mTransparencySlider_valueChanged( int value )
{
mTransparencySpnBx->setValue( value / 10.0 );
}
//
// blur
//
QgsBlurWidget::QgsBlurWidget( QWidget *parent )
: QgsPaintEffectWidget( parent )
, mEffect( nullptr )
{
setupUi( this );
mBlurTypeCombo->addItem( tr( "Stack blur (fast)" ), QgsBlurEffect::StackBlur );
mBlurTypeCombo->addItem( tr( "Gaussian blur (quality)" ), QgsBlurEffect::GaussianBlur );
initGui();
}
void QgsBlurWidget::setPaintEffect( QgsPaintEffect *effect )
{
if ( !effect || effect->type() != "blur" )
return;
mEffect = static_cast<QgsBlurEffect*>( effect );
initGui();
}
void QgsBlurWidget::initGui()
{
if ( !mEffect )
{
return;
}
blockSignals( true );
mBlurTypeCombo->setCurrentIndex( mBlurTypeCombo->findData( mEffect->blurMethod() ) );
mBlurStrengthSpnBx->setValue( mEffect->blurLevel() );
mTransparencySpnBx->setValue( mEffect->transparency() * 100.0 );
mTransparencySlider->setValue( mEffect->transparency() * 1000.0 );
mBlendCmbBx->setBlendMode( mEffect->blendMode() );
mDrawModeComboBox->setDrawMode( mEffect->drawMode() );
blockSignals( false );
}
void QgsBlurWidget::blockSignals( const bool block )
{
mBlurTypeCombo->blockSignals( block );
mBlurStrengthSpnBx->blockSignals( block );
mTransparencySlider->blockSignals( block );
mTransparencySpnBx->blockSignals( block );
mBlendCmbBx->blockSignals( block );
mDrawModeComboBox->blockSignals( block );
}
void QgsBlurWidget::on_mBlurTypeCombo_currentIndexChanged( int index )
{
if ( !mEffect )
return;
QgsBlurEffect::BlurMethod method = ( QgsBlurEffect::BlurMethod ) mBlurTypeCombo->itemData( index ).toInt();
mEffect->setBlurMethod( method );
//also update max radius
switch ( method )
{
case QgsBlurEffect::StackBlur:
mBlurStrengthSpnBx->setMaximum( 16 );
break;
case QgsBlurEffect::GaussianBlur:
mBlurStrengthSpnBx->setMaximum( 200 );
break;
}
emit changed();
}
void QgsBlurWidget::on_mBlurStrengthSpnBx_valueChanged( int value )
{
if ( !mEffect )
return;
mEffect->setBlurLevel( value );
emit changed();
}
void QgsBlurWidget::on_mTransparencySpnBx_valueChanged( double value )
{
if ( !mEffect )
return;
mTransparencySlider->blockSignals( true );
mTransparencySlider->setValue( value * 10.0 );
mTransparencySlider->blockSignals( false );
mEffect->setTransparency( value / 100.0 );
emit changed();
}
void QgsBlurWidget::on_mDrawModeComboBox_currentIndexChanged( int index )
{
Q_UNUSED( index );
if ( !mEffect )
return;
mEffect->setDrawMode( mDrawModeComboBox->drawMode() );
emit changed();
}
void QgsBlurWidget::on_mBlendCmbBx_currentIndexChanged( int index )
{
Q_UNUSED( index );
if ( !mEffect )
return;
mEffect->setBlendMode( mBlendCmbBx->blendMode() );
emit changed();
}
void QgsBlurWidget::on_mTransparencySlider_valueChanged( int value )
{
mTransparencySpnBx->setValue( value / 10.0 );
}
//
// Drop Shadow
//
QgsShadowEffectWidget::QgsShadowEffectWidget( QWidget *parent )
: QgsPaintEffectWidget( parent )
, mEffect( nullptr )
{
setupUi( this );
mShadowColorBtn->setAllowAlpha( false );
mShadowColorBtn->setColorDialogTitle( tr( "Select shadow color" ) );
mShadowColorBtn->setContext( "symbology" );
mOffsetUnitWidget->setUnits( QgsSymbolV2::OutputUnitList() << QgsSymbolV2::MM << QgsSymbolV2::Pixel << QgsSymbolV2::MapUnit );
initGui();
}
void QgsShadowEffectWidget::setPaintEffect( QgsPaintEffect *effect )
{
if ( !effect || ( effect->type() != "dropShadow" && effect->type() != "innerShadow" ) )
return;
mEffect = static_cast<QgsShadowEffect*>( effect );
initGui();
}
void QgsShadowEffectWidget::initGui()
{
if ( !mEffect )
{
return;
}
blockSignals( true );
mShadowOffsetAngleSpnBx->setValue( mEffect->offsetAngle() );
mShadowOffsetAngleDial->setValue( mEffect->offsetAngle() );
mShadowOffsetSpnBx->setValue( mEffect->offsetDistance() );
mOffsetUnitWidget->setUnit( mEffect->offsetUnit() );
mOffsetUnitWidget->setMapUnitScale( mEffect->offsetMapUnitScale() );
mShadowRadiuSpnBx->setValue( mEffect->blurLevel() );
mShadowTranspSpnBx->setValue( mEffect->transparency() * 100.0 );
mShadowTranspSlider->setValue( mEffect->transparency() * 1000.0 );
mShadowColorBtn->setColor( mEffect->color() );
mShadowBlendCmbBx->setBlendMode( mEffect->blendMode() );
mDrawModeComboBox->setDrawMode( mEffect->drawMode() );
blockSignals( false );
}
void QgsShadowEffectWidget::blockSignals( const bool block )
{
mShadowOffsetAngleSpnBx->blockSignals( block );
mShadowOffsetAngleDial->blockSignals( block );
mShadowOffsetSpnBx->blockSignals( block );
mOffsetUnitWidget->blockSignals( block );
mShadowRadiuSpnBx->blockSignals( block );
mShadowTranspSpnBx->blockSignals( block );
mShadowColorBtn->blockSignals( block );
mShadowBlendCmbBx->blockSignals( block );
mShadowTranspSlider->blockSignals( block );
mDrawModeComboBox->blockSignals( block );
}
void QgsShadowEffectWidget::on_mShadowOffsetAngleSpnBx_valueChanged( int value )
{
mShadowOffsetAngleDial->blockSignals( true );
mShadowOffsetAngleDial->setValue( value );
mShadowOffsetAngleDial->blockSignals( false );
if ( !mEffect )
return;
mEffect->setOffsetAngle( value );
emit changed();
}
void QgsShadowEffectWidget::on_mShadowOffsetAngleDial_valueChanged( int value )
{
mShadowOffsetAngleSpnBx->setValue( value );
}
void QgsShadowEffectWidget::on_mShadowOffsetSpnBx_valueChanged( double value )
{
if ( !mEffect )
return;
mEffect->setOffsetDistance( value );
emit changed();
}
void QgsShadowEffectWidget::on_mOffsetUnitWidget_changed()
{
if ( !mEffect )
{
return;
}
mEffect->setOffsetUnit( mOffsetUnitWidget->unit() );
mEffect->setOffsetMapUnitScale( mOffsetUnitWidget->getMapUnitScale() );
emit changed();
}
void QgsShadowEffectWidget::on_mShadowTranspSpnBx_valueChanged( double value )
{
if ( !mEffect )
return;
mShadowTranspSlider->blockSignals( true );
mShadowTranspSlider->setValue( value * 10.0 );
mShadowTranspSlider->blockSignals( false );
mEffect->setTransparency( value / 100.0 );
emit changed();
}
void QgsShadowEffectWidget::on_mShadowColorBtn_colorChanged( const QColor &color )
{
if ( !mEffect )
return;
mEffect->setColor( color );
emit changed();
}
void QgsShadowEffectWidget::on_mShadowRadiuSpnBx_valueChanged( int value )
{
if ( !mEffect )
return;
mEffect->setBlurLevel( value );
emit changed();
}
void QgsShadowEffectWidget::on_mShadowTranspSlider_valueChanged( int value )
{
mShadowTranspSpnBx->setValue( value / 10.0 );
}
void QgsShadowEffectWidget::on_mDrawModeComboBox_currentIndexChanged( int index )
{
Q_UNUSED( index );
if ( !mEffect )
return;
mEffect->setDrawMode( mDrawModeComboBox->drawMode() );
emit changed();
}
void QgsShadowEffectWidget::on_mShadowBlendCmbBx_currentIndexChanged( int index )
{
Q_UNUSED( index );
if ( !mEffect )
return;
mEffect->setBlendMode( mShadowBlendCmbBx->blendMode() );
emit changed();
}
//
// glow
//
QgsGlowWidget::QgsGlowWidget( QWidget *parent )
: QgsPaintEffectWidget( parent )
, mEffect( nullptr )
{
setupUi( this );
mColorBtn->setAllowAlpha( false );
mColorBtn->setColorDialogTitle( tr( "Select glow color" ) );
mColorBtn->setContext( "symbology" );
mSpreadUnitWidget->setUnits( QgsSymbolV2::OutputUnitList() << QgsSymbolV2::MM << QgsSymbolV2::Pixel << QgsSymbolV2::MapUnit );
mRampComboBox->populate( QgsStyleV2::defaultStyle() );
mRampComboBox->setShowGradientOnly( true );
connect( mRampComboBox, SIGNAL( currentIndexChanged( int ) ), this, SLOT( applyColorRamp() ) );
connect( mRampComboBox, SIGNAL( sourceRampEdited() ), this, SLOT( applyColorRamp() ) );
connect( mButtonEditRamp, SIGNAL( clicked() ), mRampComboBox, SLOT( editSourceRamp() ) );
connect( radioSingleColor, SIGNAL( toggled( bool ) ), this, SLOT( colorModeChanged() ) );
initGui();
}
void QgsGlowWidget::setPaintEffect( QgsPaintEffect *effect )
{
if ( !effect || ( effect->type() != "outerGlow" && effect->type() != "innerGlow" ) )
return;
mEffect = static_cast<QgsGlowEffect*>( effect );
initGui();
}
void QgsGlowWidget::initGui()
{
if ( !mEffect )
{
return;
}
blockSignals( true );
mSpreadSpnBx->setValue( mEffect->spread() );
mSpreadUnitWidget->setUnit( mEffect->spreadUnit() );
mSpreadUnitWidget->setMapUnitScale( mEffect->spreadMapUnitScale() );
mBlurRadiusSpnBx->setValue( mEffect->blurLevel() );
mTranspSpnBx->setValue( mEffect->transparency() * 100.0 );
mTranspSlider->setValue( mEffect->transparency() * 1000.0 );
mColorBtn->setColor( mEffect->color() );
mBlendCmbBx->setBlendMode( mEffect->blendMode() );
if ( mEffect->ramp() )
{
mRampComboBox->setSourceColorRamp( mEffect->ramp() );
}
radioSingleColor->setChecked( mEffect->colorType() == QgsGlowEffect::SingleColor );
mColorBtn->setEnabled( mEffect->colorType() == QgsGlowEffect::SingleColor );
radioColorRamp->setChecked( mEffect->colorType() == QgsGlowEffect::ColorRamp );
mRampComboBox->setEnabled( mEffect->colorType() == QgsGlowEffect::ColorRamp );
mButtonEditRamp->setEnabled( mEffect->colorType() == QgsGlowEffect::ColorRamp );
mDrawModeComboBox->setDrawMode( mEffect->drawMode() );
blockSignals( false );
}
void QgsGlowWidget::blockSignals( const bool block )
{
mSpreadSpnBx->blockSignals( block );
mSpreadUnitWidget->blockSignals( block );
mBlurRadiusSpnBx->blockSignals( block );
mTranspSpnBx->blockSignals( block );
mTranspSlider->blockSignals( block );
mColorBtn->blockSignals( block );
mBlendCmbBx->blockSignals( block );
mRampComboBox->blockSignals( block );
radioSingleColor->blockSignals( block );
radioColorRamp->blockSignals( block );
mDrawModeComboBox->blockSignals( block );
}
void QgsGlowWidget::colorModeChanged()
{
if ( !mEffect )
{
return;
}
if ( radioSingleColor->isChecked() )
{
mEffect->setColorType( QgsGlowEffect::SingleColor );
}
else
{
mEffect->setColorType( QgsGlowEffect::ColorRamp );
mEffect->setRamp( mRampComboBox->currentColorRamp() );
}
emit changed();
}
void QgsGlowWidget::on_mSpreadSpnBx_valueChanged( double value )
{
if ( !mEffect )
return;
mEffect->setSpread( value );
emit changed();
}
void QgsGlowWidget::on_mSpreadUnitWidget_changed()
{
if ( !mEffect )
{
return;
}
mEffect->setSpreadUnit( mSpreadUnitWidget->unit() );
mEffect->setSpreadMapUnitScale( mSpreadUnitWidget->getMapUnitScale() );
emit changed();
}
void QgsGlowWidget::on_mTranspSpnBx_valueChanged( double value )
{
if ( !mEffect )
return;
mTranspSlider->blockSignals( true );
mTranspSlider->setValue( value * 10.0 );
mTranspSlider->blockSignals( false );
mEffect->setTransparency( value / 100.0 );
emit changed();
}
void QgsGlowWidget::on_mColorBtn_colorChanged( const QColor &color )
{
if ( !mEffect )
return;
mEffect->setColor( color );
emit changed();
}
void QgsGlowWidget::on_mBlurRadiusSpnBx_valueChanged( int value )
{
if ( !mEffect )
return;
mEffect->setBlurLevel( value );
emit changed();
}
void QgsGlowWidget::on_mTranspSlider_valueChanged( int value )
{
mTranspSpnBx->setValue( value / 10.0 );
}
void QgsGlowWidget::on_mBlendCmbBx_currentIndexChanged( int index )
{
Q_UNUSED( index );
if ( !mEffect )
return;
mEffect->setBlendMode( mBlendCmbBx->blendMode() );
emit changed();
}
void QgsGlowWidget::on_mDrawModeComboBox_currentIndexChanged( int index )
{
Q_UNUSED( index );
if ( !mEffect )
return;
mEffect->setDrawMode( mDrawModeComboBox->drawMode() );
emit changed();
}
void QgsGlowWidget::applyColorRamp()
{
if ( !mEffect )
{
return;
}
QgsVectorColorRampV2* ramp = mRampComboBox->currentColorRamp();
if ( !ramp )
return;
mEffect->setRamp( ramp );
emit changed();
}
//
// transform
//
QgsTransformWidget::QgsTransformWidget( QWidget *parent )
: QgsPaintEffectWidget( parent )
, mEffect( nullptr )
{
setupUi( this );
mTranslateUnitWidget->setUnits( QgsSymbolV2::OutputUnitList() << QgsSymbolV2::MM << QgsSymbolV2::Pixel << QgsSymbolV2::MapUnit );
mSpinTranslateX->setClearValue( 0 );
mSpinTranslateY->setClearValue( 0 );
mSpinShearX->setClearValue( 0 );
mSpinShearY->setClearValue( 0 );
mSpinScaleX->setClearValue( 100.0 );
mSpinScaleY->setClearValue( 100.0 );
initGui();
}
void QgsTransformWidget::setPaintEffect( QgsPaintEffect *effect )
{
if ( !effect || effect->type() != "transform" )
return;
mEffect = static_cast<QgsTransformEffect*>( effect );
initGui();
}
void QgsTransformWidget::initGui()
{
if ( !mEffect )
{
return;
}
blockSignals( true );
mReflectXCheckBox->setChecked( mEffect->reflectX() );
mReflectYCheckBox->setChecked( mEffect->reflectY() );
mDrawModeComboBox->setDrawMode( mEffect->drawMode() );
mSpinTranslateX->setValue( mEffect->translateX() );
mSpinTranslateY->setValue( mEffect->translateY() );
mTranslateUnitWidget->setUnit( mEffect->translateUnit() );
mTranslateUnitWidget->setMapUnitScale( mEffect->translateMapUnitScale() );
mSpinShearX->setValue( mEffect->shearX() );
mSpinShearY->setValue( mEffect->shearY() );
mSpinScaleX->setValue( mEffect->scaleX() * 100.0 );
mSpinScaleY->setValue( mEffect->scaleY() * 100.0 );
mRotationSpinBox->setValue( mEffect->rotation() );
blockSignals( false );
}
void QgsTransformWidget::blockSignals( const bool block )
{
mDrawModeComboBox->blockSignals( block );
mTranslateUnitWidget->blockSignals( block );
mSpinTranslateX->blockSignals( block );
mSpinTranslateY->blockSignals( block );
mReflectXCheckBox->blockSignals( block );
mReflectYCheckBox->blockSignals( block );
mSpinShearX->blockSignals( block );
mSpinShearY->blockSignals( block );
mSpinScaleX->blockSignals( block );
mSpinScaleY->blockSignals( block );
mRotationSpinBox->blockSignals( block );
}
void QgsTransformWidget::on_mDrawModeComboBox_currentIndexChanged( int index )
{
Q_UNUSED( index );
if ( !mEffect )
return;
mEffect->setDrawMode( mDrawModeComboBox->drawMode() );
emit changed();
}
void QgsTransformWidget::on_mSpinTranslateX_valueChanged( double value )
{
if ( !mEffect )
return;
mEffect->setTranslateX( value );
emit changed();
}
void QgsTransformWidget::on_mSpinTranslateY_valueChanged( double value )
{
if ( !mEffect )
return;
mEffect->setTranslateY( value );
emit changed();
}
void QgsTransformWidget::on_mTranslateUnitWidget_changed()
{
if ( !mEffect )
{
return;
}
mEffect->setTranslateUnit( mTranslateUnitWidget->unit() );
mEffect->setTranslateMapUnitScale( mTranslateUnitWidget->getMapUnitScale() );
emit changed();
}
void QgsTransformWidget::on_mReflectXCheckBox_stateChanged( int state )
{
if ( !mEffect )
return;
mEffect->setReflectX( state == Qt::Checked );
emit changed();
}
void QgsTransformWidget::on_mReflectYCheckBox_stateChanged( int state )
{
if ( !mEffect )
return;
mEffect->setReflectY( state == Qt::Checked );
emit changed();
}
void QgsTransformWidget::on_mSpinShearX_valueChanged( double value )
{
if ( !mEffect )
return;
mEffect->setShearX( value );
emit changed();
}
void QgsTransformWidget::on_mSpinShearY_valueChanged( double value )
{
if ( !mEffect )
return;
mEffect->setShearY( value );
emit changed();
}
void QgsTransformWidget::on_mSpinScaleX_valueChanged( double value )
{
if ( !mEffect )
return;
mEffect->setScaleX( value / 100.0 );
emit changed();
}
void QgsTransformWidget::on_mSpinScaleY_valueChanged( double value )
{
if ( !mEffect )
return;
mEffect->setScaleY( value / 100.0 );
emit changed();
}
void QgsTransformWidget::on_mRotationSpinBox_valueChanged( double value )
{
if ( !mEffect )
return;
mEffect->setRotation( value );
emit changed();
}
//
// color effect
//
QgsColorEffectWidget::QgsColorEffectWidget( QWidget *parent )
: QgsPaintEffectWidget( parent )
, mEffect( nullptr )
{
setupUi( this );
mBrightnessSpinBox->setClearValue( 0 );
mContrastSpinBox->setClearValue( 0 );
mSaturationSpinBox->setClearValue( 0 );
mColorizeColorButton->setAllowAlpha( false );
mGrayscaleCombo->addItem( tr( "Off" ), QgsImageOperation::GrayscaleOff );
mGrayscaleCombo->addItem( tr( "By lightness" ), QgsImageOperation::GrayscaleLightness );
mGrayscaleCombo->addItem( tr( "By luminosity" ), QgsImageOperation::GrayscaleLuminosity );
mGrayscaleCombo->addItem( tr( "By average" ), QgsImageOperation::GrayscaleAverage );
initGui();
}
void QgsColorEffectWidget::setPaintEffect( QgsPaintEffect *effect )
{
if ( !effect || effect->type() != "color" )
return;
mEffect = static_cast<QgsColorEffect*>( effect );
initGui();
}
void QgsColorEffectWidget::initGui()
{
if ( !mEffect )
{
return;
}
blockSignals( true );
mSliderBrightness->setValue( mEffect->brightness() );
mSliderContrast->setValue( mEffect->contrast() );
mSliderSaturation->setValue(( mEffect->saturation() - 1.0 ) * 100.0 );
mColorizeCheck->setChecked( mEffect->colorizeOn() );
mSliderColorizeStrength->setValue( mEffect->colorizeStrength() );
mColorizeColorButton->setColor( mEffect->colorizeColor() );
int grayscaleIdx = mGrayscaleCombo->findData( QVariant(( int ) mEffect->grayscaleMode() ) );
mGrayscaleCombo->setCurrentIndex( grayscaleIdx == -1 ? 0 : grayscaleIdx );
mTranspSpnBx->setValue( mEffect->transparency() * 100.0 );
mTranspSlider->setValue( mEffect->transparency() * 1000.0 );
mBlendCmbBx->setBlendMode( mEffect->blendMode() );
mDrawModeComboBox->setDrawMode( mEffect->drawMode() );
enableColorizeControls( mEffect->colorizeOn() );
blockSignals( false );
}
void QgsColorEffectWidget::blockSignals( const bool block )
{
mBrightnessSpinBox->blockSignals( block );
mContrastSpinBox->blockSignals( block );
mSaturationSpinBox->blockSignals( block );
mColorizeStrengthSpinBox->blockSignals( block );
mColorizeCheck->blockSignals( block );
mColorizeColorButton->blockSignals( block );
mGrayscaleCombo->blockSignals( block );
mTranspSpnBx->blockSignals( block );
mTranspSlider->blockSignals( block );
mBlendCmbBx->blockSignals( block );
mDrawModeComboBox->blockSignals( block );
}
void QgsColorEffectWidget::enableColorizeControls( const bool enable )
{
mSliderColorizeStrength->setEnabled( enable );
mColorizeStrengthSpinBox->setEnabled( enable );
mColorizeColorButton->setEnabled( enable );
}
void QgsColorEffectWidget::on_mTranspSpnBx_valueChanged( double value )
{
if ( !mEffect )
return;
mTranspSlider->blockSignals( true );
mTranspSlider->setValue( value * 10.0 );
mTranspSlider->blockSignals( false );
mEffect->setTransparency( value / 100.0 );
emit changed();
}
void QgsColorEffectWidget::on_mBlendCmbBx_currentIndexChanged( int index )
{
Q_UNUSED( index );
if ( !mEffect )
return;
mEffect->setBlendMode( mBlendCmbBx->blendMode() );
emit changed();
}
void QgsColorEffectWidget::on_mDrawModeComboBox_currentIndexChanged( int index )
{
Q_UNUSED( index );
if ( !mEffect )
return;
mEffect->setDrawMode( mDrawModeComboBox->drawMode() );
emit changed();
}
void QgsColorEffectWidget::on_mTranspSlider_valueChanged( int value )
{
mTranspSpnBx->setValue( value / 10.0 );
}
void QgsColorEffectWidget::on_mBrightnessSpinBox_valueChanged( int value )
{
if ( !mEffect )
return;
mEffect->setBrightness( value );
emit changed();
}
void QgsColorEffectWidget::on_mContrastSpinBox_valueChanged( int value )
{
if ( !mEffect )
return;
mEffect->setContrast( value );
emit changed();
}
void QgsColorEffectWidget::on_mSaturationSpinBox_valueChanged( int value )
{
if ( !mEffect )
return;
mEffect->setSaturation( value / 100.0 + 1 );
emit changed();
}
void QgsColorEffectWidget::on_mColorizeStrengthSpinBox_valueChanged( int value )
{
if ( !mEffect )
return;
mEffect->setColorizeStrength( value );
emit changed();
}
void QgsColorEffectWidget::on_mColorizeCheck_stateChanged( int state )
{
if ( !mEffect )
return;
mEffect->setColorizeOn( state == Qt::Checked );
enableColorizeControls( state == Qt::Checked );
emit changed();
}
void QgsColorEffectWidget::on_mColorizeColorButton_colorChanged( const QColor &color )
{
if ( !mEffect )
return;
mEffect->setColorizeColor( color );
emit changed();
}
void QgsColorEffectWidget::on_mGrayscaleCombo_currentIndexChanged( int index )
{
Q_UNUSED( index );
if ( !mEffect )
return;
mEffect->setGrayscaleMode(( QgsImageOperation::GrayscaleMode ) mGrayscaleCombo->itemData( mGrayscaleCombo->currentIndex() ).toInt() );
emit changed();
}
| AsgerPetersen/QGIS | src/gui/effects/qgspainteffectwidget.cpp | C++ | gpl-2.0 | 23,696 |
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8202837
* @summary PBES2 AlgorithmId encoding error in PKCS12 KeyStore
*/
import java.io.ByteArrayInputStream;
import java.security.KeyStore;
public class PBES2Encoding {
// This is a PKCS 12 file using PBES2 to encrypt the cert and key. It is
// generated with these commands:
//
// keytool -keystore ks -genkeypair -storepass changeit -alias a -dname CN=A
// openssl pkcs12 -in ks -nodes -out kandc -passin pass:changeit
// openssl pkcs12 -export -in kandc -out p12 -name a -passout pass:changeit
// -certpbe AES-128-CBC -keypbe AES-128-CBC
static final String P12_FILE =
"308208860201033082084c06092a864886f70d010701a082083d048208393082" +
"08353082050406092a864886f70d010706a08204f5308204f1020100308204ea" +
"06092a864886f70d010701304906092a864886f70d01050d303c301b06092a86" +
"4886f70d01050c300e040879e103dcdf95bd3e02020800301d06096086480165" +
"0304010204108afe09885014c1315a431956bf051cd1808204909af1a5964e45" +
"fa24887c963d422500a54576bda5b79beba0a97ec61fd7f68e1d7acca9c7a2ff" +
"fa90cc161d1e930a8315158089ce5e842ae758f63d723bd02b82120e663c2965" +
"a32101d27f268f7101d9b8786ddeeb8ddfa57d63c7b110ad9015b6279f8c5adf" +
"d2a78f82d6641bbb4c363bfe6d5be78993c54a1a52d83acba21f70a70c104c18" +
"1968df3009896fb3af534661a8a3d25a09974adfd6dd587f067fd5a2017f0d34" +
"99ca0dfd9950f555e950ceb3120408fb9b72e3b43020e4cde2f1c7726901328d" +
"78471d7825ce6c9968d9f8e3ae2f2963cfc7d81bd1facfa55f56d711f3568673" +
"6c75bc6ae67beee1a70355bf1daa17aba7cdc4fe35b06881503b7a99d1c3efeb" +
"e036217042e2f7918c038dc5505447acbe84db6ac10527dd65597b25c8d5f68a" +
"349ca4da866b76934aa7c1f4c452b6c45bd97d991c35d3ce63e20342817f7874" +
"40d73d2b3329aafba3c95ed2601d2fc85231f0f1797f7e36ae4ff379af030a09" +
"1d9c476468eff8be50632c706f0308a5e3a307a1929241b8fcd4fef447c6606b" +
"7c45cc01c3dae196b54479d453428c378ec9cdbd45ff514793a91d61d0b230ff" +
"4af62765773e9b51ef2f5965c046b25e7c09b42838b2a19fe5262756a64e7b96" +
"6fa0159f369d6afb9f4486e2cc7e56a9b9d5afdd28e8c0e19ff4cdf2f7904a12" +
"8284201f51dbdfb3fffb2d482764226c8bee83190d99e6bd0bf310eab5501922" +
"aede091d3ee8fc405874a63fc696c577829192c65b70964bf54db87c77fe823b" +
"19a8344275142387926909c39c0008d9111c78d7e296ba74ca448010db327e11" +
"0927fe2029a5fcfde66d6883a26bab78e3dfdb9569a64d117b26e04d627b35b7" +
"3a795eb9e6ea7bd4469403cb8a822831c71bc587d3b81b0ae4ca381df8b6872c" +
"8bea5f8c99be643f34bafe5bac178c5a36a4c8088e0535eda0511326e3b0ae5e" +
"dafde080886fa539f659525d3fcd38468e8c00c05d223d6bd060ef875894f7bc" +
"63e61854fad5f6146959d0447a4714a3b79292890ae52c7aa82075f56386e3d3" +
"fa2d3376156dc2f5811bd1ac2ca97cb1068a22577513e68a7a0116c6268f9146" +
"a718c9e11dad701f3562be8cb9beb3aadd2003b32e3d88afbf178f7a7b5daf09" +
"f5acaad1fe0dd27d7094a522a39ede71e621dc2b25b4e855d9a1853cdfa5f6f7" +
"b4a0e1c7a5eacd4903aef9eae6a1c2df370137830bcf5cae2e96eef2d9934e9d" +
"21e756499370cba32dc923f26915864b2a3cd5b046fad05922ff686f8ccb0b2b" +
"4bce27d4c91a0c4d3fab3fd65eb0327d2435c27bdd789b66cb88fe56c31b1785" +
"b8820a7c07947f3bf0d6d18ab2d334d927a70dad2fcdad31422138bb3ef39a3d" +
"0e66c298e66d38efad20a8e963b98a59e8b6c5d92aea4364c5f720ea9ab6f510" +
"2c5ccad50bcb3b5d3fe1ae2810118af0339a6b980c3e2ff1014675ef3a8ea84c" +
"3a27b18a088979cddaee68cb65761fdeafc1ab766c13ca8c073cadedec3bf7c0" +
"bdc2e91dcbb1295100a3d66838992a19049a7c25ad683c55ed9831cf187dfdba" +
"242c38a9a32b9d023753c31519987f43d57a02b238230e93f8c5f5ab64516ece" +
"eb915dda45ceb7257e87c909a381248a809b30202884b26eac08b53f9de2478f" +
"3b0b410698e44744fbe63082032906092a864886f70d010701a082031a048203" +
"16308203123082030e060b2a864886f70d010c0a0102a08202c3308202bf3049" +
"06092a864886f70d01050d303c301b06092a864886f70d01050c300e040875ea" +
"e60a1bd8525102020800301d060960864801650304010204101c066ab644ec44" +
"506b2accab7458b77f04820270c4f2702354ebcd5eb1bfb82bd22382035a7907" +
"ab5af91d045250ac1d56f95e4b0d944a99bccd266ea4f7402e5c2082f70ac8ff" +
"081242bbd0e9b374eedcafbca01983ca9e324d8850cad4ac43396b1a3250e365" +
"fa01e3882d19a01f017724a90242d0558d75399cf310ac551cd60d92e26bc8b2" +
"7872882b1f41819d1f660f18a0a2825bd81c861e02124c586046a3609f36713b" +
"dcefdc617788032d13268dfb6530205757aba368950041830cbd07ad3ef3987a" +
"5d71c1cf9987be05de696b4191a44f405227c89fc857dfbf956fe0ab1a0d8c02" +
"613773b1234acd9d3c75994ea00883c1686e3e57661d9937c1837770b3dd2874" +
"0ccfcff02d1998cb9907a78b9d95475542cd3e064231f40e425a745dbc5cfec8" +
"30f7b6e935487e68b664d998ddfaa06db44c247a0f012f17099c8bb955827e13" +
"5017b2526bee9a222e70933f6d7b8968dffe4ca033022d4eac85259434d68e89" +
"43d3c9e4c516ec88bb81971d6751803aef4afdb01505f81f8f71d3c074ab788f" +
"7a5d197c3985488b6acc53c23bef91906f3009c6ec199cc916fcb88876a28727" +
"32ee95d59f636d78e597e10a0e305bd1a5ccda8ad9716f0b5e9c8ca9bfa9ee54" +
"224c1183d499d063c6c1ec02b7f9a482b8983bcbad6b64eefc77ef961ec4dd02" +
"1f832e3c048b9f77034bbd896b7ab13a9f22d7fe94c88626e77b7c0b2d9fac44" +
"914bd9c50cc69ef58044ae1cc423eb321bf5ce2c7505df45d21b932c675c0c5b" +
"3705328245bc70ac262808519681f94489912a3dea891aab2d3bdc573b6b17cf" +
"6bfd8c1a93404a91efaca5441cd2192b71529a543938056382a7f54fabea4760" +
"6ef9ea7c8cdd663036e528ae6043ff138354b43b85cf488f3748fb1051313830" +
"1106092a864886f70d01091431041e020061302306092a864886f70d01091531" +
"160414664fad18d5583599e1cbe7fe694f36237e2272c530313021300906052b" +
"0e03021a0500041472658e404aba0df42263cff430397794c379977504084962" +
"aeaf211dfa1f02020800";
public static void main(String[] args) throws Exception {
byte[] p12 = new byte[P12_FILE.length() / 2];
for (int i = 0; i < p12.length; i++) {
p12[i] = Integer.valueOf(P12_FILE.substring(2 * i, 2 * i + 2), 16)
.byteValue();
}
KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(new ByteArrayInputStream(p12), "changeit".toCharArray());
// Make sure both cert and key can be retrieved
System.out.println(ks.getCertificate("a"));
System.out.println(ks.getKey("a", "changeit".toCharArray()));
}
}
| openjdk/jdk8u | jdk/test/sun/security/pkcs12/PBES2Encoding.java | Java | gpl-2.0 | 7,840 |
/*
* exynos_thermal.h - Samsung EXYNOS TMU (Thermal Management Unit)
*
* Copyright (C) 2011 Samsung Electronics
* Donggeun Kim <dg77.kim@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef _LINUX_EXYNOS_THERMAL_H
#define _LINUX_EXYNOS_THERMAL_H
#include <linux/cpu_cooling.h>
enum calibration_type {
TYPE_ONE_POINT_TRIMMING,
TYPE_TWO_POINT_TRIMMING,
TYPE_NONE,
};
enum soc_type {
SOC_ARCH_EXYNOS4 = 1,
SOC_ARCH_EXYNOS5,
};
/**
* struct exynos_tmu_platform_data
* @threshold: basic temperature for generating interrupt
* 25 <= threshold <= 125 [unit: degree Celsius]
* @trigger_levels: array for each interrupt levels
* [unit: degree Celsius]
* 0: temperature for trigger_level0 interrupt
* condition for trigger_level0 interrupt:
* current temperature > threshold + trigger_levels[0]
* 1: temperature for trigger_level1 interrupt
* condition for trigger_level1 interrupt:
* current temperature > threshold + trigger_levels[1]
* 2: temperature for trigger_level2 interrupt
* condition for trigger_level2 interrupt:
* current temperature > threshold + trigger_levels[2]
* 3: temperature for trigger_level3 interrupt
* condition for trigger_level3 interrupt:
* current temperature > threshold + trigger_levels[3]
* @trigger_level0_en:
* 1 = enable trigger_level0 interrupt,
* 0 = disable trigger_level0 interrupt
* @trigger_level1_en:
* 1 = enable trigger_level1 interrupt,
* 0 = disable trigger_level1 interrupt
* @trigger_level2_en:
* 1 = enable trigger_level2 interrupt,
* 0 = disable trigger_level2 interrupt
* @trigger_level3_en:
* 1 = enable trigger_level3 interrupt,
* 0 = disable trigger_level3 interrupt
* @gain: gain of amplifier in the positive-TC generator block
* 0 <= gain <= 15
* @reference_voltage: reference voltage of amplifier
* in the positive-TC generator block
* 0 <= reference_voltage <= 31
* @noise_cancel_mode: noise cancellation mode
* 000, 100, 101, 110 and 111 can be different modes
* @type: determines the type of SOC
* @efuse_value: platform defined fuse value
* @cal_type: calibration type for temperature
* @freq_clip_table: Table representing frequency reduction percentage.
* @freq_tab_count: Count of the above table as frequency reduction may
* applicable to only some of the trigger levels.
*
* This structure is required for configuration of exynos_tmu driver.
*/
struct exynos_tmu_platform_data {
u8 threshold;
u8 trigger_levels[4];
bool trigger_level0_en;
bool trigger_level1_en;
bool trigger_level2_en;
bool trigger_level3_en;
char clk_name[100];
u8 gain;
u8 reference_voltage;
u8 noise_cancel_mode;
u32 efuse_value;
enum calibration_type cal_type;
enum soc_type type;
struct freq_clip_table freq_tab[8];
struct freq_clip_table freq_tab_kfc[8];
int size[THERMAL_TRIP_CRITICAL + 1];
unsigned int freq_tab_count;
};
#endif /* _LINUX_EXYNOS_THERMAL_H */
| rutvik95/android_kernel_samsung_universal-5260 | include/linux/platform_data/exynos_thermal.h | C | gpl-2.0 | 3,580 |
/*
Unix SMB/CIFS implementation.
replacement routines for broken systems
Copyright (C) Andrew Tridgell 1992-1998
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 "includes.h"
void replace1_dummy(void);
void replace1_dummy(void) {}
#ifndef HAVE_SETENV
int setenv(const char *name, const char *value, int overwrite)
{
char *p = NULL;
int ret = -1;
asprintf(&p, "%s=%s", name, value);
if (overwrite || getenv(name)) {
if (p) ret = putenv(p);
} else {
ret = 0;
}
return ret;
}
#endif
| ipwndev/DSLinux-Mirror | user/samba/source/lib/replace1.c | C | gpl-2.0 | 1,178 |
/* -*- Mode: c; c-basic-offset: 4; indent-tabs-mode: t; tab-width: 8; -*- */
/* cairo - a vector graphics library with display and print output
*
* Copyright © 2000 Keith Packard
* Copyright © 2005 Red Hat, Inc
*
* This library is free software; you can redistribute it and/or
* modify it either under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* (the "LGPL") or, at your option, under the terms of the Mozilla
* Public License Version 1.1 (the "MPL"). If you do not alter this
* notice, a recipient may use your version of this file under either
* the MPL or the LGPL.
*
* You should have received a copy of the LGPL along with this library
* in the file COPYING-LGPL-2.1; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA
* You should have received a copy of the MPL along with this library
* in the file COPYING-MPL-1.1
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
* OF ANY KIND, either express or implied. See the LGPL or the MPL for
* the specific language governing rights and limitations.
*
* The Original Code is the cairo graphics library.
*
* The Initial Developer of the Original Code is Red Hat, Inc.
*
* Contributor(s):
* Graydon Hoare <graydon@redhat.com>
* Owen Taylor <otaylor@redhat.com>
* Keith Packard <keithp@keithp.com>
* Carl Worth <cworth@cworth.org>
*/
#define _BSD_SOURCE /* for strdup() */
#include "cairoint.h"
#include "cairo-error-private.h"
#include "cairo-ft-private.h"
#include <float.h>
#include "cairo-fontconfig-private.h"
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_OUTLINE_H
#include FT_IMAGE_H
#include FT_TRUETYPE_TABLES_H
#if HAVE_FT_GLYPHSLOT_EMBOLDEN
#include FT_SYNTHESIS_H
#endif
#if HAVE_FT_LIBRARY_SETLCDFILTER
#include FT_LCD_FILTER_H
#endif
/* Fontconfig version older than 2.6 didn't have these options */
#ifndef FC_LCD_FILTER
#define FC_LCD_FILTER "lcdfilter"
#endif
/* Some Ubuntu versions defined FC_LCD_FILTER without defining the following */
#ifndef FC_LCD_NONE
#define FC_LCD_NONE 0
#define FC_LCD_DEFAULT 1
#define FC_LCD_LIGHT 2
#define FC_LCD_LEGACY 3
#endif
/* FreeType version older than 2.3.5(?) didn't have these options */
#ifndef FT_LCD_FILTER_NONE
#define FT_LCD_FILTER_NONE 0
#define FT_LCD_FILTER_DEFAULT 1
#define FT_LCD_FILTER_LIGHT 2
#define FT_LCD_FILTER_LEGACY 16
#endif
#define DOUBLE_TO_26_6(d) ((FT_F26Dot6)((d) * 64.0))
#define DOUBLE_FROM_26_6(t) ((double)(t) / 64.0)
#define DOUBLE_TO_16_16(d) ((FT_Fixed)((d) * 65536.0))
#define DOUBLE_FROM_16_16(t) ((double)(t) / 65536.0)
/* This is the max number of FT_face objects we keep open at once
*/
#define MAX_OPEN_FACES 10
/**
* SECTION:cairo-ft
* @Title: FreeType Fonts
* @Short_Description: Font support for FreeType
* @See_Also: #cairo_font_face_t
*
* The FreeType font backend is primarily used to render text on GNU/Linux
* systems, but can be used on other platforms too.
*/
/**
* CAIRO_HAS_FT_FONT:
*
* Defined if the FreeType font backend is available.
* This macro can be used to conditionally compile backend-specific code.
*/
/**
* CAIRO_HAS_FC_FONT:
*
* Defined if the Fontconfig-specific functions of the FreeType font backend
* are available.
* This macro can be used to conditionally compile backend-specific code.
*/
/*
* The simple 2x2 matrix is converted into separate scale and shape
* factors so that hinting works right
*/
typedef struct _cairo_ft_font_transform {
double x_scale, y_scale;
double shape[2][2];
} cairo_ft_font_transform_t;
/*
* We create an object that corresponds to a single font on the disk;
* (identified by a filename/id pair) these are shared between all
* fonts using that file. For cairo_ft_font_face_create_for_ft_face(), we
* just create a one-off version with a permanent face value.
*/
typedef struct _cairo_ft_font_face cairo_ft_font_face_t;
struct _cairo_ft_unscaled_font {
cairo_unscaled_font_t base;
cairo_bool_t from_face; /* was the FT_Face provided by user? */
FT_Face face; /* provided or cached face */
/* only set if from_face is false */
char *filename;
int id;
/* We temporarily scale the unscaled font as needed */
cairo_bool_t have_scale;
cairo_matrix_t current_scale;
double x_scale; /* Extracted X scale factor */
double y_scale; /* Extracted Y scale factor */
cairo_bool_t have_shape; /* true if the current scale has a non-scale component*/
cairo_matrix_t current_shape;
FT_Matrix Current_Shape;
cairo_mutex_t mutex;
int lock_count;
cairo_ft_font_face_t *faces; /* Linked list of faces for this font */
};
static int
_cairo_ft_unscaled_font_keys_equal (const void *key_a,
const void *key_b);
static void
_cairo_ft_unscaled_font_fini (cairo_ft_unscaled_font_t *unscaled);
typedef enum _cairo_ft_extra_flags {
CAIRO_FT_OPTIONS_HINT_METRICS = (1 << 0),
CAIRO_FT_OPTIONS_EMBOLDEN = (1 << 1)
} cairo_ft_extra_flags_t;
typedef struct _cairo_ft_options {
cairo_font_options_t base;
int load_flags; /* flags for FT_Load_Glyph */
cairo_ft_extra_flags_t extra_flags; /* other flags that affect results */
} cairo_ft_options_t;
struct _cairo_ft_font_face {
cairo_font_face_t base;
cairo_ft_unscaled_font_t *unscaled;
cairo_ft_options_t ft_options;
cairo_ft_font_face_t *next;
#if CAIRO_HAS_FC_FONT
FcPattern *pattern; /* if pattern is set, the above fields will be NULL */
cairo_font_face_t *resolved_font_face;
FcConfig *resolved_config;
#endif
};
static const cairo_unscaled_font_backend_t cairo_ft_unscaled_font_backend;
#if CAIRO_HAS_FC_FONT
static cairo_status_t
_cairo_ft_font_options_substitute (const cairo_font_options_t *options,
FcPattern *pattern);
static cairo_font_face_t *
_cairo_ft_resolve_pattern (FcPattern *pattern,
const cairo_matrix_t *font_matrix,
const cairo_matrix_t *ctm,
const cairo_font_options_t *options);
#endif
/*
* We maintain a hash table to map file/id => #cairo_ft_unscaled_font_t.
* The hash table itself isn't limited in size. However, we limit the
* number of FT_Face objects we keep around; when we've exceeded that
* limit and need to create a new FT_Face, we dump the FT_Face from a
* random #cairo_ft_unscaled_font_t which has an unlocked FT_Face, (if
* there are any).
*/
typedef struct _cairo_ft_unscaled_font_map {
cairo_hash_table_t *hash_table;
FT_Library ft_library;
int num_open_faces;
} cairo_ft_unscaled_font_map_t;
static cairo_ft_unscaled_font_map_t *cairo_ft_unscaled_font_map = NULL;
static void
_font_map_release_face_lock_held (cairo_ft_unscaled_font_map_t *font_map,
cairo_ft_unscaled_font_t *unscaled)
{
if (unscaled->face) {
FT_Done_Face (unscaled->face);
unscaled->face = NULL;
unscaled->have_scale = FALSE;
font_map->num_open_faces--;
}
}
static cairo_status_t
_cairo_ft_unscaled_font_map_create (void)
{
cairo_ft_unscaled_font_map_t *font_map;
/* This function is only intended to be called from
* _cairo_ft_unscaled_font_map_lock. So we'll crash if we can
* detect some other call path. */
assert (cairo_ft_unscaled_font_map == NULL);
font_map = malloc (sizeof (cairo_ft_unscaled_font_map_t));
if (unlikely (font_map == NULL))
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
font_map->hash_table =
_cairo_hash_table_create (_cairo_ft_unscaled_font_keys_equal);
if (unlikely (font_map->hash_table == NULL))
goto FAIL;
if (unlikely (FT_Init_FreeType (&font_map->ft_library)))
goto FAIL;
font_map->num_open_faces = 0;
cairo_ft_unscaled_font_map = font_map;
return CAIRO_STATUS_SUCCESS;
FAIL:
if (font_map->hash_table)
_cairo_hash_table_destroy (font_map->hash_table);
free (font_map);
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
}
static void
_cairo_ft_unscaled_font_map_pluck_entry (void *entry, void *closure)
{
cairo_ft_unscaled_font_t *unscaled = entry;
cairo_ft_unscaled_font_map_t *font_map = closure;
_cairo_hash_table_remove (font_map->hash_table,
&unscaled->base.hash_entry);
if (! unscaled->from_face)
_font_map_release_face_lock_held (font_map, unscaled);
_cairo_ft_unscaled_font_fini (unscaled);
free (unscaled);
}
static void
_cairo_ft_unscaled_font_map_destroy (void)
{
cairo_ft_unscaled_font_map_t *font_map;
CAIRO_MUTEX_LOCK (_cairo_ft_unscaled_font_map_mutex);
font_map = cairo_ft_unscaled_font_map;
cairo_ft_unscaled_font_map = NULL;
CAIRO_MUTEX_UNLOCK (_cairo_ft_unscaled_font_map_mutex);
if (font_map != NULL) {
_cairo_hash_table_foreach (font_map->hash_table,
_cairo_ft_unscaled_font_map_pluck_entry,
font_map);
assert (font_map->num_open_faces == 0);
FT_Done_FreeType (font_map->ft_library);
_cairo_hash_table_destroy (font_map->hash_table);
free (font_map);
}
}
static cairo_ft_unscaled_font_map_t *
_cairo_ft_unscaled_font_map_lock (void)
{
CAIRO_MUTEX_LOCK (_cairo_ft_unscaled_font_map_mutex);
if (unlikely (cairo_ft_unscaled_font_map == NULL)) {
if (unlikely (_cairo_ft_unscaled_font_map_create ())) {
CAIRO_MUTEX_UNLOCK (_cairo_ft_unscaled_font_map_mutex);
return NULL;
}
}
return cairo_ft_unscaled_font_map;
}
static void
_cairo_ft_unscaled_font_map_unlock (void)
{
CAIRO_MUTEX_UNLOCK (_cairo_ft_unscaled_font_map_mutex);
}
static void
_cairo_ft_unscaled_font_init_key (cairo_ft_unscaled_font_t *key,
cairo_bool_t from_face,
char *filename,
int id,
FT_Face face)
{
unsigned long hash;
key->from_face = from_face;
key->filename = filename;
key->id = id;
key->face = face;
hash = _cairo_hash_string (filename);
/* the constants are just arbitrary primes */
hash += ((unsigned long) id) * 1607;
hash += ((unsigned long) face) * 2137;
key->base.hash_entry.hash = hash;
}
/**
* _cairo_ft_unscaled_font_init:
*
* Initialize a #cairo_ft_unscaled_font_t.
*
* There are two basic flavors of #cairo_ft_unscaled_font_t, one
* created from an FT_Face and the other created from a filename/id
* pair. These two flavors are identified as from_face and !from_face.
*
* To initialize a from_face font, pass filename==%NULL, id=0 and the
* desired face.
*
* To initialize a !from_face font, pass the filename/id as desired
* and face==%NULL.
*
* Note that the code handles these two flavors in very distinct
* ways. For example there is a hash_table mapping
* filename/id->#cairo_unscaled_font_t in the !from_face case, but no
* parallel in the from_face case, (where the calling code would have
* to do its own mapping to ensure similar sharing).
**/
static cairo_status_t
_cairo_ft_unscaled_font_init (cairo_ft_unscaled_font_t *unscaled,
cairo_bool_t from_face,
const char *filename,
int id,
FT_Face face)
{
_cairo_unscaled_font_init (&unscaled->base,
&cairo_ft_unscaled_font_backend);
if (from_face) {
unscaled->from_face = TRUE;
_cairo_ft_unscaled_font_init_key (unscaled, TRUE, NULL, 0, face);
} else {
char *filename_copy;
unscaled->from_face = FALSE;
unscaled->face = NULL;
filename_copy = strdup (filename);
if (unlikely (filename_copy == NULL))
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
_cairo_ft_unscaled_font_init_key (unscaled, FALSE, filename_copy, id, NULL);
}
unscaled->have_scale = FALSE;
CAIRO_MUTEX_INIT (unscaled->mutex);
unscaled->lock_count = 0;
unscaled->faces = NULL;
return CAIRO_STATUS_SUCCESS;
}
/**
* _cairo_ft_unscaled_font_fini:
*
* Free all data associated with a #cairo_ft_unscaled_font_t.
*
* CAUTION: The unscaled->face field must be %NULL before calling this
* function. This is because the #cairo_ft_unscaled_font_t_map keeps a
* count of these faces (font_map->num_open_faces) so it maintains the
* unscaled->face field while it has its lock held. See
* _font_map_release_face_lock_held().
**/
static void
_cairo_ft_unscaled_font_fini (cairo_ft_unscaled_font_t *unscaled)
{
assert (unscaled->face == NULL);
if (unscaled->filename) {
free (unscaled->filename);
unscaled->filename = NULL;
}
CAIRO_MUTEX_FINI (unscaled->mutex);
}
static int
_cairo_ft_unscaled_font_keys_equal (const void *key_a,
const void *key_b)
{
const cairo_ft_unscaled_font_t *unscaled_a = key_a;
const cairo_ft_unscaled_font_t *unscaled_b = key_b;
if (unscaled_a->id == unscaled_b->id &&
unscaled_a->from_face == unscaled_b->from_face)
{
if (unscaled_a->from_face)
return unscaled_a->face == unscaled_b->face;
if (unscaled_a->filename == NULL && unscaled_b->filename == NULL)
return TRUE;
else if (unscaled_a->filename == NULL || unscaled_b->filename == NULL)
return FALSE;
else
return (strcmp (unscaled_a->filename, unscaled_b->filename) == 0);
}
return FALSE;
}
/* Finds or creates a #cairo_ft_unscaled_font_t for the filename/id from
* pattern. Returns a new reference to the unscaled font.
*/
static cairo_status_t
_cairo_ft_unscaled_font_create_internal (cairo_bool_t from_face,
char *filename,
int id,
FT_Face font_face,
cairo_ft_unscaled_font_t **out)
{
cairo_ft_unscaled_font_t key, *unscaled;
cairo_ft_unscaled_font_map_t *font_map;
cairo_status_t status;
font_map = _cairo_ft_unscaled_font_map_lock ();
if (unlikely (font_map == NULL))
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
_cairo_ft_unscaled_font_init_key (&key, from_face, filename, id, font_face);
/* Return existing unscaled font if it exists in the hash table. */
unscaled = _cairo_hash_table_lookup (font_map->hash_table,
&key.base.hash_entry);
if (unscaled != NULL) {
_cairo_unscaled_font_reference (&unscaled->base);
goto DONE;
}
/* Otherwise create it and insert into hash table. */
unscaled = malloc (sizeof (cairo_ft_unscaled_font_t));
if (unlikely (unscaled == NULL)) {
status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
goto UNWIND_FONT_MAP_LOCK;
}
status = _cairo_ft_unscaled_font_init (unscaled, from_face, filename, id, font_face);
if (unlikely (status))
goto UNWIND_UNSCALED_MALLOC;
assert (unscaled->base.hash_entry.hash == key.base.hash_entry.hash);
status = _cairo_hash_table_insert (font_map->hash_table,
&unscaled->base.hash_entry);
if (unlikely (status))
goto UNWIND_UNSCALED_FONT_INIT;
DONE:
_cairo_ft_unscaled_font_map_unlock ();
*out = unscaled;
return CAIRO_STATUS_SUCCESS;
UNWIND_UNSCALED_FONT_INIT:
_cairo_ft_unscaled_font_fini (unscaled);
UNWIND_UNSCALED_MALLOC:
free (unscaled);
UNWIND_FONT_MAP_LOCK:
_cairo_ft_unscaled_font_map_unlock ();
return status;
}
#if CAIRO_HAS_FC_FONT
static cairo_status_t
_cairo_ft_unscaled_font_create_for_pattern (FcPattern *pattern,
cairo_ft_unscaled_font_t **out)
{
FT_Face font_face = NULL;
char *filename = NULL;
int id = 0;
FcResult ret;
ret = FcPatternGetFTFace (pattern, FC_FT_FACE, 0, &font_face);
if (ret == FcResultMatch)
goto DONE;
if (ret == FcResultOutOfMemory)
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
ret = FcPatternGetString (pattern, FC_FILE, 0, (FcChar8 **) &filename);
if (ret == FcResultOutOfMemory)
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
if (ret == FcResultMatch) {
/* If FC_INDEX is not set, we just use 0 */
ret = FcPatternGetInteger (pattern, FC_INDEX, 0, &id);
if (ret == FcResultOutOfMemory)
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
goto DONE;
}
/* The pattern contains neither a face nor a filename, resolve it later. */
*out = NULL;
return CAIRO_STATUS_SUCCESS;
DONE:
return _cairo_ft_unscaled_font_create_internal (font_face != NULL,
filename, id, font_face,
out);
}
#endif
static cairo_status_t
_cairo_ft_unscaled_font_create_from_face (FT_Face face,
cairo_ft_unscaled_font_t **out)
{
return _cairo_ft_unscaled_font_create_internal (TRUE, NULL, 0, face, out);
}
static void
_cairo_ft_unscaled_font_destroy (void *abstract_font)
{
cairo_ft_unscaled_font_t *unscaled = abstract_font;
cairo_ft_unscaled_font_map_t *font_map;
if (unscaled == NULL)
return;
font_map = _cairo_ft_unscaled_font_map_lock ();
/* All created objects must have been mapped in the font map. */
assert (font_map != NULL);
if (CAIRO_REFERENCE_COUNT_HAS_REFERENCE (&unscaled->base.ref_count)) {
/* somebody recreated the font whilst we waited for the lock */
_cairo_ft_unscaled_font_map_unlock ();
return;
}
_cairo_hash_table_remove (font_map->hash_table,
&unscaled->base.hash_entry);
if (unscaled->from_face) {
/* See comments in _ft_font_face_destroy about the "zombie" state
* for a _ft_font_face.
*/
if (unscaled->faces && unscaled->faces->unscaled == NULL) {
assert (unscaled->faces->next == NULL);
cairo_font_face_destroy (&unscaled->faces->base);
}
} else {
_font_map_release_face_lock_held (font_map, unscaled);
}
unscaled->face = NULL;
_cairo_ft_unscaled_font_map_unlock ();
_cairo_ft_unscaled_font_fini (unscaled);
}
static cairo_bool_t
_has_unlocked_face (const void *entry)
{
const cairo_ft_unscaled_font_t *unscaled = entry;
return (!unscaled->from_face && unscaled->lock_count == 0 && unscaled->face);
}
/* Ensures that an unscaled font has a face object. If we exceed
* MAX_OPEN_FACES, try to close some.
*
* This differs from _cairo_ft_scaled_font_lock_face in that it doesn't
* set the scale on the face, but just returns it at the last scale.
*/
cairo_warn FT_Face
_cairo_ft_unscaled_font_lock_face (cairo_ft_unscaled_font_t *unscaled)
{
cairo_ft_unscaled_font_map_t *font_map;
FT_Face face = NULL;
CAIRO_MUTEX_LOCK (unscaled->mutex);
unscaled->lock_count++;
if (unscaled->face)
return unscaled->face;
/* If this unscaled font was created from an FT_Face then we just
* returned it above. */
assert (!unscaled->from_face);
font_map = _cairo_ft_unscaled_font_map_lock ();
{
assert (font_map != NULL);
while (font_map->num_open_faces >= MAX_OPEN_FACES)
{
cairo_ft_unscaled_font_t *entry;
entry = _cairo_hash_table_random_entry (font_map->hash_table,
_has_unlocked_face);
if (entry == NULL)
break;
_font_map_release_face_lock_held (font_map, entry);
}
}
_cairo_ft_unscaled_font_map_unlock ();
if (FT_New_Face (font_map->ft_library,
unscaled->filename,
unscaled->id,
&face) != FT_Err_Ok)
{
unscaled->lock_count--;
CAIRO_MUTEX_UNLOCK (unscaled->mutex);
_cairo_error_throw (CAIRO_STATUS_NO_MEMORY);
return NULL;
}
unscaled->face = face;
font_map->num_open_faces++;
return face;
}
/* Unlock unscaled font locked with _cairo_ft_unscaled_font_lock_face
*/
void
_cairo_ft_unscaled_font_unlock_face (cairo_ft_unscaled_font_t *unscaled)
{
assert (unscaled->lock_count > 0);
unscaled->lock_count--;
CAIRO_MUTEX_UNLOCK (unscaled->mutex);
}
static cairo_status_t
_compute_transform (cairo_ft_font_transform_t *sf,
cairo_matrix_t *scale)
{
cairo_status_t status;
double x_scale, y_scale;
cairo_matrix_t normalized = *scale;
/* The font matrix has x and y "scale" components which we extract and
* use as character scale values. These influence the way freetype
* chooses hints, as well as selecting different bitmaps in
* hand-rendered fonts. We also copy the normalized matrix to
* freetype's transformation.
*/
status = _cairo_matrix_compute_basis_scale_factors (scale,
&x_scale, &y_scale,
1);
if (unlikely (status))
return status;
/* FreeType docs say this about x_scale and y_scale:
* "A character width or height smaller than 1pt is set to 1pt;"
* So, we cap them from below at 1.0 and let the FT transform
* take care of sub-1.0 scaling. */
if (x_scale < 1.0)
x_scale = 1.0;
if (y_scale < 1.0)
y_scale = 1.0;
sf->x_scale = x_scale;
sf->y_scale = y_scale;
cairo_matrix_scale (&normalized, 1.0 / x_scale, 1.0 / y_scale);
_cairo_matrix_get_affine (&normalized,
&sf->shape[0][0], &sf->shape[0][1],
&sf->shape[1][0], &sf->shape[1][1],
NULL, NULL);
return CAIRO_STATUS_SUCCESS;
}
/* Temporarily scales an unscaled font to the give scale. We catch
* scaling to the same size, since changing a FT_Face is expensive.
*/
static cairo_status_t
_cairo_ft_unscaled_font_set_scale (cairo_ft_unscaled_font_t *unscaled,
cairo_matrix_t *scale)
{
cairo_status_t status;
cairo_ft_font_transform_t sf;
FT_Matrix mat;
FT_Error error;
assert (unscaled->face != NULL);
if (unscaled->have_scale &&
scale->xx == unscaled->current_scale.xx &&
scale->yx == unscaled->current_scale.yx &&
scale->xy == unscaled->current_scale.xy &&
scale->yy == unscaled->current_scale.yy)
return CAIRO_STATUS_SUCCESS;
unscaled->have_scale = TRUE;
unscaled->current_scale = *scale;
status = _compute_transform (&sf, scale);
if (unlikely (status))
return status;
unscaled->x_scale = sf.x_scale;
unscaled->y_scale = sf.y_scale;
mat.xx = DOUBLE_TO_16_16(sf.shape[0][0]);
mat.yx = - DOUBLE_TO_16_16(sf.shape[0][1]);
mat.xy = - DOUBLE_TO_16_16(sf.shape[1][0]);
mat.yy = DOUBLE_TO_16_16(sf.shape[1][1]);
unscaled->have_shape = (mat.xx != 0x10000 ||
mat.yx != 0x00000 ||
mat.xy != 0x00000 ||
mat.yy != 0x10000);
unscaled->Current_Shape = mat;
cairo_matrix_init (&unscaled->current_shape,
sf.shape[0][0], sf.shape[0][1],
sf.shape[1][0], sf.shape[1][1],
0.0, 0.0);
FT_Set_Transform(unscaled->face, &mat, NULL);
if ((unscaled->face->face_flags & FT_FACE_FLAG_SCALABLE) != 0) {
error = FT_Set_Char_Size (unscaled->face,
sf.x_scale * 64.0 + .5,
sf.y_scale * 64.0 + .5,
0, 0);
if (error)
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
} else {
double min_distance = DBL_MAX;
int i;
int best_i = 0;
for (i = 0; i < unscaled->face->num_fixed_sizes; i++) {
#if HAVE_FT_BITMAP_SIZE_Y_PPEM
double size = unscaled->face->available_sizes[i].y_ppem / 64.;
#else
double size = unscaled->face->available_sizes[i].height;
#endif
double distance = fabs (size - sf.y_scale);
if (distance <= min_distance) {
min_distance = distance;
best_i = i;
}
}
#if HAVE_FT_BITMAP_SIZE_Y_PPEM
error = FT_Set_Char_Size (unscaled->face,
unscaled->face->available_sizes[best_i].x_ppem,
unscaled->face->available_sizes[best_i].y_ppem,
0, 0);
if (error)
#endif
error = FT_Set_Pixel_Sizes (unscaled->face,
unscaled->face->available_sizes[best_i].width,
unscaled->face->available_sizes[best_i].height);
if (error)
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
}
return CAIRO_STATUS_SUCCESS;
}
/* we sometimes need to convert the glyph bitmap in a FT_GlyphSlot
* into a different format. For example, we want to convert a
* FT_PIXEL_MODE_LCD or FT_PIXEL_MODE_LCD_V bitmap into a 32-bit
* ARGB or ABGR bitmap.
*
* this function prepares a target descriptor for this operation.
*
* input :: target bitmap descriptor. The function will set its
* 'width', 'rows' and 'pitch' fields, and only these
*
* slot :: the glyph slot containing the source bitmap. this
* function assumes that slot->format == FT_GLYPH_FORMAT_BITMAP
*
* mode :: the requested final rendering mode. supported values are
* MONO, NORMAL (i.e. gray), LCD and LCD_V
*
* the function returns the size in bytes of the corresponding buffer,
* it's up to the caller to allocate the corresponding memory block
* before calling _fill_xrender_bitmap
*
* it also returns -1 in case of error (e.g. incompatible arguments,
* like trying to convert a gray bitmap into a monochrome one)
*/
static int
_compute_xrender_bitmap_size(FT_Bitmap *target,
FT_GlyphSlot slot,
FT_Render_Mode mode)
{
FT_Bitmap *ftbit;
int width, height, pitch;
if (slot->format != FT_GLYPH_FORMAT_BITMAP)
return -1;
/* compute the size of the final bitmap */
ftbit = &slot->bitmap;
width = ftbit->width;
height = ftbit->rows;
pitch = (width + 3) & ~3;
switch (ftbit->pixel_mode) {
case FT_PIXEL_MODE_MONO:
if (mode == FT_RENDER_MODE_MONO) {
pitch = (((width + 31) & ~31) >> 3);
break;
}
/* fall-through */
case FT_PIXEL_MODE_GRAY:
if (mode == FT_RENDER_MODE_LCD ||
mode == FT_RENDER_MODE_LCD_V)
{
/* each pixel is replicated into a 32-bit ARGB value */
pitch = width * 4;
}
break;
case FT_PIXEL_MODE_LCD:
if (mode != FT_RENDER_MODE_LCD)
return -1;
/* horz pixel triplets are packed into 32-bit ARGB values */
width /= 3;
pitch = width * 4;
break;
case FT_PIXEL_MODE_LCD_V:
if (mode != FT_RENDER_MODE_LCD_V)
return -1;
/* vert pixel triplets are packed into 32-bit ARGB values */
height /= 3;
pitch = width * 4;
break;
default: /* unsupported source format */
return -1;
}
target->width = width;
target->rows = height;
target->pitch = pitch;
target->buffer = NULL;
return pitch * height;
}
/* this functions converts the glyph bitmap found in a FT_GlyphSlot
* into a different format (see _compute_xrender_bitmap_size)
*
* you should call this function after _compute_xrender_bitmap_size
*
* target :: target bitmap descriptor. Note that its 'buffer' pointer
* must point to memory allocated by the caller
*
* slot :: the glyph slot containing the source bitmap
*
* mode :: the requested final rendering mode
*
* bgr :: boolean, set if BGR or VBGR pixel ordering is needed
*/
static void
_fill_xrender_bitmap(FT_Bitmap *target,
FT_GlyphSlot slot,
FT_Render_Mode mode,
int bgr)
{
FT_Bitmap *ftbit = &slot->bitmap;
unsigned char *srcLine = ftbit->buffer;
unsigned char *dstLine = target->buffer;
int src_pitch = ftbit->pitch;
int width = target->width;
int height = target->rows;
int pitch = target->pitch;
int subpixel;
int h;
subpixel = (mode == FT_RENDER_MODE_LCD ||
mode == FT_RENDER_MODE_LCD_V);
if (src_pitch < 0)
srcLine -= src_pitch * (ftbit->rows - 1);
target->pixel_mode = ftbit->pixel_mode;
switch (ftbit->pixel_mode) {
case FT_PIXEL_MODE_MONO:
if (subpixel) {
/* convert mono to ARGB32 values */
for (h = height; h > 0; h--, srcLine += src_pitch, dstLine += pitch) {
int x;
for (x = 0; x < width; x++) {
if (srcLine[(x >> 3)] & (0x80 >> (x & 7)))
((unsigned int *) dstLine)[x] = 0xffffffffU;
}
}
target->pixel_mode = FT_PIXEL_MODE_LCD;
} else if (mode == FT_RENDER_MODE_NORMAL) {
/* convert mono to 8-bit gray */
for (h = height; h > 0; h--, srcLine += src_pitch, dstLine += pitch) {
int x;
for (x = 0; x < width; x++) {
if (srcLine[(x >> 3)] & (0x80 >> (x & 7)))
dstLine[x] = 0xff;
}
}
target->pixel_mode = FT_PIXEL_MODE_GRAY;
} else {
/* copy mono to mono */
int bytes = (width + 7) >> 3;
for (h = height; h > 0; h--, srcLine += src_pitch, dstLine += pitch)
memcpy (dstLine, srcLine, bytes);
}
break;
case FT_PIXEL_MODE_GRAY:
if (subpixel) {
/* convert gray to ARGB32 values */
for (h = height; h > 0; h--, srcLine += src_pitch, dstLine += pitch) {
int x;
unsigned int *dst = (unsigned int *) dstLine;
for (x = 0; x < width; x++) {
unsigned int pix = srcLine[x];
pix |= (pix << 8);
pix |= (pix << 16);
dst[x] = pix;
}
}
target->pixel_mode = FT_PIXEL_MODE_LCD;
} else {
/* copy gray into gray */
for (h = height; h > 0; h--, srcLine += src_pitch, dstLine += pitch)
memcpy (dstLine, srcLine, width);
}
break;
case FT_PIXEL_MODE_LCD:
if (!bgr) {
/* convert horizontal RGB into ARGB32 */
for (h = height; h > 0; h--, srcLine += src_pitch, dstLine += pitch) {
int x;
unsigned char *src = srcLine;
unsigned int *dst = (unsigned int *) dstLine;
for (x = 0; x < width; x++, src += 3) {
unsigned int pix;
pix = ((unsigned int)src[0] << 16) |
((unsigned int)src[1] << 8) |
((unsigned int)src[2] ) |
((unsigned int)src[1] << 24) ;
dst[x] = pix;
}
}
} else {
/* convert horizontal BGR into ARGB32 */
for (h = height; h > 0; h--, srcLine += src_pitch, dstLine += pitch) {
int x;
unsigned char *src = srcLine;
unsigned int *dst = (unsigned int *) dstLine;
for (x = 0; x < width; x++, src += 3) {
unsigned int pix;
pix = ((unsigned int)src[2] << 16) |
((unsigned int)src[1] << 8) |
((unsigned int)src[0] ) |
((unsigned int)src[1] << 24) ;
dst[x] = pix;
}
}
}
break;
default: /* FT_PIXEL_MODE_LCD_V */
/* convert vertical RGB into ARGB32 */
if (!bgr) {
for (h = height; h > 0; h--, srcLine += 3 * src_pitch, dstLine += pitch) {
int x;
unsigned char* src = srcLine;
unsigned int* dst = (unsigned int *) dstLine;
for (x = 0; x < width; x++, src += 1) {
unsigned int pix;
pix = ((unsigned int)src[0] << 16) |
((unsigned int)src[src_pitch] << 8) |
((unsigned int)src[src_pitch*2] ) |
((unsigned int)src[src_pitch] << 24) ;
dst[x] = pix;
}
}
} else {
for (h = height; h > 0; h--, srcLine += 3*src_pitch, dstLine += pitch) {
int x;
unsigned char *src = srcLine;
unsigned int *dst = (unsigned int *) dstLine;
for (x = 0; x < width; x++, src += 1) {
unsigned int pix;
pix = ((unsigned int)src[src_pitch * 2] << 16) |
((unsigned int)src[src_pitch] << 8) |
((unsigned int)src[0] ) |
((unsigned int)src[src_pitch] << 24) ;
dst[x] = pix;
}
}
}
}
}
/* Fills in val->image with an image surface created from @bitmap
*/
static cairo_status_t
_get_bitmap_surface (FT_Bitmap *bitmap,
cairo_bool_t own_buffer,
cairo_font_options_t *font_options,
cairo_image_surface_t **surface)
{
int width, height, stride;
unsigned char *data;
int format = CAIRO_FORMAT_A8;
cairo_image_surface_t *image;
width = bitmap->width;
height = bitmap->rows;
if (width == 0 || height == 0) {
*surface = (cairo_image_surface_t *)
cairo_image_surface_create_for_data (NULL, format, 0, 0, 0);
return (*surface)->base.status;
}
switch (bitmap->pixel_mode) {
case FT_PIXEL_MODE_MONO:
stride = (((width + 31) & ~31) >> 3);
if (own_buffer) {
data = bitmap->buffer;
assert (stride == bitmap->pitch);
} else {
data = _cairo_malloc_ab (height, stride);
if (!data)
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
if (stride == bitmap->pitch) {
memcpy (data, bitmap->buffer, stride * height);
} else {
int i;
unsigned char *source, *dest;
source = bitmap->buffer;
dest = data;
for (i = height; i; i--) {
memcpy (dest, source, bitmap->pitch);
memset (dest + bitmap->pitch, '\0', stride - bitmap->pitch);
source += bitmap->pitch;
dest += stride;
}
}
}
#ifndef WORDS_BIGENDIAN
{
uint8_t *d = data;
int count = stride * height;
while (count--) {
*d = CAIRO_BITSWAP8 (*d);
d++;
}
}
#endif
format = CAIRO_FORMAT_A1;
break;
case FT_PIXEL_MODE_LCD:
case FT_PIXEL_MODE_LCD_V:
case FT_PIXEL_MODE_GRAY:
if (font_options->antialias != CAIRO_ANTIALIAS_SUBPIXEL) {
stride = bitmap->pitch;
if (own_buffer) {
data = bitmap->buffer;
} else {
data = _cairo_malloc_ab (height, stride);
if (!data)
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
memcpy (data, bitmap->buffer, stride * height);
}
format = CAIRO_FORMAT_A8;
} else {
/* if we get there, the data from the source bitmap
* really comes from _fill_xrender_bitmap, and is
* made of 32-bit ARGB or ABGR values */
assert (own_buffer != 0);
assert (bitmap->pixel_mode != FT_PIXEL_MODE_GRAY);
data = bitmap->buffer;
stride = bitmap->pitch;
format = CAIRO_FORMAT_ARGB32;
}
break;
case FT_PIXEL_MODE_GRAY2:
case FT_PIXEL_MODE_GRAY4:
/* These could be triggered by very rare types of TrueType fonts */
default:
if (own_buffer)
free (bitmap->buffer);
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
}
/* XXX */
*surface = image = (cairo_image_surface_t *)
cairo_image_surface_create_for_data (data,
format,
width, height, stride);
if (image->base.status) {
free (data);
return (*surface)->base.status;
}
if (format == CAIRO_FORMAT_ARGB32)
pixman_image_set_component_alpha (image->pixman_image, TRUE);
_cairo_image_surface_assume_ownership_of_data (image);
_cairo_debug_check_image_surface_is_defined (&image->base);
return CAIRO_STATUS_SUCCESS;
}
/* Converts an outline FT_GlyphSlot into an image
*
* This could go through _render_glyph_bitmap as well, letting
* FreeType convert the outline to a bitmap, but doing it ourselves
* has two minor advantages: first, we save a copy of the bitmap
* buffer: we can directly use the buffer that FreeType renders
* into.
*
* Second, it may help when we add support for subpixel
* rendering: the Xft code does it this way. (Keith thinks that
* it may also be possible to get the subpixel rendering with
* FT_Render_Glyph: something worth looking into in more detail
* when we add subpixel support. If so, we may want to eliminate
* this version of the code path entirely.
*/
static cairo_status_t
_render_glyph_outline (FT_Face face,
cairo_font_options_t *font_options,
cairo_image_surface_t **surface)
{
int rgba = FC_RGBA_UNKNOWN;
int lcd_filter = FT_LCD_FILTER_LEGACY;
FT_GlyphSlot glyphslot = face->glyph;
FT_Outline *outline = &glyphslot->outline;
FT_Bitmap bitmap;
FT_BBox cbox;
unsigned int width, height;
cairo_status_t status;
FT_Error fterror;
FT_Library library = glyphslot->library;
FT_Render_Mode render_mode = FT_RENDER_MODE_NORMAL;
switch (font_options->antialias) {
case CAIRO_ANTIALIAS_NONE:
render_mode = FT_RENDER_MODE_MONO;
break;
case CAIRO_ANTIALIAS_SUBPIXEL:
switch (font_options->subpixel_order) {
case CAIRO_SUBPIXEL_ORDER_DEFAULT:
case CAIRO_SUBPIXEL_ORDER_RGB:
case CAIRO_SUBPIXEL_ORDER_BGR:
render_mode = FT_RENDER_MODE_LCD;
break;
case CAIRO_SUBPIXEL_ORDER_VRGB:
case CAIRO_SUBPIXEL_ORDER_VBGR:
render_mode = FT_RENDER_MODE_LCD_V;
break;
}
switch (font_options->lcd_filter) {
case CAIRO_LCD_FILTER_NONE:
lcd_filter = FT_LCD_FILTER_NONE;
break;
case CAIRO_LCD_FILTER_DEFAULT:
case CAIRO_LCD_FILTER_INTRA_PIXEL:
lcd_filter = FT_LCD_FILTER_LEGACY;
break;
case CAIRO_LCD_FILTER_FIR3:
lcd_filter = FT_LCD_FILTER_LIGHT;
break;
case CAIRO_LCD_FILTER_FIR5:
lcd_filter = FT_LCD_FILTER_DEFAULT;
break;
}
break;
case CAIRO_ANTIALIAS_DEFAULT:
case CAIRO_ANTIALIAS_GRAY:
render_mode = FT_RENDER_MODE_NORMAL;
}
FT_Outline_Get_CBox (outline, &cbox);
cbox.xMin &= -64;
cbox.yMin &= -64;
cbox.xMax = (cbox.xMax + 63) & -64;
cbox.yMax = (cbox.yMax + 63) & -64;
width = (unsigned int) ((cbox.xMax - cbox.xMin) >> 6);
height = (unsigned int) ((cbox.yMax - cbox.yMin) >> 6);
if (width * height == 0) {
cairo_format_t format;
/* Looks like fb handles zero-sized images just fine */
switch (render_mode) {
case FT_RENDER_MODE_MONO:
format = CAIRO_FORMAT_A1;
break;
case FT_RENDER_MODE_LCD:
case FT_RENDER_MODE_LCD_V:
format= CAIRO_FORMAT_ARGB32;
break;
case FT_RENDER_MODE_LIGHT:
case FT_RENDER_MODE_NORMAL:
case FT_RENDER_MODE_MAX:
default:
format = CAIRO_FORMAT_A8;
break;
}
(*surface) = (cairo_image_surface_t *)
cairo_image_surface_create_for_data (NULL, format, 0, 0, 0);
if ((*surface)->base.status)
return (*surface)->base.status;
} else {
int bitmap_size;
switch (render_mode) {
case FT_RENDER_MODE_LCD:
if (font_options->subpixel_order == CAIRO_SUBPIXEL_ORDER_BGR) {
rgba = FC_RGBA_BGR;
} else {
rgba = FC_RGBA_RGB;
}
case FT_RENDER_MODE_LCD_V:
if (font_options->subpixel_order == CAIRO_SUBPIXEL_ORDER_VBGR) {
rgba = FC_RGBA_VBGR;
} else {
rgba = FC_RGBA_VRGB;
}
break;
case FT_RENDER_MODE_MONO:
case FT_RENDER_MODE_LIGHT:
case FT_RENDER_MODE_NORMAL:
case FT_RENDER_MODE_MAX:
default:
break;
}
#if HAVE_FT_LIBRARY_SETLCDFILTER
FT_Library_SetLcdFilter (library, lcd_filter);
#endif
fterror = FT_Render_Glyph (face->glyph, render_mode);
#if HAVE_FT_LIBRARY_SETLCDFILTER
FT_Library_SetLcdFilter (library, FT_LCD_FILTER_NONE);
#endif
if (fterror != 0)
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
bitmap_size = _compute_xrender_bitmap_size (&bitmap,
face->glyph,
render_mode);
if (bitmap_size < 0)
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
bitmap.buffer = calloc (1, bitmap_size);
if (bitmap.buffer == NULL)
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
_fill_xrender_bitmap (&bitmap, face->glyph, render_mode,
(rgba == FC_RGBA_BGR || rgba == FC_RGBA_VBGR));
/* Note:
* _get_bitmap_surface will free bitmap.buffer if there is an error
*/
status = _get_bitmap_surface (&bitmap, TRUE, font_options, surface);
if (unlikely (status))
return status;
/* Note: the font's coordinate system is upside down from ours, so the
* Y coordinate of the control box needs to be negated. Moreover, device
* offsets are position of glyph origin relative to top left while xMin
* and yMax are offsets of top left relative to origin. Another negation.
*/
cairo_surface_set_device_offset (&(*surface)->base,
(double)-glyphslot->bitmap_left,
(double)+glyphslot->bitmap_top);
}
return CAIRO_STATUS_SUCCESS;
}
/* Converts a bitmap (or other) FT_GlyphSlot into an image */
static cairo_status_t
_render_glyph_bitmap (FT_Face face,
cairo_font_options_t *font_options,
cairo_image_surface_t **surface)
{
FT_GlyphSlot glyphslot = face->glyph;
cairo_status_t status;
FT_Error error;
/* According to the FreeType docs, glyphslot->format could be
* something other than FT_GLYPH_FORMAT_OUTLINE or
* FT_GLYPH_FORMAT_BITMAP. Calling FT_Render_Glyph gives FreeType
* the opportunity to convert such to
* bitmap. FT_GLYPH_FORMAT_COMPOSITE will not be encountered since
* we avoid the FT_LOAD_NO_RECURSE flag.
*/
error = FT_Render_Glyph (glyphslot, FT_RENDER_MODE_NORMAL);
/* XXX ignoring all other errors for now. They are not fatal, typically
* just a glyph-not-found. */
if (error == FT_Err_Out_Of_Memory)
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
status = _get_bitmap_surface (&glyphslot->bitmap,
FALSE, font_options,
surface);
if (unlikely (status))
return status;
/*
* Note: the font's coordinate system is upside down from ours, so the
* Y coordinate of the control box needs to be negated. Moreover, device
* offsets are position of glyph origin relative to top left while
* bitmap_left and bitmap_top are offsets of top left relative to origin.
* Another negation.
*/
cairo_surface_set_device_offset (&(*surface)->base,
-glyphslot->bitmap_left,
+glyphslot->bitmap_top);
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_transform_glyph_bitmap (cairo_matrix_t * shape,
cairo_image_surface_t ** surface)
{
cairo_matrix_t original_to_transformed;
cairo_matrix_t transformed_to_original;
cairo_image_surface_t *old_image;
cairo_surface_t *image;
double x[4], y[4];
double origin_x, origin_y;
int orig_width, orig_height;
int i;
int x_min, y_min, x_max, y_max;
int width, height;
cairo_status_t status;
cairo_surface_pattern_t pattern;
/* We want to compute a transform that takes the origin
* (device_x_offset, device_y_offset) to 0,0, then applies
* the "shape" portion of the font transform
*/
original_to_transformed = *shape;
cairo_surface_get_device_offset (&(*surface)->base, &origin_x, &origin_y);
orig_width = (*surface)->width;
orig_height = (*surface)->height;
cairo_matrix_translate (&original_to_transformed,
-origin_x, -origin_y);
/* Find the bounding box of the original bitmap under that
* transform
*/
x[0] = 0; y[0] = 0;
x[1] = orig_width; y[1] = 0;
x[2] = orig_width; y[2] = orig_height;
x[3] = 0; y[3] = orig_height;
for (i = 0; i < 4; i++)
cairo_matrix_transform_point (&original_to_transformed,
&x[i], &y[i]);
x_min = floor (x[0]); y_min = floor (y[0]);
x_max = ceil (x[0]); y_max = ceil (y[0]);
for (i = 1; i < 4; i++) {
if (x[i] < x_min)
x_min = floor (x[i]);
else if (x[i] > x_max)
x_max = ceil (x[i]);
if (y[i] < y_min)
y_min = floor (y[i]);
else if (y[i] > y_max)
y_max = ceil (y[i]);
}
/* Adjust the transform so that the bounding box starts at 0,0 ...
* this gives our final transform from original bitmap to transformed
* bitmap.
*/
original_to_transformed.x0 -= x_min;
original_to_transformed.y0 -= y_min;
/* Create the transformed bitmap */
width = x_max - x_min;
height = y_max - y_min;
transformed_to_original = original_to_transformed;
status = cairo_matrix_invert (&transformed_to_original);
if (unlikely (status))
return status;
image = cairo_image_surface_create (CAIRO_FORMAT_A8, width, height);
if (unlikely (image->status))
return image->status;
/* Draw the original bitmap transformed into the new bitmap
*/
_cairo_pattern_init_for_surface (&pattern, &(*surface)->base);
cairo_pattern_set_matrix (&pattern.base, &transformed_to_original);
status = _cairo_surface_paint (image,
CAIRO_OPERATOR_SOURCE,
&pattern.base,
NULL);
_cairo_pattern_fini (&pattern.base);
if (unlikely (status)) {
cairo_surface_destroy (image);
return status;
}
/* Now update the cache entry for the new bitmap, recomputing
* the origin based on the final transform.
*/
cairo_matrix_transform_point (&original_to_transformed,
&origin_x, &origin_y);
old_image = (*surface);
(*surface) = (cairo_image_surface_t *)image;
cairo_surface_destroy (&old_image->base);
cairo_surface_set_device_offset (&(*surface)->base,
_cairo_lround (origin_x),
_cairo_lround (origin_y));
return CAIRO_STATUS_SUCCESS;
}
static const cairo_unscaled_font_backend_t cairo_ft_unscaled_font_backend = {
_cairo_ft_unscaled_font_destroy,
#if 0
_cairo_ft_unscaled_font_create_glyph
#endif
};
/* #cairo_ft_scaled_font_t */
typedef struct _cairo_ft_scaled_font {
cairo_scaled_font_t base;
cairo_ft_unscaled_font_t *unscaled;
cairo_ft_options_t ft_options;
} cairo_ft_scaled_font_t;
static const cairo_scaled_font_backend_t _cairo_ft_scaled_font_backend;
#if CAIRO_HAS_FC_FONT
/* The load flags passed to FT_Load_Glyph control aspects like hinting and
* antialiasing. Here we compute them from the fields of a FcPattern.
*/
static void
_get_pattern_ft_options (FcPattern *pattern, cairo_ft_options_t *ret)
{
FcBool antialias, vertical_layout, hinting, autohint, bitmap, embolden;
cairo_ft_options_t ft_options;
int rgba;
#ifdef FC_HINT_STYLE
int hintstyle;
#endif
_cairo_font_options_init_default (&ft_options.base);
ft_options.load_flags = FT_LOAD_DEFAULT;
ft_options.extra_flags = 0;
#ifndef FC_EMBEDDED_BITMAP
#define FC_EMBEDDED_BITMAP "embeddedbitmap"
#endif
/* Check whether to force use of embedded bitmaps */
if (FcPatternGetBool (pattern,
FC_EMBEDDED_BITMAP, 0, &bitmap) != FcResultMatch)
bitmap = FcFalse;
/* disable antialiasing if requested */
if (FcPatternGetBool (pattern,
FC_ANTIALIAS, 0, &antialias) != FcResultMatch)
antialias = FcTrue;
if (antialias) {
cairo_subpixel_order_t subpixel_order;
int lcd_filter;
/* disable hinting if requested */
if (FcPatternGetBool (pattern,
FC_HINTING, 0, &hinting) != FcResultMatch)
hinting = FcTrue;
if (FcPatternGetInteger (pattern,
FC_RGBA, 0, &rgba) != FcResultMatch)
rgba = FC_RGBA_UNKNOWN;
switch (rgba) {
case FC_RGBA_RGB:
subpixel_order = CAIRO_SUBPIXEL_ORDER_RGB;
break;
case FC_RGBA_BGR:
subpixel_order = CAIRO_SUBPIXEL_ORDER_BGR;
break;
case FC_RGBA_VRGB:
subpixel_order = CAIRO_SUBPIXEL_ORDER_VRGB;
break;
case FC_RGBA_VBGR:
subpixel_order = CAIRO_SUBPIXEL_ORDER_VBGR;
break;
case FC_RGBA_UNKNOWN:
case FC_RGBA_NONE:
default:
subpixel_order = CAIRO_SUBPIXEL_ORDER_DEFAULT;
break;
}
if (subpixel_order != CAIRO_SUBPIXEL_ORDER_DEFAULT) {
ft_options.base.subpixel_order = subpixel_order;
ft_options.base.antialias = CAIRO_ANTIALIAS_SUBPIXEL;
}
if (FcPatternGetInteger (pattern,
FC_LCD_FILTER, 0, &lcd_filter) == FcResultMatch)
{
switch (lcd_filter) {
case FC_LCD_NONE:
ft_options.base.lcd_filter = CAIRO_LCD_FILTER_NONE;
break;
case FC_LCD_DEFAULT:
ft_options.base.lcd_filter = CAIRO_LCD_FILTER_FIR5;
break;
case FC_LCD_LIGHT:
ft_options.base.lcd_filter = CAIRO_LCD_FILTER_FIR3;
break;
case FC_LCD_LEGACY:
ft_options.base.lcd_filter = CAIRO_LCD_FILTER_INTRA_PIXEL;
break;
}
}
#ifdef FC_HINT_STYLE
if (FcPatternGetInteger (pattern,
FC_HINT_STYLE, 0, &hintstyle) != FcResultMatch)
hintstyle = FC_HINT_FULL;
if (!hinting)
hintstyle = FC_HINT_NONE;
switch (hintstyle) {
case FC_HINT_NONE:
ft_options.base.hint_style = CAIRO_HINT_STYLE_NONE;
break;
case FC_HINT_SLIGHT:
ft_options.base.hint_style = CAIRO_HINT_STYLE_SLIGHT;
break;
case FC_HINT_MEDIUM:
default:
ft_options.base.hint_style = CAIRO_HINT_STYLE_MEDIUM;
break;
case FC_HINT_FULL:
ft_options.base.hint_style = CAIRO_HINT_STYLE_FULL;
break;
}
#else /* !FC_HINT_STYLE */
if (!hinting) {
ft_options.base.hint_style = CAIRO_HINT_STYLE_NONE;
}
#endif /* FC_HINT_STYLE */
/* Force embedded bitmaps off if no hinting requested */
if (ft_options.base.hint_style == CAIRO_HINT_STYLE_NONE)
bitmap = FcFalse;
if (!bitmap)
ft_options.load_flags |= FT_LOAD_NO_BITMAP;
} else {
ft_options.base.antialias = CAIRO_ANTIALIAS_NONE;
}
/* force autohinting if requested */
if (FcPatternGetBool (pattern,
FC_AUTOHINT, 0, &autohint) != FcResultMatch)
autohint = FcFalse;
if (autohint)
ft_options.load_flags |= FT_LOAD_FORCE_AUTOHINT;
if (FcPatternGetBool (pattern,
FC_VERTICAL_LAYOUT, 0, &vertical_layout) != FcResultMatch)
vertical_layout = FcFalse;
if (vertical_layout)
ft_options.load_flags |= FT_LOAD_VERTICAL_LAYOUT;
#ifndef FC_EMBOLDEN
#define FC_EMBOLDEN "embolden"
#endif
if (FcPatternGetBool (pattern,
FC_EMBOLDEN, 0, &embolden) != FcResultMatch)
embolden = FcFalse;
if (embolden)
ft_options.extra_flags |= CAIRO_FT_OPTIONS_EMBOLDEN;
*ret = ft_options;
}
#endif
static void
_cairo_ft_options_merge (cairo_ft_options_t *options,
cairo_ft_options_t *other)
{
int load_flags = other->load_flags;
int load_target = FT_LOAD_TARGET_NORMAL;
/* clear load target mode */
load_flags &= ~(FT_LOAD_TARGET_(FT_LOAD_TARGET_MODE(other->load_flags)));
if (load_flags & FT_LOAD_NO_HINTING)
other->base.hint_style = CAIRO_HINT_STYLE_NONE;
if (other->base.antialias == CAIRO_ANTIALIAS_NONE ||
options->base.antialias == CAIRO_ANTIALIAS_NONE) {
options->base.antialias = CAIRO_ANTIALIAS_NONE;
options->base.subpixel_order = CAIRO_SUBPIXEL_ORDER_DEFAULT;
}
if (other->base.antialias == CAIRO_ANTIALIAS_SUBPIXEL &&
(options->base.antialias == CAIRO_ANTIALIAS_DEFAULT ||
options->base.antialias == CAIRO_ANTIALIAS_GRAY)) {
options->base.antialias = CAIRO_ANTIALIAS_SUBPIXEL;
options->base.subpixel_order = other->base.subpixel_order;
}
if (options->base.hint_style == CAIRO_HINT_STYLE_DEFAULT)
options->base.hint_style = other->base.hint_style;
if (other->base.hint_style == CAIRO_HINT_STYLE_NONE)
options->base.hint_style = CAIRO_HINT_STYLE_NONE;
if (options->base.lcd_filter == CAIRO_LCD_FILTER_DEFAULT)
options->base.lcd_filter = other->base.lcd_filter;
if (other->base.lcd_filter == CAIRO_LCD_FILTER_NONE)
options->base.lcd_filter = CAIRO_LCD_FILTER_NONE;
if (options->base.antialias == CAIRO_ANTIALIAS_NONE) {
if (options->base.hint_style == CAIRO_HINT_STYLE_NONE)
load_flags |= FT_LOAD_NO_HINTING;
else
load_target = FT_LOAD_TARGET_MONO;
load_flags |= FT_LOAD_MONOCHROME;
} else {
switch (options->base.hint_style) {
case CAIRO_HINT_STYLE_NONE:
load_flags |= FT_LOAD_NO_HINTING;
break;
case CAIRO_HINT_STYLE_SLIGHT:
load_target = FT_LOAD_TARGET_LIGHT;
break;
case CAIRO_HINT_STYLE_MEDIUM:
break;
case CAIRO_HINT_STYLE_FULL:
case CAIRO_HINT_STYLE_DEFAULT:
if (options->base.antialias == CAIRO_ANTIALIAS_SUBPIXEL) {
switch (options->base.subpixel_order) {
case CAIRO_SUBPIXEL_ORDER_DEFAULT:
case CAIRO_SUBPIXEL_ORDER_RGB:
case CAIRO_SUBPIXEL_ORDER_BGR:
load_target = FT_LOAD_TARGET_LCD;
break;
case CAIRO_SUBPIXEL_ORDER_VRGB:
case CAIRO_SUBPIXEL_ORDER_VBGR:
load_target = FT_LOAD_TARGET_LCD_V;
break;
}
}
break;
}
}
options->load_flags = load_flags | load_target;
options->extra_flags = other->extra_flags;
if (options->base.hint_metrics != CAIRO_HINT_METRICS_OFF)
options->extra_flags |= CAIRO_FT_OPTIONS_HINT_METRICS;
}
static cairo_status_t
_cairo_ft_font_face_scaled_font_create (void *abstract_font_face,
const cairo_matrix_t *font_matrix,
const cairo_matrix_t *ctm,
const cairo_font_options_t *options,
cairo_scaled_font_t **font_out)
{
cairo_ft_font_face_t *font_face = abstract_font_face;
cairo_ft_scaled_font_t *scaled_font;
FT_Face face;
FT_Size_Metrics *metrics;
cairo_font_extents_t fs_metrics;
cairo_status_t status;
cairo_ft_unscaled_font_t *unscaled;
assert (font_face->unscaled);
face = _cairo_ft_unscaled_font_lock_face (font_face->unscaled);
if (unlikely (face == NULL)) /* backend error */
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
scaled_font = malloc (sizeof (cairo_ft_scaled_font_t));
if (unlikely (scaled_font == NULL)) {
status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
goto FAIL;
}
scaled_font->unscaled = unscaled = font_face->unscaled;
_cairo_unscaled_font_reference (&unscaled->base);
_cairo_font_options_init_copy (&scaled_font->ft_options.base, options);
_cairo_ft_options_merge (&scaled_font->ft_options, &font_face->ft_options);
status = _cairo_scaled_font_init (&scaled_font->base,
&font_face->base,
font_matrix, ctm, options,
&_cairo_ft_scaled_font_backend);
if (unlikely (status))
goto CLEANUP_SCALED_FONT;
status = _cairo_ft_unscaled_font_set_scale (unscaled,
&scaled_font->base.scale);
if (unlikely (status)) {
/* This can only fail if we encounter an error with the underlying
* font, so propagate the error back to the font-face. */
_cairo_ft_unscaled_font_unlock_face (unscaled);
_cairo_unscaled_font_destroy (&unscaled->base);
free (scaled_font);
return status;
}
metrics = &face->size->metrics;
/*
* Get to unscaled metrics so that the upper level can get back to
* user space
*
* Also use this path for bitmap-only fonts. The other branch uses
* face members that are only relevant for scalable fonts. This is
* detected by simply checking for units_per_EM==0.
*/
if (scaled_font->base.options.hint_metrics != CAIRO_HINT_METRICS_OFF ||
face->units_per_EM == 0) {
double x_factor, y_factor;
if (unscaled->x_scale == 0)
x_factor = 0;
else
x_factor = 1 / unscaled->x_scale;
if (unscaled->y_scale == 0)
y_factor = 0;
else
y_factor = 1 / unscaled->y_scale;
fs_metrics.ascent = DOUBLE_FROM_26_6(metrics->ascender) * y_factor;
fs_metrics.descent = DOUBLE_FROM_26_6(- metrics->descender) * y_factor;
fs_metrics.height = DOUBLE_FROM_26_6(metrics->height) * y_factor;
if (!_cairo_ft_scaled_font_is_vertical (&scaled_font->base)) {
fs_metrics.max_x_advance = DOUBLE_FROM_26_6(metrics->max_advance) * x_factor;
fs_metrics.max_y_advance = 0;
} else {
fs_metrics.max_x_advance = 0;
fs_metrics.max_y_advance = DOUBLE_FROM_26_6(metrics->max_advance) * y_factor;
}
} else {
double scale = face->units_per_EM;
fs_metrics.ascent = face->ascender / scale;
fs_metrics.descent = - face->descender / scale;
fs_metrics.height = face->height / scale;
if (!_cairo_ft_scaled_font_is_vertical (&scaled_font->base)) {
fs_metrics.max_x_advance = face->max_advance_width / scale;
fs_metrics.max_y_advance = 0;
} else {
fs_metrics.max_x_advance = 0;
fs_metrics.max_y_advance = face->max_advance_height / scale;
}
}
status = _cairo_scaled_font_set_metrics (&scaled_font->base, &fs_metrics);
if (unlikely (status))
goto CLEANUP_SCALED_FONT;
_cairo_ft_unscaled_font_unlock_face (unscaled);
*font_out = &scaled_font->base;
return CAIRO_STATUS_SUCCESS;
CLEANUP_SCALED_FONT:
_cairo_unscaled_font_destroy (&unscaled->base);
free (scaled_font);
FAIL:
_cairo_ft_unscaled_font_unlock_face (font_face->unscaled);
*font_out = _cairo_scaled_font_create_in_error (status);
return CAIRO_STATUS_SUCCESS; /* non-backend error */
}
cairo_bool_t
_cairo_scaled_font_is_ft (cairo_scaled_font_t *scaled_font)
{
return scaled_font->backend == &_cairo_ft_scaled_font_backend;
}
static void
_cairo_ft_scaled_font_fini (void *abstract_font)
{
cairo_ft_scaled_font_t *scaled_font = abstract_font;
if (scaled_font == NULL)
return;
_cairo_unscaled_font_destroy (&scaled_font->unscaled->base);
}
static int
_move_to (FT_Vector *to, void *closure)
{
cairo_path_fixed_t *path = closure;
cairo_fixed_t x, y;
x = _cairo_fixed_from_26_6 (to->x);
y = _cairo_fixed_from_26_6 (to->y);
if (_cairo_path_fixed_close_path (path) != CAIRO_STATUS_SUCCESS)
return 1;
if (_cairo_path_fixed_move_to (path, x, y) != CAIRO_STATUS_SUCCESS)
return 1;
return 0;
}
static int
_line_to (FT_Vector *to, void *closure)
{
cairo_path_fixed_t *path = closure;
cairo_fixed_t x, y;
x = _cairo_fixed_from_26_6 (to->x);
y = _cairo_fixed_from_26_6 (to->y);
if (_cairo_path_fixed_line_to (path, x, y) != CAIRO_STATUS_SUCCESS)
return 1;
return 0;
}
static int
_conic_to (FT_Vector *control, FT_Vector *to, void *closure)
{
cairo_path_fixed_t *path = closure;
cairo_fixed_t x0, y0;
cairo_fixed_t x1, y1;
cairo_fixed_t x2, y2;
cairo_fixed_t x3, y3;
cairo_point_t conic;
if (! _cairo_path_fixed_get_current_point (path, &x0, &y0))
return 1;
conic.x = _cairo_fixed_from_26_6 (control->x);
conic.y = _cairo_fixed_from_26_6 (control->y);
x3 = _cairo_fixed_from_26_6 (to->x);
y3 = _cairo_fixed_from_26_6 (to->y);
x1 = x0 + 2.0/3.0 * (conic.x - x0);
y1 = y0 + 2.0/3.0 * (conic.y - y0);
x2 = x3 + 2.0/3.0 * (conic.x - x3);
y2 = y3 + 2.0/3.0 * (conic.y - y3);
if (_cairo_path_fixed_curve_to (path,
x1, y1,
x2, y2,
x3, y3) != CAIRO_STATUS_SUCCESS)
return 1;
return 0;
}
static int
_cubic_to (FT_Vector *control1, FT_Vector *control2,
FT_Vector *to, void *closure)
{
cairo_path_fixed_t *path = closure;
cairo_fixed_t x0, y0;
cairo_fixed_t x1, y1;
cairo_fixed_t x2, y2;
x0 = _cairo_fixed_from_26_6 (control1->x);
y0 = _cairo_fixed_from_26_6 (control1->y);
x1 = _cairo_fixed_from_26_6 (control2->x);
y1 = _cairo_fixed_from_26_6 (control2->y);
x2 = _cairo_fixed_from_26_6 (to->x);
y2 = _cairo_fixed_from_26_6 (to->y);
if (_cairo_path_fixed_curve_to (path,
x0, y0,
x1, y1,
x2, y2) != CAIRO_STATUS_SUCCESS)
return 1;
return 0;
}
static cairo_status_t
_decompose_glyph_outline (FT_Face face,
cairo_font_options_t *options,
cairo_path_fixed_t **pathp)
{
static const FT_Outline_Funcs outline_funcs = {
(FT_Outline_MoveToFunc)_move_to,
(FT_Outline_LineToFunc)_line_to,
(FT_Outline_ConicToFunc)_conic_to,
(FT_Outline_CubicToFunc)_cubic_to,
0, /* shift */
0, /* delta */
};
static const FT_Matrix invert_y = {
DOUBLE_TO_16_16 (1.0), 0,
0, DOUBLE_TO_16_16 (-1.0),
};
FT_GlyphSlot glyph;
cairo_path_fixed_t *path;
cairo_status_t status;
path = _cairo_path_fixed_create ();
if (!path)
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
glyph = face->glyph;
/* Font glyphs have an inverted Y axis compared to cairo. */
FT_Outline_Transform (&glyph->outline, &invert_y);
if (FT_Outline_Decompose (&glyph->outline, &outline_funcs, path)) {
_cairo_path_fixed_destroy (path);
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
}
status = _cairo_path_fixed_close_path (path);
if (unlikely (status)) {
_cairo_path_fixed_destroy (path);
return status;
}
*pathp = path;
return CAIRO_STATUS_SUCCESS;
}
/*
* Translate glyph to match its metrics.
*/
static void
_cairo_ft_scaled_glyph_vertical_layout_bearing_fix (void *abstract_font,
FT_GlyphSlot glyph)
{
cairo_ft_scaled_font_t *scaled_font = abstract_font;
FT_Vector vector;
vector.x = glyph->metrics.vertBearingX - glyph->metrics.horiBearingX;
vector.y = -glyph->metrics.vertBearingY - glyph->metrics.horiBearingY;
if (glyph->format == FT_GLYPH_FORMAT_OUTLINE) {
FT_Vector_Transform (&vector, &scaled_font->unscaled->Current_Shape);
FT_Outline_Translate(&glyph->outline, vector.x, vector.y);
} else if (glyph->format == FT_GLYPH_FORMAT_BITMAP) {
glyph->bitmap_left += vector.x / 64;
glyph->bitmap_top += vector.y / 64;
}
}
static cairo_int_status_t
_cairo_ft_scaled_glyph_init (void *abstract_font,
cairo_scaled_glyph_t *scaled_glyph,
cairo_scaled_glyph_info_t info)
{
cairo_text_extents_t fs_metrics;
cairo_ft_scaled_font_t *scaled_font = abstract_font;
cairo_ft_unscaled_font_t *unscaled = scaled_font->unscaled;
FT_GlyphSlot glyph;
FT_Face face;
FT_Error error;
int load_flags = scaled_font->ft_options.load_flags;
FT_Glyph_Metrics *metrics;
double x_factor, y_factor;
cairo_bool_t vertical_layout = FALSE;
cairo_status_t status;
face = _cairo_ft_unscaled_font_lock_face (unscaled);
if (!face)
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
status = _cairo_ft_unscaled_font_set_scale (scaled_font->unscaled,
&scaled_font->base.scale);
if (unlikely (status))
goto FAIL;
/* Ignore global advance unconditionally */
load_flags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
if ((info & CAIRO_SCALED_GLYPH_INFO_PATH) != 0 &&
(info & CAIRO_SCALED_GLYPH_INFO_SURFACE) == 0)
load_flags |= FT_LOAD_NO_BITMAP;
/*
* Don't pass FT_LOAD_VERTICAL_LAYOUT to FT_Load_Glyph here as
* suggested by freetype people.
*/
if (load_flags & FT_LOAD_VERTICAL_LAYOUT) {
load_flags &= ~FT_LOAD_VERTICAL_LAYOUT;
vertical_layout = TRUE;
}
error = FT_Load_Glyph (scaled_font->unscaled->face,
_cairo_scaled_glyph_index(scaled_glyph),
load_flags);
/* XXX ignoring all other errors for now. They are not fatal, typically
* just a glyph-not-found. */
if (error == FT_Err_Out_Of_Memory) {
status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
goto FAIL;
}
glyph = face->glyph;
#if HAVE_FT_GLYPHSLOT_EMBOLDEN
/*
* embolden glyphs if requested
*/
if (scaled_font->ft_options.extra_flags & CAIRO_FT_OPTIONS_EMBOLDEN)
FT_GlyphSlot_Embolden (glyph);
#endif
if (vertical_layout)
_cairo_ft_scaled_glyph_vertical_layout_bearing_fix (scaled_font, glyph);
if (info & CAIRO_SCALED_GLYPH_INFO_METRICS) {
cairo_bool_t hint_metrics = scaled_font->base.options.hint_metrics != CAIRO_HINT_METRICS_OFF;
/*
* Compute font-space metrics
*/
metrics = &glyph->metrics;
if (unscaled->x_scale == 0)
x_factor = 0;
else
x_factor = 1 / unscaled->x_scale;
if (unscaled->y_scale == 0)
y_factor = 0;
else
y_factor = 1 / unscaled->y_scale;
/*
* Note: Y coordinates of the horizontal bearing need to be negated.
*
* Scale metrics back to glyph space from the scaled glyph space returned
* by FreeType
*
* If we want hinted metrics but aren't asking for hinted glyphs from
* FreeType, then we need to do the metric hinting ourselves.
*/
if (hint_metrics && (load_flags & FT_LOAD_NO_HINTING))
{
FT_Pos x1, x2;
FT_Pos y1, y2;
FT_Pos advance;
if (!vertical_layout) {
x1 = (metrics->horiBearingX) & -64;
x2 = (metrics->horiBearingX + metrics->width + 63) & -64;
y1 = (-metrics->horiBearingY) & -64;
y2 = (-metrics->horiBearingY + metrics->height + 63) & -64;
advance = ((metrics->horiAdvance + 32) & -64);
fs_metrics.x_bearing = DOUBLE_FROM_26_6 (x1) * x_factor;
fs_metrics.y_bearing = DOUBLE_FROM_26_6 (y1) * y_factor;
fs_metrics.width = DOUBLE_FROM_26_6 (x2 - x1) * x_factor;
fs_metrics.height = DOUBLE_FROM_26_6 (y2 - y1) * y_factor;
fs_metrics.x_advance = DOUBLE_FROM_26_6 (advance) * x_factor;
fs_metrics.y_advance = 0;
} else {
x1 = (metrics->vertBearingX) & -64;
x2 = (metrics->vertBearingX + metrics->width + 63) & -64;
y1 = (metrics->vertBearingY) & -64;
y2 = (metrics->vertBearingY + metrics->height + 63) & -64;
advance = ((metrics->vertAdvance + 32) & -64);
fs_metrics.x_bearing = DOUBLE_FROM_26_6 (x1) * x_factor;
fs_metrics.y_bearing = DOUBLE_FROM_26_6 (y1) * y_factor;
fs_metrics.width = DOUBLE_FROM_26_6 (x2 - x1) * x_factor;
fs_metrics.height = DOUBLE_FROM_26_6 (y2 - y1) * y_factor;
fs_metrics.x_advance = 0;
fs_metrics.y_advance = DOUBLE_FROM_26_6 (advance) * y_factor;
}
} else {
fs_metrics.width = DOUBLE_FROM_26_6 (metrics->width) * x_factor;
fs_metrics.height = DOUBLE_FROM_26_6 (metrics->height) * y_factor;
if (!vertical_layout) {
fs_metrics.x_bearing = DOUBLE_FROM_26_6 (metrics->horiBearingX) * x_factor;
fs_metrics.y_bearing = DOUBLE_FROM_26_6 (-metrics->horiBearingY) * y_factor;
if (hint_metrics || glyph->format != FT_GLYPH_FORMAT_OUTLINE)
fs_metrics.x_advance = DOUBLE_FROM_26_6 (metrics->horiAdvance) * x_factor;
else
fs_metrics.x_advance = DOUBLE_FROM_16_16 (glyph->linearHoriAdvance) * x_factor;
fs_metrics.y_advance = 0 * y_factor;
} else {
fs_metrics.x_bearing = DOUBLE_FROM_26_6 (metrics->vertBearingX) * x_factor;
fs_metrics.y_bearing = DOUBLE_FROM_26_6 (metrics->vertBearingY) * y_factor;
fs_metrics.x_advance = 0 * x_factor;
if (hint_metrics || glyph->format != FT_GLYPH_FORMAT_OUTLINE)
fs_metrics.y_advance = DOUBLE_FROM_26_6 (metrics->vertAdvance) * y_factor;
else
fs_metrics.y_advance = DOUBLE_FROM_16_16 (glyph->linearVertAdvance) * y_factor;
}
}
_cairo_scaled_glyph_set_metrics (scaled_glyph,
&scaled_font->base,
&fs_metrics);
}
if ((info & CAIRO_SCALED_GLYPH_INFO_SURFACE) != 0) {
cairo_image_surface_t *surface;
if (glyph->format == FT_GLYPH_FORMAT_OUTLINE) {
status = _render_glyph_outline (face, &scaled_font->ft_options.base,
&surface);
} else {
status = _render_glyph_bitmap (face, &scaled_font->ft_options.base,
&surface);
if (likely (status == CAIRO_STATUS_SUCCESS) &&
unscaled->have_shape)
{
status = _transform_glyph_bitmap (&unscaled->current_shape,
&surface);
if (unlikely (status))
cairo_surface_destroy (&surface->base);
}
}
if (unlikely (status))
goto FAIL;
_cairo_scaled_glyph_set_surface (scaled_glyph,
&scaled_font->base,
surface);
}
if (info & CAIRO_SCALED_GLYPH_INFO_PATH) {
cairo_path_fixed_t *path = NULL; /* hide compiler warning */
/*
* A kludge -- the above code will trash the outline,
* so reload it. This will probably never occur though
*/
if ((info & CAIRO_SCALED_GLYPH_INFO_SURFACE) != 0) {
error = FT_Load_Glyph (face,
_cairo_scaled_glyph_index(scaled_glyph),
load_flags | FT_LOAD_NO_BITMAP);
/* XXX ignoring all other errors for now. They are not fatal, typically
* just a glyph-not-found. */
if (error == FT_Err_Out_Of_Memory) {
status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
goto FAIL;
}
#if HAVE_FT_GLYPHSLOT_EMBOLDEN
/*
* embolden glyphs if requested
*/
if (scaled_font->ft_options.extra_flags & CAIRO_FT_OPTIONS_EMBOLDEN)
FT_GlyphSlot_Embolden (glyph);
#endif
if (vertical_layout)
_cairo_ft_scaled_glyph_vertical_layout_bearing_fix (scaled_font, glyph);
}
if (glyph->format == FT_GLYPH_FORMAT_OUTLINE)
status = _decompose_glyph_outline (face, &scaled_font->ft_options.base,
&path);
else
status = CAIRO_INT_STATUS_UNSUPPORTED;
if (unlikely (status))
goto FAIL;
_cairo_scaled_glyph_set_path (scaled_glyph,
&scaled_font->base,
path);
}
FAIL:
_cairo_ft_unscaled_font_unlock_face (unscaled);
return status;
}
static unsigned long
_cairo_ft_ucs4_to_index (void *abstract_font,
uint32_t ucs4)
{
cairo_ft_scaled_font_t *scaled_font = abstract_font;
cairo_ft_unscaled_font_t *unscaled = scaled_font->unscaled;
FT_Face face;
FT_UInt index;
face = _cairo_ft_unscaled_font_lock_face (unscaled);
if (!face)
return 0;
#if CAIRO_HAS_FC_FONT
index = FcFreeTypeCharIndex (face, ucs4);
#else
index = FT_Get_Char_Index (face, ucs4);
#endif
_cairo_ft_unscaled_font_unlock_face (unscaled);
return index;
}
static cairo_int_status_t
_cairo_ft_load_truetype_table (void *abstract_font,
unsigned long tag,
long offset,
unsigned char *buffer,
unsigned long *length)
{
cairo_ft_scaled_font_t *scaled_font = abstract_font;
cairo_ft_unscaled_font_t *unscaled = scaled_font->unscaled;
FT_Face face;
cairo_status_t status = CAIRO_INT_STATUS_UNSUPPORTED;
if (_cairo_ft_scaled_font_is_vertical (&scaled_font->base))
return CAIRO_INT_STATUS_UNSUPPORTED;
#if HAVE_FT_LOAD_SFNT_TABLE
face = _cairo_ft_unscaled_font_lock_face (unscaled);
if (!face)
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
if (FT_IS_SFNT (face) &&
FT_Load_Sfnt_Table (face, tag, offset, buffer, length) == 0)
status = CAIRO_STATUS_SUCCESS;
_cairo_ft_unscaled_font_unlock_face (unscaled);
#endif
return status;
}
static cairo_int_status_t
_cairo_ft_index_to_ucs4(void *abstract_font,
unsigned long index,
uint32_t *ucs4)
{
cairo_ft_scaled_font_t *scaled_font = abstract_font;
cairo_ft_unscaled_font_t *unscaled = scaled_font->unscaled;
FT_Face face;
FT_ULong charcode;
FT_UInt gindex;
face = _cairo_ft_unscaled_font_lock_face (unscaled);
if (!face)
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
*ucs4 = (uint32_t) -1;
charcode = FT_Get_First_Char(face, &gindex);
while (gindex != 0) {
if (gindex == index) {
*ucs4 = charcode;
break;
}
charcode = FT_Get_Next_Char (face, charcode, &gindex);
}
_cairo_ft_unscaled_font_unlock_face (unscaled);
return CAIRO_STATUS_SUCCESS;
}
static const cairo_scaled_font_backend_t _cairo_ft_scaled_font_backend = {
CAIRO_FONT_TYPE_FT,
_cairo_ft_scaled_font_fini,
_cairo_ft_scaled_glyph_init,
NULL, /* text_to_glyphs */
_cairo_ft_ucs4_to_index,
NULL, /* show_glyphs */
_cairo_ft_load_truetype_table,
_cairo_ft_index_to_ucs4
};
/* #cairo_ft_font_face_t */
#if CAIRO_HAS_FC_FONT
static cairo_status_t
_cairo_ft_font_face_create_for_pattern (FcPattern *pattern,
cairo_font_face_t **out);
static cairo_status_t
_cairo_ft_font_face_create_for_toy (cairo_toy_font_face_t *toy_face,
cairo_font_face_t **font_face)
{
FcPattern *pattern;
int fcslant;
int fcweight;
cairo_status_t status = CAIRO_STATUS_SUCCESS;
pattern = FcPatternCreate ();
if (!pattern)
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
if (!FcPatternAddString (pattern,
FC_FAMILY, (unsigned char *) toy_face->family))
{
status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
goto FREE_PATTERN;
}
switch (toy_face->slant)
{
case CAIRO_FONT_SLANT_ITALIC:
fcslant = FC_SLANT_ITALIC;
break;
case CAIRO_FONT_SLANT_OBLIQUE:
fcslant = FC_SLANT_OBLIQUE;
break;
case CAIRO_FONT_SLANT_NORMAL:
default:
fcslant = FC_SLANT_ROMAN;
break;
}
if (!FcPatternAddInteger (pattern, FC_SLANT, fcslant)) {
status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
goto FREE_PATTERN;
}
switch (toy_face->weight)
{
case CAIRO_FONT_WEIGHT_BOLD:
fcweight = FC_WEIGHT_BOLD;
break;
case CAIRO_FONT_WEIGHT_NORMAL:
default:
fcweight = FC_WEIGHT_MEDIUM;
break;
}
if (!FcPatternAddInteger (pattern, FC_WEIGHT, fcweight)) {
status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
goto FREE_PATTERN;
}
status = _cairo_ft_font_face_create_for_pattern (pattern, font_face);
FREE_PATTERN:
FcPatternDestroy (pattern);
return status;
}
#endif
static void
_cairo_ft_font_face_destroy (void *abstract_face)
{
cairo_ft_font_face_t *font_face = abstract_face;
/* When destroying a face created by cairo_ft_font_face_create_for_ft_face,
* we have a special "zombie" state for the face when the unscaled font
* is still alive but there are no other references to a font face with
* the same FT_Face.
*
* We go from:
*
* font_face ------> unscaled
* <-....weak....../
*
* To:
*
* font_face <------- unscaled
*/
if (font_face->unscaled &&
font_face->unscaled->from_face &&
font_face->next == NULL &&
font_face->unscaled->faces == font_face &&
CAIRO_REFERENCE_COUNT_GET_VALUE (&font_face->unscaled->base.ref_count) > 1)
{
cairo_font_face_reference (&font_face->base);
_cairo_unscaled_font_destroy (&font_face->unscaled->base);
font_face->unscaled = NULL;
return;
}
if (font_face->unscaled) {
cairo_ft_font_face_t *tmp_face = NULL;
cairo_ft_font_face_t *last_face = NULL;
/* Remove face from linked list */
for (tmp_face = font_face->unscaled->faces;
tmp_face;
tmp_face = tmp_face->next)
{
if (tmp_face == font_face) {
if (last_face)
last_face->next = tmp_face->next;
else
font_face->unscaled->faces = tmp_face->next;
}
last_face = tmp_face;
}
_cairo_unscaled_font_destroy (&font_face->unscaled->base);
font_face->unscaled = NULL;
}
#if CAIRO_HAS_FC_FONT
if (font_face->pattern) {
FcPatternDestroy (font_face->pattern);
cairo_font_face_destroy (font_face->resolved_font_face);
}
#endif
}
static cairo_font_face_t *
_cairo_ft_font_face_get_implementation (void *abstract_face,
const cairo_matrix_t *font_matrix,
const cairo_matrix_t *ctm,
const cairo_font_options_t *options)
{
cairo_ft_font_face_t *font_face = abstract_face;
/* The handling of font options is different depending on how the
* font face was created. When the user creates a font face with
* cairo_ft_font_face_create_for_ft_face(), then the load flags
* passed in augment the load flags for the options. But for
* cairo_ft_font_face_create_for_pattern(), the load flags are
* derived from a pattern where the user has called
* cairo_ft_font_options_substitute(), so *just* use those load
* flags and ignore the options.
*/
#if CAIRO_HAS_FC_FONT
/* If we have an unresolved pattern, resolve it and create
* unscaled font. Otherwise, use the ones stored in font_face.
*/
if (font_face->pattern) {
cairo_font_face_t *resolved;
/* Cache the resolved font whilst the FcConfig remains consistent. */
resolved = font_face->resolved_font_face;
if (resolved != NULL) {
if (! FcInitBringUptoDate ()) {
_cairo_error_throw (CAIRO_STATUS_NO_MEMORY);
return (cairo_font_face_t *) &_cairo_font_face_nil;
}
if (font_face->resolved_config == FcConfigGetCurrent ())
return cairo_font_face_reference (resolved);
cairo_font_face_destroy (resolved);
font_face->resolved_font_face = NULL;
}
resolved = _cairo_ft_resolve_pattern (font_face->pattern,
font_matrix,
ctm,
options);
if (unlikely (resolved->status))
return resolved;
font_face->resolved_font_face = cairo_font_face_reference (resolved);
font_face->resolved_config = FcConfigGetCurrent ();
return resolved;
}
#endif
return abstract_face;
}
const cairo_font_face_backend_t _cairo_ft_font_face_backend = {
CAIRO_FONT_TYPE_FT,
#if CAIRO_HAS_FC_FONT
_cairo_ft_font_face_create_for_toy,
#else
NULL,
#endif
_cairo_ft_font_face_destroy,
_cairo_ft_font_face_scaled_font_create,
_cairo_ft_font_face_get_implementation
};
#if CAIRO_HAS_FC_FONT
static cairo_status_t
_cairo_ft_font_face_create_for_pattern (FcPattern *pattern,
cairo_font_face_t **out)
{
cairo_ft_font_face_t *font_face;
font_face = malloc (sizeof (cairo_ft_font_face_t));
if (unlikely (font_face == NULL))
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
font_face->unscaled = NULL;
font_face->next = NULL;
font_face->pattern = FcPatternDuplicate (pattern);
if (unlikely (font_face->pattern == NULL)) {
free (font_face);
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
}
font_face->resolved_font_face = NULL;
font_face->resolved_config = NULL;
_cairo_font_face_init (&font_face->base, &_cairo_ft_font_face_backend);
*out = &font_face->base;
return CAIRO_STATUS_SUCCESS;
}
#endif
static cairo_font_face_t *
_cairo_ft_font_face_create (cairo_ft_unscaled_font_t *unscaled,
cairo_ft_options_t *ft_options)
{
cairo_ft_font_face_t *font_face, **prev_font_face;
/* Looked for an existing matching font face */
for (font_face = unscaled->faces, prev_font_face = &unscaled->faces;
font_face;
prev_font_face = &font_face->next, font_face = font_face->next)
{
if (font_face->ft_options.load_flags == ft_options->load_flags &&
font_face->ft_options.extra_flags == ft_options->extra_flags &&
cairo_font_options_equal (&font_face->ft_options.base, &ft_options->base))
{
if (font_face->base.status) {
/* The font_face has been left in an error state, abandon it. */
*prev_font_face = font_face->next;
break;
}
if (font_face->unscaled == NULL) {
/* Resurrect this "zombie" font_face (from
* _cairo_ft_font_face_destroy), switching its unscaled_font
* from owner to ownee. */
font_face->unscaled = unscaled;
_cairo_unscaled_font_reference (&unscaled->base);
return &font_face->base;
} else
return cairo_font_face_reference (&font_face->base);
}
}
/* No match found, create a new one */
font_face = malloc (sizeof (cairo_ft_font_face_t));
if (unlikely (!font_face)) {
_cairo_error_throw (CAIRO_STATUS_NO_MEMORY);
return (cairo_font_face_t *)&_cairo_font_face_nil;
}
font_face->unscaled = unscaled;
_cairo_unscaled_font_reference (&unscaled->base);
font_face->ft_options = *ft_options;
if (unscaled->faces && unscaled->faces->unscaled == NULL) {
/* This "zombie" font_face (from _cairo_ft_font_face_destroy)
* is no longer needed. */
assert (unscaled->from_face && unscaled->faces->next == NULL);
cairo_font_face_destroy (&unscaled->faces->base);
unscaled->faces = NULL;
}
font_face->next = unscaled->faces;
unscaled->faces = font_face;
#if CAIRO_HAS_FC_FONT
font_face->pattern = NULL;
#endif
_cairo_font_face_init (&font_face->base, &_cairo_ft_font_face_backend);
return &font_face->base;
}
/* implement the platform-specific interface */
#if CAIRO_HAS_FC_FONT
static cairo_status_t
_cairo_ft_font_options_substitute (const cairo_font_options_t *options,
FcPattern *pattern)
{
FcValue v;
if (options->antialias != CAIRO_ANTIALIAS_DEFAULT)
{
if (FcPatternGet (pattern, FC_ANTIALIAS, 0, &v) == FcResultNoMatch)
{
if (! FcPatternAddBool (pattern,
FC_ANTIALIAS,
options->antialias != CAIRO_ANTIALIAS_NONE))
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
if (options->antialias != CAIRO_ANTIALIAS_SUBPIXEL) {
FcPatternDel (pattern, FC_RGBA);
if (! FcPatternAddInteger (pattern, FC_RGBA, FC_RGBA_NONE))
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
}
}
}
if (options->antialias != CAIRO_ANTIALIAS_DEFAULT)
{
if (FcPatternGet (pattern, FC_RGBA, 0, &v) == FcResultNoMatch)
{
int rgba;
if (options->antialias == CAIRO_ANTIALIAS_SUBPIXEL) {
switch (options->subpixel_order) {
case CAIRO_SUBPIXEL_ORDER_DEFAULT:
case CAIRO_SUBPIXEL_ORDER_RGB:
default:
rgba = FC_RGBA_RGB;
break;
case CAIRO_SUBPIXEL_ORDER_BGR:
rgba = FC_RGBA_BGR;
break;
case CAIRO_SUBPIXEL_ORDER_VRGB:
rgba = FC_RGBA_VRGB;
break;
case CAIRO_SUBPIXEL_ORDER_VBGR:
rgba = FC_RGBA_VBGR;
break;
}
} else {
rgba = FC_RGBA_NONE;
}
if (! FcPatternAddInteger (pattern, FC_RGBA, rgba))
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
}
}
if (options->lcd_filter != CAIRO_LCD_FILTER_DEFAULT)
{
if (FcPatternGet (pattern, FC_LCD_FILTER, 0, &v) == FcResultNoMatch)
{
int lcd_filter;
switch (options->lcd_filter) {
case CAIRO_LCD_FILTER_NONE:
lcd_filter = FT_LCD_FILTER_NONE;
break;
case CAIRO_LCD_FILTER_DEFAULT:
case CAIRO_LCD_FILTER_INTRA_PIXEL:
lcd_filter = FT_LCD_FILTER_LEGACY;
break;
case CAIRO_LCD_FILTER_FIR3:
lcd_filter = FT_LCD_FILTER_LIGHT;
break;
default:
case CAIRO_LCD_FILTER_FIR5:
lcd_filter = FT_LCD_FILTER_DEFAULT;
break;
}
if (! FcPatternAddInteger (pattern, FC_LCD_FILTER, lcd_filter))
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
}
}
if (options->hint_style != CAIRO_HINT_STYLE_DEFAULT)
{
if (FcPatternGet (pattern, FC_HINTING, 0, &v) == FcResultNoMatch)
{
if (! FcPatternAddBool (pattern,
FC_HINTING,
options->hint_style != CAIRO_HINT_STYLE_NONE))
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
}
#ifdef FC_HINT_STYLE
if (FcPatternGet (pattern, FC_HINT_STYLE, 0, &v) == FcResultNoMatch)
{
int hint_style;
switch (options->hint_style) {
case CAIRO_HINT_STYLE_NONE:
hint_style = FC_HINT_NONE;
break;
case CAIRO_HINT_STYLE_SLIGHT:
hint_style = FC_HINT_SLIGHT;
break;
case CAIRO_HINT_STYLE_MEDIUM:
hint_style = FC_HINT_MEDIUM;
break;
case CAIRO_HINT_STYLE_FULL:
case CAIRO_HINT_STYLE_DEFAULT:
default:
hint_style = FC_HINT_FULL;
break;
}
if (! FcPatternAddInteger (pattern, FC_HINT_STYLE, hint_style))
return _cairo_error (CAIRO_STATUS_NO_MEMORY);
}
#endif
}
return CAIRO_STATUS_SUCCESS;
}
/**
* cairo_ft_font_options_substitute:
* @options: a #cairo_font_options_t object
* @pattern: an existing #FcPattern
*
* Add options to a #FcPattern based on a #cairo_font_options_t font
* options object. Options that are already in the pattern, are not overridden,
* so you should call this function after calling FcConfigSubstitute() (the
* user's settings should override options based on the surface type), but
* before calling FcDefaultSubstitute().
**/
void
cairo_ft_font_options_substitute (const cairo_font_options_t *options,
FcPattern *pattern)
{
if (cairo_font_options_status ((cairo_font_options_t *) options))
return;
_cairo_ft_font_options_substitute (options, pattern);
}
static cairo_font_face_t *
_cairo_ft_resolve_pattern (FcPattern *pattern,
const cairo_matrix_t *font_matrix,
const cairo_matrix_t *ctm,
const cairo_font_options_t *font_options)
{
cairo_status_t status;
cairo_matrix_t scale;
FcPattern *resolved;
cairo_ft_font_transform_t sf;
FcResult result;
cairo_ft_unscaled_font_t *unscaled;
cairo_ft_options_t ft_options;
cairo_font_face_t *font_face;
scale = *ctm;
scale.x0 = scale.y0 = 0;
cairo_matrix_multiply (&scale,
font_matrix,
&scale);
status = _compute_transform (&sf, &scale);
if (unlikely (status))
return (cairo_font_face_t *)&_cairo_font_face_nil;
pattern = FcPatternDuplicate (pattern);
if (pattern == NULL)
return (cairo_font_face_t *)&_cairo_font_face_nil;
if (! FcPatternAddDouble (pattern, FC_PIXEL_SIZE, sf.y_scale)) {
font_face = (cairo_font_face_t *)&_cairo_font_face_nil;
goto FREE_PATTERN;
}
if (! FcConfigSubstitute (NULL, pattern, FcMatchPattern)) {
font_face = (cairo_font_face_t *)&_cairo_font_face_nil;
goto FREE_PATTERN;
}
status = _cairo_ft_font_options_substitute (font_options, pattern);
if (status) {
font_face = (cairo_font_face_t *)&_cairo_font_face_nil;
goto FREE_PATTERN;
}
FcDefaultSubstitute (pattern);
resolved = FcFontMatch (NULL, pattern, &result);
if (!resolved) {
/* We failed to find any font. Substitute twin so that the user can
* see something (and hopefully recognise that the font is missing)
* and not just receive a NO_MEMORY error during rendering.
*/
font_face = _cairo_font_face_twin_create_fallback ();
goto FREE_PATTERN;
}
status = _cairo_ft_unscaled_font_create_for_pattern (resolved, &unscaled);
if (unlikely (status || unscaled == NULL)) {
font_face = (cairo_font_face_t *)&_cairo_font_face_nil;
goto FREE_RESOLVED;
}
_get_pattern_ft_options (resolved, &ft_options);
font_face = _cairo_ft_font_face_create (unscaled, &ft_options);
_cairo_unscaled_font_destroy (&unscaled->base);
FREE_RESOLVED:
FcPatternDestroy (resolved);
FREE_PATTERN:
FcPatternDestroy (pattern);
return font_face;
}
/**
* cairo_ft_font_face_create_for_pattern:
* @pattern: A fontconfig pattern. Cairo makes a copy of the pattern
* if it needs to. You are free to modify or free @pattern after this call.
*
* Creates a new font face for the FreeType font backend based on a
* fontconfig pattern. This font can then be used with
* cairo_set_font_face() or cairo_scaled_font_create(). The
* #cairo_scaled_font_t returned from cairo_scaled_font_create() is
* also for the FreeType backend and can be used with functions such
* as cairo_ft_scaled_font_lock_face().
*
* Font rendering options are represented both here and when you
* call cairo_scaled_font_create(). Font options that have a representation
* in a #FcPattern must be passed in here; to modify #FcPattern
* appropriately to reflect the options in a #cairo_font_options_t, call
* cairo_ft_font_options_substitute().
*
* The pattern's FC_FT_FACE element is inspected first and if that is set,
* that will be the FreeType font face associated with the returned cairo
* font face. Otherwise the FC_FILE element is checked. If it's set,
* that and the value of the FC_INDEX element (defaults to zero) of @pattern
* are used to load a font face from file.
*
* If both steps from the previous paragraph fails, @pattern will be passed
* to FcConfigSubstitute, FcDefaultSubstitute, and finally FcFontMatch,
* and the resulting font pattern is used.
*
* If the FC_FT_FACE element of @pattern is set, the user is responsible
* for making sure that the referenced FT_Face remains valid for the life
* time of the returned #cairo_font_face_t. See
* cairo_ft_font_face_create_for_ft_face() for an exmaple of how to couple
* the life time of the FT_Face to that of the cairo font-face.
*
* Return value: a newly created #cairo_font_face_t. Free with
* cairo_font_face_destroy() when you are done using it.
**/
cairo_font_face_t *
cairo_ft_font_face_create_for_pattern (FcPattern *pattern)
{
cairo_ft_unscaled_font_t *unscaled;
cairo_font_face_t *font_face;
cairo_ft_options_t ft_options;
cairo_status_t status;
status = _cairo_ft_unscaled_font_create_for_pattern (pattern, &unscaled);
if (unlikely (status))
return (cairo_font_face_t *) &_cairo_font_face_nil;
if (unlikely (unscaled == NULL)) {
/* Store the pattern. We will resolve it and create unscaled
* font when creating scaled fonts */
status = _cairo_ft_font_face_create_for_pattern (pattern,
&font_face);
if (unlikely (status))
return (cairo_font_face_t *) &_cairo_font_face_nil;
return font_face;
}
_get_pattern_ft_options (pattern, &ft_options);
font_face = _cairo_ft_font_face_create (unscaled, &ft_options);
_cairo_unscaled_font_destroy (&unscaled->base);
return font_face;
}
#endif
/**
* cairo_ft_font_face_create_for_ft_face:
* @face: A FreeType face object, already opened. This must
* be kept around until the face's ref_count drops to
* zero and it is freed. Since the face may be referenced
* internally to Cairo, the best way to determine when it
* is safe to free the face is to pass a
* #cairo_destroy_func_t to cairo_font_face_set_user_data()
* @load_flags: flags to pass to FT_Load_Glyph when loading
* glyphs from the font. These flags are OR'ed together with
* the flags derived from the #cairo_font_options_t passed
* to cairo_scaled_font_create(), so only a few values such
* as %FT_LOAD_VERTICAL_LAYOUT, and %FT_LOAD_FORCE_AUTOHINT
* are useful. You should not pass any of the flags affecting
* the load target, such as %FT_LOAD_TARGET_LIGHT.
*
* Creates a new font face for the FreeType font backend from a
* pre-opened FreeType face. This font can then be used with
* cairo_set_font_face() or cairo_scaled_font_create(). The
* #cairo_scaled_font_t returned from cairo_scaled_font_create() is
* also for the FreeType backend and can be used with functions such
* as cairo_ft_scaled_font_lock_face(). Note that Cairo may keep a reference
* to the FT_Face alive in a font-cache and the exact lifetime of the reference
* depends highly upon the exact usage pattern and is subject to external
* factors. You must not call FT_Done_Face() before the last reference to the
* #cairo_font_face_t has been dropped.
*
* As an example, below is how one might correctly couple the lifetime of
* the FreeType face object to the #cairo_font_face_t.
*
* <informalexample><programlisting>
* static const cairo_user_data_key_t key;
*
* font_face = cairo_ft_font_face_create_for_ft_face (ft_face, 0);
* status = cairo_font_face_set_user_data (font_face, &key,
* ft_face, (cairo_destroy_func_t) FT_Done_Face);
* if (status) {
* cairo_font_face_destroy (font_face);
* FT_Done_Face (ft_face);
* return ERROR;
* }
* </programlisting></informalexample>
*
* Return value: a newly created #cairo_font_face_t. Free with
* cairo_font_face_destroy() when you are done using it.
**/
cairo_font_face_t *
cairo_ft_font_face_create_for_ft_face (FT_Face face,
int load_flags)
{
cairo_ft_unscaled_font_t *unscaled;
cairo_font_face_t *font_face;
cairo_ft_options_t ft_options;
cairo_status_t status;
status = _cairo_ft_unscaled_font_create_from_face (face, &unscaled);
if (unlikely (status))
return (cairo_font_face_t *)&_cairo_font_face_nil;
ft_options.load_flags = load_flags;
ft_options.extra_flags = 0;
_cairo_font_options_init_default (&ft_options.base);
font_face = _cairo_ft_font_face_create (unscaled, &ft_options);
_cairo_unscaled_font_destroy (&unscaled->base);
return font_face;
}
/**
* cairo_ft_scaled_font_lock_face:
* @scaled_font: A #cairo_scaled_font_t from the FreeType font backend. Such an
* object can be created by calling cairo_scaled_font_create() on a
* FreeType backend font face (see cairo_ft_font_face_create_for_pattern(),
* cairo_ft_font_face_create_for_ft_face()).
*
* cairo_ft_scaled_font_lock_face() gets the #FT_Face object from a FreeType
* backend font and scales it appropriately for the font. You must
* release the face with cairo_ft_scaled_font_unlock_face()
* when you are done using it. Since the #FT_Face object can be
* shared between multiple #cairo_scaled_font_t objects, you must not
* lock any other font objects until you unlock this one. A count is
* kept of the number of times cairo_ft_scaled_font_lock_face() is
* called. cairo_ft_scaled_font_unlock_face() must be called the same number
* of times.
*
* You must be careful when using this function in a library or in a
* threaded application, because freetype's design makes it unsafe to
* call freetype functions simultaneously from multiple threads, (even
* if using distinct FT_Face objects). Because of this, application
* code that acquires an FT_Face object with this call must add its
* own locking to protect any use of that object, (and which also must
* protect any other calls into cairo as almost any cairo function
* might result in a call into the freetype library).
*
* Return value: The #FT_Face object for @font, scaled appropriately,
* or %NULL if @scaled_font is in an error state (see
* cairo_scaled_font_status()) or there is insufficient memory.
**/
FT_Face
cairo_ft_scaled_font_lock_face (cairo_scaled_font_t *abstract_font)
{
cairo_ft_scaled_font_t *scaled_font = (cairo_ft_scaled_font_t *) abstract_font;
FT_Face face;
cairo_status_t status;
if (! _cairo_scaled_font_is_ft (abstract_font)) {
_cairo_error_throw (CAIRO_STATUS_FONT_TYPE_MISMATCH);
return NULL;
}
if (scaled_font->base.status)
return NULL;
face = _cairo_ft_unscaled_font_lock_face (scaled_font->unscaled);
if (unlikely (face == NULL)) {
status = _cairo_scaled_font_set_error (&scaled_font->base, CAIRO_STATUS_NO_MEMORY);
return NULL;
}
status = _cairo_ft_unscaled_font_set_scale (scaled_font->unscaled,
&scaled_font->base.scale);
if (unlikely (status)) {
_cairo_ft_unscaled_font_unlock_face (scaled_font->unscaled);
status = _cairo_scaled_font_set_error (&scaled_font->base, status);
return NULL;
}
/* Note: We deliberately release the unscaled font's mutex here,
* so that we are not holding a lock across two separate calls to
* cairo function, (which would give the application some
* opportunity for creating deadlock. This is obviously unsafe,
* but as documented, the user must add manual locking when using
* this function. */
CAIRO_MUTEX_UNLOCK (scaled_font->unscaled->mutex);
return face;
}
/**
* cairo_ft_scaled_font_unlock_face:
* @scaled_font: A #cairo_scaled_font_t from the FreeType font backend. Such an
* object can be created by calling cairo_scaled_font_create() on a
* FreeType backend font face (see cairo_ft_font_face_create_for_pattern(),
* cairo_ft_font_face_create_for_ft_face()).
*
* Releases a face obtained with cairo_ft_scaled_font_lock_face().
**/
void
cairo_ft_scaled_font_unlock_face (cairo_scaled_font_t *abstract_font)
{
cairo_ft_scaled_font_t *scaled_font = (cairo_ft_scaled_font_t *) abstract_font;
if (! _cairo_scaled_font_is_ft (abstract_font)) {
_cairo_error_throw (CAIRO_STATUS_FONT_TYPE_MISMATCH);
return;
}
if (scaled_font->base.status)
return;
/* Note: We released the unscaled font's mutex at the end of
* cairo_ft_scaled_font_lock_face, so we have to acquire it again
* as _cairo_ft_unscaled_font_unlock_face expects it to be held
* when we call into it. */
CAIRO_MUTEX_LOCK (scaled_font->unscaled->mutex);
_cairo_ft_unscaled_font_unlock_face (scaled_font->unscaled);
}
/* We expose our unscaled font implementation internally for the the
* PDF backend, which needs to keep track of the the different
* fonts-on-disk used by a document, so it can embed them.
*/
cairo_unscaled_font_t *
_cairo_ft_scaled_font_get_unscaled_font (cairo_scaled_font_t *abstract_font)
{
cairo_ft_scaled_font_t *scaled_font = (cairo_ft_scaled_font_t *) abstract_font;
return &scaled_font->unscaled->base;
}
cairo_bool_t
_cairo_ft_scaled_font_is_vertical (cairo_scaled_font_t *scaled_font)
{
cairo_ft_scaled_font_t *ft_scaled_font;
if (!_cairo_scaled_font_is_ft (scaled_font))
return FALSE;
ft_scaled_font = (cairo_ft_scaled_font_t *) scaled_font;
if (ft_scaled_font->ft_options.load_flags & FT_LOAD_VERTICAL_LAYOUT)
return TRUE;
return FALSE;
}
unsigned int
_cairo_ft_scaled_font_get_load_flags (cairo_scaled_font_t *scaled_font)
{
cairo_ft_scaled_font_t *ft_scaled_font;
if (! _cairo_scaled_font_is_ft (scaled_font))
return 0;
ft_scaled_font = (cairo_ft_scaled_font_t *) scaled_font;
return ft_scaled_font->ft_options.load_flags;
}
void
_cairo_ft_font_reset_static_data (void)
{
_cairo_ft_unscaled_font_map_destroy ();
}
| twobob/buildroot-kindle | output/build/cairo-1.10.2/src/cairo-ft-font.c | C | gpl-2.0 | 94,222 |
<?php
/*
Copyright 2013 I.T.RO.® (email : support.itro@live.com)
This file is part of ITRO Popup Plugin.
*/
global $wpdb;
define ('OPTION_TABLE_NAME', $wpdb->prefix . 'itro_plugin_option');
define ('FIELD_TABLE_NAME', $wpdb->prefix . 'itro_plugin_field');
/* -------Create plugin tables */
function itro_db_init()
{
global $wpdb;
/* ------------------Option table */
$option_table_name = OPTION_TABLE_NAME;
$sql = "CREATE TABLE IF NOT EXISTS $option_table_name
(
option_id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(option_id),
option_name varchar(255),
option_val varchar(255)
) CHARACTER SET=utf8 COLLATE utf8_general_ci";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
/* --------------Custom field table */
$field_table_name = FIELD_TABLE_NAME;
$sql = "CREATE TABLE IF NOT EXISTS $field_table_name
(
field_id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(field_id),
field_name varchar(255),
field_value TEXT
) CHARACTER SET=utf8 COLLATE utf8_general_ci";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
/* update old fixed 'wp_' prefix to the current one' */
function itro_update_db()
{
global $wpdb;
if ( get_option('itro_prev_ver') <= 3.68 )
{
itro_update_option('popup_border_width',3);
itro_update_option('popup_border_radius',8);
}
if( get_option('itro_prev_ver') <= 4.6 && $wpdb->prefix != 'wp_' )
{
$wpdb->query("RENAME TABLE wp_itro_plugin_option TO ". $wpdb->prefix ."itro_plugin_option");
$wpdb->query("RENAME TABLE wp_itro_plugin_field TO ". $wpdb->prefix ."itro_plugin_field");
}
}
/* ------------------ PLUGIN OPTION DB MANAGEMENT -------------- */
function itro_update_option($opt_name,$opt_val)
{
global $wpdb;
$option_table_name = OPTION_TABLE_NAME;
$data_to_send = array('option_val'=> $opt_val);
$where_line = array('option_name' => $opt_name);
$wp_query = $wpdb->get_results("SELECT * FROM $option_table_name WHERE option_name='$opt_name'");
if ( $wp_query == NULL )
{
$wpdb->insert( $option_table_name , $where_line);
$wpdb->update( $option_table_name , $data_to_send, $where_line );
}
else
{
$wpdb->update( $option_table_name , $data_to_send, $where_line );
}
}
function itro_get_option($opt_name)
{
global $wpdb;
$option_table_name = OPTION_TABLE_NAME;
$result = $wpdb->get_results("SELECT * FROM $option_table_name WHERE option_name='$opt_name'");
foreach($result as $pippo)
{
$opt_val = $pippo->option_val;
}
if(isset($opt_val)) {return ($opt_val);}
else {return (NULL);}
}
/* ------------------ CUSTOM FIELD CONTENT DB MANAGEMENT -------------- */
function itro_update_field($field_name,$field_value)
{
global $wpdb;
$field_table_name = FIELD_TABLE_NAME;
$data_to_send = array('field_value'=> $field_value);
$where_line = array('field_name' => $field_name);
$wp_query = $wpdb->get_results("SELECT * FROM $field_table_name WHERE field_name='$field_name'");
if ( $wp_query == NULL )
{
$wpdb->insert( $field_table_name , $where_line);
$wpdb->update( $field_table_name , $data_to_send, $where_line );
}
else
{
$wpdb->update( $field_table_name , $data_to_send, $where_line );
}
}
function itro_get_field($field_name)
{
global $wpdb;
$field_table_name = FIELD_TABLE_NAME;
$result = $wpdb->get_results("SELECT * FROM $field_table_name WHERE field_name='$field_name'");
foreach($result as $pippo)
{
$field_value = $pippo->field_value;
}
if(isset($field_value)) {return ($field_value);}
else {return (NULL);}
}
?> | SayenkoDesign/selectahead | wp-content/plugins/itro-popup/functions/database-function.php | PHP | gpl-2.0 | 3,493 |
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// copyright : (C) 2008 by Eran Ifrah
// file name : lexer_configuration.h
//
// -------------------------------------------------------------------------
// A
// _____ _ _ _ _
// / __ \ | | | | (_) |
// | / \/ ___ __| | ___| | _| |_ ___
// | | / _ \ / _ |/ _ \ | | | __/ _ )
// | \__/\ (_) | (_| | __/ |___| | || __/
// \____/\___/ \__,_|\___\_____/_|\__\___|
//
// F i l e
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
#ifndef LEXER_CONFIGURATION_H
#define LEXER_CONFIGURATION_H
#include "wx/string.h"
#include "wx/filename.h"
#include "attribute_style.h"
#include "wx/xml/xml.h"
#include <wx/font.h>
#include "codelite_exports.h"
#include <wx/stc/stc.h>
#include <wx/sharedptr.h>
#include <smart_ptr.h>
#include "json_node.h"
#define ANNOTATION_STYLE_WARNING 210
#define ANNOTATION_STYLE_ERROR 211
#define ANNOTATION_STYLE_CC_ERROR 212
class WXDLLIMPEXP_SDK LexerConf
{
StyleProperty::Map_t m_properties;
int m_lexerId;
wxString m_name;
wxString m_extension;
wxString m_keyWords[10];
wxString m_themeName;
size_t m_flags;
public:
typedef SmartPtr<LexerConf> Ptr_t;
protected:
enum eLexerConfFlags {
kNone = 0,
kStyleInPP = (1 << 0),
kIsActive = (1 << 1),
kUseCustomTextSelectionFgColour = (1 << 2),
};
inline void EnableFlag(eLexerConfFlags flag, bool b)
{
if(b) {
m_flags |= flag;
} else {
m_flags &= ~flag;
}
}
inline bool HasFlag(eLexerConfFlags flag) const { return m_flags & flag; }
public:
struct FindByNameAndTheme {
wxString m_name;
wxString m_theme;
FindByNameAndTheme(const wxString& name, const wxString& theme)
: m_name(name)
, m_theme(theme)
{
}
bool operator()(LexerConf::Ptr_t lexer) const
{
return lexer->GetName() == m_name && lexer->GetThemeName() == m_theme;
}
};
public:
// Return an xml representation from this object
wxXmlNode* ToXml() const;
// Parse lexer object from xml node
void FromXml(wxXmlNode* node);
/**
* @brief convert the lexer settings into a JSON object
*/
JSONElement ToJSON() const;
/**
* @brief construt this object from a JSON object
* @param json
*/
void FromJSON(const JSONElement& json);
public:
LexerConf();
virtual ~LexerConf();
void SetUseCustomTextSelectionFgColour(bool b) { EnableFlag(kUseCustomTextSelectionFgColour, b); }
bool IsUseCustomTextSelectionFgColour() const { return HasFlag(kUseCustomTextSelectionFgColour); }
void SetStyleWithinPreProcessor(bool b) { EnableFlag(kStyleInPP, b); }
bool GetStyleWithinPreProcessor() const { return HasFlag(kStyleInPP); }
void SetIsActive(bool b) { EnableFlag(kIsActive, b); }
bool IsActive() const { return HasFlag(kIsActive); }
void SetThemeName(const wxString& themeName) { this->m_themeName = themeName; }
const wxString& GetThemeName() const { return m_themeName; }
/**
* @brief return true if the colours represented by this lexer are a "dark" theme
*/
bool IsDark() const;
/**
* @brief apply the current lexer configuration on an input
* wxStyledTextCtrl
*/
void Apply(wxStyledTextCtrl* ctrl, bool applyKeywords = false);
/**
* Get the lexer ID, which should be in sync with values of Scintilla
* \return
*/
int GetLexerId() const { return m_lexerId; }
/**
* Set the lexer ID
* \param id
*/
void SetLexerId(int id) { m_lexerId = id; }
/**
* Return the lexer description as described in the XML file
*/
const wxString& GetName() const { return m_name; }
void SetName(const wxString& name) { m_name = name; }
/**
* Return the lexer keywords
* \return
*/
const wxString& GetKeyWords(int set) const { return m_keyWords[set]; }
void SetKeyWords(const wxString& keywords, int set);
/**
* File patterns that this lexer should apply to
*/
const wxString& GetFileSpec() const { return m_extension; }
/**
* Return a list of the lexer properties
* \return
*/
const StyleProperty::Map_t& GetLexerProperties() const { return m_properties; }
/**
* Return a list of the lexer properties
* \return
*/
StyleProperty::Map_t& GetLexerProperties() { return m_properties; }
/**
* @brief return property. Check for IsNull() to make sure we got a valid property
* @param propertyId
* @return
*/
StyleProperty& GetProperty(int propertyId);
const StyleProperty& GetProperty(int propertyId) const;
/**
* @brief set the line numbers colour
*/
void SetLineNumbersFgColour(const wxColour& colour);
/**
* @brief set the default fg colour
*/
void SetDefaultFgColour(const wxColour& colour);
/**
* Set the lexer properties
* \param &properties
*/
void SetProperties(StyleProperty::Map_t& properties) { m_properties.swap(properties); }
/**
* Set file spec for the lexer
* \param &spec
*/
void SetFileSpec(const wxString& spec) { m_extension = spec; }
/**
* @brief return the font for a given style id
* @return return wxNullFont if error occurred or could locate the style
*/
wxFont GetFontForSyle(int styleId) const;
};
#endif // LEXER_CONFIGURATION_H
| Alexpux/codelite | Plugin/lexer_configuration.h | C | gpl-2.0 | 6,168 |
/*
* Copyright (C) 2005-2018 Team Kodi
* This file is part of Kodi - https://kodi.tv
*
* SPDX-License-Identifier: GPL-2.0-or-later
* See LICENSES/README.md for more information.
*/
#include "WIN32Util.h"
#include "Application.h"
#include "CompileInfo.h"
#include "ServiceBroker.h"
#include "Util.h"
#include "WindowHelper.h"
#include "guilib/LocalizeStrings.h"
#include "my_ntddscsi.h"
#include "storage/MediaManager.h"
#include "storage/cdioSupport.h"
#include "utils/CharsetConverter.h"
#include "utils/StringUtils.h"
#include "utils/SystemInfo.h"
#include "utils/URIUtils.h"
#include "utils/log.h"
#include "platform/win32/CharsetConverter.h"
#include <PowrProf.h>
#ifdef TARGET_WINDOWS_DESKTOP
#include <cassert>
#endif
#include <locale.h>
#include <shellapi.h>
#include <shlobj.h>
#include <winioctl.h>
#ifdef TARGET_WINDOWS_DESKTOP
extern HWND g_hWnd;
#endif
using namespace MEDIA_DETECT;
#ifdef TARGET_WINDOWS_STORE
#include "platform/win10/AsyncHelpers.h"
#include <ppltasks.h>
#include <winrt/Windows.Devices.Display.Core.h>
#include <winrt/Windows.Devices.Power.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Graphics.Display.Core.h>
#include <winrt/Windows.Storage.h>
using namespace winrt::Windows::Devices::Power;
using namespace winrt::Windows::Devices::Display::Core;
using namespace winrt::Windows::Graphics::Display;
using namespace winrt::Windows::Graphics::Display::Core;
using namespace winrt::Windows::Storage;
#endif
CWIN32Util::CWIN32Util(void)
{
}
CWIN32Util::~CWIN32Util(void)
{
}
int CWIN32Util::GetDriveStatus(const std::string &strPath, bool bStatusEx)
{
#ifdef TARGET_WINDOWS_STORE
CLog::LogF(LOGDEBUG, "is not implemented");
CLog::LogF(LOGDEBUG, "Could not determine tray status %d", GetLastError());
return -1;
#else
using KODI::PLATFORM::WINDOWS::ToW;
auto strPathW = ToW(strPath);
HANDLE hDevice; // handle to the drive to be examined
int iResult; // results flag
ULONG ulChanges=0;
DWORD dwBytesReturned;
T_SPDT_SBUF sptd_sb; //SCSI Pass Through Direct variable.
byte DataBuf[8]; //Buffer for holding data to/from drive.
CLog::LogF(LOGDEBUG, "Requesting status for drive %s.", strPath);
hDevice = CreateFile( strPathW.c_str(), // drive
0, // no access to the drive
FILE_SHARE_READ, // share mode
NULL, // default security attributes
OPEN_EXISTING, // disposition
FILE_ATTRIBUTE_READONLY, // file attributes
NULL);
if (hDevice == INVALID_HANDLE_VALUE) // cannot open the drive
{
CLog::LogF(LOGERROR, "Failed to CreateFile for %s.", strPath);
return -1;
}
CLog::LogF(LOGDEBUG, "Requesting media status for drive %s.", strPath);
iResult = DeviceIoControl((HANDLE) hDevice, // handle to device
IOCTL_STORAGE_CHECK_VERIFY2, // dwIoControlCode
NULL, // lpInBuffer
0, // nInBufferSize
&ulChanges, // lpOutBuffer
sizeof(ULONG), // nOutBufferSize
&dwBytesReturned , // number of bytes returned
NULL ); // OVERLAPPED structure
CloseHandle(hDevice);
if(iResult == 1)
return 2;
// don't request the tray status as we often doesn't need it
if(!bStatusEx)
return 0;
hDevice = CreateFile( strPathW.c_str(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_READONLY,
NULL);
if (hDevice == INVALID_HANDLE_VALUE)
{
CLog::LogF(LOGERROR, "Failed to CreateFile2 for %s.", strPath);
return -1;
}
sptd_sb.sptd.Length=sizeof(SCSI_PASS_THROUGH_DIRECT);
sptd_sb.sptd.PathId=0;
sptd_sb.sptd.TargetId=0;
sptd_sb.sptd.Lun=0;
sptd_sb.sptd.CdbLength=10;
sptd_sb.sptd.SenseInfoLength=MAX_SENSE_LEN;
sptd_sb.sptd.DataIn=SCSI_IOCTL_DATA_IN;
sptd_sb.sptd.DataTransferLength=sizeof(DataBuf);
sptd_sb.sptd.TimeOutValue=2;
sptd_sb.sptd.DataBuffer=(PVOID)&(DataBuf);
sptd_sb.sptd.SenseInfoOffset=sizeof(SCSI_PASS_THROUGH_DIRECT);
sptd_sb.sptd.Cdb[0]=0x4a;
sptd_sb.sptd.Cdb[1]=1;
sptd_sb.sptd.Cdb[2]=0;
sptd_sb.sptd.Cdb[3]=0;
sptd_sb.sptd.Cdb[4]=0x10;
sptd_sb.sptd.Cdb[5]=0;
sptd_sb.sptd.Cdb[6]=0;
sptd_sb.sptd.Cdb[7]=0;
sptd_sb.sptd.Cdb[8]=8;
sptd_sb.sptd.Cdb[9]=0;
sptd_sb.sptd.Cdb[10]=0;
sptd_sb.sptd.Cdb[11]=0;
sptd_sb.sptd.Cdb[12]=0;
sptd_sb.sptd.Cdb[13]=0;
sptd_sb.sptd.Cdb[14]=0;
sptd_sb.sptd.Cdb[15]=0;
ZeroMemory(DataBuf, 8);
ZeroMemory(sptd_sb.SenseBuf, MAX_SENSE_LEN);
//Send the command to drive
CLog::LogF(LOGDEBUG, "Requesting tray status for drive %s.", strPath);
iResult = DeviceIoControl((HANDLE) hDevice,
IOCTL_SCSI_PASS_THROUGH_DIRECT,
(PVOID)&sptd_sb, (DWORD)sizeof(sptd_sb),
(PVOID)&sptd_sb, (DWORD)sizeof(sptd_sb),
&dwBytesReturned,
NULL);
CloseHandle(hDevice);
if(iResult)
{
if(DataBuf[5] == 0) // tray close
return 0;
else if(DataBuf[5] == 1) // tray open
return 1;
else
return 2; // tray closed, media present
}
CLog::LogF(LOGERROR, "Could not determine tray status %d", GetLastError());
return -1;
#endif
}
char CWIN32Util::FirstDriveFromMask (ULONG unitmask)
{
char i;
for (i = 0; i < 26; ++i)
{
if (unitmask & 0x1) break;
unitmask = unitmask >> 1;
}
return (i + 'A');
}
bool CWIN32Util::XBMCShellExecute(const std::string &strPath, bool bWaitForScriptExit)
{
#ifdef TARGET_WINDOWS_STORE
CLog::LogF(LOGDEBUG, "s not implemented");
return false;
#else
std::string strCommand = strPath;
std::string strExe = strPath;
std::string strParams;
std::string strWorkingDir;
StringUtils::Trim(strCommand);
if (strCommand.empty())
{
return false;
}
size_t iIndex = std::string::npos;
char split = ' ';
if (strCommand[0] == '\"')
{
split = '\"';
}
iIndex = strCommand.find(split, 1);
if (iIndex != std::string::npos)
{
strExe = strCommand.substr(0, iIndex + 1);
strParams = strCommand.substr(iIndex + 1);
}
StringUtils::Replace(strExe, "\"", "");
strWorkingDir = strExe;
iIndex = strWorkingDir.rfind('\\');
if(iIndex != std::string::npos)
{
strWorkingDir[iIndex+1] = '\0';
}
std::wstring WstrExe, WstrParams, WstrWorkingDir;
g_charsetConverter.utf8ToW(strExe, WstrExe);
g_charsetConverter.utf8ToW(strParams, WstrParams);
g_charsetConverter.utf8ToW(strWorkingDir, WstrWorkingDir);
bool ret;
SHELLEXECUTEINFOW ShExecInfo = {0};
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFOW);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = NULL;
ShExecInfo.lpFile = WstrExe.c_str();
ShExecInfo.lpParameters = WstrParams.c_str();
ShExecInfo.lpDirectory = WstrWorkingDir.c_str();
ShExecInfo.nShow = SW_SHOW;
ShExecInfo.hInstApp = NULL;
g_windowHelper.StopThread();
LockSetForegroundWindow(LSFW_UNLOCK);
ShowWindow(g_hWnd,SW_MINIMIZE);
ret = ShellExecuteExW(&ShExecInfo) == TRUE;
g_windowHelper.SetHANDLE(ShExecInfo.hProcess);
// ShellExecute doesn't return the window of the started process
// we need to gather it from somewhere to allow switch back to XBMC
// when a program is minimized instead of stopped.
//g_windowHelper.SetHWND(ShExecInfo.hwnd);
g_windowHelper.Create();
if(bWaitForScriptExit)
{
//! @todo Pause music and video playback
WaitForSingleObject(ShExecInfo.hProcess,INFINITE);
}
return ret;
#endif
}
std::string CWIN32Util::GetResInfoString()
{
#ifdef TARGET_WINDOWS_STORE
auto displayInfo = DisplayInformation::GetForCurrentView();
return StringUtils::Format("Desktop Resolution: %dx%d"
, displayInfo.ScreenWidthInRawPixels()
, displayInfo.ScreenHeightInRawPixels()
);
#else
DEVMODE devmode;
ZeroMemory(&devmode, sizeof(devmode));
devmode.dmSize = sizeof(devmode);
EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &devmode);
return StringUtils::Format("Desktop Resolution: %dx%d %dBit at %dHz",devmode.dmPelsWidth,devmode.dmPelsHeight,devmode.dmBitsPerPel,devmode.dmDisplayFrequency);
#endif
}
int CWIN32Util::GetDesktopColorDepth()
{
#ifdef TARGET_WINDOWS_STORE
CLog::LogF(LOGDEBUG, "s not implemented");
return 32;
#else
DEVMODE devmode;
ZeroMemory(&devmode, sizeof(devmode));
devmode.dmSize = sizeof(devmode);
EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &devmode);
return (int)devmode.dmBitsPerPel;
#endif
}
size_t CWIN32Util::GetSystemMemorySize()
{
#ifdef TARGET_WINDOWS_STORE
MEMORYSTATUSEX statex = {};
statex.dwLength = sizeof(statex);
GlobalMemoryStatusEx(&statex);
return static_cast<size_t>(statex.ullTotalPhys / KB);
#else
ULONGLONG ramSize = 0;
GetPhysicallyInstalledSystemMemory(&ramSize);
return static_cast<size_t>(ramSize);
#endif
}
#ifdef TARGET_WINDOWS_DESKTOP
std::string CWIN32Util::GetSpecialFolder(int csidl)
{
std::string strProfilePath;
static const int bufSize = MAX_PATH;
WCHAR* buf = new WCHAR[bufSize];
if(SUCCEEDED(SHGetFolderPathW(NULL, csidl, NULL, SHGFP_TYPE_CURRENT, buf)))
{
buf[bufSize-1] = 0;
g_charsetConverter.wToUTF8(buf, strProfilePath);
strProfilePath = UncToSmb(strProfilePath);
}
else
strProfilePath = "";
delete[] buf;
return strProfilePath;
}
#endif
std::string CWIN32Util::GetSystemPath()
{
#ifdef TARGET_WINDOWS_STORE
// access to system folder is not allowed in a UWP app
return "";
#else
return GetSpecialFolder(CSIDL_SYSTEM);
#endif
}
std::string CWIN32Util::GetProfilePath()
{
std::string strProfilePath;
#ifdef TARGET_WINDOWS_STORE
auto localFolder = ApplicationData::Current().LocalFolder();
strProfilePath = KODI::PLATFORM::WINDOWS::FromW(localFolder.Path().c_str());
#else
std::string strHomePath = CUtil::GetHomePath();
if(g_application.PlatformDirectoriesEnabled())
strProfilePath = URIUtils::AddFileToFolder(GetSpecialFolder(CSIDL_APPDATA|CSIDL_FLAG_CREATE), CCompileInfo::GetAppName());
else
strProfilePath = URIUtils::AddFileToFolder(strHomePath , "portable_data");
if (strProfilePath.length() == 0)
strProfilePath = strHomePath;
URIUtils::AddSlashAtEnd(strProfilePath);
#endif
return strProfilePath;
}
std::string CWIN32Util::UncToSmb(const std::string &strPath)
{
std::string strRetPath(strPath);
if(StringUtils::StartsWith(strRetPath, "\\\\"))
{
strRetPath = "smb:" + strPath;
StringUtils::Replace(strRetPath, '\\', '/');
}
return strRetPath;
}
std::string CWIN32Util::SmbToUnc(const std::string &strPath)
{
std::string strRetPath(strPath);
if(StringUtils::StartsWithNoCase(strRetPath, "smb://"))
{
StringUtils::Replace(strRetPath, "smb://", "\\\\");
StringUtils::Replace(strRetPath, '/', '\\');
}
return strRetPath;
}
bool CWIN32Util::AddExtraLongPathPrefix(std::wstring& path)
{
const wchar_t* const str = path.c_str();
if (path.length() < 4 || str[0] != L'\\' || str[1] != L'\\' || str[3] != L'\\' || str[2] != L'?')
{
path.insert(0, L"\\\\?\\");
return true;
}
return false;
}
bool CWIN32Util::RemoveExtraLongPathPrefix(std::wstring& path)
{
const wchar_t* const str = path.c_str();
if (path.length() >= 4 && str[0] == L'\\' && str[1] == L'\\' && str[3] == L'\\' && str[2] == L'?')
{
path.erase(0, 4);
return true;
}
return false;
}
std::wstring CWIN32Util::ConvertPathToWin32Form(const std::string& pathUtf8)
{
std::wstring result;
if (pathUtf8.empty())
return result;
bool convertResult;
if (pathUtf8.compare(0, 2, "\\\\", 2) != 0) // pathUtf8 don't start from "\\"
{ // assume local file path in form 'C:\Folder\File.ext'
std::string formedPath("\\\\?\\"); // insert "\\?\" prefix
formedPath += URIUtils::CanonicalizePath(URIUtils::FixSlashesAndDups(pathUtf8, '\\'), '\\'); // fix duplicated and forward slashes, resolve relative path
convertResult = g_charsetConverter.utf8ToW(formedPath, result, false, false, true);
}
else if (pathUtf8.compare(0, 8, "\\\\?\\UNC\\", 8) == 0) // pathUtf8 starts from "\\?\UNC\"
{
std::string formedPath("\\\\?\\UNC"); // start from "\\?\UNC" prefix
formedPath += URIUtils::CanonicalizePath(URIUtils::FixSlashesAndDups(pathUtf8.substr(7), '\\'), '\\'); // fix duplicated and forward slashes, resolve relative path, don't touch "\\?\UNC" prefix,
convertResult = g_charsetConverter.utf8ToW(formedPath, result, false, false, true);
}
else if (pathUtf8.compare(0, 4, "\\\\?\\", 4) == 0) // pathUtf8 starts from "\\?\", but it's not UNC path
{
std::string formedPath("\\\\?"); // start from "\\?" prefix
formedPath += URIUtils::CanonicalizePath(URIUtils::FixSlashesAndDups(pathUtf8.substr(3), '\\'), '\\'); // fix duplicated and forward slashes, resolve relative path, don't touch "\\?" prefix,
convertResult = g_charsetConverter.utf8ToW(formedPath, result, false, false, true);
}
else // pathUtf8 starts from "\\", but not from "\\?\UNC\"
{ // assume UNC path in form '\\server\share\folder\file.ext'
std::string formedPath("\\\\?\\UNC"); // append "\\?\UNC" prefix
formedPath += URIUtils::CanonicalizePath(URIUtils::FixSlashesAndDups(pathUtf8), '\\'); // fix duplicated and forward slashes, resolve relative path, transform "\\" prefix to single "\"
convertResult = g_charsetConverter.utf8ToW(formedPath, result, false, false, true);
}
if (!convertResult)
{
CLog::Log(LOGERROR, "Error converting path \"%s\" to Win32 wide string!", pathUtf8.c_str());
return L"";
}
return result;
}
std::wstring CWIN32Util::ConvertPathToWin32Form(const CURL& url)
{
assert(url.GetProtocol().empty() || url.IsProtocol("smb"));
if (url.GetFileName().empty())
return std::wstring(); // empty string
if (url.GetProtocol().empty())
{
std::wstring result;
if (g_charsetConverter.utf8ToW("\\\\?\\" +
URIUtils::CanonicalizePath(URIUtils::FixSlashesAndDups(url.GetFileName(), '\\'), '\\'), result, false, false, true))
return result;
}
else if (url.IsProtocol("smb"))
{
if (url.GetHostName().empty())
return std::wstring(); // empty string
std::wstring result;
if (g_charsetConverter.utf8ToW("\\\\?\\UNC\\" +
URIUtils::CanonicalizePath(URIUtils::FixSlashesAndDups(url.GetHostName() + '\\' + url.GetFileName(), '\\'), '\\'),
result, false, false, true))
return result;
}
else
return std::wstring(); // unsupported protocol, return empty string
CLog::LogF(LOGERROR, "Error converting path \"%s\" to Win32 form", url.Get());
return std::wstring(); // empty string
}
__time64_t CWIN32Util::fileTimeToTimeT(const FILETIME& ftimeft)
{
if (!ftimeft.dwHighDateTime && !ftimeft.dwLowDateTime)
return 0;
return fileTimeToTimeT((__int64(ftimeft.dwHighDateTime) << 32) + __int64(ftimeft.dwLowDateTime));
}
__time64_t CWIN32Util::fileTimeToTimeT(const LARGE_INTEGER& ftimeli)
{
if (ftimeli.QuadPart == 0)
return 0;
return fileTimeToTimeT(__int64(ftimeli.QuadPart));
}
HRESULT CWIN32Util::ToggleTray(const char cDriveLetter)
{
#ifdef TARGET_WINDOWS_STORE
CLog::LogF(LOGDEBUG, "s not implemented");
return false;
#else
using namespace KODI::PLATFORM::WINDOWS;
BOOL bRet= FALSE;
DWORD dwReq = 0;
char cDL = cDriveLetter;
if( !cDL )
{
std::string dvdDevice = CServiceBroker::GetMediaManager().TranslateDevicePath("");
if(dvdDevice == "")
return S_FALSE;
cDL = dvdDevice[0];
}
auto strVolFormat = ToW(StringUtils::Format("\\\\.\\%c:", cDL));
HANDLE hDrive= CreateFile( strVolFormat.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
auto strRootFormat = ToW(StringUtils::Format("%c:\\", cDL));
if( ( hDrive != INVALID_HANDLE_VALUE || GetLastError() == NO_ERROR) &&
( GetDriveType( strRootFormat.c_str() ) == DRIVE_CDROM ) )
{
DWORD dwDummy;
dwReq = (GetDriveStatus(FromW(strVolFormat), true) == 1) ? IOCTL_STORAGE_LOAD_MEDIA : IOCTL_STORAGE_EJECT_MEDIA;
bRet = DeviceIoControl( hDrive, dwReq, NULL, 0, NULL, 0, &dwDummy, NULL);
}
// Windows doesn't seem to send always DBT_DEVICEREMOVECOMPLETE
// unmount it here too as it won't hurt
if(dwReq == IOCTL_STORAGE_EJECT_MEDIA && bRet == 1)
{
CMediaSource share;
share.strPath = StringUtils::Format("%c:", cDL);
share.strName = share.strPath;
CServiceBroker::GetMediaManager().RemoveAutoSource(share);
}
CloseHandle(hDrive);
return bRet? S_OK : S_FALSE;
#endif
}
HRESULT CWIN32Util::EjectTray(const char cDriveLetter)
{
char cDL = cDriveLetter;
if( !cDL )
{
std::string dvdDevice = CServiceBroker::GetMediaManager().TranslateDevicePath("");
if(dvdDevice.empty())
return S_FALSE;
cDL = dvdDevice[0];
}
std::string strVolFormat = StringUtils::Format("\\\\.\\%c:", cDL);
if(GetDriveStatus(strVolFormat, true) != 1)
return ToggleTray(cDL);
else
return S_OK;
}
HRESULT CWIN32Util::CloseTray(const char cDriveLetter)
{
char cDL = cDriveLetter;
if( !cDL )
{
std::string dvdDevice = CServiceBroker::GetMediaManager().TranslateDevicePath("");
if(dvdDevice.empty())
return S_FALSE;
cDL = dvdDevice[0];
}
std::string strVolFormat = StringUtils::Format( "\\\\.\\%c:", cDL);
if(GetDriveStatus(strVolFormat, true) == 1)
return ToggleTray(cDL);
else
return S_OK;
}
BOOL CWIN32Util::IsCurrentUserLocalAdministrator()
{
#ifdef TARGET_WINDOWS_STORE
// UWP apps never run as admin
return false;
#else
BOOL b;
SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
PSID AdministratorsGroup;
b = AllocateAndInitializeSid(
&NtAuthority,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&AdministratorsGroup);
if(b)
{
if (!CheckTokenMembership( NULL, AdministratorsGroup, &b))
{
b = FALSE;
}
FreeSid(AdministratorsGroup);
}
return(b);
#endif
}
extern "C"
{
FILE *fopen_utf8(const char *_Filename, const char *_Mode)
{
std::string modetmp = _Mode;
std::wstring wfilename, wmode(modetmp.begin(), modetmp.end());
g_charsetConverter.utf8ToW(_Filename, wfilename, false);
return _wfopen(wfilename.c_str(), wmode.c_str());
}
}
extern "C" {
/*
* Copyright (c) 1997, 1998, 2005 The NetBSD Foundation, Inc.
* All rights reserved.
*
* SPDX-License-Identifier: BSD-4-Clause
* See LICENSES/README.md for more information.
*
* Ported from NetBSD to Windows by Ron Koenderink, 2007
* $NetBSD: strptime.c,v 1.25 2005/11/29 03:12:00 christos Exp $
*
* This code was contributed to The NetBSD Foundation by Klaus Klein.
* Heavily optimised by David Laight
*/
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: strptime.c,v 1.25 2005/11/29 03:12:00 christos Exp $");
#endif
typedef unsigned char u_char;
typedef unsigned int uint;
#include <ctype.h>
#include <locale.h>
#include <string.h>
#include <time.h>
#ifdef __weak_alias
__weak_alias(strptime,_strptime)
#endif
#define _ctloc(x) (x)
const char *abday[] = {
"Sun", "Mon", "Tue", "Wed",
"Thu", "Fri", "Sat"
};
const char *day[] = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
};
const char *abmon[] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
const char *mon[] = {
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
const char *am_pm[] = {
"AM", "PM"
};
char *d_t_fmt = "%a %Ef %T %Y";
char *t_fmt_ampm = "%I:%M:%S %p";
char *t_fmt = "%H:%M:%S";
char *d_fmt = "%m/%d/%y";
#define TM_YEAR_BASE 1900
#define __UNCONST(x) ((char *)(((const char *)(x) - (const char *)0) + (char *)0))
/*
* We do not implement alternate representations. However, we always
* check whether a given modifier is allowed for a certain conversion.
*/
#define ALT_E 0x01
#define ALT_O 0x02
#define LEGAL_ALT(x) { if (alt_format & ~(x)) return NULL; }
static const u_char *conv_num(const unsigned char *, int *, uint, uint);
static const u_char *find_string(const u_char *, int *, const char * const *,
const char * const *, int);
char *
strptime(const char *buf, const char *fmt, struct tm *tm)
{
unsigned char c;
const unsigned char *bp;
int alt_format, i, split_year = 0;
const char *new_fmt;
bp = (const u_char *)buf;
while (bp != NULL && (c = *fmt++) != '\0') {
/* Clear `alternate' modifier prior to new conversion. */
alt_format = 0;
i = 0;
/* Eat up white-space. */
if (isspace(c)) {
while (isspace(*bp))
bp++;
continue;
}
if (c != '%')
goto literal;
again: switch (c = *fmt++) {
case '%': /* "%%" is converted to "%". */
literal:
if (c != *bp++)
return NULL;
LEGAL_ALT(0);
continue;
/*
* "Alternative" modifiers. Just set the appropriate flag
* and start over again.
*/
case 'E': /* "%E?" alternative conversion modifier. */
LEGAL_ALT(0);
alt_format |= ALT_E;
goto again;
case 'O': /* "%O?" alternative conversion modifier. */
LEGAL_ALT(0);
alt_format |= ALT_O;
goto again;
/*
* "Complex" conversion rules, implemented through recursion.
*/
case 'c': /* Date and time, using the locale's format. */
new_fmt = _ctloc(d_t_fmt);
goto recurse;
case 'D': /* The date as "%m/%d/%y". */
new_fmt = "%m/%d/%y";
LEGAL_ALT(0);
goto recurse;
case 'R': /* The time as "%H:%M". */
new_fmt = "%H:%M";
LEGAL_ALT(0);
goto recurse;
case 'r': /* The time in 12-hour clock representation. */
new_fmt =_ctloc(t_fmt_ampm);
LEGAL_ALT(0);
goto recurse;
case 'T': /* The time as "%H:%M:%S". */
new_fmt = "%H:%M:%S";
LEGAL_ALT(0);
goto recurse;
case 'X': /* The time, using the locale's format. */
new_fmt =_ctloc(t_fmt);
goto recurse;
case 'x': /* The date, using the locale's format. */
new_fmt =_ctloc(d_fmt);
recurse:
bp = (const u_char *)strptime((const char *)bp,
new_fmt, tm);
LEGAL_ALT(ALT_E);
continue;
/*
* "Elementary" conversion rules.
*/
case 'A': /* The day of week, using the locale's form. */
case 'a':
bp = find_string(bp, &tm->tm_wday, _ctloc(day),
_ctloc(abday), 7);
LEGAL_ALT(0);
continue;
case 'B': /* The month, using the locale's form. */
case 'b':
case 'h':
bp = find_string(bp, &tm->tm_mon, _ctloc(mon),
_ctloc(abmon), 12);
LEGAL_ALT(0);
continue;
case 'C': /* The century number. */
i = 20;
bp = conv_num(bp, &i, 0, 99);
i = i * 100 - TM_YEAR_BASE;
if (split_year)
i += tm->tm_year % 100;
split_year = 1;
tm->tm_year = i;
LEGAL_ALT(ALT_E);
continue;
case 'd': /* The day of month. */
case 'e':
bp = conv_num(bp, &tm->tm_mday, 1, 31);
LEGAL_ALT(ALT_O);
continue;
case 'k': /* The hour (24-hour clock representation). */
LEGAL_ALT(0);
/* FALLTHROUGH */
case 'H':
bp = conv_num(bp, &tm->tm_hour, 0, 23);
LEGAL_ALT(ALT_O);
continue;
case 'l': /* The hour (12-hour clock representation). */
LEGAL_ALT(0);
/* FALLTHROUGH */
case 'I':
bp = conv_num(bp, &tm->tm_hour, 1, 12);
if (tm->tm_hour == 12)
tm->tm_hour = 0;
LEGAL_ALT(ALT_O);
continue;
case 'j': /* The day of year. */
i = 1;
bp = conv_num(bp, &i, 1, 366);
tm->tm_yday = i - 1;
LEGAL_ALT(0);
continue;
case 'M': /* The minute. */
bp = conv_num(bp, &tm->tm_min, 0, 59);
LEGAL_ALT(ALT_O);
continue;
case 'm': /* The month. */
i = 1;
bp = conv_num(bp, &i, 1, 12);
tm->tm_mon = i - 1;
LEGAL_ALT(ALT_O);
continue;
case 'p': /* The locale's equivalent of AM/PM. */
bp = find_string(bp, &i, _ctloc(am_pm), NULL, 2);
if (tm->tm_hour > 11)
return NULL;
tm->tm_hour += i * 12;
LEGAL_ALT(0);
continue;
case 'S': /* The seconds. */
bp = conv_num(bp, &tm->tm_sec, 0, 61);
LEGAL_ALT(ALT_O);
continue;
case 'U': /* The week of year, beginning on sunday. */
case 'W': /* The week of year, beginning on monday. */
/*
* XXX This is bogus, as we can not assume any valid
* information present in the tm structure at this
* point to calculate a real value, so just check the
* range for now.
*/
bp = conv_num(bp, &i, 0, 53);
LEGAL_ALT(ALT_O);
continue;
case 'w': /* The day of week, beginning on sunday. */
bp = conv_num(bp, &tm->tm_wday, 0, 6);
LEGAL_ALT(ALT_O);
continue;
case 'Y': /* The year. */
i = TM_YEAR_BASE; /* just for data sanity... */
bp = conv_num(bp, &i, 0, 9999);
tm->tm_year = i - TM_YEAR_BASE;
LEGAL_ALT(ALT_E);
continue;
case 'y': /* The year within 100 years of the epoch. */
/* LEGAL_ALT(ALT_E | ALT_O); */
bp = conv_num(bp, &i, 0, 99);
if (split_year)
/* preserve century */
i += (tm->tm_year / 100) * 100;
else {
split_year = 1;
if (i <= 68)
i = i + 2000 - TM_YEAR_BASE;
else
i = i + 1900 - TM_YEAR_BASE;
}
tm->tm_year = i;
continue;
/*
* Miscellaneous conversions.
*/
case 'n': /* Any kind of white-space. */
case 't':
while (isspace(*bp))
bp++;
LEGAL_ALT(0);
continue;
default: /* Unknown/unsupported conversion. */
return NULL;
}
}
return __UNCONST(bp);
}
static const u_char *
conv_num(const unsigned char *buf, int *dest, uint llim, uint ulim)
{
uint result = 0;
unsigned char ch;
/* The limit also determines the number of valid digits. */
uint rulim = ulim;
ch = *buf;
if (ch < '0' || ch > '9')
return NULL;
do {
result *= 10;
result += ch - '0';
rulim /= 10;
ch = *++buf;
} while ((result * 10 <= ulim) && rulim && ch >= '0' && ch <= '9');
if (result < llim || result > ulim)
return NULL;
*dest = result;
return buf;
}
static const u_char *
find_string(const u_char *bp, int *tgt, const char * const *n1,
const char * const *n2, int c)
{
int i;
size_t len;
/* check full name - then abbreviated ones */
for (; n1 != NULL; n1 = n2, n2 = NULL) {
for (i = 0; i < c; i++, n1++) {
len = strlen(*n1);
if (StringUtils::CompareNoCase(*n1, (const char*)bp, len) == 0)
{
*tgt = i;
return bp + len;
}
}
}
/* Nothing matched */
return NULL;
}
}
#ifdef TARGET_WINDOWS_DESKTOP
LONG CWIN32Util::UtilRegGetValue( const HKEY hKey, const char *const pcKey, DWORD *const pdwType, char **const ppcBuffer, DWORD *const pdwSizeBuff, const DWORD dwSizeAdd )
{
using KODI::PLATFORM::WINDOWS::ToW;
auto pcKeyW = ToW(pcKey);
DWORD dwSize;
LONG lRet= RegQueryValueEx(hKey, pcKeyW.c_str(), nullptr, pdwType, nullptr, &dwSize );
if (lRet == ERROR_SUCCESS)
{
if (ppcBuffer)
{
char *pcValue=*ppcBuffer, *pcValueTmp;
if (!pcValue || !pdwSizeBuff || dwSize +dwSizeAdd > *pdwSizeBuff) {
pcValueTmp = static_cast<char*>(realloc(pcValue, dwSize + dwSizeAdd));
if(pcValueTmp != nullptr)
{
pcValue = pcValueTmp;
}
}
lRet= RegQueryValueEx(hKey, pcKeyW.c_str(), nullptr, nullptr, reinterpret_cast<LPBYTE>(pcValue), &dwSize);
if ( lRet == ERROR_SUCCESS || *ppcBuffer )
*ppcBuffer= pcValue;
else
free( pcValue );
}
if (pdwSizeBuff) *pdwSizeBuff= dwSize +dwSizeAdd;
}
return lRet;
}
bool CWIN32Util::UtilRegOpenKeyEx( const HKEY hKeyParent, const char *const pcKey, const REGSAM rsAccessRights, HKEY *hKey, const bool bReadX64 )
{
using KODI::PLATFORM::WINDOWS::ToW;
const REGSAM rsAccessRightsTmp = (
CSysInfo::GetKernelBitness() == 64 ? rsAccessRights |
( bReadX64 ? KEY_WOW64_64KEY : KEY_WOW64_32KEY ) : rsAccessRights );
bool bRet = ( ERROR_SUCCESS == RegOpenKeyEx(hKeyParent, ToW(pcKey).c_str(), 0, rsAccessRightsTmp, hKey));
return bRet;
}
// Retrieve the filename of the process that currently has the focus.
// Typically this will be some process using the system tray grabbing
// the focus and causing XBMC to minimise. Logging the offending
// process name can help the user fix the problem.
bool CWIN32Util::GetFocussedProcess(std::string &strProcessFile)
{
using KODI::PLATFORM::WINDOWS::FromW;
strProcessFile = "";
// Get the window that has the focus
HWND hfocus = GetForegroundWindow();
if (!hfocus)
return false;
// Get the process ID from the window handle
DWORD pid = 0;
GetWindowThreadProcessId(hfocus, &pid);
// Use OpenProcess to get the process handle from the process ID
HANDLE hproc = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, pid);
if (!hproc)
return false;
// Load QueryFullProcessImageName dynamically because it isn't available
// in all versions of Windows.
wchar_t procfile[MAX_PATH+1];
DWORD procfilelen = MAX_PATH;
if (QueryFullProcessImageNameW(hproc, 0, procfile, &procfilelen))
strProcessFile = FromW(procfile);
CloseHandle(hproc);
return true;
}
#endif
// Adjust the src rectangle so that the dst is always contained in the target rectangle.
void CWIN32Util::CropSource(CRect& src, CRect& dst, CRect target, UINT rotation /* = 0 */)
{
float s_width = src.Width(), s_height = src.Height();
float d_width = dst.Width(), d_height = dst.Height();
if (dst.x1 < target.x1)
{
switch (rotation)
{
case 90:
src.y1 -= (dst.x1 - target.x1) * s_height / d_width;
break;
case 180:
src.x2 += (dst.x1 - target.x1) * s_width / d_width;
break;
case 270:
src.y2 += (dst.x1 - target.x1) * s_height / d_width;
break;
default:
src.x1 -= (dst.x1 - target.x1) * s_width / d_width;
break;
}
dst.x1 = target.x1;
}
if(dst.y1 < target.y1)
{
switch (rotation)
{
case 90:
src.x1 -= (dst.y1 - target.y1) * s_width / d_height;
break;
case 180:
src.y2 += (dst.y1 - target.y1) * s_height / d_height;
break;
case 270:
src.x2 += (dst.y1 - target.y1) * s_width / d_height;
break;
default:
src.y1 -= (dst.y1 - target.y1) * s_height / d_height;
break;
}
dst.y1 = target.y1;
}
if(dst.x2 > target.x2)
{
switch (rotation)
{
case 90:
src.y2 -= (dst.x2 - target.x2) * s_height / d_width;
break;
case 180:
src.x1 += (dst.x2 - target.x2) * s_width / d_width;
break;
case 270:
src.y1 += (dst.x2 - target.x2) * s_height / d_width;
break;
default:
src.x2 -= (dst.x2 - target.x2) * s_width / d_width;
break;
}
dst.x2 = target.x2;
}
if(dst.y2 > target.y2)
{
switch (rotation)
{
case 90:
src.x2 -= (dst.y2 - target.y2) * s_width / d_height;
break;
case 180:
src.y1 += (dst.y2 - target.y2) * s_height / d_height;
break;
case 270:
src.x1 += (dst.y2 - target.y2) * s_width / d_height;
break;
default:
src.y2 -= (dst.y2 - target.y2) * s_height / d_height;
break;
}
dst.y2 = target.y2;
}
// Callers expect integer coordinates.
src.x1 = floor(src.x1);
src.y1 = floor(src.y1);
src.x2 = ceil(src.x2);
src.y2 = ceil(src.y2);
dst.x1 = floor(dst.x1);
dst.y1 = floor(dst.y1);
dst.x2 = ceil(dst.x2);
dst.y2 = ceil(dst.y2);
}
// detect if a drive is a usb device
// code taken from http://banderlogi.blogspot.com/2011/06/enum-drive-letters-attached-for-usb.html
bool CWIN32Util::IsUsbDevice(const std::wstring &strWdrive)
{
if (strWdrive.size() < 2)
return false;
#ifdef TARGET_WINDOWS_STORE
bool result = false;
auto removables = winrt::Windows::Storage::KnownFolders::RemovableDevices();
auto vector = Wait(removables.GetFoldersAsync());
auto strdrive = KODI::PLATFORM::WINDOWS::FromW(strWdrive);
for (auto& device : vector)
{
auto path = KODI::PLATFORM::WINDOWS::FromW(device.Path().c_str());
if (StringUtils::StartsWith(path, strdrive))
{
// looks like drive is removable
result = true;
}
}
return false;
#else
std::wstring strWDevicePath = StringUtils::Format(L"\\\\.\\%s",strWdrive.substr(0, 2).c_str());
HANDLE deviceHandle = CreateFileW(
strWDevicePath.c_str(),
0, // no access to the drive
FILE_SHARE_READ | // share mode
FILE_SHARE_WRITE,
NULL, // default security attributes
OPEN_EXISTING, // disposition
0, // file attributes
NULL); // do not copy file attributes
if(deviceHandle == INVALID_HANDLE_VALUE)
return false;
// setup query
STORAGE_PROPERTY_QUERY query;
memset(&query, 0, sizeof(query));
query.PropertyId = StorageDeviceProperty;
query.QueryType = PropertyStandardQuery;
// issue query
DWORD bytes;
STORAGE_DEVICE_DESCRIPTOR devd;
STORAGE_BUS_TYPE busType = BusTypeUnknown;
if (DeviceIoControl(deviceHandle,
IOCTL_STORAGE_QUERY_PROPERTY,
&query, sizeof(query),
&devd, sizeof(devd),
&bytes, NULL))
{
busType = devd.BusType;
}
CloseHandle(deviceHandle);
return BusTypeUsb == busType;
#endif
}
std::string CWIN32Util::WUSysMsg(DWORD dwError)
{
#define SS_DEFLANGID MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT)
CHAR szBuf[512];
if ( 0 != ::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError,
SS_DEFLANGID, szBuf, 511, NULL) )
return StringUtils::Format("%s (0x%X)", szBuf, dwError);
else
return StringUtils::Format("Unknown error (0x%X)", dwError);
}
bool CWIN32Util::SetThreadLocalLocale(bool enable /* = true */)
{
const int param = enable ? _ENABLE_PER_THREAD_LOCALE : _DISABLE_PER_THREAD_LOCALE;
return _configthreadlocale(param) != -1;
}
HDR_STATUS CWIN32Util::ToggleWindowsHDR(DXGI_MODE_DESC& modeDesc)
{
HDR_STATUS status = HDR_STATUS::HDR_TOGGLE_FAILED;
#ifdef TARGET_WINDOWS_STORE
auto hdmiDisplayInfo = HdmiDisplayInformation::GetForCurrentView();
if (hdmiDisplayInfo == nullptr)
return status;
auto current = hdmiDisplayInfo.GetCurrentDisplayMode();
auto newColorSp = (current.ColorSpace() == HdmiDisplayColorSpace::BT2020)
? HdmiDisplayColorSpace::BT709
: HdmiDisplayColorSpace::BT2020;
auto modes = hdmiDisplayInfo.GetSupportedDisplayModes();
// Browse over all modes available like the current (resolution and refresh)
// but reciprocals HDR (color space and transfer).
// NOTE: transfer for HDR is here "fake HDR" (EotfSdr) to be
// able render SRD content with HDR ON, same as Windows HDR switch does.
// GUI-skin is SDR. The real HDR mode is activated later when playback begins.
for (const auto& mode : modes)
{
if (mode.ColorSpace() == newColorSp &&
mode.ResolutionHeightInRawPixels() == current.ResolutionHeightInRawPixels() &&
mode.ResolutionWidthInRawPixels() == current.ResolutionWidthInRawPixels() &&
mode.StereoEnabled() == false && fabs(mode.RefreshRate() - current.RefreshRate()) < 0.0001)
{
if (current.ColorSpace() == HdmiDisplayColorSpace::BT2020) // HDR is ON
{
CLog::LogF(LOGINFO, "Toggle Windows HDR Off (ON => OFF).");
if (Wait(hdmiDisplayInfo.RequestSetCurrentDisplayModeAsync(mode,
HdmiDisplayHdrOption::None)))
status = HDR_STATUS::HDR_OFF;
}
else // HDR is OFF
{
CLog::LogF(LOGINFO, "Toggle Windows HDR On (OFF => ON).");
if (Wait(hdmiDisplayInfo.RequestSetCurrentDisplayModeAsync(mode,
HdmiDisplayHdrOption::EotfSdr)))
status = HDR_STATUS::HDR_ON;
}
break;
}
}
#else
uint32_t pathCount = 0;
uint32_t modeCount = 0;
MONITORINFOEXW mi = {};
mi.cbSize = sizeof(mi);
GetMonitorInfoW(MonitorFromWindow(g_hWnd, MONITOR_DEFAULTTOPRIMARY), &mi);
const std::wstring deviceNameW = mi.szDevice;
if (ERROR_SUCCESS == GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &pathCount, &modeCount))
{
std::vector<DISPLAYCONFIG_PATH_INFO> paths(pathCount);
std::vector<DISPLAYCONFIG_MODE_INFO> modes(modeCount);
if (ERROR_SUCCESS == QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &pathCount, paths.data(),
&modeCount, modes.data(), nullptr))
{
DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO getColorInfo = {};
getColorInfo.header.type = DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO;
getColorInfo.header.size = sizeof(getColorInfo);
DISPLAYCONFIG_SET_ADVANCED_COLOR_STATE setColorState = {};
setColorState.header.type = DISPLAYCONFIG_DEVICE_INFO_SET_ADVANCED_COLOR_STATE;
setColorState.header.size = sizeof(setColorState);
DISPLAYCONFIG_SOURCE_DEVICE_NAME getSourceName = {};
getSourceName.header.type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME;
getSourceName.header.size = sizeof(getSourceName);
// Only try to toggle display currently used by Kodi
for (const auto& path : paths)
{
getSourceName.header.adapterId.HighPart = path.sourceInfo.adapterId.HighPart;
getSourceName.header.adapterId.LowPart = path.sourceInfo.adapterId.LowPart;
getSourceName.header.id = path.sourceInfo.id;
if (ERROR_SUCCESS == DisplayConfigGetDeviceInfo(&getSourceName.header))
{
const std::wstring sourceNameW = getSourceName.viewGdiDeviceName;
if (deviceNameW == sourceNameW)
{
const auto& mode = modes.at(path.targetInfo.modeInfoIdx);
getColorInfo.header.adapterId.HighPart = mode.adapterId.HighPart;
getColorInfo.header.adapterId.LowPart = mode.adapterId.LowPart;
getColorInfo.header.id = mode.id;
setColorState.header.adapterId.HighPart = mode.adapterId.HighPart;
setColorState.header.adapterId.LowPart = mode.adapterId.LowPart;
setColorState.header.id = mode.id;
if (ERROR_SUCCESS == DisplayConfigGetDeviceInfo(&getColorInfo.header))
{
if (getColorInfo.advancedColorSupported)
{
if (getColorInfo.advancedColorEnabled) // HDR is ON
{
setColorState.enableAdvancedColor = FALSE;
status = HDR_STATUS::HDR_OFF;
CLog::LogF(LOGINFO, "Toggle Windows HDR Off (ON => OFF).");
}
else // HDR is OFF
{
setColorState.enableAdvancedColor = TRUE;
status = HDR_STATUS::HDR_ON;
CLog::LogF(LOGINFO, "Toggle Windows HDR On (OFF => ON).");
}
if (ERROR_SUCCESS != DisplayConfigSetDeviceInfo(&setColorState.header))
status = HDR_STATUS::HDR_TOGGLE_FAILED;
}
}
break;
}
}
}
}
}
// Restores previous graphics mode before toggle HDR
if (status != HDR_STATUS::HDR_TOGGLE_FAILED && modeDesc.RefreshRate.Denominator != 0)
{
float fps = static_cast<float>(modeDesc.RefreshRate.Numerator) /
static_cast<float>(modeDesc.RefreshRate.Denominator);
int32_t est;
DEVMODEW devmode = {};
devmode.dmSize = sizeof(devmode);
devmode.dmPelsWidth = modeDesc.Width;
devmode.dmPelsHeight = modeDesc.Height;
devmode.dmDisplayFrequency = static_cast<uint32_t>(fps);
if (modeDesc.ScanlineOrdering &&
modeDesc.ScanlineOrdering != DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE)
devmode.dmDisplayFlags = DM_INTERLACED;
devmode.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY | DM_DISPLAYFLAGS;
est = ChangeDisplaySettingsExW(deviceNameW.c_str(), &devmode, nullptr, CDS_FULLSCREEN, nullptr);
if (est == DISP_CHANGE_SUCCESSFUL)
CLog::LogF(LOGDEBUG, "Previous graphics mode restored OK");
else
CLog::LogF(LOGERROR, "Previous graphics mode cannot be restored (error# {})", est);
}
#endif
return status;
}
HDR_STATUS CWIN32Util::GetWindowsHDRStatus()
{
bool advancedColorSupported = false;
bool advancedColorEnabled = false;
HDR_STATUS status = HDR_STATUS::HDR_UNSUPPORTED;
#ifdef TARGET_WINDOWS_STORE
auto displayInformation = DisplayInformation::GetForCurrentView();
if (displayInformation)
{
auto advancedColorInfo = displayInformation.GetAdvancedColorInfo();
if (advancedColorInfo)
{
if (advancedColorInfo.CurrentAdvancedColorKind() == AdvancedColorKind::HighDynamicRange)
{
advancedColorSupported = true;
advancedColorEnabled = true;
}
}
}
// Try to find out if the display supports HDR even if Windows HDR switch is OFF
if (!advancedColorEnabled)
{
auto displayManager = DisplayManager::Create(DisplayManagerOptions::None);
if (displayManager)
{
auto targets = displayManager.GetCurrentTargets();
for (const auto& target : targets)
{
if (target.IsConnected())
{
auto displayMonitor = target.TryGetMonitor();
if (displayMonitor.MaxLuminanceInNits() >= 400.0f)
{
advancedColorSupported = true;
break;
}
}
}
displayManager.Close();
}
}
#else
uint32_t pathCount = 0;
uint32_t modeCount = 0;
MONITORINFOEXW mi = {};
mi.cbSize = sizeof(mi);
GetMonitorInfoW(MonitorFromWindow(g_hWnd, MONITOR_DEFAULTTOPRIMARY), &mi);
const std::wstring deviceNameW = mi.szDevice;
if (ERROR_SUCCESS == GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &pathCount, &modeCount))
{
std::vector<DISPLAYCONFIG_PATH_INFO> paths(pathCount);
std::vector<DISPLAYCONFIG_MODE_INFO> modes(modeCount);
if (ERROR_SUCCESS == QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &pathCount, paths.data(),
&modeCount, modes.data(), 0))
{
DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO getColorInfo = {};
getColorInfo.header.type = DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO;
getColorInfo.header.size = sizeof(getColorInfo);
DISPLAYCONFIG_SOURCE_DEVICE_NAME getSourceName = {};
getSourceName.header.type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME;
getSourceName.header.size = sizeof(getSourceName);
for (const auto& path : paths)
{
getSourceName.header.adapterId.HighPart = path.sourceInfo.adapterId.HighPart;
getSourceName.header.adapterId.LowPart = path.sourceInfo.adapterId.LowPart;
getSourceName.header.id = path.sourceInfo.id;
if (ERROR_SUCCESS == DisplayConfigGetDeviceInfo(&getSourceName.header))
{
const std::wstring sourceNameW = getSourceName.viewGdiDeviceName;
if (g_hWnd == nullptr || deviceNameW == sourceNameW)
{
const auto& mode = modes.at(path.targetInfo.modeInfoIdx);
getColorInfo.header.adapterId.HighPart = mode.adapterId.HighPart;
getColorInfo.header.adapterId.LowPart = mode.adapterId.LowPart;
getColorInfo.header.id = mode.id;
if (ERROR_SUCCESS == DisplayConfigGetDeviceInfo(&getColorInfo.header))
{
if (getColorInfo.advancedColorEnabled)
advancedColorEnabled = true;
if (getColorInfo.advancedColorSupported)
advancedColorSupported = true;
}
if (g_hWnd != nullptr)
break;
}
}
}
}
}
#endif
if (!advancedColorSupported)
{
status = HDR_STATUS::HDR_UNSUPPORTED;
if (CServiceBroker::IsServiceManagerUp())
CLog::LogF(LOGDEBUG, "Display is not HDR capable or cannot be detected");
}
else
{
status = advancedColorEnabled ? HDR_STATUS::HDR_ON : HDR_STATUS::HDR_OFF;
if (CServiceBroker::IsServiceManagerUp())
CLog::LogF(LOGDEBUG, "Display HDR capable and current HDR status is {}",
advancedColorEnabled ? "ON" : "OFF");
}
return status;
}
| scbash/xbmc | xbmc/platform/win32/WIN32Util.cpp | C++ | gpl-2.0 | 45,687 |
<?php
global $wpdb;
if (!defined('ABSPATH')) {
require_once '../../../../wp-load.php';
}
list($email_id, $user_id) = explode(';', base64_decode($_GET['r']), 2);
$wpdb->insert(NEWSLETTER_STATS_TABLE, array(
'email_id' => $email_id,
'user_id' => $user_id,
'ip' => $_SERVER['REMOTE_ADDR']
)
);
header('Content-Type: image/gif');
echo base64_decode('_R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
die();
| phucanh92/vietlong | wp-content/plugins/newsletter/statistics/open.php | PHP | gpl-2.0 | 442 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 AlgorithmX2
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package appeng.api.networking.energy;
import appeng.api.config.AccessRestriction;
import appeng.api.config.Actionable;
/**
* Used to access information about AE's various power accepting blocks for monitoring purposes.
*/
public interface IAEPowerStorage extends IEnergySource
{
/**
* Inject amt, power into the device, it will store what it can, and return the amount unable to be stored.
*
* @param amt to be injected amount
* @param mode action mode
*
* @return amount of power which was unable to be stored
*/
public double injectAEPower(double amt, Actionable mode);
/**
* @return the current maximum power ( this can change :P )
*/
public double getAEMaxPower();
/**
* @return the current AE Power Level, this may exceed getMEMaxPower()
*/
public double getAECurrentPower();
/**
* Checked on network reset to see if your block can be used as a public power storage ( use getPowerFlow to control
* the behavior )
*
* @return true if it can be used as a public power storage
*/
public boolean isAEPublicPowerStorage();
/**
* Control the power flow by telling what the network can do, either add? or subtract? or both!
*
* @return access restriction what the network can do
*/
public AccessRestriction getPowerFlow();
} | Vexatos/PeripheralsPlusPlus | src/api/java/appeng/api/networking/energy/IAEPowerStorage.java | Java | gpl-2.0 | 2,432 |
// Copyright 2008 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
// Additional copyrights go to Duddie (c) 2005 (duddie@walla.com)
#include "Core/DSP/DSPTables.h"
#include <algorithm>
#include <array>
#include <cstddef>
#include "Common/CommonTypes.h"
#include "Common/Logging/Log.h"
#include "Core/DSP/Interpreter/DSPIntTables.h"
namespace DSP
{
// clang-format off
const std::array<DSPOPCTemplate, 214> s_opcodes =
{{
// # of parameters----+ {type, size, loc, lshift, mask} branch reads PC // instruction approximation
// name opcode mask size-V V param 1 param 2 param 3 extendable uncond. updates SR
{"NOP", 0x0000, 0xfffc, 1, 0, {}, false, false, false, false, false}, // no operation
{"DAR", 0x0004, 0xfffc, 1, 1, {{P_REG, 1, 0, 0, 0x0003}}, false, false, false, false, false}, // $arD--
{"IAR", 0x0008, 0xfffc, 1, 1, {{P_REG, 1, 0, 0, 0x0003}}, false, false, false, false, false}, // $arD++
{"SUBARN", 0x000c, 0xfffc, 1, 1, {{P_REG, 1, 0, 0, 0x0003}}, false, false, false, false, false}, // $arD -= $ixS
{"ADDARN", 0x0010, 0xfff0, 1, 2, {{P_REG, 1, 0, 0, 0x0003}, {P_REG04, 1, 0, 2, 0x000c}}, false, false, false, false, false}, // $arD += $ixS
{"HALT", 0x0021, 0xffff, 1, 0, {}, false, true, true, false, false}, // halt until reset
{"RETGE", 0x02d0, 0xffff, 1, 0, {}, false, true, false, true, false}, // return if greater or equal
{"RETL", 0x02d1, 0xffff, 1, 0, {}, false, true, false, true, false}, // return if less
{"RETG", 0x02d2, 0xffff, 1, 0, {}, false, true, false, true, false}, // return if greater
{"RETLE", 0x02d3, 0xffff, 1, 0, {}, false, true, false, true, false}, // return if less or equal
{"RETNZ", 0x02d4, 0xffff, 1, 0, {}, false, true, false, true, false}, // return if not zero
{"RETZ", 0x02d5, 0xffff, 1, 0, {}, false, true, false, true, false}, // return if zero
{"RETNC", 0x02d6, 0xffff, 1, 0, {}, false, true, false, true, false}, // return if not carry
{"RETC", 0x02d7, 0xffff, 1, 0, {}, false, true, false, true, false}, // return if carry
{"RETx8", 0x02d8, 0xffff, 1, 0, {}, false, true, false, true, false}, // return if TODO
{"RETx9", 0x02d9, 0xffff, 1, 0, {}, false, true, false, true, false}, // return if TODO
{"RETxA", 0x02da, 0xffff, 1, 0, {}, false, true, false, true, false}, // return if TODO
{"RETxB", 0x02db, 0xffff, 1, 0, {}, false, true, false, true, false}, // return if TODO
{"RETLNZ", 0x02dc, 0xffff, 1, 0, {}, false, true, false, true, false}, // return if logic not zero
{"RETLZ", 0x02dd, 0xffff, 1, 0, {}, false, true, false, true, false}, // return if logic zero
{"RETO", 0x02de, 0xffff, 1, 0, {}, false, true, false, true, false}, // return if overflow
{"RET", 0x02df, 0xffff, 1, 0, {}, false, true, true, false, false}, // unconditional return
{"RTI", 0x02ff, 0xffff, 1, 0, {}, false, true, true, false, false}, // return from interrupt
{"CALLGE", 0x02b0, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // call if greater or equal
{"CALLL", 0x02b1, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // call if less
{"CALLG", 0x02b2, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // call if greater
{"CALLLE", 0x02b3, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // call if less or equal
{"CALLNZ", 0x02b4, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // call if not zero
{"CALLZ", 0x02b5, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // call if zero
{"CALLNC", 0x02b6, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // call if not carry
{"CALLC", 0x02b7, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // call if carry
{"CALLx8", 0x02b8, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // call if TODO
{"CALLx9", 0x02b9, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // call if TODO
{"CALLxA", 0x02ba, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // call if TODO
{"CALLxB", 0x02bb, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // call if TODO
{"CALLLNZ", 0x02bc, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // call if logic not zero
{"CALLLZ", 0x02bd, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // call if logic zero
{"CALLO", 0x02be, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // call if overflow
{"CALL", 0x02bf, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, true, true, false}, // unconditional call
{"IFGE", 0x0270, 0xffff, 1, 0, {}, false, true, false, true, false}, // if greater or equal
{"IFL", 0x0271, 0xffff, 1, 0, {}, false, true, false, true, false}, // if less
{"IFG", 0x0272, 0xffff, 1, 0, {}, false, true, false, true, false}, // if greater
{"IFLE", 0x0273, 0xffff, 1, 0, {}, false, true, false, true, false}, // if less or equal
{"IFNZ", 0x0274, 0xffff, 1, 0, {}, false, true, false, true, false}, // if not zero
{"IFZ", 0x0275, 0xffff, 1, 0, {}, false, true, false, true, false}, // if zero
{"IFNC", 0x0276, 0xffff, 1, 0, {}, false, true, false, true, false}, // if not carry
{"IFC", 0x0277, 0xffff, 1, 0, {}, false, true, false, true, false}, // if carry
{"IFx8", 0x0278, 0xffff, 1, 0, {}, false, true, false, true, false}, // if TODO
{"IFx9", 0x0279, 0xffff, 1, 0, {}, false, true, false, true, false}, // if TODO
{"IFxA", 0x027a, 0xffff, 1, 0, {}, false, true, false, true, false}, // if TODO
{"IFxB", 0x027b, 0xffff, 1, 0, {}, false, true, false, true, false}, // if TODO
{"IFLNZ", 0x027c, 0xffff, 1, 0, {}, false, true, false, true, false}, // if logic not zero
{"IFLZ", 0x027d, 0xffff, 1, 0, {}, false, true, false, true, false}, // if logic zero
{"IFO", 0x027e, 0xffff, 1, 0, {}, false, true, false, true, false}, // if overflow
{"IF", 0x027f, 0xffff, 1, 0, {}, false, true, true, true, false}, // what is this, I don't even...
{"JGE", 0x0290, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // jump if greater or equal
{"JL", 0x0291, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // jump if less
{"JG", 0x0292, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // jump if greater
{"JLE", 0x0293, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // jump if less or equal
{"JNZ", 0x0294, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // jump if not zero
{"JZ", 0x0295, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // jump if zero
{"JNC", 0x0296, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // jump if not carry
{"JC", 0x0297, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // jump if carry
{"JMPx8", 0x0298, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // jump if TODO
{"JMPx9", 0x0299, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // jump if TODO
{"JMPxA", 0x029a, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // jump if TODO
{"JMPxB", 0x029b, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // jump if TODO
{"JLNZ", 0x029c, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // jump if logic not zero
{"JLZ", 0x029d, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // jump if logic zero
{"JO", 0x029e, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, false, true, false}, // jump if overflow
{"JMP", 0x029f, 0xffff, 2, 1, {{P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, true, true, false}, // unconditional jump
{"JRGE", 0x1700, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, false, false}, // jump to $R if greater or equal
{"JRL", 0x1701, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, false, false}, // jump to $R if less
{"JRG", 0x1702, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, false, false}, // jump to $R if greater
{"JRLE", 0x1703, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, false, false}, // jump to $R if less or equal
{"JRNZ", 0x1704, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, false, false}, // jump to $R if not zero
{"JRZ", 0x1705, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, false, false}, // jump to $R if zero
{"JRNC", 0x1706, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, false, false}, // jump to $R if not carry
{"JRC", 0x1707, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, false, false}, // jump to $R if carry
{"JMPRx8", 0x1708, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, false, false}, // jump to $R if TODO
{"JMPRx9", 0x1709, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, false, false}, // jump to $R if TODO
{"JMPRxA", 0x170a, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, false, false}, // jump to $R if TODO
{"JMPRxB", 0x170b, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, false, false}, // jump to $R if TODO
{"JRLNZ", 0x170c, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, false, false}, // jump to $R if logic not zero
{"JRLZ", 0x170d, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, false, false}, // jump to $R if logic zero
{"JRO", 0x170e, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, false, false}, // jump to $R if overflow
{"JMPR", 0x170f, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, true, false, false}, // jump to $R
{"CALLRGE", 0x1710, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, true, false}, // call $R if greater or equal
{"CALLRL", 0x1711, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, true, false}, // call $R if less
{"CALLRG", 0x1712, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, true, false}, // call $R if greater
{"CALLRLE", 0x1713, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, true, false}, // call $R if less or equal
{"CALLRNZ", 0x1714, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, true, false}, // call $R if not zero
{"CALLRZ", 0x1715, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, true, false}, // call $R if zero
{"CALLRNC", 0x1716, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, true, false}, // call $R if not carry
{"CALLRC", 0x1717, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, true, false}, // call $R if carry
{"CALLRx8", 0x1718, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, true, false}, // call $R if TODO
{"CALLRx9", 0x1719, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, true, false}, // call $R if TODO
{"CALLRxA", 0x171a, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, true, false}, // call $R if TODO
{"CALLRxB", 0x171b, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, true, false}, // call $R if TODO
{"CALLRLNZ", 0x171c, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, true, false}, // call $R if logic not zero
{"CALLRLZ", 0x171d, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, true, false}, // call $R if logic zero
{"CALLRO", 0x171e, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, false, true, false}, // call $R if overflow
{"CALLR", 0x171f, 0xff1f, 1, 1, {{P_REG, 1, 0, 5, 0x00e0}}, false, true, true, true, false}, // call $R
{"SBCLR", 0x1200, 0xff00, 1, 1, {{P_IMM, 1, 0, 0, 0x0007}}, false, false, false, false, false}, // $sr &= ~(I + 6)
{"SBSET", 0x1300, 0xff00, 1, 1, {{P_IMM, 1, 0, 0, 0x0007}}, false, false, false, false, false}, // $sr |= (I + 6)
{"LSL", 0x1400, 0xfec0, 1, 2, {{P_ACC, 1, 0, 8, 0x0100}, {P_IMM, 1, 0, 0, 0x003f}}, false, false, false, false, true}, // $acR <<= I
{"LSR", 0x1440, 0xfec0, 1, 2, {{P_ACC, 1, 0, 8, 0x0100}, {P_IMM, 1, 0, 0, 0x003f}}, false, false, false, false, true}, // $acR >>= I (shifting in zeros)
{"ASL", 0x1480, 0xfec0, 1, 2, {{P_ACC, 1, 0, 8, 0x0100}, {P_IMM, 1, 0, 0, 0x003f}}, false, false, false, false, true}, // $acR <<= I
{"ASR", 0x14c0, 0xfec0, 1, 2, {{P_ACC, 1, 0, 8, 0x0100}, {P_IMM, 1, 0, 0, 0x003f}}, false, false, false, false, true}, // $acR >>= I (shifting in sign bits)
// these two were discovered by ector
{"LSRN", 0x02ca, 0xffff, 1, 0, {}, false, false, false, false, true}, // $ac0 >>=/<<= $ac1.m[0-6]
{"ASRN", 0x02cb, 0xffff, 1, 0, {}, false, false, false, false, true}, // $ac0 >>=/<<= $ac1.m[0-6] (arithmetic)
{"LRI", 0x0080, 0xffe0, 2, 2, {{P_REG, 1, 0, 0, 0x001f}, {P_IMM, 2, 1, 0, 0xffff}}, false, false, false, true, false}, // $D = I
{"LR", 0x00c0, 0xffe0, 2, 2, {{P_REG, 1, 0, 0, 0x001f}, {P_MEM, 2, 1, 0, 0xffff}}, false, false, false, true, false}, // $D = MEM[M]
{"SR", 0x00e0, 0xffe0, 2, 2, {{P_MEM, 2, 1, 0, 0xffff}, {P_REG, 1, 0, 0, 0x001f}}, false, false, false, true, false}, // MEM[M] = $S
{"MRR", 0x1c00, 0xfc00, 1, 2, {{P_REG, 1, 0, 5, 0x03e0}, {P_REG, 1, 0, 0, 0x001f}}, false, false, false, false, false}, // $D = $S
{"SI", 0x1600, 0xff00, 2, 2, {{P_MEM, 1, 0, 0, 0x00ff}, {P_IMM, 2, 1, 0, 0xffff}}, false, false, false, true, false}, // MEM[M] = I
{"ADDIS", 0x0400, 0xfe00, 1, 2, {{P_ACCM, 1, 0, 8, 0x0100}, {P_IMM, 1, 0, 0, 0x00ff}}, false, false, false, false, true}, // $acD.hm += I
{"CMPIS", 0x0600, 0xfe00, 1, 2, {{P_ACCM, 1, 0, 8, 0x0100}, {P_IMM, 1, 0, 0, 0x00ff}}, false, false, false, false, true}, // FLAGS($acD - I)
{"LRIS", 0x0800, 0xf800, 1, 2, {{P_REG18, 1, 0, 8, 0x0700}, {P_IMM, 1, 0, 0, 0x00ff}}, false, false, false, false, true}, // $(D+24) = I
{"ADDI", 0x0200, 0xfeff, 2, 2, {{P_ACCM, 1, 0, 8, 0x0100}, {P_IMM, 2, 1, 0, 0xffff}}, false, false, false, true, true}, // $acD.hm += I
{"XORI", 0x0220, 0xfeff, 2, 2, {{P_ACCM, 1, 0, 8, 0x0100}, {P_IMM, 2, 1, 0, 0xffff}}, false, false, false, true, true}, // $acD.m ^= I
{"ANDI", 0x0240, 0xfeff, 2, 2, {{P_ACCM, 1, 0, 8, 0x0100}, {P_IMM, 2, 1, 0, 0xffff}}, false, false, false, true, true}, // $acD.m &= I
{"ORI", 0x0260, 0xfeff, 2, 2, {{P_ACCM, 1, 0, 8, 0x0100}, {P_IMM, 2, 1, 0, 0xffff}}, false, false, false, true, true}, // $acD.m |= I
{"CMPI", 0x0280, 0xfeff, 2, 2, {{P_ACCM, 1, 0, 8, 0x0100}, {P_IMM, 2, 1, 0, 0xffff}}, false, false, false, true, true}, // FLAGS(($acD.hm - I) | $acD.l)
{"ANDF", 0x02a0, 0xfeff, 2, 2, {{P_ACCM, 1, 0, 8, 0x0100}, {P_IMM, 2, 1, 0, 0xffff}}, false, false, false, true, true}, // $sr.LZ = ($acD.m & I) == 0 ? 1 : 0
{"ANDCF", 0x02c0, 0xfeff, 2, 2, {{P_ACCM, 1, 0, 8, 0x0100}, {P_IMM, 2, 1, 0, 0xffff}}, false, false, false, true, true}, // $sr.LZ = ($acD.m & I) == I ? 1 : 0
{"ILRR", 0x0210, 0xfefc, 1, 2, {{P_ACCM, 1, 0, 8, 0x0100}, {P_PRG, 1, 0, 0, 0x0003}}, false, false, false, false, false}, // $acD.m = IMEM[$arS]
{"ILRRD", 0x0214, 0xfefc, 1, 2, {{P_ACCM, 1, 0, 8, 0x0100}, {P_PRG, 1, 0, 0, 0x0003}}, false, false, false, false, false}, // $acD.m = IMEM[$arS--]
{"ILRRI", 0x0218, 0xfefc, 1, 2, {{P_ACCM, 1, 0, 8, 0x0100}, {P_PRG, 1, 0, 0, 0x0003}}, false, false, false, false, false}, // $acD.m = IMEM[$arS++]
{"ILRRN", 0x021c, 0xfefc, 1, 2, {{P_ACCM, 1, 0, 8, 0x0100}, {P_PRG, 1, 0, 0, 0x0003}}, false, false, false, false, false}, // $acD.m = IMEM[$arS]; $arS += $ixS
// LOOPS
{"LOOP", 0x0040, 0xffe0, 1, 1, {{P_REG, 1, 0, 0, 0x001f}}, false, true, true, true, false}, // run next instruction $R times
{"BLOOP", 0x0060, 0xffe0, 2, 2, {{P_REG, 1, 0, 0, 0x001f}, {P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, true, true, false}, // COMEFROM addr $R times
{"LOOPI", 0x1000, 0xff00, 1, 1, {{P_IMM, 1, 0, 0, 0x00ff}}, false, true, true, true, false}, // run next instruction I times
{"BLOOPI", 0x1100, 0xff00, 2, 2, {{P_IMM, 1, 0, 0, 0x00ff}, {P_ADDR_I, 2, 1, 0, 0xffff}}, false, true, true, true, false}, // COMEFROM addr I times
// load and store value pointed by indexing reg and increment; LRR/SRR variants
{"LRR", 0x1800, 0xff80, 1, 2, {{P_REG, 1, 0, 0, 0x001f}, {P_PRG, 1, 0, 5, 0x0060}}, false, false, false, false, false}, // $D = MEM[$arS]
{"LRRD", 0x1880, 0xff80, 1, 2, {{P_REG, 1, 0, 0, 0x001f}, {P_PRG, 1, 0, 5, 0x0060}}, false, false, false, false, false}, // $D = MEM[$arS--]
{"LRRI", 0x1900, 0xff80, 1, 2, {{P_REG, 1, 0, 0, 0x001f}, {P_PRG, 1, 0, 5, 0x0060}}, false, false, false, false, false}, // $D = MEM[$arS++]
{"LRRN", 0x1980, 0xff80, 1, 2, {{P_REG, 1, 0, 0, 0x001f}, {P_PRG, 1, 0, 5, 0x0060}}, false, false, false, false, false}, // $D = MEM[$arS]; $arS += $ixS
{"SRR", 0x1a00, 0xff80, 1, 2, {{P_PRG, 1, 0, 5, 0x0060}, {P_REG, 1, 0, 0, 0x001f}}, false, false, false, false, false}, // MEM[$arD] = $S
{"SRRD", 0x1a80, 0xff80, 1, 2, {{P_PRG, 1, 0, 5, 0x0060}, {P_REG, 1, 0, 0, 0x001f}}, false, false, false, false, false}, // MEM[$arD--] = $S
{"SRRI", 0x1b00, 0xff80, 1, 2, {{P_PRG, 1, 0, 5, 0x0060}, {P_REG, 1, 0, 0, 0x001f}}, false, false, false, false, false}, // MEM[$arD++] = $S
{"SRRN", 0x1b80, 0xff80, 1, 2, {{P_PRG, 1, 0, 5, 0x0060}, {P_REG, 1, 0, 0, 0x001f}}, false, false, false, false, false}, // MEM[$arD] = $S; $arD += $ixD
//2
{"LRS", 0x2000, 0xf800, 1, 2, {{P_REG18, 1, 0, 8, 0x0700}, {P_MEM, 1, 0, 0, 0x00ff}}, false, false, false, false, false}, // $(D+24) = MEM[($cr[0-7] << 8) | I]
{"SRS", 0x2800, 0xf800, 1, 2, {{P_MEM, 1, 0, 0, 0x00ff}, {P_REG18, 1, 0, 8, 0x0700}}, false, false, false, false, false}, // MEM[($cr[0-7] << 8) | I] = $(S+24)
// opcodes that can be extended
//3 - main opcode defined by 9 bits, extension defined by last 7 bits!!
{"XORR", 0x3000, 0xfc80, 1, 2, {{P_ACCM, 1, 0, 8, 0x0100}, {P_REG1A, 1, 0, 9, 0x0200}}, true, false, false, false, true}, // $acD.m ^= $axS.h
{"ANDR", 0x3400, 0xfc80, 1, 2, {{P_ACCM, 1, 0, 8, 0x0100}, {P_REG1A, 1, 0, 9, 0x0200}}, true, false, false, false, true}, // $acD.m &= $axS.h
{"ORR", 0x3800, 0xfc80, 1, 2, {{P_ACCM, 1, 0, 8, 0x0100}, {P_REG1A, 1, 0, 9, 0x0200}}, true, false, false, false, true}, // $acD.m |= $axS.h
{"ANDC", 0x3c00, 0xfe80, 1, 2, {{P_ACCM, 1, 0, 8, 0x0100}, {P_ACCM_D, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acD.m &= $ac(1-D).m
{"ORC", 0x3e00, 0xfe80, 1, 2, {{P_ACCM, 1, 0, 8, 0x0100}, {P_ACCM_D, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acD.m |= $ac(1-D).m
{"XORC", 0x3080, 0xfe80, 1, 2, {{P_ACCM, 1, 0, 8, 0x0100}, {P_ACCM_D, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acD.m ^= $ac(1-D).m
{"NOT", 0x3280, 0xfe80, 1, 1, {{P_ACCM, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acD.m = ~$acD.m
{"LSRNRX", 0x3480, 0xfc80, 1, 2, {{P_ACC, 1, 0, 8, 0x0100}, {P_REG1A, 1, 0, 9, 0x0200}}, true, false, false, false, true}, // $acD >>=/<<= $axS.h[0-6]
{"ASRNRX", 0x3880, 0xfc80, 1, 2, {{P_ACC, 1, 0, 8, 0x0100}, {P_REG1A, 1, 0, 9, 0x0200}}, true, false, false, false, true}, // $acD >>=/<<= $axS.h[0-6] (arithmetic)
{"LSRNR", 0x3c80, 0xfe80, 1, 2, {{P_ACC, 1, 0, 8, 0x0100}, {P_ACCM_D, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acD >>=/<<= $ac(1-D).m[0-6]
{"ASRNR", 0x3e80, 0xfe80, 1, 2, {{P_ACC, 1, 0, 8, 0x0100}, {P_ACCM_D, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acD >>=/<<= $ac(1-D).m[0-6] (arithmetic)
//4
{"ADDR", 0x4000, 0xf800, 1, 2, {{P_ACC, 1, 0, 8, 0x0100}, {P_REG18, 1, 0, 9, 0x0600}}, true, false, false, false, true}, // $acD += $(S+24)
{"ADDAX", 0x4800, 0xfc00, 1, 2, {{P_ACC, 1, 0, 8, 0x0100}, {P_AX, 1, 0, 9, 0x0200}}, true, false, false, false, true}, // $acD += $axS
{"ADD", 0x4c00, 0xfe00, 1, 2, {{P_ACC, 1, 0, 8, 0x0100}, {P_ACC_D, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acD += $ac(1-D)
{"ADDP", 0x4e00, 0xfe00, 1, 1, {{P_ACC, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acD += $prod
//5
{"SUBR", 0x5000, 0xf800, 1, 2, {{P_ACC, 1, 0, 8, 0x0100}, {P_REG18, 1, 0, 9, 0x0600}}, true, false, false, false, true}, // $acD -= $(S+24)
{"SUBAX", 0x5800, 0xfc00, 1, 2, {{P_ACC, 1, 0, 8, 0x0100}, {P_AX, 1, 0, 9, 0x0200}}, true, false, false, false, true}, // $acD -= $axS
{"SUB", 0x5c00, 0xfe00, 1, 2, {{P_ACC, 1, 0, 8, 0x0100}, {P_ACC_D, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acD -= $ac(1-D)
{"SUBP", 0x5e00, 0xfe00, 1, 1, {{P_ACC, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acD -= $prod
//6
{"MOVR", 0x6000, 0xf800, 1, 2, {{P_ACC, 1, 0, 8, 0x0100}, {P_REG18, 1, 0, 9, 0x0600}}, true, false, false, false, true}, // $acD.hm = $(S+24); $acD.l = 0
{"MOVAX", 0x6800, 0xfc00, 1, 2, {{P_ACC, 1, 0, 8, 0x0100}, {P_AX, 1, 0, 9, 0x0200}}, true, false, false, false, true}, // $acD = $axS
{"MOV", 0x6c00, 0xfe00, 1, 2, {{P_ACC, 1, 0, 8, 0x0100}, {P_ACC_D, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acD = $ax(1-D)
{"MOVP", 0x6e00, 0xfe00, 1, 1, {{P_ACC, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acD = $prod
//7
{"ADDAXL", 0x7000, 0xfc00, 1, 2, {{P_ACC, 1, 0, 8, 0x0100}, {P_REG18, 1, 0, 9, 0x0200}}, true, false, false, false, true}, // $acD += $axS.l
{"INCM", 0x7400, 0xfe00, 1, 1, {{P_ACCM, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acsD++
{"INC", 0x7600, 0xfe00, 1, 1, {{P_ACC, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acD++
{"DECM", 0x7800, 0xfe00, 1, 1, {{P_ACCM, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acsD--
{"DEC", 0x7a00, 0xfe00, 1, 1, {{P_ACC, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acD--
{"NEG", 0x7c00, 0xfe00, 1, 1, {{P_ACC, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acD = -$acD
{"MOVNP", 0x7e00, 0xfe00, 1, 1, {{P_ACC, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acD = -$prod
//8
{"NX", 0x8000, 0xf700, 1, 0, {}, true, false, false, false, false}, // extendable nop
{"CLR", 0x8100, 0xf700, 1, 1, {{P_ACC, 1, 0, 11, 0x0800}}, true, false, false, false, true}, // $acD = 0
{"CMP", 0x8200, 0xff00, 1, 0, {}, true, false, false, false, true}, // FLAGS($ac0 - $ac1)
{"MULAXH", 0x8300, 0xff00, 1, 0, {}, true, false, false, false, true}, // $prod = $ax0.h * $ax0.h
{"CLRP", 0x8400, 0xff00, 1, 0, {}, true, false, false, false, true}, // $prod = 0
{"TSTPROD", 0x8500, 0xff00, 1, 0, {}, true, false, false, false, true}, // FLAGS($prod)
{"TSTAXH", 0x8600, 0xfe00, 1, 1, {{P_REG1A, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // FLAGS($axR.h)
{"M2", 0x8a00, 0xff00, 1, 0, {}, true, false, false, false, false}, // enable "$prod *= 2" after every multiplication
{"M0", 0x8b00, 0xff00, 1, 0, {}, true, false, false, false, false}, // disable "$prod *= 2" after every multiplication
{"CLR15", 0x8c00, 0xff00, 1, 0, {}, true, false, false, false, false}, // set normal multiplication
{"SET15", 0x8d00, 0xff00, 1, 0, {}, true, false, false, false, false}, // set unsigned multiplication in MUL
{"SET16", 0x8e00, 0xff00, 1, 0, {}, true, false, false, false, false}, // set 16 bit sign extension width
{"SET40", 0x8f00, 0xff00, 1, 0, {}, true, false, false, false, false}, // set 40 bit sign extension width
//9
{"MUL", 0x9000, 0xf700, 1, 2, {{P_REG18, 1, 0, 11, 0x0800}, {P_REG1A, 1, 0, 11, 0x0800}}, true, false, false, false, true}, // $prod = $axS.l * $axS.h
{"ASR16", 0x9100, 0xf700, 1, 1, {{P_ACC, 1, 0, 11, 0x0800}}, true, false, false, false, true}, // $acD >>= 16 (shifting in sign bits)
{"MULMVZ", 0x9200, 0xf600, 1, 3, {{P_REG18, 1, 0, 11, 0x0800}, {P_REG1A, 1, 0, 11, 0x0800}, {P_ACC, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acR.hm = $prod.hm; $acR.l = 0; $prod = $axS.l * $axS.h
{"MULAC", 0x9400, 0xf600, 1, 3, {{P_REG18, 1, 0, 11, 0x0800}, {P_REG1A, 1, 0, 11, 0x0800}, {P_ACC, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acR += $prod; $prod = $axS.l * $axS.h
{"MULMV", 0x9600, 0xf600, 1, 3, {{P_REG18, 1, 0, 11, 0x0800}, {P_REG1A, 1, 0, 11, 0x0800}, {P_ACC, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acR = $prod; $prod = $axS.l * $axS.h
//a-b
{"MULX", 0xa000, 0xe700, 1, 2, {{P_REGM18, 1, 0, 11, 0x1000}, {P_REGM19, 1, 0, 10, 0x0800}}, true, false, false, false, true}, // $prod = $ax0.S * $ax1.T
{"ABS", 0xa100, 0xf700, 1, 1, {{P_ACC, 1, 0, 11, 0x0800}}, true, false, false, false, true}, // $acD = abs($acD)
{"MULXMVZ", 0xa200, 0xe600, 1, 3, {{P_REGM18, 1, 0, 11, 0x1000}, {P_REGM19, 1, 0, 10, 0x0800}, {P_ACC, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acR.hm = $prod.hm; $acR.l = 0; $prod = $ax0.S * $ax1.T
{"MULXAC", 0xa400, 0xe600, 1, 3, {{P_REGM18, 1, 0, 11, 0x1000}, {P_REGM19, 1, 0, 10, 0x0800}, {P_ACC, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acR += $prod; $prod = $ax0.S * $ax1.T
{"MULXMV", 0xa600, 0xe600, 1, 3, {{P_REGM18, 1, 0, 11, 0x1000}, {P_REGM19, 1, 0, 10, 0x0800}, {P_ACC, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acR = $prod; $prod = $ax0.S * $ax1.T
{"TST", 0xb100, 0xf700, 1, 1, {{P_ACC, 1, 0, 11, 0x0800}}, true, false, false, false, true}, // FLAGS($acR)
//c-d
{"MULC", 0xc000, 0xe700, 1, 2, {{P_ACCM, 1, 0, 12, 0x1000}, {P_REG1A, 1, 0, 11, 0x0800}}, true, false, false, false, true}, // $prod = $acS.m * $axS.h
{"CMPAR", 0xc100, 0xe700, 1, 2, {{P_ACC, 1, 0, 11, 0x0800}, {P_REG1A, 1, 0, 12, 0x1000}}, true, false, false, false, true}, // FLAGS($acS - axR.h)
{"MULCMVZ", 0xc200, 0xe600, 1, 3, {{P_ACCM, 1, 0, 12, 0x1000}, {P_REG1A, 1, 0, 11, 0x0800}, {P_ACC, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acR.hm, $acR.l, $prod = $prod.hm, 0, $acS.m * $axS.h
{"MULCAC", 0xc400, 0xe600, 1, 3, {{P_ACCM, 1, 0, 12, 0x1000}, {P_REG1A, 1, 0, 11, 0x0800}, {P_ACC, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acR, $prod = $acR + $prod, $acS.m * $axS.h
{"MULCMV", 0xc600, 0xe600, 1, 3, {{P_ACCM, 1, 0, 12, 0x1000}, {P_REG1A, 1, 0, 11, 0x0800}, {P_ACC, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acR, $prod = $prod, $acS.m * $axS.h
//e
{"MADDX", 0xe000, 0xfc00, 1, 2, {{P_REGM18, 1, 0, 8, 0x0200}, {P_REGM19, 1, 0, 7, 0x0100}}, true, false, false, false, true}, // $prod += $ax0.S * $ax1.T
{"MSUBX", 0xe400, 0xfc00, 1, 2, {{P_REGM18, 1, 0, 8, 0x0200}, {P_REGM19, 1, 0, 7, 0x0100}}, true, false, false, false, true}, // $prod -= $ax0.S * $ax1.T
{"MADDC", 0xe800, 0xfc00, 1, 2, {{P_ACCM, 1, 0, 9, 0x0200}, {P_REG19, 1, 0, 7, 0x0100}}, true, false, false, false, true}, // $prod += $acS.m * $axT.h
{"MSUBC", 0xec00, 0xfc00, 1, 2, {{P_ACCM, 1, 0, 9, 0x0200}, {P_REG19, 1, 0, 7, 0x0100}}, true, false, false, false, true}, // $prod -= $acS.m * $axT.h
//f
{"LSL16", 0xf000, 0xfe00, 1, 1, {{P_ACC, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acR <<= 16
{"MADD", 0xf200, 0xfe00, 1, 2, {{P_REG18, 1, 0, 8, 0x0100}, {P_REG1A, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $prod += $axS.l * $axS.h
{"LSR16", 0xf400, 0xfe00, 1, 1, {{P_ACC, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acR >>= 16
{"MSUB", 0xf600, 0xfe00, 1, 2, {{P_REG18, 1, 0, 8, 0x0100}, {P_REG1A, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $prod -= $axS.l * $axS.h
{"ADDPAXZ", 0xf800, 0xfc00, 1, 2, {{P_ACC, 1, 0, 9, 0x0200}, {P_AX, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acD.hm = $prod.hm + $ax.h; $acD.l = 0
{"CLRL", 0xfc00, 0xfe00, 1, 1, {{P_ACCL, 1, 0, 11, 0x0800}}, true, false, false, false, true}, // $acR.l = 0
{"MOVPZ", 0xfe00, 0xfe00, 1, 1, {{P_ACC, 1, 0, 8, 0x0100}}, true, false, false, false, true}, // $acD.hm = $prod.hm; $acD.l = 0
}};
const DSPOPCTemplate cw =
{"CW", 0x0000, 0x0000, 1, 1, {{P_VAL, 2, 0, 0, 0xffff}}, false, false, false, false, false};
// extended opcodes
const std::array<DSPOPCTemplate, 25> s_opcodes_ext =
{{
{"XXX", 0x0000, 0x00fc, 1, 1, {{P_VAL, 1, 0, 0, 0x00ff}}, false, false, false, false, false}, // no operation
{"DR", 0x0004, 0x00fc, 1, 1, {{P_REG, 1, 0, 0, 0x0003}}, false, false, false, false, false}, // $arR--
{"IR", 0x0008, 0x00fc, 1, 1, {{P_REG, 1, 0, 0, 0x0003}}, false, false, false, false, false}, // $arR++
{"NR", 0x000c, 0x00fc, 1, 1, {{P_REG, 1, 0, 0, 0x0003}}, false, false, false, false, false}, // $arR += $ixR
{"MV", 0x0010, 0x00f0, 1, 2, {{P_REG18, 1, 0, 2, 0x000c}, {P_REG1C, 1, 0, 0, 0x0003}}, false, false, false, false, false}, // $(D+24) = $(S+28)
{"S", 0x0020, 0x00e4, 1, 2, {{P_PRG, 1, 0, 0, 0x0003}, {P_REG1C, 1, 0, 3, 0x0018}}, false, false, false, false, false}, // MEM[$D++] = $(S+28)
{"SN", 0x0024, 0x00e4, 1, 2, {{P_PRG, 1, 0, 0, 0x0003}, {P_REG1C, 1, 0, 3, 0x0018}}, false, false, false, false, false}, // MEM[$D] = $(D+28); $D += $(D+4)
{"L", 0x0040, 0x00c4, 1, 2, {{P_REG18, 1, 0, 3, 0x0038}, {P_PRG, 1, 0, 0, 0x0003}}, false, false, false, false, false}, // $(D+24) = MEM[$S++]
{"LN", 0x0044, 0x00c4, 1, 2, {{P_REG18, 1, 0, 3, 0x0038}, {P_PRG, 1, 0, 0, 0x0003}}, false, false, false, false, false}, // $(D+24) = MEM[$S]; $S += $(S+4)
{"LS", 0x0080, 0x00ce, 1, 2, {{P_REG18, 1, 0, 4, 0x0030}, {P_ACCM, 1, 0, 0, 0x0001}}, false, false, false, false, false}, // $(D+24) = MEM[$ar0++]; MEM[$ar3++] = $acS.m
{"SL", 0x0082, 0x00ce, 1, 2, {{P_ACCM, 1, 0, 0, 0x0001}, {P_REG18, 1, 0, 4, 0x0030}}, false, false, false, false, false}, // MEM[$ar0++] = $acS.m; $(D+24) = MEM[$ar3++]
{"LSN", 0x0084, 0x00ce, 1, 2, {{P_REG18, 1, 0, 4, 0x0030}, {P_ACCM, 1, 0, 0, 0x0001}}, false, false, false, false, false}, // $(D+24) = MEM[$ar0]; MEM[$ar3++] = $acS.m; $ar0 += $ix0
{"SLN", 0x0086, 0x00ce, 1, 2, {{P_ACCM, 1, 0, 0, 0x0001}, {P_REG18, 1, 0, 4, 0x0030}}, false, false, false, false, false}, // MEM[$ar0] = $acS.m; $(D+24) = MEM[$ar3++]; $ar0 += $ix0
{"LSM", 0x0088, 0x00ce, 1, 2, {{P_REG18, 1, 0, 4, 0x0030}, {P_ACCM, 1, 0, 0, 0x0001}}, false, false, false, false, false}, // $(D+24) = MEM[$ar0++]; MEM[$ar3] = $acS.m; $ar3 += $ix3
{"SLM", 0x008a, 0x00ce, 1, 2, {{P_ACCM, 1, 0, 0, 0x0001}, {P_REG18, 1, 0, 4, 0x0030}}, false, false, false, false, false}, // MEM[$ar0++] = $acS.m; $(D+24) = MEM[$ar3]; $ar3 += $ix3
{"LSNM", 0x008c, 0x00ce, 1, 2, {{P_REG18, 1, 0, 4, 0x0030}, {P_ACCM, 1, 0, 0, 0x0001}}, false, false, false, false, false}, // $(D+24) = MEM[$ar0]; MEM[$ar3] = $acS.m; $ar0 += $ix0; $ar3 += $ix3
{"SLNM", 0x008e, 0x00ce, 1, 2, {{P_ACCM, 1, 0, 0, 0x0001}, {P_REG18, 1, 0, 4, 0x0030}}, false, false, false, false, false}, // MEM[$ar0] = $acS.m; $(D+24) = MEM[$ar3]; $ar0 += $ix0; $ar3 += $ix3
{"LDAX", 0x00c3, 0x00cf, 1, 2, {{P_AX, 1, 0, 4, 0x0010}, {P_PRG, 1, 0, 5, 0x0020}}, false, false, false, false, false}, // $axR.h = MEM[$arS++]; $axR.l = MEM[$ar3++]
{"LDAXN", 0x00c7, 0x00cf, 1, 2, {{P_AX, 1, 0, 4, 0x0010}, {P_PRG, 1, 0, 5, 0x0020}}, false, false, false, false, false}, // $axR.h = MEM[$arS]; $axR.l = MEM[$ar3++]; $arS += $ixS
{"LDAXM", 0x00cb, 0x00cf, 1, 2, {{P_AX, 1, 0, 4, 0x0010}, {P_PRG, 1, 0, 5, 0x0020}}, false, false, false, false, false}, // $axR.h = MEM[$arS++]; $axR.l = MEM[$ar3]; $ar3 += $ix3
{"LDAXNM", 0x00cf, 0x00cf, 1, 2, {{P_AX, 1, 0, 4, 0x0010}, {P_PRG, 1, 0, 5, 0x0020}}, false, false, false, false, false}, // $axR.h = MEM[$arS]; $axR.l = MEM[$ar3]; $arS += $ixS; $ar3 += $ix3
{"LD", 0x00c0, 0x00cc, 1, 3, {{P_REGM18, 1, 0, 4, 0x0020}, {P_REGM19, 1, 0, 3, 0x0010}, {P_PRG, 1, 0, 0, 0x0003}}, false, false, false, false, false}, // $ax0.D = MEM[$arS++]; $ax1.R = MEM[$ar3++]
{"LDN", 0x00c4, 0x00cc, 1, 3, {{P_REGM18, 1, 0, 4, 0x0020}, {P_REGM19, 1, 0, 3, 0x0010}, {P_PRG, 1, 0, 0, 0x0003}}, false, false, false, false, false}, // $ax0.D = MEM[$arS]; $ax1.R = MEM[$ar3++]; $arS += $ixS
{"LDM", 0x00c8, 0x00cc, 1, 3, {{P_REGM18, 1, 0, 4, 0x0020}, {P_REGM19, 1, 0, 3, 0x0010}, {P_PRG, 1, 0, 0, 0x0003}}, false, false, false, false, false}, // $ax0.D = MEM[$arS++]; $ax1.R = MEM[$ar3]; $ar3 += $ix3
{"LDNM", 0x00cc, 0x00cc, 1, 3, {{P_REGM18, 1, 0, 4, 0x0020}, {P_REGM19, 1, 0, 3, 0x0010}, {P_PRG, 1, 0, 0, 0x0003}}, false, false, false, false, false}, // $ax0.D = MEM[$arS]; $ax1.R = MEM[$ar3]; $arS += $ixS; $ar3 += $ix3
}};
const std::array<pdlabel_t, 96> pdlabels =
{{
{0xffa0, "COEF_A1_0", "COEF_A1_0",},
{0xffa1, "COEF_A2_0", "COEF_A2_0",},
{0xffa2, "COEF_A1_1", "COEF_A1_1",},
{0xffa3, "COEF_A2_1", "COEF_A2_1",},
{0xffa4, "COEF_A1_2", "COEF_A1_2",},
{0xffa5, "COEF_A2_2", "COEF_A2_2",},
{0xffa6, "COEF_A1_3", "COEF_A1_3",},
{0xffa7, "COEF_A2_3", "COEF_A2_3",},
{0xffa8, "COEF_A1_4", "COEF_A1_4",},
{0xffa9, "COEF_A2_4", "COEF_A2_4",},
{0xffaa, "COEF_A1_5", "COEF_A1_5",},
{0xffab, "COEF_A2_5", "COEF_A2_5",},
{0xffac, "COEF_A1_6", "COEF_A1_6",},
{0xffad, "COEF_A2_6", "COEF_A2_6",},
{0xffae, "COEF_A1_7", "COEF_A1_7",},
{0xffaf, "COEF_A2_7", "COEF_A2_7",},
{0xffb0, "0xffb0", nullptr,},
{0xffb1, "0xffb1", nullptr,},
{0xffb2, "0xffb2", nullptr,},
{0xffb3, "0xffb3", nullptr,},
{0xffb4, "0xffb4", nullptr,},
{0xffb5, "0xffb5", nullptr,},
{0xffb6, "0xffb6", nullptr,},
{0xffb7, "0xffb7", nullptr,},
{0xffb8, "0xffb8", nullptr,},
{0xffb9, "0xffb9", nullptr,},
{0xffba, "0xffba", nullptr,},
{0xffbb, "0xffbb", nullptr,},
{0xffbc, "0xffbc", nullptr,},
{0xffbd, "0xffbd", nullptr,},
{0xffbe, "0xffbe", nullptr,},
{0xffbf, "0xffbf", nullptr,},
{0xffc0, "0xffc0", nullptr,},
{0xffc1, "0xffc1", nullptr,},
{0xffc2, "0xffc2", nullptr,},
{0xffc3, "0xffc3", nullptr,},
{0xffc4, "0xffc4", nullptr,},
{0xffc5, "0xffc5", nullptr,},
{0xffc6, "0xffc6", nullptr,},
{0xffc7, "0xffc7", nullptr,},
{0xffc8, "0xffc8", nullptr,},
{0xffc9, "DSCR", "DSP DMA Control Reg",},
{0xffca, "0xffca", nullptr,},
{0xffcb, "DSBL", "DSP DMA Block Length",},
{0xffcc, "0xffcc", nullptr,},
{0xffcd, "DSPA", "DSP DMA DMEM Address",},
{0xffce, "DSMAH", "DSP DMA Mem Address H",},
{0xffcf, "DSMAL", "DSP DMA Mem Address L",},
{0xffd0, "0xffd0",nullptr,},
{0xffd1, "SampleFormat", "SampleFormat",},
{0xffd2, "0xffd2",nullptr,},
{0xffd3, "UnkZelda", "Unk Zelda reads/writes from/to it",},
{0xffd4, "ACSAH", "Accelerator start address H",},
{0xffd5, "ACSAL", "Accelerator start address L",},
{0xffd6, "ACEAH", "Accelerator end address H",},
{0xffd7, "ACEAL", "Accelerator end address L",},
{0xffd8, "ACCAH", "Accelerator current address H",},
{0xffd9, "ACCAL", "Accelerator current address L",},
{0xffda, "pred_scale", "pred_scale",},
{0xffdb, "yn1", "yn1",},
{0xffdc, "yn2", "yn2",},
{0xffdd, "ARAM", "Direct Read from ARAM (uses ADPCM)",},
{0xffde, "GAIN", "Gain",},
{0xffdf, "0xffdf", nullptr,},
{0xffe0, "0xffe0",nullptr,},
{0xffe1, "0xffe1",nullptr,},
{0xffe2, "0xffe2",nullptr,},
{0xffe3, "0xffe3",nullptr,},
{0xffe4, "0xffe4",nullptr,},
{0xffe5, "0xffe5",nullptr,},
{0xffe6, "0xffe6",nullptr,},
{0xffe7, "0xffe7",nullptr,},
{0xffe8, "0xffe8",nullptr,},
{0xffe9, "0xffe9",nullptr,},
{0xffea, "0xffea",nullptr,},
{0xffeb, "0xffeb",nullptr,},
{0xffec, "0xffec",nullptr,},
{0xffed, "0xffed",nullptr,},
{0xffee, "0xffee",nullptr,},
{0xffef, "AMDM", "ARAM DMA Request Mask",},
{0xfff0, "0xfff0",nullptr,},
{0xfff1, "0xfff1",nullptr,},
{0xfff2, "0xfff2",nullptr,},
{0xfff3, "0xfff3",nullptr,},
{0xfff4, "0xfff4",nullptr,},
{0xfff5, "0xfff5",nullptr,},
{0xfff6, "0xfff6",nullptr,},
{0xfff7, "0xfff7",nullptr,},
{0xfff8, "0xfff8",nullptr,},
{0xfff9, "0xfff9",nullptr,},
{0xfffa, "0xfffa",nullptr,},
{0xfffb, "DIRQ", "DSP IRQ Request",},
{0xfffc, "DMBH", "DSP Mailbox H",},
{0xfffd, "DMBL", "DSP Mailbox L",},
{0xfffe, "CMBH", "CPU Mailbox H",},
{0xffff, "CMBL", "CPU Mailbox L",},
}};
const std::array<pdlabel_t, 36> regnames =
{{
{0x00, "AR0", "Addr Reg 00",},
{0x01, "AR1", "Addr Reg 01",},
{0x02, "AR2", "Addr Reg 02",},
{0x03, "AR3", "Addr Reg 03",},
{0x04, "IX0", "Index Reg 0",},
{0x05, "IX1", "Index Reg 1",},
{0x06, "IX2", "Index Reg 2",},
{0x07, "IX3", "Index Reg 3",},
{0x08, "WR0", "Wrapping Register 0",},
{0x09, "WR1", "Wrapping Register 1",},
{0x0a, "WR2", "Wrapping Register 2",},
{0x0b, "WR3", "Wrapping Register 3",},
{0x0c, "ST0", "Call stack",},
{0x0d, "ST1", "Data stack",},
{0x0e, "ST2", "Loop addr stack",},
{0x0f, "ST3", "Loop counter",},
{0x10, "AC0.H", "Accu High 0",},
{0x11, "AC1.H", "Accu High 1",},
{0x12, "CR", "Config Register",},
{0x13, "SR", "Special Register",},
{0x14, "PROD.L", "Prod L",},
{0x15, "PROD.M1", "Prod M1",},
{0x16, "PROD.H", "Prod H",},
{0x17, "PROD.M2", "Prod M2",},
{0x18, "AX0.L", "Extra Accu L 0",},
{0x19, "AX1.L", "Extra Accu L 1",},
{0x1a, "AX0.H", "Extra Accu H 0",},
{0x1b, "AX1.H", "Extra Accu H 1",},
{0x1c, "AC0.L", "Accu Low 0",},
{0x1d, "AC1.L", "Accu Low 1",},
{0x1e, "AC0.M", "Accu Mid 0",},
{0x1f, "AC1.M", "Accu Mid 1",},
// To resolve combined register names.
{0x20, "ACC0", "Accu Full 0",},
{0x21, "ACC1", "Accu Full 1",},
{0x22, "AX0", "Extra Accu 0",},
{0x23, "AX1", "Extra Accu 1",},
}};
// clang-format on
std::array<u16, WRITEBACK_LOG_SIZE> writeBackLog;
std::array<int, WRITEBACK_LOG_SIZE> writeBackLogIdx;
const char* pdname(u16 val)
{
static char tmpstr[12]; // nasty
for (const pdlabel_t& pdlabel : pdlabels)
{
if (pdlabel.addr == val)
return pdlabel.name;
}
sprintf(tmpstr, "0x%04x", val);
return tmpstr;
}
const char* pdregname(int val)
{
return regnames[val].name;
}
const char* pdregnamelong(int val)
{
return regnames[val].description;
}
namespace
{
constexpr size_t OPTABLE_SIZE = 0xffff + 1;
constexpr size_t EXT_OPTABLE_SIZE = 0xff + 1;
std::array<const DSPOPCTemplate*, OPTABLE_SIZE> s_op_table;
std::array<const DSPOPCTemplate*, EXT_OPTABLE_SIZE> s_ext_op_table;
template <size_t N>
auto FindByName(std::string_view name, const std::array<DSPOPCTemplate, N>& data)
{
return std::find_if(data.cbegin(), data.cend(),
[&name](const auto& info) { return name == info.name; });
}
} // Anonymous namespace
const DSPOPCTemplate* FindOpInfoByOpcode(UDSPInstruction opcode)
{
const auto iter = FindByOpcode(opcode, s_opcodes);
if (iter == s_opcodes.cend())
return nullptr;
return &*iter;
}
const DSPOPCTemplate* FindOpInfoByName(std::string_view name)
{
const auto iter = FindByName(name, s_opcodes);
if (iter == s_opcodes.cend())
return nullptr;
return &*iter;
}
const DSPOPCTemplate* FindExtOpInfoByOpcode(UDSPInstruction opcode)
{
const auto iter = FindByOpcode(opcode, s_opcodes_ext);
if (iter == s_opcodes_ext.cend())
return nullptr;
return &*iter;
}
const DSPOPCTemplate* FindExtOpInfoByName(std::string_view name)
{
const auto iter = FindByName(name, s_opcodes_ext);
if (iter == s_opcodes_ext.cend())
return nullptr;
return &*iter;
}
const DSPOPCTemplate* GetOpTemplate(UDSPInstruction inst)
{
return s_op_table[inst];
}
const DSPOPCTemplate* GetExtOpTemplate(UDSPInstruction inst)
{
const bool has_seven_bit_extension = (inst >> 12) == 0x3;
if (has_seven_bit_extension)
return s_ext_op_table[inst & 0x7F];
return s_ext_op_table[inst & 0xFF];
}
// This function could use the above GetOpTemplate, but then we'd lose the
// nice property that it catches colliding op masks.
void InitInstructionTable()
{
// ext op table
for (size_t i = 0; i < s_ext_op_table.size(); i++)
{
s_ext_op_table[i] = &cw;
const auto iter = FindByOpcode(static_cast<UDSPInstruction>(i), s_opcodes_ext);
if (iter == s_opcodes_ext.cend())
continue;
if (s_ext_op_table[i] == &cw)
{
s_ext_op_table[i] = &*iter;
}
else
{
// If the entry already in the table is a strict subset, allow it
if ((s_ext_op_table[i]->opcode_mask | iter->opcode_mask) != s_ext_op_table[i]->opcode_mask)
{
ERROR_LOG(DSPLLE, "opcode ext table place %zu already in use by %s when inserting %s", i,
s_ext_op_table[i]->name, iter->name);
}
}
}
// op table
s_op_table.fill(&cw);
for (size_t i = 0; i < s_op_table.size(); i++)
{
const auto iter = FindByOpcode(static_cast<UDSPInstruction>(i), s_opcodes);
if (iter == s_opcodes.cend())
continue;
if (s_op_table[i] == &cw)
s_op_table[i] = &*iter;
else
ERROR_LOG(DSPLLE, "opcode table place %zu already in use for %s", i, iter->name);
}
writeBackLogIdx.fill(-1);
// Ensure the interpreter tables are all set up, as JITs also rely on them.
Interpreter::InitInstructionTables();
}
} // namespace DSP
| LAGonauta/dolphin | Source/Core/Core/DSP/DSPTables.cpp | C++ | gpl-2.0 | 53,941 |
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* NetworkManager -- Network link manager
*
* 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.
*
* Copyright (C) 2009 - 2013 Red Hat, Inc.
*/
#include "config.h"
#include <string.h>
#include <gudev/gudev.h>
#include "nm-rfkill-manager.h"
#include "nm-logging.h"
typedef struct {
GUdevClient *client;
/* Authoritative rfkill state (RFKILL_* enum) */
RfKillState rfkill_states[RFKILL_TYPE_MAX];
GSList *killswitches;
} NMRfkillManagerPrivate;
#define NM_RFKILL_MANAGER_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), NM_TYPE_RFKILL_MANAGER, NMRfkillManagerPrivate))
G_DEFINE_TYPE (NMRfkillManager, nm_rfkill_manager, G_TYPE_OBJECT)
enum {
RFKILL_CHANGED,
LAST_SIGNAL
};
static guint signals[LAST_SIGNAL] = { 0 };
typedef struct {
char *name;
guint64 seqnum;
char *path;
char *driver;
RfKillType rtype;
gint state;
gboolean platform;
} Killswitch;
RfKillState
nm_rfkill_manager_get_rfkill_state (NMRfkillManager *self, RfKillType rtype)
{
g_return_val_if_fail (self != NULL, RFKILL_UNBLOCKED);
g_return_val_if_fail (rtype < RFKILL_TYPE_MAX, RFKILL_UNBLOCKED);
return NM_RFKILL_MANAGER_GET_PRIVATE (self)->rfkill_states[rtype];
}
static const char *
rfkill_type_to_desc (RfKillType rtype)
{
if (rtype == 0)
return "WiFi";
else if (rtype == 1)
return "WWAN";
else if (rtype == 2)
return "WiMAX";
return "unknown";
}
static const char *
rfkill_state_to_desc (RfKillState rstate)
{
if (rstate == 0)
return "unblocked";
else if (rstate == 1)
return "soft-blocked";
else if (rstate == 2)
return "hard-blocked";
return "unknown";
}
static Killswitch *
killswitch_new (GUdevDevice *device, RfKillType rtype)
{
Killswitch *ks;
GUdevDevice *parent = NULL, *grandparent = NULL;
const char *driver, *subsys, *parent_subsys = NULL;
ks = g_malloc0 (sizeof (Killswitch));
ks->name = g_strdup (g_udev_device_get_name (device));
ks->seqnum = g_udev_device_get_seqnum (device);
ks->path = g_strdup (g_udev_device_get_sysfs_path (device));
ks->rtype = rtype;
driver = g_udev_device_get_property (device, "DRIVER");
subsys = g_udev_device_get_subsystem (device);
/* Check parent for various attributes */
parent = g_udev_device_get_parent (device);
if (parent) {
parent_subsys = g_udev_device_get_subsystem (parent);
if (!driver)
driver = g_udev_device_get_property (parent, "DRIVER");
if (!driver) {
/* Sigh; try the grandparent */
grandparent = g_udev_device_get_parent (parent);
if (grandparent)
driver = g_udev_device_get_property (grandparent, "DRIVER");
}
}
if (!driver)
driver = "(unknown)";
ks->driver = g_strdup (driver);
if ( g_strcmp0 (subsys, "platform") == 0
|| g_strcmp0 (parent_subsys, "platform") == 0
|| g_strcmp0 (subsys, "acpi") == 0
|| g_strcmp0 (parent_subsys, "acpi") == 0)
ks->platform = TRUE;
if (grandparent)
g_object_unref (grandparent);
if (parent)
g_object_unref (parent);
return ks;
}
static void
killswitch_destroy (Killswitch *ks)
{
g_return_if_fail (ks != NULL);
g_free (ks->name);
g_free (ks->path);
g_free (ks->driver);
memset (ks, 0, sizeof (Killswitch));
g_free (ks);
}
NMRfkillManager *
nm_rfkill_manager_new (void)
{
return NM_RFKILL_MANAGER (g_object_new (NM_TYPE_RFKILL_MANAGER, NULL));
}
static RfKillState
sysfs_state_to_nm_state (gint sysfs_state)
{
switch (sysfs_state) {
case 0:
return RFKILL_SOFT_BLOCKED;
case 1:
return RFKILL_UNBLOCKED;
case 2:
return RFKILL_HARD_BLOCKED;
default:
nm_log_warn (LOGD_RFKILL, "unhandled rfkill state %d", sysfs_state);
break;
}
return RFKILL_UNBLOCKED;
}
static void
recheck_killswitches (NMRfkillManager *self)
{
NMRfkillManagerPrivate *priv = NM_RFKILL_MANAGER_GET_PRIVATE (self);
GSList *iter;
RfKillState poll_states[RFKILL_TYPE_MAX];
RfKillState platform_states[RFKILL_TYPE_MAX];
gboolean platform_checked[RFKILL_TYPE_MAX];
int i;
/* Default state is unblocked */
for (i = 0; i < RFKILL_TYPE_MAX; i++) {
poll_states[i] = RFKILL_UNBLOCKED;
platform_states[i] = RFKILL_UNBLOCKED;
platform_checked[i] = FALSE;
}
/* Poll the states of all killswitches */
for (iter = priv->killswitches; iter; iter = g_slist_next (iter)) {
Killswitch *ks = iter->data;
GUdevDevice *device;
RfKillState dev_state;
int sysfs_state;
device = g_udev_client_query_by_subsystem_and_name (priv->client, "rfkill", ks->name);
if (device) {
sysfs_state = g_udev_device_get_property_as_int (device, "RFKILL_STATE");
dev_state = sysfs_state_to_nm_state (sysfs_state);
nm_log_dbg (LOGD_RFKILL, "%s rfkill%s switch %s state now %d/%u",
rfkill_type_to_desc (ks->rtype),
ks->platform ? " platform" : "",
ks->name,
sysfs_state,
dev_state);
if (ks->platform == FALSE) {
if (dev_state > poll_states[ks->rtype])
poll_states[ks->rtype] = dev_state;
} else {
platform_checked[ks->rtype] = TRUE;
if (dev_state > platform_states[ks->rtype])
platform_states[ks->rtype] = dev_state;
}
g_object_unref (device);
}
}
/* Log and emit change signal for final rfkill states */
for (i = 0; i < RFKILL_TYPE_MAX; i++) {
if (platform_checked[i] == TRUE) {
/* blocked platform switch state overrides device state, otherwise
* let the device state stand. (bgo #655773)
*/
if (platform_states[i] != RFKILL_UNBLOCKED)
poll_states[i] = platform_states[i];
}
if (poll_states[i] != priv->rfkill_states[i]) {
nm_log_dbg (LOGD_RFKILL, "%s rfkill state now '%s'",
rfkill_type_to_desc (i),
rfkill_state_to_desc (poll_states[i]));
priv->rfkill_states[i] = poll_states[i];
g_signal_emit (self, signals[RFKILL_CHANGED], 0, i, priv->rfkill_states[i]);
}
}
}
static Killswitch *
killswitch_find_by_name (NMRfkillManager *self, const char *name)
{
NMRfkillManagerPrivate *priv = NM_RFKILL_MANAGER_GET_PRIVATE (self);
GSList *iter;
g_return_val_if_fail (name != NULL, NULL);
for (iter = priv->killswitches; iter; iter = g_slist_next (iter)) {
Killswitch *candidate = iter->data;
if (!strcmp (name, candidate->name))
return candidate;
}
return NULL;
}
static const RfKillType
rfkill_type_to_enum (const char *str)
{
g_return_val_if_fail (str != NULL, RFKILL_TYPE_UNKNOWN);
if (!strcmp (str, "wlan"))
return RFKILL_TYPE_WLAN;
else if (!strcmp (str, "wwan"))
return RFKILL_TYPE_WWAN;
else if (!strcmp (str, "wimax"))
return RFKILL_TYPE_WIMAX;
return RFKILL_TYPE_UNKNOWN;
}
static void
add_one_killswitch (NMRfkillManager *self, GUdevDevice *device)
{
NMRfkillManagerPrivate *priv = NM_RFKILL_MANAGER_GET_PRIVATE (self);
const char *str_type;
RfKillType rtype;
Killswitch *ks;
str_type = g_udev_device_get_property (device, "RFKILL_TYPE");
rtype = rfkill_type_to_enum (str_type);
if (rtype == RFKILL_TYPE_UNKNOWN)
return;
ks = killswitch_new (device, rtype);
priv->killswitches = g_slist_prepend (priv->killswitches, ks);
nm_log_info (LOGD_RFKILL, "%s: found %s radio killswitch (at %s) (%sdriver %s)",
ks->name,
rfkill_type_to_desc (rtype),
ks->path,
ks->platform ? "platform " : "",
ks->driver ? ks->driver : "<unknown>");
}
static void
rfkill_add (NMRfkillManager *self, GUdevDevice *device)
{
const char *name;
g_return_if_fail (device != NULL);
name = g_udev_device_get_name (device);
g_return_if_fail (name != NULL);
if (!killswitch_find_by_name (self, name))
add_one_killswitch (self, device);
}
static void
rfkill_remove (NMRfkillManager *self,
GUdevDevice *device)
{
NMRfkillManagerPrivate *priv = NM_RFKILL_MANAGER_GET_PRIVATE (self);
GSList *iter;
const char *name;
g_return_if_fail (device != NULL);
name = g_udev_device_get_name (device);
g_return_if_fail (name != NULL);
for (iter = priv->killswitches; iter; iter = g_slist_next (iter)) {
Killswitch *ks = iter->data;
if (!strcmp (ks->name, name)) {
nm_log_info (LOGD_RFKILL, "radio killswitch %s disappeared", ks->path);
priv->killswitches = g_slist_remove (priv->killswitches, ks);
killswitch_destroy (ks);
break;
}
}
}
static void
handle_uevent (GUdevClient *client,
const char *action,
GUdevDevice *device,
gpointer user_data)
{
NMRfkillManager *self = NM_RFKILL_MANAGER (user_data);
const char *subsys;
g_return_if_fail (action != NULL);
/* A bit paranoid */
subsys = g_udev_device_get_subsystem (device);
g_return_if_fail (!g_strcmp0 (subsys, "rfkill"));
nm_log_dbg (LOGD_HW, "udev rfkill event: action '%s' device '%s'",
action, g_udev_device_get_name (device));
if (!strcmp (action, "add"))
rfkill_add (self, device);
else if (!strcmp (action, "remove"))
rfkill_remove (self, device);
recheck_killswitches (self);
}
static void
nm_rfkill_manager_init (NMRfkillManager *self)
{
NMRfkillManagerPrivate *priv = NM_RFKILL_MANAGER_GET_PRIVATE (self);
const char *subsys[] = { "rfkill", NULL };
GList *switches, *iter;
guint32 i;
for (i = 0; i < RFKILL_TYPE_MAX; i++)
priv->rfkill_states[i] = RFKILL_UNBLOCKED;
priv->client = g_udev_client_new (subsys);
g_signal_connect (priv->client, "uevent", G_CALLBACK (handle_uevent), self);
switches = g_udev_client_query_by_subsystem (priv->client, "rfkill");
for (iter = switches; iter; iter = g_list_next (iter)) {
add_one_killswitch (self, G_UDEV_DEVICE (iter->data));
g_object_unref (G_UDEV_DEVICE (iter->data));
}
g_list_free (switches);
recheck_killswitches (self);
}
static void
dispose (GObject *object)
{
NMRfkillManager *self = NM_RFKILL_MANAGER (object);
NMRfkillManagerPrivate *priv = NM_RFKILL_MANAGER_GET_PRIVATE (self);
g_clear_object (&priv->client);
if (priv->killswitches) {
g_slist_free_full (priv->killswitches, (GDestroyNotify) killswitch_destroy);
priv->killswitches = NULL;
}
G_OBJECT_CLASS (nm_rfkill_manager_parent_class)->dispose (object);
}
static void
nm_rfkill_manager_class_init (NMRfkillManagerClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
g_type_class_add_private (klass, sizeof (NMRfkillManagerPrivate));
/* virtual methods */
object_class->dispose = dispose;
/* Signals */
signals[RFKILL_CHANGED] =
g_signal_new ("rfkill-changed",
G_OBJECT_CLASS_TYPE (object_class),
G_SIGNAL_RUN_FIRST,
G_STRUCT_OFFSET (NMRfkillManagerClass, rfkill_changed),
NULL, NULL, NULL,
G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_UINT);
}
| vicamo/NetworkManager | src/nm-rfkill-manager.c | C | gpl-2.0 | 11,265 |
<?php
/**
* File containing the RestContentType ValueObjectVisitor class
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
* @version 2014.11.1
*/
namespace eZ\Publish\Core\REST\Server\Output\ValueObjectVisitor;
use eZ\Publish\Core\REST\Common\Output\Generator;
use eZ\Publish\Core\REST\Common\Output\Visitor;
use eZ\Publish\API\Repository\Values\ContentType\ContentType as APIContentType;
use eZ\Publish\Core\REST\Server\Values;
/**
* RestContentType value object visitor
*/
class RestContentType extends RestContentTypeBase
{
/**
* Visit struct returned by controllers
*
* @param \eZ\Publish\Core\REST\Common\Output\Visitor $visitor
* @param \eZ\Publish\Core\REST\Common\Output\Generator $generator
* @param \eZ\Publish\Core\REST\Server\Values\RestContentType $data
*/
public function visit( Visitor $visitor, Generator $generator, $data )
{
$contentType = $data->contentType;
$urlTypeSuffix = $this->getUrlTypeSuffix( $contentType->status );
$mediaType = $data->fieldDefinitions !== null ? 'ContentType' : 'ContentTypeInfo';
$generator->startObjectElement( $mediaType );
$visitor->setHeader( 'Content-Type', $generator->getMediaType( $mediaType ) );
if ( $contentType->status === APIContentType::STATUS_DRAFT )
{
$visitor->setHeader( 'Accept-Patch', $generator->getMediaType( 'ContentTypeUpdate' ) );
}
$generator->startAttribute(
'href',
$this->router->generate(
'ezpublish_rest_loadContentType' . $urlTypeSuffix,
array(
'contentTypeId' => $contentType->id,
)
)
);
$generator->endAttribute( 'href' );
$generator->startValueElement( 'id', $contentType->id );
$generator->endValueElement( 'id' );
$generator->startValueElement( 'status', $this->serializeStatus( $contentType->status ) );
$generator->endValueElement( 'status' );
$generator->startValueElement( 'identifier', $contentType->identifier );
$generator->endValueElement( 'identifier' );
$this->visitNamesList( $generator, $contentType->getNames() );
$descriptions = $contentType->getDescriptions();
if ( is_array( $descriptions ) )
{
$this->visitDescriptionsList( $generator, $descriptions );
}
$generator->startValueElement( 'creationDate', $contentType->creationDate->format( 'c' ) );
$generator->endValueElement( 'creationDate' );
$generator->startValueElement( 'modificationDate', $contentType->modificationDate->format( 'c' ) );
$generator->endValueElement( 'modificationDate' );
$generator->startObjectElement( 'Creator', 'User' );
$generator->startAttribute(
'href',
$this->router->generate(
'ezpublish_rest_loadUser',
array( 'userId' => $contentType->creatorId )
)
);
$generator->endAttribute( 'href' );
$generator->endObjectElement( 'Creator' );
$generator->startObjectElement( 'Modifier', 'User' );
$generator->startAttribute(
'href',
$this->router->generate(
'ezpublish_rest_loadUser',
array( 'userId' => $contentType->modifierId )
)
);
$generator->endAttribute( 'href' );
$generator->endObjectElement( 'Modifier' );
$generator->startObjectElement( 'Groups', 'ContentTypeGroupRefList' );
$generator->startAttribute(
'href',
$this->router->generate(
'ezpublish_rest_loadGroupsOfContentType',
array( 'contentTypeId' => $contentType->id )
)
);
$generator->endAttribute( 'href' );
$generator->endObjectElement( 'Groups' );
$generator->startObjectElement( 'Draft', 'ContentType' );
$generator->startAttribute(
'href',
$this->router->generate(
'ezpublish_rest_loadContentTypeDraft',
array( 'contentTypeId' => $contentType->id )
)
);
$generator->endAttribute( 'href' );
$generator->endObjectElement( 'Draft' );
$generator->startValueElement( 'remoteId', $contentType->remoteId );
$generator->endValueElement( 'remoteId' );
$generator->startValueElement( 'urlAliasSchema', $contentType->urlAliasSchema );
$generator->endValueElement( 'urlAliasSchema' );
$generator->startValueElement( 'nameSchema', $contentType->nameSchema );
$generator->endValueElement( 'nameSchema' );
$generator->startValueElement(
'isContainer',
$this->serializeBool( $generator, $contentType->isContainer )
);
$generator->endValueElement( 'isContainer' );
$generator->startValueElement( 'mainLanguageCode', $contentType->mainLanguageCode );
$generator->endValueElement( 'mainLanguageCode' );
$generator->startValueElement(
'defaultAlwaysAvailable',
$this->serializeBool( $generator, $contentType->defaultAlwaysAvailable )
);
$generator->endValueElement( 'defaultAlwaysAvailable' );
$generator->startValueElement( 'defaultSortField', $this->serializeSortField( $contentType->defaultSortField ) );
$generator->endValueElement( 'defaultSortField' );
$generator->startValueElement( 'defaultSortOrder', $this->serializeSortOrder( $contentType->defaultSortOrder ) );
$generator->endValueElement( 'defaultSortOrder' );
if ( $data->fieldDefinitions !== null )
{
$visitor->visitValueObject(
new Values\FieldDefinitionList(
$contentType,
$data->fieldDefinitions
)
);
}
$generator->endObjectElement( $mediaType );
}
}
| wnsonsa/destin-foot | vendor/ezsystems/ezpublish-kernel/eZ/Publish/Core/REST/Server/Output/ValueObjectVisitor/RestContentType.php | PHP | gpl-2.0 | 6,138 |
/* input.h - Interface to the input component of a virtual console.
Copyright (C) 2002 Free Software Foundation, Inc.
Written by Marcus Brinkmann.
This file is part of the GNU Hurd.
The GNU Hurd is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2, or (at
your option) any later version.
The GNU Hurd 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, USA. */
#ifndef INPUT_H
#define INPUT_H
#include <errno.h>
struct input;
typedef struct input *input_t;
/* Create a new virtual console input queue, with the system encoding
being ENCODING. */
error_t input_create (input_t *r_input, const char *encoding);
/* Destroy the input queue INPUT. */
void input_destroy (input_t input);
/* Enter DATALEN characters from the buffer DATA into the input queue
INPUT. The DATA must be supplied in UTF-8 encoding (XXX UCS-4
would be nice, too, but it requires knowledge of endianness). The
function returns the amount of bytes written (might be smaller than
DATALEN) or -1 and the error number in errno. If NONBLOCK is not
zero, return with -1 and set errno to EWOULDBLOCK if operation
would block for a long time. */
ssize_t input_enqueue (input_t input, int nonblock, char *data,
size_t datalen);
/* Remove DATALEN characters from the input queue and put them in the
buffer DATA. The data will be supplied in the local encoding. The
function returns the amount of bytes removed (might be smaller than
DATALEN) or -1 and the error number in errno. If NONBLOCK is not
zero, return with -1 and set errno to EWOULDBLOCK if operation
would block for a long time. */
ssize_t input_dequeue (input_t input, int nonblock, char *data,
size_t datalen);
/* Flush the input buffer, discarding all pending data. */
void input_flush (input_t input);
#endif /* INPUT_H */
| sebastianscatularo/hurd | console/input.h | C | gpl-2.0 | 2,348 |
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.2 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2012 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2012
* $Id$
*
*/
class CRM_Utils_Migrate_ExportJSON {
CONST CHUNK_SIZE = 128;
protected $_contactIDs;
protected $_allContactIDs;
protected $_values;
protected $_discoverContacts = FALSE;
protected $_renameGroups = 1;
protected $_renameTags = 1;
protected $_sitePrefix = 'Site 1'; function __construct(&$params) {
foreach ($params as $name => $value) {
$varName = '_' . $name;
$this->$varName = $value;
}
}
/**
* Split a large array of contactIDs into more manageable smaller chunks
*/
function &splitContactIDs(&$contactIDs) {
// contactIDs could be a real large array, so we split it up into
// smaller chunks and then general xml for each chunk
$chunks = array();
$current = 0;
$chunks[$current] = array();
$count = 0;
foreach ($contactIDs as $k => $v) {
$chunks[$current][$k] = $v;
$count++;
if ($count == self::CHUNK_SIZE) {
$current++;
$chunks[$current] = array();
$count = 0;
}
}
if (empty($chunks[$current])) {
unset($chunks[$current]);
}
return $chunks;
}
/**
* Given a set of contact IDs get the values
*/
function getValues(&$contactIDs, &$additionalContactIDs) {
$this->contact($contactIDs);
$this->address($contactIDs);
$this->phone($contactIDs);
$this->email($contactIDs);
$this->im($contactIDs);
$this->website($contactIDs);
$this->note($contactIDs);
$this->group($contactIDs);
$this->groupContact($contactIDs);
$this->savedSearch($contactIDs);
$this->tag($contactIDs);
$this->entityTag($contactIDs);
$this->relationship($contactIDs, $additionalContactIDs);
$this->activity($contactIDs, $additionalContactIDs);
}
function metaData() {
$optionGroupVars = array(
'prefix_id' => 'individual_prefix',
'suffix_id' => 'individual_suffix',
'gender_id' => 'gender',
'mobile_provider' => 'mobile_provider',
'phone_type' => 'phone_type',
'activity_type' => 'activity_type',
'status_id' => 'activity_status_id',
'priority_id' => 'activity_priority_id',
'medium_id' => 'encounter_medium',
'email_greeting' => 'email_greeting',
'postal_greeting' => 'postal_greeting',
'addressee_id' => 'addressee',
);
$this->optionGroup($optionGroupVars);
$auxilaryTables = array(
'civicrm_location_type' => 'CRM_Core_DAO_LocationType',
'civicrm_relationship_type' => 'CRM_Contact_DAO_RelationshipType',
);
$this->auxTable($auxilaryTables);
}
function auxTable($tables) {
foreach ($tables as $tableName => $daoName) {
$fields = &$this->dbFields($daoName, TRUE);
$sql = "SELECT * from $tableName";
$this->sql($sql, $tableName, $fields);
}
}
function optionGroup($optionGroupVars) {
$names = array_values($optionGroupVars);
$str = array();
foreach ($names as $name) {
$str[] = "'$name'";
}
$nameString = implode(",", $str);
$sql = "
SELECT *
FROM civicrm_option_group
WHERE name IN ( $nameString )
";
$fields = &$this->dbFields('CRM_Core_DAO_OptionGroup', TRUE);
$this->sql($sql, 'civicrm_option_group', $fields);
$sql = "
SELECT v.*
FROM civicrm_option_value v
INNER JOIN civicrm_option_group g ON v.option_group_id = g.id
WHERE g.name IN ( $nameString )
";
$fields = &$this->dbFields('CRM_Core_DAO_OptionValue', TRUE);
$this->sql($sql, 'civicrm_option_value', $fields);
}
function table(&$ids,
$tableName,
&$fields,
$whereField,
$additionalWhereCond = NULL
) {
if (empty($ids)) {
return;
}
$idString = implode(',', $ids);
$sql = "
SELECT *
FROM $tableName
WHERE $whereField IN ( $idString )
";
if ($additionalWhereCond) {
$sql .= " AND $additionalWhereCond";
}
$this->sql($sql, $tableName, &$fields);
}
function sql($sql, $tableName, &$fields) {
$dao = &CRM_Core_DAO::executeQuery($sql);
while ($dao->fetch()) {
$value = array();
foreach ($fields as $name) {
if (empty($dao->$name)) {
$value[$name] = NULL;
}
else {
$value[$name] = $dao->$name;
}
}
$this->appendValue($dao->id, $tableName, $value);
}
$dao->free();
}
function contact(&$contactIDs) {
$fields = &$this->dbFields('CRM_Contact_DAO_Contact', TRUE);
$this->table($contactIDs, 'civicrm_contact', $fields, 'id', NULL);
}
function note(&$contactIDs) {
$fields = &$this->dbFields('CRM_Core_DAO_Note', TRUE);
$this->table($contactIDs, 'civicrm_note', $fields, 'entity_id', "entity_table = 'civicrm_contact'");
}
function phone(&$contactIDs) {
$fields = &$this->dbFields('CRM_Core_DAO_Phone', TRUE);
$this->table($contactIDs, 'civicrm_phone', $fields, 'contact_id', NULL);
}
function email(&$contactIDs) {
$fields = &$this->dbFields('CRM_Core_DAO_Email', TRUE);
$this->table($contactIDs, 'civicrm_email', $fields, 'contact_id', NULL);
}
function im(&$contactIDs) {
$fields = &$this->dbFields('CRM_Core_DAO_IM', TRUE);
$this->table($contactIDs, 'civicrm_im', $fields, 'contact_id', NULL);
}
function website(&$contactIDs) {
$fields = &$this->dbFields('CRM_Core_DAO_Website', TRUE);
$this->table($contactIDs, 'civicrm_website', $fields, 'contact_id', NULL);
}
function address(&$contactIDs) {
$fields = &$this->dbFields('CRM_Core_DAO_Email', TRUE);
$this->table($contactIDs, 'civicrm_address', $fields, 'contact_id', NULL);
}
function groupContact(&$contactIDs) {
$fields = &$this->dbFields('CRM_Contact_DAO_GroupContact', TRUE);
$this->table($contactIDs, 'civicrm_group_contact', $fields, 'contact_id', NULL);
}
// TODO - support group inheritance
// Parent child group ids are encoded in a text string
function group(&$contactIDs) {
// handle groups only once
static $_groupsHandled = array();
$ids = implode(',', $contactIDs);
$sql = "
SELECT DISTINCT group_id
FROM civicrm_group_contact
WHERE contact_id IN ( $ids )
";
$dao = CRM_Core_DAO::executeQuery($sql);
$groupIDs = array();
while ($dao->fetch()) {
if (!isset($_groupsHandled[$dao->group_id])) {
$groupIDs[] = $dao->group_id;
$_groupsHandled[$dao->group_id] = 1;
}
}
$fields = &$this->dbFields('CRM_Contact_DAO_Group', TRUE);
$this->table($groupIDs, 'civicrm_group', $fields, 'id');
$this->savedSearch($groupIDs);
}
// TODO - support search builder and custom saved searches
function savedSearch(&$groupIDs) {
if (empty($groupIDs)) {
return;
}
$idString = implode(",", $groupIDs);
$sql = "
SELECT s.*
FROM civicrm_saved_search s
INNER JOIN civicrm_group g on g.saved_search_id = s.id
WHERE g.id IN ( $idString )
";
$fields = &$this->dbFields('CRM_Contact_DAO_SavedSearch', TRUE);
$this->sql($sql, 'civicrm_saved_search', $fields);
}
function entityTag(&$contactIDs) {
$fields = &$this->dbFields('CRM_Core_DAO_EntityTag', TRUE);
$this->table($contactIDs, 'civicrm_entity_tag', $fields, 'entity_id', "entity_table = 'civicrm_contact'");
}
function tag(&$contactIDs) {
// handle tags only once
static $_tagsHandled = array();
$ids = implode(',', $contactIDs);
$sql = "
SELECT DISTINCT tag_id
FROM civicrm_entity_tag
WHERE entity_id IN ( $ids )
AND entity_table = 'civicrm_contact'
";
$dao = CRM_Core_DAO::executeQuery($sql);
$tagIDs = array();
while ($dao->fetch()) {
if (!isset($_tagsHandled[$dao->tag_id])) {
$tagIDs[] = $dao->tag_id;
$_tagsHandled[$dao->tag_id] = 1;
}
}
$fields = &$this->dbFields('CRM_Core_DAO_Tag', TRUE);
$this->table($tagIDs, 'civicrm_tag', $fields, 'id');
}
function relationship(&$contactIDs, &$additionalContacts) {
// handle relationships only once
static $_relationshipsHandled = array();
$ids = implode(',', $contactIDs);
$sql = "(
SELECT r.*
FROM civicrm_relationship r
WHERE r.contact_id_a IN ( $ids )
) UNION (
SELECT r.*
FROM civicrm_relationship r
WHERE r.contact_id_b IN ( $ids )
)
";
$fields = $this->dbFields('CRM_Contact_DAO_Relationship', TRUE);
$dao = &CRM_Core_DAO::executeQuery($sql);
while ($dao->fetch()) {
if (isset($_relationshipsHandled[$dao->id])) {
continue;
}
$_relationshipsHandled[$dao->id] = $dao->id;
$relationship = array();
foreach ($fields as $fld) {
if (empty($dao->$fld)) {
$relationship[$fld] = NULL;
}
else {
$relationship[$fld] = $dao->$fld;
}
}
$this->appendValue($dao->id, 'civicrm_relationship', $relationship);
$this->addAdditionalContacts(array(
$dao->contact_id_a,
$dao->contact_id_b,
),
$additionalContacts
);
}
$dao->free();
}
function activity(&$contactIDs, &$additionalContacts) {
static $_activitiesHandled = array();
$ids = implode(',', $contactIDs);
$sql = "(
SELECT a.*
FROM civicrm_activity a
INNER JOIN civicrm_activity_assignment aa ON aa.activity_id = a.id
WHERE aa.assignee_contact_id IN ( $ids )
AND ( a.activity_type_id != 3 AND a.activity_type_id != 20 )
) UNION (
SELECT a.*
FROM civicrm_activity a
INNER JOIN civicrm_activity_target at ON at.activity_id = a.id
WHERE at.target_contact_id IN ( $ids )
AND ( a.activity_type_id != 3 AND a.activity_type_id != 20 )
)
";
$fields = &$this->dbFields('CRM_Activity_DAO_Activity', TRUE);
$activityIDs = array();
$dao = &CRM_Core_DAO::executeQuery($sql);
while ($dao->fetch()) {
if (isset($_activitiesHandled[$dao->id])) {
continue;
}
$_activitiesHandled[$dao->id] = $dao->id;
$activityIDs[] = $dao->id;
$activity = array();
foreach ($fields as $fld) {
if (empty($dao->$fld)) {
$activity[$fld] = NULL;
}
else {
$activity[$fld] = $dao->$fld;
}
}
$this->appendValue($dao->id, 'civicrm_activity', $activity);
$this->addAdditionalContacts(array($dao->source_contact_id),
$additionalContacts
);
}
$dao->free();
if (empty($activityIDs)) {
return;
}
$activityIDString = implode(",", $activityIDs);
// now get all assignee contact ids and target contact ids for this activity
$sql = "SELECT * FROM civicrm_activity_assignment WHERE activity_id IN ($activityIDString)";
$aaDAO = &CRM_Core_DAO::executeQuery($sql);
$activityContacts = array();
while ($aaDAO->fetch()) {
$activityAssignee = array(
'id' => $aaDAO->id,
'assignee_contact_id' => $aaDAO->assignee_contact_id,
'activity_id' => $aaDAO->activity_id,
);
$this->appendValue($aaDAO->id, 'civicrm_activity_assignment', $activityAssignee);
$activityContacts[] = $aaDAO->assignee_contact_id;
}
$aaDAO->free();
$sql = "SELECT * FROM civicrm_activity_target WHERE activity_id IN ($activityIDString)";
$atDAO = &CRM_Core_DAO::executeQuery($sql);
while ($atDAO->fetch()) {
$activityTarget = array(
'id' => $atDAO->id,
'target_contact_id' => $atDAO->target_contact_id,
'activity_id' => $atDAO->activity_id,
);
$this->appendValue($atDAO->id, 'civicrm_activity_target', $activityTarget);
$activityContacts[] = $atDAO->target_contact_id;
}
$atDAO->free();
$this->addAdditionalContacts($activityContacts, $additionalContacts);
}
function appendValue($id, $name, $value) {
if (empty($value)) {
return;
}
if (!isset($this->_values[$name])) {
$this->_values[$name] = array();
$this->_values[$name][] = array_keys($value);
}
$this->_values[$name][] = array_values($value);
}
function dbFields($daoName, $onlyKeys = FALSE) {
static $_fieldsRetrieved = array();
if (!isset($_fieldsRetrieved[$daoName])) {
$_fieldsRetrieved[$daoName] = array();
$daoFile = str_replace('_',
DIRECTORY_SEPARATOR,
$daoName
) . '.php';
include_once ($daoFile);
$daoFields = &$daoName::fields();
foreach ($daoFields as $key => & $value) {
$_fieldsRetrieved[$daoName][$value['name']] = array(
'uniqueName' => $key,
'type' => $value['type'],
'title' => CRM_Utils_Array::value('title', $value, NULL),
);
}
}
if ($onlyKeys) {
return array_keys($_fieldsRetrieved[$daoName]);
}
else {
return $_fieldsRetrieved[$daoName];
}
}
function addAdditionalContacts($contactIDs, &$additionalContacts) {
if (!$this->_discoverContacts) {
return;
}
foreach ($contactIDs as $cid) {
if ($cid &&
!isset($this->_allContactIDs[$cid]) &&
!isset($additionalContacts[$cid])
) {
$additionalContacts[$cid] = $cid;
}
}
}
function export(&$contactIDs) {
$chunks = &$this->splitContactIDs($contactIDs);
$additionalContactIDs = array();
foreach ($chunks as $chunk) {
$this->getValues($chunk, $additionalContactIDs);
}
if (!empty($additionalContactIDs)) {
$this->_allContactIDs = $this->_allContactIDs + $additionalContactIDs;
$this->export($additionalContactIDs);
}
}
function run($fileName,
$lastExportTime = NULL,
$discoverContacts = FALSE
) {
$this->_discoverContacts = $discoverContacts;
if (!$lastExportTime) {
$sql = "
SELECT id
FROM civicrm_contact
";
}
else {
$sql = "(
SELECT DISTINCT entity_id
FROM civicrm_log
WHERE entity_table = 'civicrm_contact'
AND modified_date >= $lastExportTime
) UNION (
SELECT DISTINCT contact_id
FROM civicrm_subscription_history
WHERE date >= $lastExportTime
)
";
}
$dao = &CRM_Core_DAO::executeQuery($sql);
$contactIDs = array();
while ($dao->fetch()) {
$contactIDs[$dao->id] = $dao->id;
}
$this->_allContactIDs = $contactIDs;
$this->_values = array();
$this->metaData();
$this->export($contactIDs);
$json = json_encode($this->_values, JSON_NUMERIC_CHECK);
file_put_contents($fileName,
$json
);
// print_r( json_decode( $json ) );
}
}
| GreeneHillFoodCoop/members | sites/all/modules/civicrm/CRM/Utils/Migrate/ExportJSON.php | PHP | gpl-2.0 | 16,208 |
/*
* Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.InputEvent;
import java.util.Properties;
/*
* @test
* @key headful
* @summary To check the functionality of newly added API getSystemSelection & make sure
* that it's mapped to primary clipboard
* @author Jitender(jitender.singh@eng.sun.com) area=AWT
* @library /lib/client
* @build ExtendedRobot
* @run main SystemSelectionAWTTest
*/
public class SystemSelectionAWTTest {
Frame frame;
TextField tf1, tf2;
Clipboard clip;
Transferable t;
public static void main(String[] args) throws Exception {
new SystemSelectionAWTTest().doTest();
}
SystemSelectionAWTTest() {
frame = new Frame();
frame.setSize(200, 200);
tf1 = new TextField();
tf1.addFocusListener( new FocusAdapter() {
public void focusGained(FocusEvent fe) {
fe.getSource();
}
});
tf2 = new TextField();
frame.add(tf2, BorderLayout.NORTH);
frame.add(tf1, BorderLayout.CENTER);
frame.setVisible(true);
frame.toFront();
tf1.requestFocus();
tf1.setText("Selection Testing");
}
// Check whether Security manager is there
public void checkSecurity() {
SecurityManager sm = System.getSecurityManager();
if (sm == null) {
System.out.println("security manager is not there");
getPrimaryClipboard();
} else {
try {
sm.checkPermission(new AWTPermission("accessClipboard"));
getPrimaryClipboard();
} catch(SecurityException e) {
clip = null;
System.out.println("Access to System selection is not allowed");
}
}
}
// Get the contents from the clipboard
void getClipboardContent() throws Exception {
t = clip.getContents(this);
if ( (t != null) && (t.isDataFlavorSupported(DataFlavor.stringFlavor) )) {
tf2.setBackground(Color.red);
tf2.setForeground(Color.black);
tf2.setText((String) t.getTransferData(DataFlavor.stringFlavor));
}
}
// Get System Selection i.e. Primary Clipboard
private void getPrimaryClipboard() {
Properties ps = System.getProperties();
String operSys = ps.getProperty("os.name");
clip = Toolkit.getDefaultToolkit().getSystemSelection();
if (clip == null) {
if ((operSys.substring(0,3)).equalsIgnoreCase("Win") ||
(operSys.substring(0,3)).equalsIgnoreCase("Mac"))
System.out.println(operSys + " operating system does not support system selection ");
else
throw new RuntimeException("Method getSystemSelection() is returning null on X11 platform");
}
}
// Compare the selected text with one pasted from the clipboard
public void compareText() {
if ((tf2.getText()).equals(tf1.getSelectedText()) &&
System.getProperties().getProperty("os.name").substring(0,3) != "Win") {
System.out.println("Selected text & clipboard contents are same\n");
} else {
throw new RuntimeException("Selected text & clipboard contents differs\n");
}
}
public void doTest() throws Exception {
ExtendedRobot robot = new ExtendedRobot();
frame.setLocation(100, 100);
robot.waitForIdle(2000);
Point tf1Location = tf1.getLocationOnScreen();
Dimension tf1Size = tf1.getSize();
checkSecurity();
if (clip != null) {
robot.mouseMove(tf1Location.x + 5, tf1Location.y + tf1Size.height / 2);
robot.waitForIdle(2000);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle(20);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle(20);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle(20);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle(2000);
getClipboardContent();
compareText();
robot.mouseMove(tf1Location.x + tf1Size.width / 2, tf1Location.y + tf1Size.height / 2);
robot.waitForIdle(2000);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle(20);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle(20);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle(20);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle(2000);
getClipboardContent();
compareText();
}
}
}
| md-5/jdk10 | test/jdk/java/awt/datatransfer/SystemSelection/SystemSelectionAWTTest.java | Java | gpl-2.0 | 6,193 |
/* <!-- copyright */
/*
* aria2 - The high speed download utility
*
* Copyright (C) 2006 Tatsuhiro Tsujikawa
*
* 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
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
/* copyright --> */
#ifndef D_TIMED_HALT_COMMAND_H
#define D_TIMED_HALT_COMMAND_H
#include "TimeBasedCommand.h"
namespace aria2 {
class TimedHaltCommand:public TimeBasedCommand {
private:
bool forceHalt_;
public:
TimedHaltCommand(cuid_t cuid, DownloadEngine* e,
std::chrono::seconds secondsToHalt, bool forceHalt = false);
virtual ~TimedHaltCommand();
virtual void preProcess() CXX11_OVERRIDE;
virtual void process() CXX11_OVERRIDE;
};
} // namespace aria2
#endif // D_TIMED_HALT_COMMAND_H
| bright-sparks/aria2 | src/TimedHaltCommand.h | C | gpl-2.0 | 2,103 |
//===========================================================
// Lukas Valine * Mr. Inspiration * February 18, 2015
//===========================================================
// An algorithmic approach to music composition
//-----------------------------------------------------------
import java.awt.Color;
import java.awt.FontFormatException;
import java.io.IOException;
import javax.swing.JFrame;
import Controller.Controller;
import Model.Model;
import View.MainView;
public class MrInspiration{
public static void main(String[] args) throws FontFormatException, IOException{
System.setProperty("awt.useSystemAAFontSettings","on");
System.setProperty("swing.aatext", "true");
Model theModel = new Model();
MainView theView = new MainView(theModel);
Controller theController = new Controller(theView, theModel);
theModel.addObserver(theView);
theView.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theView.setSize(950,800);
theView.getContentPane().setBackground(new Color(180, 180, 180));
theView.setVisible(true);}}
| Valine/mri | SwingVersion/Mr.i_0.3/src/MrInspiration.java | Java | gpl-2.0 | 1,064 |
/*
* Copyright 2009 Marco Martin <notmart@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, 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 Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef PLASMA_ASSOCIATEDAPPLICATIONMANAGER_P_H
#define PLASMA_ASSOCIATEDAPPLICATIONMANAGER_P_H
#include <QObject>
#include <kurl.h>
namespace Plasma
{
class Applet;
class AssociatedApplicationManagerPrivate;
class AssociatedApplicationManager : public QObject
{
Q_OBJECT
public:
static AssociatedApplicationManager *self();
//set an application name for an applet
void setApplication(Plasma::Applet *applet, const QString &application);
//returns the application name associated to an applet
QString application(const Plasma::Applet *applet) const;
//sets the urls associated to an applet
void setUrls(Plasma::Applet *applet, const KUrl::List &urls);
//returns the urls associated to an applet
KUrl::List urls(const Plasma::Applet *applet) const;
//run the associated application or the urls if no app is associated
void run(Plasma::Applet *applet);
//returns true if the applet has a valid associated application or urls
bool appletHasValidAssociatedApplication(const Plasma::Applet *applet) const;
private:
AssociatedApplicationManager(QObject *parent = 0);
~AssociatedApplicationManager();
AssociatedApplicationManagerPrivate *const d;
friend class AssociatedApplicationManagerSingleton;
Q_PRIVATE_SLOT(d, void cleanupApplet(QObject *obj))
};
} // namespace Plasma
#endif // multiple inclusion guard
| vasi/kdelibs | plasma/private/associatedapplicationmanager_p.h | C | gpl-2.0 | 2,204 |
############################################################################
# IlbcRfc3951Config.cmake
# Copyright (C) 2015 Belledonne Communications, Grenoble France
#
############################################################################
#
# 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.
#
############################################################################
#
# Config file for the libilbcrfc3951 package.
# It defines the following variables:
#
# ILBCRFC3951_FOUND - system has libilbcrfc3951
# ILBCRFC3951_INCLUDE_DIRS - the libilbcrfc3951 include directory
# ILBCRFC3951_LIBRARIES - The libraries needed to use libilbcrfc3951
include("${CMAKE_CURRENT_LIST_DIR}/IlbcRfc3951Targets.cmake")
get_filename_component(ILBCRFC3951_CMAKE_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
set(ILBCRFC3951_INCLUDE_DIRS "${ILBCRFC3951_CMAKE_DIR}/../../../include")
set(ILBCRFC3951_LIBRARIES BelledonneCommunications::ilbcrfc3951)
set(ILBCRFC3951_FOUND 1)
| husseinalzand/linphone | liblinphone-sdk/x86_64-apple-darwin.ios/lib/cmake/IlbcRfc3951/IlbcRfc3951Config.cmake | CMake | gpl-2.0 | 1,612 |
/*
* Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
*
* @summary converted from VM Testbase runtime/jbe/hoist/hoist01.
* VM Testbase keywords: [quick, runtime]
*
* @library /vmTestbase
* /test/lib
* @run driver jdk.test.lib.FileInstaller . .
* @run main/othervm vm.compiler.jbe.hoist.hoist01.hoist01
*/
package vm.compiler.jbe.hoist.hoist01;
// hoist01.java
/* -- Test hoist invariant code of double expression. This eliminates unnecessary recomputations of invariant expressions in loops.
Example:
double a[];
double x, y, z;
for (i = 0; i < 100; i++)
a[i] = (x + y)*z;
*/
public class hoist01 {
final static double PI=3.14159;
int LEN = 5000;
double a[] = new double[LEN];
double aopt[] = new double[LEN];
int i1=1, i2=2, i3=3, i4=4, i5=5, i6=6, i7=7, i8=8;
int i9=9, i10=10, i11=11, i12=12, i13=13, i14=14, i15=15;
public static void main(String args[]) {
hoist01 hst = new hoist01();
hst.f();
hst.fopt();
if (hst.eCheck()) {
System.out.println("Test hoist01 Passed.");
} else {
throw new Error("Test hoist01 Failed.");
}
}
void f() {
// Non-optimized version: i1 through i15 are invariants
for (int i = 1; i < a.length; i++) {
a[0] = Math.sin(2 * PI * Math.pow(1/PI,3));
a[i] = a[0] + (i1 + i2)*PI + i3 + i4 + i5/i6*i7 +
i9%i8 + i10*(i11*i12) + i13 + i14 + i15;
}
}
// Code fragment after the invariant expression is hoisted out of the loop.
void fopt() {
double t;
aopt[0] = Math.sin(2 * PI * Math.pow(1/PI,3));
t = aopt[0] + (i1 + i2)*PI + i3 + i4 + i5/i6*i7 +
i9%i8 + i10*(i11*i12) + i13 + i14 + i15;
for (int i = 1; i < aopt.length; i++) {
aopt[i] = t;
}
}
// Check Loop Hoisting results
boolean eCheck() {
for (int i = 0; i < a.length; i++)
if (a[i] != aopt[i])
return false;
return true;
}
}
| md-5/jdk10 | test/hotspot/jtreg/vmTestbase/vm/compiler/jbe/hoist/hoist01/hoist01.java | Java | gpl-2.0 | 3,088 |
Ext.define('KitchenSink.view.charts.area.NegativeController', {
extend: 'Ext.app.ViewController',
alias: 'controller.area-negative',
onPreview: function () {
var chart = this.lookupReference('chart');
chart.preview();
},
getSeriesConfig: function (field, title) {
return {
type: 'area',
title: title,
xField: 'quarter',
yField: field,
style: {
opacity: 0.60
},
marker: {
opacity: 0,
scaling: 0.01,
fx: {
duration: 200,
easing: 'easeOut'
}
},
highlightCfg: {
opacity: 1,
scaling: 1.5
},
tooltip: {
trackMouse: true,
renderer: function (tooltip, record, item) {
tooltip.setHtml(title + ' (' + record.get('quarter') + '): ' +
record.get(field));
}
}
};
},
onAfterRender: function () {
var me = this,
chart = me.lookupReference('chart');
chart.setSeries([
me.getSeriesConfig('phone', 'Phone Hardware'),
me.getSeriesConfig('consumer', 'Consumer Licensing'),
me.getSeriesConfig('gaming', 'Gaming Hardware'),
me.getSeriesConfig('corporate', 'Corporate and Other')
]);
}
}); | mesocentrefc/Janua-SMS | janua-web/ext/examples/kitchensink/classic/samples/view/charts/area/NegativeController.js | JavaScript | gpl-2.0 | 1,559 |
// NAnt - A .NET build tool
// Copyright (C) 2001-2008 Gerry Shaw
//
// 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
//
// Gert Driesen (drieseng@users.sourceforge.net.be)
namespace NAnt.Core.Extensibility {
public interface IPlugin {
}
}
| nant/nant | src/NAnt.Core/Extensibility/IPlugin.cs | C# | gpl-2.0 | 913 |
{template "content","header"}
<link href="{CSS_PATH}vms/vms.css" rel="stylesheet" type="text/css" />
<div class="clr ct show_pg">
<div class="crumbs"><a href="{APP_PATH}">首页</a><span> > </span>{catpos($catid)}> 正文</div>
<div class="ad"><a href="#" title="text"><img src="{IMG_PATH}vms/vms/ad960x40.jpg" width="960" height="40"></a></div>
<div class="lty1">
<div class="clr">
<div class="zj"><h5>{$title}</h5></div>
<div class="clr xxg">
<div class="clr">总播放:<span id="hits"></span> <span>|</span> 更新时间:{$inputtime}</div>
</div>
</div>
<div class="plbox">
<embed src="{pc_base::load_config('ku6server', 'player_url')}MkSb6DCJMuQSFrG8/style/0rbBFMwIVDQ./" quality="high" width="600" height="500" align="middle" allowScriptAccess="always" allowfullscreen="true" type="application/x-shockwave-flash"></embed>
</div>
<div class="sr">
<ul class="srli">
<li>
<a href="#" title="text" class="xx"></a>
<strong>分享视频:</strong><a href="#" title="text" class=""></a>
<!-- Baidu Button BEGIN -->
<div id="bdshare" class="bdshare_b" style="line-height: 12px;"><img src="http://bdimg.share.baidu.com/static/images/type-button-5.jpg" />
<a class="shareCount"></a>
</div>
<script type="text/javascript" id="bdshare_js" data="type=button" ></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=" + new Date().getHours();
</script>
<!-- Baidu Button END -->
</li>
<li>
<strong>嵌入代码:</strong>
<input name="radio" type="radio" value="1" onclick="">
<label>网页代码</label><input name="radio" type="radio" value="2" onclick="">
<label>脚本代码</label>
</li>
<li>
<input name="url" id="url" type="text" class="fz_ipt"><input type="button" class="fz_btn" value="复制">
</li>
</ul>
</div>
<div class="clr bfj">
{if $video[data]}
{loop $video[data] $v}
<a href="{$v[url]}" >{$v[title]}</a>
{/loop}
{/if}
</div>
<div class="clr mgt10 mgb10">
{if $allow_comment && module_exists('comment')}
<iframe src="{APP_PATH}index.php?m=comment&c=index&a=init&commentid={id_encode("content_$catid",$id,$siteid)}&iframe=1" width="100%" height="100%" id="comment_iframe" frameborder="0" scrolling="no"></iframe>
<div class="bk10"></div>
<div class="box">
<h5>评论排行</h5>
{pc:comment action="bang" siteid="$siteid" cache="3600"}
<ul class="content list blue f14 row-2">
{loop $data $r}
<li>·<a href="{$r[url]}" target="_blank">{str_cut($r[title], 40)}</a><span>({$r[total]})</span></li>
{/loop}
</ul>
{/pc}
</div>
{/if}
</div>
</div>
<div class="wp lty2">
<div class="box0">
<div class="nav">
<span class="more"><input name="" type="checkbox" value="" id="lb"> <label for="lb">联播</label></span>
<h5>专辑列表</h5>
</div>
<div class="bct">
<div class="lbbox">
<ul class="c1 c2">
{pc:special action="content_list" specialid="19" listorder="2" num="3"}
{loop $data $r}
<li>
<div class="clr h77">
<a href="{$r[url]}" ><img src="{$r[thumb]}" width="104" height="65" class="l"></a>
<div class="lh21"><a href="{$r[url]}" >{$r[title]}</a></div>
<div class="sz"><span class="shows">播放次数:23 </span><span>评论:321</span></div>
</div>
</li>
{/loop}
{/pc}
</ul>
</div>
</div>
</div>
<div class="ad"><a href="#" title="text"><img src="{IMG_PATH}vms/vms/318x63.jpg" width="318" height="63"></a></div>
<div class="box0">
<div class="nav"><h5>精彩推荐</h5></div>
<div class="bct">
<ul class="c1 c2">
{pc:content action="position" posid="18" catid="$catid" order="listorder DESC" num="6" return="info"}
{loop $info $v}
<li>
<div class="clr h77">
<a href="{$v[url]}" target="_blank" title="{$v[title]}"><img src="{$v[thumb]}" width="104" height="65" class="l"></a>
<div class="lh21"><a href="{$v[url]}" title="{$v[title]}" target="_blank">{str_cut($v[title],22,false)}</a></div>
<div class="sz"><span class="shows">播放次数:{get_views('c-'.$CATEGORYS[$v[catid]][modelid].'-'.$v['id'])}</span><span>评论:{get_comments(id_encode("content_$v[catid]",$v[id],$siteid))}</span></div>
</div>
</li>
{/loop}
{/pc}
</ul>
</div>
</div>
</div>
</div>
<script language="JavaScript" src="{APP_PATH}api.php?op=count&id={$id}&modelid={$modelid}"></script>
<script language="JavaScript">
<!--
//切换地址
function show_url(id) {
var local_value = $('#url').val();
if(id == 1){
$('#url').val('');
}else{
}
var local = 'local'+id;
var remote = 'remote'+id;
var remote_value = $('#'+remote).val();
$.get('index.php', {m:'cloudhost', c:'bucket', a:'ChangeBucket', local:local_value,remote:remote_value, id:id, time:Math.random()}, function (data){
if(data=='ok'){
alert('记录修改成功!');
}else{
alert('修改失败!');
}
});
}
//-->
})
</script>
{template "content","footer"}
| fishermanmax/fdyzt | phpcms/templates/xsc_fdyzt/content/play_list.html | HTML | gpl-2.0 | 5,601 |
#ifndef included_main_version_h
#define included_main_version_h
/*****************************************************************************/
/* */
/* Copyright (c) 1990-2001 Morgan Stanley Dean Witter & Co. All rights reserved. */
/* See .../src/LICENSE for terms of distribution. */
/* */
/* */
/*****************************************************************************/
/* external macro declarations */
#define RELEASE_CODE "4.22"
#define OWNER_FULLNAME ""
#define IMDIR "/usr/local"
#endif /* included_main_version_h */
| PlanetAPL/a-plus | src/main/version.h | C | gpl-2.0 | 842 |
#! /usr/bin/python
# Script for increasing versions numbers across the code
import sys
import glob
import re
import argparse
def check_version_format(version):
"""Check format of version number"""
pattern = '^[0-9]+[\.][0-9]+[\.][0-9]+(\-.+)*$'
return re.match(pattern, version) is not None
BIO_FORMATS_ARTIFACT = (
r"(<groupId>%s</groupId>\n"
".*<artifactId>pom-bio-formats</artifactId>\n"
".*<version>).*(</version>)")
class Replacer(object):
def __init__(self, old_group="ome", new_group="ome"):
self.old_group = old_group
self.new_group = new_group
self.group_pattern = \
r"(<groupId>)%s(</groupId>)" % \
old_group
self.artifact_pattern = BIO_FORMATS_ARTIFACT % old_group
self.release_version_pattern = \
r"(<release.version>).*(</release.version>)"
self.stableversion_pattern = \
r"(STABLE_VERSION = \").*(\";)"
self.upgradecheck = \
"components/formats-bsd/src/loci/formats/UpgradeChecker.java"
def replace_file(self, input_path, pattern, version):
"""Substitute a pattern with version in a file"""
with open(input_path, "r") as infile:
regexp = re.compile(pattern)
new_content = regexp.sub(r"\g<1>%s\g<2>" % version, infile.read())
with open(input_path, "w") as output:
output.write(new_content)
output.close()
infile.close()
def bump_pom_versions(self, version):
"""Replace versions in pom.xml files"""
# Replace versions in components pom.xml
for pomfile in (glob.glob("*/*/pom.xml") + glob.glob("*/*/*/pom.xml")):
self.replace_file(pomfile, self.artifact_pattern, version)
self.replace_file(pomfile, self.group_pattern, self.new_group)
# Replace versions in top-level pom.xml
toplevelpomfile = "pom.xml"
self.replace_file(
toplevelpomfile, self.artifact_pattern, version)
self.replace_file(
toplevelpomfile, self.release_version_pattern, version)
self.replace_file(
toplevelpomfile, self.group_pattern, self.new_group)
def bump_stable_version(self, version):
"""Replace UpgradeChecker stable version"""
self.replace_file(
self.upgradecheck, self.stableversion_pattern, version)
if __name__ == "__main__":
# Input check
parser = argparse.ArgumentParser()
parser.add_argument("--old-group", type=str, default="ome")
parser.add_argument("--new-group", type=str, default="ome")
parser.add_argument("version", type=str)
ns = parser.parse_args()
if not check_version_format(ns.version):
print "Invalid version format"
sys.exit(1)
replacer = Replacer(old_group=ns.old_group, new_group=ns.new_group)
replacer.bump_pom_versions(ns.version)
if not ns.version.endswith('SNAPSHOT'):
replacer.bump_stable_version(ns.version)
| stelfrich/bioformats | tools/bump_maven_version.py | Python | gpl-2.0 | 3,006 |
<?php
/**
* This software is intended for use with Oxwall Free Community Software http://www.oxwall.org/ and is
* licensed under The BSD license.
* ---
* Copyright (c) 2011, Oxwall Foundation
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this list of conditions and
* the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Oxwall Foundation nor the names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
$errors = array();
try
{
Updater::getDbo()->query("ALTER TABLE `" . OW_DB_PREFIX . "event_user` ADD INDEX `userId` ( `userId` )");
}
catch( Exception $e )
{
$errors[] = $e;
}
try
{
Updater::getDbo()->query("ALTER TABLE `" . OW_DB_PREFIX . "event_invite` DROP INDEX `userId`");
}
catch( Exception $e )
{
$errors[] = $e;
}
Updater::getLanguageService()->importPrefixFromZip(dirname(__FILE__) . DS . 'langs.zip', 'event'); | seret/oxtebafu | ow_plugins/event/update/3521/update.php | PHP | gpl-2.0 | 2,153 |
/* Handle loading and unloading shared objects for internal libc purposes.
Copyright (C) 1999-2002,2004,2005,2006 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Zack Weinberg <zack@rabi.columbia.edu>, 1999.
The GNU C 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.
The GNU C 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 the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <dlfcn.h>
#include <stdlib.h>
#include <ldsodefs.h>
extern int __libc_argc attribute_hidden;
extern char **__libc_argv attribute_hidden;
extern char **__environ;
/* The purpose of this file is to provide wrappers around the dynamic
linker error mechanism (similar to dlopen() et al in libdl) which
are usable from within libc. Generally we want to throw away the
string that dlerror() would return and just pass back a null pointer
for errors. This also lets the rest of libc not know about the error
handling mechanism.
Much of this code came from gconv_dl.c with slight modifications. */
static int
internal_function
dlerror_run (void (*operate) (void *), void *args)
{
const char *objname;
const char *last_errstring = NULL;
bool malloced;
(void) GLRO(dl_catch_error) (&objname, &last_errstring, &malloced,
operate, args);
int result = last_errstring != NULL;
if (result && malloced)
free ((char *) last_errstring);
return result;
}
/* These functions are called by dlerror_run... */
struct do_dlopen_args
{
/* Argument to do_dlopen. */
const char *name;
/* Opening mode. */
int mode;
/* Return from do_dlopen. */
struct link_map *map;
};
struct do_dlsym_args
{
/* Arguments to do_dlsym. */
struct link_map *map;
const char *name;
/* Return values of do_dlsym. */
lookup_t loadbase;
const ElfW(Sym) *ref;
};
static void
do_dlopen (void *ptr)
{
struct do_dlopen_args *args = (struct do_dlopen_args *) ptr;
/* Open and relocate the shared object. */
args->map = GLRO(dl_open) (args->name, args->mode, NULL, __LM_ID_CALLER,
__libc_argc, __libc_argv, __environ);
}
static void
do_dlsym (void *ptr)
{
struct do_dlsym_args *args = (struct do_dlsym_args *) ptr;
args->ref = NULL;
args->loadbase = GLRO(dl_lookup_symbol_x) (args->name, args->map, &args->ref,
args->map->l_local_scope, NULL, 0,
DL_LOOKUP_RETURN_NEWEST, NULL);
}
static void
do_dlclose (void *ptr)
{
GLRO(dl_close) ((struct link_map *) ptr);
}
/* This code is to support __libc_dlopen from __libc_dlopen'ed shared
libraries. We need to ensure the statically linked __libc_dlopen
etc. functions are used instead of the dynamically loaded. */
struct dl_open_hook
{
void *(*dlopen_mode) (const char *name, int mode);
void *(*dlsym) (void *map, const char *name);
int (*dlclose) (void *map);
};
#ifdef SHARED
extern struct dl_open_hook *_dl_open_hook;
libc_hidden_proto (_dl_open_hook);
struct dl_open_hook *_dl_open_hook __attribute__ ((nocommon));
libc_hidden_data_def (_dl_open_hook);
#else
static void
do_dlsym_private (void *ptr)
{
lookup_t l;
struct r_found_version vers;
vers.name = "GLIBC_PRIVATE";
vers.hidden = 1;
/* vers.hash = _dl_elf_hash (vers.name); */
vers.hash = 0x0963cf85;
vers.filename = NULL;
struct do_dlsym_args *args = (struct do_dlsym_args *) ptr;
args->ref = NULL;
l = GLRO(dl_lookup_symbol_x) (args->name, args->map, &args->ref,
args->map->l_scope, &vers, 0, 0, NULL);
args->loadbase = l;
}
static struct dl_open_hook _dl_open_hook =
{
.dlopen_mode = __libc_dlopen_mode,
.dlsym = __libc_dlsym,
.dlclose = __libc_dlclose
};
#endif
/* ... and these functions call dlerror_run. */
void *
__libc_dlopen_mode (const char *name, int mode)
{
struct do_dlopen_args args;
args.name = name;
args.mode = mode;
#ifdef SHARED
if (__builtin_expect (_dl_open_hook != NULL, 0))
return _dl_open_hook->dlopen_mode (name, mode);
return (dlerror_run (do_dlopen, &args) ? NULL : (void *) args.map);
#else
if (dlerror_run (do_dlopen, &args))
return NULL;
__libc_register_dl_open_hook (args.map);
__libc_register_dlfcn_hook (args.map);
return (void *) args.map;
#endif
}
libc_hidden_def (__libc_dlopen_mode)
#ifndef SHARED
void *
__libc_dlsym_private (struct link_map *map, const char *name)
{
struct do_dlsym_args sargs;
sargs.map = map;
sargs.name = name;
if (! dlerror_run (do_dlsym_private, &sargs))
return DL_SYMBOL_ADDRESS (sargs.loadbase, sargs.ref);
return NULL;
}
void
__libc_register_dl_open_hook (struct link_map *map)
{
struct dl_open_hook **hook;
hook = (struct dl_open_hook **) __libc_dlsym_private (map, "_dl_open_hook");
if (hook != NULL)
*hook = &_dl_open_hook;
}
#endif
void *
__libc_dlsym (void *map, const char *name)
{
struct do_dlsym_args args;
args.map = map;
args.name = name;
#ifdef SHARED
if (__builtin_expect (_dl_open_hook != NULL, 0))
return _dl_open_hook->dlsym (map, name);
#endif
return (dlerror_run (do_dlsym, &args) ? NULL
: (void *) (DL_SYMBOL_ADDRESS (args.loadbase, args.ref)));
}
libc_hidden_def (__libc_dlsym)
int
__libc_dlclose (void *map)
{
#ifdef SHARED
if (__builtin_expect (_dl_open_hook != NULL, 0))
return _dl_open_hook->dlclose (map);
#endif
return dlerror_run (do_dlclose, map);
}
libc_hidden_def (__libc_dlclose)
libc_freeres_fn (free_mem)
{
struct link_map *l;
struct r_search_path_elem *d;
/* Remove all search directories. */
d = GL(dl_all_dirs);
while (d != GLRO(dl_init_all_dirs))
{
struct r_search_path_elem *old = d;
d = d->next;
free (old);
}
/* Remove all additional names added to the objects. */
for (Lmid_t ns = 0; ns < DL_NNS; ++ns)
for (l = GL(dl_ns)[ns]._ns_loaded; l != NULL; l = l->l_next)
{
struct libname_list *lnp = l->l_libname->next;
l->l_libname->next = NULL;
while (lnp != NULL)
{
struct libname_list *old = lnp;
lnp = lnp->next;
if (! old->dont_free)
free (old);
}
}
}
| mseaborn/nacl-glibc | elf/dl-libc.c | C | gpl-2.0 | 6,598 |
/**
*
* This example shows how to create a pivot grid and display the results in
* a compact layout.
*
*/
Ext.define('KitchenSink.view.pivot.LayoutCompact', {
extend: 'Ext.pivot.Grid',
xtype: 'compact-pivot-grid',
controller: 'pivotlayout',
requires: [
'KitchenSink.store.pivot.Sales',
'KitchenSink.view.pivot.LayoutController'
],
title: 'Compact layout',
collapsible: true,
multiSelect: true,
height: 350,
store: {
type: 'sales'
},
selModel: {
type: 'cellmodel'
},
// Set layout type to "compact"
viewLayoutType: 'compact',
// Set this to false if multiple dimensions are configured on leftAxis and
// you want to automatically expand the row groups when calculations are ready.
startRowGroupsCollapsed: false,
// Set this to false if multiple dimensions are configured on topAxis and
// you want to automatically expand the col groups when calculations are ready.
startColGroupsCollapsed: false,
// Configure the aggregate dimensions. Multiple dimensions are supported.
aggregate: [{
dataIndex: 'value',
header: 'Sum of value',
aggregator: 'sum',
width: 90
}],
// Configure the left axis dimensions that will be used to generate the grid rows
leftAxis: [{
dataIndex: 'person',
header: 'Person'
},{
dataIndex: 'company',
header: 'Company',
sortable: false
},{
dataIndex: 'country',
header: 'Country'
}],
// Configure the top axis dimensions that will be used to generate the columns.
// When columns are generated the aggregate dimensions are also used. If multiple aggregation dimensions
// are defined then each top axis result will have in the end a column header with children
// columns for each aggregate dimension defined.
topAxis: [{
dataIndex: 'year',
header: 'Year'
}, {
dataIndex: 'month',
header: 'Month',
renderer: function(v){
return Ext.Date.monthNames[v];
}
}],
tbar: [{
text: 'Collapsing',
menu: [{
text: 'Collapse all',
handler: 'collapseAll'
},{
text: 'Expand all',
handler: 'expandAll'
}]
},{
text: 'Subtotals position',
menu: {
defaults: {
xtype: 'menucheckitem',
group: 'subtotals',
checkHandler: 'subtotalsHandler'
},
items: [{
text: 'First',
checked: true
},{
text: 'Last'
},{
text: 'None'
}]
}
},{
text: 'Totals position',
menu: {
defaults: {
xtype: 'menucheckitem',
group: 'totals',
checkHandler: 'totalsHandler'
},
items: [{
text: 'First'
},{
text: 'Last',
checked: true
},{
text: 'None'
}]
}
}],
//<example>
otherContent: [{
type: 'Controller',
path: 'classic/samples/view/pivot/LayoutController.js'
},{
type: 'Model',
path: 'classic/samples/model/pivot/Sale.js'
},{
type: 'Store',
path: 'classic/samples/store/pivot/Sales.js'
}],
profiles: {
classic: {
width: 600
},
neptune: {
width: 750
}
},
//</example>
initComponent: function () {
var me = this;
me.width = me.profileInfo.width;
me.callParent();
}
});
| mesocentrefc/Janua-SMS | janua-web/ext/examples/kitchensink/classic/samples/view/pivot/LayoutCompact.js | JavaScript | gpl-2.0 | 3,950 |
<?php
/**
* File generates service container builder instance
*
* Expects global $installDir to be set by caller
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
* @version 2014.11.1
*/
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\Config\FileLocator;
use eZ\Publish\Core\Base\Container\Compiler;
use Symfony\Component\Config\Resource\FileResource;
if ( !isset( $installDir ) )
{
throw new \RuntimeException( '$installDir not provided to ' . __FILE__ );
}
$containerBuilder = new ContainerBuilder();
// Track current file for changes
$containerBuilder->addResource( new FileResource( __FILE__ ) );
$settingsPath = $installDir . "/eZ/Publish/Core/settings/";
$loader = new YamlFileLoader( $containerBuilder, new FileLocator( $settingsPath ) );
$loader->load( 'fieldtype_external_storages.yml' );
$loader->load( 'fieldtype_services.yml' );
$loader->load( 'fieldtypes.yml' );
$loader->load( 'indexable_fieldtypes.yml' );
$loader->load( 'io.yml' );
$loader->load( 'repository.yml' );
$loader->load( 'roles.yml' );
$loader->load( 'storage_engines/common.yml' );
$loader->load( 'storage_engines/cache.yml' );
$loader->load( 'storage_engines/legacy.yml' );
$loader->load( 'storage_engines/legacy_solr.yml' );
$loader->load( 'storage_engines/legacy_elasticsearch.yml' );
$loader->load( 'settings.yml' );
$loader->load( 'utils.yml' );
$containerBuilder->setParameter( "ezpublish.kernel.root_dir", $installDir );
$containerBuilder->addCompilerPass( new Compiler\FieldTypeCollectionPass() );
$containerBuilder->addCompilerPass( new Compiler\RegisterLimitationTypePass() );
$containerBuilder->addCompilerPass( new Compiler\Storage\ExternalStorageRegistryPass() );
$containerBuilder->addCompilerPass( new Compiler\Storage\Legacy\CriteriaConverterPass() );
$containerBuilder->addCompilerPass( new Compiler\Storage\Legacy\CriterionFieldValueHandlerRegistryPass() );
$containerBuilder->addCompilerPass( new Compiler\Storage\Legacy\FieldValueConverterRegistryPass() );
$containerBuilder->addCompilerPass( new Compiler\Storage\Legacy\RoleLimitationConverterPass() );
$containerBuilder->addCompilerPass( new Compiler\Storage\Legacy\SortClauseConverterPass() );
return $containerBuilder;
| cjw-network/cjwpublish1411 | vendor/ezsystems/ezpublish-kernel/eZ/Publish/Core/settings/containerBuilder.php | PHP | gpl-2.0 | 2,414 |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />
<link rel="shortcut icon" type="image/x-icon" href="../../../../../../../favicon.ico" />
<title>ChangeEvent | Android Developers</title>
<!-- STYLESHEETS -->
<link rel="stylesheet"
href="http://fonts.googleapis.com/css?family=Roboto+Condensed">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:light,regular,medium,thin,italic,mediumitalic,bold"
title="roboto">
<link href="../../../../../../../assets/css/default.css" rel="stylesheet" type="text/css">
<!-- FULLSCREEN STYLESHEET -->
<link href="../../../../../../../assets/css/fullscreen.css" rel="stylesheet" class="fullscreen"
type="text/css">
<!-- JAVASCRIPT -->
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script src="../../../../../../../assets/js/android_3p-bundle.js" type="text/javascript"></script>
<script type="text/javascript">
var toRoot = "../../../../../../../";
var metaTags = [];
var devsite = false;
</script>
<script src="../../../../../../../assets/js/docs.js" type="text/javascript"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-5831155-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body class="gc-documentation
develop" itemscope itemtype="http://schema.org/Article">
<div id="doc-api-level" class="" style="display:none"></div>
<a name="top"></a>
<a name="top"></a>
<!-- Header -->
<div id="header-wrapper">
<div id="header">
<div class="wrap" id="header-wrap">
<div class="col-3 logo">
<a href="../../../../../../../index.html">
<img src="../../../../../../../assets/images/dac_logo.png"
srcset="../../../../../../../assets/images/dac_logo@2x.png 2x"
width="123" height="25" alt="Android Developers" />
</a>
<div class="btn-quicknav" id="btn-quicknav">
<a href="#" class="arrow-inactive">Quicknav</a>
<a href="#" class="arrow-active">Quicknav</a>
</div>
</div>
<ul class="nav-x col-9">
<li class="design">
<a href="../../../../../../../design/index.html"
zh-tw-lang="設計"
zh-cn-lang="设计"
ru-lang="Проектирование"
ko-lang="디자인"
ja-lang="設計"
es-lang="Diseñar"
>Design</a></li>
<li class="develop"><a href="../../../../../../../develop/index.html"
zh-tw-lang="開發"
zh-cn-lang="开发"
ru-lang="Разработка"
ko-lang="개발"
ja-lang="開発"
es-lang="Desarrollar"
>Develop</a></li>
<li class="distribute last"><a href="../../../../../../../distribute/googleplay/index.html"
zh-tw-lang="發佈"
zh-cn-lang="分发"
ru-lang="Распространение"
ko-lang="배포"
ja-lang="配布"
es-lang="Distribuir"
>Distribute</a></li>
</ul>
<div class="menu-container">
<div class="moremenu">
<div id="more-btn"></div>
</div>
<div class="morehover" id="moremenu">
<div class="top"></div>
<div class="mid">
<div class="header">Links</div>
<ul>
<li><a href="https://play.google.com/apps/publish/" target="_googleplay">Google Play Developer Console</a></li>
<li><a href="http://android-developers.blogspot.com/">Android Developers Blog</a></li>
<li><a href="../../../../../../../about/index.html">About Android</a></li>
</ul>
<div class="header">Android Sites</div>
<ul>
<li><a href="http://www.android.com">Android.com</a></li>
<li class="active"><a>Android Developers</a></li>
<li><a href="http://source.android.com">Android Open Source Project</a></li>
</ul>
<br class="clearfix" />
</div><!-- end 'mid' -->
<div class="bottom"></div>
</div><!-- end 'moremenu' -->
<div class="search" id="search-container">
<div class="search-inner">
<div id="search-btn"></div>
<div class="left"></div>
<form onsubmit="return submit_search()">
<input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../../../../../')"
onkeyup="return search_changed(event, false, '../../../../../../../')" />
</form>
<div class="right"></div>
<a class="close hide">close</a>
<div class="left"></div>
<div class="right"></div>
</div><!-- end search-inner -->
</div><!-- end search-container -->
<div class="search_filtered_wrapper reference">
<div class="suggest-card reference no-display">
<ul class="search_filtered">
</ul>
</div>
</div>
<div class="search_filtered_wrapper docs">
<div class="suggest-card dummy no-display"> </div>
<div class="suggest-card develop no-display">
<ul class="search_filtered">
</ul>
<div class="child-card guides no-display">
</div>
<div class="child-card training no-display">
</div>
<div class="child-card samples no-display">
</div>
</div>
<div class="suggest-card design no-display">
<ul class="search_filtered">
</ul>
</div>
<div class="suggest-card distribute no-display">
<ul class="search_filtered">
</ul>
</div>
</div>
</div><!-- end menu-container (search and menu widget) -->
<!-- Expanded quicknav -->
<div id="quicknav" class="col-9">
<ul>
<li class="design">
<ul>
<li><a href="../../../../../../../design/index.html">Get Started</a></li>
<li><a href="../../../../../../../design/style/index.html">Style</a></li>
<li><a href="../../../../../../../design/patterns/index.html">Patterns</a></li>
<li><a href="../../../../../../../design/building-blocks/index.html">Building Blocks</a></li>
<li><a href="../../../../../../../design/downloads/index.html">Downloads</a></li>
<li><a href="../../../../../../../design/videos/index.html">Videos</a></li>
</ul>
</li>
<li class="develop">
<ul>
<li><a href="../../../../../../../training/index.html"
zh-tw-lang="訓練課程"
zh-cn-lang="培训"
ru-lang="Курсы"
ko-lang="교육"
ja-lang="トレーニング"
es-lang="Capacitación"
>Training</a></li>
<li><a href="../../../../../../../guide/index.html"
zh-tw-lang="API 指南"
zh-cn-lang="API 指南"
ru-lang="Руководства по API"
ko-lang="API 가이드"
ja-lang="API ガイド"
es-lang="Guías de la API"
>API Guides</a></li>
<li><a href="../../../../../../../reference/packages.html"
zh-tw-lang="參考資源"
zh-cn-lang="参考"
ru-lang="Справочник"
ko-lang="참조문서"
ja-lang="リファレンス"
es-lang="Referencia"
>Reference</a></li>
<li><a href="../../../../../../../tools/index.html"
zh-tw-lang="相關工具"
zh-cn-lang="工具"
ru-lang="Инструменты"
ko-lang="도구"
ja-lang="ツール"
es-lang="Herramientas"
>Tools</a>
<ul><li><a href="../../../../../../../sdk/index.html">Get the SDK</a></li></ul>
</li>
<li><a href="../../../../../../../google/index.html">Google Services</a>
</li>
</ul>
</li>
<li class="distribute last">
<ul>
<li><a href="../../../../../../../distribute/googleplay/index.html">Google Play</a></li>
<li><a href="../../../../../../../distribute/essentials/index.html">Essentials</a></li>
<li><a href="../../../../../../../distribute/users/index.html">Get Users</a></li>
<li><a href="../../../../../../../distribute/engage/index.html">Engage & Retain</a></li>
<li><a href="../../../../../../../distribute/monetize/index.html">Monetize</a></li>
<li><a href="../../../../../../../distribute/tools/index.html">Tools & Reference</a></li>
<li><a href="../../../../../../../distribute/stories/index.html">Developer Stories</a></li>
</ul>
</li>
</ul>
</div><!-- /Expanded quicknav -->
</div><!-- end header-wrap.wrap -->
</div><!-- end header -->
<!-- Secondary x-nav -->
<div id="nav-x">
<div class="wrap">
<ul class="nav-x col-9 develop" style="width:100%">
<li class="training"><a href="../../../../../../../training/index.html"
zh-tw-lang="訓練課程"
zh-cn-lang="培训"
ru-lang="Курсы"
ko-lang="교육"
ja-lang="トレーニング"
es-lang="Capacitación"
>Training</a></li>
<li class="guide"><a href="../../../../../../../guide/index.html"
zh-tw-lang="API 指南"
zh-cn-lang="API 指南"
ru-lang="Руководства по API"
ko-lang="API 가이드"
ja-lang="API ガイド"
es-lang="Guías de la API"
>API Guides</a></li>
<li class="reference"><a href="../../../../../../../reference/packages.html"
zh-tw-lang="參考資源"
zh-cn-lang="参考"
ru-lang="Справочник"
ko-lang="참조문서"
ja-lang="リファレンス"
es-lang="Referencia"
>Reference</a></li>
<li class="tools"><a href="../../../../../../../tools/index.html"
zh-tw-lang="相關工具"
zh-cn-lang="工具"
ru-lang="Инструменты"
ko-lang="도구"
ja-lang="ツール"
es-lang="Herramientas"
>Tools</a></li>
<li class="google"><a href="../../../../../../../google/index.html"
>Google Services</a>
</li>
</ul>
</div>
</div>
<!-- /Sendondary x-nav -->
<div id="searchResults" class="wrap" style="display:none;">
<h2 id="searchTitle">Results</h2>
<div id="leftSearchControl" class="search-control">Loading...</div>
</div>
</div> <!--end header-wrapper -->
<div id="sticky-header">
<div>
<a class="logo" href="#top"></a>
<a class="top" href="#top"></a>
<ul class="breadcrumb">
<li class="current">ChangeEvent</li>
</ul>
</div>
</div>
<div class="wrap clearfix" id="body-content">
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav">
<div id="api-nav-header">
<div id="api-level-toggle">
<label for="apiLevelCheckbox" class="disabled"
title="Select your target API level to dim unavailable APIs">API level: </label>
<div class="select-wrapper">
<select id="apiLevelSelector">
<!-- option elements added by buildApiLevelSelector() -->
</select>
</div>
</div><!-- end toggle -->
<div id="api-nav-title">Android APIs</div>
</div><!-- end nav header -->
<script>
var SINCE_DATA = [ ];
buildApiLevelSelector();
</script>
<div id="swapper">
<div id="nav-panels">
<div id="resize-packages-nav">
<div id="packages-nav" class="scroll-pane">
<ul>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/package-summary.html">com.google.android.gms</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/actions/package-summary.html">com.google.android.gms.actions</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/package-summary.html">com.google.android.gms.ads</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/doubleclick/package-summary.html">com.google.android.gms.ads.doubleclick</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/identifier/package-summary.html">com.google.android.gms.ads.identifier</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/mediation/package-summary.html">com.google.android.gms.ads.mediation</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/mediation/admob/package-summary.html">com.google.android.gms.ads.mediation.admob</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/mediation/customevent/package-summary.html">com.google.android.gms.ads.mediation.customevent</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/purchase/package-summary.html">com.google.android.gms.ads.purchase</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/search/package-summary.html">com.google.android.gms.ads.search</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/analytics/package-summary.html">com.google.android.gms.analytics</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/analytics/ecommerce/package-summary.html">com.google.android.gms.analytics.ecommerce</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/appindexing/package-summary.html">com.google.android.gms.appindexing</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/appstate/package-summary.html">com.google.android.gms.appstate</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/auth/package-summary.html">com.google.android.gms.auth</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/cast/package-summary.html">com.google.android.gms.cast</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/package-summary.html">com.google.android.gms.common</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/annotation/package-summary.html">com.google.android.gms.common.annotation</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/api/package-summary.html">com.google.android.gms.common.api</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/data/package-summary.html">com.google.android.gms.common.data</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/images/package-summary.html">com.google.android.gms.common.images</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/package-summary.html">com.google.android.gms.drive</a></li>
<li class="selected api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/events/package-summary.html">com.google.android.gms.drive.events</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/metadata/package-summary.html">com.google.android.gms.drive.metadata</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/query/package-summary.html">com.google.android.gms.drive.query</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/widget/package-summary.html">com.google.android.gms.drive.widget</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/package-summary.html">com.google.android.gms.games</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/achievement/package-summary.html">com.google.android.gms.games.achievement</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/event/package-summary.html">com.google.android.gms.games.event</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/leaderboard/package-summary.html">com.google.android.gms.games.leaderboard</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/package-summary.html">com.google.android.gms.games.multiplayer</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/realtime/package-summary.html">com.google.android.gms.games.multiplayer.realtime</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/turnbased/package-summary.html">com.google.android.gms.games.multiplayer.turnbased</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/quest/package-summary.html">com.google.android.gms.games.quest</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/request/package-summary.html">com.google.android.gms.games.request</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/snapshot/package-summary.html">com.google.android.gms.games.snapshot</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/gcm/package-summary.html">com.google.android.gms.gcm</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/identity/intents/package-summary.html">com.google.android.gms.identity.intents</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/identity/intents/model/package-summary.html">com.google.android.gms.identity.intents.model</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/location/package-summary.html">com.google.android.gms.location</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/maps/package-summary.html">com.google.android.gms.maps</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/maps/model/package-summary.html">com.google.android.gms.maps.model</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/panorama/package-summary.html">com.google.android.gms.panorama</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/package-summary.html">com.google.android.gms.plus</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/model/moments/package-summary.html">com.google.android.gms.plus.model.moments</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/model/people/package-summary.html">com.google.android.gms.plus.model.people</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/security/package-summary.html">com.google.android.gms.security</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/tagmanager/package-summary.html">com.google.android.gms.tagmanager</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/wallet/package-summary.html">com.google.android.gms.wallet</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/wallet/fragment/package-summary.html">com.google.android.gms.wallet.fragment</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/wearable/package-summary.html">com.google.android.gms.wearable</a></li>
</ul><br/>
</div> <!-- end packages-nav -->
</div> <!-- end resize-packages -->
<div id="classes-nav" class="scroll-pane">
<ul>
<li><h2>Interfaces</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/drive/events/DriveEvent.html">DriveEvent</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/drive/events/DriveEvent.Listener.html">DriveEvent.Listener</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/drive/events/ResourceEvent.html">ResourceEvent</a></li>
</ul>
</li>
<li><h2>Classes</h2>
<ul>
<li class="selected api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/drive/events/ChangeEvent.html">ChangeEvent</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/drive/events/DriveEventService.html">DriveEventService</a></li>
</ul>
</li>
</ul><br/>
</div><!-- end classes -->
</div><!-- end nav-panels -->
<div id="nav-tree" style="display:none" class="scroll-pane">
<div id="tree-list"></div>
</div><!-- end nav-tree -->
</div><!-- end swapper -->
<div id="nav-swap">
<a class="fullscreen">fullscreen</a>
<a href='#' onclick='swapNav();return false;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>
</div>
</div> <!-- end devdoc-nav -->
</div> <!-- end side-nav -->
<script type="text/javascript">
// init fullscreen based on user pref
var fullscreen = readCookie("fullscreen");
if (fullscreen != 0) {
if (fullscreen == "false") {
toggleFullscreen(false);
} else {
toggleFullscreen(true);
}
}
// init nav version for mobile
if (isMobile) {
swapNav(); // tree view should be used on mobile
$('#nav-swap').hide();
} else {
chooseDefaultNav();
if ($("#nav-tree").is(':visible')) {
init_default_navtree("../../../../../../../");
}
}
// scroll the selected page into view
$(document).ready(function() {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
});
</script>
<div class="col-12" id="doc-col">
<div id="api-info-block">
<div class="sum-details-links">
Summary:
<a href="#inhconstants">Inherited Constants</a>
| <a href="#lfields">Fields</a>
| <a href="#pubmethods">Methods</a>
| <a href="#inhmethods">Inherited Methods</a>
| <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a>
</div><!-- end sum-details-links -->
<div class="api-level">
</div>
</div><!-- end api-info-block -->
<!-- ======== START OF CLASS DATA ======== -->
<div id="jd-header">
public
final
class
<h1 itemprop="name">ChangeEvent</h1>
extends <a href="http://developer.android.com/reference/java/lang/Object.html">Object</a><br/>
implements
SafeParcelable
<a href="../../../../../../../reference/com/google/android/gms/drive/events/ResourceEvent.html">ResourceEvent</a>
</div><!-- end header -->
<div id="naMessage"></div>
<div id="jd-content" class="api apilevel-">
<table class="jd-inheritance-table">
<tr>
<td colspan="2" class="jd-inheritance-class-cell"><a href="http://developer.android.com/reference/java/lang/Object.html">java.lang.Object</a></td>
</tr>
<tr>
<td class="jd-inheritance-space"> ↳</td>
<td colspan="1" class="jd-inheritance-class-cell">com.google.android.gms.drive.events.ChangeEvent</td>
</tr>
</table>
<div class="jd-descr">
<h2>Class Overview</h2>
<p itemprop="articleBody">Sent when a <code><a href="../../../../../../../reference/com/google/android/gms/drive/DriveResource.html">DriveResource</a></code> has had a change to its <code><a href="../../../../../../../reference/com/google/android/gms/drive/Contents.html">Contents</a></code> or <code><a href="../../../../../../../reference/com/google/android/gms/drive/Metadata.html">Metadata</a></code>.
Refer to <code><a href="../../../../../../../reference/com/google/android/gms/drive/events/DriveEvent.html">DriveEvent</a></code> for additional information about event listeners.
Refer to <code><a href="../../../../../../../reference/com/google/android/gms/drive/events/DriveEvent.html">DriveEvent</a></code> for general information about event listeners and
<code><a href="../../../../../../../reference/com/google/android/gms/drive/DriveResource.html#addChangeListener(com.google.android.gms.common.api.GoogleApiClient, com.google.android.gms.drive.events.DriveEvent.Listener<com.google.android.gms.drive.events.ChangeEvent>)">addChangeListener(GoogleApiClient, DriveEvent.Listener<ChangeEvent>)</a></code> for how to create them.
</p>
</div><!-- jd-descr -->
<div class="jd-descr">
<h2>Summary</h2>
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<table id="inhconstants" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Constants</div></th></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-constants-android.os.Parcelable" class="jd-expando-trigger closed"
><img id="inherited-constants-android.os.Parcelable-trigger"
src="../../../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>From interface
android.os.Parcelable
<div id="inherited-constants-android.os.Parcelable">
<div id="inherited-constants-android.os.Parcelable-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-constants-android.os.Parcelable-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">int</td>
<td class="jd-linkcol">CONTENTS_FILE_DESCRIPTOR</td>
<td class="jd-descrcol" width="100%"></td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">int</td>
<td class="jd-linkcol">PARCELABLE_WRITE_RETURN_VALUE</td>
<td class="jd-descrcol" width="100%"></td>
</tr>
</table>
</div>
</div>
</td></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-constants-com.google.android.gms.common.internal.safeparcel.SafeParcelable" class="jd-expando-trigger closed"
><img id="inherited-constants-com.google.android.gms.common.internal.safeparcel.SafeParcelable-trigger"
src="../../../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>From interface
com.google.android.gms.common.internal.safeparcel.SafeParcelable
<div id="inherited-constants-com.google.android.gms.common.internal.safeparcel.SafeParcelable">
<div id="inherited-constants-com.google.android.gms.common.internal.safeparcel.SafeParcelable-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-constants-com.google.android.gms.common.internal.safeparcel.SafeParcelable-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><a href="http://developer.android.com/reference/java/lang/String.html">String</a></td>
<td class="jd-linkcol">NULL</td>
<td class="jd-descrcol" width="100%"></td>
</tr>
</table>
</div>
</div>
</td></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-constants-com.google.android.gms.drive.events.DriveEvent" class="jd-expando-trigger closed"
><img id="inherited-constants-com.google.android.gms.drive.events.DriveEvent-trigger"
src="../../../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>From interface
<a href="../../../../../../../reference/com/google/android/gms/drive/events/DriveEvent.html">com.google.android.gms.drive.events.DriveEvent</a>
<div id="inherited-constants-com.google.android.gms.drive.events.DriveEvent">
<div id="inherited-constants-com.google.android.gms.drive.events.DriveEvent-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-constants-com.google.android.gms.drive.events.DriveEvent-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">int</td>
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/drive/events/DriveEvent.html#TYPE_CHANGE">TYPE_CHANGE</a></td>
<td class="jd-descrcol" width="100%">Event type that indicates a resource change.</td>
</tr>
</table>
</div>
</div>
</td></tr>
</table>
<!-- =========== FIELD SUMMARY =========== -->
<table id="lfields" class="jd-sumtable"><tr><th colspan="12">Fields</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
public
static
final
<a href="http://developer.android.com/reference/android/os/Parcelable.Creator.html">Creator</a><<a href="../../../../../../../reference/com/google/android/gms/drive/events/ChangeEvent.html">ChangeEvent</a>></nobr></td>
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/drive/events/ChangeEvent.html#CREATOR">CREATOR</a></td>
<td class="jd-descrcol" width="100%"></td>
</tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="pubmethods" class="jd-sumtable"><tr><th colspan="12">Public Methods</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/drive/events/ChangeEvent.html#describeContents()">describeContents</a></span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../../reference/com/google/android/gms/drive/DriveId.html">DriveId</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/drive/events/ChangeEvent.html#getDriveId()">getDriveId</a></span>()</nobr>
<div class="jd-descrdiv">Returns the id of the Drive resource that triggered the event, or <code>null</code> if not
resource-specific.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/drive/events/ChangeEvent.html#getType()">getType</a></span>()</nobr>
<div class="jd-descrdiv">Returns the type of an event.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
boolean</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/drive/events/ChangeEvent.html#hasContentChanged()">hasContentChanged</a></span>()</nobr>
<div class="jd-descrdiv">Returns <code>true</code> if the content has changed for this resource.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
boolean</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/drive/events/ChangeEvent.html#hasMetadataChanged()">hasMetadataChanged</a></span>()</nobr>
<div class="jd-descrdiv">Returns <code>true</code> if the metadata has changed for this resource.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="http://developer.android.com/reference/java/lang/String.html">String</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/drive/events/ChangeEvent.html#toString()">toString</a></span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/drive/events/ChangeEvent.html#writeToParcel(android.os.Parcel, int)">writeToParcel</a></span>(<a href="http://developer.android.com/reference/android/os/Parcel.html">Parcel</a> dest, int flags)</nobr>
</td></tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="inhmethods" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Methods</div></th></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-java.lang.Object" class="jd-expando-trigger closed"
><img id="inherited-methods-java.lang.Object-trigger"
src="../../../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From class
<a href="http://developer.android.com/reference/java/lang/Object.html">java.lang.Object</a>
<div id="inherited-methods-java.lang.Object">
<div id="inherited-methods-java.lang.Object-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-java.lang.Object-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="http://developer.android.com/reference/java/lang/Object.html">Object</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">clone</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
boolean</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">equals</span>(<a href="http://developer.android.com/reference/java/lang/Object.html">Object</a> arg0)</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">finalize</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
final
<a href="http://developer.android.com/reference/java/lang/Class.html">Class</a><?></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">getClass</span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">hashCode</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">notify</span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">notifyAll</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="http://developer.android.com/reference/java/lang/String.html">String</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">toString</span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">wait</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">wait</span>(long arg0, int arg1)</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">wait</span>(long arg0)</nobr>
</td></tr>
</table>
</div>
</div>
</td></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-android.os.Parcelable" class="jd-expando-trigger closed"
><img id="inherited-methods-android.os.Parcelable-trigger"
src="../../../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From interface
<a href="http://developer.android.com/reference/android/os/Parcelable.html">android.os.Parcelable</a>
<div id="inherited-methods-android.os.Parcelable">
<div id="inherited-methods-android.os.Parcelable-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-android.os.Parcelable-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
abstract
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">describeContents</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
abstract
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">writeToParcel</span>(<a href="http://developer.android.com/reference/android/os/Parcel.html">Parcel</a> arg0, int arg1)</nobr>
</td></tr>
</table>
</div>
</div>
</td></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-com.google.android.gms.drive.events.DriveEvent" class="jd-expando-trigger closed"
><img id="inherited-methods-com.google.android.gms.drive.events.DriveEvent-trigger"
src="../../../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From interface
<a href="../../../../../../../reference/com/google/android/gms/drive/events/DriveEvent.html">com.google.android.gms.drive.events.DriveEvent</a>
<div id="inherited-methods-com.google.android.gms.drive.events.DriveEvent">
<div id="inherited-methods-com.google.android.gms.drive.events.DriveEvent-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-com.google.android.gms.drive.events.DriveEvent-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
abstract
<a href="../../../../../../../reference/com/google/android/gms/drive/DriveId.html">DriveId</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/drive/events/DriveEvent.html#getDriveId()">getDriveId</a></span>()</nobr>
<div class="jd-descrdiv">Returns the id of the Drive resource that triggered the event, or <code>null</code> if not
resource-specific.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
abstract
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/drive/events/DriveEvent.html#getType()">getType</a></span>()</nobr>
<div class="jd-descrdiv">Returns the type of an event.</div>
</td></tr>
</table>
</div>
</div>
</td></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-com.google.android.gms.drive.events.ResourceEvent" class="jd-expando-trigger closed"
><img id="inherited-methods-com.google.android.gms.drive.events.ResourceEvent-trigger"
src="../../../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From interface
<a href="../../../../../../../reference/com/google/android/gms/drive/events/ResourceEvent.html">com.google.android.gms.drive.events.ResourceEvent</a>
<div id="inherited-methods-com.google.android.gms.drive.events.ResourceEvent">
<div id="inherited-methods-com.google.android.gms.drive.events.ResourceEvent-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-com.google.android.gms.drive.events.ResourceEvent-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
abstract
<a href="../../../../../../../reference/com/google/android/gms/drive/DriveId.html">DriveId</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/drive/events/ResourceEvent.html#getDriveId()">getDriveId</a></span>()</nobr>
<div class="jd-descrdiv">Returns the id of the Drive resource that triggered the event, or <code>null</code> if not
resource-specific.</div>
</td></tr>
</table>
</div>
</div>
</td></tr>
</table>
</div><!-- jd-descr (summary) -->
<!-- Details -->
<!-- XML Attributes -->
<!-- Enum Values -->
<!-- Constants -->
<!-- Fields -->
<!-- ========= FIELD DETAIL ======== -->
<h2>Fields</h2>
<A NAME="CREATOR"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
static
final
<a href="http://developer.android.com/reference/android/os/Parcelable.Creator.html">Creator</a><<a href="../../../../../../../reference/com/google/android/gms/drive/events/ChangeEvent.html">ChangeEvent</a>>
</span>
CREATOR
</h4>
<div class="api-level">
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<!-- Public ctors -->
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<!-- Protected ctors -->
<!-- ========= METHOD DETAIL ======== -->
<!-- Public methdos -->
<h2>Public Methods</h2>
<A NAME="describeContents()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
int
</span>
<span class="sympad">describeContents</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<A NAME="getDriveId()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../../reference/com/google/android/gms/drive/DriveId.html">DriveId</a>
</span>
<span class="sympad">getDriveId</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns the id of the Drive resource that triggered the event, or <code>null</code> if not
resource-specific.
</p></div>
</div>
</div>
<A NAME="getType()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
int
</span>
<span class="sympad">getType</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns the type of an event. See the <code>TYPE_*</code> constants for possible values.
</p></div>
</div>
</div>
<A NAME="hasContentChanged()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
boolean
</span>
<span class="sympad">hasContentChanged</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns <code>true</code> if the content has changed for this resource.
</p></div>
</div>
</div>
<A NAME="hasMetadataChanged()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
boolean
</span>
<span class="sympad">hasMetadataChanged</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns <code>true</code> if the metadata has changed for this resource.
</p></div>
</div>
</div>
<A NAME="toString()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="http://developer.android.com/reference/java/lang/String.html">String</a>
</span>
<span class="sympad">toString</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<A NAME="writeToParcel(android.os.Parcel, int)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
void
</span>
<span class="sympad">writeToParcel</span>
<span class="normal">(<a href="http://developer.android.com/reference/android/os/Parcel.html">Parcel</a> dest, int flags)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<!-- ========= METHOD DETAIL ======== -->
<!-- ========= END OF CLASS DATA ========= -->
<A NAME="navbar_top"></A>
<div id="footer" class="wrap" >
<div id="copyright">
Except as noted, this content is licensed under <a
href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>.
For details and restrictions, see the <a href="../../../../../../../license.html">
Content License</a>.
</div>
<div id="build_info">
Android GmsCore 1307510 r —
<script src="../../../../../../../timestamp.js" type="text/javascript"></script>
<script>document.write(BUILD_TIMESTAMP)</script>
</div>
<div id="footerlinks">
<p>
<a href="../../../../../../../about/index.html">About Android</a> |
<a href="../../../../../../../legal.html">Legal</a> |
<a href="../../../../../../../support.html">Support</a>
</p>
</div>
</div> <!-- end footer -->
</div> <!-- jd-content -->
</div><!-- end doc-content -->
</div> <!-- end body-content -->
</body>
</html>
| EdHubbell/truxieXamarin | packages/Xamarin.GooglePlayServices.19.0.0.1/lib/MonoAndroid23/19/content/google-play-services/docs/reference/com/google/android/gms/drive/events/ChangeEvent.html | HTML | gpl-2.0 | 52,916 |
// directory.h
// Data structures to manage a UNIX-like directory of file names.
//
// A directory is a table of pairs: <file name, sector #>,
// giving the name of each file in the directory, and
// where to find its file header (the data structure describing
// where to find the file's data blocks) on disk.
//
// We assume mutual exclusion is provided by the caller.
//
// Copyright (c) 1992-1993 The Regents of the University of California.
// All rights reserved. See copyright.h for copyright notice and limitation
// of liability and disclaimer of warranty provisions.
#include "copyright.h"
#ifndef DIRECTORY_H
#define DIRECTORY_H
#include "openfile.h"
#define FileNameMaxLen 9 // for simplicity, we assume
// file names are <= 9 characters long
// The following class defines a "directory entry", representing a file
// in the directory. Each entry gives the name of the file, and where
// the file's header is to be found on disk.
//
// Internal data structures kept public so that Directory operations can
// access them directly.
class DirectoryEntry {
public:
bool inUse; // Is this directory entry in use?
int sector; // Location on disk to find the
// FileHeader for this file
char name[FileNameMaxLen + 1]; // Text name for file, with +1 for
// the trailing '\0'
};
// The following class defines a UNIX-like "directory". Each entry in
// the directory describes a file, and where to find it on disk.
//
// The directory data structure can be stored in memory, or on disk.
// When it is on disk, it is stored as a regular Nachos file.
//
// The constructor initializes a directory structure in memory; the
// FetchFrom/WriteBack operations shuffle the directory information
// from/to disk.
class Directory {
public:
Directory(int size); // Initialize an empty directory
// with space for "size" files
~Directory(); // De-allocate the directory
void FetchFrom(OpenFile *file); // Init directory contents from disk
void WriteBack(OpenFile *file); // Write modifications to
// directory contents back to disk
int Find(char *name); // Find the sector number of the
// FileHeader for file: "name"
bool Add(char *name, int newSector); // Add a file name into the directory
bool Remove(char *name); // Remove a file from the directory
void List(); // Print the names of all the files
// in the directory
void Print(); // Verbose print of the contents
// of the directory -- all the file
// names and their contents.
private:
int tableSize; // Number of directory entries
DirectoryEntry *table; // Table of pairs:
// <file name, file header location>
int FindIndex(char *name); // Find the index into the directory
// table corresponding to "name"
};
#endif // DIRECTORY_H
| k4rtik/nachos-nitc | nachos-3.4/code/filesys/directory.h | C | gpl-2.0 | 2,878 |
<?php
/**
* @package Joomla.Administrator
* @subpackage com_contact
*
* @copyright Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
/**
* View to edit a contact.
*
* @since 1.6
*/
class ContactViewContact extends JViewLegacy
{
protected $form;
protected $item;
protected $state;
/**
* Display the view.
*
* @param string $tpl The name of the template file to parse; automatically searches through the template paths.
*
* @return mixed A string if successful, otherwise an Error object.
*/
public function display($tpl = null)
{
// Initialise variables.
$this->form = $this->get('Form');
$this->item = $this->get('Item');
$this->state = $this->get('State');
// Check for errors.
if (count($errors = $this->get('Errors')))
{
JError::raiseError(500, implode("\n", $errors));
return false;
}
if ($this->getLayout() == 'modal')
{
$this->form->setFieldAttribute('language', 'readonly', 'true');
$this->form->setFieldAttribute('catid', 'readonly', 'true');
}
$this->addToolbar();
parent::display($tpl);
}
/**
* Add the page title and toolbar.
*
* @return void
*
* @since 1.6
*/
protected function addToolbar()
{
JFactory::getApplication()->input->set('hidemainmenu', true);
$user = JFactory::getUser();
$userId = $user->get('id');
$isNew = ($this->item->id == 0);
$checkedOut = !($this->item->checked_out == 0 || $this->item->checked_out == $userId);
// Since we don't track these assets at the item level, use the category id.
$canDo = JHelperContent::getActions('com_contact', 'category', $this->item->catid);
JToolbarHelper::title($isNew ? JText::_('COM_CONTACT_MANAGER_CONTACT_NEW') : JText::_('COM_CONTACT_MANAGER_CONTACT_EDIT'), 'address contact');
// Build the actions for new and existing records.
if ($isNew)
{
// For new records, check the create permission.
if ($isNew && (count($user->getAuthorisedCategories('com_contact', 'core.create')) > 0))
{
JToolbarHelper::apply('contact.apply');
JToolbarHelper::save('contact.save');
JToolbarHelper::save2new('contact.save2new');
}
JToolbarHelper::cancel('contact.cancel');
}
else
{
// Can't save the record if it's checked out.
if (!$checkedOut)
{
// Since it's an existing record, check the edit permission, or fall back to edit own if the owner.
if ($canDo->get('core.edit') || ($canDo->get('core.edit.own') && $this->item->created_by == $userId))
{
JToolbarHelper::apply('contact.apply');
JToolbarHelper::save('contact.save');
// We can save this record, but check the create permission to see if we can return to make a new one.
if ($canDo->get('core.create'))
{
JToolbarHelper::save2new('contact.save2new');
}
}
}
// If checked out, we can still save
if ($canDo->get('core.create'))
{
JToolbarHelper::save2copy('contact.save2copy');
}
if ($this->state->params->get('save_history', 0) && $user->authorise('core.edit'))
{
JToolbarHelper::versions('com_contact.contact', $this->item->id);
}
JToolbarHelper::cancel('contact.cancel', 'JTOOLBAR_CLOSE');
}
JToolbarHelper::divider();
JToolbarHelper::help('JHELP_COMPONENTS_CONTACTS_CONTACTS_EDIT');
}
}
| SyntaxC4-MSFT/joomla-cms | administrator/components/com_contact/views/contact/view.html.php | PHP | gpl-2.0 | 3,413 |
/* $Id$ */
/** @file
* VBox OpenGL list of opengl functions common in Mesa and vbox opengl stub
*/
/*
* Copyright (C) 2009-2010 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#ifndef GLXAPI_ENTRY
#error GLXAPI_ENTRY should be defined.
#endif
/*This should match glX* entries which are exported by Mesa's libGL.so,
* use something like the following to get the list:
* objdump -T libGL.so|grep glX|grep -v __|awk '{print $7;};'|sed 's/glX//'|awk '{OFS=""; print "GLXAPI_ENTRY(",$1,")"}'
*/
/* #######Note: if you change the list, don't forget to change Linux_i386_glxapi_exports.py####### */
GLXAPI_ENTRY(CopyContext)
GLXAPI_ENTRY(UseXFont)
/*GLXAPI_ENTRY(GetDriverConfig)*/
GLXAPI_ENTRY(GetProcAddress)
GLXAPI_ENTRY(QueryExtension)
GLXAPI_ENTRY(IsDirect)
GLXAPI_ENTRY(DestroyGLXPbufferSGIX)
GLXAPI_ENTRY(QueryGLXPbufferSGIX)
GLXAPI_ENTRY(CreateGLXPixmap)
GLXAPI_ENTRY(CreateGLXPixmapWithConfigSGIX)
GLXAPI_ENTRY(QueryContext)
GLXAPI_ENTRY(CreateContextWithConfigSGIX)
GLXAPI_ENTRY(SwapBuffers)
GLXAPI_ENTRY(CreateNewContext)
GLXAPI_ENTRY(SelectEventSGIX)
GLXAPI_ENTRY(GetCurrentDrawable)
GLXAPI_ENTRY(ChooseFBConfig)
GLXAPI_ENTRY(WaitGL)
GLXAPI_ENTRY(GetFBConfigs)
GLXAPI_ENTRY(CreatePixmap)
GLXAPI_ENTRY(GetSelectedEventSGIX)
GLXAPI_ENTRY(GetCurrentReadDrawable)
GLXAPI_ENTRY(GetCurrentDisplay)
GLXAPI_ENTRY(QueryServerString)
GLXAPI_ENTRY(CreateWindow)
GLXAPI_ENTRY(SelectEvent)
GLXAPI_ENTRY(GetVisualFromFBConfigSGIX)
GLXAPI_ENTRY(GetFBConfigFromVisualSGIX)
GLXAPI_ENTRY(QueryDrawable)
GLXAPI_ENTRY(CreateContext)
GLXAPI_ENTRY(GetConfig)
GLXAPI_ENTRY(CreateGLXPbufferSGIX)
GLXAPI_ENTRY(CreatePbuffer)
GLXAPI_ENTRY(ChooseFBConfigSGIX)
GLXAPI_ENTRY(WaitX)
GLXAPI_ENTRY(GetVisualFromFBConfig)
/*GLXAPI_ENTRY(GetScreenDriver)*/
GLXAPI_ENTRY(GetFBConfigAttrib)
GLXAPI_ENTRY(GetCurrentContext)
GLXAPI_ENTRY(GetClientString)
GLXAPI_ENTRY(DestroyPixmap)
GLXAPI_ENTRY(MakeCurrent)
GLXAPI_ENTRY(DestroyContext)
GLXAPI_ENTRY(GetProcAddressARB)
GLXAPI_ENTRY(GetSelectedEvent)
GLXAPI_ENTRY(DestroyPbuffer)
GLXAPI_ENTRY(DestroyWindow)
GLXAPI_ENTRY(DestroyGLXPixmap)
GLXAPI_ENTRY(QueryVersion)
GLXAPI_ENTRY(ChooseVisual)
GLXAPI_ENTRY(MakeContextCurrent)
GLXAPI_ENTRY(QueryExtensionsString)
GLXAPI_ENTRY(GetFBConfigAttribSGIX)
#ifdef VBOXOGL_FAKEDRI
GLXAPI_ENTRY(FreeMemoryMESA)
GLXAPI_ENTRY(QueryContextInfoEXT)
GLXAPI_ENTRY(ImportContextEXT)
GLXAPI_ENTRY(GetContextIDEXT)
GLXAPI_ENTRY(MakeCurrentReadSGI)
GLXAPI_ENTRY(AllocateMemoryMESA)
GLXAPI_ENTRY(GetMemoryOffsetMESA)
GLXAPI_ENTRY(CreateGLXPixmapMESA)
GLXAPI_ENTRY(GetCurrentDisplayEXT)
GLXAPI_ENTRY(FreeContextEXT)
#endif
| mirror/vbox | src/VBox/Additions/common/crOpenGL/fakedri_glxfuncsList.h | C | gpl-2.0 | 3,040 |
using System;
using System.Collections.Generic;
using Server.ContextMenus;
using Server.Mobiles;
namespace Server.Items
{
[FlipableAttribute(0x2790, 0x27DB)]
public class LeatherNinjaBelt : BaseWaist, IDyable, INinjaWeapon
{
private int m_UsesRemaining;
private Poison m_Poison;
private int m_PoisonCharges;
[Constructable]
public LeatherNinjaBelt()
: base(0x2790)
{
this.Weight = 1.0;
this.Layer = Layer.Waist;
}
public LeatherNinjaBelt(Serial serial)
: base(serial)
{
}
public override CraftResource DefaultResource
{
get
{
return CraftResource.RegularLeather;
}
}
public virtual int WrongAmmoMessage
{
get
{
return 1063301;
}
}//You can only place shuriken in a ninja belt.
public virtual int NoFreeHandMessage
{
get
{
return 1063299;
}
}//You must have a free hand to throw shuriken.
public virtual int EmptyWeaponMessage
{
get
{
return 1063297;
}
}//You have no shuriken in your ninja belt!
public virtual int RecentlyUsedMessage
{
get
{
return 1063298;
}
}//You cannot throw another shuriken yet.
public virtual int FullWeaponMessage
{
get
{
return 1063302;
}
}//You cannot add any more shuriken.
public virtual int WeaponMinRange
{
get
{
return 2;
}
}
public virtual int WeaponMaxRange
{
get
{
return 10;
}
}
public virtual int WeaponDamage
{
get
{
return Utility.RandomMinMax(3, 5);
}
}
public virtual Type AmmoType
{
get
{
return typeof(Shuriken);
}
}
[CommandProperty(AccessLevel.GameMaster)]
public int UsesRemaining
{
get
{
return this.m_UsesRemaining;
}
set
{
this.m_UsesRemaining = value;
this.InvalidateProperties();
}
}
[CommandProperty(AccessLevel.GameMaster)]
public Poison Poison
{
get
{
return this.m_Poison;
}
set
{
this.m_Poison = value;
this.InvalidateProperties();
}
}
[CommandProperty(AccessLevel.GameMaster)]
public int PoisonCharges
{
get
{
return this.m_PoisonCharges;
}
set
{
this.m_PoisonCharges = value;
this.InvalidateProperties();
}
}
public bool ShowUsesRemaining
{
get
{
return true;
}
set
{
}
}
public void AttackAnimation(Mobile from, Mobile to)
{
if (from.Body.IsHuman)
{
from.Animate(from.Mounted ? 26 : 9, 7, 1, true, false, 0);
}
from.PlaySound(0x23A);
from.MovingEffect(to, 0x27AC, 1, 0, false, false);
}
public override void GetProperties(ObjectPropertyList list)
{
base.GetProperties(list);
if (ReforgedSuffix != ReforgedSuffix.Blackthorn)
list.Add(1060584, this.m_UsesRemaining.ToString()); // uses remaining: ~1_val~
if (this.m_Poison != null && this.m_PoisonCharges > 0)
list.Add(1062412 + this.m_Poison.Level, this.m_PoisonCharges.ToString());
}
public override bool OnEquip(Mobile from)
{
if (base.OnEquip(from))
{
from.SendLocalizedMessage(1070785); // Double click this item each time you wish to throw a shuriken.
return true;
}
return false;
}
public override void OnDoubleClick(Mobile from)
{
NinjaWeapon.AttemptShoot((PlayerMobile)from, this);
}
public override void GetContextMenuEntries(Mobile from, List<ContextMenuEntry> list)
{
base.GetContextMenuEntries(from, list);
if (this.IsChildOf(from))
{
list.Add(new NinjaWeapon.LoadEntry(this, 6222));
list.Add(new NinjaWeapon.UnloadEntry(this, 6223));
}
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
writer.Write((int)this.m_UsesRemaining);
Poison.Serialize(this.m_Poison, writer);
writer.Write((int)this.m_PoisonCharges);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
switch ( version )
{
case 0:
{
this.m_UsesRemaining = reader.ReadInt();
this.m_Poison = Poison.Deserialize(reader);
this.m_PoisonCharges = reader.ReadInt();
break;
}
}
}
}
} | tbewley10310/Land-of-Archon | Scripts/Items/Equipment/Clothing/LeatherNinjaBelt.cs | C# | gpl-2.0 | 5,823 |
/*
* linux/fs/namei.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
/*
* Some corrections by tytso.
*/
/* [Feb 1997 T. Schoebel-Theuer] Complete rewrite of the pathname
* lookup logic.
*/
/* [Feb-Apr 2000, AV] Rewrite to the new namespace architecture.
*/
#include <linux/init.h>
#include <linux/export.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/namei.h>
#include <linux/pagemap.h>
#include <linux/fsnotify.h>
#include <linux/personality.h>
#include <linux/security.h>
#include <linux/ima.h>
#include <linux/syscalls.h>
#include <linux/mount.h>
#include <linux/audit.h>
#include <linux/capability.h>
#include <linux/file.h>
#include <linux/fcntl.h>
#include <linux/device_cgroup.h>
#include <linux/fs_struct.h>
#include <linux/posix_acl.h>
#include <linux/hash.h>
#include <asm/uaccess.h>
#include "internal.h"
#include "mount.h"
#ifdef CONFIG_SDCARD_FS
#include "sdcardfs/sdcardfs.h"
#endif
/* [Feb-1997 T. Schoebel-Theuer]
* Fundamental changes in the pathname lookup mechanisms (namei)
* were necessary because of omirr. The reason is that omirr needs
* to know the _real_ pathname, not the user-supplied one, in case
* of symlinks (and also when transname replacements occur).
*
* The new code replaces the old recursive symlink resolution with
* an iterative one (in case of non-nested symlink chains). It does
* this with calls to <fs>_follow_link().
* As a side effect, dir_namei(), _namei() and follow_link() are now
* replaced with a single function lookup_dentry() that can handle all
* the special cases of the former code.
*
* With the new dcache, the pathname is stored at each inode, at least as
* long as the refcount of the inode is positive. As a side effect, the
* size of the dcache depends on the inode cache and thus is dynamic.
*
* [29-Apr-1998 C. Scott Ananian] Updated above description of symlink
* resolution to correspond with current state of the code.
*
* Note that the symlink resolution is not *completely* iterative.
* There is still a significant amount of tail- and mid- recursion in
* the algorithm. Also, note that <fs>_readlink() is not used in
* lookup_dentry(): lookup_dentry() on the result of <fs>_readlink()
* may return different results than <fs>_follow_link(). Many virtual
* filesystems (including /proc) exhibit this behavior.
*/
/* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation:
* New symlink semantics: when open() is called with flags O_CREAT | O_EXCL
* and the name already exists in form of a symlink, try to create the new
* name indicated by the symlink. The old code always complained that the
* name already exists, due to not following the symlink even if its target
* is nonexistent. The new semantics affects also mknod() and link() when
* the name is a symlink pointing to a non-existent name.
*
* I don't know which semantics is the right one, since I have no access
* to standards. But I found by trial that HP-UX 9.0 has the full "new"
* semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the
* "old" one. Personally, I think the new semantics is much more logical.
* Note that "ln old new" where "new" is a symlink pointing to a non-existing
* file does succeed in both HP-UX and SunOs, but not in Solaris
* and in the old Linux semantics.
*/
/* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink
* semantics. See the comments in "open_namei" and "do_link" below.
*
* [10-Sep-98 Alan Modra] Another symlink change.
*/
/* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks:
* inside the path - always follow.
* in the last component in creation/removal/renaming - never follow.
* if LOOKUP_FOLLOW passed - follow.
* if the pathname has trailing slashes - follow.
* otherwise - don't follow.
* (applied in that order).
*
* [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT
* restored for 2.4. This is the last surviving part of old 4.2BSD bug.
* During the 2.4 we need to fix the userland stuff depending on it -
* hopefully we will be able to get rid of that wart in 2.5. So far only
* XEmacs seems to be relying on it...
*/
/*
* [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland)
* implemented. Let's see if raised priority of ->s_vfs_rename_mutex gives
* any extra contention...
*/
/* In order to reduce some races, while at the same time doing additional
* checking and hopefully speeding things up, we copy filenames to the
* kernel data space before using them..
*
* POSIX.1 2.4: an empty pathname is invalid (ENOENT).
* PATH_MAX includes the nul terminator --RR.
*/
void final_putname(struct filename *name)
{
if (name->separate) {
__putname(name->name);
kfree(name);
} else {
__putname(name);
}
}
#define EMBEDDED_NAME_MAX (PATH_MAX - sizeof(struct filename))
static struct filename *
getname_flags(const char __user *filename, int flags, int *empty)
{
struct filename *result, *err;
int len;
long max;
char *kname;
result = audit_reusename(filename);
if (result)
return result;
result = __getname();
if (unlikely(!result))
return ERR_PTR(-ENOMEM);
/*
* First, try to embed the struct filename inside the names_cache
* allocation
*/
kname = (char *)result + sizeof(*result);
result->name = kname;
result->separate = false;
max = EMBEDDED_NAME_MAX;
recopy:
len = strncpy_from_user(kname, filename, max);
if (unlikely(len < 0)) {
err = ERR_PTR(len);
goto error;
}
/*
* Uh-oh. We have a name that's approaching PATH_MAX. Allocate a
* separate struct filename so we can dedicate the entire
* names_cache allocation for the pathname, and re-do the copy from
* userland.
*/
if (len == EMBEDDED_NAME_MAX && max == EMBEDDED_NAME_MAX) {
kname = (char *)result;
result = kzalloc(sizeof(*result), GFP_KERNEL);
if (!result) {
err = ERR_PTR(-ENOMEM);
result = (struct filename *)kname;
goto error;
}
result->name = kname;
result->separate = true;
max = PATH_MAX;
goto recopy;
}
/* The empty path is special. */
if (unlikely(!len)) {
if (empty)
*empty = 1;
err = ERR_PTR(-ENOENT);
if (!(flags & LOOKUP_EMPTY))
goto error;
}
err = ERR_PTR(-ENAMETOOLONG);
if (unlikely(len >= PATH_MAX))
goto error;
result->uptr = filename;
result->aname = NULL;
audit_getname(result);
return result;
error:
final_putname(result);
return err;
}
struct filename *
getname(const char __user * filename)
{
return getname_flags(filename, 0, NULL);
}
/*
* The "getname_kernel()" interface doesn't do pathnames longer
* than EMBEDDED_NAME_MAX. Deal with it - you're a kernel user.
*/
struct filename *
getname_kernel(const char * filename)
{
struct filename *result;
char *kname;
int len;
len = strlen(filename);
if (len >= EMBEDDED_NAME_MAX)
return ERR_PTR(-ENAMETOOLONG);
result = __getname();
if (unlikely(!result))
return ERR_PTR(-ENOMEM);
kname = (char *)result + sizeof(*result);
result->name = kname;
result->uptr = NULL;
result->aname = NULL;
result->separate = false;
strlcpy(kname, filename, EMBEDDED_NAME_MAX);
return result;
}
#ifdef CONFIG_AUDITSYSCALL
void putname(struct filename *name)
{
if (unlikely(!audit_dummy_context()))
return audit_putname(name);
final_putname(name);
}
#endif
static int check_acl(struct inode *inode, int mask)
{
#ifdef CONFIG_FS_POSIX_ACL
struct posix_acl *acl;
if (mask & MAY_NOT_BLOCK) {
acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS);
if (!acl)
return -EAGAIN;
/* no ->get_acl() calls in RCU mode... */
if (acl == ACL_NOT_CACHED)
return -ECHILD;
return posix_acl_permission(inode, acl, mask & ~MAY_NOT_BLOCK);
}
acl = get_acl(inode, ACL_TYPE_ACCESS);
if (IS_ERR(acl))
return PTR_ERR(acl);
if (acl) {
int error = posix_acl_permission(inode, acl, mask);
posix_acl_release(acl);
return error;
}
#endif
return -EAGAIN;
}
/*
* This does the basic permission checking
*/
static int acl_permission_check(struct inode *inode, int mask)
{
unsigned int mode = inode->i_mode;
if (likely(uid_eq(current_fsuid(), inode->i_uid)))
mode >>= 6;
else {
if (IS_POSIXACL(inode) && (mode & S_IRWXG)) {
int error = check_acl(inode, mask);
if (error != -EAGAIN)
return error;
}
if (in_group_p(inode->i_gid))
mode >>= 3;
}
/*
* If the DACs are ok we don't need any capability check.
*/
if ((mask & ~mode & (MAY_READ | MAY_WRITE | MAY_EXEC)) == 0)
return 0;
return -EACCES;
}
/**
* generic_permission - check for access rights on a Posix-like filesystem
* @inode: inode to check access rights for
* @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC, ...)
*
* Used to check for read/write/execute permissions on a file.
* We use "fsuid" for this, letting us set arbitrary permissions
* for filesystem access without changing the "normal" uids which
* are used for other things.
*
* generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk
* request cannot be satisfied (eg. requires blocking or too much complexity).
* It would then be called again in ref-walk mode.
*/
int generic_permission(struct inode *inode, int mask)
{
int ret;
/*
* Do the basic permission checks.
*/
ret = acl_permission_check(inode, mask);
if (ret != -EACCES)
return ret;
if (S_ISDIR(inode->i_mode)) {
/* DACs are overridable for directories */
if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE))
return 0;
if (!(mask & MAY_WRITE))
if (capable_wrt_inode_uidgid(inode,
CAP_DAC_READ_SEARCH))
return 0;
return -EACCES;
}
/*
* Read/write DACs are always overridable.
* Executable DACs are overridable when there is
* at least one exec bit set.
*/
if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))
if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE))
return 0;
/*
* Searching includes executable on directories, else just read.
*/
mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
if (mask == MAY_READ)
if (capable_wrt_inode_uidgid(inode, CAP_DAC_READ_SEARCH))
return 0;
return -EACCES;
}
EXPORT_SYMBOL(generic_permission);
/*
* We _really_ want to just do "generic_permission()" without
* even looking at the inode->i_op values. So we keep a cache
* flag in inode->i_opflags, that says "this has not special
* permission function, use the fast case".
*/
static inline int do_inode_permission(struct inode *inode, int mask)
{
if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) {
if (likely(inode->i_op->permission))
return inode->i_op->permission(inode, mask);
/* This gets set once for the inode lifetime */
spin_lock(&inode->i_lock);
inode->i_opflags |= IOP_FASTPERM;
spin_unlock(&inode->i_lock);
}
return generic_permission(inode, mask);
}
/**
* __inode_permission - Check for access rights to a given inode
* @inode: Inode to check permission on
* @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
*
* Check for read/write/execute permissions on an inode.
*
* When checking for MAY_APPEND, MAY_WRITE must also be set in @mask.
*
* This does not check for a read-only file system. You probably want
* inode_permission().
*/
int __inode_permission(struct inode *inode, int mask)
{
int retval;
if (unlikely(mask & MAY_WRITE)) {
/*
* Nobody gets write access to an immutable file.
*/
if (IS_IMMUTABLE(inode))
return -EACCES;
}
retval = do_inode_permission(inode, mask);
if (retval)
return retval;
retval = devcgroup_inode_permission(inode, mask);
if (retval)
return retval;
return security_inode_permission(inode, mask);
}
EXPORT_SYMBOL(__inode_permission);
/**
* sb_permission - Check superblock-level permissions
* @sb: Superblock of inode to check permission on
* @inode: Inode to check permission on
* @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
*
* Separate out file-system wide checks from inode-specific permission checks.
*/
static int sb_permission(struct super_block *sb, struct inode *inode, int mask)
{
if (unlikely(mask & MAY_WRITE)) {
umode_t mode = inode->i_mode;
/* Nobody gets write access to a read-only fs. */
if ((sb->s_flags & MS_RDONLY) &&
(S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
return -EROFS;
}
return 0;
}
/**
* inode_permission - Check for access rights to a given inode
* @inode: Inode to check permission on
* @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
*
* Check for read/write/execute permissions on an inode. We use fs[ug]id for
* this, letting us set arbitrary permissions for filesystem access without
* changing the "normal" UIDs which are used for other things.
*
* When checking for MAY_APPEND, MAY_WRITE must also be set in @mask.
*/
int inode_permission(struct inode *inode, int mask)
{
int retval;
retval = sb_permission(inode->i_sb, inode, mask);
if (retval)
return retval;
return __inode_permission(inode, mask);
}
EXPORT_SYMBOL(inode_permission);
/**
* path_get - get a reference to a path
* @path: path to get the reference to
*
* Given a path increment the reference count to the dentry and the vfsmount.
*/
void path_get(const struct path *path)
{
mntget(path->mnt);
dget(path->dentry);
}
EXPORT_SYMBOL(path_get);
/**
* path_put - put a reference to a path
* @path: path to put the reference to
*
* Given a path decrement the reference count to the dentry and the vfsmount.
*/
void path_put(const struct path *path)
{
dput(path->dentry);
mntput(path->mnt);
}
EXPORT_SYMBOL(path_put);
/**
* path_connected - Verify that a path->dentry is below path->mnt.mnt_root
* @path: nameidate to verify
*
* Rename can sometimes move a file or directory outside of a bind
* mount, path_connected allows those cases to be detected.
*/
static bool path_connected(const struct path *path)
{
struct vfsmount *mnt = path->mnt;
/* Only bind mounts can have disconnected paths */
if (mnt->mnt_root == mnt->mnt_sb->s_root)
return true;
return is_subdir(path->dentry, mnt->mnt_root);
}
/*
* Path walking has 2 modes, rcu-walk and ref-walk (see
* Documentation/filesystems/path-lookup.txt). In situations when we can't
* continue in RCU mode, we attempt to drop out of rcu-walk mode and grab
* normal reference counts on dentries and vfsmounts to transition to rcu-walk
* mode. Refcounts are grabbed at the last known good point before rcu-walk
* got stuck, so ref-walk may continue from there. If this is not successful
* (eg. a seqcount has changed), then failure is returned and it's up to caller
* to restart the path walk from the beginning in ref-walk mode.
*/
/**
* unlazy_walk - try to switch to ref-walk mode.
* @nd: nameidata pathwalk data
* @dentry: child of nd->path.dentry or NULL
* Returns: 0 on success, -ECHILD on failure
*
* unlazy_walk attempts to legitimize the current nd->path, nd->root and dentry
* for ref-walk mode. @dentry must be a path found by a do_lookup call on
* @nd or NULL. Must be called from rcu-walk context.
*/
static int unlazy_walk(struct nameidata *nd, struct dentry *dentry)
{
struct fs_struct *fs = current->fs;
struct dentry *parent = nd->path.dentry;
BUG_ON(!(nd->flags & LOOKUP_RCU));
/*
* After legitimizing the bastards, terminate_walk()
* will do the right thing for non-RCU mode, and all our
* subsequent exit cases should rcu_read_unlock()
* before returning. Do vfsmount first; if dentry
* can't be legitimized, just set nd->path.dentry to NULL
* and rely on dput(NULL) being a no-op.
*/
if (!legitimize_mnt(nd->path.mnt, nd->m_seq))
return -ECHILD;
nd->flags &= ~LOOKUP_RCU;
if (!lockref_get_not_dead(&parent->d_lockref)) {
nd->path.dentry = NULL;
goto out;
}
/*
* For a negative lookup, the lookup sequence point is the parents
* sequence point, and it only needs to revalidate the parent dentry.
*
* For a positive lookup, we need to move both the parent and the
* dentry from the RCU domain to be properly refcounted. And the
* sequence number in the dentry validates *both* dentry counters,
* since we checked the sequence number of the parent after we got
* the child sequence number. So we know the parent must still
* be valid if the child sequence number is still valid.
*/
if (!dentry) {
if (read_seqcount_retry(&parent->d_seq, nd->seq))
goto out;
BUG_ON(nd->inode != parent->d_inode);
} else {
if (!lockref_get_not_dead(&dentry->d_lockref))
goto out;
if (read_seqcount_retry(&dentry->d_seq, nd->seq))
goto drop_dentry;
}
/*
* Sequence counts matched. Now make sure that the root is
* still valid and get it if required.
*/
if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) {
spin_lock(&fs->lock);
if (nd->root.mnt != fs->root.mnt || nd->root.dentry != fs->root.dentry)
goto unlock_and_drop_dentry;
path_get(&nd->root);
spin_unlock(&fs->lock);
}
rcu_read_unlock();
return 0;
unlock_and_drop_dentry:
spin_unlock(&fs->lock);
drop_dentry:
rcu_read_unlock();
dput(dentry);
goto drop_root_mnt;
out:
rcu_read_unlock();
drop_root_mnt:
if (!(nd->flags & LOOKUP_ROOT))
nd->root.mnt = NULL;
return -ECHILD;
}
static inline int d_revalidate(struct dentry *dentry, unsigned int flags)
{
return dentry->d_op->d_revalidate(dentry, flags);
}
/**
* complete_walk - successful completion of path walk
* @nd: pointer nameidata
*
* If we had been in RCU mode, drop out of it and legitimize nd->path.
* Revalidate the final result, unless we'd already done that during
* the path walk or the filesystem doesn't ask for it. Return 0 on
* success, -error on failure. In case of failure caller does not
* need to drop nd->path.
*/
static int complete_walk(struct nameidata *nd)
{
struct dentry *dentry = nd->path.dentry;
int status;
if (nd->flags & LOOKUP_RCU) {
nd->flags &= ~LOOKUP_RCU;
if (!(nd->flags & LOOKUP_ROOT))
nd->root.mnt = NULL;
if (!legitimize_mnt(nd->path.mnt, nd->m_seq)) {
rcu_read_unlock();
return -ECHILD;
}
if (unlikely(!lockref_get_not_dead(&dentry->d_lockref))) {
rcu_read_unlock();
mntput(nd->path.mnt);
return -ECHILD;
}
if (read_seqcount_retry(&dentry->d_seq, nd->seq)) {
rcu_read_unlock();
dput(dentry);
mntput(nd->path.mnt);
return -ECHILD;
}
rcu_read_unlock();
}
if (likely(!(nd->flags & LOOKUP_JUMPED)))
return 0;
if (likely(!(dentry->d_flags & DCACHE_OP_WEAK_REVALIDATE)))
return 0;
status = dentry->d_op->d_weak_revalidate(dentry, nd->flags);
if (status > 0)
return 0;
if (!status)
status = -ESTALE;
path_put(&nd->path);
return status;
}
static __always_inline void set_root(struct nameidata *nd)
{
get_fs_root(current->fs, &nd->root);
}
static int link_path_walk(const char *, struct nameidata *);
static __always_inline unsigned set_root_rcu(struct nameidata *nd)
{
struct fs_struct *fs = current->fs;
unsigned seq, res;
do {
seq = read_seqcount_begin(&fs->seq);
nd->root = fs->root;
res = __read_seqcount_begin(&nd->root.dentry->d_seq);
} while (read_seqcount_retry(&fs->seq, seq));
return res;
}
static void path_put_conditional(struct path *path, struct nameidata *nd)
{
dput(path->dentry);
if (path->mnt != nd->path.mnt)
mntput(path->mnt);
}
static inline void path_to_nameidata(const struct path *path,
struct nameidata *nd)
{
if (!(nd->flags & LOOKUP_RCU)) {
dput(nd->path.dentry);
if (nd->path.mnt != path->mnt)
mntput(nd->path.mnt);
}
nd->path.mnt = path->mnt;
nd->path.dentry = path->dentry;
}
/*
* Helper to directly jump to a known parsed path from ->follow_link,
* caller must have taken a reference to path beforehand.
*/
void nd_jump_link(struct nameidata *nd, struct path *path)
{
path_put(&nd->path);
nd->path = *path;
nd->inode = nd->path.dentry->d_inode;
nd->flags |= LOOKUP_JUMPED;
}
static inline void put_link(struct nameidata *nd, struct path *link, void *cookie)
{
struct inode *inode = link->dentry->d_inode;
if (inode->i_op->put_link)
inode->i_op->put_link(link->dentry, nd, cookie);
path_put(link);
}
int sysctl_protected_symlinks __read_mostly = 0;
int sysctl_protected_hardlinks __read_mostly = 0;
/**
* may_follow_link - Check symlink following for unsafe situations
* @link: The path of the symlink
* @nd: nameidata pathwalk data
*
* In the case of the sysctl_protected_symlinks sysctl being enabled,
* CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is
* in a sticky world-writable directory. This is to protect privileged
* processes from failing races against path names that may change out
* from under them by way of other users creating malicious symlinks.
* It will permit symlinks to be followed only when outside a sticky
* world-writable directory, or when the uid of the symlink and follower
* match, or when the directory owner matches the symlink's owner.
*
* Returns 0 if following the symlink is allowed, -ve on error.
*/
static inline int may_follow_link(struct path *link, struct nameidata *nd)
{
const struct inode *inode;
const struct inode *parent;
if (!sysctl_protected_symlinks)
return 0;
/* Allowed if owner and follower match. */
inode = link->dentry->d_inode;
if (uid_eq(current_cred()->fsuid, inode->i_uid))
return 0;
/* Allowed if parent directory not sticky and world-writable. */
parent = nd->path.dentry->d_inode;
if ((parent->i_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH))
return 0;
/* Allowed if parent directory and link owner match. */
if (uid_eq(parent->i_uid, inode->i_uid))
return 0;
audit_log_link_denied("follow_link", link);
path_put_conditional(link, nd);
path_put(&nd->path);
return -EACCES;
}
/**
* safe_hardlink_source - Check for safe hardlink conditions
* @inode: the source inode to hardlink from
*
* Return false if at least one of the following conditions:
* - inode is not a regular file
* - inode is setuid
* - inode is setgid and group-exec
* - access failure for read and write
*
* Otherwise returns true.
*/
static bool safe_hardlink_source(struct inode *inode)
{
umode_t mode = inode->i_mode;
/* Special files should not get pinned to the filesystem. */
if (!S_ISREG(mode))
return false;
/* Setuid files should not get pinned to the filesystem. */
if (mode & S_ISUID)
return false;
/* Executable setgid files should not get pinned to the filesystem. */
if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
return false;
/* Hardlinking to unreadable or unwritable sources is dangerous. */
if (inode_permission(inode, MAY_READ | MAY_WRITE))
return false;
return true;
}
/**
* may_linkat - Check permissions for creating a hardlink
* @link: the source to hardlink from
*
* Block hardlink when all of:
* - sysctl_protected_hardlinks enabled
* - fsuid does not match inode
* - hardlink source is unsafe (see safe_hardlink_source() above)
* - not CAP_FOWNER
*
* Returns 0 if successful, -ve on error.
*/
static int may_linkat(struct path *link)
{
const struct cred *cred;
struct inode *inode;
if (!sysctl_protected_hardlinks)
return 0;
cred = current_cred();
inode = link->dentry->d_inode;
/* Source inode owner (or CAP_FOWNER) can hardlink all they like,
* otherwise, it must be a safe source.
*/
if (uid_eq(cred->fsuid, inode->i_uid) || safe_hardlink_source(inode) ||
capable(CAP_FOWNER))
return 0;
audit_log_link_denied("linkat", link);
return -EPERM;
}
static __always_inline int
follow_link(struct path *link, struct nameidata *nd, void **p)
{
struct dentry *dentry = link->dentry;
int error;
char *s;
BUG_ON(nd->flags & LOOKUP_RCU);
if (link->mnt == nd->path.mnt)
mntget(link->mnt);
error = -ELOOP;
if (unlikely(current->total_link_count >= 40))
goto out_put_nd_path;
cond_resched();
current->total_link_count++;
touch_atime(link);
nd_set_link(nd, NULL);
error = security_inode_follow_link(link->dentry, nd);
if (error)
goto out_put_nd_path;
nd->last_type = LAST_BIND;
*p = dentry->d_inode->i_op->follow_link(dentry, nd);
error = PTR_ERR(*p);
if (IS_ERR(*p))
goto out_put_nd_path;
error = 0;
s = nd_get_link(nd);
if (s) {
if (unlikely(IS_ERR(s))) {
path_put(&nd->path);
put_link(nd, link, *p);
return PTR_ERR(s);
}
if (*s == '/') {
if (!nd->root.mnt)
set_root(nd);
path_put(&nd->path);
nd->path = nd->root;
path_get(&nd->root);
nd->flags |= LOOKUP_JUMPED;
}
nd->inode = nd->path.dentry->d_inode;
error = link_path_walk(s, nd);
if (unlikely(error))
put_link(nd, link, *p);
}
return error;
out_put_nd_path:
*p = NULL;
path_put(&nd->path);
path_put(link);
return error;
}
static int follow_up_rcu(struct path *path)
{
struct mount *mnt = real_mount(path->mnt);
struct mount *parent;
struct dentry *mountpoint;
parent = mnt->mnt_parent;
if (&parent->mnt == path->mnt)
return 0;
mountpoint = mnt->mnt_mountpoint;
path->dentry = mountpoint;
path->mnt = &parent->mnt;
return 1;
}
/*
* follow_up - Find the mountpoint of path's vfsmount
*
* Given a path, find the mountpoint of its source file system.
* Replace @path with the path of the mountpoint in the parent mount.
* Up is towards /.
*
* Return 1 if we went up a level and 0 if we were already at the
* root.
*/
int follow_up(struct path *path)
{
struct mount *mnt = real_mount(path->mnt);
struct mount *parent;
struct dentry *mountpoint;
read_seqlock_excl(&mount_lock);
parent = mnt->mnt_parent;
if (parent == mnt) {
read_sequnlock_excl(&mount_lock);
return 0;
}
mntget(&parent->mnt);
mountpoint = dget(mnt->mnt_mountpoint);
read_sequnlock_excl(&mount_lock);
dput(path->dentry);
path->dentry = mountpoint;
mntput(path->mnt);
path->mnt = &parent->mnt;
return 1;
}
EXPORT_SYMBOL(follow_up);
/*
* Perform an automount
* - return -EISDIR to tell follow_managed() to stop and return the path we
* were called with.
*/
static int follow_automount(struct path *path, unsigned flags,
bool *need_mntput)
{
struct vfsmount *mnt;
int err;
if (!path->dentry->d_op || !path->dentry->d_op->d_automount)
return -EREMOTE;
/* We don't want to mount if someone's just doing a stat -
* unless they're stat'ing a directory and appended a '/' to
* the name.
*
* We do, however, want to mount if someone wants to open or
* create a file of any type under the mountpoint, wants to
* traverse through the mountpoint or wants to open the
* mounted directory. Also, autofs may mark negative dentries
* as being automount points. These will need the attentions
* of the daemon to instantiate them before they can be used.
*/
if (!(flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY |
LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) &&
path->dentry->d_inode)
return -EISDIR;
current->total_link_count++;
if (current->total_link_count >= 40)
return -ELOOP;
mnt = path->dentry->d_op->d_automount(path);
if (IS_ERR(mnt)) {
/*
* The filesystem is allowed to return -EISDIR here to indicate
* it doesn't want to automount. For instance, autofs would do
* this so that its userspace daemon can mount on this dentry.
*
* However, we can only permit this if it's a terminal point in
* the path being looked up; if it wasn't then the remainder of
* the path is inaccessible and we should say so.
*/
if (PTR_ERR(mnt) == -EISDIR && (flags & LOOKUP_PARENT))
return -EREMOTE;
return PTR_ERR(mnt);
}
if (!mnt) /* mount collision */
return 0;
if (!*need_mntput) {
/* lock_mount() may release path->mnt on error */
mntget(path->mnt);
*need_mntput = true;
}
err = finish_automount(mnt, path);
switch (err) {
case -EBUSY:
/* Someone else made a mount here whilst we were busy */
return 0;
case 0:
path_put(path);
path->mnt = mnt;
path->dentry = dget(mnt->mnt_root);
return 0;
default:
return err;
}
}
/*
* Handle a dentry that is managed in some way.
* - Flagged for transit management (autofs)
* - Flagged as mountpoint
* - Flagged as automount point
*
* This may only be called in refwalk mode.
*
* Serialization is taken care of in namespace.c
*/
static int follow_managed(struct path *path, unsigned flags)
{
struct vfsmount *mnt = path->mnt; /* held by caller, must be left alone */
unsigned managed;
bool need_mntput = false;
int ret = 0;
/* Given that we're not holding a lock here, we retain the value in a
* local variable for each dentry as we look at it so that we don't see
* the components of that value change under us */
while (managed = ACCESS_ONCE(path->dentry->d_flags),
managed &= DCACHE_MANAGED_DENTRY,
unlikely(managed != 0)) {
/* Allow the filesystem to manage the transit without i_mutex
* being held. */
if (managed & DCACHE_MANAGE_TRANSIT) {
BUG_ON(!path->dentry->d_op);
BUG_ON(!path->dentry->d_op->d_manage);
ret = path->dentry->d_op->d_manage(path->dentry, false);
if (ret < 0)
break;
}
/* Transit to a mounted filesystem. */
if (managed & DCACHE_MOUNTED) {
struct vfsmount *mounted = lookup_mnt(path);
if (mounted) {
dput(path->dentry);
if (need_mntput)
mntput(path->mnt);
path->mnt = mounted;
path->dentry = dget(mounted->mnt_root);
need_mntput = true;
continue;
}
/* Something is mounted on this dentry in another
* namespace and/or whatever was mounted there in this
* namespace got unmounted before lookup_mnt() could
* get it */
}
/* Handle an automount point */
if (managed & DCACHE_NEED_AUTOMOUNT) {
ret = follow_automount(path, flags, &need_mntput);
if (ret < 0)
break;
continue;
}
/* We didn't change the current path point */
break;
}
if (need_mntput && path->mnt == mnt)
mntput(path->mnt);
if (ret == -EISDIR)
ret = 0;
return ret < 0 ? ret : need_mntput;
}
int follow_down_one(struct path *path)
{
struct vfsmount *mounted;
mounted = lookup_mnt(path);
if (mounted) {
dput(path->dentry);
mntput(path->mnt);
path->mnt = mounted;
path->dentry = dget(mounted->mnt_root);
return 1;
}
return 0;
}
EXPORT_SYMBOL(follow_down_one);
static inline int managed_dentry_rcu(struct dentry *dentry)
{
return (dentry->d_flags & DCACHE_MANAGE_TRANSIT) ?
dentry->d_op->d_manage(dentry, true) : 0;
}
/*
* Try to skip to top of mountpoint pile in rcuwalk mode. Fail if
* we meet a managed dentry that would need blocking.
*/
static bool __follow_mount_rcu(struct nameidata *nd, struct path *path,
struct inode **inode)
{
for (;;) {
struct mount *mounted;
/*
* Don't forget we might have a non-mountpoint managed dentry
* that wants to block transit.
*/
switch (managed_dentry_rcu(path->dentry)) {
case -ECHILD:
default:
return false;
case -EISDIR:
return true;
case 0:
break;
}
if (!d_mountpoint(path->dentry))
return !(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT);
mounted = __lookup_mnt(path->mnt, path->dentry);
if (!mounted)
break;
path->mnt = &mounted->mnt;
path->dentry = mounted->mnt.mnt_root;
nd->flags |= LOOKUP_JUMPED;
nd->seq = read_seqcount_begin(&path->dentry->d_seq);
/*
* Update the inode too. We don't need to re-check the
* dentry sequence number here after this d_inode read,
* because a mount-point is always pinned.
*/
*inode = path->dentry->d_inode;
}
return !read_seqretry(&mount_lock, nd->m_seq) &&
!(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT);
}
static int follow_dotdot_rcu(struct nameidata *nd)
{
struct inode *inode = nd->inode;
if (!nd->root.mnt)
set_root_rcu(nd);
while (1) {
if (nd->path.dentry == nd->root.dentry &&
nd->path.mnt == nd->root.mnt) {
break;
}
if (nd->path.dentry != nd->path.mnt->mnt_root) {
struct dentry *old = nd->path.dentry;
struct dentry *parent = old->d_parent;
unsigned seq;
inode = parent->d_inode;
seq = read_seqcount_begin(&parent->d_seq);
if (read_seqcount_retry(&old->d_seq, nd->seq))
goto failed;
nd->path.dentry = parent;
nd->seq = seq;
if (unlikely(!path_connected(&nd->path)))
goto failed;
break;
}
if (!follow_up_rcu(&nd->path))
break;
inode = nd->path.dentry->d_inode;
nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
}
while (d_mountpoint(nd->path.dentry)) {
struct mount *mounted;
mounted = __lookup_mnt(nd->path.mnt, nd->path.dentry);
if (!mounted)
break;
nd->path.mnt = &mounted->mnt;
nd->path.dentry = mounted->mnt.mnt_root;
inode = nd->path.dentry->d_inode;
nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
if (read_seqretry(&mount_lock, nd->m_seq))
goto failed;
}
nd->inode = inode;
return 0;
failed:
nd->flags &= ~LOOKUP_RCU;
if (!(nd->flags & LOOKUP_ROOT))
nd->root.mnt = NULL;
rcu_read_unlock();
return -ECHILD;
}
/*
* Follow down to the covering mount currently visible to userspace. At each
* point, the filesystem owning that dentry may be queried as to whether the
* caller is permitted to proceed or not.
*/
int follow_down(struct path *path)
{
unsigned managed;
int ret;
while (managed = ACCESS_ONCE(path->dentry->d_flags),
unlikely(managed & DCACHE_MANAGED_DENTRY)) {
/* Allow the filesystem to manage the transit without i_mutex
* being held.
*
* We indicate to the filesystem if someone is trying to mount
* something here. This gives autofs the chance to deny anyone
* other than its daemon the right to mount on its
* superstructure.
*
* The filesystem may sleep at this point.
*/
if (managed & DCACHE_MANAGE_TRANSIT) {
BUG_ON(!path->dentry->d_op);
BUG_ON(!path->dentry->d_op->d_manage);
ret = path->dentry->d_op->d_manage(
path->dentry, false);
if (ret < 0)
return ret == -EISDIR ? 0 : ret;
}
/* Transit to a mounted filesystem. */
if (managed & DCACHE_MOUNTED) {
struct vfsmount *mounted = lookup_mnt(path);
if (!mounted)
break;
dput(path->dentry);
mntput(path->mnt);
path->mnt = mounted;
path->dentry = dget(mounted->mnt_root);
continue;
}
/* Don't handle automount points here */
break;
}
return 0;
}
EXPORT_SYMBOL(follow_down);
/*
* Skip to top of mountpoint pile in refwalk mode for follow_dotdot()
*/
static void follow_mount(struct path *path)
{
while (d_mountpoint(path->dentry)) {
struct vfsmount *mounted = lookup_mnt(path);
if (!mounted)
break;
dput(path->dentry);
mntput(path->mnt);
path->mnt = mounted;
path->dentry = dget(mounted->mnt_root);
}
}
static int follow_dotdot(struct nameidata *nd)
{
if (!nd->root.mnt)
set_root(nd);
while(1) {
struct dentry *old = nd->path.dentry;
if (nd->path.dentry == nd->root.dentry &&
nd->path.mnt == nd->root.mnt) {
break;
}
if (nd->path.dentry != nd->path.mnt->mnt_root) {
/* rare case of legitimate dget_parent()... */
nd->path.dentry = dget_parent(nd->path.dentry);
dput(old);
if (unlikely(!path_connected(&nd->path))) {
path_put(&nd->path);
return -ENOENT;
}
break;
}
if (!follow_up(&nd->path))
break;
}
follow_mount(&nd->path);
nd->inode = nd->path.dentry->d_inode;
return 0;
}
/*
* This looks up the name in dcache, possibly revalidates the old dentry and
* allocates a new one if not found or not valid. In the need_lookup argument
* returns whether i_op->lookup is necessary.
*
* dir->d_inode->i_mutex must be held
*/
static struct dentry *lookup_dcache(struct qstr *name, struct dentry *dir,
unsigned int flags, bool *need_lookup)
{
struct dentry *dentry;
int error;
*need_lookup = false;
dentry = d_lookup(dir, name);
if (dentry) {
if (dentry->d_flags & DCACHE_OP_REVALIDATE) {
error = d_revalidate(dentry, flags);
if (unlikely(error <= 0)) {
if (error < 0) {
dput(dentry);
return ERR_PTR(error);
} else {
d_invalidate(dentry);
dput(dentry);
dentry = NULL;
}
}
}
}
if (!dentry) {
dentry = d_alloc(dir, name);
if (unlikely(!dentry))
return ERR_PTR(-ENOMEM);
*need_lookup = true;
}
return dentry;
}
/*
* Call i_op->lookup on the dentry. The dentry must be negative and
* unhashed.
*
* dir->d_inode->i_mutex must be held
*/
static struct dentry *lookup_real(struct inode *dir, struct dentry *dentry,
unsigned int flags)
{
struct dentry *old;
/* Don't create child dentry for a dead directory. */
if (unlikely(IS_DEADDIR(dir))) {
dput(dentry);
return ERR_PTR(-ENOENT);
}
old = dir->i_op->lookup(dir, dentry, flags);
if (unlikely(old)) {
dput(dentry);
dentry = old;
}
return dentry;
}
static struct dentry *__lookup_hash(struct qstr *name,
struct dentry *base, unsigned int flags)
{
bool need_lookup;
struct dentry *dentry;
dentry = lookup_dcache(name, base, flags, &need_lookup);
if (!need_lookup)
return dentry;
return lookup_real(base->d_inode, dentry, flags);
}
/*
* It's more convoluted than I'd like it to be, but... it's still fairly
* small and for now I'd prefer to have fast path as straight as possible.
* It _is_ time-critical.
*/
static int lookup_fast(struct nameidata *nd,
struct path *path, struct inode **inode)
{
struct vfsmount *mnt = nd->path.mnt;
struct dentry *dentry, *parent = nd->path.dentry;
int need_reval = 1;
int status = 1;
int err;
/*
* Rename seqlock is not required here because in the off chance
* of a false negative due to a concurrent rename, we're going to
* do the non-racy lookup, below.
*/
if (nd->flags & LOOKUP_RCU) {
unsigned seq;
dentry = __d_lookup_rcu(parent, &nd->last, &seq);
if (!dentry)
goto unlazy;
/*
* This sequence count validates that the inode matches
* the dentry name information from lookup.
*/
*inode = dentry->d_inode;
if (read_seqcount_retry(&dentry->d_seq, seq))
return -ECHILD;
/*
* This sequence count validates that the parent had no
* changes while we did the lookup of the dentry above.
*
* The memory barrier in read_seqcount_begin of child is
* enough, we can use __read_seqcount_retry here.
*/
if (__read_seqcount_retry(&parent->d_seq, nd->seq))
return -ECHILD;
nd->seq = seq;
if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE)) {
status = d_revalidate(dentry, nd->flags);
if (unlikely(status <= 0)) {
if (status != -ECHILD)
need_reval = 0;
goto unlazy;
}
}
path->mnt = mnt;
path->dentry = dentry;
if (likely(__follow_mount_rcu(nd, path, inode)))
return 0;
unlazy:
if (unlazy_walk(nd, dentry))
return -ECHILD;
} else {
dentry = __d_lookup(parent, &nd->last);
}
if (unlikely(!dentry))
goto need_lookup;
if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE) && need_reval)
status = d_revalidate(dentry, nd->flags);
if (unlikely(status <= 0)) {
if (status < 0) {
dput(dentry);
return status;
}
d_invalidate(dentry);
dput(dentry);
goto need_lookup;
}
path->mnt = mnt;
path->dentry = dentry;
err = follow_managed(path, nd->flags);
if (unlikely(err < 0)) {
path_put_conditional(path, nd);
return err;
}
if (err)
nd->flags |= LOOKUP_JUMPED;
*inode = path->dentry->d_inode;
return 0;
need_lookup:
return 1;
}
/* Fast lookup failed, do it the slow way */
static int lookup_slow(struct nameidata *nd, struct path *path)
{
struct dentry *dentry, *parent;
int err;
parent = nd->path.dentry;
BUG_ON(nd->inode != parent->d_inode);
mutex_lock(&parent->d_inode->i_mutex);
dentry = __lookup_hash(&nd->last, parent, nd->flags);
mutex_unlock(&parent->d_inode->i_mutex);
if (IS_ERR(dentry))
return PTR_ERR(dentry);
path->mnt = nd->path.mnt;
path->dentry = dentry;
err = follow_managed(path, nd->flags);
if (unlikely(err < 0)) {
path_put_conditional(path, nd);
return err;
}
if (err)
nd->flags |= LOOKUP_JUMPED;
return 0;
}
static inline int may_lookup(struct nameidata *nd)
{
if (nd->flags & LOOKUP_RCU) {
int err = inode_permission(nd->inode, MAY_EXEC|MAY_NOT_BLOCK);
if (err != -ECHILD)
return err;
if (unlazy_walk(nd, NULL))
return -ECHILD;
}
return inode_permission(nd->inode, MAY_EXEC);
}
static inline int handle_dots(struct nameidata *nd, int type)
{
if (type == LAST_DOTDOT) {
if (nd->flags & LOOKUP_RCU) {
if (follow_dotdot_rcu(nd))
return -ECHILD;
} else
return follow_dotdot(nd);
}
return 0;
}
static void terminate_walk(struct nameidata *nd)
{
if (!(nd->flags & LOOKUP_RCU)) {
path_put(&nd->path);
} else {
nd->flags &= ~LOOKUP_RCU;
if (!(nd->flags & LOOKUP_ROOT))
nd->root.mnt = NULL;
rcu_read_unlock();
}
}
/*
* Do we need to follow links? We _really_ want to be able
* to do this check without having to look at inode->i_op,
* so we keep a cache of "no, this doesn't need follow_link"
* for the common case.
*/
static inline int should_follow_link(struct dentry *dentry, int follow)
{
return unlikely(d_is_symlink(dentry)) ? follow : 0;
}
static inline int walk_component(struct nameidata *nd, struct path *path,
int follow)
{
struct inode *inode;
int err;
/*
* "." and ".." are special - ".." especially so because it has
* to be able to know about the current root directory and
* parent relationships.
*/
if (unlikely(nd->last_type != LAST_NORM))
return handle_dots(nd, nd->last_type);
err = lookup_fast(nd, path, &inode);
if (unlikely(err)) {
if (err < 0)
goto out_err;
err = lookup_slow(nd, path);
if (err < 0)
goto out_err;
inode = path->dentry->d_inode;
}
err = -ENOENT;
if (!inode || d_is_negative(path->dentry))
goto out_path_put;
if (should_follow_link(path->dentry, follow)) {
if (nd->flags & LOOKUP_RCU) {
if (unlikely(nd->path.mnt != path->mnt ||
unlazy_walk(nd, path->dentry))) {
err = -ECHILD;
goto out_err;
}
}
BUG_ON(inode != path->dentry->d_inode);
return 1;
}
path_to_nameidata(path, nd);
nd->inode = inode;
return 0;
out_path_put:
path_to_nameidata(path, nd);
out_err:
terminate_walk(nd);
return err;
}
/*
* This limits recursive symlink follows to 8, while
* limiting consecutive symlinks to 40.
*
* Without that kind of total limit, nasty chains of consecutive
* symlinks can cause almost arbitrarily long lookups.
*/
static inline int nested_symlink(struct path *path, struct nameidata *nd)
{
int res;
if (unlikely(current->link_count >= MAX_NESTED_LINKS)) {
path_put_conditional(path, nd);
path_put(&nd->path);
return -ELOOP;
}
BUG_ON(nd->depth >= MAX_NESTED_LINKS);
nd->depth++;
current->link_count++;
do {
struct path link = *path;
void *cookie;
res = follow_link(&link, nd, &cookie);
if (res)
break;
res = walk_component(nd, path, LOOKUP_FOLLOW);
put_link(nd, &link, cookie);
} while (res > 0);
current->link_count--;
nd->depth--;
return res;
}
/*
* We can do the critical dentry name comparison and hashing
* operations one word at a time, but we are limited to:
*
* - Architectures with fast unaligned word accesses. We could
* do a "get_unaligned()" if this helps and is sufficiently
* fast.
*
* - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we
* do not trap on the (extremely unlikely) case of a page
* crossing operation.
*
* - Furthermore, we need an efficient 64-bit compile for the
* 64-bit case in order to generate the "number of bytes in
* the final mask". Again, that could be replaced with a
* efficient population count instruction or similar.
*/
#ifdef CONFIG_DCACHE_WORD_ACCESS
#include <asm/word-at-a-time.h>
#ifdef CONFIG_64BIT
static inline unsigned int fold_hash(unsigned long hash)
{
return hash_64(hash, 32);
}
#else /* 32-bit case */
#define fold_hash(x) (x)
#endif
unsigned int full_name_hash(const unsigned char *name, unsigned int len)
{
unsigned long a, mask;
unsigned long hash = 0;
for (;;) {
a = load_unaligned_zeropad(name);
if (len < sizeof(unsigned long))
break;
hash += a;
hash *= 9;
name += sizeof(unsigned long);
len -= sizeof(unsigned long);
if (!len)
goto done;
}
mask = bytemask_from_count(len);
hash += mask & a;
done:
return fold_hash(hash);
}
EXPORT_SYMBOL(full_name_hash);
/*
* Calculate the length and hash of the path component, and
* return the "hash_len" as the result.
*/
static inline u64 hash_name(const char *name)
{
unsigned long a, b, adata, bdata, mask, hash, len;
const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
hash = a = 0;
len = -sizeof(unsigned long);
do {
hash = (hash + a) * 9;
len += sizeof(unsigned long);
a = load_unaligned_zeropad(name+len);
b = a ^ REPEAT_BYTE('/');
} while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants)));
adata = prep_zero_mask(a, adata, &constants);
bdata = prep_zero_mask(b, bdata, &constants);
mask = create_zero_mask(adata | bdata);
hash += a & zero_bytemask(mask);
len += find_zero(mask);
return hashlen_create(fold_hash(hash), len);
}
#else
unsigned int full_name_hash(const unsigned char *name, unsigned int len)
{
unsigned long hash = init_name_hash();
while (len--)
hash = partial_name_hash(*name++, hash);
return end_name_hash(hash);
}
EXPORT_SYMBOL(full_name_hash);
/*
* We know there's a real path component here of at least
* one character.
*/
static inline u64 hash_name(const char *name)
{
unsigned long hash = init_name_hash();
unsigned long len = 0, c;
c = (unsigned char)*name;
do {
len++;
hash = partial_name_hash(c, hash);
c = (unsigned char)name[len];
} while (c && c != '/');
return hashlen_create(end_name_hash(hash), len);
}
#endif
/*
* Name resolution.
* This is the basic name resolution function, turning a pathname into
* the final dentry. We expect 'base' to be positive and a directory.
*
* Returns 0 and nd will have valid dentry and mnt on success.
* Returns error and drops reference to input namei data on failure.
*/
static int link_path_walk(const char *name, struct nameidata *nd)
{
struct path next;
int err;
while (*name=='/')
name++;
if (!*name)
return 0;
/* At this point we know we have a real path component. */
for(;;) {
u64 hash_len;
int type;
err = may_lookup(nd);
if (err)
break;
hash_len = hash_name(name);
type = LAST_NORM;
if (name[0] == '.') switch (hashlen_len(hash_len)) {
case 2:
if (name[1] == '.') {
type = LAST_DOTDOT;
nd->flags |= LOOKUP_JUMPED;
}
break;
case 1:
type = LAST_DOT;
}
if (likely(type == LAST_NORM)) {
struct dentry *parent = nd->path.dentry;
nd->flags &= ~LOOKUP_JUMPED;
if (unlikely(parent->d_flags & DCACHE_OP_HASH)) {
struct qstr this = { { .hash_len = hash_len }, .name = name };
err = parent->d_op->d_hash(parent, &this);
if (err < 0)
break;
hash_len = this.hash_len;
name = this.name;
}
}
nd->last.hash_len = hash_len;
nd->last.name = name;
nd->last_type = type;
name += hashlen_len(hash_len);
if (!*name)
return 0;
/*
* If it wasn't NUL, we know it was '/'. Skip that
* slash, and continue until no more slashes.
*/
do {
name++;
} while (unlikely(*name == '/'));
if (!*name)
return 0;
err = walk_component(nd, &next, LOOKUP_FOLLOW);
if (err < 0)
return err;
if (err) {
err = nested_symlink(&next, nd);
if (err)
return err;
}
if (!d_can_lookup(nd->path.dentry)) {
err = -ENOTDIR;
break;
}
}
terminate_walk(nd);
return err;
}
static int path_init(int dfd, const char *name, unsigned int flags,
struct nameidata *nd, struct file **fp)
{
int retval = 0;
nd->last_type = LAST_ROOT; /* if there are only slashes... */
nd->flags = flags | LOOKUP_JUMPED;
nd->depth = 0;
if (flags & LOOKUP_ROOT) {
struct dentry *root = nd->root.dentry;
struct inode *inode = root->d_inode;
if (*name) {
if (!d_can_lookup(root))
return -ENOTDIR;
retval = inode_permission(inode, MAY_EXEC);
if (retval)
return retval;
}
nd->path = nd->root;
nd->inode = inode;
if (flags & LOOKUP_RCU) {
rcu_read_lock();
nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
nd->m_seq = read_seqbegin(&mount_lock);
} else {
path_get(&nd->path);
}
return 0;
}
nd->root.mnt = NULL;
nd->m_seq = read_seqbegin(&mount_lock);
if (*name=='/') {
if (flags & LOOKUP_RCU) {
rcu_read_lock();
nd->seq = set_root_rcu(nd);
} else {
set_root(nd);
path_get(&nd->root);
}
nd->path = nd->root;
} else if (dfd == AT_FDCWD) {
if (flags & LOOKUP_RCU) {
struct fs_struct *fs = current->fs;
unsigned seq;
rcu_read_lock();
do {
seq = read_seqcount_begin(&fs->seq);
nd->path = fs->pwd;
nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
} while (read_seqcount_retry(&fs->seq, seq));
} else {
get_fs_pwd(current->fs, &nd->path);
}
} else {
/* Caller must check execute permissions on the starting path component */
struct fd f = fdget_raw(dfd);
struct dentry *dentry;
if (!f.file)
return -EBADF;
dentry = f.file->f_path.dentry;
if (*name) {
if (!d_can_lookup(dentry)) {
fdput(f);
return -ENOTDIR;
}
}
nd->path = f.file->f_path;
if (flags & LOOKUP_RCU) {
if (f.flags & FDPUT_FPUT)
*fp = f.file;
nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
rcu_read_lock();
} else {
path_get(&nd->path);
fdput(f);
}
}
nd->inode = nd->path.dentry->d_inode;
if (!(flags & LOOKUP_RCU))
return 0;
if (likely(!read_seqcount_retry(&nd->path.dentry->d_seq, nd->seq)))
return 0;
if (!(nd->flags & LOOKUP_ROOT))
nd->root.mnt = NULL;
rcu_read_unlock();
return -ECHILD;
}
static inline int lookup_last(struct nameidata *nd, struct path *path)
{
if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len])
nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
nd->flags &= ~LOOKUP_PARENT;
return walk_component(nd, path, nd->flags & LOOKUP_FOLLOW);
}
/* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
static int path_lookupat(int dfd, const char *name,
unsigned int flags, struct nameidata *nd)
{
struct file *base = NULL;
struct path path;
int err;
/*
* Path walking is largely split up into 2 different synchronisation
* schemes, rcu-walk and ref-walk (explained in
* Documentation/filesystems/path-lookup.txt). These share much of the
* path walk code, but some things particularly setup, cleanup, and
* following mounts are sufficiently divergent that functions are
* duplicated. Typically there is a function foo(), and its RCU
* analogue, foo_rcu().
*
* -ECHILD is the error number of choice (just to avoid clashes) that
* is returned if some aspect of an rcu-walk fails. Such an error must
* be handled by restarting a traditional ref-walk (which will always
* be able to complete).
*/
err = path_init(dfd, name, flags | LOOKUP_PARENT, nd, &base);
if (unlikely(err))
goto out;
current->total_link_count = 0;
err = link_path_walk(name, nd);
if (!err && !(flags & LOOKUP_PARENT)) {
err = lookup_last(nd, &path);
while (err > 0) {
void *cookie;
struct path link = path;
err = may_follow_link(&link, nd);
if (unlikely(err))
break;
nd->flags |= LOOKUP_PARENT;
err = follow_link(&link, nd, &cookie);
if (err)
break;
err = lookup_last(nd, &path);
put_link(nd, &link, cookie);
}
}
if (!err)
err = complete_walk(nd);
if (!err && nd->flags & LOOKUP_DIRECTORY) {
if (!d_can_lookup(nd->path.dentry)) {
path_put(&nd->path);
err = -ENOTDIR;
}
}
out:
if (base)
fput(base);
if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) {
path_put(&nd->root);
nd->root.mnt = NULL;
}
return err;
}
static int filename_lookup(int dfd, struct filename *name,
unsigned int flags, struct nameidata *nd)
{
int retval = path_lookupat(dfd, name->name, flags | LOOKUP_RCU, nd);
if (unlikely(retval == -ECHILD))
retval = path_lookupat(dfd, name->name, flags, nd);
if (unlikely(retval == -ESTALE))
retval = path_lookupat(dfd, name->name,
flags | LOOKUP_REVAL, nd);
if (likely(!retval))
audit_inode(name, nd->path.dentry, flags & LOOKUP_PARENT);
return retval;
}
static int do_path_lookup(int dfd, const char *name,
unsigned int flags, struct nameidata *nd)
{
struct filename filename = { .name = name };
return filename_lookup(dfd, &filename, flags, nd);
}
/* does lookup, returns the object with parent locked */
struct dentry *kern_path_locked(const char *name, struct path *path)
{
struct nameidata nd;
struct dentry *d;
int err = do_path_lookup(AT_FDCWD, name, LOOKUP_PARENT, &nd);
if (err)
return ERR_PTR(err);
if (nd.last_type != LAST_NORM) {
path_put(&nd.path);
return ERR_PTR(-EINVAL);
}
mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
d = __lookup_hash(&nd.last, nd.path.dentry, 0);
if (IS_ERR(d)) {
mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
path_put(&nd.path);
return d;
}
*path = nd.path;
return d;
}
int kern_path(const char *name, unsigned int flags, struct path *path)
{
struct nameidata nd;
int res = do_path_lookup(AT_FDCWD, name, flags, &nd);
if (!res)
*path = nd.path;
return res;
}
EXPORT_SYMBOL(kern_path);
/**
* vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
* @dentry: pointer to dentry of the base directory
* @mnt: pointer to vfs mount of the base directory
* @name: pointer to file name
* @flags: lookup flags
* @path: pointer to struct path to fill
*/
int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
const char *name, unsigned int flags,
struct path *path)
{
struct nameidata nd;
int err;
nd.root.dentry = dentry;
nd.root.mnt = mnt;
BUG_ON(flags & LOOKUP_PARENT);
/* the first argument of do_path_lookup() is ignored with LOOKUP_ROOT */
err = do_path_lookup(AT_FDCWD, name, flags | LOOKUP_ROOT, &nd);
if (!err)
*path = nd.path;
return err;
}
EXPORT_SYMBOL(vfs_path_lookup);
/*
* Restricted form of lookup. Doesn't follow links, single-component only,
* needs parent already locked. Doesn't follow mounts.
* SMP-safe.
*/
static struct dentry *lookup_hash(struct nameidata *nd)
{
return __lookup_hash(&nd->last, nd->path.dentry, nd->flags);
}
/**
* lookup_one_len - filesystem helper to lookup single pathname component
* @name: pathname component to lookup
* @base: base directory to lookup from
* @len: maximum length @len should be interpreted to
*
* Note that this routine is purely a helper for filesystem usage and should
* not be called by generic code. Also note that by using this function the
* nameidata argument is passed to the filesystem methods and a filesystem
* using this helper needs to be prepared for that.
*/
struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
{
struct qstr this;
unsigned int c;
int err;
WARN_ON_ONCE(!mutex_is_locked(&base->d_inode->i_mutex));
this.name = name;
this.len = len;
this.hash = full_name_hash(name, len);
if (!len)
return ERR_PTR(-EACCES);
if (unlikely(name[0] == '.')) {
if (len < 2 || (len == 2 && name[1] == '.'))
return ERR_PTR(-EACCES);
}
while (len--) {
c = *(const unsigned char *)name++;
if (c == '/' || c == '\0')
return ERR_PTR(-EACCES);
}
/*
* See if the low-level filesystem might want
* to use its own hash..
*/
if (base->d_flags & DCACHE_OP_HASH) {
int err = base->d_op->d_hash(base, &this);
if (err < 0)
return ERR_PTR(err);
}
err = inode_permission(base->d_inode, MAY_EXEC);
if (err)
return ERR_PTR(err);
return __lookup_hash(&this, base, 0);
}
EXPORT_SYMBOL(lookup_one_len);
int user_path_at_empty(int dfd, const char __user *name, unsigned flags,
struct path *path, int *empty)
{
struct nameidata nd;
struct filename *tmp = getname_flags(name, flags, empty);
int err = PTR_ERR(tmp);
if (!IS_ERR(tmp)) {
BUG_ON(flags & LOOKUP_PARENT);
err = filename_lookup(dfd, tmp, flags, &nd);
putname(tmp);
if (!err)
*path = nd.path;
}
return err;
}
int user_path_at(int dfd, const char __user *name, unsigned flags,
struct path *path)
{
return user_path_at_empty(dfd, name, flags, path, NULL);
}
EXPORT_SYMBOL(user_path_at);
/*
* NB: most callers don't do anything directly with the reference to the
* to struct filename, but the nd->last pointer points into the name string
* allocated by getname. So we must hold the reference to it until all
* path-walking is complete.
*/
static struct filename *
user_path_parent(int dfd, const char __user *path, struct nameidata *nd,
unsigned int flags)
{
struct filename *s = getname(path);
int error;
/* only LOOKUP_REVAL is allowed in extra flags */
flags &= LOOKUP_REVAL;
if (IS_ERR(s))
return s;
error = filename_lookup(dfd, s, flags | LOOKUP_PARENT, nd);
if (error) {
putname(s);
return ERR_PTR(error);
}
return s;
}
/**
* mountpoint_last - look up last component for umount
* @nd: pathwalk nameidata - currently pointing at parent directory of "last"
* @path: pointer to container for result
*
* This is a special lookup_last function just for umount. In this case, we
* need to resolve the path without doing any revalidation.
*
* The nameidata should be the result of doing a LOOKUP_PARENT pathwalk. Since
* mountpoints are always pinned in the dcache, their ancestors are too. Thus,
* in almost all cases, this lookup will be served out of the dcache. The only
* cases where it won't are if nd->last refers to a symlink or the path is
* bogus and it doesn't exist.
*
* Returns:
* -error: if there was an error during lookup. This includes -ENOENT if the
* lookup found a negative dentry. The nd->path reference will also be
* put in this case.
*
* 0: if we successfully resolved nd->path and found it to not to be a
* symlink that needs to be followed. "path" will also be populated.
* The nd->path reference will also be put.
*
* 1: if we successfully resolved nd->last and found it to be a symlink
* that needs to be followed. "path" will be populated with the path
* to the link, and nd->path will *not* be put.
*/
static int
mountpoint_last(struct nameidata *nd, struct path *path)
{
int error = 0;
struct dentry *dentry;
struct dentry *dir = nd->path.dentry;
/* If we're in rcuwalk, drop out of it to handle last component */
if (nd->flags & LOOKUP_RCU) {
if (unlazy_walk(nd, NULL)) {
error = -ECHILD;
goto out;
}
}
nd->flags &= ~LOOKUP_PARENT;
if (unlikely(nd->last_type != LAST_NORM)) {
error = handle_dots(nd, nd->last_type);
if (error)
return error;
dentry = dget(nd->path.dentry);
goto done;
}
mutex_lock(&dir->d_inode->i_mutex);
dentry = d_lookup(dir, &nd->last);
if (!dentry) {
/*
* No cached dentry. Mounted dentries are pinned in the cache,
* so that means that this dentry is probably a symlink or the
* path doesn't actually point to a mounted dentry.
*/
dentry = d_alloc(dir, &nd->last);
if (!dentry) {
error = -ENOMEM;
mutex_unlock(&dir->d_inode->i_mutex);
goto out;
}
dentry = lookup_real(dir->d_inode, dentry, nd->flags);
error = PTR_ERR(dentry);
if (IS_ERR(dentry)) {
mutex_unlock(&dir->d_inode->i_mutex);
goto out;
}
}
mutex_unlock(&dir->d_inode->i_mutex);
done:
if (!dentry->d_inode || d_is_negative(dentry)) {
error = -ENOENT;
dput(dentry);
goto out;
}
path->dentry = dentry;
path->mnt = nd->path.mnt;
if (should_follow_link(dentry, nd->flags & LOOKUP_FOLLOW))
return 1;
mntget(path->mnt);
follow_mount(path);
error = 0;
out:
terminate_walk(nd);
return error;
}
/**
* path_mountpoint - look up a path to be umounted
* @dfd: directory file descriptor to start walk from
* @name: full pathname to walk
* @path: pointer to container for result
* @flags: lookup flags
*
* Look up the given name, but don't attempt to revalidate the last component.
* Returns 0 and "path" will be valid on success; Returns error otherwise.
*/
static int
path_mountpoint(int dfd, const char *name, struct path *path, unsigned int flags)
{
struct file *base = NULL;
struct nameidata nd;
int err;
err = path_init(dfd, name, flags | LOOKUP_PARENT, &nd, &base);
if (unlikely(err))
goto out;
current->total_link_count = 0;
err = link_path_walk(name, &nd);
if (err)
goto out;
err = mountpoint_last(&nd, path);
while (err > 0) {
void *cookie;
struct path link = *path;
err = may_follow_link(&link, &nd);
if (unlikely(err))
break;
nd.flags |= LOOKUP_PARENT;
err = follow_link(&link, &nd, &cookie);
if (err)
break;
err = mountpoint_last(&nd, path);
put_link(&nd, &link, cookie);
}
out:
if (base)
fput(base);
if (nd.root.mnt && !(nd.flags & LOOKUP_ROOT))
path_put(&nd.root);
return err;
}
static int
filename_mountpoint(int dfd, struct filename *s, struct path *path,
unsigned int flags)
{
int error = path_mountpoint(dfd, s->name, path, flags | LOOKUP_RCU);
if (unlikely(error == -ECHILD))
error = path_mountpoint(dfd, s->name, path, flags);
if (unlikely(error == -ESTALE))
error = path_mountpoint(dfd, s->name, path, flags | LOOKUP_REVAL);
if (likely(!error))
audit_inode(s, path->dentry, 0);
return error;
}
/**
* user_path_mountpoint_at - lookup a path from userland in order to umount it
* @dfd: directory file descriptor
* @name: pathname from userland
* @flags: lookup flags
* @path: pointer to container to hold result
*
* A umount is a special case for path walking. We're not actually interested
* in the inode in this situation, and ESTALE errors can be a problem. We
* simply want track down the dentry and vfsmount attached at the mountpoint
* and avoid revalidating the last component.
*
* Returns 0 and populates "path" on success.
*/
int
user_path_mountpoint_at(int dfd, const char __user *name, unsigned int flags,
struct path *path)
{
struct filename *s = getname(name);
int error;
if (IS_ERR(s))
return PTR_ERR(s);
error = filename_mountpoint(dfd, s, path, flags);
putname(s);
return error;
}
int
kern_path_mountpoint(int dfd, const char *name, struct path *path,
unsigned int flags)
{
struct filename s = {.name = name};
return filename_mountpoint(dfd, &s, path, flags);
}
EXPORT_SYMBOL(kern_path_mountpoint);
int __check_sticky(struct inode *dir, struct inode *inode)
{
kuid_t fsuid = current_fsuid();
if (uid_eq(inode->i_uid, fsuid))
return 0;
if (uid_eq(dir->i_uid, fsuid))
return 0;
return !capable_wrt_inode_uidgid(inode, CAP_FOWNER);
}
EXPORT_SYMBOL(__check_sticky);
/*
* Check whether we can remove a link victim from directory dir, check
* whether the type of victim is right.
* 1. We can't do it if dir is read-only (done in permission())
* 2. We should have write and exec permissions on dir
* 3. We can't remove anything from append-only dir
* 4. We can't do anything with immutable dir (done in permission())
* 5. If the sticky bit on dir is set we should either
* a. be owner of dir, or
* b. be owner of victim, or
* c. have CAP_FOWNER capability
* 6. If the victim is append-only or immutable we can't do antyhing with
* links pointing to it.
* 7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
* 8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
* 9. We can't remove a root or mountpoint.
* 10. We don't allow removal of NFS sillyrenamed files; it's handled by
* nfs_async_unlink().
*/
static int may_delete(struct inode *dir, struct dentry *victim, bool isdir)
{
struct inode *inode = victim->d_inode;
int error;
if (d_is_negative(victim))
return -ENOENT;
BUG_ON(!inode);
BUG_ON(victim->d_parent->d_inode != dir);
audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
if (error)
return error;
if (IS_APPEND(dir))
return -EPERM;
if (check_sticky(dir, inode) || IS_APPEND(inode) ||
IS_IMMUTABLE(inode) || IS_SWAPFILE(inode))
return -EPERM;
if (isdir) {
if (!d_is_dir(victim))
return -ENOTDIR;
if (IS_ROOT(victim))
return -EBUSY;
} else if (d_is_dir(victim))
return -EISDIR;
if (IS_DEADDIR(dir))
return -ENOENT;
if (victim->d_flags & DCACHE_NFSFS_RENAMED)
return -EBUSY;
return 0;
}
/* Check whether we can create an object with dentry child in directory
* dir.
* 1. We can't do it if child already exists (open has special treatment for
* this case, but since we are inlined it's OK)
* 2. We can't do it if dir is read-only (done in permission())
* 3. We should have write and exec permissions on dir
* 4. We can't do it if dir is immutable (done in permission())
*/
static inline int may_create(struct inode *dir, struct dentry *child)
{
audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE);
if (child->d_inode)
return -EEXIST;
if (IS_DEADDIR(dir))
return -ENOENT;
return inode_permission(dir, MAY_WRITE | MAY_EXEC);
}
/*
* p1 and p2 should be directories on the same fs.
*/
struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
{
struct dentry *p;
if (p1 == p2) {
mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
return NULL;
}
mutex_lock(&p1->d_inode->i_sb->s_vfs_rename_mutex);
p = d_ancestor(p2, p1);
if (p) {
mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_PARENT);
mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_CHILD);
return p;
}
p = d_ancestor(p1, p2);
if (p) {
mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD);
return p;
}
mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_PARENT2);
return NULL;
}
EXPORT_SYMBOL(lock_rename);
void unlock_rename(struct dentry *p1, struct dentry *p2)
{
mutex_unlock(&p1->d_inode->i_mutex);
if (p1 != p2) {
mutex_unlock(&p2->d_inode->i_mutex);
mutex_unlock(&p1->d_inode->i_sb->s_vfs_rename_mutex);
}
}
EXPORT_SYMBOL(unlock_rename);
int vfs_create(struct inode *dir, struct dentry *dentry, umode_t mode,
bool want_excl)
{
int error = may_create(dir, dentry);
if (error)
return error;
if (!dir->i_op->create)
return -EACCES; /* shouldn't it be ENOSYS? */
mode &= S_IALLUGO;
mode |= S_IFREG;
error = security_inode_create(dir, dentry, mode);
if (error)
return error;
error = dir->i_op->create(dir, dentry, mode, want_excl);
if (error)
return error;
error = security_inode_post_create(dir, dentry, mode);
if (error)
return error;
if (!error)
fsnotify_create(dir, dentry);
return error;
}
EXPORT_SYMBOL(vfs_create);
static int may_open(struct path *path, int acc_mode, int flag)
{
struct dentry *dentry = path->dentry;
struct inode *inode = dentry->d_inode;
int error;
/* O_PATH? */
if (!acc_mode)
return 0;
if (!inode)
return -ENOENT;
switch (inode->i_mode & S_IFMT) {
case S_IFLNK:
return -ELOOP;
case S_IFDIR:
if (acc_mode & MAY_WRITE)
return -EISDIR;
break;
case S_IFBLK:
case S_IFCHR:
if (path->mnt->mnt_flags & MNT_NODEV)
return -EACCES;
/*FALLTHRU*/
case S_IFIFO:
case S_IFSOCK:
flag &= ~O_TRUNC;
break;
}
error = inode_permission(inode, acc_mode);
if (error)
return error;
/*
* An append-only file must be opened in append mode for writing.
*/
if (IS_APPEND(inode)) {
if ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
return -EPERM;
if (flag & O_TRUNC)
return -EPERM;
}
/* O_NOATIME can only be set by the owner or superuser */
if (flag & O_NOATIME && !inode_owner_or_capable(inode))
return -EPERM;
return 0;
}
static int handle_truncate(struct file *filp)
{
struct path *path = &filp->f_path;
struct inode *inode = path->dentry->d_inode;
int error = get_write_access(inode);
if (error)
return error;
/*
* Refuse to truncate files with mandatory locks held on them.
*/
error = locks_verify_locked(filp);
if (!error)
error = security_path_truncate(path);
if (!error) {
error = do_truncate(path->dentry, 0,
ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
filp);
}
put_write_access(inode);
return error;
}
static inline int open_to_namei_flags(int flag)
{
if ((flag & O_ACCMODE) == 3)
flag--;
return flag;
}
static int may_o_create(struct path *dir, struct dentry *dentry, umode_t mode)
{
int error = security_path_mknod(dir, dentry, mode, 0);
if (error)
return error;
error = inode_permission(dir->dentry->d_inode, MAY_WRITE | MAY_EXEC);
if (error)
return error;
return security_inode_create(dir->dentry->d_inode, dentry, mode);
}
/*
* Attempt to atomically look up, create and open a file from a negative
* dentry.
*
* Returns 0 if successful. The file will have been created and attached to
* @file by the filesystem calling finish_open().
*
* Returns 1 if the file was looked up only or didn't need creating. The
* caller will need to perform the open themselves. @path will have been
* updated to point to the new dentry. This may be negative.
*
* Returns an error code otherwise.
*/
static int atomic_open(struct nameidata *nd, struct dentry *dentry,
struct path *path, struct file *file,
const struct open_flags *op,
bool got_write, bool need_lookup,
int *opened)
{
struct inode *dir = nd->path.dentry->d_inode;
unsigned open_flag = open_to_namei_flags(op->open_flag);
umode_t mode;
int error;
int acc_mode;
int create_error = 0;
struct dentry *const DENTRY_NOT_SET = (void *) -1UL;
bool excl;
BUG_ON(dentry->d_inode);
/* Don't create child dentry for a dead directory. */
if (unlikely(IS_DEADDIR(dir))) {
error = -ENOENT;
goto out;
}
mode = op->mode;
if ((open_flag & O_CREAT) && !IS_POSIXACL(dir))
mode &= ~current_umask();
excl = (open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT);
if (excl)
open_flag &= ~O_TRUNC;
/*
* Checking write permission is tricky, bacuse we don't know if we are
* going to actually need it: O_CREAT opens should work as long as the
* file exists. But checking existence breaks atomicity. The trick is
* to check access and if not granted clear O_CREAT from the flags.
*
* Another problem is returing the "right" error value (e.g. for an
* O_EXCL open we want to return EEXIST not EROFS).
*/
if (((open_flag & (O_CREAT | O_TRUNC)) ||
(open_flag & O_ACCMODE) != O_RDONLY) && unlikely(!got_write)) {
if (!(open_flag & O_CREAT)) {
/*
* No O_CREATE -> atomicity not a requirement -> fall
* back to lookup + open
*/
goto no_open;
} else if (open_flag & (O_EXCL | O_TRUNC)) {
/* Fall back and fail with the right error */
create_error = -EROFS;
goto no_open;
} else {
/* No side effects, safe to clear O_CREAT */
create_error = -EROFS;
open_flag &= ~O_CREAT;
}
}
if (open_flag & O_CREAT) {
error = may_o_create(&nd->path, dentry, mode);
if (error) {
create_error = error;
if (open_flag & O_EXCL)
goto no_open;
open_flag &= ~O_CREAT;
}
}
if (nd->flags & LOOKUP_DIRECTORY)
open_flag |= O_DIRECTORY;
file->f_path.dentry = DENTRY_NOT_SET;
file->f_path.mnt = nd->path.mnt;
error = dir->i_op->atomic_open(dir, dentry, file, open_flag, mode,
opened);
if (error < 0) {
if (create_error && error == -ENOENT)
error = create_error;
goto out;
}
if (error) { /* returned 1, that is */
if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) {
error = -EIO;
goto out;
}
if (file->f_path.dentry) {
dput(dentry);
dentry = file->f_path.dentry;
}
if (*opened & FILE_CREATED)
fsnotify_create(dir, dentry);
if (!dentry->d_inode) {
WARN_ON(*opened & FILE_CREATED);
if (create_error) {
error = create_error;
goto out;
}
} else {
if (excl && !(*opened & FILE_CREATED)) {
error = -EEXIST;
goto out;
}
}
goto looked_up;
}
/*
* We didn't have the inode before the open, so check open permission
* here.
*/
acc_mode = op->acc_mode;
if (*opened & FILE_CREATED) {
WARN_ON(!(open_flag & O_CREAT));
fsnotify_create(dir, dentry);
acc_mode = MAY_OPEN;
}
error = may_open(&file->f_path, acc_mode, open_flag);
if (error)
fput(file);
out:
dput(dentry);
return error;
no_open:
if (need_lookup) {
dentry = lookup_real(dir, dentry, nd->flags);
if (IS_ERR(dentry))
return PTR_ERR(dentry);
if (create_error) {
int open_flag = op->open_flag;
error = create_error;
if ((open_flag & O_EXCL)) {
if (!dentry->d_inode)
goto out;
} else if (!dentry->d_inode) {
goto out;
} else if ((open_flag & O_TRUNC) &&
S_ISREG(dentry->d_inode->i_mode)) {
goto out;
}
/* will fail later, go on to get the right error */
}
}
looked_up:
path->dentry = dentry;
path->mnt = nd->path.mnt;
return 1;
}
/*
* Look up and maybe create and open the last component.
*
* Must be called with i_mutex held on parent.
*
* Returns 0 if the file was successfully atomically created (if necessary) and
* opened. In this case the file will be returned attached to @file.
*
* Returns 1 if the file was not completely opened at this time, though lookups
* and creations will have been performed and the dentry returned in @path will
* be positive upon return if O_CREAT was specified. If O_CREAT wasn't
* specified then a negative dentry may be returned.
*
* An error code is returned otherwise.
*
* FILE_CREATE will be set in @*opened if the dentry was created and will be
* cleared otherwise prior to returning.
*/
static int lookup_open(struct nameidata *nd, struct path *path,
struct file *file,
const struct open_flags *op,
bool got_write, int *opened)
{
struct dentry *dir = nd->path.dentry;
struct inode *dir_inode = dir->d_inode;
struct dentry *dentry;
int error;
bool need_lookup;
*opened &= ~FILE_CREATED;
dentry = lookup_dcache(&nd->last, dir, nd->flags, &need_lookup);
if (IS_ERR(dentry))
return PTR_ERR(dentry);
/* Cached positive dentry: will open in f_op->open */
if (!need_lookup && dentry->d_inode)
goto out_no_open;
if ((nd->flags & LOOKUP_OPEN) && dir_inode->i_op->atomic_open) {
return atomic_open(nd, dentry, path, file, op, got_write,
need_lookup, opened);
}
if (need_lookup) {
BUG_ON(dentry->d_inode);
dentry = lookup_real(dir_inode, dentry, nd->flags);
if (IS_ERR(dentry))
return PTR_ERR(dentry);
}
/* Negative dentry, just create the file */
if (!dentry->d_inode && (op->open_flag & O_CREAT)) {
umode_t mode = op->mode;
if (!IS_POSIXACL(dir->d_inode))
mode &= ~current_umask();
/*
* This write is needed to ensure that a
* rw->ro transition does not occur between
* the time when the file is created and when
* a permanent write count is taken through
* the 'struct file' in finish_open().
*/
if (!got_write) {
error = -EROFS;
goto out_dput;
}
*opened |= FILE_CREATED;
error = security_path_mknod(&nd->path, dentry, mode, 0);
if (error)
goto out_dput;
error = vfs_create(dir->d_inode, dentry, mode,
nd->flags & LOOKUP_EXCL);
if (error)
goto out_dput;
}
out_no_open:
path->dentry = dentry;
path->mnt = nd->path.mnt;
return 1;
out_dput:
dput(dentry);
return error;
}
/*
* Handle the last step of open()
*/
static int do_last(struct nameidata *nd, struct path *path,
struct file *file, const struct open_flags *op,
int *opened, struct filename *name)
{
struct dentry *dir = nd->path.dentry;
int open_flag = op->open_flag;
bool will_truncate = (open_flag & O_TRUNC) != 0;
bool got_write = false;
int acc_mode = op->acc_mode;
struct inode *inode;
bool symlink_ok = false;
struct path save_parent = { .dentry = NULL, .mnt = NULL };
bool retried = false;
int error;
nd->flags &= ~LOOKUP_PARENT;
nd->flags |= op->intent;
if (nd->last_type != LAST_NORM) {
error = handle_dots(nd, nd->last_type);
if (error)
return error;
goto finish_open;
}
if (!(open_flag & O_CREAT)) {
if (nd->last.name[nd->last.len])
nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
if (open_flag & O_PATH && !(nd->flags & LOOKUP_FOLLOW))
symlink_ok = true;
/* we _can_ be in RCU mode here */
error = lookup_fast(nd, path, &inode);
if (likely(!error))
goto finish_lookup;
if (error < 0)
goto out;
BUG_ON(nd->inode != dir->d_inode);
} else {
/* create side of things */
/*
* This will *only* deal with leaving RCU mode - LOOKUP_JUMPED
* has been cleared when we got to the last component we are
* about to look up
*/
error = complete_walk(nd);
if (error)
return error;
audit_inode(name, dir, LOOKUP_PARENT);
error = -EISDIR;
/* trailing slashes? */
if (nd->last.name[nd->last.len])
goto out;
}
retry_lookup:
if (op->open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) {
error = mnt_want_write(nd->path.mnt);
if (!error)
got_write = true;
/*
* do _not_ fail yet - we might not need that or fail with
* a different error; let lookup_open() decide; we'll be
* dropping this one anyway.
*/
}
mutex_lock(&dir->d_inode->i_mutex);
error = lookup_open(nd, path, file, op, got_write, opened);
mutex_unlock(&dir->d_inode->i_mutex);
if (error <= 0) {
if (error)
goto out;
if ((*opened & FILE_CREATED) ||
!S_ISREG(file_inode(file)->i_mode))
will_truncate = false;
audit_inode(name, file->f_path.dentry, 0);
goto opened;
}
if (*opened & FILE_CREATED) {
/* Don't check for write permission, don't truncate */
open_flag &= ~O_TRUNC;
will_truncate = false;
acc_mode = MAY_OPEN;
path_to_nameidata(path, nd);
goto finish_open_created;
}
/*
* create/update audit record if it already exists.
*/
if (d_is_positive(path->dentry))
audit_inode(name, path->dentry, 0);
/*
* If atomic_open() acquired write access it is dropped now due to
* possible mount and symlink following (this might be optimized away if
* necessary...)
*/
if (got_write) {
mnt_drop_write(nd->path.mnt);
got_write = false;
}
error = -EEXIST;
if ((open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT))
goto exit_dput;
error = follow_managed(path, nd->flags);
if (error < 0)
goto exit_dput;
if (error)
nd->flags |= LOOKUP_JUMPED;
BUG_ON(nd->flags & LOOKUP_RCU);
inode = path->dentry->d_inode;
finish_lookup:
/* we _can_ be in RCU mode here */
error = -ENOENT;
if (!inode || d_is_negative(path->dentry)) {
path_to_nameidata(path, nd);
goto out;
}
if (should_follow_link(path->dentry, !symlink_ok)) {
if (nd->flags & LOOKUP_RCU) {
if (unlikely(nd->path.mnt != path->mnt ||
unlazy_walk(nd, path->dentry))) {
error = -ECHILD;
goto out;
}
}
BUG_ON(inode != path->dentry->d_inode);
return 1;
}
if ((nd->flags & LOOKUP_RCU) || nd->path.mnt != path->mnt) {
path_to_nameidata(path, nd);
} else {
save_parent.dentry = nd->path.dentry;
save_parent.mnt = mntget(path->mnt);
nd->path.dentry = path->dentry;
}
nd->inode = inode;
/* Why this, you ask? _Now_ we might have grown LOOKUP_JUMPED... */
finish_open:
error = complete_walk(nd);
if (error) {
path_put(&save_parent);
return error;
}
audit_inode(name, nd->path.dentry, 0);
error = -EISDIR;
if ((open_flag & O_CREAT) && d_is_dir(nd->path.dentry))
goto out;
error = -ENOTDIR;
if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry))
goto out;
if (!S_ISREG(nd->inode->i_mode))
will_truncate = false;
if (will_truncate) {
error = mnt_want_write(nd->path.mnt);
if (error)
goto out;
got_write = true;
}
finish_open_created:
error = may_open(&nd->path, acc_mode, open_flag);
if (error)
goto out;
BUG_ON(*opened & FILE_OPENED); /* once it's opened, it's opened */
error = vfs_open(&nd->path, file, current_cred());
if (!error) {
*opened |= FILE_OPENED;
} else {
if (error == -EOPENSTALE)
goto stale_open;
goto out;
}
opened:
error = open_check_o_direct(file);
if (error)
goto exit_fput;
error = ima_file_check(file, op->acc_mode, *opened);
if (error)
goto exit_fput;
if (will_truncate) {
error = handle_truncate(file);
if (error)
goto exit_fput;
}
out:
if (unlikely(error > 0)) {
WARN_ON(1);
error = -EINVAL;
}
if (got_write)
mnt_drop_write(nd->path.mnt);
path_put(&save_parent);
terminate_walk(nd);
return error;
exit_dput:
path_put_conditional(path, nd);
goto out;
exit_fput:
fput(file);
goto out;
stale_open:
/* If no saved parent or already retried then can't retry */
if (!save_parent.dentry || retried)
goto out;
BUG_ON(save_parent.dentry != dir);
path_put(&nd->path);
nd->path = save_parent;
nd->inode = dir->d_inode;
save_parent.mnt = NULL;
save_parent.dentry = NULL;
if (got_write) {
mnt_drop_write(nd->path.mnt);
got_write = false;
}
retried = true;
goto retry_lookup;
}
static int do_tmpfile(int dfd, struct filename *pathname,
struct nameidata *nd, int flags,
const struct open_flags *op,
struct file *file, int *opened)
{
static const struct qstr name = QSTR_INIT("/", 1);
struct dentry *dentry, *child;
struct inode *dir;
int error = path_lookupat(dfd, pathname->name,
flags | LOOKUP_DIRECTORY, nd);
if (unlikely(error))
return error;
error = mnt_want_write(nd->path.mnt);
if (unlikely(error))
goto out;
/* we want directory to be writable */
error = inode_permission(nd->inode, MAY_WRITE | MAY_EXEC);
if (error)
goto out2;
dentry = nd->path.dentry;
dir = dentry->d_inode;
if (!dir->i_op->tmpfile) {
error = -EOPNOTSUPP;
goto out2;
}
child = d_alloc(dentry, &name);
if (unlikely(!child)) {
error = -ENOMEM;
goto out2;
}
nd->flags &= ~LOOKUP_DIRECTORY;
nd->flags |= op->intent;
dput(nd->path.dentry);
nd->path.dentry = child;
error = dir->i_op->tmpfile(dir, nd->path.dentry, op->mode);
if (error)
goto out2;
audit_inode(pathname, nd->path.dentry, 0);
/* Don't check for other permissions, the inode was just created */
error = may_open(&nd->path, MAY_OPEN, op->open_flag);
if (error)
goto out2;
file->f_path.mnt = nd->path.mnt;
error = finish_open(file, nd->path.dentry, NULL, opened);
if (error)
goto out2;
error = open_check_o_direct(file);
if (error) {
fput(file);
} else if (!(op->open_flag & O_EXCL)) {
struct inode *inode = file_inode(file);
spin_lock(&inode->i_lock);
inode->i_state |= I_LINKABLE;
spin_unlock(&inode->i_lock);
}
out2:
mnt_drop_write(nd->path.mnt);
out:
path_put(&nd->path);
return error;
}
static struct file *path_openat(int dfd, struct filename *pathname,
struct nameidata *nd, const struct open_flags *op, int flags)
{
struct file *base = NULL;
struct file *file;
struct path path;
int opened = 0;
int error;
file = get_empty_filp();
if (IS_ERR(file))
return file;
file->f_flags = op->open_flag;
if (unlikely(file->f_flags & __O_TMPFILE)) {
error = do_tmpfile(dfd, pathname, nd, flags, op, file, &opened);
goto out2;
}
error = path_init(dfd, pathname->name, flags | LOOKUP_PARENT, nd, &base);
if (unlikely(error))
goto out;
current->total_link_count = 0;
error = link_path_walk(pathname->name, nd);
if (unlikely(error))
goto out;
error = do_last(nd, &path, file, op, &opened, pathname);
while (unlikely(error > 0)) { /* trailing symlink */
struct path link = path;
void *cookie;
if (!(nd->flags & LOOKUP_FOLLOW)) {
path_put_conditional(&path, nd);
path_put(&nd->path);
error = -ELOOP;
break;
}
error = may_follow_link(&link, nd);
if (unlikely(error))
break;
nd->flags |= LOOKUP_PARENT;
nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
error = follow_link(&link, nd, &cookie);
if (unlikely(error))
break;
error = do_last(nd, &path, file, op, &opened, pathname);
put_link(nd, &link, cookie);
}
out:
if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT))
path_put(&nd->root);
if (base)
fput(base);
out2:
if (!(opened & FILE_OPENED)) {
BUG_ON(!error);
put_filp(file);
}
if (unlikely(error)) {
if (error == -EOPENSTALE) {
if (flags & LOOKUP_RCU)
error = -ECHILD;
else
error = -ESTALE;
}
file = ERR_PTR(error);
} else {
global_filetable_add(file);
}
return file;
}
struct file *do_filp_open(int dfd, struct filename *pathname,
const struct open_flags *op)
{
struct nameidata nd;
int flags = op->lookup_flags;
struct file *filp;
filp = path_openat(dfd, pathname, &nd, op, flags | LOOKUP_RCU);
if (unlikely(filp == ERR_PTR(-ECHILD)))
filp = path_openat(dfd, pathname, &nd, op, flags);
if (unlikely(filp == ERR_PTR(-ESTALE)))
filp = path_openat(dfd, pathname, &nd, op, flags | LOOKUP_REVAL);
return filp;
}
struct file *do_file_open_root(struct dentry *dentry, struct vfsmount *mnt,
const char *name, const struct open_flags *op)
{
struct nameidata nd;
struct file *file;
struct filename filename = { .name = name };
int flags = op->lookup_flags | LOOKUP_ROOT;
nd.root.mnt = mnt;
nd.root.dentry = dentry;
if (d_is_symlink(dentry) && op->intent & LOOKUP_OPEN)
return ERR_PTR(-ELOOP);
file = path_openat(-1, &filename, &nd, op, flags | LOOKUP_RCU);
if (unlikely(file == ERR_PTR(-ECHILD)))
file = path_openat(-1, &filename, &nd, op, flags);
if (unlikely(file == ERR_PTR(-ESTALE)))
file = path_openat(-1, &filename, &nd, op, flags | LOOKUP_REVAL);
return file;
}
struct dentry *kern_path_create(int dfd, const char *pathname,
struct path *path, unsigned int lookup_flags)
{
struct dentry *dentry = ERR_PTR(-EEXIST);
struct nameidata nd;
int err2;
int error;
bool is_dir = (lookup_flags & LOOKUP_DIRECTORY);
/*
* Note that only LOOKUP_REVAL and LOOKUP_DIRECTORY matter here. Any
* other flags passed in are ignored!
*/
lookup_flags &= LOOKUP_REVAL;
error = do_path_lookup(dfd, pathname, LOOKUP_PARENT|lookup_flags, &nd);
if (error)
return ERR_PTR(error);
/*
* Yucky last component or no last component at all?
* (foo/., foo/.., /////)
*/
if (nd.last_type != LAST_NORM)
goto out;
nd.flags &= ~LOOKUP_PARENT;
nd.flags |= LOOKUP_CREATE | LOOKUP_EXCL;
/* don't fail immediately if it's r/o, at least try to report other errors */
err2 = mnt_want_write(nd.path.mnt);
/*
* Do the final lookup.
*/
mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
dentry = lookup_hash(&nd);
if (IS_ERR(dentry))
goto unlock;
error = -EEXIST;
if (d_is_positive(dentry))
goto fail;
/*
* Special case - lookup gave negative, but... we had foo/bar/
* From the vfs_mknod() POV we just have a negative dentry -
* all is fine. Let's be bastards - you had / on the end, you've
* been asking for (non-existent) directory. -ENOENT for you.
*/
if (unlikely(!is_dir && nd.last.name[nd.last.len])) {
error = -ENOENT;
goto fail;
}
if (unlikely(err2)) {
error = err2;
goto fail;
}
*path = nd.path;
return dentry;
fail:
dput(dentry);
dentry = ERR_PTR(error);
unlock:
mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
if (!err2)
mnt_drop_write(nd.path.mnt);
out:
path_put(&nd.path);
return dentry;
}
EXPORT_SYMBOL(kern_path_create);
void done_path_create(struct path *path, struct dentry *dentry)
{
dput(dentry);
mutex_unlock(&path->dentry->d_inode->i_mutex);
mnt_drop_write(path->mnt);
path_put(path);
}
EXPORT_SYMBOL(done_path_create);
struct dentry *user_path_create(int dfd, const char __user *pathname,
struct path *path, unsigned int lookup_flags)
{
struct filename *tmp = getname(pathname);
struct dentry *res;
if (IS_ERR(tmp))
return ERR_CAST(tmp);
res = kern_path_create(dfd, tmp->name, path, lookup_flags);
putname(tmp);
return res;
}
EXPORT_SYMBOL(user_path_create);
int vfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
{
int error = may_create(dir, dentry);
if (error)
return error;
if ((S_ISCHR(mode) || S_ISBLK(mode)) && !capable(CAP_MKNOD))
return -EPERM;
if (!dir->i_op->mknod)
return -EPERM;
error = devcgroup_inode_mknod(mode, dev);
if (error)
return error;
error = security_inode_mknod(dir, dentry, mode, dev);
if (error)
return error;
error = dir->i_op->mknod(dir, dentry, mode, dev);
if (error)
return error;
error = security_inode_post_create(dir, dentry, mode);
if (error)
return error;
if (!error)
fsnotify_create(dir, dentry);
return error;
}
EXPORT_SYMBOL(vfs_mknod);
static int may_mknod(umode_t mode)
{
switch (mode & S_IFMT) {
case S_IFREG:
case S_IFCHR:
case S_IFBLK:
case S_IFIFO:
case S_IFSOCK:
case 0: /* zero mode translates to S_IFREG */
return 0;
case S_IFDIR:
return -EPERM;
default:
return -EINVAL;
}
}
SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode,
unsigned, dev)
{
struct dentry *dentry;
struct path path;
int error;
unsigned int lookup_flags = 0;
error = may_mknod(mode);
if (error)
return error;
retry:
dentry = user_path_create(dfd, filename, &path, lookup_flags);
if (IS_ERR(dentry))
return PTR_ERR(dentry);
if (!IS_POSIXACL(path.dentry->d_inode))
mode &= ~current_umask();
error = security_path_mknod(&path, dentry, mode, dev);
if (error)
goto out;
switch (mode & S_IFMT) {
case 0: case S_IFREG:
error = vfs_create(path.dentry->d_inode,dentry,mode,true);
break;
case S_IFCHR: case S_IFBLK:
error = vfs_mknod(path.dentry->d_inode,dentry,mode,
new_decode_dev(dev));
break;
case S_IFIFO: case S_IFSOCK:
error = vfs_mknod(path.dentry->d_inode,dentry,mode,0);
break;
}
out:
done_path_create(&path, dentry);
if (retry_estale(error, lookup_flags)) {
lookup_flags |= LOOKUP_REVAL;
goto retry;
}
return error;
}
SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
{
return sys_mknodat(AT_FDCWD, filename, mode, dev);
}
int vfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
{
int error = may_create(dir, dentry);
unsigned max_links = dir->i_sb->s_max_links;
if (error)
return error;
if (!dir->i_op->mkdir)
return -EPERM;
mode &= (S_IRWXUGO|S_ISVTX);
error = security_inode_mkdir(dir, dentry, mode);
if (error)
return error;
if (max_links && dir->i_nlink >= max_links)
return -EMLINK;
error = dir->i_op->mkdir(dir, dentry, mode);
if (!error)
fsnotify_mkdir(dir, dentry);
return error;
}
EXPORT_SYMBOL(vfs_mkdir);
SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode)
{
struct dentry *dentry;
struct path path;
int error;
unsigned int lookup_flags = LOOKUP_DIRECTORY;
retry:
dentry = user_path_create(dfd, pathname, &path, lookup_flags);
if (IS_ERR(dentry))
return PTR_ERR(dentry);
if (!IS_POSIXACL(path.dentry->d_inode))
mode &= ~current_umask();
error = security_path_mkdir(&path, dentry, mode);
if (!error)
error = vfs_mkdir(path.dentry->d_inode, dentry, mode);
done_path_create(&path, dentry);
if (retry_estale(error, lookup_flags)) {
lookup_flags |= LOOKUP_REVAL;
goto retry;
}
return error;
}
SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode)
{
return sys_mkdirat(AT_FDCWD, pathname, mode);
}
/*
* The dentry_unhash() helper will try to drop the dentry early: we
* should have a usage count of 1 if we're the only user of this
* dentry, and if that is true (possibly after pruning the dcache),
* then we drop the dentry now.
*
* A low-level filesystem can, if it choses, legally
* do a
*
* if (!d_unhashed(dentry))
* return -EBUSY;
*
* if it cannot handle the case of removing a directory
* that is still in use by something else..
*/
void dentry_unhash(struct dentry *dentry)
{
shrink_dcache_parent(dentry);
spin_lock(&dentry->d_lock);
if (dentry->d_lockref.count == 1)
__d_drop(dentry);
spin_unlock(&dentry->d_lock);
}
EXPORT_SYMBOL(dentry_unhash);
int vfs_rmdir(struct inode *dir, struct dentry *dentry)
{
int error = may_delete(dir, dentry, 1);
if (error)
return error;
if (!dir->i_op->rmdir)
return -EPERM;
dget(dentry);
mutex_lock(&dentry->d_inode->i_mutex);
error = -EBUSY;
if (is_local_mountpoint(dentry))
goto out;
error = security_inode_rmdir(dir, dentry);
if (error)
goto out;
shrink_dcache_parent(dentry);
error = dir->i_op->rmdir(dir, dentry);
if (error)
goto out;
dentry->d_inode->i_flags |= S_DEAD;
dont_mount(dentry);
detach_mounts(dentry);
out:
mutex_unlock(&dentry->d_inode->i_mutex);
dput(dentry);
if (!error)
d_delete(dentry);
return error;
}
EXPORT_SYMBOL(vfs_rmdir);
static long do_rmdir(int dfd, const char __user *pathname)
{
int error = 0;
struct filename *name;
struct dentry *dentry;
struct nameidata nd;
unsigned int lookup_flags = 0;
retry:
name = user_path_parent(dfd, pathname, &nd, lookup_flags);
if (IS_ERR(name))
return PTR_ERR(name);
switch(nd.last_type) {
case LAST_DOTDOT:
error = -ENOTEMPTY;
goto exit1;
case LAST_DOT:
error = -EINVAL;
goto exit1;
case LAST_ROOT:
error = -EBUSY;
goto exit1;
}
nd.flags &= ~LOOKUP_PARENT;
error = mnt_want_write(nd.path.mnt);
if (error)
goto exit1;
mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
dentry = lookup_hash(&nd);
error = PTR_ERR(dentry);
if (IS_ERR(dentry))
goto exit2;
if (!dentry->d_inode) {
error = -ENOENT;
goto exit3;
}
error = security_path_rmdir(&nd.path, dentry);
if (error)
goto exit3;
error = vfs_rmdir(nd.path.dentry->d_inode, dentry);
exit3:
dput(dentry);
exit2:
mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
mnt_drop_write(nd.path.mnt);
exit1:
path_put(&nd.path);
putname(name);
if (retry_estale(error, lookup_flags)) {
lookup_flags |= LOOKUP_REVAL;
goto retry;
}
return error;
}
SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
{
return do_rmdir(AT_FDCWD, pathname);
}
/**
* vfs_unlink - unlink a filesystem object
* @dir: parent directory
* @dentry: victim
* @delegated_inode: returns victim inode, if the inode is delegated.
*
* The caller must hold dir->i_mutex.
*
* If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
* return a reference to the inode in delegated_inode. The caller
* should then break the delegation on that inode and retry. Because
* breaking a delegation may take a long time, the caller should drop
* dir->i_mutex before doing so.
*
* Alternatively, a caller may pass NULL for delegated_inode. This may
* be appropriate for callers that expect the underlying filesystem not
* to be NFS exported.
*/
int vfs_unlink(struct inode *dir, struct dentry *dentry, struct inode **delegated_inode)
{
struct inode *target = dentry->d_inode;
int error = may_delete(dir, dentry, 0);
if (error)
return error;
if (!dir->i_op->unlink)
return -EPERM;
mutex_lock(&target->i_mutex);
if (is_local_mountpoint(dentry))
error = -EBUSY;
else {
error = security_inode_unlink(dir, dentry);
if (!error) {
error = try_break_deleg(target, delegated_inode);
if (error)
goto out;
error = dir->i_op->unlink(dir, dentry);
if (!error) {
dont_mount(dentry);
detach_mounts(dentry);
}
}
}
out:
mutex_unlock(&target->i_mutex);
/* We don't d_delete() NFS sillyrenamed files--they still exist. */
if (!error && !(dentry->d_flags & DCACHE_NFSFS_RENAMED)) {
fsnotify_link_count(target);
d_delete(dentry);
}
return error;
}
EXPORT_SYMBOL(vfs_unlink);
/*
* Make sure that the actual truncation of the file will occur outside its
* directory's i_mutex. Truncate can take a long time if there is a lot of
* writeout happening, and we don't want to prevent access to the directory
* while waiting on the I/O.
*/
#ifdef CONFIG_SDCARD_FS
long do_unlinkat(int dfd, const char __user *pathname, bool propagate)
#else
static long do_unlinkat(int dfd, const char __user *pathname)
#endif
{
int error;
struct filename *name;
struct dentry *dentry;
struct nameidata nd;
struct inode *inode = NULL;
struct inode *delegated_inode = NULL;
unsigned int lookup_flags = 0;
#ifdef CONFIG_SDCARD_FS
/* temp code to avoid issue */
char *path_buf = NULL;
char *propagate_path = NULL;
#endif
retry:
name = user_path_parent(dfd, pathname, &nd, lookup_flags);
if (IS_ERR(name))
return PTR_ERR(name);
error = -EISDIR;
if (nd.last_type != LAST_NORM)
goto exit1;
nd.flags &= ~LOOKUP_PARENT;
error = mnt_want_write(nd.path.mnt);
if (error)
goto exit1;
retry_deleg:
mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
dentry = lookup_hash(&nd);
error = PTR_ERR(dentry);
if (!IS_ERR(dentry)) {
/* Why not before? Because we want correct error value */
if (nd.last.name[nd.last.len])
goto slashes;
inode = dentry->d_inode;
if (d_is_negative(dentry))
goto slashes;
#ifdef CONFIG_SDCARD_FS
/* temp code to avoid issue */
if (inode->i_sb->s_op->unlink_callback && propagate) {
struct inode *lower_inode = inode;
while (lower_inode->i_op->get_lower_inode) {
if (inode->i_sb->s_magic == SDCARDFS_SUPER_MAGIC
&& SDCARDFS_SB(inode->i_sb)->options.label) {
path_buf = kmalloc(PATH_MAX, GFP_KERNEL);
propagate_path = dentry_path_raw(dentry, path_buf, PATH_MAX);
}
lower_inode = lower_inode->i_op->get_lower_inode(lower_inode);
}
}
#endif
ihold(inode);
error = security_path_unlink(&nd.path, dentry);
if (error)
goto exit2;
error = vfs_unlink(nd.path.dentry->d_inode, dentry, &delegated_inode);
exit2:
dput(dentry);
}
mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
#ifdef CONFIG_SDCARD_FS
/* temp code to avoid issue */
if (path_buf && !IS_ERR(path_buf) && !error && propagate) {
inode->i_sb->s_op->unlink_callback(inode, propagate_path);
kfree(path_buf);
}
#endif
if (inode)
iput(inode); /* truncate the inode here */
inode = NULL;
if (delegated_inode) {
error = break_deleg_wait(&delegated_inode);
if (!error)
goto retry_deleg;
}
mnt_drop_write(nd.path.mnt);
exit1:
path_put(&nd.path);
putname(name);
if (retry_estale(error, lookup_flags)) {
lookup_flags |= LOOKUP_REVAL;
inode = NULL;
goto retry;
}
return error;
slashes:
if (d_is_negative(dentry))
error = -ENOENT;
else if (d_is_dir(dentry))
error = -EISDIR;
else
error = -ENOTDIR;
goto exit2;
}
SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
{
if ((flag & ~AT_REMOVEDIR) != 0)
return -EINVAL;
if (flag & AT_REMOVEDIR)
return do_rmdir(dfd, pathname);
#ifdef CONFIG_SDCARD_FS
return do_unlinkat(dfd, pathname, true);
#else
return do_unlinkat(dfd, pathname);
#endif
}
SYSCALL_DEFINE1(unlink, const char __user *, pathname)
{
#ifdef CONFIG_SDCARD_FS
return do_unlinkat(AT_FDCWD, pathname, true);
#else
return do_unlinkat(AT_FDCWD, pathname);
#endif
}
int vfs_symlink(struct inode *dir, struct dentry *dentry, const char *oldname)
{
int error = may_create(dir, dentry);
if (error)
return error;
if (!dir->i_op->symlink)
return -EPERM;
error = security_inode_symlink(dir, dentry, oldname);
if (error)
return error;
error = dir->i_op->symlink(dir, dentry, oldname);
if (!error)
fsnotify_create(dir, dentry);
return error;
}
EXPORT_SYMBOL(vfs_symlink);
SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
int, newdfd, const char __user *, newname)
{
int error;
struct filename *from;
struct dentry *dentry;
struct path path;
unsigned int lookup_flags = 0;
from = getname(oldname);
if (IS_ERR(from))
return PTR_ERR(from);
retry:
dentry = user_path_create(newdfd, newname, &path, lookup_flags);
error = PTR_ERR(dentry);
if (IS_ERR(dentry))
goto out_putname;
error = security_path_symlink(&path, dentry, from->name);
if (!error)
error = vfs_symlink(path.dentry->d_inode, dentry, from->name);
done_path_create(&path, dentry);
if (retry_estale(error, lookup_flags)) {
lookup_flags |= LOOKUP_REVAL;
goto retry;
}
out_putname:
putname(from);
return error;
}
SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
{
return sys_symlinkat(oldname, AT_FDCWD, newname);
}
/**
* vfs_link - create a new link
* @old_dentry: object to be linked
* @dir: new parent
* @new_dentry: where to create the new link
* @delegated_inode: returns inode needing a delegation break
*
* The caller must hold dir->i_mutex
*
* If vfs_link discovers a delegation on the to-be-linked file in need
* of breaking, it will return -EWOULDBLOCK and return a reference to the
* inode in delegated_inode. The caller should then break the delegation
* and retry. Because breaking a delegation may take a long time, the
* caller should drop the i_mutex before doing so.
*
* Alternatively, a caller may pass NULL for delegated_inode. This may
* be appropriate for callers that expect the underlying filesystem not
* to be NFS exported.
*/
int vfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry, struct inode **delegated_inode)
{
struct inode *inode = old_dentry->d_inode;
unsigned max_links = dir->i_sb->s_max_links;
int error;
if (!inode)
return -ENOENT;
error = may_create(dir, new_dentry);
if (error)
return error;
if (dir->i_sb != inode->i_sb)
return -EXDEV;
/*
* A link to an append-only or immutable file cannot be created.
*/
if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
return -EPERM;
if (!dir->i_op->link)
return -EPERM;
if (S_ISDIR(inode->i_mode))
return -EPERM;
error = security_inode_link(old_dentry, dir, new_dentry);
if (error)
return error;
mutex_lock(&inode->i_mutex);
/* Make sure we don't allow creating hardlink to an unlinked file */
if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE))
error = -ENOENT;
else if (max_links && inode->i_nlink >= max_links)
error = -EMLINK;
else {
error = try_break_deleg(inode, delegated_inode);
if (!error)
error = dir->i_op->link(old_dentry, dir, new_dentry);
}
if (!error && (inode->i_state & I_LINKABLE)) {
spin_lock(&inode->i_lock);
inode->i_state &= ~I_LINKABLE;
spin_unlock(&inode->i_lock);
}
mutex_unlock(&inode->i_mutex);
if (!error)
fsnotify_link(dir, inode, new_dentry);
return error;
}
EXPORT_SYMBOL(vfs_link);
/*
* Hardlinks are often used in delicate situations. We avoid
* security-related surprises by not following symlinks on the
* newname. --KAB
*
* We don't follow them on the oldname either to be compatible
* with linux 2.0, and to avoid hard-linking to directories
* and other special files. --ADM
*/
SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
int, newdfd, const char __user *, newname, int, flags)
{
struct dentry *new_dentry;
struct path old_path, new_path;
struct inode *delegated_inode = NULL;
int how = 0;
int error;
if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0)
return -EINVAL;
/*
* To use null names we require CAP_DAC_READ_SEARCH
* This ensures that not everyone will be able to create
* handlink using the passed filedescriptor.
*/
if (flags & AT_EMPTY_PATH) {
if (!capable(CAP_DAC_READ_SEARCH))
return -ENOENT;
how = LOOKUP_EMPTY;
}
if (flags & AT_SYMLINK_FOLLOW)
how |= LOOKUP_FOLLOW;
retry:
error = user_path_at(olddfd, oldname, how, &old_path);
if (error)
return error;
new_dentry = user_path_create(newdfd, newname, &new_path,
(how & LOOKUP_REVAL));
error = PTR_ERR(new_dentry);
if (IS_ERR(new_dentry))
goto out;
error = -EXDEV;
if (old_path.mnt != new_path.mnt)
goto out_dput;
error = may_linkat(&old_path);
if (unlikely(error))
goto out_dput;
error = security_path_link(old_path.dentry, &new_path, new_dentry);
if (error)
goto out_dput;
error = vfs_link(old_path.dentry, new_path.dentry->d_inode, new_dentry, &delegated_inode);
out_dput:
done_path_create(&new_path, new_dentry);
if (delegated_inode) {
error = break_deleg_wait(&delegated_inode);
if (!error) {
path_put(&old_path);
goto retry;
}
}
if (retry_estale(error, how)) {
path_put(&old_path);
how |= LOOKUP_REVAL;
goto retry;
}
out:
path_put(&old_path);
return error;
}
SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
{
return sys_linkat(AT_FDCWD, oldname, AT_FDCWD, newname, 0);
}
/**
* vfs_rename - rename a filesystem object
* @old_dir: parent of source
* @old_dentry: source
* @new_dir: parent of destination
* @new_dentry: destination
* @delegated_inode: returns an inode needing a delegation break
* @flags: rename flags
*
* The caller must hold multiple mutexes--see lock_rename()).
*
* If vfs_rename discovers a delegation in need of breaking at either
* the source or destination, it will return -EWOULDBLOCK and return a
* reference to the inode in delegated_inode. The caller should then
* break the delegation and retry. Because breaking a delegation may
* take a long time, the caller should drop all locks before doing
* so.
*
* Alternatively, a caller may pass NULL for delegated_inode. This may
* be appropriate for callers that expect the underlying filesystem not
* to be NFS exported.
*
* The worst of all namespace operations - renaming directory. "Perverted"
* doesn't even start to describe it. Somebody in UCB had a heck of a trip...
* Problems:
* a) we can get into loop creation.
* b) race potential - two innocent renames can create a loop together.
* That's where 4.4 screws up. Current fix: serialization on
* sb->s_vfs_rename_mutex. We might be more accurate, but that's another
* story.
* c) we have to lock _four_ objects - parents and victim (if it exists),
* and source (if it is not a directory).
* And that - after we got ->i_mutex on parents (until then we don't know
* whether the target exists). Solution: try to be smart with locking
* order for inodes. We rely on the fact that tree topology may change
* only under ->s_vfs_rename_mutex _and_ that parent of the object we
* move will be locked. Thus we can rank directories by the tree
* (ancestors first) and rank all non-directories after them.
* That works since everybody except rename does "lock parent, lookup,
* lock child" and rename is under ->s_vfs_rename_mutex.
* HOWEVER, it relies on the assumption that any object with ->lookup()
* has no more than 1 dentry. If "hybrid" objects will ever appear,
* we'd better make sure that there's no link(2) for them.
* d) conversion from fhandle to dentry may come in the wrong moment - when
* we are removing the target. Solution: we will have to grab ->i_mutex
* in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
* ->i_mutex on parents, which works but leads to some truly excessive
* locking].
*/
int vfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry,
struct inode **delegated_inode, unsigned int flags)
{
int error;
bool is_dir = d_is_dir(old_dentry);
const unsigned char *old_name;
struct inode *source = old_dentry->d_inode;
struct inode *target = new_dentry->d_inode;
bool new_is_dir = false;
unsigned max_links = new_dir->i_sb->s_max_links;
if (source == target)
return 0;
error = may_delete(old_dir, old_dentry, is_dir);
if (error)
return error;
if (!target) {
error = may_create(new_dir, new_dentry);
} else {
new_is_dir = d_is_dir(new_dentry);
if (!(flags & RENAME_EXCHANGE))
error = may_delete(new_dir, new_dentry, is_dir);
else
error = may_delete(new_dir, new_dentry, new_is_dir);
}
if (error)
return error;
if (!old_dir->i_op->rename && !old_dir->i_op->rename2)
return -EPERM;
if (flags && !old_dir->i_op->rename2)
return -EINVAL;
/*
* If we are going to change the parent - check write permissions,
* we'll need to flip '..'.
*/
if (new_dir != old_dir) {
if (is_dir) {
error = inode_permission(source, MAY_WRITE);
if (error)
return error;
}
if ((flags & RENAME_EXCHANGE) && new_is_dir) {
error = inode_permission(target, MAY_WRITE);
if (error)
return error;
}
}
error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
flags);
if (error)
return error;
old_name = fsnotify_oldname_init(old_dentry->d_name.name);
dget(new_dentry);
if (!is_dir || (flags & RENAME_EXCHANGE))
lock_two_nondirectories(source, target);
else if (target)
mutex_lock(&target->i_mutex);
error = -EBUSY;
if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
goto out;
if (max_links && new_dir != old_dir) {
error = -EMLINK;
if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
goto out;
if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
old_dir->i_nlink >= max_links)
goto out;
}
if (is_dir && !(flags & RENAME_EXCHANGE) && target)
shrink_dcache_parent(new_dentry);
if (!is_dir) {
error = try_break_deleg(source, delegated_inode);
if (error)
goto out;
}
if (target && !new_is_dir) {
error = try_break_deleg(target, delegated_inode);
if (error)
goto out;
}
if (!old_dir->i_op->rename2) {
error = old_dir->i_op->rename(old_dir, old_dentry,
new_dir, new_dentry);
} else {
WARN_ON(old_dir->i_op->rename != NULL);
error = old_dir->i_op->rename2(old_dir, old_dentry,
new_dir, new_dentry, flags);
}
if (error)
goto out;
if (!(flags & RENAME_EXCHANGE) && target) {
if (is_dir)
target->i_flags |= S_DEAD;
dont_mount(new_dentry);
detach_mounts(new_dentry);
}
if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
if (!(flags & RENAME_EXCHANGE))
d_move(old_dentry, new_dentry);
else
d_exchange(old_dentry, new_dentry);
}
out:
if (!is_dir || (flags & RENAME_EXCHANGE))
unlock_two_nondirectories(source, target);
else if (target)
mutex_unlock(&target->i_mutex);
dput(new_dentry);
if (!error) {
fsnotify_move(old_dir, new_dir, old_name, is_dir,
!(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
if (flags & RENAME_EXCHANGE) {
fsnotify_move(new_dir, old_dir, old_dentry->d_name.name,
new_is_dir, NULL, new_dentry);
}
}
fsnotify_oldname_free(old_name);
return error;
}
EXPORT_SYMBOL(vfs_rename);
SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname,
int, newdfd, const char __user *, newname, unsigned int, flags)
{
struct dentry *old_dir, *new_dir;
struct dentry *old_dentry, *new_dentry;
struct dentry *trap;
struct nameidata oldnd, newnd;
struct inode *delegated_inode = NULL;
struct filename *from;
struct filename *to;
unsigned int lookup_flags = 0;
bool should_retry = false;
int error;
if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
return -EINVAL;
if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) &&
(flags & RENAME_EXCHANGE))
return -EINVAL;
if ((flags & RENAME_WHITEOUT) && !capable(CAP_MKNOD))
return -EPERM;
retry:
from = user_path_parent(olddfd, oldname, &oldnd, lookup_flags);
if (IS_ERR(from)) {
error = PTR_ERR(from);
goto exit;
}
to = user_path_parent(newdfd, newname, &newnd, lookup_flags);
if (IS_ERR(to)) {
error = PTR_ERR(to);
goto exit1;
}
error = -EXDEV;
if (oldnd.path.mnt != newnd.path.mnt)
goto exit2;
old_dir = oldnd.path.dentry;
error = -EBUSY;
if (oldnd.last_type != LAST_NORM)
goto exit2;
new_dir = newnd.path.dentry;
if (flags & RENAME_NOREPLACE)
error = -EEXIST;
if (newnd.last_type != LAST_NORM)
goto exit2;
error = mnt_want_write(oldnd.path.mnt);
if (error)
goto exit2;
oldnd.flags &= ~LOOKUP_PARENT;
newnd.flags &= ~LOOKUP_PARENT;
if (!(flags & RENAME_EXCHANGE))
newnd.flags |= LOOKUP_RENAME_TARGET;
retry_deleg:
trap = lock_rename(new_dir, old_dir);
old_dentry = lookup_hash(&oldnd);
error = PTR_ERR(old_dentry);
if (IS_ERR(old_dentry))
goto exit3;
/* source must exist */
error = -ENOENT;
if (d_is_negative(old_dentry))
goto exit4;
new_dentry = lookup_hash(&newnd);
error = PTR_ERR(new_dentry);
if (IS_ERR(new_dentry))
goto exit4;
error = -EEXIST;
if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry))
goto exit5;
if (flags & RENAME_EXCHANGE) {
error = -ENOENT;
if (d_is_negative(new_dentry))
goto exit5;
if (!d_is_dir(new_dentry)) {
error = -ENOTDIR;
if (newnd.last.name[newnd.last.len])
goto exit5;
}
}
/* unless the source is a directory trailing slashes give -ENOTDIR */
if (!d_is_dir(old_dentry)) {
error = -ENOTDIR;
if (oldnd.last.name[oldnd.last.len])
goto exit5;
if (!(flags & RENAME_EXCHANGE) && newnd.last.name[newnd.last.len])
goto exit5;
}
/* source should not be ancestor of target */
error = -EINVAL;
if (old_dentry == trap)
goto exit5;
/* target should not be an ancestor of source */
if (!(flags & RENAME_EXCHANGE))
error = -ENOTEMPTY;
if (new_dentry == trap)
goto exit5;
error = security_path_rename(&oldnd.path, old_dentry,
&newnd.path, new_dentry, flags);
if (error)
goto exit5;
error = vfs_rename(old_dir->d_inode, old_dentry,
new_dir->d_inode, new_dentry,
&delegated_inode, flags);
exit5:
dput(new_dentry);
exit4:
dput(old_dentry);
exit3:
unlock_rename(new_dir, old_dir);
if (delegated_inode) {
error = break_deleg_wait(&delegated_inode);
if (!error)
goto retry_deleg;
}
mnt_drop_write(oldnd.path.mnt);
exit2:
if (retry_estale(error, lookup_flags))
should_retry = true;
path_put(&newnd.path);
putname(to);
exit1:
path_put(&oldnd.path);
putname(from);
if (should_retry) {
should_retry = false;
lookup_flags |= LOOKUP_REVAL;
goto retry;
}
exit:
return error;
}
SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
int, newdfd, const char __user *, newname)
{
return sys_renameat2(olddfd, oldname, newdfd, newname, 0);
}
SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
{
return sys_renameat2(AT_FDCWD, oldname, AT_FDCWD, newname, 0);
}
int vfs_whiteout(struct inode *dir, struct dentry *dentry)
{
int error = may_create(dir, dentry);
if (error)
return error;
if (!dir->i_op->mknod)
return -EPERM;
return dir->i_op->mknod(dir, dentry,
S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
}
EXPORT_SYMBOL(vfs_whiteout);
int readlink_copy(char __user *buffer, int buflen, const char *link)
{
int len = PTR_ERR(link);
if (IS_ERR(link))
goto out;
len = strlen(link);
if (len > (unsigned) buflen)
len = buflen;
if (copy_to_user(buffer, link, len))
len = -EFAULT;
out:
return len;
}
EXPORT_SYMBOL(readlink_copy);
/*
* A helper for ->readlink(). This should be used *ONLY* for symlinks that
* have ->follow_link() touching nd only in nd_set_link(). Using (or not
* using) it for any given inode is up to filesystem.
*/
int generic_readlink(struct dentry *dentry, char __user *buffer, int buflen)
{
struct nameidata nd;
void *cookie;
int res;
nd.depth = 0;
cookie = dentry->d_inode->i_op->follow_link(dentry, &nd);
if (IS_ERR(cookie))
return PTR_ERR(cookie);
res = readlink_copy(buffer, buflen, nd_get_link(&nd));
if (dentry->d_inode->i_op->put_link)
dentry->d_inode->i_op->put_link(dentry, &nd, cookie);
return res;
}
EXPORT_SYMBOL(generic_readlink);
/* get the link contents into pagecache */
static char *page_getlink(struct dentry * dentry, struct page **ppage)
{
char *kaddr;
struct page *page;
struct address_space *mapping = dentry->d_inode->i_mapping;
page = read_mapping_page(mapping, 0, NULL);
if (IS_ERR(page))
return (char*)page;
*ppage = page;
kaddr = kmap(page);
nd_terminate_link(kaddr, dentry->d_inode->i_size, PAGE_SIZE - 1);
return kaddr;
}
int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
{
struct page *page = NULL;
int res = readlink_copy(buffer, buflen, page_getlink(dentry, &page));
if (page) {
kunmap(page);
page_cache_release(page);
}
return res;
}
EXPORT_SYMBOL(page_readlink);
void *page_follow_link_light(struct dentry *dentry, struct nameidata *nd)
{
struct page *page = NULL;
nd_set_link(nd, page_getlink(dentry, &page));
return page;
}
EXPORT_SYMBOL(page_follow_link_light);
void page_put_link(struct dentry *dentry, struct nameidata *nd, void *cookie)
{
struct page *page = cookie;
if (page) {
kunmap(page);
page_cache_release(page);
}
}
EXPORT_SYMBOL(page_put_link);
/*
* The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS
*/
int __page_symlink(struct inode *inode, const char *symname, int len, int nofs)
{
struct address_space *mapping = inode->i_mapping;
struct page *page;
void *fsdata;
int err;
char *kaddr;
unsigned int flags = AOP_FLAG_UNINTERRUPTIBLE;
if (nofs)
flags |= AOP_FLAG_NOFS;
retry:
err = pagecache_write_begin(NULL, mapping, 0, len-1,
flags, &page, &fsdata);
if (err)
goto fail;
kaddr = kmap_atomic(page);
memcpy(kaddr, symname, len-1);
kunmap_atomic(kaddr);
err = pagecache_write_end(NULL, mapping, 0, len-1, len-1,
page, fsdata);
if (err < 0)
goto fail;
if (err < len-1)
goto retry;
mark_inode_dirty(inode);
return 0;
fail:
return err;
}
EXPORT_SYMBOL(__page_symlink);
int page_symlink(struct inode *inode, const char *symname, int len)
{
return __page_symlink(inode, symname, len,
!(mapping_gfp_mask(inode->i_mapping) & __GFP_FS));
}
EXPORT_SYMBOL(page_symlink);
const struct inode_operations page_symlink_inode_operations = {
.readlink = generic_readlink,
.follow_link = page_follow_link_light,
.put_link = page_put_link,
};
EXPORT_SYMBOL(page_symlink_inode_operations);
| Tilde88/android_kernel_lge_msm8996 | fs/namei.c | C | gpl-2.0 | 116,687 |
// Project64 - A Nintendo 64 emulator
// https://www.pj64-emu.com/
// Copyright(C) 2001-2021 Project64
// Copyright(C) 2000-2015 Azimer
// GNU/GPLv2 licensed: https://gnu.org/licenses/gpl-2.0.html
#pragma once
#include <Common/SyncEvent.h>
#include <Common/CriticalSection.h>
class SoundDriverBase
{
public:
SoundDriverBase();
void AI_SetFrequency(uint32_t Frequency, uint32_t BufferSize);
void AI_LenChanged(uint8_t *start, uint32_t length);
void AI_Startup();
void AI_Shutdown();
void AI_Update(bool Wait);
uint32_t AI_ReadLength();
virtual void SetFrequency(uint32_t Frequency, uint32_t BufferSize);
virtual void StartAudio();
virtual void StopAudio();
protected:
enum { MAX_SIZE = 48000 * 2 * 2 }; // Max buffer size (44100Hz * 16-bit * stereo)
virtual bool Initialize();
void LoadAiBuffer(uint8_t *start, uint32_t length); // Reads in length amount of audio bytes
uint32_t m_MaxBufferSize; // Variable size determined by playback rate
CriticalSection m_CS;
private:
void BufferAudio();
SyncEvent m_AiUpdateEvent;
uint8_t *m_AI_DMAPrimaryBuffer, *m_AI_DMASecondaryBuffer;
uint32_t m_AI_DMAPrimaryBytes, m_AI_DMASecondaryBytes;
uint32_t m_BufferRemaining; // Buffer remaining
uint32_t m_CurrentReadLoc; // Currently playing buffer
uint32_t m_CurrentWriteLoc; // Currently writing buffer
uint8_t m_Buffer[MAX_SIZE]; // Emulated buffers
};
| project64/project64 | Source/Project64-audio/Driver/SoundBase.h | C | gpl-2.0 | 1,444 |
/*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* Implementation of the Transmission Control Protocol(TCP).
*
* Authors: Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
* Mark Evans, <evansmp@uhura.aston.ac.uk>
* Corey Minyard <wf-rch!minyard@relay.EU.net>
* Florian La Roche, <flla@stud.uni-sb.de>
* Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
* Linus Torvalds, <torvalds@cs.helsinki.fi>
* Alan Cox, <gw4pts@gw4pts.ampr.org>
* Matthew Dillon, <dillon@apollo.west.oic.com>
* Arnt Gulbrandsen, <agulbra@nvg.unit.no>
* Jorge Cwik, <jorge@laser.satlink.net>
*/
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/sysctl.h>
#include <linux/workqueue.h>
#include <net/tcp.h>
#include <net/inet_common.h>
#include <net/xfrm.h>
int sysctl_tcp_syncookies __read_mostly = 1;
EXPORT_SYMBOL(sysctl_tcp_syncookies);
int sysctl_tcp_abort_on_overflow __read_mostly;
struct inet_timewait_death_row tcp_death_row = {
.sysctl_max_tw_buckets = NR_FILE * 2,
.period = TCP_TIMEWAIT_LEN / INET_TWDR_TWKILL_SLOTS,
.death_lock = __SPIN_LOCK_UNLOCKED(tcp_death_row.death_lock),
.hashinfo = &tcp_hashinfo,
.tw_timer = TIMER_INITIALIZER(inet_twdr_hangman, 0,
(unsigned long)&tcp_death_row),
.twkill_work = __WORK_INITIALIZER(tcp_death_row.twkill_work,
inet_twdr_twkill_work),
/* Short-time timewait calendar */
.twcal_hand = -1,
.twcal_timer = TIMER_INITIALIZER(inet_twdr_twcal_tick, 0,
(unsigned long)&tcp_death_row),
};
EXPORT_SYMBOL_GPL(tcp_death_row);
static bool tcp_in_window(u32 seq, u32 end_seq, u32 s_win, u32 e_win)
{
if (seq == s_win)
return true;
if (after(end_seq, s_win) && before(seq, e_win))
return true;
return seq == e_win && seq == end_seq;
}
/*
* * Main purpose of TIME-WAIT state is to close connection gracefully,
* when one of ends sits in LAST-ACK or CLOSING retransmitting FIN
* (and, probably, tail of data) and one or more our ACKs are lost.
* * What is TIME-WAIT timeout? It is associated with maximal packet
* lifetime in the internet, which results in wrong conclusion, that
* it is set to catch "old duplicate segments" wandering out of their path.
* It is not quite correct. This timeout is calculated so that it exceeds
* maximal retransmission timeout enough to allow to lose one (or more)
* segments sent by peer and our ACKs. This time may be calculated from RTO.
* * When TIME-WAIT socket receives RST, it means that another end
* finally closed and we are allowed to kill TIME-WAIT too.
* * Second purpose of TIME-WAIT is catching old duplicate segments.
* Well, certainly it is pure paranoia, but if we load TIME-WAIT
* with this semantics, we MUST NOT kill TIME-WAIT state with RSTs.
* * If we invented some more clever way to catch duplicates
* (f.e. based on PAWS), we could truncate TIME-WAIT to several RTOs.
*
* The algorithm below is based on FORMAL INTERPRETATION of RFCs.
* When you compare it to RFCs, please, read section SEGMENT ARRIVES
* from the very beginning.
*
* NOTE. With recycling (and later with fin-wait-2) TW bucket
* is _not_ stateless. It means, that strictly speaking we must
* spinlock it. I do not want! Well, probability of misbehaviour
* is ridiculously low and, seems, we could use some mb() tricks
* to avoid misread sequence numbers, states etc. --ANK
*
* We don't need to initialize tmp_out.sack_ok as we don't use the results
*/
enum tcp_tw_status
tcp_timewait_state_process(struct inet_timewait_sock *tw, struct sk_buff *skb,
const struct tcphdr *th)
{
struct tcp_options_received tmp_opt;
struct tcp_timewait_sock *tcptw = tcp_twsk((struct sock *)tw);
bool paws_reject = false;
tmp_opt.saw_tstamp = 0;
if (th->doff > (sizeof(*th) >> 2) && tcptw->tw_ts_recent_stamp) {
tcp_parse_options(skb, &tmp_opt, 0, NULL);
if (tmp_opt.saw_tstamp) {
tmp_opt.rcv_tsecr -= tcptw->tw_ts_offset;
tmp_opt.ts_recent = tcptw->tw_ts_recent;
tmp_opt.ts_recent_stamp = tcptw->tw_ts_recent_stamp;
paws_reject = tcp_paws_reject(&tmp_opt, th->rst);
}
}
if (tw->tw_substate == TCP_FIN_WAIT2) {
/* Just repeat all the checks of tcp_rcv_state_process() */
/* Out of window, send ACK */
if (paws_reject ||
!tcp_in_window(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq,
tcptw->tw_rcv_nxt,
tcptw->tw_rcv_nxt + tcptw->tw_rcv_wnd))
return TCP_TW_ACK;
if (th->rst)
goto kill;
if (th->syn && !before(TCP_SKB_CB(skb)->seq, tcptw->tw_rcv_nxt))
goto kill_with_rst;
/* Dup ACK? */
if (!th->ack ||
!after(TCP_SKB_CB(skb)->end_seq, tcptw->tw_rcv_nxt) ||
TCP_SKB_CB(skb)->end_seq == TCP_SKB_CB(skb)->seq) {
inet_twsk_put(tw);
return TCP_TW_SUCCESS;
}
/* New data or FIN. If new data arrive after half-duplex close,
* reset.
*/
if (!th->fin ||
TCP_SKB_CB(skb)->end_seq != tcptw->tw_rcv_nxt + 1) {
kill_with_rst:
inet_twsk_deschedule(tw, &tcp_death_row);
inet_twsk_put(tw);
return TCP_TW_RST;
}
/* FIN arrived, enter true time-wait state. */
tw->tw_substate = TCP_TIME_WAIT;
tcptw->tw_rcv_nxt = TCP_SKB_CB(skb)->end_seq;
if (tmp_opt.saw_tstamp) {
tcptw->tw_ts_recent_stamp = get_seconds();
tcptw->tw_ts_recent = tmp_opt.rcv_tsval;
}
if (tcp_death_row.sysctl_tw_recycle &&
tcptw->tw_ts_recent_stamp &&
tcp_tw_remember_stamp(tw))
inet_twsk_schedule(tw, &tcp_death_row, tw->tw_timeout,
TCP_TIMEWAIT_LEN);
else
inet_twsk_schedule(tw, &tcp_death_row, TCP_TIMEWAIT_LEN,
TCP_TIMEWAIT_LEN);
return TCP_TW_ACK;
}
/*
* Now real TIME-WAIT state.
*
* RFC 1122:
* "When a connection is [...] on TIME-WAIT state [...]
* [a TCP] MAY accept a new SYN from the remote TCP to
* reopen the connection directly, if it:
*
* (1) assigns its initial sequence number for the new
* connection to be larger than the largest sequence
* number it used on the previous connection incarnation,
* and
*
* (2) returns to TIME-WAIT state if the SYN turns out
* to be an old duplicate".
*/
if (!paws_reject &&
(TCP_SKB_CB(skb)->seq == tcptw->tw_rcv_nxt &&
(TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq || th->rst))) {
/* In window segment, it may be only reset or bare ack. */
if (th->rst) {
/* This is TIME_WAIT assassination, in two flavors.
* Oh well... nobody has a sufficient solution to this
* protocol bug yet.
*/
if (sysctl_tcp_rfc1337 == 0) {
kill:
inet_twsk_deschedule(tw, &tcp_death_row);
inet_twsk_put(tw);
return TCP_TW_SUCCESS;
}
}
inet_twsk_schedule(tw, &tcp_death_row, TCP_TIMEWAIT_LEN,
TCP_TIMEWAIT_LEN);
if (tmp_opt.saw_tstamp) {
tcptw->tw_ts_recent = tmp_opt.rcv_tsval;
tcptw->tw_ts_recent_stamp = get_seconds();
}
inet_twsk_put(tw);
return TCP_TW_SUCCESS;
}
/* Out of window segment.
All the segments are ACKed immediately.
The only exception is new SYN. We accept it, if it is
not old duplicate and we are not in danger to be killed
by delayed old duplicates. RFC check is that it has
newer sequence number works at rates <40Mbit/sec.
However, if paws works, it is reliable AND even more,
we even may relax silly seq space cutoff.
RED-PEN: we violate main RFC requirement, if this SYN will appear
old duplicate (i.e. we receive RST in reply to SYN-ACK),
we must return socket to time-wait state. It is not good,
but not fatal yet.
*/
if (th->syn && !th->rst && !th->ack && !paws_reject &&
(after(TCP_SKB_CB(skb)->seq, tcptw->tw_rcv_nxt) ||
(tmp_opt.saw_tstamp &&
(s32)(tcptw->tw_ts_recent - tmp_opt.rcv_tsval) < 0))) {
u32 isn = tcptw->tw_snd_nxt + 65535 + 2;
if (isn == 0)
isn++;
TCP_SKB_CB(skb)->when = isn;
return TCP_TW_SYN;
}
if (paws_reject)
NET_INC_STATS_BH(twsk_net(tw), LINUX_MIB_PAWSESTABREJECTED);
if (!th->rst) {
/* In this case we must reset the TIMEWAIT timer.
*
* If it is ACKless SYN it may be both old duplicate
* and new good SYN with random sequence number <rcv_nxt.
* Do not reschedule in the last case.
*/
if (paws_reject || th->ack)
inet_twsk_schedule(tw, &tcp_death_row, TCP_TIMEWAIT_LEN,
TCP_TIMEWAIT_LEN);
/* Send ACK. Note, we do not put the bucket,
* it will be released by caller.
*/
return TCP_TW_ACK;
}
inet_twsk_put(tw);
return TCP_TW_SUCCESS;
}
EXPORT_SYMBOL(tcp_timewait_state_process);
/*
* Move a socket to time-wait or dead fin-wait-2 state.
*/
void tcp_time_wait(struct sock *sk, int state, int timeo)
{
struct inet_timewait_sock *tw = NULL;
const struct inet_connection_sock *icsk = inet_csk(sk);
const struct tcp_sock *tp = tcp_sk(sk);
bool recycle_ok = false;
if (tcp_death_row.sysctl_tw_recycle && tp->rx_opt.ts_recent_stamp)
recycle_ok = tcp_remember_stamp(sk);
if (tcp_death_row.tw_count < tcp_death_row.sysctl_max_tw_buckets)
tw = inet_twsk_alloc(sk, state);
if (tw != NULL) {
struct tcp_timewait_sock *tcptw = tcp_twsk((struct sock *)tw);
const int rto = (icsk->icsk_rto << 2) - (icsk->icsk_rto >> 1);
struct inet_sock *inet = inet_sk(sk);
tw->tw_transparent = inet->transparent;
tw->tw_rcv_wscale = tp->rx_opt.rcv_wscale;
tcptw->tw_rcv_nxt = tp->rcv_nxt;
tcptw->tw_snd_nxt = tp->snd_nxt;
tcptw->tw_rcv_wnd = tcp_receive_window(tp);
tcptw->tw_ts_recent = tp->rx_opt.ts_recent;
tcptw->tw_ts_recent_stamp = tp->rx_opt.ts_recent_stamp;
tcptw->tw_ts_offset = tp->tsoffset;
#if IS_ENABLED(CONFIG_IPV6)
if (tw->tw_family == PF_INET6) {
struct ipv6_pinfo *np = inet6_sk(sk);
tw->tw_v6_daddr = sk->sk_v6_daddr;
tw->tw_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
tw->tw_tclass = np->tclass;
tw->tw_flowlabel = np->flow_label >> 12;
tw->tw_ipv6only = np->ipv6only;
}
#endif
#ifdef CONFIG_TCP_MD5SIG
/*
* The timewait bucket does not have the key DB from the
* sock structure. We just make a quick copy of the
* md5 key being used (if indeed we are using one)
* so the timewait ack generating code has the key.
*/
do {
struct tcp_md5sig_key *key;
tcptw->tw_md5_key = NULL;
key = tp->af_specific->md5_lookup(sk, sk);
if (key != NULL) {
tcptw->tw_md5_key = kmemdup(key, sizeof(*key), GFP_ATOMIC);
if (tcptw->tw_md5_key && !tcp_alloc_md5sig_pool())
BUG();
}
} while (0);
#endif
/* Linkage updates. */
__inet_twsk_hashdance(tw, sk, &tcp_hashinfo);
/* Get the TIME_WAIT timeout firing. */
if (timeo < rto)
timeo = rto;
if (recycle_ok) {
tw->tw_timeout = rto;
} else {
tw->tw_timeout = TCP_TIMEWAIT_LEN;
if (state == TCP_TIME_WAIT)
timeo = TCP_TIMEWAIT_LEN;
}
inet_twsk_schedule(tw, &tcp_death_row, timeo,
TCP_TIMEWAIT_LEN);
inet_twsk_put(tw);
} else {
/* Sorry, if we're out of memory, just CLOSE this
* socket up. We've got bigger problems than
* non-graceful socket closings.
*/
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPTIMEWAITOVERFLOW);
}
tcp_update_metrics(sk);
tcp_done(sk);
}
void tcp_twsk_destructor(struct sock *sk)
{
#ifdef CONFIG_TCP_MD5SIG
struct tcp_timewait_sock *twsk = tcp_twsk(sk);
if (twsk->tw_md5_key)
kfree_rcu(twsk->tw_md5_key, rcu);
#endif
}
EXPORT_SYMBOL_GPL(tcp_twsk_destructor);
static inline void TCP_ECN_openreq_child(struct tcp_sock *tp,
struct request_sock *req)
{
tp->ecn_flags = inet_rsk(req)->ecn_ok ? TCP_ECN_OK : 0;
}
/* This is not only more efficient than what we used to do, it eliminates
* a lot of code duplication between IPv4/IPv6 SYN recv processing. -DaveM
*
* Actually, we could lots of memory writes here. tp of listening
* socket contains all necessary default parameters.
*/
struct sock *tcp_create_openreq_child(struct sock *sk, struct request_sock *req, struct sk_buff *skb)
{
struct sock *newsk = inet_csk_clone_lock(sk, req, GFP_ATOMIC);
if (newsk != NULL) {
const struct inet_request_sock *ireq = inet_rsk(req);
struct tcp_request_sock *treq = tcp_rsk(req);
struct inet_connection_sock *newicsk = inet_csk(newsk);
struct tcp_sock *newtp = tcp_sk(newsk);
/* Now setup tcp_sock */
newtp->pred_flags = 0;
newtp->rcv_wup = newtp->copied_seq =
newtp->rcv_nxt = treq->rcv_isn + 1;
newtp->snd_sml = newtp->snd_una =
newtp->snd_nxt = newtp->snd_up = treq->snt_isn + 1;
tcp_prequeue_init(newtp);
INIT_LIST_HEAD(&newtp->tsq_node);
tcp_init_wl(newtp, treq->rcv_isn);
newtp->srtt_us = 0;
newtp->mdev_us = jiffies_to_usecs(TCP_TIMEOUT_INIT);
newicsk->icsk_rto = TCP_TIMEOUT_INIT;
newtp->packets_out = 0;
newtp->retrans_out = 0;
newtp->sacked_out = 0;
newtp->fackets_out = 0;
newtp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
tcp_enable_early_retrans(newtp);
newtp->tlp_high_seq = 0;
newtp->lsndtime = treq->snt_synack;
newtp->total_retrans = req->num_retrans;
/* So many TCP implementations out there (incorrectly) count the
* initial SYN frame in their delayed-ACK and congestion control
* algorithms that we must have the following bandaid to talk
* efficiently to them. -DaveM
*/
newtp->snd_cwnd = TCP_INIT_CWND;
newtp->snd_cwnd_cnt = 0;
if (newicsk->icsk_ca_ops != &tcp_init_congestion_ops &&
!try_module_get(newicsk->icsk_ca_ops->owner))
newicsk->icsk_ca_ops = &tcp_init_congestion_ops;
tcp_set_ca_state(newsk, TCP_CA_Open);
tcp_init_xmit_timers(newsk);
__skb_queue_head_init(&newtp->out_of_order_queue);
newtp->write_seq = newtp->pushed_seq = treq->snt_isn + 1;
newtp->rx_opt.saw_tstamp = 0;
newtp->rx_opt.dsack = 0;
newtp->rx_opt.num_sacks = 0;
newtp->urg_data = 0;
if (sock_flag(newsk, SOCK_KEEPOPEN))
inet_csk_reset_keepalive_timer(newsk,
keepalive_time_when(newtp));
newtp->rx_opt.tstamp_ok = ireq->tstamp_ok;
if ((newtp->rx_opt.sack_ok = ireq->sack_ok) != 0) {
if (sysctl_tcp_fack)
tcp_enable_fack(newtp);
}
newtp->window_clamp = req->window_clamp;
newtp->rcv_ssthresh = req->rcv_wnd;
newtp->rcv_wnd = req->rcv_wnd;
newtp->rx_opt.wscale_ok = ireq->wscale_ok;
if (newtp->rx_opt.wscale_ok) {
newtp->rx_opt.snd_wscale = ireq->snd_wscale;
newtp->rx_opt.rcv_wscale = ireq->rcv_wscale;
} else {
newtp->rx_opt.snd_wscale = newtp->rx_opt.rcv_wscale = 0;
newtp->window_clamp = min(newtp->window_clamp, 65535U);
}
newtp->snd_wnd = (ntohs(tcp_hdr(skb)->window) <<
newtp->rx_opt.snd_wscale);
newtp->max_window = newtp->snd_wnd;
if (newtp->rx_opt.tstamp_ok) {
newtp->rx_opt.ts_recent = req->ts_recent;
newtp->rx_opt.ts_recent_stamp = get_seconds();
newtp->tcp_header_len = sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
} else {
newtp->rx_opt.ts_recent_stamp = 0;
newtp->tcp_header_len = sizeof(struct tcphdr);
}
newtp->tsoffset = 0;
#ifdef CONFIG_TCP_MD5SIG
newtp->md5sig_info = NULL; /*XXX*/
if (newtp->af_specific->md5_lookup(sk, newsk))
newtp->tcp_header_len += TCPOLEN_MD5SIG_ALIGNED;
#endif
if (skb->len >= TCP_MSS_DEFAULT + newtp->tcp_header_len)
newicsk->icsk_ack.last_seg_size = skb->len - newtp->tcp_header_len;
newtp->rx_opt.mss_clamp = req->mss;
TCP_ECN_openreq_child(newtp, req);
newtp->fastopen_rsk = NULL;
newtp->syn_data_acked = 0;
TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_PASSIVEOPENS);
}
return newsk;
}
EXPORT_SYMBOL(tcp_create_openreq_child);
/*
* Process an incoming packet for SYN_RECV sockets represented as a
* request_sock. Normally sk is the listener socket but for TFO it
* points to the child socket.
*
* XXX (TFO) - The current impl contains a special check for ack
* validation and inside tcp_v4_reqsk_send_ack(). Can we do better?
*
* We don't need to initialize tmp_opt.sack_ok as we don't use the results
*/
struct sock *tcp_check_req(struct sock *sk, struct sk_buff *skb,
struct request_sock *req,
struct request_sock **prev,
bool fastopen)
{
struct tcp_options_received tmp_opt;
struct sock *child;
const struct tcphdr *th = tcp_hdr(skb);
__be32 flg = tcp_flag_word(th) & (TCP_FLAG_RST|TCP_FLAG_SYN|TCP_FLAG_ACK);
bool paws_reject = false;
BUG_ON(fastopen == (sk->sk_state == TCP_LISTEN));
tmp_opt.saw_tstamp = 0;
if (th->doff > (sizeof(struct tcphdr)>>2)) {
tcp_parse_options(skb, &tmp_opt, 0, NULL);
if (tmp_opt.saw_tstamp) {
tmp_opt.ts_recent = req->ts_recent;
/* We do not store true stamp, but it is not required,
* it can be estimated (approximately)
* from another data.
*/
tmp_opt.ts_recent_stamp = get_seconds() - ((TCP_TIMEOUT_INIT/HZ)<<req->num_timeout);
paws_reject = tcp_paws_reject(&tmp_opt, th->rst);
}
}
/* Check for pure retransmitted SYN. */
if (TCP_SKB_CB(skb)->seq == tcp_rsk(req)->rcv_isn &&
flg == TCP_FLAG_SYN &&
!paws_reject) {
/*
* RFC793 draws (Incorrectly! It was fixed in RFC1122)
* this case on figure 6 and figure 8, but formal
* protocol description says NOTHING.
* To be more exact, it says that we should send ACK,
* because this segment (at least, if it has no data)
* is out of window.
*
* CONCLUSION: RFC793 (even with RFC1122) DOES NOT
* describe SYN-RECV state. All the description
* is wrong, we cannot believe to it and should
* rely only on common sense and implementation
* experience.
*
* Enforce "SYN-ACK" according to figure 8, figure 6
* of RFC793, fixed by RFC1122.
*
* Note that even if there is new data in the SYN packet
* they will be thrown away too.
*
* Reset timer after retransmitting SYNACK, similar to
* the idea of fast retransmit in recovery.
*/
if (!inet_rtx_syn_ack(sk, req))
req->expires = min(TCP_TIMEOUT_INIT << req->num_timeout,
TCP_RTO_MAX) + jiffies;
return NULL;
}
/* Further reproduces section "SEGMENT ARRIVES"
for state SYN-RECEIVED of RFC793.
It is broken, however, it does not work only
when SYNs are crossed.
You would think that SYN crossing is impossible here, since
we should have a SYN_SENT socket (from connect()) on our end,
but this is not true if the crossed SYNs were sent to both
ends by a malicious third party. We must defend against this,
and to do that we first verify the ACK (as per RFC793, page
36) and reset if it is invalid. Is this a true full defense?
To convince ourselves, let us consider a way in which the ACK
test can still pass in this 'malicious crossed SYNs' case.
Malicious sender sends identical SYNs (and thus identical sequence
numbers) to both A and B:
A: gets SYN, seq=7
B: gets SYN, seq=7
By our good fortune, both A and B select the same initial
send sequence number of seven :-)
A: sends SYN|ACK, seq=7, ack_seq=8
B: sends SYN|ACK, seq=7, ack_seq=8
So we are now A eating this SYN|ACK, ACK test passes. So
does sequence test, SYN is truncated, and thus we consider
it a bare ACK.
If icsk->icsk_accept_queue.rskq_defer_accept, we silently drop this
bare ACK. Otherwise, we create an established connection. Both
ends (listening sockets) accept the new incoming connection and try
to talk to each other. 8-)
Note: This case is both harmless, and rare. Possibility is about the
same as us discovering intelligent life on another plant tomorrow.
But generally, we should (RFC lies!) to accept ACK
from SYNACK both here and in tcp_rcv_state_process().
tcp_rcv_state_process() does not, hence, we do not too.
Note that the case is absolutely generic:
we cannot optimize anything here without
violating protocol. All the checks must be made
before attempt to create socket.
*/
/* RFC793 page 36: "If the connection is in any non-synchronized state ...
* and the incoming segment acknowledges something not yet
* sent (the segment carries an unacceptable ACK) ...
* a reset is sent."
*
* Invalid ACK: reset will be sent by listening socket.
* Note that the ACK validity check for a Fast Open socket is done
* elsewhere and is checked directly against the child socket rather
* than req because user data may have been sent out.
*/
if ((flg & TCP_FLAG_ACK) && !fastopen &&
(TCP_SKB_CB(skb)->ack_seq !=
tcp_rsk(req)->snt_isn + 1))
return sk;
/* Also, it would be not so bad idea to check rcv_tsecr, which
* is essentially ACK extension and too early or too late values
* should cause reset in unsynchronized states.
*/
/* RFC793: "first check sequence number". */
if (paws_reject || !tcp_in_window(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq,
tcp_rsk(req)->rcv_nxt, tcp_rsk(req)->rcv_nxt + req->rcv_wnd)) {
/* Out of window: send ACK and drop. */
if (!(flg & TCP_FLAG_RST))
req->rsk_ops->send_ack(sk, skb, req);
if (paws_reject)
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_PAWSESTABREJECTED);
return NULL;
}
/* In sequence, PAWS is OK. */
if (tmp_opt.saw_tstamp && !after(TCP_SKB_CB(skb)->seq, tcp_rsk(req)->rcv_nxt))
req->ts_recent = tmp_opt.rcv_tsval;
if (TCP_SKB_CB(skb)->seq == tcp_rsk(req)->rcv_isn) {
/* Truncate SYN, it is out of window starting
at tcp_rsk(req)->rcv_isn + 1. */
flg &= ~TCP_FLAG_SYN;
}
/* RFC793: "second check the RST bit" and
* "fourth, check the SYN bit"
*/
if (flg & (TCP_FLAG_RST|TCP_FLAG_SYN)) {
TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_ATTEMPTFAILS);
goto embryonic_reset;
}
/* ACK sequence verified above, just make sure ACK is
* set. If ACK not set, just silently drop the packet.
*
* XXX (TFO) - if we ever allow "data after SYN", the
* following check needs to be removed.
*/
if (!(flg & TCP_FLAG_ACK))
return NULL;
/* For Fast Open no more processing is needed (sk is the
* child socket).
*/
if (fastopen)
return sk;
/* While TCP_DEFER_ACCEPT is active, drop bare ACK. */
if (req->num_timeout < inet_csk(sk)->icsk_accept_queue.rskq_defer_accept &&
TCP_SKB_CB(skb)->end_seq == tcp_rsk(req)->rcv_isn + 1) {
inet_rsk(req)->acked = 1;
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPDEFERACCEPTDROP);
return NULL;
}
/* OK, ACK is valid, create big socket and
* feed this segment to it. It will repeat all
* the tests. THIS SEGMENT MUST MOVE SOCKET TO
* ESTABLISHED STATE. If it will be dropped after
* socket is created, wait for troubles.
*/
child = inet_csk(sk)->icsk_af_ops->syn_recv_sock(sk, skb, req, NULL);
if (child == NULL)
goto listen_overflow;
inet_csk_reqsk_queue_unlink(sk, req, prev);
inet_csk_reqsk_queue_removed(sk, req);
inet_csk_reqsk_queue_add(sk, req, child);
return child;
listen_overflow:
if (!sysctl_tcp_abort_on_overflow) {
inet_rsk(req)->acked = 1;
return NULL;
}
embryonic_reset:
if (!(flg & TCP_FLAG_RST)) {
/* Received a bad SYN pkt - for TFO We try not to reset
* the local connection unless it's really necessary to
* avoid becoming vulnerable to outside attack aiming at
* resetting legit local connections.
*/
req->rsk_ops->send_reset(sk, skb);
} else if (fastopen) { /* received a valid RST pkt */
reqsk_fastopen_remove(sk, req, true);
tcp_reset(sk);
}
if (!fastopen) {
inet_csk_reqsk_queue_drop(sk, req, prev);
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_EMBRYONICRSTS);
}
return NULL;
}
EXPORT_SYMBOL(tcp_check_req);
/*
* Queue segment on the new socket if the new socket is active,
* otherwise we just shortcircuit this and continue with
* the new socket.
*
* For the vast majority of cases child->sk_state will be TCP_SYN_RECV
* when entering. But other states are possible due to a race condition
* where after __inet_lookup_established() fails but before the listener
* locked is obtained, other packets cause the same connection to
* be created.
*/
int tcp_child_process(struct sock *parent, struct sock *child,
struct sk_buff *skb)
{
int ret = 0;
int state = child->sk_state;
if (!sock_owned_by_user(child)) {
ret = tcp_rcv_state_process(child, skb, tcp_hdr(skb),
skb->len);
/* Wakeup parent, send SIGIO */
if (state == TCP_SYN_RECV && child->sk_state != state)
parent->sk_data_ready(parent, 0);
} else {
/* Alas, it is possible again, because we do lookup
* in main socket hash table and lock on listening
* socket does not protect us more.
*/
__sk_add_backlog(child, skb);
}
bh_unlock_sock(child);
sock_put(child);
return ret;
}
EXPORT_SYMBOL(tcp_child_process);
| longman88/kernel-qspinlock | net/ipv4/tcp_minisocks.c | C | gpl-2.0 | 24,460 |
#ifndef __ARM_ARCH_DEV_HAWII_LOGANDS_NFC_H
#define __ARM_ARCH_DEV_HAWII_LOGANDS_NFC_H
void __init hawaii_nfc_init(void);
#endif | alexey6600/kernel_sony_tetra_2 | arch/arm/mach-hawaii/include/mach/dev-hawaii_logands_nfc.h | C | gpl-2.0 | 127 |
/*
* AMD Elan SC520 processor Watchdog Timer driver
*
* Based on acquirewdt.c by Alan Cox,
* and sbc60xxwdt.c by Jakob Oestergaard <jakob@unthought.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.
*
* The authors do NOT admit liability nor provide warranty for
* any of this software. This material is provided "AS-IS" in
* the hope that it may be useful for others.
*
* (c) Copyright 2001 Scott Jennings <linuxdrivers@oro.net>
* 9/27 - 2001 [Initial release]
*
* Additional fixes Alan Cox
* - Fixed formatting
* - Removed debug printks
* - Fixed SMP built kernel deadlock
* - Switched to private locks not lock_kernel
* - Used ioremap/writew/readw
* - Added NOWAYOUT support
* 4/12 - 2002 Changes by Rob Radez <rob@osinvestor.com>
* - Change comments
* - Eliminate fop_llseek
* - Change CONFIG_WATCHDOG_NOWAYOUT semantics
* - Add KERN_* tags to printks
* - fix possible wdt_is_open race
* - Report proper capabilities in watchdog_info
* - Add WDIOC_{GETSTATUS, GETBOOTSTATUS, SETTIMEOUT,
* GETTIMEOUT, SETOPTIONS} ioctls
* 09/8 - 2003 Changes by Wim Van Sebroeck <wim@iguana.be>
* - cleanup of trailing spaces
* - added extra printk's for startup problems
* - use module_param
* - made timeout (the emulated heartbeat) a module_param
* - made the keepalive ping an internal subroutine
* 3/27 - 2004 Changes by Sean Young <sean@mess.org>
* - set MMCR_BASE to 0xfffef000
* - CBAR does not need to be read
* - removed debugging printks
*
* This WDT driver is different from most other Linux WDT
* drivers in that the driver will ping the watchdog by itself,
* because this particular WDT has a very short timeout (1.6
* seconds) and it would be insane to count on any userspace
* daemon always getting scheduled within that time frame.
*
* This driver uses memory mapped IO, and spinlock.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/types.h>
#include <linux/timer.h>
#include <linux/miscdevice.h>
#include <linux/watchdog.h>
#include <linux/fs.h>
#include <linux/ioport.h>
#include <linux/notifier.h>
#include <linux/reboot.h>
#include <linux/init.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <asm/system.h>
#define OUR_NAME "sc520_wdt"
#define PFX OUR_NAME ": "
/*
* The AMD Elan SC520 timeout value is 492us times a power of 2 (0-7)
*
* 0: 492us 2: 1.01s 4: 4.03s 6: 16.22s
* 1: 503ms 3: 2.01s 5: 8.05s 7: 32.21s
*
* We will program the SC520 watchdog for a timeout of 2.01s.
* If we reset the watchdog every ~250ms we should be safe.
*/
#define WDT_INTERVAL (HZ/4+1)
/*
* We must not require too good response from the userspace daemon.
* Here we require the userspace daemon to send us a heartbeat
* char to /dev/watchdog every 30 seconds.
*/
#define WATCHDOG_TIMEOUT 30 /* 30 sec default timeout */
static int timeout = WATCHDOG_TIMEOUT; /* in seconds, will be multiplied by HZ to get seconds to wait for a ping */
module_param(timeout, int, 0);
MODULE_PARM_DESC(timeout, "Watchdog timeout in seconds. (1<=timeout<=3600, default=" __MODULE_STRING(WATCHDOG_TIMEOUT) ")");
static int nowayout = WATCHDOG_NOWAYOUT;
module_param(nowayout, int, 0);
MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started (default=CONFIG_WATCHDOG_NOWAYOUT)");
/*
* AMD Elan SC520 - Watchdog Timer Registers
*/
#define MMCR_BASE 0xfffef000 /* The default base address */
#define OFFS_WDTMRCTL 0xCB0 /* Watchdog Timer Control Register */
/* WDT Control Register bit definitions */
#define WDT_EXP_SEL_01 0x0001 /* [01] Time-out = 496 us (with 33 Mhz clk). */
#define WDT_EXP_SEL_02 0x0002 /* [02] Time-out = 508 ms (with 33 Mhz clk). */
#define WDT_EXP_SEL_03 0x0004 /* [03] Time-out = 1.02 s (with 33 Mhz clk). */
#define WDT_EXP_SEL_04 0x0008 /* [04] Time-out = 2.03 s (with 33 Mhz clk). */
#define WDT_EXP_SEL_05 0x0010 /* [05] Time-out = 4.07 s (with 33 Mhz clk). */
#define WDT_EXP_SEL_06 0x0020 /* [06] Time-out = 8.13 s (with 33 Mhz clk). */
#define WDT_EXP_SEL_07 0x0040 /* [07] Time-out = 16.27s (with 33 Mhz clk). */
#define WDT_EXP_SEL_08 0x0080 /* [08] Time-out = 32.54s (with 33 Mhz clk). */
#define WDT_IRQ_FLG 0x1000 /* [12] Interrupt Request Flag */
#define WDT_WRST_ENB 0x4000 /* [14] Watchdog Timer Reset Enable */
#define WDT_ENB 0x8000 /* [15] Watchdog Timer Enable */
static __u16 __iomem *wdtmrctl;
static void wdt_timer_ping(unsigned long);
static struct timer_list timer;
static unsigned long next_heartbeat;
static unsigned long wdt_is_open;
static char wdt_expect_close;
static spinlock_t wdt_spinlock;
/*
* Whack the dog
*/
static void wdt_timer_ping(unsigned long data)
{
/* If we got a heartbeat pulse within the WDT_US_INTERVAL
* we agree to ping the WDT
*/
if(time_before(jiffies, next_heartbeat))
{
/* Ping the WDT */
spin_lock(&wdt_spinlock);
writew(0xAAAA, wdtmrctl);
writew(0x5555, wdtmrctl);
spin_unlock(&wdt_spinlock);
/* Re-set the timer interval */
timer.expires = jiffies + WDT_INTERVAL;
add_timer(&timer);
} else {
printk(KERN_WARNING PFX "Heartbeat lost! Will not ping the watchdog\n");
}
}
/*
* Utility routines
*/
static void wdt_config(int writeval)
{
__u16 dummy;
unsigned long flags;
/* buy some time (ping) */
spin_lock_irqsave(&wdt_spinlock, flags);
dummy=readw(wdtmrctl); /* ensure write synchronization */
writew(0xAAAA, wdtmrctl);
writew(0x5555, wdtmrctl);
/* unlock WDT = make WDT configuration register writable one time */
writew(0x3333, wdtmrctl);
writew(0xCCCC, wdtmrctl);
/* write WDT configuration register */
writew(writeval, wdtmrctl);
spin_unlock_irqrestore(&wdt_spinlock, flags);
}
static int wdt_startup(void)
{
next_heartbeat = jiffies + (timeout * HZ);
/* Start the timer */
timer.expires = jiffies + WDT_INTERVAL;
add_timer(&timer);
/* Start the watchdog */
wdt_config(WDT_ENB | WDT_WRST_ENB | WDT_EXP_SEL_04);
printk(KERN_INFO PFX "Watchdog timer is now enabled.\n");
return 0;
}
static int wdt_turnoff(void)
{
/* Stop the timer */
del_timer(&timer);
/* Stop the watchdog */
wdt_config(0);
printk(KERN_INFO PFX "Watchdog timer is now disabled...\n");
return 0;
}
static int wdt_keepalive(void)
{
/* user land ping */
next_heartbeat = jiffies + (timeout * HZ);
return 0;
}
static int wdt_set_heartbeat(int t)
{
if ((t < 1) || (t > 3600)) /* arbitrary upper limit */
return -EINVAL;
timeout = t;
return 0;
}
/*
* /dev/watchdog handling
*/
static ssize_t fop_write(struct file * file, const char __user * buf, size_t count, loff_t * ppos)
{
/* See if we got the magic character 'V' and reload the timer */
if(count) {
if (!nowayout) {
size_t ofs;
/* note: just in case someone wrote the magic character
* five months ago... */
wdt_expect_close = 0;
/* now scan */
for(ofs = 0; ofs != count; ofs++) {
char c;
if (get_user(c, buf + ofs))
return -EFAULT;
if(c == 'V')
wdt_expect_close = 42;
}
}
/* Well, anyhow someone wrote to us, we should return that favour */
wdt_keepalive();
}
return count;
}
static int fop_open(struct inode * inode, struct file * file)
{
nonseekable_open(inode, file);
/* Just in case we're already talking to someone... */
if(test_and_set_bit(0, &wdt_is_open))
return -EBUSY;
if (nowayout)
__module_get(THIS_MODULE);
/* Good, fire up the show */
wdt_startup();
return 0;
}
static int fop_close(struct inode * inode, struct file * file)
{
if(wdt_expect_close == 42) {
wdt_turnoff();
} else {
printk(KERN_CRIT PFX "Unexpected close, not stopping watchdog!\n");
wdt_keepalive();
}
clear_bit(0, &wdt_is_open);
wdt_expect_close = 0;
return 0;
}
static int fop_ioctl(struct inode *inode, struct file *file, unsigned int cmd,
unsigned long arg)
{
void __user *argp = (void __user *)arg;
int __user *p = argp;
static struct watchdog_info ident = {
.options = WDIOF_KEEPALIVEPING | WDIOF_SETTIMEOUT | WDIOF_MAGICCLOSE,
.firmware_version = 1,
.identity = "SC520",
};
switch(cmd)
{
default:
return -ENOIOCTLCMD;
case WDIOC_GETSUPPORT:
return copy_to_user(argp, &ident, sizeof(ident))?-EFAULT:0;
case WDIOC_GETSTATUS:
case WDIOC_GETBOOTSTATUS:
return put_user(0, p);
case WDIOC_KEEPALIVE:
wdt_keepalive();
return 0;
case WDIOC_SETOPTIONS:
{
int new_options, retval = -EINVAL;
if(get_user(new_options, p))
return -EFAULT;
if(new_options & WDIOS_DISABLECARD) {
wdt_turnoff();
retval = 0;
}
if(new_options & WDIOS_ENABLECARD) {
wdt_startup();
retval = 0;
}
return retval;
}
case WDIOC_SETTIMEOUT:
{
int new_timeout;
if(get_user(new_timeout, p))
return -EFAULT;
if(wdt_set_heartbeat(new_timeout))
return -EINVAL;
wdt_keepalive();
/* Fall through */
}
case WDIOC_GETTIMEOUT:
return put_user(timeout, p);
}
}
static struct file_operations wdt_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.write = fop_write,
.open = fop_open,
.release = fop_close,
.ioctl = fop_ioctl,
};
static struct miscdevice wdt_miscdev = {
.minor = WATCHDOG_MINOR,
.name = "watchdog",
.fops = &wdt_fops,
};
/*
* Notifier for system down
*/
static int wdt_notify_sys(struct notifier_block *this, unsigned long code,
void *unused)
{
if(code==SYS_DOWN || code==SYS_HALT)
wdt_turnoff();
return NOTIFY_DONE;
}
/*
* The WDT needs to learn about soft shutdowns in order to
* turn the timebomb registers off.
*/
static struct notifier_block wdt_notifier = {
.notifier_call = wdt_notify_sys,
};
static void __exit sc520_wdt_unload(void)
{
if (!nowayout)
wdt_turnoff();
/* Deregister */
misc_deregister(&wdt_miscdev);
unregister_reboot_notifier(&wdt_notifier);
iounmap(wdtmrctl);
}
static int __init sc520_wdt_init(void)
{
int rc = -EBUSY;
spin_lock_init(&wdt_spinlock);
init_timer(&timer);
timer.function = wdt_timer_ping;
timer.data = 0;
/* Check that the timeout value is within it's range ; if not reset to the default */
if (wdt_set_heartbeat(timeout)) {
wdt_set_heartbeat(WATCHDOG_TIMEOUT);
printk(KERN_INFO PFX "timeout value must be 1<=timeout<=3600, using %d\n",
WATCHDOG_TIMEOUT);
}
wdtmrctl = ioremap((unsigned long)(MMCR_BASE + OFFS_WDTMRCTL), 2);
if (!wdtmrctl) {
printk(KERN_ERR PFX "Unable to remap memory\n");
rc = -ENOMEM;
goto err_out_region2;
}
rc = register_reboot_notifier(&wdt_notifier);
if (rc) {
printk(KERN_ERR PFX "cannot register reboot notifier (err=%d)\n",
rc);
goto err_out_ioremap;
}
rc = misc_register(&wdt_miscdev);
if (rc) {
printk(KERN_ERR PFX "cannot register miscdev on minor=%d (err=%d)\n",
WATCHDOG_MINOR, rc);
goto err_out_notifier;
}
printk(KERN_INFO PFX "WDT driver for SC520 initialised. timeout=%d sec (nowayout=%d)\n",
timeout,nowayout);
return 0;
err_out_notifier:
unregister_reboot_notifier(&wdt_notifier);
err_out_ioremap:
iounmap(wdtmrctl);
err_out_region2:
return rc;
}
module_init(sc520_wdt_init);
module_exit(sc520_wdt_unload);
MODULE_AUTHOR("Scott and Bill Jennings");
MODULE_DESCRIPTION("Driver for watchdog timer in AMD \"Elan\" SC520 uProcessor");
MODULE_LICENSE("GPL");
MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
| ipwndev/DSLinux-Mirror | linux-2.6.x/drivers/char/watchdog/sc520_wdt.c | C | gpl-2.0 | 11,394 |
# Copyright (C) 2010-2013 Zentyal S.L.
#
# 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
use strict;
use warnings;
package EBox::CGI::Wizard;
use base 'EBox::CGI::ClientBase';
use EBox::Global;
use EBox::Gettext;
sub new # (error=?, msg=?, cgi=?)
{
my $class = shift;
my $self = $class->SUPER::new('title' => __('Initial configuration wizard'),
'template' => 'wizard/wizard.mas',
@_);
bless($self, $class);
return $self;
}
sub _process
{
my $self = shift;
my @array = ();
my $global = EBox::Global->getInstance();
my $first = EBox::Global->first() ? '1' : '0';
my $image = $global->theme()->{'image_title'};
push (@array, image_title => $image);
my @pages;
if ($self->param('page')) {
@pages = ( $self->param('page') );
} else {
@pages = @{ $self->_modulesWizardPages() };
}
if (not @pages) {
if ($global->unsaved()) {
$self->{redirect} = "/SaveChanges?firstTime=$first&noPopup=1&save=1";
} else {
$self->{redirect} = "/Wizard/SoftwareSetupFinish?firstTime=$first";
}
return;
}
push(@array, 'pages' => \@pages);
push(@array, 'first' => $first);
$self->{params} = \@array;
}
# Method: _modulesWizardPages
#
# Returns an array ref with installed modules wizard pages
sub _modulesWizardPages
{
my $global = EBox::Global->getInstance();
my @pages = ();
my @modules = @{$global->modInstancesOfType('EBox::Module::Service')};
foreach my $module ( @modules ) {
if ($module->firstInstall()) {
push (@pages, @{$module->wizardPages()});
}
}
# Sort and get pages
my @sortedPages = sort { $a->{order} <=> $b->{order} } @pages;
@sortedPages = map { $_->{page} } @sortedPages;
return \@sortedPages;
}
sub _menu
{
my ($self) = @_;
if (EBox::Global->first() and EBox::Global->modExists('software')) {
my $software = EBox::Global->modInstance('software');
return $software->firstTimeMenu(3);
} else {
return $self->SUPER::_menu(@_);
}
}
sub _top
{
my ($self)= @_;
return $self->_topNoAction();
}
1;
| Zentyal/zentyal | main/core/src/EBox/CGI/Wizard.pm | Perl | gpl-2.0 | 2,778 |
//
// $Id$
//
//
// Copyright (c) 2001-2015, Andrew Aksyonoff
// Copyright (c) 2008-2015, Sphinx Technologies Inc
// 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. You should have
// received a copy of the GPL license along with this program; if you
// did not, you can find it at http://www.gnu.org/
//
#include "sphinx.h"
#include "sphinxint.h"
#include "sphinxjson.h"
#include <time.h>
#include <math.h>
#if !USE_WINDOWS
#include <unistd.h>
#include <sys/time.h>
#endif
//////////////////////////////////////////////////////////////////////////
// TRAITS
//////////////////////////////////////////////////////////////////////////
void ISphMatchSorter::SetState ( const CSphMatchComparatorState & tState )
{
m_tState = tState;
m_tState.m_iNow = (DWORD) time ( NULL );
}
/// groupby key type
typedef int64_t SphGroupKey_t;
/// base grouper (class that computes groupby key)
class CSphGrouper
{
public:
virtual ~CSphGrouper () {}
virtual SphGroupKey_t KeyFromValue ( SphAttr_t uValue ) const = 0;
virtual SphGroupKey_t KeyFromMatch ( const CSphMatch & tMatch ) const = 0;
virtual void GetLocator ( CSphAttrLocator & tOut ) const = 0;
virtual ESphAttr GetResultType () const = 0;
virtual void SetStringPool ( const BYTE * ) {}
virtual bool CanMulti () const { return true; }
};
static bool HasString ( const CSphMatchComparatorState * pState )
{
assert ( pState );
for ( int i=0; i<CSphMatchComparatorState::MAX_ATTRS; i++ )
{
if ( pState->m_eKeypart[i]==SPH_KEYPART_STRING || pState->m_eKeypart[i]==SPH_KEYPART_STRINGPTR || ( pState->m_tSubKeys[i].m_sKey.cstr() ) )
return true;
}
return false;
}
/// match-sorting priority queue traits
class CSphMatchQueueTraits : public ISphMatchSorter, ISphNoncopyable
{
protected:
CSphMatch * m_pData;
int m_iUsed;
int m_iSize;
const bool m_bUsesAttrs;
private:
int m_iAllocatedSize;
int m_iDataLength;
public:
/// ctor
CSphMatchQueueTraits ( int iSize, bool bUsesAttrs )
: m_iUsed ( 0 )
, m_iSize ( iSize )
, m_bUsesAttrs ( bUsesAttrs )
, m_iAllocatedSize ( iSize )
, m_iDataLength ( iSize )
{
assert ( iSize>0 );
m_pData = new CSphMatch [ m_iAllocatedSize ];
assert ( m_pData );
m_tState.m_iNow = (DWORD) time ( NULL );
}
/// dtor
~CSphMatchQueueTraits ()
{
for ( int i=0; i<m_iAllocatedSize; ++i )
m_tSchema.FreeStringPtrs ( m_pData+i );
SafeDeleteArray ( m_pData );
}
public:
bool UsesAttrs () const { return m_bUsesAttrs; }
virtual int GetLength () const { return m_iUsed; }
virtual int GetDataLength () const { return m_iDataLength; }
virtual bool CanMulti () const
{
return !HasString ( &m_tState );
}
};
//////////////////////////////////////////////////////////////////////////
// SORTING QUEUES
//////////////////////////////////////////////////////////////////////////
template < typename COMP >
struct CompareIndex_fn
{
const CSphMatch * m_pBase;
const CSphMatchComparatorState * m_pState;
CompareIndex_fn ( const CSphMatch * pBase, const CSphMatchComparatorState * pState )
: m_pBase ( pBase )
, m_pState ( pState )
{}
bool IsLess ( int a, int b ) const
{
return COMP::IsLess ( m_pBase[b], m_pBase[a], *m_pState );
}
};
/// heap sorter
/// plain binary heap based PQ
template < typename COMP, bool NOTIFICATIONS >
class CSphMatchQueue : public CSphMatchQueueTraits
{
public:
/// ctor
CSphMatchQueue ( int iSize, bool bUsesAttrs )
: CSphMatchQueueTraits ( iSize, bUsesAttrs )
{
if_const ( NOTIFICATIONS )
m_dJustPopped.Reserve(1);
}
/// check if this sorter does groupby
virtual bool IsGroupby () const
{
return false;
}
virtual const CSphMatch * GetWorst() const
{
return m_pData;
}
/// add entry to the queue
virtual bool Push ( const CSphMatch & tEntry )
{
m_iTotal++;
if_const ( NOTIFICATIONS )
{
m_iJustPushed = 0;
m_dJustPopped.Resize(0);
}
if ( m_iUsed==m_iSize )
{
// if it's worse that current min, reject it, else pop off current min
if ( COMP::IsLess ( tEntry, m_pData[0], m_tState ) )
return true;
else
Pop ();
}
// do add
m_tSchema.CloneMatch ( m_pData+m_iUsed, tEntry );
if_const ( NOTIFICATIONS )
m_iJustPushed = tEntry.m_uDocID;
int iEntry = m_iUsed++;
// sift up if needed, so that worst (lesser) ones float to the top
while ( iEntry )
{
int iParent = ( iEntry-1 ) >> 1;
if ( !COMP::IsLess ( m_pData[iEntry], m_pData[iParent], m_tState ) )
break;
// entry is less than parent, should float to the top
Swap ( m_pData[iEntry], m_pData[iParent] );
iEntry = iParent;
}
return true;
}
/// add grouped entry (must not happen)
virtual bool PushGrouped ( const CSphMatch &, bool )
{
assert ( 0 );
return false;
}
/// remove root (ie. top priority) entry
virtual void Pop ()
{
assert ( m_iUsed );
if ( !(--m_iUsed) ) // empty queue? just return
return;
// make the last entry my new root
Swap ( m_pData[0], m_pData[m_iUsed] );
m_tSchema.FreeStringPtrs ( &m_pData[m_iUsed] );
if_const ( NOTIFICATIONS )
{
if ( m_dJustPopped.GetLength() )
m_dJustPopped[0] = m_pData[m_iUsed].m_uDocID;
else
m_dJustPopped.Add ( m_pData[m_iUsed].m_uDocID );
}
// sift down if needed
int iEntry = 0;
for ( ;; )
{
// select child
int iChild = (iEntry<<1) + 1;
if ( iChild>=m_iUsed )
break;
// select smallest child
if ( iChild+1<m_iUsed )
if ( COMP::IsLess ( m_pData[iChild+1], m_pData[iChild], m_tState ) )
iChild++;
// if smallest child is less than entry, do float it to the top
if ( COMP::IsLess ( m_pData[iChild], m_pData[iEntry], m_tState ) )
{
Swap ( m_pData[iChild], m_pData[iEntry] );
iEntry = iChild;
continue;
}
break;
}
}
/// store all entries into specified location in sorted order, and remove them from queue
int Flatten ( CSphMatch * pTo, int iTag )
{
assert ( m_iUsed>=0 );
pTo += m_iUsed;
int iCopied = m_iUsed;
while ( m_iUsed>0 )
{
--pTo;
m_tSchema.FreeStringPtrs ( pTo );
Swap ( *pTo, *m_pData );
if ( iTag>=0 )
pTo->m_iTag = iTag;
Pop ();
}
m_iTotal = 0;
return iCopied;
}
void Finalize ( ISphMatchProcessor & tProcessor, bool bCallProcessInResultSetOrder )
{
if ( !GetLength() )
return;
if ( !bCallProcessInResultSetOrder )
{
// just evaluate in heap order
CSphMatch * pCur = m_pData;
const CSphMatch * pEnd = m_pData + m_iUsed;
while ( pCur<pEnd )
{
tProcessor.Process ( pCur++ );
}
} else
{
// means final-stage calls will be evaluated
// a) over the final, pre-limit result set
// b) in the final result set order
CSphFixedVector<int> dIndexes ( GetLength() );
ARRAY_FOREACH ( i, dIndexes )
dIndexes[i] = i;
sphSort ( dIndexes.Begin(), dIndexes.GetLength(), CompareIndex_fn<COMP> ( m_pData, &m_tState ) );
ARRAY_FOREACH ( i, dIndexes )
{
tProcessor.Process ( m_pData + dIndexes[i] );
}
}
}
};
//////////////////////////////////////////////////////////////////////////
/// match sorting functor
template < typename COMP >
struct MatchSort_fn : public MatchSortAccessor_t
{
CSphMatchComparatorState m_tState;
explicit MatchSort_fn ( const CSphMatchComparatorState & tState )
: m_tState ( tState )
{}
bool IsLess ( const MEDIAN_TYPE a, const MEDIAN_TYPE b )
{
return COMP::IsLess ( *a, *b, m_tState );
}
};
/// K-buffer (generalized double buffer) sorter
/// faster worst-case but slower average-case than the heap sorter
template < typename COMP, bool NOTIFICATIONS >
class CSphKbufferMatchQueue : public CSphMatchQueueTraits
{
protected:
static const int COEFF = 4;
CSphMatch * m_pEnd;
CSphMatch * m_pWorst;
bool m_bFinalized;
public:
/// ctor
CSphKbufferMatchQueue ( int iSize, bool bUsesAttrs )
: CSphMatchQueueTraits ( iSize*COEFF, bUsesAttrs )
, m_pEnd ( m_pData+iSize*COEFF )
, m_pWorst ( NULL )
, m_bFinalized ( false )
{
if_const ( NOTIFICATIONS )
m_dJustPopped.Reserve ( m_iSize );
m_iSize /= COEFF;
}
/// check if this sorter does groupby
virtual bool IsGroupby () const
{
return false;
}
/// add entry to the queue
virtual bool Push ( const CSphMatch & tEntry )
{
if_const ( NOTIFICATIONS )
{
m_iJustPushed = 0;
m_dJustPopped.Resize(0);
}
// quick early rejection checks
m_iTotal++;
if ( m_pWorst && COMP::IsLess ( tEntry, *m_pWorst, m_tState ) )
return true;
// quick check passed
// fill the data, back to front
m_bFinalized = false;
m_iUsed++;
m_tSchema.CloneMatch ( m_pEnd-m_iUsed, tEntry );
if_const ( NOTIFICATIONS )
m_iJustPushed = tEntry.m_uDocID;
// do the initial sort once
if ( m_iTotal==m_iSize )
{
assert ( m_iUsed==m_iSize && !m_pWorst );
MatchSort_fn<COMP> tComp ( m_tState );
sphSort ( m_pEnd-m_iSize, m_iSize, tComp, tComp );
m_pWorst = m_pEnd-m_iSize;
m_bFinalized = true;
return true;
}
// do the sort/cut when the K-buffer is full
if ( m_iUsed==m_iSize*COEFF )
{
MatchSort_fn<COMP> tComp ( m_tState );
sphSort ( m_pData, m_iUsed, tComp, tComp );
if_const ( NOTIFICATIONS )
{
for ( CSphMatch * pMatch = m_pData; pMatch < m_pEnd-m_iSize; pMatch++ )
m_dJustPopped.Add ( pMatch->m_uDocID );
}
m_iUsed = m_iSize;
m_pWorst = m_pEnd-m_iSize;
m_bFinalized = true;
}
return true;
}
/// add grouped entry (must not happen)
virtual bool PushGrouped ( const CSphMatch &, bool )
{
assert ( 0 );
return false;
}
/// finalize, perform final sort/cut as needed
virtual void Finalize ( ISphMatchProcessor & tProcessor, bool )
{
if ( !GetLength() )
return;
if ( !m_bFinalized )
{
MatchSort_fn<COMP> tComp ( m_tState );
sphSort ( m_pEnd-m_iUsed, m_iUsed, tComp, tComp );
m_iUsed = Min ( m_iUsed, m_iSize );
m_bFinalized = true;
}
// reverse order iteration
CSphMatch * pCur = m_pEnd - 1;
const CSphMatch * pEnd = m_pEnd - m_iUsed;
while ( pCur>=pEnd )
{
tProcessor.Process ( pCur-- );
}
}
/// current result set length
virtual int GetLength () const
{
return Min ( m_iUsed, m_iSize );
}
/// store all entries into specified location in sorted order, and remove them from queue
int Flatten ( CSphMatch * pTo, int iTag )
{
const CSphMatch * pBegin = pTo;
// ensure we are sorted
if ( m_iUsed )
{
MatchSort_fn<COMP> tComp ( m_tState );
sphSort ( m_pEnd-m_iUsed, m_iUsed, tComp, tComp );
}
// reverse copy
for ( int i=1; i<=Min ( m_iUsed, m_iSize ); i++ )
{
m_tSchema.FreeStringPtrs ( pTo );
Swap ( *pTo, m_pEnd[-i] );
if ( iTag>=0 )
pTo->m_iTag = iTag;
pTo++;
}
// clean up for the next work session
m_iTotal = 0;
m_iUsed = 0;
m_iSize = 0;
m_bFinalized = false;
return ( pTo-pBegin );
}
};
//////////////////////////////////////////////////////////////////////////
/// collector for UPDATE statement
class CSphUpdateQueue : public CSphMatchQueueTraits
{
CSphAttrUpdate m_tWorkSet;
CSphIndex * m_pIndex;
CSphString * m_pError;
CSphString * m_pWarning;
int * m_pAffected;
private:
void DoUpdate()
{
if ( !m_iUsed )
return;
m_tWorkSet.m_dRowOffset.Resize ( m_iUsed );
m_tWorkSet.m_dDocids.Resize ( m_iUsed );
m_tWorkSet.m_dRows.Resize ( m_iUsed );
ARRAY_FOREACH ( i, m_tWorkSet.m_dDocids )
{
m_tWorkSet.m_dRowOffset[i] = 0;
m_tWorkSet.m_dDocids[i] = 0;
m_tWorkSet.m_dRows[i] = NULL;
if ( !DOCINFO2ID ( STATIC2DOCINFO ( m_pData[i].m_pStatic ) ) ) // if static attributes were copied, so, they actually dynamic
{
m_tWorkSet.m_dDocids[i] = m_pData[i].m_uDocID;
} else // static attributes points to the active indexes - so, no lookup, 5 times faster update.
{
m_tWorkSet.m_dRows[i] = m_pData[i].m_pStatic - ( sizeof(SphDocID_t) / sizeof(CSphRowitem) );
}
}
*m_pAffected += m_pIndex->UpdateAttributes ( m_tWorkSet, -1, *m_pError, *m_pWarning );
m_iUsed = 0;
}
public:
/// ctor
CSphUpdateQueue ( int iSize, CSphAttrUpdateEx * pUpdate, bool bIgnoreNonexistent, bool bStrict )
: CSphMatchQueueTraits ( iSize, true )
{
m_tWorkSet.m_dRowOffset.Reserve ( m_iSize );
m_tWorkSet.m_dDocids.Reserve ( m_iSize );
m_tWorkSet.m_dRows.Reserve ( m_iSize );
m_tWorkSet.m_bIgnoreNonexistent = bIgnoreNonexistent;
m_tWorkSet.m_bStrict = bStrict;
m_tWorkSet.m_dTypes = pUpdate->m_pUpdate->m_dTypes;
m_tWorkSet.m_dPool = pUpdate->m_pUpdate->m_dPool;
m_tWorkSet.m_dAttrs.Resize ( pUpdate->m_pUpdate->m_dAttrs.GetLength() );
ARRAY_FOREACH ( i, m_tWorkSet.m_dAttrs )
{
CSphString sTmp;
sTmp = pUpdate->m_pUpdate->m_dAttrs[i];
m_tWorkSet.m_dAttrs[i] = sTmp.Leak();
}
m_pIndex = pUpdate->m_pIndex;
m_pError = pUpdate->m_pError;
m_pWarning = pUpdate->m_pWarning;
m_pAffected = &pUpdate->m_iAffected;
}
/// check if this sorter does groupby
virtual bool IsGroupby () const
{
return false;
}
/// add entry to the queue
virtual bool Push ( const CSphMatch & tEntry )
{
m_iTotal++;
if ( m_iUsed==m_iSize )
DoUpdate();
// do add
m_tSchema.CloneMatch ( &m_pData[m_iUsed++], tEntry );
return true;
}
/// add grouped entry (must not happen)
virtual bool PushGrouped ( const CSphMatch &, bool )
{
assert ( 0 );
return false;
}
/// store all entries into specified location in sorted order, and remove them from queue
int Flatten ( CSphMatch *, int )
{
assert ( m_iUsed>=0 );
DoUpdate();
m_iTotal = 0;
return 0;
}
virtual void Finalize ( ISphMatchProcessor & tProcessor, bool )
{
if ( !GetLength() )
return;
// just evaluate in heap order
CSphMatch * pCur = m_pData;
const CSphMatch * pEnd = m_pData + m_iUsed;
while ( pCur<pEnd )
{
tProcessor.Process ( pCur++ );
}
}
};
//////////////////////////////////////////////////////////////////////////
/// collector for DELETE statement
class CSphDeleteQueue : public CSphMatchQueueTraits
{
CSphVector<SphDocID_t>* m_pValues;
public:
/// ctor
CSphDeleteQueue ( int iSize, CSphVector<SphDocID_t> * pDeletes )
: CSphMatchQueueTraits ( 1, false )
, m_pValues ( pDeletes )
{
m_pValues->Reserve ( iSize );
}
/// check if this sorter does groupby
virtual bool IsGroupby () const
{
return false;
}
/// add entry to the queue
virtual bool Push ( const CSphMatch & tEntry )
{
m_iTotal++;
m_pValues->Add ( tEntry.m_uDocID );
return true;
}
/// add grouped entry (must not happen)
virtual bool PushGrouped ( const CSphMatch &, bool )
{
assert ( 0 );
return false;
}
/// store all entries into specified location in sorted order, and remove them from queue
int Flatten ( CSphMatch *, int )
{
m_iTotal = 0;
return 0;
}
virtual void Finalize ( ISphMatchProcessor &, bool )
{}
};
//////////////////////////////////////////////////////////////////////////
// SORTING+GROUPING QUEUE
//////////////////////////////////////////////////////////////////////////
static bool IsCount ( const CSphString & s )
{
return s=="@count" || s=="count(*)";
}
static bool IsGroupby ( const CSphString & s )
{
return s=="@groupby" || s=="@distinct" || s=="groupby()" || s=="@groupbystr";
}
static bool IsGroupbyMagic ( const CSphString & s )
{
return IsGroupby ( s ) || IsCount ( s );
}
/// groupers
#define GROUPER_BEGIN(_name) \
class _name : public CSphGrouper \
{ \
protected: \
CSphAttrLocator m_tLocator; \
public: \
explicit _name ( const CSphAttrLocator & tLoc ) : m_tLocator ( tLoc ) {} \
virtual void GetLocator ( CSphAttrLocator & tOut ) const { tOut = m_tLocator; } \
virtual ESphAttr GetResultType () const { return m_tLocator.m_iBitCount>8*(int)sizeof(DWORD) ? SPH_ATTR_BIGINT : SPH_ATTR_INTEGER; } \
virtual SphGroupKey_t KeyFromMatch ( const CSphMatch & tMatch ) const { return KeyFromValue ( tMatch.GetAttr ( m_tLocator ) ); } \
virtual SphGroupKey_t KeyFromValue ( SphAttr_t uValue ) const \
{
// NOLINT
#define GROUPER_END \
} \
};
#define GROUPER_BEGIN_SPLIT(_name) \
GROUPER_BEGIN(_name) \
time_t tStamp = (time_t)uValue; \
struct tm tSplit; \
localtime_r ( &tStamp, &tSplit );
GROUPER_BEGIN ( CSphGrouperAttr )
return uValue;
GROUPER_END
GROUPER_BEGIN_SPLIT ( CSphGrouperDay )
return (tSplit.tm_year+1900)*10000 + (1+tSplit.tm_mon)*100 + tSplit.tm_mday;
GROUPER_END
GROUPER_BEGIN_SPLIT ( CSphGrouperWeek )
int iPrevSunday = (1+tSplit.tm_yday) - tSplit.tm_wday; // prev Sunday day of year, base 1
int iYear = tSplit.tm_year+1900;
if ( iPrevSunday<=0 ) // check if we crossed year boundary
{
// adjust day and year
iPrevSunday += 365;
iYear--;
// adjust for leap years
if ( iYear%4==0 && ( iYear%100!=0 || iYear%400==0 ) )
iPrevSunday++;
}
return iYear*1000 + iPrevSunday;
GROUPER_END
GROUPER_BEGIN_SPLIT ( CSphGrouperMonth )
return (tSplit.tm_year+1900)*100 + (1+tSplit.tm_mon);
GROUPER_END
GROUPER_BEGIN_SPLIT ( CSphGrouperYear )
return (tSplit.tm_year+1900);
GROUPER_END
template <class PRED>
class CSphGrouperString : public CSphGrouperAttr, public PRED
{
protected:
const BYTE * m_pStringBase;
public:
explicit CSphGrouperString ( const CSphAttrLocator & tLoc )
: CSphGrouperAttr ( tLoc )
, m_pStringBase ( NULL )
{
}
virtual ESphAttr GetResultType () const
{
return SPH_ATTR_BIGINT;
}
virtual SphGroupKey_t KeyFromValue ( SphAttr_t uValue ) const
{
if ( !m_pStringBase || !uValue )
return 0;
const BYTE * pStr = NULL;
int iLen = sphUnpackStr ( m_pStringBase+uValue, &pStr );
if ( !pStr || !iLen )
return 0;
return PRED::Hash ( pStr, iLen );
}
virtual void SetStringPool ( const BYTE * pStrings )
{
m_pStringBase = pStrings;
}
virtual bool CanMulti () const { return false; }
};
class BinaryHash_fn
{
public:
uint64_t Hash ( const BYTE * pStr, int iLen, uint64_t uPrev=SPH_FNV64_SEED ) const
{
assert ( pStr && iLen );
return sphFNV64 ( pStr, iLen, uPrev );
}
};
template < typename T >
inline static char * FormatInt ( char sBuf[32], T v )
{
if_const ( sizeof(T)==4 && v==INT_MIN )
return strncpy ( sBuf, "-2147483648", 32 );
if_const ( sizeof(T)==8 && v==LLONG_MIN )
return strncpy ( sBuf, "-9223372036854775808", 32 );
bool s = ( v<0 );
if ( s )
v = -v;
char * p = sBuf+31;
*p = 0;
do
{
*--p = '0' + char ( v % 10 );
v /= 10;
} while ( v );
if ( s )
*--p = '-';
return p;
}
/// lookup JSON key, group by looked up value (used in CSphKBufferJsonGroupSorter)
class CSphGrouperJsonField : public CSphGrouper
{
protected:
CSphAttrLocator m_tLocator;
public:
ISphExpr * m_pExpr;
const BYTE * m_pStrings;
explicit CSphGrouperJsonField ( const CSphAttrLocator & tLoc, ISphExpr * pExpr )
: m_tLocator ( tLoc )
, m_pExpr ( pExpr )
, m_pStrings ( NULL )
{}
virtual ~CSphGrouperJsonField ()
{
SafeRelease ( m_pExpr );
}
virtual void SetStringPool ( const BYTE * pStrings )
{
m_pStrings = pStrings;
if ( m_pExpr )
m_pExpr->Command ( SPH_EXPR_SET_STRING_POOL, (void*)pStrings );
}
virtual void GetLocator ( CSphAttrLocator & tOut ) const
{
tOut = m_tLocator;
}
virtual ESphAttr GetResultType () const
{
return SPH_ATTR_BIGINT;
}
virtual SphGroupKey_t KeyFromMatch ( const CSphMatch & tMatch ) const
{
if ( !m_pExpr )
return SphGroupKey_t();
return m_pExpr->Int64Eval ( tMatch );
}
virtual SphGroupKey_t KeyFromValue ( SphAttr_t ) const { assert(0); return SphGroupKey_t(); }
};
template <class PRED>
class CSphGrouperMulti : public CSphGrouper, public PRED
{
public:
CSphGrouperMulti ( const CSphVector<CSphAttrLocator> & dLocators, const CSphVector<ESphAttr> & dAttrTypes, const CSphVector<ISphExpr *> & dJsonKeys )
: m_dLocators ( dLocators )
, m_dAttrTypes ( dAttrTypes )
, m_dJsonKeys ( dJsonKeys )
{
assert ( m_dLocators.GetLength()>1 );
assert ( m_dLocators.GetLength()==m_dAttrTypes.GetLength() && m_dLocators.GetLength()==dJsonKeys.GetLength() );
}
virtual ~CSphGrouperMulti ()
{
ARRAY_FOREACH ( i, m_dJsonKeys )
SafeDelete ( m_dJsonKeys[i] );
}
virtual SphGroupKey_t KeyFromMatch ( const CSphMatch & tMatch ) const
{
SphGroupKey_t tKey = SPH_FNV64_SEED;
for ( int i=0; i<m_dLocators.GetLength(); i++ )
{
SphAttr_t tAttr = tMatch.GetAttr ( m_dLocators[i] );
if ( m_dAttrTypes[i]==SPH_ATTR_STRING )
{
assert ( m_pStringBase );
const BYTE * pStr = NULL;
int iLen = sphUnpackStr ( m_pStringBase+tAttr, &pStr );
if ( !pStr || !iLen )
continue;
tKey = PRED::Hash ( pStr, iLen, tKey );
} else if ( m_dAttrTypes[i]==SPH_ATTR_JSON )
{
assert ( m_pStringBase );
const BYTE * pStr = NULL;
int iLen = sphUnpackStr ( m_pStringBase+tAttr, &pStr );
if ( !pStr || !iLen )
continue;
uint64_t uValue = m_dJsonKeys[i]->Int64Eval ( tMatch );
const BYTE * pValue = m_pStringBase + ( uValue & 0xffffffff );
ESphJsonType eRes = (ESphJsonType)( uValue >> 32 );
int i32Val;
int64_t i64Val;
double fVal;
switch ( eRes )
{
case JSON_STRING:
iLen = sphJsonUnpackInt ( &pValue );
tKey = sphFNV64 ( pValue, iLen, tKey );
break;
case JSON_INT32:
i32Val = sphJsonLoadInt ( &pValue );
tKey = sphFNV64 ( &i32Val, sizeof(i32Val), tKey );
break;
case JSON_INT64:
i64Val = sphJsonLoadBigint ( &pValue );
tKey = sphFNV64 ( &i64Val, sizeof(i64Val), tKey );
break;
case JSON_DOUBLE:
fVal = sphQW2D ( sphJsonLoadBigint ( &pValue ) );
tKey = sphFNV64 ( &fVal, sizeof(fVal), tKey );
break;
default:
break;
}
} else
tKey = sphFNV64 ( &tAttr, sizeof(SphAttr_t), tKey );
}
return tKey;
}
virtual void SetStringPool ( const BYTE * pStrings )
{
m_pStringBase = pStrings;
ARRAY_FOREACH ( i, m_dJsonKeys )
{
if ( m_dJsonKeys[i] )
m_dJsonKeys[i]->Command ( SPH_EXPR_SET_STRING_POOL, (void*)pStrings );
}
}
virtual SphGroupKey_t KeyFromValue ( SphAttr_t ) const { assert(0); return SphGroupKey_t(); }
virtual void GetLocator ( CSphAttrLocator & ) const { assert(0); }
virtual ESphAttr GetResultType() const { return SPH_ATTR_BIGINT; }
virtual bool CanMulti () const { return false; }
private:
CSphVector<CSphAttrLocator> m_dLocators;
CSphVector<ESphAttr> m_dAttrTypes;
const BYTE * m_pStringBase;
CSphVector<ISphExpr *> m_dJsonKeys;
};
//////////////////////////////////////////////////////////////////////////
/// simple fixed-size hash
/// doesn't keep the order
template < typename T, typename KEY, typename HASHFUNC >
class CSphFixedHash : ISphNoncopyable
{
protected:
static const int HASH_LIST_END = -1;
static const int HASH_DELETED = -2;
struct HashEntry_t
{
KEY m_tKey;
T m_tValue;
int m_iNext;
};
protected:
CSphVector<HashEntry_t> m_dEntries; ///< key-value pairs storage pool
CSphVector<int> m_dHash; ///< hash into m_dEntries pool
int m_iFree; ///< free pairs count
CSphVector<int> m_dFree; ///< free pair indexes
public:
/// ctor
explicit CSphFixedHash ( int iLength )
{
int iBuckets = ( 2 << sphLog2 ( iLength-1 ) ); // less than 50% bucket usage guaranteed
assert ( iLength>0 );
assert ( iLength<=iBuckets );
m_dEntries.Resize ( iLength );
m_dHash.Resize ( iBuckets );
m_dFree.Resize ( iLength );
Reset ();
}
/// cleanup
void Reset ()
{
ARRAY_FOREACH ( i, m_dEntries )
m_dEntries[i].m_iNext = HASH_DELETED;
ARRAY_FOREACH ( i, m_dHash )
m_dHash[i] = HASH_LIST_END;
m_iFree = m_dFree.GetLength();
ARRAY_FOREACH ( i, m_dFree )
m_dFree[i] = i;
}
/// add new entry
/// returns NULL on success
/// returns pointer to value if already hashed, or replace it with new one, if insisted.
T * Add ( const T & tValue, const KEY & tKey, bool bReplace=false )
{
assert ( m_iFree>0 && "hash overflow" );
// check if it's already hashed
DWORD uHash = DWORD ( HASHFUNC::Hash ( tKey ) ) & ( m_dHash.GetLength()-1 );
int iPrev = -1, iEntry;
for ( iEntry=m_dHash[uHash]; iEntry>=0; iPrev=iEntry, iEntry=m_dEntries[iEntry].m_iNext )
if ( m_dEntries[iEntry].m_tKey==tKey )
{
if ( bReplace )
m_dEntries[iEntry].m_tValue = tValue;
return &m_dEntries[iEntry].m_tValue;
}
assert ( iEntry!=HASH_DELETED );
// if it's not, do add
int iNew = m_dFree [ --m_iFree ];
HashEntry_t & tNew = m_dEntries[iNew];
assert ( tNew.m_iNext==HASH_DELETED );
tNew.m_tKey = tKey;
tNew.m_tValue = tValue;
tNew.m_iNext = HASH_LIST_END;
if ( iPrev>=0 )
{
assert ( m_dEntries[iPrev].m_iNext==HASH_LIST_END );
m_dEntries[iPrev].m_iNext = iNew;
} else
{
assert ( m_dHash[uHash]==HASH_LIST_END );
m_dHash[uHash] = iNew;
}
return NULL;
}
/// remove entry from hash
void Remove ( const KEY & tKey )
{
// check if it's already hashed
DWORD uHash = DWORD ( HASHFUNC::Hash ( tKey ) ) & ( m_dHash.GetLength()-1 );
int iPrev = -1, iEntry;
for ( iEntry=m_dHash[uHash]; iEntry>=0; iPrev=iEntry, iEntry=m_dEntries[iEntry].m_iNext )
if ( m_dEntries[iEntry].m_tKey==tKey )
{
// found, remove it
assert ( m_dEntries[iEntry].m_iNext!=HASH_DELETED );
if ( iPrev>=0 )
m_dEntries[iPrev].m_iNext = m_dEntries[iEntry].m_iNext;
else
m_dHash[uHash] = m_dEntries[iEntry].m_iNext;
#ifndef NDEBUG
m_dEntries[iEntry].m_iNext = HASH_DELETED;
#endif
m_dFree [ m_iFree++ ] = iEntry;
return;
}
assert ( iEntry!=HASH_DELETED );
}
/// get value pointer by key
T * operator () ( const KEY & tKey ) const
{
DWORD uHash = DWORD ( HASHFUNC::Hash ( tKey ) ) & ( m_dHash.GetLength()-1 );
int iEntry;
for ( iEntry=m_dHash[uHash]; iEntry>=0; iEntry=m_dEntries[iEntry].m_iNext )
if ( m_dEntries[iEntry].m_tKey==tKey )
return (T*)&m_dEntries[iEntry].m_tValue;
assert ( iEntry!=HASH_DELETED );
return NULL;
}
};
/////////////////////////////////////////////////////////////////////////////
/// (group,attrvalue) pair
struct SphGroupedValue_t
{
public:
SphGroupKey_t m_uGroup;
SphAttr_t m_uValue;
int m_iCount;
public:
SphGroupedValue_t ()
{}
SphGroupedValue_t ( SphGroupKey_t uGroup, SphAttr_t uValue, int iCount )
: m_uGroup ( uGroup )
, m_uValue ( uValue )
, m_iCount ( iCount )
{}
inline bool operator < ( const SphGroupedValue_t & rhs ) const
{
if ( m_uGroup!=rhs.m_uGroup ) return m_uGroup<rhs.m_uGroup;
if ( m_uValue!=rhs.m_uValue ) return m_uValue<rhs.m_uValue;
return m_iCount>rhs.m_iCount;
}
inline bool operator == ( const SphGroupedValue_t & rhs ) const
{
return m_uGroup==rhs.m_uGroup && m_uValue==rhs.m_uValue;
}
};
/// same as SphGroupedValue_t but without group
struct SphUngroupedValue_t
{
public:
SphAttr_t m_uValue;
int m_iCount;
public:
SphUngroupedValue_t ()
{}
SphUngroupedValue_t ( SphAttr_t uValue, int iCount )
: m_uValue ( uValue )
, m_iCount ( iCount )
{}
inline bool operator < ( const SphUngroupedValue_t & rhs ) const
{
if ( m_uValue!=rhs.m_uValue ) return m_uValue<rhs.m_uValue;
return m_iCount>rhs.m_iCount;
}
inline bool operator == ( const SphUngroupedValue_t & rhs ) const
{
return m_uValue==rhs.m_uValue;
}
};
/// unique values counter
/// used for COUNT(DISTINCT xxx) GROUP BY yyy queries
class CSphUniqounter : public CSphVector<SphGroupedValue_t>
{
public:
#ifndef NDEBUG
CSphUniqounter () : m_iCountPos ( 0 ), m_bSorted ( true ) { Reserve ( 16384 ); }
void Add ( const SphGroupedValue_t & tValue ) { CSphVector<SphGroupedValue_t>::Add ( tValue ); m_bSorted = false; }
void Sort () { CSphVector<SphGroupedValue_t>::Sort (); m_bSorted = true; }
#else
CSphUniqounter () : m_iCountPos ( 0 ) {}
#endif
public:
int CountStart ( SphGroupKey_t * pOutGroup ); ///< starting counting distinct values, returns count and group key (0 if empty)
int CountNext ( SphGroupKey_t * pOutGroup ); ///< continues counting distinct values, returns count and group key (0 if done)
void Compact ( SphGroupKey_t * pRemoveGroups, int iRemoveGroups );
protected:
int m_iCountPos;
#ifndef NDEBUG
bool m_bSorted;
#endif
};
int CSphUniqounter::CountStart ( SphGroupKey_t * pOutGroup )
{
m_iCountPos = 0;
return CountNext ( pOutGroup );
}
int CSphUniqounter::CountNext ( SphGroupKey_t * pOutGroup )
{
assert ( m_bSorted );
if ( m_iCountPos>=m_iLength )
return 0;
SphGroupKey_t uGroup = m_pData[m_iCountPos].m_uGroup;
SphAttr_t uValue = m_pData[m_iCountPos].m_uValue;
int iCount = m_pData[m_iCountPos].m_iCount;
*pOutGroup = uGroup;
while ( m_iCountPos<m_iLength && m_pData[m_iCountPos].m_uGroup==uGroup )
{
if ( m_pData[m_iCountPos].m_uValue!=uValue )
iCount += m_pData[m_iCountPos].m_iCount;
uValue = m_pData[m_iCountPos].m_uValue;
m_iCountPos++;
}
return iCount;
}
void CSphUniqounter::Compact ( SphGroupKey_t * pRemoveGroups, int iRemoveGroups )
{
assert ( m_bSorted );
if ( !m_iLength )
return;
sphSort ( pRemoveGroups, iRemoveGroups );
SphGroupedValue_t * pSrc = m_pData;
SphGroupedValue_t * pDst = m_pData;
SphGroupedValue_t * pEnd = m_pData + m_iLength;
// skip remove-groups which are not in my list
while ( iRemoveGroups && (*pRemoveGroups)<pSrc->m_uGroup )
{
pRemoveGroups++;
iRemoveGroups--;
}
for ( ; pSrc<pEnd; pSrc++ )
{
// check if this entry needs to be removed
while ( iRemoveGroups && (*pRemoveGroups)<pSrc->m_uGroup )
{
pRemoveGroups++;
iRemoveGroups--;
}
if ( iRemoveGroups && pSrc->m_uGroup==*pRemoveGroups )
continue;
// check if it's a dupe
if ( pDst>m_pData && pDst[-1]==pSrc[0] )
continue;
*pDst++ = *pSrc;
}
assert ( pDst-m_pData<=m_iLength );
m_iLength = pDst-m_pData;
}
/////////////////////////////////////////////////////////////////////////////
/// attribute magic
enum
{
SPH_VATTR_ID = -1, ///< tells match sorter to use doc id
SPH_VATTR_RELEVANCE = -2, ///< tells match sorter to use match weight
SPH_VATTR_FLOAT = 10000 ///< tells match sorter to compare floats
};
/// match comparator interface from group-by sorter point of view
struct ISphMatchComparator
{
virtual ~ISphMatchComparator () {}
virtual bool VirtualIsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & tState ) const = 0;
};
/// additional group-by sorter settings
struct CSphGroupSorterSettings
{
CSphAttrLocator m_tLocGroupby; ///< locator for @groupby
CSphAttrLocator m_tLocCount; ///< locator for @count
CSphAttrLocator m_tLocDistinct; ///< locator for @distinct
CSphAttrLocator m_tDistinctLoc; ///< locator for attribute to compute count(distinct) for
bool m_bDistinct; ///< whether we need distinct
bool m_bMVA; ///< whether we're grouping by MVA attribute
bool m_bMva64;
CSphGrouper * m_pGrouper; ///< group key calculator
bool m_bImplicit; ///< for queries with aggregate functions but without group by clause
const ISphFilter * m_pAggrFilterTrait; ///< aggregate filter that got owned by grouper
bool m_bJson; ///< whether we're grouping by Json attribute
CSphAttrLocator m_tLocGroupbyStr; ///< locator for @groupbystr
CSphGroupSorterSettings ()
: m_bDistinct ( false )
, m_bMVA ( false )
, m_bMva64 ( false )
, m_pGrouper ( NULL )
, m_bImplicit ( false )
, m_pAggrFilterTrait ( NULL )
, m_bJson ( false )
{}
};
/// aggregate function interface
class IAggrFunc
{
public:
virtual ~IAggrFunc() {}
virtual void Ungroup ( CSphMatch * ) {}
virtual void Update ( CSphMatch * pDst, const CSphMatch * pSrc, bool bGrouped ) = 0;
virtual void Finalize ( CSphMatch * ) {}
};
/// aggregate traits for different attribute types
template < typename T >
class IAggrFuncTraits : public IAggrFunc
{
public:
explicit IAggrFuncTraits ( const CSphAttrLocator & tLocator ) : m_tLocator ( tLocator ) {}
inline T GetValue ( const CSphMatch * pRow );
inline void SetValue ( CSphMatch * pRow, T val );
protected:
CSphAttrLocator m_tLocator;
};
template<>
DWORD IAggrFuncTraits<DWORD>::GetValue ( const CSphMatch * pRow )
{
return (DWORD)pRow->GetAttr ( m_tLocator );
}
template<>
void IAggrFuncTraits<DWORD>::SetValue ( CSphMatch * pRow, DWORD val )
{
pRow->SetAttr ( m_tLocator, val );
}
template<>
int64_t IAggrFuncTraits<int64_t>::GetValue ( const CSphMatch * pRow )
{
return pRow->GetAttr ( m_tLocator );
}
template<>
void IAggrFuncTraits<int64_t>::SetValue ( CSphMatch * pRow, int64_t val )
{
pRow->SetAttr ( m_tLocator, val );
}
template<>
float IAggrFuncTraits<float>::GetValue ( const CSphMatch * pRow )
{
return pRow->GetAttrFloat ( m_tLocator );
}
template<>
void IAggrFuncTraits<float>::SetValue ( CSphMatch * pRow, float val )
{
pRow->SetAttrFloat ( m_tLocator, val );
}
/// SUM() implementation
template < typename T >
class AggrSum_t : public IAggrFuncTraits<T>
{
public:
explicit AggrSum_t ( const CSphAttrLocator & tLoc ) : IAggrFuncTraits<T> ( tLoc )
{}
virtual void Update ( CSphMatch * pDst, const CSphMatch * pSrc, bool )
{
this->SetValue ( pDst, this->GetValue(pDst)+this->GetValue(pSrc) );
}
};
/// AVG() implementation
template < typename T >
class AggrAvg_t : public IAggrFuncTraits<T>
{
protected:
CSphAttrLocator m_tCountLoc;
public:
AggrAvg_t ( const CSphAttrLocator & tLoc, const CSphAttrLocator & tCountLoc ) : IAggrFuncTraits<T> ( tLoc ), m_tCountLoc ( tCountLoc )
{}
virtual void Ungroup ( CSphMatch * pDst )
{
this->SetValue ( pDst, T ( this->GetValue ( pDst ) * pDst->GetAttr ( m_tCountLoc ) ) );
}
virtual void Update ( CSphMatch * pDst, const CSphMatch * pSrc, bool bGrouped )
{
if ( bGrouped )
this->SetValue ( pDst, T ( this->GetValue ( pDst ) + this->GetValue ( pSrc ) * pSrc->GetAttr ( m_tCountLoc ) ) );
else
this->SetValue ( pDst, this->GetValue ( pDst ) + this->GetValue ( pSrc ) );
}
virtual void Finalize ( CSphMatch * pDst )
{
this->SetValue ( pDst, T ( this->GetValue ( pDst ) / pDst->GetAttr ( m_tCountLoc ) ) );
}
};
/// MAX() implementation
template < typename T >
class AggrMax_t : public IAggrFuncTraits<T>
{
public:
explicit AggrMax_t ( const CSphAttrLocator & tLoc ) : IAggrFuncTraits<T> ( tLoc )
{}
virtual void Update ( CSphMatch * pDst, const CSphMatch * pSrc, bool )
{
this->SetValue ( pDst, Max ( this->GetValue(pDst), this->GetValue(pSrc) ) );
}
};
/// MIN() implementation
template < typename T >
class AggrMin_t : public IAggrFuncTraits<T>
{
public:
explicit AggrMin_t ( const CSphAttrLocator & tLoc ) : IAggrFuncTraits<T> ( tLoc )
{}
virtual void Update ( CSphMatch * pDst, const CSphMatch * pSrc, bool )
{
this->SetValue ( pDst, Min ( this->GetValue(pDst), this->GetValue(pSrc) ) );
}
};
/// GROUP_CONCAT() implementation
class AggrConcat_t : public IAggrFunc
{
protected:
CSphAttrLocator m_tLoc;
public:
explicit AggrConcat_t ( const CSphColumnInfo & tCol )
: m_tLoc ( tCol.m_tLocator )
{}
void Ungroup ( CSphMatch * ) {}
void Finalize ( CSphMatch * ) {}
void Update ( CSphMatch * pDst, const CSphMatch * pSrc, bool )
{
const char * sDst = (const char*) pDst->GetAttr(m_tLoc);
const char * sSrc = (const char*) pSrc->GetAttr(m_tLoc);
assert ( !sDst || *sDst ); // ensure the string is either NULL, or has data
assert ( !sSrc || *sSrc );
// empty source? kinda weird, but done!
if ( !sSrc )
return;
// empty destination? just clone the source
if ( !sDst )
{
if ( sSrc )
pDst->SetAttr ( m_tLoc, (SphAttr_t)strdup(sSrc) );
return;
}
// both source and destination present? append source to destination
// note that it gotta be manual copying here, as SetSprintf (currently) comes with a 1K limit
assert ( sDst && sSrc );
int iSrc = strlen ( sSrc );
int iDst = strlen ( sDst );
char * sNew = new char [ iSrc+iDst+2 ]; // OPTIMIZE? careful pre-reserve and/or realloc would be even faster
memcpy ( sNew, sDst, iDst );
sNew [ iDst ] = ',';
memcpy ( sNew+iDst+1, sSrc, iSrc );
sNew [ iSrc+iDst+1 ] = '\0';
pDst->SetAttr ( m_tLoc, (SphAttr_t)sNew );
SafeDeleteArray ( sDst );
}
};
/// group sorting functor
template < typename COMPGROUP >
struct GroupSorter_fn : public CSphMatchComparatorState, public MatchSortAccessor_t
{
bool IsLess ( const MEDIAN_TYPE a, const MEDIAN_TYPE b ) const
{
return COMPGROUP::IsLess ( *b, *a, *this );
}
};
struct MatchCloner_t
{
CSphFixedVector<CSphRowitem> m_dRowBuf;
CSphVector<CSphAttrLocator> m_dAttrsRaw;
CSphVector<CSphAttrLocator> m_dAttrsPtr;
const CSphRsetSchema * m_pSchema;
MatchCloner_t ()
: m_dRowBuf ( 0 )
, m_pSchema ( NULL )
{ }
void SetSchema ( const CSphRsetSchema * pSchema )
{
m_pSchema = pSchema;
m_dRowBuf.Reset ( m_pSchema->GetDynamicSize() );
}
void Combine ( CSphMatch * pDst, const CSphMatch * pSrc, const CSphMatch * pGroup )
{
assert ( m_pSchema && pDst && pSrc && pGroup );
assert ( pDst!=pGroup );
m_pSchema->CloneMatch ( pDst, *pSrc );
ARRAY_FOREACH ( i, m_dAttrsRaw )
{
pDst->SetAttr ( m_dAttrsRaw[i], pGroup->GetAttr ( m_dAttrsRaw[i] ) );
}
ARRAY_FOREACH ( i, m_dAttrsPtr )
{
assert ( !pDst->GetAttr ( m_dAttrsPtr[i] ) );
const char * sSrc = (const char*)pGroup->GetAttr ( m_dAttrsPtr[i] );
const char * sDst = NULL;
if ( sSrc && *sSrc )
sDst = strdup(sSrc);
pDst->SetAttr ( m_dAttrsPtr[i], (SphAttr_t)sDst );
}
}
void Clone ( CSphMatch * pOld, const CSphMatch * pNew )
{
assert ( m_pSchema && pOld && pNew );
if ( pOld->m_pDynamic==NULL ) // no old match has no data to copy, just a fresh but old match
{
m_pSchema->CloneMatch ( pOld, *pNew );
return;
}
memcpy ( m_dRowBuf.Begin(), pOld->m_pDynamic, sizeof(m_dRowBuf[0]) * m_dRowBuf.GetLength() );
// don't let cloning operation to free old string data
// as it will be copied back
ARRAY_FOREACH ( i, m_dAttrsPtr )
pOld->SetAttr ( m_dAttrsPtr[i], 0 );
m_pSchema->CloneMatch ( pOld, *pNew );
ARRAY_FOREACH ( i, m_dAttrsRaw )
pOld->SetAttr ( m_dAttrsRaw[i], sphGetRowAttr ( m_dRowBuf.Begin(), m_dAttrsRaw[i] ) );
ARRAY_FOREACH ( i, m_dAttrsPtr )
pOld->SetAttr ( m_dAttrsPtr[i], sphGetRowAttr ( m_dRowBuf.Begin(), m_dAttrsPtr[i] ) );
}
};
static void ExtractAggregates ( const CSphRsetSchema & tSchema, const CSphAttrLocator & tLocCount, const ESphSortKeyPart * m_pGroupSorterKeyparts, const CSphAttrLocator * m_pGroupSorterLocator,
CSphVector<IAggrFunc *> & dAggregates, CSphVector<IAggrFunc *> & dAvgs, MatchCloner_t & tCloner )
{
for ( int i=0; i<tSchema.GetAttrsCount(); i++ )
{
const CSphColumnInfo & tAttr = tSchema.GetAttr(i);
bool bMagicAggr = IsGroupbyMagic ( tAttr.m_sName ) || sphIsSortStringInternal ( tAttr.m_sName.cstr() ); // magic legacy aggregates
if ( tAttr.m_eAggrFunc==SPH_AGGR_NONE || bMagicAggr )
continue;
switch ( tAttr.m_eAggrFunc )
{
case SPH_AGGR_SUM:
switch ( tAttr.m_eAttrType )
{
case SPH_ATTR_INTEGER: dAggregates.Add ( new AggrSum_t<DWORD> ( tAttr.m_tLocator ) ); break;
case SPH_ATTR_BIGINT: dAggregates.Add ( new AggrSum_t<int64_t> ( tAttr.m_tLocator ) ); break;
case SPH_ATTR_FLOAT: dAggregates.Add ( new AggrSum_t<float> ( tAttr.m_tLocator ) ); break;
default: assert ( 0 && "internal error: unhandled aggregate type" ); break;
}
break;
case SPH_AGGR_AVG:
switch ( tAttr.m_eAttrType )
{
case SPH_ATTR_INTEGER: dAggregates.Add ( new AggrAvg_t<DWORD> ( tAttr.m_tLocator, tLocCount ) ); break;
case SPH_ATTR_BIGINT: dAggregates.Add ( new AggrAvg_t<int64_t> ( tAttr.m_tLocator, tLocCount ) ); break;
case SPH_ATTR_FLOAT: dAggregates.Add ( new AggrAvg_t<float> ( tAttr.m_tLocator, tLocCount ) ); break;
default: assert ( 0 && "internal error: unhandled aggregate type" ); break;
}
// store avg to calculate these attributes prior to groups sort
for ( int iState=0; iState<CSphMatchComparatorState::MAX_ATTRS; iState++ )
{
ESphSortKeyPart eKeypart = m_pGroupSorterKeyparts[iState];
CSphAttrLocator tLoc = m_pGroupSorterLocator[iState];
if ( ( eKeypart==SPH_KEYPART_INT || eKeypart==SPH_KEYPART_FLOAT )
&& tLoc.m_bDynamic==tAttr.m_tLocator.m_bDynamic && tLoc.m_iBitOffset==tAttr.m_tLocator.m_iBitOffset
&& tLoc.m_iBitCount==tAttr.m_tLocator.m_iBitCount )
{
dAvgs.Add ( dAggregates.Last() );
break;
}
}
break;
case SPH_AGGR_MIN:
switch ( tAttr.m_eAttrType )
{
case SPH_ATTR_INTEGER: dAggregates.Add ( new AggrMin_t<DWORD> ( tAttr.m_tLocator ) ); break;
case SPH_ATTR_BIGINT: dAggregates.Add ( new AggrMin_t<int64_t> ( tAttr.m_tLocator ) ); break;
case SPH_ATTR_FLOAT: dAggregates.Add ( new AggrMin_t<float> ( tAttr.m_tLocator ) ); break;
default: assert ( 0 && "internal error: unhandled aggregate type" ); break;
}
break;
case SPH_AGGR_MAX:
switch ( tAttr.m_eAttrType )
{
case SPH_ATTR_INTEGER: dAggregates.Add ( new AggrMax_t<DWORD> ( tAttr.m_tLocator ) ); break;
case SPH_ATTR_BIGINT: dAggregates.Add ( new AggrMax_t<int64_t> ( tAttr.m_tLocator ) ); break;
case SPH_ATTR_FLOAT: dAggregates.Add ( new AggrMax_t<float> ( tAttr.m_tLocator ) ); break;
default: assert ( 0 && "internal error: unhandled aggregate type" ); break;
}
break;
case SPH_AGGR_CAT:
dAggregates.Add ( new AggrConcat_t ( tAttr ) );
break;
default:
assert ( 0 && "internal error: unhandled aggregate function" );
break;
}
if ( tAttr.m_eAggrFunc==SPH_AGGR_CAT )
tCloner.m_dAttrsPtr.Add ( tAttr.m_tLocator );
else
tCloner.m_dAttrsRaw.Add ( tAttr.m_tLocator );
}
}
/// match sorter with k-buffering and group-by
template < typename COMPGROUP, bool DISTINCT, bool NOTIFICATIONS >
class CSphKBufferGroupSorter : public CSphMatchQueueTraits, protected CSphGroupSorterSettings
{
protected:
ESphGroupBy m_eGroupBy; ///< group-by function
CSphGrouper * m_pGrouper;
CSphFixedHash < CSphMatch *, SphGroupKey_t, IdentityHash_fn > m_hGroup2Match;
protected:
int m_iLimit; ///< max matches to be retrieved
CSphUniqounter m_tUniq;
bool m_bSortByDistinct;
GroupSorter_fn<COMPGROUP> m_tGroupSorter;
const ISphMatchComparator * m_pComp;
CSphVector<IAggrFunc *> m_dAggregates;
CSphVector<IAggrFunc *> m_dAvgs;
const ISphFilter * m_pAggrFilter; ///< aggregate filter for matches on flatten
MatchCloner_t m_tPregroup;
static const int GROUPBY_FACTOR = 4; ///< allocate this times more storage when doing group-by (k, as in k-buffer)
public:
/// ctor
CSphKBufferGroupSorter ( const ISphMatchComparator * pComp, const CSphQuery * pQuery, const CSphGroupSorterSettings & tSettings ) // FIXME! make k configurable
: CSphMatchQueueTraits ( pQuery->m_iMaxMatches*GROUPBY_FACTOR, true )
, CSphGroupSorterSettings ( tSettings )
, m_eGroupBy ( pQuery->m_eGroupFunc )
, m_pGrouper ( tSettings.m_pGrouper )
, m_hGroup2Match ( pQuery->m_iMaxMatches*GROUPBY_FACTOR )
, m_iLimit ( pQuery->m_iMaxMatches )
, m_bSortByDistinct ( false )
, m_pComp ( pComp )
, m_pAggrFilter ( tSettings.m_pAggrFilterTrait )
{
assert ( GROUPBY_FACTOR>1 );
assert ( DISTINCT==false || tSettings.m_tDistinctLoc.m_iBitOffset>=0 );
if_const ( NOTIFICATIONS )
m_dJustPopped.Reserve ( m_iSize );
}
/// schema setup
virtual void SetSchema ( CSphRsetSchema & tSchema )
{
m_tSchema = tSchema;
m_tPregroup.SetSchema ( &m_tSchema );
m_tPregroup.m_dAttrsRaw.Add ( m_tLocGroupby );
m_tPregroup.m_dAttrsRaw.Add ( m_tLocCount );
if_const ( DISTINCT )
{
m_tPregroup.m_dAttrsRaw.Add ( m_tLocDistinct );
}
ExtractAggregates ( m_tSchema, m_tLocCount, m_tGroupSorter.m_eKeypart, m_tGroupSorter.m_tLocator, m_dAggregates, m_dAvgs, m_tPregroup );
}
/// dtor
~CSphKBufferGroupSorter ()
{
SafeDelete ( m_pComp );
SafeDelete ( m_pGrouper );
SafeDelete ( m_pAggrFilter );
ARRAY_FOREACH ( i, m_dAggregates )
SafeDelete ( m_dAggregates[i] );
}
/// check if this sorter does groupby
virtual bool IsGroupby () const
{
return true;
}
virtual bool CanMulti () const
{
if ( m_pGrouper && !m_pGrouper->CanMulti() )
return false;
if ( HasString ( &m_tState ) )
return false;
if ( HasString ( &m_tGroupSorter ) )
return false;
return true;
}
/// set string pool pointer (for string+groupby sorters)
void SetStringPool ( const BYTE * pStrings )
{
m_pGrouper->SetStringPool ( pStrings );
}
/// add entry to the queue
virtual bool Push ( const CSphMatch & tEntry )
{
SphGroupKey_t uGroupKey = m_pGrouper->KeyFromMatch ( tEntry );
return PushEx ( tEntry, uGroupKey, false, false );
}
/// add grouped entry to the queue
virtual bool PushGrouped ( const CSphMatch & tEntry, bool )
{
return PushEx ( tEntry, tEntry.GetAttr ( m_tLocGroupby ), true, false );
}
/// add entry to the queue
virtual bool PushEx ( const CSphMatch & tEntry, const SphGroupKey_t uGroupKey, bool bGrouped, bool, SphAttr_t * pAttr=NULL )
{
if_const ( NOTIFICATIONS )
{
m_iJustPushed = 0;
m_dJustPopped.Resize(0);
}
// if this group is already hashed, we only need to update the corresponding match
CSphMatch ** ppMatch = m_hGroup2Match ( uGroupKey );
if ( ppMatch )
{
CSphMatch * pMatch = (*ppMatch);
assert ( pMatch );
assert ( pMatch->GetAttr ( m_tLocGroupby )==uGroupKey );
assert ( pMatch->m_pDynamic[-1]==tEntry.m_pDynamic[-1] );
if ( bGrouped )
{
// it's already grouped match
// sum grouped matches count
pMatch->SetAttr ( m_tLocCount, pMatch->GetAttr ( m_tLocCount ) + tEntry.GetAttr ( m_tLocCount ) ); // OPTIMIZE! AddAttr()?
} else
{
// it's a simple match
// increase grouped matches count
pMatch->SetAttr ( m_tLocCount, 1 + pMatch->GetAttr ( m_tLocCount ) ); // OPTIMIZE! IncAttr()?
}
// update aggregates
ARRAY_FOREACH ( i, m_dAggregates )
m_dAggregates[i]->Update ( pMatch, &tEntry, bGrouped );
// if new entry is more relevant, update from it
if ( m_pComp->VirtualIsLess ( *pMatch, tEntry, m_tState ) )
{
if_const ( NOTIFICATIONS )
{
m_iJustPushed = tEntry.m_uDocID;
m_dJustPopped.Add ( pMatch->m_uDocID );
}
// clone the low part of the match
m_tPregroup.Clone ( pMatch, &tEntry );
// update @groupbystr value, if available
if ( pAttr && m_tLocGroupbyStr.m_bDynamic )
pMatch->SetAttr ( m_tLocGroupbyStr, *pAttr );
}
}
// submit actual distinct value in all cases
if_const ( DISTINCT )
{
int iCount = 1;
if ( bGrouped )
iCount = (int)tEntry.GetAttr ( m_tLocDistinct );
m_tUniq.Add ( SphGroupedValue_t ( uGroupKey, tEntry.GetAttr ( m_tDistinctLoc ), iCount ) ); // OPTIMIZE! use simpler locator here?
}
// it's a dupe anyway, so we shouldn't update total matches count
if ( ppMatch )
return false;
// if we're full, let's cut off some worst groups
if ( m_iUsed==m_iSize )
CutWorst ( m_iLimit * (int)(GROUPBY_FACTOR/2) );
// do add
assert ( m_iUsed<m_iSize );
CSphMatch & tNew = m_pData [ m_iUsed++ ];
m_tSchema.CloneMatch ( &tNew, tEntry );
if_const ( NOTIFICATIONS )
m_iJustPushed = tNew.m_uDocID;
if ( !bGrouped )
{
tNew.SetAttr ( m_tLocGroupby, uGroupKey );
tNew.SetAttr ( m_tLocCount, 1 );
if_const ( DISTINCT )
tNew.SetAttr ( m_tLocDistinct, 0 );
// set @groupbystr value if available
if ( pAttr && m_tLocGroupbyStr.m_bDynamic )
tNew.SetAttr ( m_tLocGroupbyStr, *pAttr );
} else
{
ARRAY_FOREACH ( i, m_dAggregates )
m_dAggregates[i]->Ungroup ( &tNew );
}
m_hGroup2Match.Add ( &tNew, uGroupKey );
m_iTotal++;
return true;
}
void CalcAvg ( bool bGroup )
{
if ( !m_dAvgs.GetLength() )
return;
CSphMatch * pMatch = m_pData;
CSphMatch * pEnd = pMatch + m_iUsed;
while ( pMatch<pEnd )
{
ARRAY_FOREACH ( j, m_dAvgs )
{
if ( bGroup )
m_dAvgs[j]->Finalize ( pMatch );
else
m_dAvgs[j]->Ungroup ( pMatch );
}
++pMatch;
}
}
/// store all entries into specified location in sorted order, and remove them from queue
int Flatten ( CSphMatch * pTo, int iTag )
{
CountDistinct ();
CalcAvg ( true );
SortGroups ();
CSphVector<IAggrFunc *> dAggrs;
if ( m_dAggregates.GetLength()!=m_dAvgs.GetLength() )
{
dAggrs = m_dAggregates;
ARRAY_FOREACH ( i, m_dAvgs )
dAggrs.RemoveValue ( m_dAvgs[i] );
}
// FIXME!!! we should provide up-to max_matches to output buffer
const CSphMatch * pBegin = pTo;
int iLen = GetLength ();
for ( int i=0; i<iLen; ++i )
{
CSphMatch & tMatch = m_pData[i];
ARRAY_FOREACH ( j, dAggrs )
dAggrs[j]->Finalize ( &tMatch );
// HAVING filtering
if ( m_pAggrFilter && !m_pAggrFilter->Eval ( tMatch ) )
continue;
m_tSchema.CloneMatch ( pTo, tMatch );
if ( iTag>=0 )
pTo->m_iTag = iTag;
pTo++;
}
m_iUsed = 0;
m_iTotal = 0;
m_hGroup2Match.Reset ();
if_const ( DISTINCT )
m_tUniq.Resize ( 0 );
return ( pTo-pBegin );
}
/// get entries count
int GetLength () const
{
return Min ( m_iUsed, m_iLimit );
}
/// set group comparator state
void SetGroupState ( const CSphMatchComparatorState & tState )
{
m_tGroupSorter.m_fnStrCmp = tState.m_fnStrCmp;
// FIXME! manual bitwise copying.. yuck
for ( int i=0; i<CSphMatchComparatorState::MAX_ATTRS; i++ )
{
m_tGroupSorter.m_eKeypart[i] = tState.m_eKeypart[i];
m_tGroupSorter.m_tLocator[i] = tState.m_tLocator[i];
}
m_tGroupSorter.m_uAttrDesc = tState.m_uAttrDesc;
m_tGroupSorter.m_iNow = tState.m_iNow;
// check whether we sort by distinct
if_const ( DISTINCT && m_tDistinctLoc.m_iBitOffset>=0 )
for ( int i=0; i<CSphMatchComparatorState::MAX_ATTRS; i++ )
if ( m_tGroupSorter.m_tLocator[i].m_iBitOffset==m_tDistinctLoc.m_iBitOffset )
{
m_bSortByDistinct = true;
break;
}
}
protected:
/// count distinct values if necessary
void CountDistinct ()
{
if_const ( DISTINCT )
{
m_tUniq.Sort ();
SphGroupKey_t uGroup;
for ( int iCount = m_tUniq.CountStart ( &uGroup ); iCount; iCount = m_tUniq.CountNext ( &uGroup ) )
{
CSphMatch ** ppMatch = m_hGroup2Match(uGroup);
if ( ppMatch )
(*ppMatch)->SetAttr ( m_tLocDistinct, iCount );
}
}
}
/// cut worst N groups off the buffer tail
void CutWorst ( int iBound )
{
// sort groups
if ( m_bSortByDistinct )
CountDistinct ();
CalcAvg ( true );
SortGroups ();
CalcAvg ( false );
if_const ( NOTIFICATIONS )
{
for ( int i = iBound; i < m_iUsed; ++i )
m_dJustPopped.Add ( m_pData[i].m_uDocID );
}
// cleanup unused distinct stuff
if_const ( DISTINCT )
{
// build kill-list
CSphVector<SphGroupKey_t> dRemove;
dRemove.Resize ( m_iUsed-iBound );
ARRAY_FOREACH ( i, dRemove )
dRemove[i] = m_pData[iBound+i].GetAttr ( m_tLocGroupby );
// sort and compact
if ( !m_bSortByDistinct )
m_tUniq.Sort ();
m_tUniq.Compact ( &dRemove[0], m_iUsed-iBound );
}
// rehash
m_hGroup2Match.Reset ();
for ( int i=0; i<iBound; i++ )
m_hGroup2Match.Add ( m_pData+i, m_pData[i].GetAttr ( m_tLocGroupby ) );
// cut groups
m_iUsed = iBound;
}
/// sort groups buffer
void SortGroups ()
{
sphSort ( m_pData, m_iUsed, m_tGroupSorter, m_tGroupSorter );
}
virtual void Finalize ( ISphMatchProcessor & tProcessor, bool )
{
if ( !GetLength() )
return;
if ( m_iUsed>m_iLimit )
CutWorst ( m_iLimit );
// just evaluate in heap order
CSphMatch * pCur = m_pData;
const CSphMatch * pEnd = m_pData + m_iUsed;
while ( pCur<pEnd )
tProcessor.Process ( pCur++ );
}
};
/// match sorter with k-buffering and N-best group-by
template < typename COMPGROUP, bool DISTINCT, bool NOTIFICATIONS >
class CSphKBufferNGroupSorter : public CSphMatchQueueTraits, protected CSphGroupSorterSettings
{
protected:
ESphGroupBy m_eGroupBy; ///< group-by function
CSphGrouper * m_pGrouper;
CSphFixedHash < CSphMatch *, SphGroupKey_t, IdentityHash_fn > m_hGroup2Match;
protected:
int m_iLimit; ///< max matches to be retrieved
int m_iGLimit; ///< limit per one group
CSphVector<int> m_dGroupByList; ///< chains of equal matches from groups
CSphVector<int> m_dGroupsLen; ///< lengths of chains of equal matches from groups
int m_iHeads; ///< insertion point for head matches.
int m_iTails; ///< where to put tails of the subgroups
SphGroupKey_t m_uLastGroupKey; ///< helps to determine in pushEx whether the new subgroup started
#ifndef NDEBUG
int m_iruns; ///< helpers for conditional breakpoints on debug
int m_ipushed;
#endif
CSphUniqounter m_tUniq;
bool m_bSortByDistinct;
GroupSorter_fn<COMPGROUP> m_tGroupSorter;
const ISphMatchComparator * m_pComp;
CSphVector<IAggrFunc *> m_dAggregates;
CSphVector<IAggrFunc *> m_dAvgs;
const ISphFilter * m_pAggrFilter; ///< aggregate filter for matches on flatten
MatchCloner_t m_tPregroup;
static const int GROUPBY_FACTOR = 4; ///< allocate this times more storage when doing group-by (k, as in k-buffer)
protected:
inline int AddMatch ( bool bTail=false )
{
// if we're full, let's cut off some worst groups
if ( m_iUsed==m_iSize )
{
CutWorst ( m_iLimit * (int)(GROUPBY_FACTOR/2) );
// don't return true value for tail this case,
// since the context might be changed by the CutWorst!
if ( bTail )
return -1;
}
// do add
assert ( m_iUsed<m_iSize );
++m_iUsed;
if ( bTail )
{
// trick!
// m_iTails may be in 1-st of 2-nd subrange of 0..m_iSize..2*m_iSize.
// 1-st case the next free elem is just the next a row (+m_iSize shift)
// in 2-nd it is pulled from linked list
assert ( m_iTails>=0 && m_iTails<2*m_iSize );
int iRes;
if ( m_iTails<m_iSize )
iRes = m_iSize+m_iTails++;
else
{
iRes = m_iTails;
m_iTails = m_dGroupByList[m_iTails];
}
return iRes;
} else
return m_iHeads++;
}
public:
/// ctor
CSphKBufferNGroupSorter ( const ISphMatchComparator * pComp, const CSphQuery * pQuery, const CSphGroupSorterSettings & tSettings ) // FIXME! make k configurable
: CSphMatchQueueTraits ( ((pQuery->m_iGroupbyLimit>1)?2:1)*pQuery->m_iMaxMatches*GROUPBY_FACTOR, true )
, CSphGroupSorterSettings ( tSettings )
, m_eGroupBy ( pQuery->m_eGroupFunc )
, m_pGrouper ( tSettings.m_pGrouper )
, m_hGroup2Match ( pQuery->m_iMaxMatches*GROUPBY_FACTOR*2 )
, m_iLimit ( pQuery->m_iMaxMatches )
, m_iGLimit ( pQuery->m_iGroupbyLimit )
, m_iHeads ( 0 )
, m_iTails ( 0 )
, m_uLastGroupKey ( -1 )
, m_bSortByDistinct ( false )
, m_pComp ( pComp )
, m_pAggrFilter ( tSettings.m_pAggrFilterTrait )
{
assert ( GROUPBY_FACTOR>1 );
assert ( DISTINCT==false || tSettings.m_tDistinctLoc.m_iBitOffset>=0 );
assert ( m_iGLimit > 1 );
// trick! This case we allocated 2*m_iSize mem.
// range 0..m_iSize used for 1-st matches of each subgroup (i.e., for heads)
// range m_iSize+1..2*m_iSize used for the tails.
m_dGroupByList.Resize ( m_iSize );
m_dGroupsLen.Resize ( m_iSize );
m_iSize >>= 1;
if_const ( NOTIFICATIONS )
m_dJustPopped.Reserve ( m_iSize );
#ifndef NDEBUG
m_iruns = 0;
m_ipushed = 0;
#endif
}
// only for n-group
virtual int GetDataLength () const
{
return CSphMatchQueueTraits::GetDataLength()/2;
}
/// schema setup
virtual void SetSchema ( CSphRsetSchema & tSchema )
{
m_tSchema = tSchema;
m_tPregroup.SetSchema ( &m_tSchema );
m_tPregroup.m_dAttrsRaw.Add ( m_tLocGroupby );
m_tPregroup.m_dAttrsRaw.Add ( m_tLocCount );
if_const ( DISTINCT )
{
m_tPregroup.m_dAttrsRaw.Add ( m_tLocDistinct );
}
ExtractAggregates ( m_tSchema, m_tLocCount, m_tGroupSorter.m_eKeypart, m_tGroupSorter.m_tLocator, m_dAggregates, m_dAvgs, m_tPregroup );
}
/// dtor
~CSphKBufferNGroupSorter ()
{
SafeDelete ( m_pComp );
SafeDelete ( m_pGrouper );
SafeDelete ( m_pAggrFilter );
ARRAY_FOREACH ( i, m_dAggregates )
SafeDelete ( m_dAggregates[i] );
}
/// check if this sorter does groupby
virtual bool IsGroupby () const
{
return true;
}
virtual bool CanMulti () const
{
if ( m_pGrouper && !m_pGrouper->CanMulti() )
return false;
if ( HasString ( &m_tState ) )
return false;
if ( HasString ( &m_tGroupSorter ) )
return false;
return true;
}
/// set string pool pointer (for string+groupby sorters)
void SetStringPool ( const BYTE * pStrings )
{
m_pGrouper->SetStringPool ( pStrings );
}
/// add entry to the queue
virtual bool Push ( const CSphMatch & tEntry )
{
SphGroupKey_t uGroupKey = m_pGrouper->KeyFromMatch ( tEntry );
return PushEx ( tEntry, uGroupKey, false, false );
}
/// add grouped entry to the queue
virtual bool PushGrouped ( const CSphMatch & tEntry, bool bNewSet )
{
return PushEx ( tEntry, tEntry.GetAttr ( m_tLocGroupby ), true, bNewSet );
}
// insert a match into subgroup, or discard it
// returns 0 if no place now (need to flush)
// returns 1 if value was discarded or replaced other existing value
// returns 2 if value was added.
int InsertMatch ( int iPos, const CSphMatch & tEntry )
{
int iHead = iPos;
int iPrev = -1;
bool bDoAdd = m_dGroupsLen[iHead] < m_iGLimit;
while ( iPos>=0 )
{
CSphMatch * pMatch = m_pData+iPos;
if ( m_pComp->VirtualIsLess ( *pMatch, tEntry, m_tState ) ) // the tEntry is better than current *pMatch
{
int iPoint = iPos;
if ( bDoAdd )
{
iPoint = AddMatch(true); // add to the tails (2-nd subrange)
if ( iPoint<0 )
return 0;
} else
{
int iPreLast = iPrev;
while ( m_dGroupByList[iPoint]>0 )
{
iPreLast = iPoint;
iPoint = m_dGroupByList[iPoint];
}
m_dGroupByList[iPreLast]=-1;
if ( iPos==iPoint ) // avoid cycle link to itself
iPos = -1;
}
CSphMatch & tNew = m_pData [ iPoint ];
if ( iPos==iHead ) // this is the first elem, need to copy groupby staff from it
{
// trick point! The first elem MUST live in the low half of the pool.
// So, replacing the first is actually moving existing one to the last half,
// then overwriting the one in the low half with the new value and link them
m_tPregroup.Clone ( &tNew, pMatch );
m_tPregroup.Clone ( pMatch, &tEntry );
m_dGroupByList[iPoint]=m_dGroupByList[iPos];
m_dGroupByList[iPos]=iPoint;
} else // this is elem somewhere in the chain, just shift it.
{
m_tPregroup.Clone ( &tNew, &tEntry );
m_dGroupByList[iPrev] = iPoint;
m_dGroupByList[iPoint] = iPos;
}
break;
}
iPrev = iPos;
iPos = m_dGroupByList[iPos];
}
if ( bDoAdd )
++m_dGroupsLen[iHead];
if ( iPos<0 && bDoAdd ) // this item is less than everything, but still appropriate
{
int iPoint = AddMatch(true); // add to the tails (2-nd subrange)
if ( iPoint<0 )
return false;
CSphMatch & tNew = m_pData [ iPoint ];
m_tPregroup.Clone ( &tNew, &tEntry );
m_dGroupByList[iPrev] = iPoint;
m_dGroupByList[iPoint] = iPos;
}
return bDoAdd ? 2 : 1;
}
#ifndef NDEBUG
void CheckIntegrity()
{
#if PARANOID
int iTotalLen = 0;
for ( int i=0; i<m_iHeads; ++i )
{
int iLen = 0;
int iCur = i;
while ( iCur>=0 )
{
iCur = m_dGroupByList[iCur];
++iLen;
}
assert ( m_dGroupsLen[i]==iLen );
iTotalLen += iLen;
}
assert ( iTotalLen==m_iUsed );
#endif
}
#define CHECKINTEGRITY() CheckIntegrity()
#else
#define CHECKINTEGRITY()
#endif
/// add entry to the queue
virtual bool PushEx ( const CSphMatch & tEntry, const SphGroupKey_t uGroupKey, bool bGrouped, bool bNewSet )
{
#ifndef NDEBUG
++m_ipushed;
#endif
CHECKINTEGRITY();
if_const ( NOTIFICATIONS )
{
m_iJustPushed = 0;
m_dJustPopped.Resize(0);
}
// if this group is already hashed, we only need to update the corresponding match
CSphMatch ** ppMatch = m_hGroup2Match ( uGroupKey );
if ( ppMatch )
{
CSphMatch * pMatch = (*ppMatch);
assert ( pMatch );
assert ( pMatch->GetAttr ( m_tLocGroupby )==uGroupKey );
assert ( pMatch->m_pDynamic[-1]==tEntry.m_pDynamic[-1] );
if ( bGrouped )
{
// it's already grouped match
// sum grouped matches count
if ( bNewSet || uGroupKey!=m_uLastGroupKey )
{
pMatch->SetAttr ( m_tLocCount, pMatch->GetAttr ( m_tLocCount ) + tEntry.GetAttr ( m_tLocCount ) ); // OPTIMIZE! AddAttr()?
m_uLastGroupKey = uGroupKey;
bNewSet = true;
}
} else
{
// it's a simple match
// increase grouped matches count
pMatch->SetAttr ( m_tLocCount, 1 + pMatch->GetAttr ( m_tLocCount ) ); // OPTIMIZE! IncAttr()?
}
bNewSet |= !bGrouped;
// update aggregates
if ( bNewSet )
ARRAY_FOREACH ( i, m_dAggregates )
m_dAggregates[i]->Update ( pMatch, &tEntry, bGrouped );
// if new entry is more relevant, update from it
int iAdded = InsertMatch ( pMatch-m_pData, tEntry );
if ( !iAdded )
// was no insertion because cache cleaning. Recall myself
PushEx ( tEntry, uGroupKey, bGrouped, bNewSet );
else if ( iAdded>1 )
{
if ( bGrouped )
return true;
++m_iTotal;
}
}
// submit actual distinct value in all cases
if_const ( DISTINCT )
{
int iCount = 1;
if ( bGrouped )
iCount = (int)tEntry.GetAttr ( m_tLocDistinct );
m_tUniq.Add ( SphGroupedValue_t ( uGroupKey, tEntry.GetAttr ( m_tDistinctLoc ), iCount ) ); // OPTIMIZE! use simpler locator here?
}
CHECKINTEGRITY();
// it's a dupe anyway, so we shouldn't update total matches count
if ( ppMatch )
return false;
// do add
int iNew = AddMatch();
CSphMatch & tNew = m_pData [ iNew ];
m_tSchema.CloneMatch ( &tNew, tEntry );
m_dGroupByList [ iNew ] = -1;
m_dGroupsLen [ iNew ] = 1;
if_const ( NOTIFICATIONS )
m_iJustPushed = tNew.m_uDocID;
if ( !bGrouped )
{
tNew.SetAttr ( m_tLocGroupby, uGroupKey );
tNew.SetAttr ( m_tLocCount, 1 );
if_const ( DISTINCT )
tNew.SetAttr ( m_tLocDistinct, 0 );
} else
{
m_uLastGroupKey = uGroupKey;
ARRAY_FOREACH ( i, m_dAggregates )
m_dAggregates[i]->Ungroup ( &tNew );
}
m_hGroup2Match.Add ( &tNew, uGroupKey );
m_iTotal++;
CHECKINTEGRITY();
return true;
}
void CalcAvg ( bool bGroup )
{
if ( !m_dAvgs.GetLength() )
return;
int iHeadMatch;
int iMatch = iHeadMatch = 0;
for ( int i=0; i<m_iUsed; ++i )
{
CSphMatch * pMatch = m_pData + iMatch;
ARRAY_FOREACH ( j, m_dAvgs )
{
if ( bGroup )
m_dAvgs[j]->Finalize ( pMatch );
else
m_dAvgs[j]->Ungroup ( pMatch );
}
iMatch = m_dGroupByList [ iMatch ];
if ( iMatch<0 )
iMatch = ++iHeadMatch;
}
}
// rebuild m_hGroup2Match to point to the subgroups (2-nd elem and further)
// returns true if any such subroup found
inline bool Hash2nd()
{
// let the hash points to the chains from 2-nd elem
m_hGroup2Match.Reset();
bool bHaveTails = false;
int iHeads = m_iUsed;
for ( int i=0; i<iHeads; i++ )
{
if ( m_dGroupByList[i]>0 )
{
m_hGroup2Match.Add ( m_pData+m_dGroupByList[i], m_pData[i].GetAttr ( m_tLocGroupby ) );
bHaveTails = true;
iHeads-=m_dGroupsLen[i]-1;
m_dGroupsLen[m_dGroupByList[i]] = m_dGroupsLen[i];
}
}
return bHaveTails;
}
/// store all entries into specified location in sorted order, and remove them from queue
int Flatten ( CSphMatch * pTo, int iTag )
{
CountDistinct ();
CalcAvg ( true );
Hash2nd();
SortGroups ();
CSphVector<IAggrFunc *> dAggrs;
if ( m_dAggregates.GetLength()!=m_dAvgs.GetLength() )
{
dAggrs = m_dAggregates;
ARRAY_FOREACH ( i, m_dAvgs )
dAggrs.RemoveValue ( m_dAvgs[i] );
}
const CSphMatch * pBegin = pTo;
int iTotal = GetLength ();
int iTopGroupMatch = 0;
int iEntry = 0;
while ( iEntry<iTotal )
{
CSphMatch * pMatch = m_pData + iTopGroupMatch;
ARRAY_FOREACH ( j, dAggrs )
dAggrs[j]->Finalize ( pMatch );
bool bTopPassed = ( !m_pAggrFilter || m_pAggrFilter->Eval ( *pMatch ) );
// copy top group match
if ( bTopPassed )
{
m_tSchema.CloneMatch ( pTo, *pMatch );
if ( iTag>=0 )
pTo->m_iTag = iTag;
pTo++;
}
iEntry++;
iTopGroupMatch++;
// now look for the next match.
// In this specific case (2-nd, just after the head)
// we have to look it in the hash, not in the linked list!
CSphMatch ** ppMatch = m_hGroup2Match ( pMatch->GetAttr ( m_tLocGroupby ) );
int iNext = ( ppMatch ? *ppMatch-m_pData : -1 );
while ( iNext>=0 )
{
// copy rest group matches
if ( bTopPassed )
{
m_tPregroup.Combine ( pTo, m_pData+iNext, pMatch );
if ( iTag>=0 )
pTo->m_iTag = iTag;
pTo++;
}
iEntry++;
iNext = m_dGroupByList[iNext];
}
}
m_iHeads = m_iUsed = 0;
m_iTotal = 0;
memset ( m_pData+m_iSize, 0, m_iSize*sizeof(CSphMatch) );
m_iTails = 0;
m_hGroup2Match.Reset ();
if_const ( DISTINCT )
m_tUniq.Resize ( 0 );
return ( pTo-pBegin );
}
/// get entries count
int GetLength () const
{
return Min ( m_iUsed, m_iLimit );
}
/// set group comparator state
void SetGroupState ( const CSphMatchComparatorState & tState )
{
m_tGroupSorter.m_fnStrCmp = tState.m_fnStrCmp;
// FIXME! manual bitwise copying.. yuck
for ( int i=0; i<CSphMatchComparatorState::MAX_ATTRS; i++ )
{
m_tGroupSorter.m_eKeypart[i] = tState.m_eKeypart[i];
m_tGroupSorter.m_tLocator[i] = tState.m_tLocator[i];
}
m_tGroupSorter.m_uAttrDesc = tState.m_uAttrDesc;
m_tGroupSorter.m_iNow = tState.m_iNow;
// check whether we sort by distinct
if_const ( DISTINCT && m_tDistinctLoc.m_iBitOffset>=0 )
for ( int i=0; i<CSphMatchComparatorState::MAX_ATTRS; i++ )
if ( m_tGroupSorter.m_tLocator[i].m_iBitOffset==m_tDistinctLoc.m_iBitOffset )
{
m_bSortByDistinct = true;
break;
}
}
protected:
/// count distinct values if necessary
void CountDistinct ()
{
if_const ( DISTINCT )
{
m_tUniq.Sort ();
SphGroupKey_t uGroup;
for ( int iCount = m_tUniq.CountStart ( &uGroup ); iCount; iCount = m_tUniq.CountNext ( &uGroup ) )
{
CSphMatch ** ppMatch = m_hGroup2Match(uGroup);
if ( ppMatch )
(*ppMatch)->SetAttr ( m_tLocDistinct, iCount );
}
}
}
void CutWorstSubgroups ( int iBound )
{
#ifndef NDEBUG
++m_iruns;
#endif
CHECKINTEGRITY();
CalcAvg ( true );
SortGroups ();
CalcAvg ( false );
CSphVector<SphGroupKey_t> dRemove;
if_const ( DISTINCT )
dRemove.Reserve ( m_iUsed-iBound );
int iHeadMatch = 1;
int iMatch = 0;
int iHeadBound = -1;
int iLastSize = 0;
for ( int i=0; i<m_iUsed; ++i )
{
CSphMatch * pMatch = m_pData + iMatch;
if ( i>=iBound )
{
if ( iHeadBound<0 )
iHeadBound = ( iMatch+1==iHeadMatch ) ? iMatch : iHeadMatch;
// do the staff with matches to cut
if_const ( NOTIFICATIONS )
m_dJustPopped.Add ( pMatch->m_uDocID );
if_const ( DISTINCT )
dRemove.Add ( pMatch->GetAttr ( m_tLocGroupby ) );
if ( iMatch>=m_iSize )
{
Swap ( m_dGroupByList[iMatch], m_iTails );
Swap ( m_iTails, iMatch );
if ( iMatch<0 )
iMatch = iHeadMatch++;
continue;
}
}
++iLastSize;
if ( iMatch < m_iSize )
{
// next match have to be looked in the hash
CSphMatch ** ppMatch = m_hGroup2Match ( pMatch->GetAttr ( m_tLocGroupby ) );
if ( ppMatch )
{
int iChainLen = 1;
if ( i==iBound-1 )
{
// edge case. Next match will be deleted.
m_dGroupByList[iMatch] = -1;
} else
{
m_dGroupByList[iMatch] = *ppMatch-m_pData;
iChainLen = m_dGroupsLen[*ppMatch-m_pData];
}
m_dGroupsLen[iMatch] = iChainLen;
if ( i+iChainLen<iBound ) // optimize: may jump over the chain
{
i+=iChainLen-1;
iMatch = iHeadMatch++;
iLastSize = 0;
} else
iMatch = *ppMatch-m_pData;
} else
{
m_dGroupByList[iMatch] = -1;
m_dGroupsLen[iMatch] = 1;
iMatch = iHeadMatch++;
iLastSize = 0;
}
} else
{
if ( i==iBound-1 )
{
int ifoo = m_dGroupByList[iMatch];
// edge case. Next node will be deleted, so we need to terminate the pointer to it.
m_dGroupByList[iMatch]=-1;
m_dGroupsLen[iHeadMatch-1] = iLastSize;
iMatch = ifoo;
} else
iMatch = m_dGroupByList[iMatch];
if ( iMatch<0 )
{
iMatch = iHeadMatch++;
iLastSize=0;
}
}
}
if_const ( DISTINCT )
{
if ( !m_bSortByDistinct )
m_tUniq.Sort ();
m_tUniq.Compact ( &dRemove[0], iBound );
}
// rehash
m_hGroup2Match.Reset ();
for ( int i=0; i<iHeadBound; i++ )
m_hGroup2Match.Add ( m_pData+i, m_pData[i].GetAttr ( m_tLocGroupby ) );
#ifndef NDEBUG
{
int imanaged = 0;
int i;
for ( i=m_iTails; i>=m_iSize; i=m_dGroupByList[i] )
{
assert ( i!=m_dGroupByList[i] ); // cycle link to myself
++imanaged;
assert ( imanaged<=m_iSize ); // cycle links
}
imanaged +=iBound - iHeadBound;
assert ( imanaged==i || imanaged+1==i ); // leaks
}
#endif
// cut groups
m_iUsed = iBound;
m_iHeads = iHeadBound;
CHECKINTEGRITY();
}
/// cut worst N groups off the buffer tail
void CutWorst ( int iBound )
{
// sort groups
if ( m_bSortByDistinct )
CountDistinct ();
CHECKINTEGRITY();
if ( Hash2nd() )
{
CutWorstSubgroups ( iBound );
return;
}
CalcAvg ( true );
SortGroups ();
CalcAvg ( false );
if_const ( NOTIFICATIONS )
{
for ( int i = iBound; i < m_iUsed; ++i )
m_dJustPopped.Add ( m_pData[i].m_uDocID );
}
// cleanup unused distinct stuff
if_const ( DISTINCT )
{
// build kill-list
CSphVector<SphGroupKey_t> dRemove;
dRemove.Resize ( m_iUsed-iBound );
ARRAY_FOREACH ( i, dRemove )
dRemove[i] = m_pData[iBound+i].GetAttr ( m_tLocGroupby );
// sort and compact
if ( !m_bSortByDistinct )
m_tUniq.Sort ();
m_tUniq.Compact ( &dRemove[0], m_iUsed-iBound );
}
// rehash
m_hGroup2Match.Reset ();
for ( int i=0; i<iBound; i++ )
m_hGroup2Match.Add ( m_pData+i, m_pData[i].GetAttr ( m_tLocGroupby ) );
// cut groups
m_iHeads = m_iUsed = iBound;
}
/// sort groups buffer
void SortGroups ()
{
sphSort ( m_pData, m_iHeads, m_tGroupSorter, m_tGroupSorter );
}
virtual void Finalize ( ISphMatchProcessor & tProcessor, bool )
{
if ( !GetLength() )
return;
if ( m_iUsed>m_iLimit )
CutWorst ( m_iLimit );
int iMatch = 0;
int iNextHead = 0;
for ( int i=0; i<m_iUsed; ++i )
{
tProcessor.Process ( m_pData + iMatch );
if ( iMatch < m_iSize ) // this is head match
iNextHead = iMatch + 1;
iMatch = m_dGroupByList[iMatch];
if ( iMatch<0 )
iMatch = iNextHead;
}
}
};
/// match sorter with k-buffering and group-by for MVAs
template < typename COMPGROUP, bool DISTINCT, bool NOTIFICATIONS >
class CSphKBufferMVAGroupSorter : public CSphKBufferGroupSorter < COMPGROUP, DISTINCT, NOTIFICATIONS >
{
protected:
const DWORD * m_pMva; ///< pointer to MVA pool for incoming matches
bool m_bArenaProhibit;
CSphAttrLocator m_tMvaLocator;
bool m_bMva64;
public:
/// ctor
CSphKBufferMVAGroupSorter ( const ISphMatchComparator * pComp, const CSphQuery * pQuery, const CSphGroupSorterSettings & tSettings )
: CSphKBufferGroupSorter < COMPGROUP, DISTINCT, NOTIFICATIONS > ( pComp, pQuery, tSettings )
, m_pMva ( NULL )
, m_bArenaProhibit ( false )
, m_bMva64 ( tSettings.m_bMva64 )
{
this->m_pGrouper->GetLocator ( m_tMvaLocator );
}
/// check if this sorter does groupby
virtual bool IsGroupby () const
{
return true;
}
/// set MVA pool for subsequent matches
void SetMVAPool ( const DWORD * pMva, bool bArenaProhibit )
{
m_pMva = pMva;
m_bArenaProhibit = bArenaProhibit;
}
/// add entry to the queue
virtual bool Push ( const CSphMatch & tEntry )
{
assert ( m_pMva );
if ( !m_pMva )
return false;
// get that list
// FIXME! OPTIMIZE! use simpler locator than full bits/count here
// FIXME! hardcoded MVA type, so here's MVA_DOWNSIZE marker for searching
const DWORD * pValues = tEntry.GetAttrMVA ( this->m_tMvaLocator, m_pMva, m_bArenaProhibit ); // (this pointer is for gcc; it doesn't work otherwise)
if ( !pValues )
return false;
DWORD iValues = *pValues++;
bool bRes = false;
if ( m_bMva64 )
{
assert ( ( iValues%2 )==0 );
for ( ;iValues>0; iValues-=2, pValues+=2 )
{
int64_t iMva = MVA_UPSIZE ( pValues );
SphGroupKey_t uGroupkey = this->m_pGrouper->KeyFromValue ( iMva );
bRes |= this->PushEx ( tEntry, uGroupkey, false, false );
}
} else
{
while ( iValues-- )
{
SphGroupKey_t uGroupkey = this->m_pGrouper->KeyFromValue ( *pValues++ );
bRes |= this->PushEx ( tEntry, uGroupkey, false, false );
}
}
return bRes;
}
/// add pre-grouped entry to the queue
virtual bool PushGrouped ( const CSphMatch & tEntry, bool bNewSet )
{
// re-group it based on the group key
// (first 'this' is for icc; second 'this' is for gcc)
return this->PushEx ( tEntry, tEntry.GetAttr ( this->m_tLocGroupby ), true, bNewSet );
}
};
/// match sorter with k-buffering and group-by for JSON arrays
template < typename COMPGROUP, bool DISTINCT, bool NOTIFICATIONS >
class CSphKBufferJsonGroupSorter : public CSphKBufferGroupSorter < COMPGROUP, DISTINCT, NOTIFICATIONS >
{
public:
/// ctor
CSphKBufferJsonGroupSorter ( const ISphMatchComparator * pComp, const CSphQuery * pQuery, const CSphGroupSorterSettings & tSettings )
: CSphKBufferGroupSorter < COMPGROUP, DISTINCT, NOTIFICATIONS > ( pComp, pQuery, tSettings )
{}
/// check if this sorter does groupby
virtual bool IsGroupby () const
{
return true;
}
/// add entry to the queue
virtual bool Push ( const CSphMatch & tMatch )
{
bool bRes = false;
int iLen;
char sBuf[32];
SphGroupKey_t uGroupkey = this->m_pGrouper->KeyFromMatch ( tMatch );
int64_t iValue = (int64_t)uGroupkey;
const BYTE * pStrings = ((CSphGrouperJsonField*)this->m_pGrouper)->m_pStrings;
const BYTE * pValue = pStrings + ( iValue & 0xffffffff );
ESphJsonType eRes = (ESphJsonType)( iValue >> 32 );
switch ( eRes )
{
case JSON_ROOT:
{
iLen = sphJsonNodeSize ( JSON_ROOT, pValue-4 );
bool bEmpty = iLen==5; // mask and JSON_EOF
uGroupkey = bEmpty ? 0 : sphFNV64 ( pValue, iLen );
return this->PushEx ( tMatch, uGroupkey, false, false, bEmpty ? NULL : &iValue );
}
case JSON_STRING:
case JSON_OBJECT:
case JSON_MIXED_VECTOR:
iLen = sphJsonUnpackInt ( &pValue );
uGroupkey = iLen==1 ? 0 : sphFNV64 ( pValue, iLen );
return this->PushEx ( tMatch, uGroupkey, false, false, iLen==1 ? 0: &iValue );
case JSON_STRING_VECTOR:
{
sphJsonUnpackInt ( &pValue );
iLen = sphJsonUnpackInt ( &pValue );
for ( int i=0;i<iLen;i++ )
{
DWORD uOff = pValue-pStrings;
int64_t iValue = ( ( (int64_t)uOff ) | ( ( (int64_t)JSON_STRING )<<32 ) );
int iStrLen = sphJsonUnpackInt ( &pValue );
uGroupkey = sphFNV64 ( pValue, iStrLen );
bRes |= this->PushEx ( tMatch, uGroupkey, false, false, &iValue );
pValue += iStrLen;
}
return bRes;
}
case JSON_INT32:
uGroupkey = sphFNV64 ( (BYTE*)FormatInt ( sBuf, (int)sphGetDword(pValue) ) );
break;
case JSON_INT64:
uGroupkey = sphFNV64 ( (BYTE*)FormatInt ( sBuf, (int)sphJsonLoadBigint ( &pValue ) ) );
break;
case JSON_DOUBLE:
snprintf ( sBuf, sizeof(sBuf), "%f", sphQW2D ( sphJsonLoadBigint ( &pValue ) ) );
uGroupkey = sphFNV64 ( (const BYTE*)sBuf );
break;
case JSON_INT32_VECTOR:
{
iLen = sphJsonUnpackInt ( &pValue );
int * p = (int*)pValue;
DWORD uOff = pValue-pStrings;
for ( int i=0;i<iLen;i++ )
{
int64_t iPacked = ( ( (int64_t)uOff ) | ( ( (int64_t)JSON_INT32 )<<32 ) );
uGroupkey = *p++;
bRes |= this->PushEx ( tMatch, uGroupkey, false, false, &iPacked );
uOff+=4;
}
return bRes;
}
break;
case JSON_INT64_VECTOR:
case JSON_DOUBLE_VECTOR:
{
iLen = sphJsonUnpackInt ( &pValue );
int64_t * p = (int64_t*)pValue;
DWORD uOff = pValue-pStrings;
ESphJsonType eType = eRes==JSON_INT64_VECTOR ? JSON_INT64 : JSON_DOUBLE;
for ( int i=0;i<iLen;i++ )
{
int64_t iPacked = ( ( (int64_t)uOff ) | ( ( (int64_t)eType )<<32 ) );
uGroupkey = *p++;
bRes |= this->PushEx ( tMatch, uGroupkey, false, false, &iPacked );
uOff+=8;
}
return bRes;
}
break;
default:
uGroupkey = 0;
break;
}
bRes |= this->PushEx ( tMatch, uGroupkey, false, false, &iValue );
return bRes;
}
/// add pre-grouped entry to the queue
virtual bool PushGrouped ( const CSphMatch & tEntry, bool bNewSet )
{
// re-group it based on the group key
// (first 'this' is for icc; second 'this' is for gcc)
return this->PushEx ( tEntry, tEntry.GetAttr ( this->m_tLocGroupby ), true, bNewSet );
}
};
/// implicit group-by sorter
template < typename COMPGROUP, bool DISTINCT, bool NOTIFICATIONS >
class CSphImplicitGroupSorter : public ISphMatchSorter, ISphNoncopyable, protected CSphGroupSorterSettings
{
protected:
CSphMatch m_tData;
bool m_bDataInitialized;
CSphVector<SphUngroupedValue_t> m_dUniq;
CSphVector<IAggrFunc *> m_dAggregates;
const ISphFilter * m_pAggrFilter; ///< aggregate filter for matches on flatten
MatchCloner_t m_tPregroup;
public:
/// ctor
CSphImplicitGroupSorter ( const ISphMatchComparator * DEBUGARG(pComp), const CSphQuery *, const CSphGroupSorterSettings & tSettings )
: CSphGroupSorterSettings ( tSettings )
, m_bDataInitialized ( false )
, m_pAggrFilter ( tSettings.m_pAggrFilterTrait )
{
assert ( DISTINCT==false || tSettings.m_tDistinctLoc.m_iBitOffset>=0 );
assert ( !pComp );
if_const ( NOTIFICATIONS )
m_dJustPopped.Reserve(1);
m_dUniq.Reserve ( 16384 );
}
/// dtor
~CSphImplicitGroupSorter ()
{
SafeDelete ( m_pAggrFilter );
ARRAY_FOREACH ( i, m_dAggregates )
SafeDelete ( m_dAggregates[i] );
}
/// schema setup
virtual void SetSchema ( CSphRsetSchema & tSchema )
{
m_tSchema = tSchema;
m_tPregroup.SetSchema ( &m_tSchema );
m_tPregroup.m_dAttrsRaw.Add ( m_tLocGroupby );
m_tPregroup.m_dAttrsRaw.Add ( m_tLocCount );
if_const ( DISTINCT )
{
m_tPregroup.m_dAttrsRaw.Add ( m_tLocDistinct );
}
CSphVector<IAggrFunc *> dTmp;
ESphSortKeyPart dTmpKeypart[CSphMatchComparatorState::MAX_ATTRS];
CSphAttrLocator dTmpLocator[CSphMatchComparatorState::MAX_ATTRS];
ExtractAggregates ( m_tSchema, m_tLocCount, dTmpKeypart, dTmpLocator, m_dAggregates, dTmp, m_tPregroup );
assert ( !dTmp.GetLength() );
}
int GetDataLength () const
{
return 1;
}
bool UsesAttrs () const
{
return true;
}
/// check if this sorter does groupby
virtual bool IsGroupby () const
{
return true;
}
virtual bool CanMulti () const
{
return true;
}
/// set string pool pointer (for string+groupby sorters)
void SetStringPool ( const BYTE * )
{
}
/// add entry to the queue
virtual bool Push ( const CSphMatch & tEntry )
{
return PushEx ( tEntry, false );
}
/// add grouped entry to the queue. bNewSet indicates the beginning of resultset returned by an agent.
virtual bool PushGrouped ( const CSphMatch & tEntry, bool )
{
return PushEx ( tEntry, true );
}
/// store all entries into specified location in sorted order, and remove them from queue
virtual int Flatten ( CSphMatch * pTo, int iTag )
{
assert ( m_bDataInitialized );
CountDistinct ();
ARRAY_FOREACH ( j, m_dAggregates )
m_dAggregates[j]->Finalize ( &m_tData );
int iCopied = 0;
if ( !m_pAggrFilter || m_pAggrFilter->Eval ( m_tData ) )
{
iCopied = 1;
m_tSchema.CloneMatch ( pTo, m_tData );
m_tSchema.FreeStringPtrs ( &m_tData );
if ( iTag>=0 )
pTo->m_iTag = iTag;
}
m_iTotal = 0;
m_bDataInitialized = false;
if_const ( DISTINCT )
m_dUniq.Resize(0);
return iCopied;
}
/// finalize, perform final sort/cut as needed
void Finalize ( ISphMatchProcessor & tProcessor, bool )
{
if ( !GetLength() )
return;
tProcessor.Process ( &m_tData );
}
/// get entries count
int GetLength () const
{
return m_bDataInitialized ? 1 : 0;
}
protected:
/// add entry to the queue
bool PushEx ( const CSphMatch & tEntry, bool bGrouped )
{
if_const ( NOTIFICATIONS )
{
m_iJustPushed = 0;
m_dJustPopped.Resize(0);
}
if ( m_bDataInitialized )
{
assert ( m_tData.m_pDynamic[-1]==tEntry.m_pDynamic[-1] );
if ( bGrouped )
{
// it's already grouped match
// sum grouped matches count
m_tData.SetAttr ( m_tLocCount, m_tData.GetAttr ( m_tLocCount ) + tEntry.GetAttr ( m_tLocCount ) ); // OPTIMIZE! AddAttr()?
} else
{
// it's a simple match
// increase grouped matches count
m_tData.SetAttr ( m_tLocCount, 1 + m_tData.GetAttr ( m_tLocCount ) ); // OPTIMIZE! IncAttr()?
}
// update aggregates
ARRAY_FOREACH ( i, m_dAggregates )
m_dAggregates[i]->Update ( &m_tData, &tEntry, bGrouped );
// if new entry is more relevant, update from it
if ( tEntry.m_uDocID<m_tData.m_uDocID )
{
if_const ( NOTIFICATIONS )
{
m_iJustPushed = tEntry.m_uDocID;
m_dJustPopped.Add ( m_tData.m_uDocID );
}
m_tPregroup.Clone ( &m_tData, &tEntry );
}
}
// submit actual distinct value in all cases
if_const ( DISTINCT )
{
int iCount = 1;
if ( bGrouped )
iCount = (int)tEntry.GetAttr ( m_tLocDistinct );
m_dUniq.Add ( SphUngroupedValue_t ( tEntry.GetAttr ( m_tDistinctLoc ), iCount ) ); // OPTIMIZE! use simpler locator here?
}
// it's a dupe anyway, so we shouldn't update total matches count
if ( m_bDataInitialized )
return false;
// add first
m_tSchema.CloneMatch ( &m_tData, tEntry );
if_const ( NOTIFICATIONS )
m_iJustPushed = m_tData.m_uDocID;
if ( !bGrouped )
{
m_tData.SetAttr ( m_tLocGroupby, 1 ); // fake group number
m_tData.SetAttr ( m_tLocCount, 1 );
if_const ( DISTINCT )
m_tData.SetAttr ( m_tLocDistinct, 0 );
} else
{
ARRAY_FOREACH ( i, m_dAggregates )
m_dAggregates[i]->Ungroup ( &m_tData );
}
m_bDataInitialized = true;
m_iTotal++;
return true;
}
/// count distinct values if necessary
void CountDistinct ()
{
if_const ( DISTINCT )
{
assert ( m_bDataInitialized );
m_dUniq.Sort ();
int iCount = 0;
ARRAY_FOREACH ( i, m_dUniq )
{
if ( i>0 && m_dUniq[i-1]==m_dUniq[i] )
continue;
iCount += m_dUniq[i].m_iCount;
}
m_tData.SetAttr ( m_tLocDistinct, iCount );
}
}
};
//////////////////////////////////////////////////////////////////////////
// PLAIN SORTING FUNCTORS
//////////////////////////////////////////////////////////////////////////
/// match sorter
struct MatchRelevanceLt_fn : public ISphMatchComparator
{
virtual bool VirtualIsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t ) const
{
return IsLess ( a, b, t );
}
static bool IsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & )
{
if ( a.m_iWeight!=b.m_iWeight )
return a.m_iWeight < b.m_iWeight;
return a.m_uDocID > b.m_uDocID;
}
};
/// match sorter
struct MatchAttrLt_fn : public ISphMatchComparator
{
virtual bool VirtualIsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t ) const
{
return IsLess ( a, b, t );
}
static inline bool IsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t )
{
if ( t.m_eKeypart[0]!=SPH_KEYPART_STRING )
{
SphAttr_t aa = a.GetAttr ( t.m_tLocator[0] );
SphAttr_t bb = b.GetAttr ( t.m_tLocator[0] );
if ( aa!=bb )
return aa<bb;
} else
{
int iCmp = t.CmpStrings ( a, b, 0 );
if ( iCmp!=0 )
return iCmp<0;
}
if ( a.m_iWeight!=b.m_iWeight )
return a.m_iWeight < b.m_iWeight;
return a.m_uDocID > b.m_uDocID;
}
};
/// match sorter
struct MatchAttrGt_fn : public ISphMatchComparator
{
virtual bool VirtualIsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t ) const
{
return IsLess ( a, b, t );
}
static inline bool IsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t )
{
if ( t.m_eKeypart[0]!=SPH_KEYPART_STRING )
{
SphAttr_t aa = a.GetAttr ( t.m_tLocator[0] );
SphAttr_t bb = b.GetAttr ( t.m_tLocator[0] );
if ( aa!=bb )
return aa>bb;
} else
{
int iCmp = t.CmpStrings ( a, b, 0 );
if ( iCmp!=0 )
return iCmp>0;
}
if ( a.m_iWeight!=b.m_iWeight )
return a.m_iWeight < b.m_iWeight;
return a.m_uDocID > b.m_uDocID;
}
};
/// match sorter
struct MatchTimeSegments_fn : public ISphMatchComparator
{
virtual bool VirtualIsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t ) const
{
return IsLess ( a, b, t );
}
static inline bool IsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t )
{
SphAttr_t aa = a.GetAttr ( t.m_tLocator[0] );
SphAttr_t bb = b.GetAttr ( t.m_tLocator[0] );
int iA = GetSegment ( aa, t.m_iNow );
int iB = GetSegment ( bb, t.m_iNow );
if ( iA!=iB )
return iA > iB;
if ( a.m_iWeight!=b.m_iWeight )
return a.m_iWeight < b.m_iWeight;
if ( aa!=bb )
return aa<bb;
return a.m_uDocID > b.m_uDocID;
}
protected:
static inline int GetSegment ( SphAttr_t iStamp, SphAttr_t iNow )
{
if ( iStamp>=iNow-3600 ) return 0; // last hour
if ( iStamp>=iNow-24*3600 ) return 1; // last day
if ( iStamp>=iNow-7*24*3600 ) return 2; // last week
if ( iStamp>=iNow-30*24*3600 ) return 3; // last month
if ( iStamp>=iNow-90*24*3600 ) return 4; // last 3 months
return 5; // everything else
}
};
/// match sorter
struct MatchExpr_fn : public ISphMatchComparator
{
virtual bool VirtualIsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t ) const
{
return IsLess ( a, b, t );
}
static inline bool IsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t )
{
float aa = a.GetAttrFloat ( t.m_tLocator[0] ); // FIXME! OPTIMIZE!!! simplified (dword-granular) getter could be used here
float bb = b.GetAttrFloat ( t.m_tLocator[0] );
if ( aa!=bb )
return aa<bb;
return a.m_uDocID>b.m_uDocID;
}
};
/////////////////////////////////////////////////////////////////////////////
#define SPH_TEST_PAIR(_aa,_bb,_idx ) \
if ( (_aa)!=(_bb) ) \
return ( (t.m_uAttrDesc >> (_idx)) & 1 ) ^ ( (_aa) > (_bb) );
#define SPH_TEST_KEYPART(_idx) \
switch ( t.m_eKeypart[_idx] ) \
{ \
case SPH_KEYPART_ID: SPH_TEST_PAIR ( a.m_uDocID, b.m_uDocID, _idx ); break; \
case SPH_KEYPART_WEIGHT: SPH_TEST_PAIR ( a.m_iWeight, b.m_iWeight, _idx ); break; \
case SPH_KEYPART_INT: \
{ \
register SphAttr_t aa = a.GetAttr ( t.m_tLocator[_idx] ); \
register SphAttr_t bb = b.GetAttr ( t.m_tLocator[_idx] ); \
SPH_TEST_PAIR ( aa, bb, _idx ); \
break; \
} \
case SPH_KEYPART_FLOAT: \
{ \
register float aa = a.GetAttrFloat ( t.m_tLocator[_idx] ); \
register float bb = b.GetAttrFloat ( t.m_tLocator[_idx] ); \
SPH_TEST_PAIR ( aa, bb, _idx ) \
break; \
} \
case SPH_KEYPART_STRINGPTR: \
case SPH_KEYPART_STRING: \
{ \
int iCmp = t.CmpStrings ( a, b, _idx ); \
if ( iCmp!=0 ) \
return ( ( t.m_uAttrDesc >> (_idx) ) & 1 ) ^ ( iCmp>0 ); \
break; \
} \
}
struct MatchGeneric2_fn : public ISphMatchComparator
{
virtual bool VirtualIsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t ) const
{
return IsLess ( a, b, t );
}
static inline bool IsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t )
{
SPH_TEST_KEYPART(0);
SPH_TEST_KEYPART(1);
return a.m_uDocID>b.m_uDocID;
}
};
struct MatchGeneric3_fn : public ISphMatchComparator
{
virtual bool VirtualIsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t ) const
{
return IsLess ( a, b, t );
}
static inline bool IsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t )
{
SPH_TEST_KEYPART(0);
SPH_TEST_KEYPART(1);
SPH_TEST_KEYPART(2);
return a.m_uDocID>b.m_uDocID;
}
};
struct MatchGeneric4_fn : public ISphMatchComparator
{
virtual bool VirtualIsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t ) const
{
return IsLess ( a, b, t );
}
static inline bool IsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t )
{
SPH_TEST_KEYPART(0);
SPH_TEST_KEYPART(1);
SPH_TEST_KEYPART(2);
SPH_TEST_KEYPART(3);
return a.m_uDocID>b.m_uDocID;
}
};
struct MatchGeneric5_fn : public ISphMatchComparator
{
virtual bool VirtualIsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t ) const
{
return IsLess ( a, b, t );
}
static inline bool IsLess ( const CSphMatch & a, const CSphMatch & b, const CSphMatchComparatorState & t )
{
SPH_TEST_KEYPART(0);
SPH_TEST_KEYPART(1);
SPH_TEST_KEYPART(2);
SPH_TEST_KEYPART(3);
SPH_TEST_KEYPART(4);
return a.m_uDocID>b.m_uDocID;
}
};
//////////////////////////////////////////////////////////////////////////
// SORT CLAUSE PARSER
//////////////////////////////////////////////////////////////////////////
static const int MAX_SORT_FIELDS = 5; // MUST be in sync with CSphMatchComparatorState::m_iAttr
class SortClauseTokenizer_t
{
protected:
char * m_pCur;
char * m_pMax;
char * m_pBuf;
protected:
char ToLower ( char c )
{
// 0..9, A..Z->a..z, _, a..z, @, .
if ( ( c>='0' && c<='9' ) || ( c>='a' && c<='z' ) || c=='_' || c=='@' || c=='.' || c=='[' || c==']' || c=='\'' || c=='\"' || c=='(' || c==')' || c=='*' )
return c;
if ( c>='A' && c<='Z' )
return c-'A'+'a';
return 0;
}
public:
explicit SortClauseTokenizer_t ( const char * sBuffer )
{
int iLen = strlen(sBuffer);
m_pBuf = new char [ iLen+1 ];
m_pMax = m_pBuf+iLen;
m_pCur = m_pBuf;
// make string lowercase but keep case of JSON.field
bool bJson = false;
for ( int i=0; i<=iLen; i++ )
{
char cSrc = sBuffer[i];
char cDst = ToLower ( cSrc );
bJson = ( cSrc=='.' || cSrc=='[' || ( bJson && cDst>0 ) ); // keep case of valid char sequence after '.' and '[' symbols
m_pBuf[i] = bJson ? cSrc : cDst;
}
}
~SortClauseTokenizer_t ()
{
SafeDeleteArray ( m_pBuf );
}
const char * GetToken ()
{
// skip spaces
while ( m_pCur<m_pMax && !*m_pCur )
m_pCur++;
if ( m_pCur>=m_pMax )
return NULL;
// memorize token start, and move pointer forward
const char * sRes = m_pCur;
while ( *m_pCur )
m_pCur++;
return sRes;
}
};
static inline ESphSortKeyPart Attr2Keypart ( ESphAttr eType )
{
switch ( eType )
{
case SPH_ATTR_FLOAT: return SPH_KEYPART_FLOAT;
case SPH_ATTR_STRING: return SPH_KEYPART_STRING;
case SPH_ATTR_JSON:
case SPH_ATTR_JSON_FIELD:
case SPH_ATTR_STRINGPTR: return SPH_KEYPART_STRINGPTR;
default: return SPH_KEYPART_INT;
}
}
static const char g_sIntAttrPrefix[] = "@int_str2ptr_";
ESortClauseParseResult sphParseSortClause ( const CSphQuery * pQuery, const char * sClause, const ISphSchema & tSchema,
ESphSortFunc & eFunc, CSphMatchComparatorState & tState, CSphString & sError )
{
for ( int i=0; i<CSphMatchComparatorState::MAX_ATTRS; i++ )
tState.m_dAttrs[i] = -1;
// mini parser
SortClauseTokenizer_t tTok ( sClause );
bool bField = false; // whether i'm expecting field name or sort order
int iField = 0;
for ( const char * pTok=tTok.GetToken(); pTok; pTok=tTok.GetToken() )
{
bField = !bField;
// special case, sort by random
if ( iField==0 && bField && strcmp ( pTok, "@random" )==0 )
return SORT_CLAUSE_RANDOM;
// handle sort order
if ( !bField )
{
// check
if ( strcmp ( pTok, "desc" ) && strcmp ( pTok, "asc" ) )
{
sError.SetSprintf ( "invalid sorting order '%s'", pTok );
return SORT_CLAUSE_ERROR;
}
// set
if ( !strcmp ( pTok, "desc" ) )
tState.m_uAttrDesc |= ( 1<<iField );
iField++;
continue;
}
// handle attribute name
if ( iField==MAX_SORT_FIELDS )
{
sError.SetSprintf ( "too many sort-by attributes; maximum count is %d", MAX_SORT_FIELDS );
return SORT_CLAUSE_ERROR;
}
if ( !strcasecmp ( pTok, "@relevance" )
|| !strcasecmp ( pTok, "@rank" )
|| !strcasecmp ( pTok, "@weight" )
|| !strcasecmp ( pTok, "weight()" ) )
{
tState.m_eKeypart[iField] = SPH_KEYPART_WEIGHT;
} else if ( !strcasecmp ( pTok, "@id" ) || !strcasecmp ( pTok, "id" ) )
{
tState.m_eKeypart[iField] = SPH_KEYPART_ID;
} else
{
ESphAttr eAttrType = SPH_ATTR_NONE;
if ( !strcasecmp ( pTok, "@group" ) )
pTok = "@groupby";
else if ( !strcasecmp ( pTok, "count(*)" ) )
pTok = "@count";
else if ( !strcasecmp ( pTok, "facet()" ) )
pTok = "@groupby"; // facet() is essentially a @groupby alias
// try to lookup plain attr in sorter schema
int iAttr = tSchema.GetAttrIndex ( pTok );
// try to lookup aliased count(*) and aliased groupby() in select items
if ( iAttr<0 )
{
ARRAY_FOREACH ( i, pQuery->m_dItems )
{
const CSphQueryItem & tItem = pQuery->m_dItems[i];
if ( !tItem.m_sAlias.cstr() || strcasecmp ( tItem.m_sAlias.cstr(), pTok ) )
continue;
if ( tItem.m_sExpr.Begins("@") )
iAttr = tSchema.GetAttrIndex ( tItem.m_sExpr.cstr() );
else if ( tItem.m_sExpr=="count(*)" )
iAttr = tSchema.GetAttrIndex ( "@count" );
else if ( tItem.m_sExpr=="groupby()" )
{
iAttr = tSchema.GetAttrIndex ( "@groupbystr" );
// try numeric group by
if ( iAttr<0 )
iAttr = tSchema.GetAttrIndex ( "@groupby" );
}
break; // break in any case; because we did match the alias
}
}
// try JSON attribute and use JSON attribute instead of JSON field
if ( iAttr<0 || ( iAttr>=0 && ( tSchema.GetAttr ( iAttr ).m_eAttrType==SPH_ATTR_JSON_FIELD
|| tSchema.GetAttr ( iAttr ).m_eAttrType==SPH_ATTR_JSON ) ) )
{
if ( iAttr>=0 )
{
// aliased SPH_ATTR_JSON_FIELD, reuse existing expression
const CSphColumnInfo * pAttr = &tSchema.GetAttr(iAttr);
if ( pAttr->m_pExpr.Ptr() )
pAttr->m_pExpr->AddRef(); // SetupSortRemap uses refcounted pointer, but does not AddRef() itself, so help it
tState.m_tSubExpr[iField] = pAttr->m_pExpr.Ptr();
tState.m_tSubKeys[iField] = JsonKey_t ( pTok, strlen ( pTok ) );
} else
{
CSphString sJsonCol, sJsonKey;
if ( sphJsonNameSplit ( pTok, &sJsonCol, &sJsonKey ) )
{
iAttr = tSchema.GetAttrIndex ( sJsonCol.cstr() );
if ( iAttr>=0 )
{
tState.m_tSubExpr[iField] = sphExprParse ( pTok, tSchema, NULL, NULL, sError, NULL );
tState.m_tSubKeys[iField] = JsonKey_t ( pTok, strlen ( pTok ) );
}
}
}
}
// try json conversion functions (integer()/double()/bigint() in the order by clause)
if ( iAttr<0 )
{
ISphExpr * pExpr = sphExprParse ( pTok, tSchema, &eAttrType, NULL, sError, NULL );
if ( pExpr )
{
tState.m_tSubExpr[iField] = pExpr;
tState.m_tSubKeys[iField] = JsonKey_t ( pTok, strlen(pTok) );
tState.m_tSubKeys[iField].m_uMask = 0;
tState.m_tSubType[iField] = eAttrType;
iAttr = 0; // will be remapped in SetupSortRemap
}
}
// try precalculated json fields received from agents (prefixed with @int_*)
if ( iAttr<0 )
{
CSphString sName;
sName.SetSprintf ( "%s%s", g_sIntAttrPrefix, pTok );
iAttr = tSchema.GetAttrIndex ( sName.cstr() );
}
// epic fail
if ( iAttr<0 )
{
sError.SetSprintf ( "sort-by attribute '%s' not found", pTok );
return SORT_CLAUSE_ERROR;
}
const CSphColumnInfo & tCol = tSchema.GetAttr(iAttr);
tState.m_eKeypart[iField] = Attr2Keypart ( eAttrType!=SPH_ATTR_NONE ? eAttrType : tCol.m_eAttrType );
tState.m_tLocator[iField] = tCol.m_tLocator;
tState.m_dAttrs[iField] = iAttr;
}
}
if ( iField==0 )
{
sError.SetSprintf ( "no sort order defined" );
return SORT_CLAUSE_ERROR;
}
if ( iField==1 )
tState.m_eKeypart[iField++] = SPH_KEYPART_ID; // add "id ASC"
switch ( iField )
{
case 2: eFunc = FUNC_GENERIC2; break;
case 3: eFunc = FUNC_GENERIC3; break;
case 4: eFunc = FUNC_GENERIC4; break;
case 5: eFunc = FUNC_GENERIC5; break;
default: sError.SetSprintf ( "INTERNAL ERROR: %d fields in sphParseSortClause()", iField ); return SORT_CLAUSE_ERROR;
}
return SORT_CLAUSE_OK;
}
//////////////////////////////////////////////////////////////////////////
// SORTING+GROUPING INSTANTIATION
//////////////////////////////////////////////////////////////////////////
template < typename COMPGROUP >
static ISphMatchSorter * sphCreateSorter3rd ( const ISphMatchComparator * pComp, const CSphQuery * pQuery,
const CSphGroupSorterSettings & tSettings, bool bHasPackedFactors )
{
BYTE uSelector = (bHasPackedFactors?1:0)
+(tSettings.m_bDistinct?2:0)
+(tSettings.m_bMVA?4:0)
+(tSettings.m_bImplicit?8:0)
+((pQuery->m_iGroupbyLimit>1)?16:0)
+(tSettings.m_bJson?32:0);
switch ( uSelector )
{
case 0:
return new CSphKBufferGroupSorter < COMPGROUP, false, false > ( pComp, pQuery, tSettings );
case 1:
return new CSphKBufferGroupSorter < COMPGROUP, false, true > ( pComp, pQuery, tSettings );
case 2:
return new CSphKBufferGroupSorter < COMPGROUP, true, false > ( pComp, pQuery, tSettings );
case 3:
return new CSphKBufferGroupSorter < COMPGROUP, true, true > ( pComp, pQuery, tSettings );
case 4:
return new CSphKBufferMVAGroupSorter < COMPGROUP, false, false > ( pComp, pQuery, tSettings );
case 5:
return new CSphKBufferMVAGroupSorter < COMPGROUP, false, true > ( pComp, pQuery, tSettings );
case 6:
return new CSphKBufferMVAGroupSorter < COMPGROUP, true, false > ( pComp, pQuery, tSettings);
case 7:
return new CSphKBufferMVAGroupSorter < COMPGROUP, true, true > ( pComp, pQuery, tSettings);
case 8:
return new CSphImplicitGroupSorter < COMPGROUP, false, false > ( pComp, pQuery, tSettings );
case 9:
return new CSphImplicitGroupSorter < COMPGROUP, false, true > ( pComp, pQuery, tSettings );
case 10:
return new CSphImplicitGroupSorter < COMPGROUP, true, false > ( pComp, pQuery, tSettings );
case 11:
return new CSphImplicitGroupSorter < COMPGROUP, true, true > ( pComp, pQuery, tSettings );
case 16:
return new CSphKBufferNGroupSorter < COMPGROUP, false, false > ( pComp, pQuery, tSettings );
case 17:
return new CSphKBufferNGroupSorter < COMPGROUP, false, true > ( pComp, pQuery, tSettings );
case 18:
return new CSphKBufferNGroupSorter < COMPGROUP, true, false > ( pComp, pQuery, tSettings );
case 19:
return new CSphKBufferNGroupSorter < COMPGROUP, true, true > ( pComp, pQuery, tSettings );
case 32:
return new CSphKBufferJsonGroupSorter < COMPGROUP, false, false > ( pComp, pQuery, tSettings );
case 33:
return new CSphKBufferJsonGroupSorter < COMPGROUP, false, true > ( pComp, pQuery, tSettings );
case 34:
return new CSphKBufferJsonGroupSorter < COMPGROUP, true, false > ( pComp, pQuery, tSettings);
case 35:
return new CSphKBufferJsonGroupSorter < COMPGROUP, true, true > ( pComp, pQuery, tSettings);
}
assert(0);
return NULL;
}
static ISphMatchSorter * sphCreateSorter2nd ( ESphSortFunc eGroupFunc, const ISphMatchComparator * pComp,
const CSphQuery * pQuery, const CSphGroupSorterSettings & tSettings, bool bHasPackedFactors )
{
switch ( eGroupFunc )
{
case FUNC_GENERIC2: return sphCreateSorter3rd<MatchGeneric2_fn> ( pComp, pQuery, tSettings, bHasPackedFactors ); break;
case FUNC_GENERIC3: return sphCreateSorter3rd<MatchGeneric3_fn> ( pComp, pQuery, tSettings, bHasPackedFactors ); break;
case FUNC_GENERIC4: return sphCreateSorter3rd<MatchGeneric4_fn> ( pComp, pQuery, tSettings, bHasPackedFactors ); break;
case FUNC_GENERIC5: return sphCreateSorter3rd<MatchGeneric5_fn> ( pComp, pQuery, tSettings, bHasPackedFactors ); break;
case FUNC_EXPR: return sphCreateSorter3rd<MatchExpr_fn> ( pComp, pQuery, tSettings, bHasPackedFactors ); break;
default: return NULL;
}
}
static ISphMatchSorter * sphCreateSorter1st ( ESphSortFunc eMatchFunc, ESphSortFunc eGroupFunc,
const CSphQuery * pQuery, const CSphGroupSorterSettings & tSettings, bool bHasPackedFactors )
{
if ( tSettings.m_bImplicit )
return sphCreateSorter2nd ( eGroupFunc, NULL, pQuery, tSettings, bHasPackedFactors );
ISphMatchComparator * pComp = NULL;
switch ( eMatchFunc )
{
case FUNC_REL_DESC: pComp = new MatchRelevanceLt_fn(); break;
case FUNC_ATTR_DESC: pComp = new MatchAttrLt_fn(); break;
case FUNC_ATTR_ASC: pComp = new MatchAttrGt_fn(); break;
case FUNC_TIMESEGS: pComp = new MatchTimeSegments_fn(); break;
case FUNC_GENERIC2: pComp = new MatchGeneric2_fn(); break;
case FUNC_GENERIC3: pComp = new MatchGeneric3_fn(); break;
case FUNC_GENERIC4: pComp = new MatchGeneric4_fn(); break;
case FUNC_GENERIC5: pComp = new MatchGeneric5_fn(); break;
case FUNC_EXPR: pComp = new MatchExpr_fn(); break; // only for non-bitfields, obviously
}
assert ( pComp );
return sphCreateSorter2nd ( eGroupFunc, pComp, pQuery, tSettings, bHasPackedFactors );
}
//////////////////////////////////////////////////////////////////////////
// GEODIST
//////////////////////////////////////////////////////////////////////////
struct ExprGeodist_t : public ISphExpr
{
public:
ExprGeodist_t () {}
bool Setup ( const CSphQuery * pQuery, const ISphSchema & tSchema, CSphString & sError );
virtual float Eval ( const CSphMatch & tMatch ) const;
virtual void Command ( ESphExprCommand eCmd, void * pArg );
protected:
CSphAttrLocator m_tGeoLatLoc;
CSphAttrLocator m_tGeoLongLoc;
float m_fGeoAnchorLat;
float m_fGeoAnchorLong;
int m_iLat;
int m_iLon;
};
bool ExprGeodist_t::Setup ( const CSphQuery * pQuery, const ISphSchema & tSchema, CSphString & sError )
{
if ( !pQuery->m_bGeoAnchor )
{
sError.SetSprintf ( "INTERNAL ERROR: no geoanchor, can not create geodist evaluator" );
return false;
}
int iLat = tSchema.GetAttrIndex ( pQuery->m_sGeoLatAttr.cstr() );
if ( iLat<0 )
{
sError.SetSprintf ( "unknown latitude attribute '%s'", pQuery->m_sGeoLatAttr.cstr() );
return false;
}
int iLong = tSchema.GetAttrIndex ( pQuery->m_sGeoLongAttr.cstr() );
if ( iLong<0 )
{
sError.SetSprintf ( "unknown latitude attribute '%s'", pQuery->m_sGeoLongAttr.cstr() );
return false;
}
m_tGeoLatLoc = tSchema.GetAttr(iLat).m_tLocator;
m_tGeoLongLoc = tSchema.GetAttr(iLong).m_tLocator;
m_fGeoAnchorLat = pQuery->m_fGeoLatitude;
m_fGeoAnchorLong = pQuery->m_fGeoLongitude;
m_iLat = iLat;
m_iLon = iLong;
return true;
}
static inline double sphSqr ( double v )
{
return v*v;
}
float ExprGeodist_t::Eval ( const CSphMatch & tMatch ) const
{
const double R = 6384000;
float plat = tMatch.GetAttrFloat ( m_tGeoLatLoc );
float plon = tMatch.GetAttrFloat ( m_tGeoLongLoc );
double dlat = plat - m_fGeoAnchorLat;
double dlon = plon - m_fGeoAnchorLong;
double a = sphSqr ( sin ( dlat/2 ) ) + cos(plat)*cos(m_fGeoAnchorLat)*sphSqr(sin(dlon/2));
double c = 2*asin ( Min ( 1.0, sqrt(a) ) );
return (float)(R*c);
}
void ExprGeodist_t::Command ( ESphExprCommand eCmd, void * pArg )
{
if ( eCmd==SPH_EXPR_GET_DEPENDENT_COLS )
{
static_cast < CSphVector<int>* >(pArg)->Add ( m_iLat );
static_cast < CSphVector<int>* >(pArg)->Add ( m_iLon );
}
}
//////////////////////////////////////////////////////////////////////////
// PUBLIC FUNCTIONS (FACTORY AND FLATTENING)
//////////////////////////////////////////////////////////////////////////
static CSphGrouper * sphCreateGrouperString ( const CSphAttrLocator & tLoc, ESphCollation eCollation );
static CSphGrouper * sphCreateGrouperMulti ( const CSphVector<CSphAttrLocator> & dLocators, const CSphVector<ESphAttr> & dAttrTypes,
const CSphVector<ISphExpr *> & dJsonKeys, ESphCollation eCollation );
static bool SetupGroupbySettings ( const CSphQuery * pQuery, const ISphSchema & tSchema,
CSphGroupSorterSettings & tSettings, CSphVector<int> & dGroupColumns, CSphString & sError, bool bImplicit )
{
tSettings.m_tDistinctLoc.m_iBitOffset = -1;
if ( pQuery->m_sGroupBy.IsEmpty() && !bImplicit )
return true;
if ( pQuery->m_eGroupFunc==SPH_GROUPBY_ATTRPAIR )
{
sError.SetSprintf ( "SPH_GROUPBY_ATTRPAIR is not supported any more (just group on 'bigint' attribute)" );
return false;
}
CSphString sJsonColumn;
CSphString sJsonKey;
if ( pQuery->m_eGroupFunc==SPH_GROUPBY_MULTIPLE )
{
CSphVector<CSphAttrLocator> dLocators;
CSphVector<ESphAttr> dAttrTypes;
CSphVector<ISphExpr *> dJsonKeys;
CSphVector<CSphString> dGroupBy;
const char * a = pQuery->m_sGroupBy.cstr();
const char * b = a;
while ( *a )
{
while ( *b && *b!=',' )
b++;
CSphString & sNew = dGroupBy.Add();
sNew.SetBinary ( a, b-a );
if ( *b==',' )
b += 2;
a = b;
}
dGroupBy.Uniq();
ARRAY_FOREACH ( i, dGroupBy )
{
CSphString sJsonExpr;
dJsonKeys.Add ( NULL );
if ( sphJsonNameSplit ( dGroupBy[i].cstr(), &sJsonColumn, &sJsonKey ) )
{
sJsonExpr = dGroupBy[i];
dGroupBy[i] = sJsonColumn;
}
const int iAttr = tSchema.GetAttrIndex ( dGroupBy[i].cstr() );
if ( iAttr<0 )
{
sError.SetSprintf ( "group-by attribute '%s' not found", dGroupBy[i].cstr() );
return false;
}
ESphAttr eType = tSchema.GetAttr ( iAttr ).m_eAttrType;
if ( eType==SPH_ATTR_UINT32SET || eType==SPH_ATTR_INT64SET )
{
sError.SetSprintf ( "MVA values can't be used in multiple group-by" );
return false;
} else if ( sJsonExpr.IsEmpty() && eType==SPH_ATTR_JSON )
{
sError.SetSprintf ( "JSON blob can't be used in multiple group-by" );
return false;
}
dLocators.Add ( tSchema.GetAttr ( iAttr ).m_tLocator );
dAttrTypes.Add ( eType );
dGroupColumns.Add ( iAttr );
if ( !sJsonExpr.IsEmpty() )
dJsonKeys.Last() = sphExprParse ( sJsonExpr.cstr(), tSchema, NULL, NULL, sError, NULL );
}
tSettings.m_pGrouper = sphCreateGrouperMulti ( dLocators, dAttrTypes, dJsonKeys, pQuery->m_eCollation );
} else if ( sphJsonNameSplit ( pQuery->m_sGroupBy.cstr(), &sJsonColumn, &sJsonKey ) )
{
const int iAttr = tSchema.GetAttrIndex ( sJsonColumn.cstr() );
if ( iAttr<0 )
{
sError.SetSprintf ( "groupby: no such attribute '%s'", sJsonColumn.cstr() );
return false;
}
if ( tSchema.GetAttr(iAttr).m_eAttrType!=SPH_ATTR_JSON )
{
sError.SetSprintf ( "groupby: attribute '%s' does not have subfields (must be sql_attr_json)", sJsonColumn.cstr() );
return false;
}
if ( pQuery->m_eGroupFunc!=SPH_GROUPBY_ATTR )
{
sError.SetSprintf ( "groupby: legacy groupby modes are not supported on JSON attributes" );
return false;
}
dGroupColumns.Add ( iAttr );
// FIXME! handle collations here?
ISphExpr * pExpr = sphExprParse ( pQuery->m_sGroupBy.cstr(), tSchema, NULL, NULL, sError, NULL );
tSettings.m_pGrouper = new CSphGrouperJsonField ( tSchema.GetAttr(iAttr).m_tLocator, pExpr );
tSettings.m_bJson = true;
} else if ( bImplicit )
{
tSettings.m_bImplicit = true;
} else
{
// setup groupby attr
int iGroupBy = tSchema.GetAttrIndex ( pQuery->m_sGroupBy.cstr() );
if ( iGroupBy<0 )
{
// try aliased groupby attr (facets)
ARRAY_FOREACH ( i, pQuery->m_dItems )
if ( pQuery->m_sGroupBy==pQuery->m_dItems[i].m_sExpr )
{
iGroupBy = tSchema.GetAttrIndex ( pQuery->m_dItems[i].m_sAlias.cstr() );
break;
}
}
if ( iGroupBy<0 )
{
sError.SetSprintf ( "group-by attribute '%s' not found", pQuery->m_sGroupBy.cstr() );
return false;
}
ESphAttr eType = tSchema.GetAttr ( iGroupBy ).m_eAttrType;
CSphAttrLocator tLoc = tSchema.GetAttr ( iGroupBy ).m_tLocator;
switch ( pQuery->m_eGroupFunc )
{
case SPH_GROUPBY_DAY: tSettings.m_pGrouper = new CSphGrouperDay ( tLoc ); break;
case SPH_GROUPBY_WEEK: tSettings.m_pGrouper = new CSphGrouperWeek ( tLoc ); break;
case SPH_GROUPBY_MONTH: tSettings.m_pGrouper = new CSphGrouperMonth ( tLoc ); break;
case SPH_GROUPBY_YEAR: tSettings.m_pGrouper = new CSphGrouperYear ( tLoc ); break;
case SPH_GROUPBY_ATTR:
if ( eType==SPH_ATTR_JSON )
{
// allow group by top-level json array
ISphExpr * pExpr = sphExprParse ( pQuery->m_sGroupBy.cstr(), tSchema, NULL, NULL, sError, NULL );
tSettings.m_pGrouper = new CSphGrouperJsonField ( tLoc, pExpr );
tSettings.m_bJson = true;
} else if ( eType==SPH_ATTR_STRING )
tSettings.m_pGrouper = sphCreateGrouperString ( tLoc, pQuery->m_eCollation );
else
tSettings.m_pGrouper = new CSphGrouperAttr ( tLoc );
break;
default:
sError.SetSprintf ( "invalid group-by mode (mode=%d)", pQuery->m_eGroupFunc );
return false;
}
tSettings.m_bMVA = ( eType==SPH_ATTR_UINT32SET || eType==SPH_ATTR_INT64SET );
tSettings.m_bMva64 = ( eType==SPH_ATTR_INT64SET );
dGroupColumns.Add ( iGroupBy );
}
// setup distinct attr
if ( !pQuery->m_sGroupDistinct.IsEmpty() )
{
int iDistinct = tSchema.GetAttrIndex ( pQuery->m_sGroupDistinct.cstr() );
if ( iDistinct<0 )
{
sError.SetSprintf ( "group-count-distinct attribute '%s' not found", pQuery->m_sGroupDistinct.cstr() );
return false;
}
tSettings.m_tDistinctLoc = tSchema.GetAttr ( iDistinct ).m_tLocator;
}
return true;
}
// move expressions used in ORDER BY or WITHIN GROUP ORDER BY to presort phase
static bool FixupDependency ( ISphSchema & tSchema, const int * pAttrs, int iAttrCount )
{
assert ( pAttrs );
CSphVector<int> dCur;
// add valid attributes to processing list
for ( int i=0; i<iAttrCount; i++ )
if ( pAttrs[i]>=0 )
dCur.Add ( pAttrs[i] );
int iInitialAttrs = dCur.GetLength();
// collect columns which affect current expressions
for ( int i=0; i<dCur.GetLength(); i++ )
{
const CSphColumnInfo & tCol = tSchema.GetAttr ( dCur[i] );
if ( tCol.m_eStage>SPH_EVAL_PRESORT && tCol.m_pExpr.Ptr()!=NULL )
tCol.m_pExpr->Command ( SPH_EXPR_GET_DEPENDENT_COLS, &dCur );
}
// get rid of dupes
dCur.Uniq();
// fix up of attributes stages
ARRAY_FOREACH ( i, dCur )
{
int iAttr = dCur[i];
if ( iAttr<0 )
continue;
CSphColumnInfo & tCol = const_cast < CSphColumnInfo & > ( tSchema.GetAttr ( iAttr ) );
if ( tCol.m_eStage==SPH_EVAL_FINAL )
tCol.m_eStage = SPH_EVAL_PRESORT;
}
// it uses attributes if it has dependencies from other attributes
return ( iInitialAttrs>dCur.GetLength() );
}
// expression that transform string pool base + offset -> ptr
struct ExprSortStringAttrFixup_c : public ISphExpr
{
const BYTE * m_pStrings; ///< string pool; base for offset of string attributes
const CSphAttrLocator m_tLocator; ///< string attribute to fix
explicit ExprSortStringAttrFixup_c ( const CSphAttrLocator & tLocator )
: m_pStrings ( NULL )
, m_tLocator ( tLocator )
{
}
virtual float Eval ( const CSphMatch & ) const { assert ( 0 ); return 0.0f; }
virtual int64_t Int64Eval ( const CSphMatch & tMatch ) const
{
SphAttr_t uOff = tMatch.GetAttr ( m_tLocator );
return (int64_t)( m_pStrings && uOff ? m_pStrings + uOff : NULL );
}
virtual void Command ( ESphExprCommand eCmd, void * pArg )
{
if ( eCmd==SPH_EXPR_SET_STRING_POOL )
m_pStrings = (const BYTE*)pArg;
}
};
// expression that transform string pool base + offset -> ptr
struct ExprSortJson2StringPtr_c : public ISphExpr
{
const BYTE * m_pStrings; ///< string pool; base for offset of string attributes
const CSphAttrLocator m_tJsonCol; ///< JSON attribute to fix
CSphRefcountedPtr<ISphExpr> m_pExpr;
ExprSortJson2StringPtr_c ( const CSphAttrLocator & tLocator, ISphExpr * pExpr )
: m_pStrings ( NULL )
, m_tJsonCol ( tLocator )
, m_pExpr ( pExpr )
{}
virtual bool IsStringPtr () const { return true; }
virtual float Eval ( const CSphMatch & ) const { assert ( 0 ); return 0.0f; }
virtual int StringEval ( const CSphMatch & tMatch, const BYTE ** ppStr ) const
{
if ( !m_pStrings || !m_pExpr )
{
*ppStr = NULL;
return 0;
}
uint64_t uValue = m_pExpr->Int64Eval ( tMatch );
const BYTE * pVal = m_pStrings + ( uValue & 0xffffffff );
ESphJsonType eJson = (ESphJsonType)( uValue >> 32 );
CSphString sVal;
// FIXME!!! make string length configurable for STRING and STRING_VECTOR to compare and allocate only Min(String.Length, CMP_LENGTH)
switch ( eJson )
{
case JSON_INT32:
sVal.SetSprintf ( "%d", sphJsonLoadInt ( &pVal ) );
break;
case JSON_INT64:
sVal.SetSprintf ( INT64_FMT, sphJsonLoadBigint ( &pVal ) );
break;
case JSON_DOUBLE:
sVal.SetSprintf ( "%f", sphQW2D ( sphJsonLoadBigint ( &pVal ) ) );
break;
case JSON_STRING:
{
int iLen = sphJsonUnpackInt ( &pVal );
sVal.SetBinary ( (const char *)pVal, iLen );
break;
}
case JSON_STRING_VECTOR:
{
int iTotalLen = sphJsonUnpackInt ( &pVal );
int iCount = sphJsonUnpackInt ( &pVal );
CSphFixedVector<BYTE> dBuf ( iTotalLen + 4 ); // data and tail GAP
BYTE * pDst = dBuf.Begin();
// head element
if ( iCount )
{
int iElemLen = sphJsonUnpackInt ( &pVal );
memcpy ( pDst, pVal, iElemLen );
pDst += iElemLen;
}
// tail elements separated by space
for ( int i=1; i<iCount; i++ )
{
*pDst++ = ' ';
int iElemLen = sphJsonUnpackInt ( &pVal );
memcpy ( pDst, pVal, iElemLen );
pDst += iElemLen;
}
int iStrLen = pDst-dBuf.Begin();
// filling junk space
while ( pDst<dBuf.Begin()+dBuf.GetLength() )
*pDst++ = '\0';
*ppStr = dBuf.LeakData();
return iStrLen;
}
default:
break;
}
int iStriLen = sVal.Length();
*ppStr = (const BYTE *)sVal.Leak();
return iStriLen;
}
virtual void Command ( ESphExprCommand eCmd, void * pArg )
{
if ( eCmd==SPH_EXPR_SET_STRING_POOL )
{
m_pStrings = (const BYTE*)pArg;
if ( m_pExpr.Ptr() )
m_pExpr->Command ( eCmd, pArg );
}
}
};
bool sphIsSortStringInternal ( const char * sColumnName )
{
assert ( sColumnName );
return ( strncmp ( sColumnName, g_sIntAttrPrefix, sizeof(g_sIntAttrPrefix)-1 )==0 );
}
// only STRING ( static packed ) and JSON fields mush be remapped
static void SetupSortRemap ( CSphRsetSchema & tSorterSchema, CSphMatchComparatorState & tState )
{
#ifndef NDEBUG
int iColWasCount = tSorterSchema.GetAttrsCount();
#endif
for ( int i=0; i<CSphMatchComparatorState::MAX_ATTRS; i++ )
{
if ( !( tState.m_eKeypart[i]==SPH_KEYPART_STRING || tState.m_tSubKeys[i].m_sKey.cstr() ) )
continue;
assert ( tState.m_dAttrs[i]>=0 && tState.m_dAttrs[i]<iColWasCount );
bool bIsJson = !tState.m_tSubKeys[i].m_sKey.IsEmpty();
bool bIsFunc = bIsJson && tState.m_tSubKeys[i].m_uMask==0;
CSphString sRemapCol;
sRemapCol.SetSprintf ( "%s%s", g_sIntAttrPrefix, bIsJson
? tState.m_tSubKeys[i].m_sKey.cstr()
: tSorterSchema.GetAttr ( tState.m_dAttrs[i] ).m_sName.cstr() );
int iRemap = tSorterSchema.GetAttrIndex ( sRemapCol.cstr() );
if ( iRemap==-1 && bIsJson )
{
CSphString sRemapLowercase = sRemapCol;
sRemapLowercase.ToLower();
iRemap = tSorterSchema.GetAttrIndex ( sRemapLowercase.cstr() );
}
if ( iRemap==-1 )
{
CSphColumnInfo tRemapCol ( sRemapCol.cstr(), bIsJson ? SPH_ATTR_STRINGPTR : SPH_ATTR_BIGINT );
tRemapCol.m_eStage = SPH_EVAL_PRESORT;
if ( bIsJson )
tRemapCol.m_pExpr = bIsFunc ? tState.m_tSubExpr[i] : new ExprSortJson2StringPtr_c ( tState.m_tLocator[i], tState.m_tSubExpr[i] );
else
tRemapCol.m_pExpr = new ExprSortStringAttrFixup_c ( tState.m_tLocator[i] );
if ( bIsFunc )
{
tRemapCol.m_eAttrType = tState.m_tSubType[i];
tState.m_eKeypart[i] = Attr2Keypart ( tState.m_tSubType[i] );
}
iRemap = tSorterSchema.GetAttrsCount();
tSorterSchema.AddDynamicAttr ( tRemapCol );
}
tState.m_tLocator[i] = tSorterSchema.GetAttr ( iRemap ).m_tLocator;
}
}
bool sphSortGetStringRemap ( const ISphSchema & tSorterSchema, const ISphSchema & tIndexSchema,
CSphVector<SphStringSorterRemap_t> & dAttrs )
{
dAttrs.Resize ( 0 );
for ( int i=0; i<tSorterSchema.GetAttrsCount(); i++ )
{
const CSphColumnInfo & tDst = tSorterSchema.GetAttr(i);
// remap only static strings
if ( !tDst.m_sName.Begins ( g_sIntAttrPrefix ) || tDst.m_eAttrType==SPH_ATTR_STRINGPTR )
continue;
const CSphColumnInfo * pSrcCol = tIndexSchema.GetAttr ( tDst.m_sName.cstr()+sizeof(g_sIntAttrPrefix)-1 );
if ( !pSrcCol ) // skip internal attributes received from agents
continue;
SphStringSorterRemap_t & tRemap = dAttrs.Add();
tRemap.m_tSrc = pSrcCol->m_tLocator;
tRemap.m_tDst = tDst.m_tLocator;
}
return ( dAttrs.GetLength()>0 );
}
////////////////////
// BINARY COLLATION
////////////////////
int sphCollateBinary ( const BYTE * pStr1, const BYTE * pStr2, bool bPacked )
{
if ( bPacked )
{
int iLen1 = sphUnpackStr ( pStr1, &pStr1 );
int iLen2 = sphUnpackStr ( pStr2, &pStr2 );
int iRes = memcmp ( (const char *)pStr1, (const char *)pStr2, Min ( iLen1, iLen2 ) );
return iRes ? iRes : ( iLen1-iLen2 );
} else
{
return strcmp ( (const char *)pStr1, (const char *)pStr2 );
}
}
///////////////////////////////
// LIBC_CI, LIBC_CS COLLATIONS
///////////////////////////////
/// libc_ci, wrapper for strcasecmp
int sphCollateLibcCI ( const BYTE * pStr1, const BYTE * pStr2, bool bPacked )
{
if ( bPacked )
{
int iLen1 = sphUnpackStr ( pStr1, &pStr1 );
int iLen2 = sphUnpackStr ( pStr2, &pStr2 );
int iRes = strncasecmp ( (const char *)pStr1, (const char *)pStr2, Min ( iLen1, iLen2 ) );
return iRes ? iRes : ( iLen1-iLen2 );
} else
{
return strcasecmp ( (const char *)pStr1, (const char *)pStr2 );
}
}
/// libc_cs, wrapper for strcoll
int sphCollateLibcCS ( const BYTE * pStr1, const BYTE * pStr2, bool bPacked )
{
#define COLLATE_STACK_BUFFER 1024
if ( bPacked )
{
int iLen1 = sphUnpackStr ( pStr1, &pStr1 );
int iLen2 = sphUnpackStr ( pStr2, &pStr2 );
// strcoll wants asciiz strings, so we would have to copy them over
// lets use stack buffer for smaller ones, and allocate from heap for bigger ones
int iRes = 0;
int iLen = Min ( iLen1, iLen2 );
if ( iLen<COLLATE_STACK_BUFFER )
{
// small strings on stack
BYTE sBuf1[COLLATE_STACK_BUFFER];
BYTE sBuf2[COLLATE_STACK_BUFFER];
memcpy ( sBuf1, pStr1, iLen );
memcpy ( sBuf2, pStr2, iLen );
sBuf1[iLen] = sBuf2[iLen] = '\0';
iRes = strcoll ( (const char*)sBuf1, (const char*)sBuf2 );
} else
{
// big strings on heap
char * pBuf1 = new char [ iLen ];
char * pBuf2 = new char [ iLen ];
memcpy ( pBuf1, pStr1, iLen );
memcpy ( pBuf2, pStr2, iLen );
pBuf1[iLen] = pBuf2[iLen] = '\0';
iRes = strcoll ( (const char*)pBuf1, (const char*)pBuf2 );
SafeDeleteArray ( pBuf2 );
SafeDeleteArray ( pBuf1 );
}
return iRes ? iRes : ( iLen1-iLen2 );
} else
{
return strcoll ( (const char *)pStr1, (const char *)pStr2 );
}
}
/////////////////////////////
// UTF8_GENERAL_CI COLLATION
/////////////////////////////
/// 1st level LUT
static unsigned short * g_dCollPlanes_UTF8CI[0x100];
/// 2nd level LUT, non-trivial collation data
static unsigned short g_dCollWeights_UTF8CI[0xb00] =
{
// weights for 0x0 to 0x5ff
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 123, 124, 125, 126, 127,
128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, 179, 180, 924, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
65, 65, 65, 65, 65, 65, 198, 67, 69, 69, 69, 69, 73, 73, 73, 73,
208, 78, 79, 79, 79, 79, 79, 215, 216, 85, 85, 85, 85, 89, 222, 83,
65, 65, 65, 65, 65, 65, 198, 67, 69, 69, 69, 69, 73, 73, 73, 73,
208, 78, 79, 79, 79, 79, 79, 247, 216, 85, 85, 85, 85, 89, 222, 89,
65, 65, 65, 65, 65, 65, 67, 67, 67, 67, 67, 67, 67, 67, 68, 68,
272, 272, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 71, 71, 71, 71,
71, 71, 71, 71, 72, 72, 294, 294, 73, 73, 73, 73, 73, 73, 73, 73,
73, 73, 306, 306, 74, 74, 75, 75, 312, 76, 76, 76, 76, 76, 76, 319,
319, 321, 321, 78, 78, 78, 78, 78, 78, 329, 330, 330, 79, 79, 79, 79,
79, 79, 338, 338, 82, 82, 82, 82, 82, 82, 83, 83, 83, 83, 83, 83,
83, 83, 84, 84, 84, 84, 358, 358, 85, 85, 85, 85, 85, 85, 85, 85,
85, 85, 85, 85, 87, 87, 89, 89, 89, 90, 90, 90, 90, 90, 90, 83,
384, 385, 386, 386, 388, 388, 390, 391, 391, 393, 394, 395, 395, 397, 398, 399,
400, 401, 401, 403, 404, 502, 406, 407, 408, 408, 410, 411, 412, 413, 414, 415,
79, 79, 418, 418, 420, 420, 422, 423, 423, 425, 426, 427, 428, 428, 430, 85,
85, 433, 434, 435, 435, 437, 437, 439, 440, 440, 442, 443, 444, 444, 446, 503,
448, 449, 450, 451, 452, 452, 452, 455, 455, 455, 458, 458, 458, 65, 65, 73,
73, 79, 79, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 398, 65, 65,
65, 65, 198, 198, 484, 484, 71, 71, 75, 75, 79, 79, 79, 79, 439, 439,
74, 497, 497, 497, 71, 71, 502, 503, 78, 78, 65, 65, 198, 198, 216, 216,
65, 65, 65, 65, 69, 69, 69, 69, 73, 73, 73, 73, 79, 79, 79, 79,
82, 82, 82, 82, 85, 85, 85, 85, 83, 83, 84, 84, 540, 540, 72, 72,
544, 545, 546, 546, 548, 548, 65, 65, 69, 69, 79, 79, 79, 79, 79, 79,
79, 79, 89, 89, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575,
576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591,
592, 593, 594, 385, 390, 597, 393, 394, 600, 399, 602, 400, 604, 605, 606, 607,
403, 609, 610, 404, 612, 613, 614, 615, 407, 406, 618, 619, 620, 621, 622, 412,
624, 625, 413, 627, 628, 415, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639,
422, 641, 642, 425, 644, 645, 646, 647, 430, 649, 433, 434, 652, 653, 654, 655,
656, 657, 439, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671,
672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687,
688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703,
704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719,
720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735,
736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751,
752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767,
768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783,
784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799,
800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815,
816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831,
832, 833, 834, 835, 836, 921, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847,
848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863,
864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879,
880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895,
896, 897, 898, 899, 900, 901, 913, 903, 917, 919, 921, 907, 927, 909, 933, 937,
921, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927,
928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 921, 933, 913, 917, 919, 921,
933, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927,
928, 929, 931, 931, 932, 933, 934, 935, 936, 937, 921, 933, 927, 933, 937, 975,
914, 920, 978, 978, 978, 934, 928, 983, 984, 985, 986, 986, 988, 988, 990, 990,
992, 992, 994, 994, 996, 996, 998, 998, 1000, 1000, 1002, 1002, 1004, 1004, 1006, 1006,
922, 929, 931, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023,
1045, 1045, 1026, 1043, 1028, 1029, 1030, 1030, 1032, 1033, 1034, 1035, 1050, 1048, 1059, 1039,
1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055,
1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071,
1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055,
1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071,
1045, 1045, 1026, 1043, 1028, 1029, 1030, 1030, 1032, 1033, 1034, 1035, 1050, 1048, 1059, 1039,
1120, 1120, 1122, 1122, 1124, 1124, 1126, 1126, 1128, 1128, 1130, 1130, 1132, 1132, 1134, 1134,
1136, 1136, 1138, 1138, 1140, 1140, 1140, 1140, 1144, 1144, 1146, 1146, 1148, 1148, 1150, 1150,
1152, 1152, 1154, 1155, 1156, 1157, 1158, 1159, 1160, 1161, 1162, 1163, 1164, 1164, 1166, 1166,
1168, 1168, 1170, 1170, 1172, 1172, 1174, 1174, 1176, 1176, 1178, 1178, 1180, 1180, 1182, 1182,
1184, 1184, 1186, 1186, 1188, 1188, 1190, 1190, 1192, 1192, 1194, 1194, 1196, 1196, 1198, 1198,
1200, 1200, 1202, 1202, 1204, 1204, 1206, 1206, 1208, 1208, 1210, 1210, 1212, 1212, 1214, 1214,
1216, 1046, 1046, 1219, 1219, 1221, 1222, 1223, 1223, 1225, 1226, 1227, 1227, 1229, 1230, 1231,
1040, 1040, 1040, 1040, 1236, 1236, 1045, 1045, 1240, 1240, 1240, 1240, 1046, 1046, 1047, 1047,
1248, 1248, 1048, 1048, 1048, 1048, 1054, 1054, 1256, 1256, 1256, 1256, 1069, 1069, 1059, 1059,
1059, 1059, 1059, 1059, 1063, 1063, 1270, 1271, 1067, 1067, 1274, 1275, 1276, 1277, 1278, 1279,
1280, 1281, 1282, 1283, 1284, 1285, 1286, 1287, 1288, 1289, 1290, 1291, 1292, 1293, 1294, 1295,
1296, 1297, 1298, 1299, 1300, 1301, 1302, 1303, 1304, 1305, 1306, 1307, 1308, 1309, 1310, 1311,
1312, 1313, 1314, 1315, 1316, 1317, 1318, 1319, 1320, 1321, 1322, 1323, 1324, 1325, 1326, 1327,
1328, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343,
1344, 1345, 1346, 1347, 1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358, 1359,
1360, 1361, 1362, 1363, 1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1372, 1373, 1374, 1375,
1376, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343,
1344, 1345, 1346, 1347, 1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358, 1359,
1360, 1361, 1362, 1363, 1364, 1365, 1366, 1415, 1416, 1417, 1418, 1419, 1420, 1421, 1422, 1423,
1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 1434, 1435, 1436, 1437, 1438, 1439,
1440, 1441, 1442, 1443, 1444, 1445, 1446, 1447, 1448, 1449, 1450, 1451, 1452, 1453, 1454, 1455,
1456, 1457, 1458, 1459, 1460, 1461, 1462, 1463, 1464, 1465, 1466, 1467, 1468, 1469, 1470, 1471,
1472, 1473, 1474, 1475, 1476, 1477, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487,
1488, 1489, 1490, 1491, 1492, 1493, 1494, 1495, 1496, 1497, 1498, 1499, 1500, 1501, 1502, 1503,
1504, 1505, 1506, 1507, 1508, 1509, 1510, 1511, 1512, 1513, 1514, 1515, 1516, 1517, 1518, 1519,
1520, 1521, 1522, 1523, 1524, 1525, 1526, 1527, 1528, 1529, 1530, 1531, 1532, 1533, 1534, 1535,
// weights for codepoints 0x1e00 to 0x1fff
65, 65, 66, 66, 66, 66, 66, 66, 67, 67, 68, 68, 68, 68, 68, 68,
68, 68, 68, 68, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 70, 70,
71, 71, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 73, 73, 73, 73,
75, 75, 75, 75, 75, 75, 76, 76, 76, 76, 76, 76, 76, 76, 77, 77,
77, 77, 77, 77, 78, 78, 78, 78, 78, 78, 78, 78, 79, 79, 79, 79,
79, 79, 79, 79, 80, 80, 80, 80, 82, 82, 82, 82, 82, 82, 82, 82,
83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 84, 84, 84, 84, 84, 84,
84, 84, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 86, 86, 86, 86,
87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 88, 88, 88, 88, 89, 89,
90, 90, 90, 90, 90, 90, 72, 84, 87, 89, 7834, 83, 7836, 7837, 7838, 7839,
65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
65, 65, 65, 65, 65, 65, 65, 65, 69, 69, 69, 69, 69, 69, 69, 69,
69, 69, 69, 69, 69, 69, 69, 69, 73, 73, 73, 73, 79, 79, 79, 79,
79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79,
79, 79, 79, 79, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85,
85, 85, 89, 89, 89, 89, 89, 89, 89, 89, 7930, 7931, 7932, 7933, 7934, 7935,
913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913,
917, 917, 917, 917, 917, 917, 7958, 7959, 917, 917, 917, 917, 917, 917, 7966, 7967,
919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919,
921, 921, 921, 921, 921, 921, 921, 921, 921, 921, 921, 921, 921, 921, 921, 921,
927, 927, 927, 927, 927, 927, 8006, 8007, 927, 927, 927, 927, 927, 927, 8014, 8015,
933, 933, 933, 933, 933, 933, 933, 933, 8024, 933, 8026, 933, 8028, 933, 8030, 933,
937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937,
913, 8123, 917, 8137, 919, 8139, 921, 8155, 927, 8185, 933, 8171, 937, 8187, 8062, 8063,
913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913,
919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919,
937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937,
913, 913, 913, 913, 913, 8117, 913, 913, 913, 913, 913, 8123, 913, 8125, 921, 8127,
8128, 8129, 919, 919, 919, 8133, 919, 919, 917, 8137, 919, 8139, 919, 8141, 8142, 8143,
921, 921, 921, 8147, 8148, 8149, 921, 921, 921, 921, 921, 8155, 8156, 8157, 8158, 8159,
933, 933, 933, 8163, 929, 929, 933, 933, 933, 933, 933, 8171, 929, 8173, 8174, 8175,
8176, 8177, 937, 937, 937, 8181, 937, 937, 927, 8185, 937, 8187, 937, 8189, 8190, 8191
// space for codepoints 0x21xx, 0x24xx, 0xffxx (generated)
};
/// initialize collation LUTs
void sphCollationInit()
{
const int dWeightPlane[0x0b] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x1e, 0x1f, 0x21, 0x24, 0xff };
// generate missing weights
for ( int i=0; i<0x100; i++ )
{
g_dCollWeights_UTF8CI[i+0x800] = (unsigned short)( 0x2100 + i - ( i>=0x70 && i<=0x7f )*16 ); // 2170..217f, -16
g_dCollWeights_UTF8CI[i+0x900] = (unsigned short)( 0x2400 + i - ( i>=0xd0 && i<=0xe9 )*26 ); // 24d0..24e9, -26
g_dCollWeights_UTF8CI[i+0xa00] = (unsigned short)( 0xff00 + i - ( i>=0x41 && i<=0x5a )*32 ); // ff41..ff5a, -32
}
// generate planes table
for ( int i=0; i<0x100; i++ )
g_dCollPlanes_UTF8CI[i] = NULL;
for ( int i=0; i<0x0b; i++ )
g_dCollPlanes_UTF8CI [ dWeightPlane[i] ] = g_dCollWeights_UTF8CI + 0x100*i;
}
/// collate a single codepoint
static inline int CollateUTF8CI ( int iCode )
{
return ( ( iCode>>16 ) || !g_dCollPlanes_UTF8CI [ iCode>>8 ] )
? iCode
: g_dCollPlanes_UTF8CI [ iCode>>8 ][ iCode&0xff ];
}
/// utf8_general_ci
int sphCollateUtf8GeneralCI ( const BYTE * pArg1, const BYTE * pArg2, bool bPacked )
{
const BYTE * pStr1 = pArg1;
const BYTE * pStr2 = pArg2;
const BYTE * pMax1 = NULL;
const BYTE * pMax2 = NULL;
if ( bPacked )
{
int iLen1 = sphUnpackStr ( pStr1, (const BYTE**)&pStr1 );
int iLen2 = sphUnpackStr ( pStr2, (const BYTE**)&pStr2 );
pMax1 = pStr1 + iLen1;
pMax2 = pStr2 + iLen2;
}
while ( ( bPacked && pStr1<pMax1 && pStr2<pMax2 ) || ( !bPacked && *pStr1 && *pStr2 ) )
{
// FIXME! on broken data, decode might go beyond buffer bounds
int iCode1 = sphUTF8Decode ( pStr1 );
int iCode2 = sphUTF8Decode ( pStr2 );
if ( !iCode1 && !iCode2 )
return 0;
if ( !iCode1 || !iCode2 )
return !iCode1 ? -1 : 1;
if ( iCode1==iCode2 )
continue;
iCode1 = CollateUTF8CI ( iCode1 );
iCode2 = CollateUTF8CI ( iCode2 );
if ( iCode1!=iCode2 )
return iCode1-iCode2;
}
if ( bPacked )
{
if ( pStr1>=pMax1 && pStr2>=pMax2 )
return 0;
return ( pStr1<pMax1 ) ? 1 : -1;
} else
{
if ( !*pStr1 && !*pStr2 )
return 0;
return ( *pStr1 ? 1 : -1 );
}
}
/////////////////////////////
// hashing functions
/////////////////////////////
class LibcCSHash_fn
{
public:
mutable CSphTightVector<BYTE> m_dBuf;
static const int LOCALE_SAFE_GAP = 16;
LibcCSHash_fn()
{
m_dBuf.Resize ( COLLATE_STACK_BUFFER );
}
uint64_t Hash ( const BYTE * pStr, int iLen, uint64_t uPrev=SPH_FNV64_SEED ) const
{
assert ( pStr && iLen );
int iCompositeLen = iLen + 1 + (int)( 3.0f * iLen ) + LOCALE_SAFE_GAP;
if ( m_dBuf.GetLength()<iCompositeLen )
m_dBuf.Resize ( iCompositeLen );
memcpy ( m_dBuf.Begin(), pStr, iLen );
m_dBuf[iLen] = '\0';
BYTE * pDst = m_dBuf.Begin()+iLen+1;
int iDstAvailable = m_dBuf.GetLength() - iLen - LOCALE_SAFE_GAP;
int iDstLen = strxfrm ( (char *)pDst, (const char *)m_dBuf.Begin(), iDstAvailable );
assert ( iDstLen<iDstAvailable+LOCALE_SAFE_GAP );
uint64_t uAcc = sphFNV64 ( pDst, iDstLen, uPrev );
return uAcc;
}
};
class LibcCIHash_fn
{
public:
uint64_t Hash ( const BYTE * pStr, int iLen, uint64_t uPrev=SPH_FNV64_SEED ) const
{
assert ( pStr && iLen );
uint64_t uAcc = uPrev;
while ( iLen-- )
{
int iChar = tolower ( *pStr++ );
uAcc = sphFNV64 ( &iChar, 4, uAcc );
}
return uAcc;
}
};
class Utf8CIHash_fn
{
public:
uint64_t Hash ( const BYTE * pStr, int iLen, uint64_t uPrev=SPH_FNV64_SEED ) const
{
assert ( pStr && iLen );
uint64_t uAcc = uPrev;
while ( iLen-- )
{
const BYTE * pCur = pStr++;
int iCode = sphUTF8Decode ( pCur );
iCode = CollateUTF8CI ( iCode );
uAcc = sphFNV64 ( &iCode, 4, uAcc );
}
return uAcc;
}
};
CSphGrouper * sphCreateGrouperString ( const CSphAttrLocator & tLoc, ESphCollation eCollation )
{
if ( eCollation==SPH_COLLATION_UTF8_GENERAL_CI )
return new CSphGrouperString<Utf8CIHash_fn> ( tLoc );
else if ( eCollation==SPH_COLLATION_LIBC_CI )
return new CSphGrouperString<LibcCIHash_fn> ( tLoc );
else if ( eCollation==SPH_COLLATION_LIBC_CS )
return new CSphGrouperString<LibcCSHash_fn> ( tLoc );
else
return new CSphGrouperString<BinaryHash_fn> ( tLoc );
}
CSphGrouper * sphCreateGrouperMulti ( const CSphVector<CSphAttrLocator> & dLocators, const CSphVector<ESphAttr> & dAttrTypes,
const CSphVector<ISphExpr *> & dJsonKeys, ESphCollation eCollation )
{
if ( eCollation==SPH_COLLATION_UTF8_GENERAL_CI )
return new CSphGrouperMulti<Utf8CIHash_fn> ( dLocators, dAttrTypes, dJsonKeys );
else if ( eCollation==SPH_COLLATION_LIBC_CI )
return new CSphGrouperMulti<LibcCIHash_fn> ( dLocators, dAttrTypes, dJsonKeys );
else if ( eCollation==SPH_COLLATION_LIBC_CS )
return new CSphGrouperMulti<LibcCSHash_fn> ( dLocators, dAttrTypes, dJsonKeys );
else
return new CSphGrouperMulti<BinaryHash_fn> ( dLocators, dAttrTypes, dJsonKeys );
}
/////////////////////////
// SORTING QUEUE FACTORY
/////////////////////////
template < typename COMP >
static ISphMatchSorter * CreatePlainSorter ( bool bKbuffer, int iMaxMatches, bool bUsesAttrs, bool bFactors )
{
if ( bKbuffer )
{
if ( bFactors )
return new CSphKbufferMatchQueue<COMP, true> ( iMaxMatches, bUsesAttrs );
else
return new CSphKbufferMatchQueue<COMP, false> ( iMaxMatches, bUsesAttrs );
} else
{
if ( bFactors )
return new CSphMatchQueue<COMP, true> ( iMaxMatches, bUsesAttrs );
else
return new CSphMatchQueue<COMP, false> ( iMaxMatches, bUsesAttrs );
}
}
static ISphMatchSorter * CreatePlainSorter ( ESphSortFunc eMatchFunc, bool bKbuffer, int iMaxMatches, bool bUsesAttrs, bool bFactors )
{
switch ( eMatchFunc )
{
case FUNC_REL_DESC: return CreatePlainSorter<MatchRelevanceLt_fn> ( bKbuffer, iMaxMatches, bUsesAttrs, bFactors ); break;
case FUNC_ATTR_DESC: return CreatePlainSorter<MatchAttrLt_fn> ( bKbuffer, iMaxMatches, bUsesAttrs, bFactors ); break;
case FUNC_ATTR_ASC: return CreatePlainSorter<MatchAttrGt_fn> ( bKbuffer, iMaxMatches, bUsesAttrs, bFactors ); break;
case FUNC_TIMESEGS: return CreatePlainSorter<MatchTimeSegments_fn> ( bKbuffer, iMaxMatches, bUsesAttrs, bFactors ); break;
case FUNC_GENERIC2: return CreatePlainSorter<MatchGeneric2_fn> ( bKbuffer, iMaxMatches, bUsesAttrs, bFactors ); break;
case FUNC_GENERIC3: return CreatePlainSorter<MatchGeneric3_fn> ( bKbuffer, iMaxMatches, bUsesAttrs, bFactors ); break;
case FUNC_GENERIC4: return CreatePlainSorter<MatchGeneric4_fn> ( bKbuffer, iMaxMatches, bUsesAttrs, bFactors ); break;
case FUNC_GENERIC5: return CreatePlainSorter<MatchGeneric5_fn> ( bKbuffer, iMaxMatches, bUsesAttrs, bFactors ); break;
case FUNC_EXPR: return CreatePlainSorter<MatchExpr_fn> ( bKbuffer, iMaxMatches, bUsesAttrs, bFactors ); break;
default: return NULL;
}
}
static void ExtraAddSortkeys ( CSphSchema * pExtra, const ISphSchema & tSorterSchema, const int * dAttrs )
{
if ( pExtra )
for ( int i=0; i<CSphMatchComparatorState::MAX_ATTRS; i++ )
if ( dAttrs[i]>=0 )
pExtra->AddAttr ( tSorterSchema.GetAttr ( dAttrs[i] ), true );
}
ISphMatchSorter * sphCreateQueue ( SphQueueSettings_t & tQueue )
{
// prepare for descent
ISphMatchSorter * pTop = NULL;
CSphMatchComparatorState tStateMatch, tStateGroup;
// short-cuts
const CSphQuery * pQuery = &tQueue.m_tQuery;
const ISphSchema & tSchema = tQueue.m_tSchema;
CSphString & sError = tQueue.m_sError;
CSphQueryProfile * pProfiler = tQueue.m_pProfiler;
CSphSchema * pExtra = tQueue.m_pExtra;
sError = "";
bool bHasZonespanlist = false;
bool bNeedZonespanlist = false;
DWORD uPackedFactorFlags = SPH_FACTOR_DISABLE;
///////////////////////////////////////
// build incoming and outgoing schemas
///////////////////////////////////////
// sorter schema
// adds computed expressions and groupby stuff on top of the original index schema
CSphRsetSchema tSorterSchema;
tSorterSchema = tSchema;
CSphVector<uint64_t> dQueryAttrs;
// we need this to perform a sanity check
bool bHasGroupByExpr = false;
// setup overrides, detach them into dynamic part
ARRAY_FOREACH ( i, pQuery->m_dOverrides )
{
const char * sAttr = pQuery->m_dOverrides[i].m_sAttr.cstr();
int iIndex = tSorterSchema.GetAttrIndex ( sAttr );
if ( iIndex<0 )
{
sError.SetSprintf ( "override attribute '%s' not found", sAttr );
return NULL;
}
CSphColumnInfo tCol;
tCol = tSorterSchema.GetAttr ( iIndex );
tCol.m_eStage = SPH_EVAL_OVERRIDE;
tSorterSchema.AddDynamicAttr ( tCol );
if ( pExtra )
pExtra->AddAttr ( tCol, true );
tSorterSchema.RemoveStaticAttr ( iIndex );
dQueryAttrs.Add ( sphFNV64 ( tCol.m_sName.cstr() ) );
}
// setup @geodist
if ( pQuery->m_bGeoAnchor && tSorterSchema.GetAttrIndex ( "@geodist" )<0 )
{
ExprGeodist_t * pExpr = new ExprGeodist_t ();
if ( !pExpr->Setup ( pQuery, tSorterSchema, sError ) )
{
pExpr->Release ();
return NULL;
}
CSphColumnInfo tCol ( "@geodist", SPH_ATTR_FLOAT );
tCol.m_pExpr = pExpr; // takes ownership, no need to for explicit pExpr release
tCol.m_eStage = SPH_EVAL_PREFILTER; // OPTIMIZE? actual stage depends on usage
tSorterSchema.AddDynamicAttr ( tCol );
if ( pExtra )
pExtra->AddAttr ( tCol, true );
dQueryAttrs.Add ( sphFNV64 ( tCol.m_sName.cstr() ) );
}
// setup @expr
if ( pQuery->m_eSort==SPH_SORT_EXPR && tSorterSchema.GetAttrIndex ( "@expr" )<0 )
{
CSphColumnInfo tCol ( "@expr", SPH_ATTR_FLOAT ); // enforce float type for backwards compatibility (ie. too lazy to fix those tests right now)
tCol.m_pExpr = sphExprParse ( pQuery->m_sSortBy.cstr(), tSorterSchema, NULL, NULL, sError, pProfiler, NULL, &bHasZonespanlist );
bNeedZonespanlist |= bHasZonespanlist;
if ( !tCol.m_pExpr )
return NULL;
tCol.m_eStage = SPH_EVAL_PRESORT;
tSorterSchema.AddDynamicAttr ( tCol );
dQueryAttrs.Add ( sphFNV64 ( tCol.m_sName.cstr() ) );
}
// expressions from select items
bool bHasCount = false;
if ( tQueue.m_bComputeItems )
ARRAY_FOREACH ( iItem, pQuery->m_dItems )
{
const CSphQueryItem & tItem = pQuery->m_dItems[iItem];
const CSphString & sExpr = tItem.m_sExpr;
bool bIsCount = IsCount(sExpr);
bHasCount |= bIsCount;
if ( sExpr=="*" )
{
for ( int i=0; i<tSchema.GetAttrsCount(); i++ )
dQueryAttrs.Add ( sphFNV64 ( tSchema.GetAttr(i).m_sName.cstr() ) );
}
// for now, just always pass "plain" attrs from index to sorter; they will be filtered on searchd level
int iAttrIdx = tSchema.GetAttrIndex ( sExpr.cstr() );
bool bPlainAttr = ( ( sExpr=="*" || ( iAttrIdx>=0 && tItem.m_eAggrFunc==SPH_AGGR_NONE ) ) &&
( tItem.m_sAlias.IsEmpty() || tItem.m_sAlias==tItem.m_sExpr ) );
if ( iAttrIdx>=0 )
{
ESphAttr eAttr = tSchema.GetAttr ( iAttrIdx ).m_eAttrType;
if ( eAttr==SPH_ATTR_STRING || eAttr==SPH_ATTR_UINT32SET || eAttr==SPH_ATTR_INT64SET )
{
if ( tItem.m_eAggrFunc!=SPH_AGGR_NONE )
{
sError.SetSprintf ( "can not aggregate non-scalar attribute '%s'", tItem.m_sExpr.cstr() );
return NULL;
}
if ( !bPlainAttr )
{
bPlainAttr = true;
for ( int i=0; i<iItem && bPlainAttr; i++ )
if ( sExpr==pQuery->m_dItems[i].m_sAlias )
bPlainAttr = false;
}
}
}
if ( bPlainAttr || IsGroupby ( sExpr ) || bIsCount )
{
bHasGroupByExpr = IsGroupby ( sExpr );
continue;
}
// not an attribute? must be an expression, and must be aliased by query parser
assert ( !tItem.m_sAlias.IsEmpty() );
// tricky part
// we might be fed with precomputed matches, but it's all or nothing
// the incoming match either does not have anything computed, or it has everything
int iSorterAttr = tSorterSchema.GetAttrIndex ( tItem.m_sAlias.cstr() );
if ( iSorterAttr>=0 )
{
if ( dQueryAttrs.Contains ( sphFNV64 ( tItem.m_sAlias.cstr() ) ) )
{
sError.SetSprintf ( "alias '%s' must be unique (conflicts with another alias)", tItem.m_sAlias.cstr() );
return NULL;
} else
{
tSorterSchema.RemoveStaticAttr ( iSorterAttr );
}
}
// a new and shiny expression, lets parse
CSphColumnInfo tExprCol ( tItem.m_sAlias.cstr(), SPH_ATTR_NONE );
DWORD uQueryPackedFactorFlags = SPH_FACTOR_DISABLE;
// tricky bit
// GROUP_CONCAT() adds an implicit TO_STRING() conversion on top of its argument
// and then the aggregate operation simply concatenates strings as matches arrive
// ideally, we would instead pass ownership of the expression to G_C() implementation
// and also the original expression type, and let the string conversion happen in G_C() itself
// but that ideal route seems somewhat more complicated in the current architecture
if ( tItem.m_eAggrFunc==SPH_AGGR_CAT )
{
CSphString sExpr2;
sExpr2.SetSprintf ( "TO_STRING(%s)", sExpr.cstr() );
tExprCol.m_pExpr = sphExprParse ( sExpr2.cstr(), tSorterSchema, &tExprCol.m_eAttrType,
&tExprCol.m_bWeight, sError, pProfiler, tQueue.m_pHook, &bHasZonespanlist, &uQueryPackedFactorFlags, &tExprCol.m_eStage );
} else
{
tExprCol.m_pExpr = sphExprParse ( sExpr.cstr(), tSorterSchema, &tExprCol.m_eAttrType,
&tExprCol.m_bWeight, sError, pProfiler, tQueue.m_pHook, &bHasZonespanlist, &uQueryPackedFactorFlags, &tExprCol.m_eStage );
}
uPackedFactorFlags |= uQueryPackedFactorFlags;
bNeedZonespanlist |= bHasZonespanlist;
tExprCol.m_eAggrFunc = tItem.m_eAggrFunc;
if ( !tExprCol.m_pExpr )
{
sError.SetSprintf ( "parse error: %s", sError.cstr() );
return NULL;
}
// force AVG() to be computed in floats
if ( tExprCol.m_eAggrFunc==SPH_AGGR_AVG )
{
tExprCol.m_eAttrType = SPH_ATTR_FLOAT;
tExprCol.m_tLocator.m_iBitCount = 32;
}
// force explicit type conversion for JSON attributes
if ( tExprCol.m_eAggrFunc!=SPH_AGGR_NONE && tExprCol.m_eAttrType==SPH_ATTR_JSON_FIELD )
{
sError.SetSprintf ( "ambiguous attribute type '%s', use INTEGER(), BIGINT() or DOUBLE() conversion functions", tItem.m_sExpr.cstr() );
return NULL;
}
if ( uQueryPackedFactorFlags & SPH_FACTOR_JSON_OUT )
tExprCol.m_eAttrType = SPH_ATTR_FACTORS_JSON;
// force GROUP_CONCAT() to be computed as strings
if ( tExprCol.m_eAggrFunc==SPH_AGGR_CAT )
{
tExprCol.m_eAttrType = SPH_ATTR_STRINGPTR;
tExprCol.m_tLocator.m_iBitCount = ROWITEMPTR_BITS;
}
// postpone aggregates, add non-aggregates
if ( tExprCol.m_eAggrFunc==SPH_AGGR_NONE )
{
// is this expression used in filter?
// OPTIMIZE? hash filters and do hash lookups?
if ( tExprCol.m_eAttrType!=SPH_ATTR_JSON_FIELD )
ARRAY_FOREACH ( i, pQuery->m_dFilters )
if ( pQuery->m_dFilters[i].m_sAttrName==tExprCol.m_sName )
{
// is this a hack?
// m_bWeight is computed after EarlyReject() get called
// that means we can't evaluate expressions with WEIGHT() in prefilter phase
if ( tExprCol.m_bWeight )
{
tExprCol.m_eStage = SPH_EVAL_PRESORT; // special, weight filter ( short cut )
break;
}
// so we are about to add a filter condition
// but it might depend on some preceding columns (e.g. SELECT 1+attr f1 ... WHERE f1>5)
// lets detect those and move them to prefilter \ presort phase too
CSphVector<int> dCur;
tExprCol.m_pExpr->Command ( SPH_EXPR_GET_DEPENDENT_COLS, &dCur );
// usual filter
tExprCol.m_eStage = SPH_EVAL_PREFILTER;
ARRAY_FOREACH ( j, dCur )
{
const CSphColumnInfo & tCol = tSorterSchema.GetAttr ( dCur[j] );
if ( tCol.m_bWeight )
{
tExprCol.m_eStage = SPH_EVAL_PRESORT;
tExprCol.m_bWeight = true;
}
// handle chains of dependencies (e.g. SELECT 1+attr f1, f1-1 f2 ... WHERE f2>5)
if ( tCol.m_pExpr.Ptr() )
{
tCol.m_pExpr->Command ( SPH_EXPR_GET_DEPENDENT_COLS, &dCur );
}
}
dCur.Uniq();
ARRAY_FOREACH ( j, dCur )
{
CSphColumnInfo & tDep = const_cast < CSphColumnInfo & > ( tSorterSchema.GetAttr ( dCur[j] ) );
if ( tDep.m_eStage>tExprCol.m_eStage )
tDep.m_eStage = tExprCol.m_eStage;
}
break;
}
// add it!
// NOTE, "final" stage might need to be fixed up later
// we'll do that when parsing sorting clause
tSorterSchema.AddDynamicAttr ( tExprCol );
} else // some aggregate
{
tExprCol.m_eStage = SPH_EVAL_PRESORT; // sorter expects computed expression
tSorterSchema.AddDynamicAttr ( tExprCol );
if ( pExtra )
pExtra->AddAttr ( tExprCol, true );
/// update aggregate dependencies (e.g. SELECT 1+attr f1, min(f1), ...)
CSphVector<int> dCur;
tExprCol.m_pExpr->Command ( SPH_EXPR_GET_DEPENDENT_COLS, &dCur );
ARRAY_FOREACH ( j, dCur )
{
const CSphColumnInfo & tCol = tSorterSchema.GetAttr ( dCur[j] );
if ( tCol.m_pExpr.Ptr() )
tCol.m_pExpr->Command ( SPH_EXPR_GET_DEPENDENT_COLS, &dCur );
}
dCur.Uniq();
ARRAY_FOREACH ( j, dCur )
{
CSphColumnInfo & tDep = const_cast < CSphColumnInfo & > ( tSorterSchema.GetAttr ( dCur[j] ) );
if ( tDep.m_eStage>tExprCol.m_eStage )
tDep.m_eStage = tExprCol.m_eStage;
}
}
dQueryAttrs.Add ( sphFNV64 ( (const BYTE *)tExprCol.m_sName.cstr() ) );
}
////////////////////////////////////////////
// setup groupby settings, create shortcuts
////////////////////////////////////////////
CSphVector<int> dGroupColumns;
CSphGroupSorterSettings tSettings;
bool bImplicit = false;
if ( pQuery->m_sGroupBy.IsEmpty() )
ARRAY_FOREACH_COND ( i, pQuery->m_dItems, !bImplicit )
{
const CSphQueryItem & t = pQuery->m_dItems[i];
bImplicit = ( t.m_eAggrFunc!=SPH_AGGR_NONE ) || t.m_sExpr=="count(*)" || t.m_sExpr=="@distinct";
}
if ( !SetupGroupbySettings ( pQuery, tSorterSchema, tSettings, dGroupColumns, sError, bImplicit ) )
return NULL;
const bool bGotGroupby = !pQuery->m_sGroupBy.IsEmpty() || tSettings.m_bImplicit; // or else, check in SetupGroupbySettings() would already fail
const bool bGotDistinct = ( tSettings.m_tDistinctLoc.m_iBitOffset>=0 );
if ( bHasGroupByExpr && !bGotGroupby )
{
sError = "GROUPBY() is allowed only in GROUP BY queries";
return NULL;
}
// check for HAVING constrains
if ( tQueue.m_pAggrFilter && !tQueue.m_pAggrFilter->m_sAttrName.IsEmpty() && !bGotGroupby )
{
sError.SetSprintf ( "can not use HAVING without group by" );
return NULL;
}
// now lets add @groupby etc if needed
if ( bGotGroupby && tSorterSchema.GetAttrIndex ( "@groupby" )<0 )
{
ESphAttr eGroupByResult = ( !tSettings.m_bImplicit ) ? tSettings.m_pGrouper->GetResultType() : SPH_ATTR_INTEGER; // implicit do not have grouper
if ( tSettings.m_bMva64 )
eGroupByResult = SPH_ATTR_BIGINT;
CSphColumnInfo tGroupby ( "@groupby", eGroupByResult );
CSphColumnInfo tCount ( "@count", SPH_ATTR_INTEGER );
CSphColumnInfo tDistinct ( "@distinct", SPH_ATTR_INTEGER );
tGroupby.m_eStage = SPH_EVAL_SORTER;
tCount.m_eStage = SPH_EVAL_SORTER;
tDistinct.m_eStage = SPH_EVAL_SORTER;
tSorterSchema.AddDynamicAttr ( tGroupby );
tSorterSchema.AddDynamicAttr ( tCount );
if ( pExtra )
{
pExtra->AddAttr ( tGroupby, true );
pExtra->AddAttr ( tCount, true );
}
if ( bGotDistinct )
{
tSorterSchema.AddDynamicAttr ( tDistinct );
if ( pExtra )
pExtra->AddAttr ( tDistinct, true );
}
// add @groupbystr last in case we need to skip it on sending (like @int_str2ptr_*)
if ( tSettings.m_bJson )
{
CSphColumnInfo tGroupbyStr ( "@groupbystr", SPH_ATTR_JSON_FIELD );
tGroupbyStr.m_eStage = SPH_EVAL_SORTER;
tSorterSchema.AddDynamicAttr ( tGroupbyStr );
}
}
#define LOC_CHECK(_cond,_msg) if (!(_cond)) { sError = "invalid schema: " _msg; return NULL; }
int iGroupby = tSorterSchema.GetAttrIndex ( "@groupby" );
if ( iGroupby>=0 )
{
tSettings.m_bDistinct = bGotDistinct;
tSettings.m_tLocGroupby = tSorterSchema.GetAttr ( iGroupby ).m_tLocator;
LOC_CHECK ( tSettings.m_tLocGroupby.m_bDynamic, "@groupby must be dynamic" );
int iCount = tSorterSchema.GetAttrIndex ( "@count" );
LOC_CHECK ( iCount>=0, "missing @count" );
tSettings.m_tLocCount = tSorterSchema.GetAttr ( iCount ).m_tLocator;
LOC_CHECK ( tSettings.m_tLocCount.m_bDynamic, "@count must be dynamic" );
int iDistinct = tSorterSchema.GetAttrIndex ( "@distinct" );
if ( bGotDistinct )
{
LOC_CHECK ( iDistinct>=0, "missing @distinct" );
tSettings.m_tLocDistinct = tSorterSchema.GetAttr ( iDistinct ).m_tLocator;
LOC_CHECK ( tSettings.m_tLocDistinct.m_bDynamic, "@distinct must be dynamic" );
} else
{
LOC_CHECK ( iDistinct<=0, "unexpected @distinct" );
}
int iGroupbyStr = tSorterSchema.GetAttrIndex ( "@groupbystr" );
if ( iGroupbyStr>=0 )
tSettings.m_tLocGroupbyStr = tSorterSchema.GetAttr ( iGroupbyStr ).m_tLocator;
}
if ( bHasCount )
{
LOC_CHECK ( tSorterSchema.GetAttrIndex ( "@count" )>=0, "Count(*) or @count is queried, but not available in the schema" );
}
#undef LOC_CHECK
////////////////////////////////////
// choose and setup sorting functor
////////////////////////////////////
ESphSortFunc eMatchFunc = FUNC_REL_DESC;
ESphSortFunc eGroupFunc = FUNC_REL_DESC;
bool bUsesAttrs = false;
bool bRandomize = false;
// matches sorting function
if ( pQuery->m_eSort==SPH_SORT_EXTENDED )
{
ESortClauseParseResult eRes = sphParseSortClause ( pQuery, pQuery->m_sSortBy.cstr(),
tSorterSchema, eMatchFunc, tStateMatch, sError );
if ( eRes==SORT_CLAUSE_ERROR )
return NULL;
if ( eRes==SORT_CLAUSE_RANDOM )
bRandomize = true;
ExtraAddSortkeys ( pExtra, tSorterSchema, tStateMatch.m_dAttrs );
bUsesAttrs = FixupDependency ( tSorterSchema, tStateMatch.m_dAttrs, CSphMatchComparatorState::MAX_ATTRS );
if ( !bUsesAttrs )
{
for ( int i=0; i<CSphMatchComparatorState::MAX_ATTRS; i++ )
{
ESphSortKeyPart ePart = tStateMatch.m_eKeypart[i];
if ( ePart==SPH_KEYPART_INT || ePart==SPH_KEYPART_FLOAT || ePart==SPH_KEYPART_STRING || ePart==SPH_KEYPART_STRINGPTR )
bUsesAttrs = true;
}
}
SetupSortRemap ( tSorterSchema, tStateMatch );
} else if ( pQuery->m_eSort==SPH_SORT_EXPR )
{
tStateMatch.m_eKeypart[0] = SPH_KEYPART_INT;
tStateMatch.m_tLocator[0] = tSorterSchema.GetAttr ( tSorterSchema.GetAttrIndex ( "@expr" ) ).m_tLocator;
tStateMatch.m_eKeypart[1] = SPH_KEYPART_ID;
tStateMatch.m_uAttrDesc = 1;
eMatchFunc = FUNC_EXPR;
bUsesAttrs = true;
} else
{
// check sort-by attribute
if ( pQuery->m_eSort!=SPH_SORT_RELEVANCE )
{
int iSortAttr = tSorterSchema.GetAttrIndex ( pQuery->m_sSortBy.cstr() );
if ( iSortAttr<0 )
{
sError.SetSprintf ( "sort-by attribute '%s' not found", pQuery->m_sSortBy.cstr() );
return NULL;
}
const CSphColumnInfo & tAttr = tSorterSchema.GetAttr ( iSortAttr );
tStateMatch.m_eKeypart[0] = Attr2Keypart ( tAttr.m_eAttrType );
tStateMatch.m_tLocator[0] = tAttr.m_tLocator;
tStateMatch.m_dAttrs[0] = iSortAttr;
SetupSortRemap ( tSorterSchema, tStateMatch );
}
// find out what function to use and whether it needs attributes
bUsesAttrs = true;
switch ( pQuery->m_eSort )
{
case SPH_SORT_ATTR_DESC: eMatchFunc = FUNC_ATTR_DESC; break;
case SPH_SORT_ATTR_ASC: eMatchFunc = FUNC_ATTR_ASC; break;
case SPH_SORT_TIME_SEGMENTS: eMatchFunc = FUNC_TIMESEGS; break;
case SPH_SORT_RELEVANCE: eMatchFunc = FUNC_REL_DESC; bUsesAttrs = false; break;
default:
sError.SetSprintf ( "unknown sorting mode %d", pQuery->m_eSort );
return NULL;
}
}
// groups sorting function
if ( bGotGroupby )
{
ESortClauseParseResult eRes = sphParseSortClause ( pQuery, pQuery->m_sGroupSortBy.cstr(),
tSorterSchema, eGroupFunc, tStateGroup, sError );
if ( eRes==SORT_CLAUSE_ERROR || eRes==SORT_CLAUSE_RANDOM )
{
if ( eRes==SORT_CLAUSE_RANDOM )
sError.SetSprintf ( "groups can not be sorted by @random" );
return NULL;
}
ExtraAddSortkeys ( pExtra, tSorterSchema, tStateGroup.m_dAttrs );
assert ( dGroupColumns.GetLength() || tSettings.m_bImplicit );
if ( pExtra && !tSettings.m_bImplicit )
{
ARRAY_FOREACH ( i, dGroupColumns )
pExtra->AddAttr ( tSorterSchema.GetAttr ( dGroupColumns[i] ), true );
}
if ( bGotDistinct )
{
dGroupColumns.Add ( tSorterSchema.GetAttrIndex ( pQuery->m_sGroupDistinct.cstr() ) );
assert ( dGroupColumns.Last()>=0 );
if ( pExtra )
pExtra->AddAttr ( tSorterSchema.GetAttr ( dGroupColumns.Last() ), true );
}
if ( dGroupColumns.GetLength() ) // implicit case
{
FixupDependency ( tSorterSchema, dGroupColumns.Begin(), dGroupColumns.GetLength() );
}
FixupDependency ( tSorterSchema, tStateGroup.m_dAttrs, CSphMatchComparatorState::MAX_ATTRS );
// GroupSortBy str attributes setup
SetupSortRemap ( tSorterSchema, tStateGroup );
}
// set up aggregate filter for grouper
if ( bGotGroupby && tQueue.m_pAggrFilter && !tQueue.m_pAggrFilter->m_sAttrName.IsEmpty() )
{
if ( tSorterSchema.GetAttr ( tQueue.m_pAggrFilter->m_sAttrName.cstr() ) )
{
tSettings.m_pAggrFilterTrait = sphCreateAggrFilter ( tQueue.m_pAggrFilter, tQueue.m_pAggrFilter->m_sAttrName, tSorterSchema, sError );
} else
{
// having might reference aliased attributes but @* attributes got stored without alias in sorter schema
CSphString sHaving;
ARRAY_FOREACH ( i, pQuery->m_dItems )
{
const CSphQueryItem & tItem = pQuery->m_dItems[i];
if ( tItem.m_sAlias==tQueue.m_pAggrFilter->m_sAttrName )
{
sHaving = tItem.m_sExpr;
break;
}
}
if ( sHaving=="groupby()" )
sHaving = "@groupby";
else if ( sHaving=="count(*)" )
sHaving = "@count";
tSettings.m_pAggrFilterTrait = sphCreateAggrFilter ( tQueue.m_pAggrFilter, sHaving, tSorterSchema, sError );
}
if ( !tSettings.m_pAggrFilterTrait )
return NULL;
}
///////////////////
// spawn the queue
///////////////////
if ( !bGotGroupby )
{
if ( tQueue.m_pUpdate )
pTop = new CSphUpdateQueue ( pQuery->m_iMaxMatches, tQueue.m_pUpdate, pQuery->m_bIgnoreNonexistent, pQuery->m_bStrict );
else if ( tQueue.m_pDeletes )
pTop = new CSphDeleteQueue ( pQuery->m_iMaxMatches, tQueue.m_pDeletes );
else
pTop = CreatePlainSorter ( eMatchFunc, pQuery->m_bSortKbuffer, pQuery->m_iMaxMatches, bUsesAttrs, uPackedFactorFlags & SPH_FACTOR_ENABLE );
} else
{
pTop = sphCreateSorter1st ( eMatchFunc, eGroupFunc, pQuery, tSettings, uPackedFactorFlags & SPH_FACTOR_ENABLE );
}
if ( !pTop )
{
sError.SetSprintf ( "internal error: unhandled sorting mode (match-sort=%d, group=%d, group-sort=%d)",
eMatchFunc, bGotGroupby, eGroupFunc );
return NULL;
}
switch ( pQuery->m_eCollation )
{
case SPH_COLLATION_LIBC_CI:
tStateMatch.m_fnStrCmp = sphCollateLibcCI;
tStateGroup.m_fnStrCmp = sphCollateLibcCI;
break;
case SPH_COLLATION_LIBC_CS:
tStateMatch.m_fnStrCmp = sphCollateLibcCS;
tStateGroup.m_fnStrCmp = sphCollateLibcCS;
break;
case SPH_COLLATION_UTF8_GENERAL_CI:
tStateMatch.m_fnStrCmp = sphCollateUtf8GeneralCI;
tStateGroup.m_fnStrCmp = sphCollateUtf8GeneralCI;
break;
case SPH_COLLATION_BINARY:
tStateMatch.m_fnStrCmp = sphCollateBinary;
tStateGroup.m_fnStrCmp = sphCollateBinary;
break;
}
assert ( pTop );
pTop->SetState ( tStateMatch );
pTop->SetGroupState ( tStateGroup );
pTop->SetSchema ( tSorterSchema );
pTop->m_bRandomize = bRandomize;
if ( bRandomize )
{
if ( pQuery->m_iRandSeed>=0 )
sphSrand ( (DWORD)pQuery->m_iRandSeed );
else
sphAutoSrand ();
}
tQueue.m_bZonespanlist = bNeedZonespanlist;
tQueue.m_uPackedFactorFlags = uPackedFactorFlags;
return pTop;
}
int sphFlattenQueue ( ISphMatchSorter * pQueue, CSphQueryResult * pResult, int iTag )
{
if ( !pQueue || !pQueue->GetLength() )
return 0;
int iOffset = pResult->m_dMatches.GetLength ();
pResult->m_dMatches.Resize ( iOffset + pQueue->GetLength() );
int iCopied = pQueue->Flatten ( pResult->m_dMatches.Begin() + iOffset, iTag );
pResult->m_dMatches.Resize ( iOffset + iCopied );
return iCopied;
}
bool sphHasExpressions ( const CSphQuery & tQuery, const CSphSchema & tSchema )
{
ARRAY_FOREACH ( i, tQuery.m_dItems )
{
const CSphQueryItem & tItem = tQuery.m_dItems[i];
const CSphString & sExpr = tItem.m_sExpr;
// all expressions that come from parser are automatically aliased
assert ( !tItem.m_sAlias.IsEmpty() );
if ( !( sExpr=="*"
|| ( tSchema.GetAttrIndex ( sExpr.cstr() )>=0 && tItem.m_eAggrFunc==SPH_AGGR_NONE && tItem.m_sAlias==sExpr )
|| IsGroupbyMagic ( sExpr ) ) )
return true;
}
return false;
}
//
// $Id$
//
| remialvado/sphinxsearch | src/sphinxsort.cpp | C++ | gpl-2.0 | 157,080 |
/*
* \brief Signal context for timer events
* \author Josef Soentgen
* \date 2014-10-10
*/
/*
* Copyright (C) 2014 Genode Labs GmbH
*
* This file is part of the Genode OS framework, which is distributed
* under the terms of the GNU General Public License version 2.
*/
/* Genode includes */
#include <base/env.h>
#include <base/heap.h>
#include <base/printf.h>
#include <base/tslab.h>
#include <timer_session/connection.h>
/* local includes */
#include <list.h>
#include <lx.h>
#include <extern_c_begin.h>
# include <lx_emul.h>
#include <extern_c_end.h>
unsigned long jiffies;
static void run_timer(void*);
namespace Lx {
class Timer;
}
/**
* Lx::Timer
*/
class Lx::Timer
{
public:
/**
* Context encapsulates a regular linux timer_list
*/
struct Context : public Lx::List<Context>::Element
{
enum { INVALID_TIMEOUT = ~0UL };
struct timer_list *timer;
bool pending { false };
unsigned long timeout { INVALID_TIMEOUT }; /* absolute in jiffies */
bool programmed { false };
Context(struct timer_list *timer) : timer(timer) { }
};
private:
::Timer::Connection _timer_conn;
Lx::List<Context> _list;
Lx::Task _timer_task;
Genode::Signal_rpc_member<Lx::Timer> _dispatcher;
Genode::Tslab<Context, 32 * sizeof(Context)> _timer_alloc;
/**
* Lookup local timer
*/
Context *_find_context(struct timer_list const *timer)
{
for (Context *c = _list.first(); c; c = c->next())
if (c->timer == timer)
return c;
return 0;
}
/**
* Program the first timer in the list
*
* The first timer is programmed if the 'programmed' flag was not set
* before. The second timer is flagged as not programmed as
* 'Timer::trigger_once' invalidates former registered one-shot
* timeouts.
*/
void _program_first_timer()
{
Context *ctx = _list.first();
if (!ctx)
return;
if (ctx->programmed)
return;
/* calculate relative microseconds for trigger */
unsigned long us = ctx->timeout > jiffies ?
jiffies_to_msecs(ctx->timeout - jiffies) * 1000 : 0;
_timer_conn.trigger_once(us);
ctx->programmed = true;
/* possibly programmed successor must be reprogrammed later */
if (Context *next = ctx->next())
next->programmed = false;
}
/**
* Schedule timer
*
* Add the context to the scheduling list depending on its timeout
* and reprogram the first timer.
*/
void _schedule_timer(Context *ctx, unsigned long expires)
{
_list.remove(ctx);
ctx->timeout = expires;
ctx->pending = true;
ctx->programmed = false;
/*
* Also write the timeout value to the expires field in
* struct timer_list because the wireless stack checks
* it directly.
*/
ctx->timer->expires = expires;
Context *c;
for (c = _list.first(); c; c = c->next())
if (ctx->timeout <= c->timeout)
break;
_list.insert_before(ctx, c);
_program_first_timer();
}
/**
* Handle trigger_once signal
*/
void _handle(unsigned)
{
_timer_task.unblock();
Lx::scheduler().schedule();
}
public:
/**
* Constructor
*/
Timer(Server::Entrypoint &ep)
:
_timer_task(run_timer, nullptr, "timer", Lx::Task::PRIORITY_2,
Lx::scheduler()),
_dispatcher(ep, *this, &Lx::Timer::_handle),
_timer_alloc(Genode::env()->heap())
{
_timer_conn.sigh(_dispatcher);
}
/**
* Add new linux timer
*/
void add(struct timer_list *timer)
{
Context *t = new (&_timer_alloc) Context(timer);
_list.append(t);
}
/**
* Delete linux timer
*/
int del(struct timer_list *timer)
{
Context *ctx = _find_context(timer);
/**
* If the timer expired it was already cleaned up after its
* execution.
*/
if (!ctx)
return 0;
int rv = ctx->timeout != Context::INVALID_TIMEOUT ? 1 : 0;
_list.remove(ctx);
destroy(&_timer_alloc, ctx);
return rv;
}
/**
* Initial scheduling of linux timer
*/
int schedule(struct timer_list *timer, unsigned long expires)
{
Context *ctx = _find_context(timer);
if (!ctx) {
PERR("schedule unknown timer %p", timer);
return -1; /* XXX better use 0 as rv? */
}
/*
* If timer was already active return 1, otherwise 0. The return
* value is needed by mod_timer().
*/
int rv = ctx->timeout != Context::INVALID_TIMEOUT ? 1 : 0;
_schedule_timer(ctx, expires);
return rv;
}
/**
* Schedule next linux timer
*/
void schedule_next() { _program_first_timer(); }
/**
* Check if the timer is currently pending
*/
bool pending(struct timer_list const *timer)
{
Context *ctx = _find_context(timer);
if (!ctx) {
return false;
}
return ctx->pending;
}
Context *find(struct timer_list const *timer) {
return _find_context(timer); }
/**
* Update jiffie counter
*/
void update_jiffies()
{
jiffies = msecs_to_jiffies(_timer_conn.elapsed_ms());
}
/**
* Get first timer context
*/
Context* first() { return _list.first(); }
};
static Lx::Timer *_lx_timer;
void Lx::timer_init(Server::Entrypoint &ep)
{
/* XXX safer way preventing possible nullptr access? */
static Lx::Timer lx_timer(ep);
_lx_timer = &lx_timer;
/* initialize value explicitly */
jiffies = 0UL;
}
void Lx::timer_update_jiffies() {
_lx_timer->update_jiffies(); }
static void run_timer(void *)
{
while (1) {
Lx::scheduler().current()->block_and_schedule();
while (Lx::Timer::Context *ctx = _lx_timer->first()) {
if (ctx->timeout > jiffies)
break;
ctx->timer->function(ctx->timer->data);
_lx_timer->del(ctx->timer);
}
_lx_timer->schedule_next();
}
}
/*******************
** linux/timer.h **
*******************/
void init_timer(struct timer_list *timer) { }
int mod_timer(struct timer_list *timer, unsigned long expires)
{
if (!_lx_timer->find(timer))
_lx_timer->add(timer);
return _lx_timer->schedule(timer, expires);
}
void setup_timer(struct timer_list *timer,void (*function)(unsigned long),
unsigned long data)
{
timer->function = function;
timer->data = data;
init_timer(timer);
}
int timer_pending(const struct timer_list *timer)
{
bool pending = _lx_timer->pending(timer);
return pending;
}
int del_timer(struct timer_list *timer)
{
int rv = _lx_timer->del(timer);
_lx_timer->schedule_next();
return rv;
}
/*******************
** linux/sched.h **
*******************/
static void unblock_task(unsigned long task)
{
Lx::Task *t = (Lx::Task *)task;
t->unblock();
}
signed long schedule_timeout(signed long timeout)
{
struct timer_list timer;
setup_timer(&timer, unblock_task, (unsigned long)Lx::scheduler().current());
mod_timer(&timer, timeout);
Lx::scheduler().current()->block_and_schedule();
del_timer(&timer);
timeout = (timeout - jiffies);
return timeout < 0 ? 0 : timeout;
}
| waylon531/genode | repos/dde_linux/src/lib/wifi/timer.cc | C++ | gpl-2.0 | 7,017 |
/*
Copyright (C) 1999-2008 by Mark D. Hill and David A. Wood for the
Wisconsin Multifacet Project. Contact: gems@cs.wisc.edu
http://www.cs.wisc.edu/gems/
--------------------------------------------------------------------
This file is part of the Opal Timing-First Microarchitectural
Simulator, a component of the Multifacet GEMS (General
Execution-driven Multiprocessor Simulator) software toolset
originally developed at the University of Wisconsin-Madison.
Opal was originally developed by Carl Mauer based upon code by
Craig Zilles.
Substantial further development of Multifacet GEMS at the
University of Wisconsin was performed by Alaa Alameldeen, Brad
Beckmann, Jayaram Bobba, Ross Dickson, Dan Gibson, Pacia Harper,
Derek Hower, Milo Martin, Michael Marty, Carl Mauer, Michelle Moravan,
Kevin Moore, Andrew Phelps, Manoj Plakal, Daniel Sorin, Haris Volos,
Min Xu, and Luke Yen.
--------------------------------------------------------------------
If your use of this software contributes to a published paper, we
request that you (1) cite our summary paper that appears on our
website (http://www.cs.wisc.edu/gems/) and (2) e-mail a citation
for your published paper to gems@cs.wisc.edu.
If you redistribute derivatives of this software, we request that
you notify us and either (1) ask people to register with us at our
website (http://www.cs.wisc.edu/gems/) or (2) collect registration
information and periodically send it to us.
--------------------------------------------------------------------
Multifacet GEMS is free software; you can redistribute it and/or
modify it under the terms of version 2 of the GNU General Public
License as published by the Free Software Foundation.
Multifacet GEMS 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 the Multifacet GEMS; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307, USA
The GNU General Public License is contained in the file LICENSE.
### END HEADER ###
*/
#ifndef CS752_CACHE_H
#define CS752_CACHE_H
#include <iostream.h>
#include <sys/types.h>
#include "Types.h"
#include "CacheEntry.h"
// #define CACHE_SIZE 0x800000
// #define CACHE_LINE_SIZE 0x40
// #define CACHE_ASSOCIATIVITY 1
// #define CACHE_NUM_LINES CACHE_SIZE/(CACHE_LINE_SIZE*CACHE_ASSOCIATIVITY)
class Cache
{
public:
Cache(uint64_t cacheSize, int cacheAss, int lineSize);
// address accessors
Address getTag(Address a);
Address getIndex(Address a);
Address getOffset(Address a);
int getNumLines( void );
bool isHit(Address a, CacheEntry * &matchedEntry);
void updateLRUStatus(Address mostRecentAddress);
void load(Address newPhysicalAddress,
Address newLoadingPC,
CacheEntry &victimEntry);
void load(Address newPhysicalAddress,
Address newLoadingPC,
CacheEntry &victimEntry,
int ReadOrWrite,
bool isData);
void dump(void);
protected:
void updateLRUStatus(Address index, int entryOffset);
int findLRUIndex( Address index );
int getLog2(uint64_t num);
uint64_t getMask(uint64_t numBits);
CacheEntry **lines;
uint64_t m_tagBits;
uint64_t m_indexBits;
uint64_t m_offsetBits;
uint64_t m_tagMask;
uint64_t m_indexMask;
uint64_t m_offsetMask;
int m_cacheAss;
int m_lineSize;
int m_cacheSize;
int m_numLines;
};
#endif
| xpuente/tpzsimul.gems | opal/bypassing/Cache.h | C | gpl-2.0 | 3,841 |
/* OS/2 compatibility functions.
Copyright (C) 2001-2002 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published
by the Free Software Foundation; either version 2, 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA. */
#define OS2_AWARE
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdlib.h>
#include <string.h>
/* A version of getenv() that works from DLLs */
extern unsigned long DosScanEnv (const unsigned char *pszName, unsigned char **ppszValue);
char *
_nl_getenv (const char *name)
{
unsigned char *value;
if (DosScanEnv (name, &value))
return NULL;
else
return value;
}
char _nl_default_dirname[] = /* a 260+1 bytes large buffer */
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0"
#define LOCALEDIR_MAX 260
char *_os2_libdir = NULL;
char *_os2_localealiaspath = NULL;
char *_os2_localedir = NULL;
static __attribute__((constructor)) void
os2_initialize ()
{
char *root = getenv ("UNIXROOT");
char *gnulocaledir = getenv ("GNULOCALEDIR");
_os2_libdir = gnulocaledir;
if (!_os2_libdir)
{
if (root)
{
size_t sl = strlen (root);
_os2_libdir = (char *) malloc (sl + strlen (LIBDIR) + 1);
memcpy (_os2_libdir, root, sl);
memcpy (_os2_libdir + sl, LIBDIR, strlen (LIBDIR) + 1);
}
else
_os2_libdir = LIBDIR;
}
_os2_localealiaspath = gnulocaledir;
if (!_os2_localealiaspath)
{
if (root)
{
size_t sl = strlen (root);
_os2_localealiaspath = (char *) malloc (sl + strlen (LOCALE_ALIAS_PATH) + 1);
memcpy (_os2_localealiaspath, root, sl);
memcpy (_os2_localealiaspath + sl, LOCALE_ALIAS_PATH, strlen (LOCALE_ALIAS_PATH) + 1);
}
else
_os2_localealiaspath = LOCALE_ALIAS_PATH;
}
_os2_localedir = gnulocaledir;
if (!_os2_localedir)
{
if (root)
{
size_t sl = strlen (root);
_os2_localedir = (char *) malloc (sl + strlen (LOCALEDIR) + 1);
memcpy (_os2_localedir, root, sl);
memcpy (_os2_localedir + sl, LOCALEDIR, strlen (LOCALEDIR) + 1);
}
else
_os2_localedir = LOCALEDIR;
}
{
extern const char _nl_default_dirname__[];
if (strlen (_os2_localedir) <= LOCALEDIR_MAX)
strcpy (_nl_default_dirname__, _os2_localedir);
}
}
| ipwndev/DSLinux-Mirror | user/sed/src/intl/os2compat.c | C | gpl-2.0 | 3,451 |
#define yy_create_buffer ada__create_buffer
#define yy_delete_buffer ada__delete_buffer
#define yy_scan_buffer ada__scan_buffer
#define yy_scan_string ada__scan_string
#define yy_scan_bytes ada__scan_bytes
#define yy_flex_debug ada__flex_debug
#define yy_init_buffer ada__init_buffer
#define yy_flush_buffer ada__flush_buffer
#define yy_load_buffer_state ada__load_buffer_state
#define yy_switch_to_buffer ada__switch_to_buffer
#define yyin ada_in
#define yyleng ada_leng
#define yylex ada_lex
#define yyout ada_out
#define yyrestart ada_restart
#define yytext ada_text
#define yywrap ada_wrap
#line 20 "adalexer.c"
/* A lexical scanner generated by flex */
/* Scanner skeleton version:
* $Header$
*/
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 5
#include <stdio.h>
#include <errno.h>
/* cfront 1.2 defines "c_plusplus" instead of "__cplusplus" */
#ifdef c_plusplus
#ifndef __cplusplus
#define __cplusplus
#endif
#endif
#ifdef __cplusplus
#include <stdlib.h>
#ifndef _WIN32
#include <unistd.h>
#else
#ifndef YY_ALWAYS_INTERACTIVE
#ifndef YY_NEVER_INTERACTIVE
extern int isatty YY_PROTO(( int ));
#endif
#endif
#endif
/* Use prototypes in function declarations. */
#define YY_USE_PROTOS
/* The "const" storage-class-modifier is valid. */
#define YY_USE_CONST
#else /* ! __cplusplus */
#if __STDC__
#define YY_USE_PROTOS
#define YY_USE_CONST
#endif /* __STDC__ */
#endif /* ! __cplusplus */
#ifdef __TURBOC__
#pragma warn -rch
#pragma warn -use
#include <io.h>
#include <stdlib.h>
#define YY_USE_CONST
#define YY_USE_PROTOS
#endif
#ifdef YY_USE_CONST
#define yyconst const
#else
#define yyconst
#endif
#ifdef YY_USE_PROTOS
#define YY_PROTO(proto) proto
#else
#define YY_PROTO(proto) ()
#endif
/* Returned upon end-of-file. */
#define YY_NULL 0
/* Promotes a possibly negative, possibly signed char to an unsigned
* integer for use as an array index. If the signed char is negative,
* we want to instead treat it as an 8-bit unsigned char, hence the
* double cast.
*/
#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
/* Enter a start condition. This macro really ought to take a parameter,
* but we do it the disgusting crufty way forced on us by the ()-less
* definition of BEGIN.
*/
#define BEGIN yy_start = 1 + 2 *
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START ((yy_start - 1) / 2)
#define YYSTATE YY_START
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
/* Special action meaning "start processing a new file". */
#define YY_NEW_FILE yyrestart( yyin )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
#define YY_BUF_SIZE 16384
typedef struct yy_buffer_state *YY_BUFFER_STATE;
extern int yyleng;
extern FILE *yyin, *yyout;
#define EOB_ACT_CONTINUE_SCAN 0
#define EOB_ACT_END_OF_FILE 1
#define EOB_ACT_LAST_MATCH 2
/* The funky do-while in the following #define is used to turn the definition
* int a single C statement (which needs a semi-colon terminator). This
* avoids problems with code like:
*
* if ( condition_holds )
* yyless( 5 );
* else
* do_something_else();
*
* Prior to using the do-while the compiler would get upset at the
* "else" because it interpreted the "if" statement as being all
* done when it reached the ';' after the yyless() call.
*/
/* Return all but the first 'n' matched characters back to the input stream. */
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
*yy_cp = yy_hold_char; \
YY_RESTORE_YY_MORE_OFFSET \
yy_c_buf_p = yy_cp = yy_bp + n - YY_MORE_ADJ; \
YY_DO_BEFORE_ACTION; /* set up yytext again */ \
} \
while ( 0 )
#define unput(c) yyunput( c, yytext_ptr )
/* The following is because we cannot portably get our hands on size_t
* (without autoconf's help, which isn't available because we want
* flex-generated scanners to compile on their own).
*/
typedef unsigned int yy_size_t;
struct yy_buffer_state
{
FILE *yy_input_file;
char *yy_ch_buf; /* input buffer */
char *yy_buf_pos; /* current position in input buffer */
/* Size of input buffer in bytes, not including room for EOB
* characters.
*/
yy_size_t yy_buf_size;
/* Number of characters read into yy_ch_buf, not including EOB
* characters.
*/
int yy_n_chars;
/* Whether we "own" the buffer - i.e., we know we created it,
* and can realloc() it to grow it, and should free() it to
* delete it.
*/
int yy_is_our_buffer;
/* Whether this is an "interactive" input source; if so, and
* if we're using stdio for input, then we want to use getc()
* instead of fread(), to make sure we stop fetching input after
* each newline.
*/
int yy_is_interactive;
/* Whether we're considered to be at the beginning of a line.
* If so, '^' rules will be active on the next match, otherwise
* not.
*/
int yy_at_bol;
/* Whether to try to fill the input buffer when we reach the
* end of it.
*/
int yy_fill_buffer;
int yy_buffer_status;
#define YY_BUFFER_NEW 0
#define YY_BUFFER_NORMAL 1
/* When an EOF's been seen but there's still some text to process
* then we mark the buffer as YY_EOF_PENDING, to indicate that we
* shouldn't try reading from the input source any more. We might
* still have a bunch of tokens to match, though, because of
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
* (via yyrestart()), so that the user can continue scanning by
* just pointing yyin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
};
static YY_BUFFER_STATE yy_current_buffer = 0;
/* We provide macros for accessing buffer states in case in the
* future we want to put the buffer states in a more general
* "scanner state".
*/
#define YY_CURRENT_BUFFER yy_current_buffer
/* yy_hold_char holds the character lost when yytext is formed. */
static char yy_hold_char;
static int yy_n_chars; /* number of characters read into yy_ch_buf */
int yyleng;
/* Points to current character in buffer. */
static char *yy_c_buf_p = (char *) 0;
static int yy_init = 1; /* whether we need to initialize */
static int yy_start = 0; /* start state number */
/* Flag which is used to allow yywrap()'s to do buffer switches
* instead of setting up a fresh yyin. A bit of a hack ...
*/
static int yy_did_buffer_switch_on_eof;
void yyrestart YY_PROTO(( FILE *input_file ));
void yy_switch_to_buffer YY_PROTO(( YY_BUFFER_STATE new_buffer ));
void yy_load_buffer_state YY_PROTO(( void ));
YY_BUFFER_STATE yy_create_buffer YY_PROTO(( FILE *file, int size ));
void yy_delete_buffer YY_PROTO(( YY_BUFFER_STATE b ));
void yy_init_buffer YY_PROTO(( YY_BUFFER_STATE b, FILE *file ));
void yy_flush_buffer YY_PROTO(( YY_BUFFER_STATE b ));
#define YY_FLUSH_BUFFER yy_flush_buffer( yy_current_buffer )
YY_BUFFER_STATE yy_scan_buffer YY_PROTO(( char *base, yy_size_t size ));
YY_BUFFER_STATE yy_scan_string YY_PROTO(( yyconst char *yy_str ));
YY_BUFFER_STATE yy_scan_bytes YY_PROTO(( yyconst char *bytes, int len ));
static void *yy_flex_alloc YY_PROTO(( yy_size_t ));
static void *yy_flex_realloc YY_PROTO(( void *, yy_size_t ));
static void yy_flex_free YY_PROTO(( void * ));
#define yy_new_buffer yy_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! yy_current_buffer ) \
yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \
yy_current_buffer->yy_is_interactive = is_interactive; \
}
#define yy_set_bol(at_bol) \
{ \
if ( ! yy_current_buffer ) \
yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \
yy_current_buffer->yy_at_bol = at_bol; \
}
#define YY_AT_BOL() (yy_current_buffer->yy_at_bol)
typedef unsigned char YY_CHAR;
FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0;
typedef int yy_state_type;
extern char *yytext;
#define yytext_ptr yytext
static yy_state_type yy_get_previous_state YY_PROTO(( void ));
static yy_state_type yy_try_NUL_trans YY_PROTO(( yy_state_type current_state ));
static int yy_get_next_buffer YY_PROTO(( void ));
static void yy_fatal_error YY_PROTO(( yyconst char msg[] ));
/* Done after the current pattern has been matched and before the
* corresponding action - sets up yytext.
*/
#define YY_DO_BEFORE_ACTION \
yytext_ptr = yy_bp; \
yyleng = (int) (yy_cp - yy_bp); \
yy_hold_char = *yy_cp; \
*yy_cp = '\0'; \
yy_c_buf_p = yy_cp;
#define YY_NUM_RULES 95
#define YY_END_OF_BUFFER 96
static yyconst short int yy_accept[400] =
{ 0,
0, 0, 96, 94, 92, 89, 91, 94, 94, 94,
87, 93, 93, 93, 93, 93, 93, 93, 93, 93,
93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
93, 90, 0, 86, 0, 85, 87, 93, 93, 93,
93, 93, 93, 26, 93, 93, 93, 93, 93, 93,
93, 34, 93, 93, 93, 93, 93, 93, 93, 93,
93, 45, 46, 47, 93, 93, 93, 93, 93, 93,
93, 54, 55, 93, 93, 93, 93, 93, 93, 93,
93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
93, 93, 93, 0, 86, 88, 85, 93, 19, 93,
93, 24, 25, 93, 93, 93, 93, 93, 93, 93,
93, 93, 93, 93, 37, 93, 93, 93, 93, 93,
41, 93, 93, 93, 93, 93, 93, 93, 50, 93,
51, 52, 93, 93, 57, 93, 93, 93, 93, 93,
93, 93, 93, 66, 93, 93, 93, 93, 93, 93,
93, 93, 93, 93, 93, 93, 93, 93, 93, 80,
93, 93, 93, 84, 93, 93, 93, 93, 93, 93,
28, 93, 29, 93, 93, 93, 93, 93, 93, 35,
93, 93, 93, 40, 93, 93, 93, 93, 44, 93,
93, 93, 49, 93, 53, 93, 93, 93, 93, 93,
93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
93, 93, 93, 93, 93, 75, 93, 77, 78, 93,
81, 93, 83, 18, 93, 93, 93, 93, 1, 27,
93, 93, 93, 93, 31, 32, 93, 36, 38, 93,
5, 6, 93, 93, 93, 93, 93, 93, 93, 93,
93, 93, 93, 93, 93, 63, 64, 93, 93, 93,
93, 93, 93, 93, 93, 93, 93, 93, 93, 79,
82, 93, 21, 22, 93, 93, 93, 93, 93, 33,
93, 93, 93, 93, 93, 93, 93, 93, 93, 56,
93, 93, 59, 93, 93, 93, 93, 93, 93, 69,
93, 71, 93, 93, 17, 93, 74, 93, 93, 23,
2, 93, 93, 30, 93, 93, 43, 7, 48, 93,
93, 93, 12, 58, 93, 60, 93, 93, 65, 67,
68, 70, 93, 93, 93, 93, 73, 93, 20, 93,
4, 93, 42, 93, 93, 93, 13, 93, 93, 72,
93, 93, 93, 93, 3, 39, 93, 93, 93, 61,
62, 93, 93, 93, 76, 8, 93, 93, 93, 93,
93, 93, 93, 93, 14, 93, 93, 10, 93, 93,
93, 93, 93, 93, 15, 93, 93, 93, 93, 9,
93, 93, 93, 93, 11, 93, 93, 16, 0
} ;
static yyconst int yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 2, 3,
4, 4, 5, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 2, 1, 6, 1, 1, 1, 1, 7, 1,
1, 1, 1, 8, 9, 1, 1, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 1, 1, 1,
1, 1, 1, 1, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
28, 29, 30, 31, 32, 33, 34, 35, 36, 21,
1, 1, 1, 1, 11, 1, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 21, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1
} ;
static yyconst int yy_meta[37] =
{ 0,
1, 1, 2, 3, 3, 1, 1, 1, 1, 1,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4
} ;
static yyconst short int yy_base[405] =
{ 0,
0, 0, 415, 416, 416, 416, 411, 407, 0, 403,
401, 0, 24, 24, 32, 26, 31, 37, 45, 42,
19, 384, 52, 45, 53, 69, 64, 74, 18, 68,
383, 416, 402, 401, 399, 0, 395, 0, 68, 390,
50, 388, 373, 0, 383, 74, 370, 387, 373, 78,
379, 0, 366, 60, 83, 360, 368, 364, 367, 366,
359, 0, 358, 0, 364, 79, 372, 355, 351, 353,
360, 0, 0, 363, 350, 366, 349, 87, 86, 100,
85, 352, 348, 363, 91, 346, 358, 346, 341, 355,
99, 339, 340, 362, 361, 416, 0, 337, 334, 348,
351, 0, 0, 350, 341, 324, 336, 342, 328, 326,
332, 104, 334, 102, 0, 324, 336, 320, 334, 337,
0, 334, 331, 320, 329, 324, 325, 315, 0, 309,
0, 0, 317, 323, 0, 316, 317, 318, 302, 103,
304, 315, 306, 0, 319, 298, 297, 312, 311, 314,
296, 304, 292, 304, 299, 296, 294, 302, 297, 0,
291, 292, 295, 0, 282, 283, 93, 281, 274, 284,
0, 292, 0, 295, 275, 293, 268, 291, 271, 0,
284, 264, 272, 0, 283, 266, 265, 266, 0, 276,
262, 281, 0, 262, 0, 261, 277, 257, 263, 274,
269, 268, 267, 266, 252, 256, 263, 249, 248, 262,
246, 243, 248, 236, 255, 0, 250, 0, 0, 246,
0, 252, 0, 0, 255, 235, 235, 248, 0, 0,
251, 248, 249, 231, 0, 0, 229, 0, 0, 227,
0, 0, 237, 236, 239, 238, 109, 241, 222, 233,
230, 237, 217, 232, 232, 0, 0, 230, 228, 211,
217, 211, 209, 227, 227, 219, 209, 220, 209, 0,
0, 219, 0, 0, 217, 206, 199, 204, 212, 0,
207, 200, 211, 195, 208, 199, 196, 194, 196, 0,
202, 184, 0, 200, 183, 183, 205, 182, 195, 0,
194, 0, 178, 110, 0, 192, 0, 195, 175, 0,
0, 189, 173, 0, 177, 177, 0, 0, 0, 175,
169, 174, 0, 0, 182, 0, 168, 180, 416, 0,
0, 0, 179, 171, 168, 173, 0, 160, 0, 161,
0, 164, 0, 176, 171, 168, 0, 169, 169, 0,
157, 151, 155, 164, 0, 0, 148, 160, 166, 0,
0, 164, 159, 145, 0, 0, 157, 119, 141, 153,
139, 140, 145, 142, 0, 150, 154, 0, 138, 132,
133, 141, 148, 143, 0, 133, 126, 137, 123, 0,
134, 130, 113, 120, 0, 121, 73, 0, 416, 140,
144, 37, 148, 152
} ;
static yyconst short int yy_def[405] =
{ 0,
399, 1, 399, 399, 399, 399, 399, 400, 401, 399,
399, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 399, 400, 403, 399, 404, 399, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 400, 403, 399, 404, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 399, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 402, 402,
402, 402, 402, 402, 402, 402, 402, 402, 0, 399,
399, 399, 399, 399
} ;
static yyconst short int yy_nxt[453] =
{ 0,
4, 5, 6, 5, 7, 8, 9, 4, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 12, 20,
12, 12, 21, 22, 23, 24, 25, 12, 26, 27,
28, 29, 12, 30, 31, 12, 39, 40, 65, 45,
38, 50, 89, 47, 66, 51, 41, 90, 42, 46,
48, 52, 43, 53, 44, 54, 56, 49, 62, 57,
60, 72, 58, 68, 76, 55, 63, 69, 59, 101,
61, 64, 102, 73, 115, 74, 75, 70, 77, 81,
79, 78, 82, 71, 80, 85, 91, 92, 106, 86,
116, 111, 87, 98, 83, 84, 117, 99, 138, 107,
112, 398, 118, 127, 128, 141, 139, 149, 154, 88,
142, 150, 140, 143, 161, 177, 201, 180, 162, 226,
155, 181, 227, 144, 145, 286, 334, 146, 287, 335,
147, 288, 148, 202, 178, 373, 397, 396, 374, 336,
33, 395, 33, 33, 35, 394, 35, 35, 94, 393,
94, 94, 97, 392, 391, 97, 390, 389, 388, 387,
386, 385, 384, 383, 382, 381, 380, 379, 378, 377,
376, 375, 372, 371, 370, 369, 368, 367, 366, 365,
364, 363, 362, 361, 360, 359, 358, 357, 356, 355,
354, 353, 352, 351, 350, 349, 348, 347, 346, 345,
344, 343, 342, 341, 340, 339, 338, 337, 333, 332,
331, 330, 329, 328, 327, 326, 325, 324, 323, 322,
321, 320, 319, 318, 317, 316, 315, 314, 313, 312,
311, 310, 309, 308, 307, 306, 305, 304, 303, 302,
301, 300, 299, 298, 297, 296, 295, 294, 293, 292,
291, 290, 289, 285, 284, 283, 282, 281, 280, 279,
278, 277, 276, 275, 274, 273, 272, 271, 270, 269,
268, 267, 266, 265, 264, 263, 262, 261, 260, 259,
258, 257, 256, 255, 254, 253, 252, 251, 250, 249,
248, 247, 246, 245, 244, 243, 242, 241, 240, 239,
238, 237, 236, 235, 234, 233, 232, 231, 230, 229,
228, 225, 224, 223, 222, 221, 220, 219, 218, 217,
216, 215, 214, 213, 212, 211, 210, 209, 208, 207,
206, 205, 204, 203, 200, 199, 198, 197, 196, 195,
194, 193, 192, 191, 190, 189, 188, 187, 186, 185,
184, 183, 182, 179, 176, 175, 174, 173, 172, 171,
170, 169, 168, 167, 166, 165, 95, 34, 164, 163,
160, 159, 158, 157, 156, 153, 152, 151, 137, 136,
135, 134, 133, 132, 131, 130, 129, 126, 125, 124,
123, 122, 121, 120, 119, 114, 113, 110, 109, 108,
105, 104, 103, 100, 37, 96, 95, 34, 93, 67,
37, 36, 34, 32, 399, 3, 399, 399, 399, 399,
399, 399, 399, 399, 399, 399, 399, 399, 399, 399,
399, 399, 399, 399, 399, 399, 399, 399, 399, 399,
399, 399, 399, 399, 399, 399, 399, 399, 399, 399,
399, 399
} ;
static yyconst short int yy_chk[453] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 13, 13, 21, 14,
402, 16, 29, 15, 21, 16, 13, 29, 13, 14,
15, 16, 13, 17, 13, 17, 18, 15, 20, 18,
19, 24, 18, 23, 25, 17, 20, 23, 18, 41,
19, 20, 41, 24, 54, 24, 24, 23, 25, 27,
26, 25, 27, 23, 26, 28, 30, 30, 46, 28,
54, 50, 28, 39, 27, 27, 55, 39, 78, 46,
50, 397, 55, 66, 66, 79, 78, 81, 85, 28,
79, 81, 78, 80, 91, 112, 140, 114, 91, 167,
85, 114, 167, 80, 80, 247, 304, 80, 247, 304,
80, 247, 80, 140, 112, 368, 396, 394, 368, 304,
400, 393, 400, 400, 401, 392, 401, 401, 403, 391,
403, 403, 404, 389, 388, 404, 387, 386, 384, 383,
382, 381, 380, 379, 377, 376, 374, 373, 372, 371,
370, 369, 367, 364, 363, 362, 359, 358, 357, 354,
353, 352, 351, 349, 348, 346, 345, 344, 342, 340,
338, 336, 335, 334, 333, 328, 327, 325, 322, 321,
320, 316, 315, 313, 312, 309, 308, 306, 303, 301,
299, 298, 297, 296, 295, 294, 292, 291, 289, 288,
287, 286, 285, 284, 283, 282, 281, 279, 278, 277,
276, 275, 272, 269, 268, 267, 266, 265, 264, 263,
262, 261, 260, 259, 258, 255, 254, 253, 252, 251,
250, 249, 248, 246, 245, 244, 243, 240, 237, 234,
233, 232, 231, 228, 227, 226, 225, 222, 220, 217,
215, 214, 213, 212, 211, 210, 209, 208, 207, 206,
205, 204, 203, 202, 201, 200, 199, 198, 197, 196,
194, 192, 191, 190, 188, 187, 186, 185, 183, 182,
181, 179, 178, 177, 176, 175, 174, 172, 170, 169,
168, 166, 165, 163, 162, 161, 159, 158, 157, 156,
155, 154, 153, 152, 151, 150, 149, 148, 147, 146,
145, 143, 142, 141, 139, 138, 137, 136, 134, 133,
130, 128, 127, 126, 125, 124, 123, 122, 120, 119,
118, 117, 116, 113, 111, 110, 109, 108, 107, 106,
105, 104, 101, 100, 99, 98, 95, 94, 93, 92,
90, 89, 88, 87, 86, 84, 83, 82, 77, 76,
75, 74, 71, 70, 69, 68, 67, 65, 63, 61,
60, 59, 58, 57, 56, 53, 51, 49, 48, 47,
45, 43, 42, 40, 37, 35, 34, 33, 31, 22,
11, 10, 8, 7, 3, 399, 399, 399, 399, 399,
399, 399, 399, 399, 399, 399, 399, 399, 399, 399,
399, 399, 399, 399, 399, 399, 399, 399, 399, 399,
399, 399, 399, 399, 399, 399, 399, 399, 399, 399,
399, 399
} ;
static yy_state_type yy_last_accepting_state;
static char *yy_last_accepting_cpos;
/* The intent behind this definition is that it'll catch
* any uses of REJECT which flex missed.
*/
#define REJECT reject_used_but_not_detected
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
char *yytext;
#line 1 "adalexer.l"
#define INITIAL 0
#line 9 "adalexer.l"
/* System Includes */
#include <stdio.h>
#include "tokenizer.h"
#line 628 "adalexer.c"
/* Macros after this point can all be overridden by user definitions in
* section 1.
*/
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int yywrap YY_PROTO(( void ));
#else
extern int yywrap YY_PROTO(( void ));
#endif
#endif
#ifndef YY_NO_UNPUT
static void yyunput YY_PROTO(( int c, char *buf_ptr ));
#endif
#ifndef yytext_ptr
static void yy_flex_strncpy YY_PROTO(( char *, yyconst char *, int ));
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen YY_PROTO(( yyconst char * ));
#endif
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput YY_PROTO(( void ));
#else
static int input YY_PROTO(( void ));
#endif
#endif
#if YY_STACK_USED
static int yy_start_stack_ptr = 0;
static int yy_start_stack_depth = 0;
static int *yy_start_stack = 0;
#ifndef YY_NO_PUSH_STATE
static void yy_push_state YY_PROTO(( int new_state ));
#endif
#ifndef YY_NO_POP_STATE
static void yy_pop_state YY_PROTO(( void ));
#endif
#ifndef YY_NO_TOP_STATE
static int yy_top_state YY_PROTO(( void ));
#endif
#else
#define YY_NO_PUSH_STATE 1
#define YY_NO_POP_STATE 1
#define YY_NO_TOP_STATE 1
#endif
#ifdef YY_MALLOC_DECL
YY_MALLOC_DECL
#else
#if __STDC__
#ifndef __cplusplus
#include <stdlib.h>
#endif
#else
/* Just try to get by without declaring the routines. This will fail
* miserably on non-ANSI systems for which sizeof(size_t) != sizeof(int)
* or sizeof(void*) != sizeof(int).
*/
#endif
#endif
/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#define YY_READ_BUF_SIZE 8192
#endif
/* Copy whatever the last rule matched to the standard output. */
#ifndef ECHO
/* This used to be an fputs(), but since the string might contain NUL's,
* we now use fwrite().
*/
#define ECHO (void) fwrite( yytext, yyleng, 1, yyout )
#endif
/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
* is returned in "result".
*/
#ifndef YY_INPUT
#define YY_INPUT(buf,result,max_size) \
if ( yy_current_buffer->yy_is_interactive ) \
{ \
int c = '*', n; \
for ( n = 0; n < max_size && \
(c = getc( yyin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
if ( c == '\n' ) \
buf[n++] = (char) c; \
if ( c == EOF && ferror( yyin ) ) \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
result = n; \
} \
else \
{ \
errno=0; \
while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
{ \
if( errno != EINTR) \
{ \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
break; \
} \
errno=0; \
clearerr(yyin); \
} \
}
#endif
/* No semi-colon after return; correct usage is to write "yyterminate();" -
* we don't want an extra ';' after the "return" because that will cause
* some compilers to complain about unreachable statements.
*/
#ifndef yyterminate
#define yyterminate() return YY_NULL
#endif
/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif
/* Report a fatal error. */
#ifndef YY_FATAL_ERROR
#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
#endif
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL int yylex YY_PROTO(( void ))
#endif
/* Code executed at the beginning of each rule, after yytext and yyleng
* have been set up.
*/
#ifndef YY_USER_ACTION
#define YY_USER_ACTION
#endif
/* Code executed at the end of each rule. */
#ifndef YY_BREAK
#define YY_BREAK break;
#endif
#define YY_RULE_SETUP \
YY_USER_ACTION
YY_DECL
{
register yy_state_type yy_current_state;
register char *yy_cp, *yy_bp;
register int yy_act;
#line 16 "adalexer.l"
#line 792 "adalexer.c"
if ( yy_init )
{
yy_init = 0;
#ifdef YY_USER_INIT
YY_USER_INIT;
#endif
if ( ! yy_start )
yy_start = 1; /* first start state */
if ( ! yyin )
yyin = stdin;
if ( ! yyout )
yyout = stdout;
if ( ! yy_current_buffer )
yy_current_buffer =
yy_create_buffer( yyin, YY_BUF_SIZE );
yy_load_buffer_state();
}
while ( 1 ) /* loops until end-of-file is reached */
{
yy_cp = yy_c_buf_p;
/* Support of yytext. */
*yy_cp = yy_hold_char;
/* yy_bp points to the position in yy_ch_buf of the start of
* the current run.
*/
yy_bp = yy_cp;
yy_current_state = yy_start;
yy_match:
do
{
register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
if ( yy_accept[yy_current_state] )
{
yy_last_accepting_state = yy_current_state;
yy_last_accepting_cpos = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 400 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
++yy_cp;
}
while ( yy_base[yy_current_state] != 416 );
yy_find_action:
yy_act = yy_accept[yy_current_state];
if ( yy_act == 0 )
{ /* have to back up */
yy_cp = yy_last_accepting_cpos;
yy_current_state = yy_last_accepting_state;
yy_act = yy_accept[yy_current_state];
}
YY_DO_BEFORE_ACTION;
do_action: /* This label is used only to access EOF actions. */
switch ( yy_act )
{ /* beginning of action switch */
case 0: /* must back up */
/* undo the effects of YY_DO_BEFORE_ACTION */
*yy_cp = yy_hold_char;
yy_cp = yy_last_accepting_cpos;
yy_current_state = yy_last_accepting_state;
goto yy_find_action;
case 1:
YY_RULE_SETUP
#line 17 "adalexer.l"
{ return(TOKENIZER_TYPE); }
YY_BREAK
case 2:
YY_RULE_SETUP
#line 18 "adalexer.l"
{ return(TOKENIZER_TYPE); }
YY_BREAK
case 3:
YY_RULE_SETUP
#line 19 "adalexer.l"
{ return(TOKENIZER_TYPE); }
YY_BREAK
case 4:
YY_RULE_SETUP
#line 20 "adalexer.l"
{ return(TOKENIZER_TYPE); }
YY_BREAK
case 5:
YY_RULE_SETUP
#line 21 "adalexer.l"
{ return(TOKENIZER_TYPE); }
YY_BREAK
case 6:
YY_RULE_SETUP
#line 22 "adalexer.l"
{ return(TOKENIZER_TYPE); }
YY_BREAK
case 7:
YY_RULE_SETUP
#line 23 "adalexer.l"
{ return(TOKENIZER_TYPE); }
YY_BREAK
case 8:
YY_RULE_SETUP
#line 24 "adalexer.l"
{ return(TOKENIZER_TYPE); }
YY_BREAK
case 9:
YY_RULE_SETUP
#line 25 "adalexer.l"
{ return(TOKENIZER_TYPE); }
YY_BREAK
case 10:
YY_RULE_SETUP
#line 26 "adalexer.l"
{ return(TOKENIZER_TYPE); }
YY_BREAK
case 11:
YY_RULE_SETUP
#line 27 "adalexer.l"
{ return(TOKENIZER_TYPE); }
YY_BREAK
case 12:
YY_RULE_SETUP
#line 28 "adalexer.l"
{ return(TOKENIZER_TYPE); }
YY_BREAK
case 13:
YY_RULE_SETUP
#line 29 "adalexer.l"
{ return(TOKENIZER_TYPE); }
YY_BREAK
case 14:
YY_RULE_SETUP
#line 30 "adalexer.l"
{ return(TOKENIZER_TYPE); }
YY_BREAK
case 15:
YY_RULE_SETUP
#line 31 "adalexer.l"
{ return(TOKENIZER_TYPE); }
YY_BREAK
case 16:
YY_RULE_SETUP
#line 32 "adalexer.l"
{ return(TOKENIZER_TYPE); }
YY_BREAK
case 17:
YY_RULE_SETUP
#line 33 "adalexer.l"
{ return(TOKENIZER_TYPE); }
YY_BREAK
case 18:
YY_RULE_SETUP
#line 35 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 19:
YY_RULE_SETUP
#line 36 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 20:
YY_RULE_SETUP
#line 37 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 21:
YY_RULE_SETUP
#line 38 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 22:
YY_RULE_SETUP
#line 39 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 23:
YY_RULE_SETUP
#line 40 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 24:
YY_RULE_SETUP
#line 41 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 25:
YY_RULE_SETUP
#line 42 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 26:
YY_RULE_SETUP
#line 43 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 27:
YY_RULE_SETUP
#line 44 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 28:
YY_RULE_SETUP
#line 45 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 29:
YY_RULE_SETUP
#line 46 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 30:
YY_RULE_SETUP
#line 47 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 31:
YY_RULE_SETUP
#line 48 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 32:
YY_RULE_SETUP
#line 49 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 33:
YY_RULE_SETUP
#line 50 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 34:
YY_RULE_SETUP
#line 51 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 35:
YY_RULE_SETUP
#line 52 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 36:
YY_RULE_SETUP
#line 53 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 37:
YY_RULE_SETUP
#line 54 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 38:
YY_RULE_SETUP
#line 55 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 39:
YY_RULE_SETUP
#line 56 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 40:
YY_RULE_SETUP
#line 57 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 41:
YY_RULE_SETUP
#line 58 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 42:
YY_RULE_SETUP
#line 59 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 43:
YY_RULE_SETUP
#line 60 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 44:
YY_RULE_SETUP
#line 61 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 45:
YY_RULE_SETUP
#line 62 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 46:
YY_RULE_SETUP
#line 63 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 47:
YY_RULE_SETUP
#line 64 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 48:
YY_RULE_SETUP
#line 65 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 49:
YY_RULE_SETUP
#line 66 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 50:
YY_RULE_SETUP
#line 67 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 51:
YY_RULE_SETUP
#line 68 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 52:
YY_RULE_SETUP
#line 69 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 53:
YY_RULE_SETUP
#line 70 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 54:
YY_RULE_SETUP
#line 71 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 55:
YY_RULE_SETUP
#line 72 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 56:
YY_RULE_SETUP
#line 73 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 57:
YY_RULE_SETUP
#line 74 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 58:
YY_RULE_SETUP
#line 75 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 59:
YY_RULE_SETUP
#line 76 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 60:
YY_RULE_SETUP
#line 77 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 61:
YY_RULE_SETUP
#line 78 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 62:
YY_RULE_SETUP
#line 79 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 63:
YY_RULE_SETUP
#line 80 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 64:
YY_RULE_SETUP
#line 81 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 65:
YY_RULE_SETUP
#line 82 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 66:
YY_RULE_SETUP
#line 83 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 67:
YY_RULE_SETUP
#line 84 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 68:
YY_RULE_SETUP
#line 85 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 69:
YY_RULE_SETUP
#line 86 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 70:
YY_RULE_SETUP
#line 87 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 71:
YY_RULE_SETUP
#line 88 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 72:
YY_RULE_SETUP
#line 89 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 73:
YY_RULE_SETUP
#line 90 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 74:
YY_RULE_SETUP
#line 91 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 75:
YY_RULE_SETUP
#line 92 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 76:
YY_RULE_SETUP
#line 93 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 77:
YY_RULE_SETUP
#line 94 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 78:
YY_RULE_SETUP
#line 95 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 79:
YY_RULE_SETUP
#line 96 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 80:
YY_RULE_SETUP
#line 97 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 81:
YY_RULE_SETUP
#line 98 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 82:
YY_RULE_SETUP
#line 99 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 83:
YY_RULE_SETUP
#line 100 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 84:
YY_RULE_SETUP
#line 101 "adalexer.l"
{ return(TOKENIZER_KEYWORD); }
YY_BREAK
case 85:
YY_RULE_SETUP
#line 103 "adalexer.l"
{ return(TOKENIZER_COMMENT); }
YY_BREAK
case 86:
YY_RULE_SETUP
#line 104 "adalexer.l"
{ return(TOKENIZER_LITERAL); }
YY_BREAK
case 87:
YY_RULE_SETUP
#line 105 "adalexer.l"
{ return(TOKENIZER_LITERAL); }
YY_BREAK
case 88:
YY_RULE_SETUP
#line 106 "adalexer.l"
{ return(TOKENIZER_LITERAL); }
YY_BREAK
case 89:
YY_RULE_SETUP
#line 108 "adalexer.l"
{ return(TOKENIZER_NEWLINE); }
YY_BREAK
case 90:
YY_RULE_SETUP
#line 109 "adalexer.l"
{ return(TOKENIZER_NEWLINE); }
YY_BREAK
case 91:
YY_RULE_SETUP
#line 110 "adalexer.l"
{ return(TOKENIZER_NEWLINE); }
YY_BREAK
case 92:
YY_RULE_SETUP
#line 111 "adalexer.l"
{ return(TOKENIZER_TEXT); }
YY_BREAK
case 93:
YY_RULE_SETUP
#line 112 "adalexer.l"
{ return(TOKENIZER_TEXT); }
YY_BREAK
case 94:
YY_RULE_SETUP
#line 113 "adalexer.l"
{ return(TOKENIZER_TEXT); }
YY_BREAK
case 95:
YY_RULE_SETUP
#line 114 "adalexer.l"
ECHO;
YY_BREAK
#line 1350 "adalexer.c"
case YY_STATE_EOF(INITIAL):
yyterminate();
case YY_END_OF_BUFFER:
{
/* Amount of text matched not including the EOB char. */
int yy_amount_of_matched_text = (int) (yy_cp - yytext_ptr) - 1;
/* Undo the effects of YY_DO_BEFORE_ACTION. */
*yy_cp = yy_hold_char;
YY_RESTORE_YY_MORE_OFFSET
if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_NEW )
{
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed yyin at a new source and called
* yylex(). If so, then we have to assure
* consistency between yy_current_buffer and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
* back-up) that will match for the new input source.
*/
yy_n_chars = yy_current_buffer->yy_n_chars;
yy_current_buffer->yy_input_file = yyin;
yy_current_buffer->yy_buffer_status = YY_BUFFER_NORMAL;
}
/* Note that here we test for yy_c_buf_p "<=" to the position
* of the first EOB in the buffer, since yy_c_buf_p will
* already have been incremented past the NUL character
* (since all states make transitions on EOB to the
* end-of-buffer state). Contrast this with the test
* in input().
*/
if ( yy_c_buf_p <= &yy_current_buffer->yy_ch_buf[yy_n_chars] )
{ /* This was really a NUL. */
yy_state_type yy_next_state;
yy_c_buf_p = yytext_ptr + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state();
/* Okay, we're now positioned to make the NUL
* transition. We couldn't have
* yy_get_previous_state() go ahead and do it
* for us because it doesn't know how to deal
* with the possibility of jamming (and we don't
* want to build jamming into it because then it
* will run more slowly).
*/
yy_next_state = yy_try_NUL_trans( yy_current_state );
yy_bp = yytext_ptr + YY_MORE_ADJ;
if ( yy_next_state )
{
/* Consume the NUL. */
yy_cp = ++yy_c_buf_p;
yy_current_state = yy_next_state;
goto yy_match;
}
else
{
yy_cp = yy_c_buf_p;
goto yy_find_action;
}
}
else switch ( yy_get_next_buffer() )
{
case EOB_ACT_END_OF_FILE:
{
yy_did_buffer_switch_on_eof = 0;
if ( yywrap() )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
* yytext, we can now set up
* yy_c_buf_p so that if some total
* hoser (like flex itself) wants to
* call the scanner after we return the
* YY_NULL, it'll still work - another
* YY_NULL will get returned.
*/
yy_c_buf_p = yytext_ptr + YY_MORE_ADJ;
yy_act = YY_STATE_EOF(YY_START);
goto do_action;
}
else
{
if ( ! yy_did_buffer_switch_on_eof )
YY_NEW_FILE;
}
break;
}
case EOB_ACT_CONTINUE_SCAN:
yy_c_buf_p =
yytext_ptr + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state();
yy_cp = yy_c_buf_p;
yy_bp = yytext_ptr + YY_MORE_ADJ;
goto yy_match;
case EOB_ACT_LAST_MATCH:
yy_c_buf_p =
&yy_current_buffer->yy_ch_buf[yy_n_chars];
yy_current_state = yy_get_previous_state();
yy_cp = yy_c_buf_p;
yy_bp = yytext_ptr + YY_MORE_ADJ;
goto yy_find_action;
}
break;
}
default:
YY_FATAL_ERROR(
"fatal flex scanner internal error--no action found" );
} /* end of action switch */
} /* end of scanning one token */
} /* end of yylex */
/* yy_get_next_buffer - try to read in a new buffer
*
* Returns a code representing an action:
* EOB_ACT_LAST_MATCH -
* EOB_ACT_CONTINUE_SCAN - continue scanning from current position
* EOB_ACT_END_OF_FILE - end of file
*/
static int yy_get_next_buffer()
{
register char *dest = yy_current_buffer->yy_ch_buf;
register char *source = yytext_ptr;
register int number_to_move, i;
int ret_val;
if ( yy_c_buf_p > &yy_current_buffer->yy_ch_buf[yy_n_chars + 1] )
YY_FATAL_ERROR(
"fatal flex scanner internal error--end of buffer missed" );
if ( yy_current_buffer->yy_fill_buffer == 0 )
{ /* Don't try to fill the buffer, so this is an EOF. */
if ( yy_c_buf_p - yytext_ptr - YY_MORE_ADJ == 1 )
{
/* We matched a single character, the EOB, so
* treat this as a final EOF.
*/
return EOB_ACT_END_OF_FILE;
}
else
{
/* We matched some text prior to the EOB, first
* process it.
*/
return EOB_ACT_LAST_MATCH;
}
}
/* Try to read more data. */
/* First move last chars to start of buffer. */
number_to_move = (int) (yy_c_buf_p - yytext_ptr) - 1;
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_EOF_PENDING )
/* don't do the read, it's not guaranteed to return an EOF,
* just force an EOF
*/
yy_current_buffer->yy_n_chars = yy_n_chars = 0;
else
{
int num_to_read =
yy_current_buffer->yy_buf_size - number_to_move - 1;
while ( num_to_read <= 0 )
{ /* Not enough room in the buffer - grow it. */
#ifdef YY_USES_REJECT
YY_FATAL_ERROR(
"input buffer overflow, can't enlarge buffer because scanner uses REJECT" );
#else
/* just a shorter name for the current buffer */
YY_BUFFER_STATE b = yy_current_buffer;
int yy_c_buf_p_offset =
(int) (yy_c_buf_p - b->yy_ch_buf);
if ( b->yy_is_our_buffer )
{
int new_size = b->yy_buf_size * 2;
if ( new_size <= 0 )
b->yy_buf_size += b->yy_buf_size / 8;
else
b->yy_buf_size *= 2;
b->yy_ch_buf = (char *)
/* Include room in for 2 EOB chars. */
yy_flex_realloc( (void *) b->yy_ch_buf,
b->yy_buf_size + 2 );
}
else
/* Can't grow it, we don't own it. */
b->yy_ch_buf = 0;
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR(
"fatal error - scanner input buffer overflow" );
yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset];
num_to_read = yy_current_buffer->yy_buf_size -
number_to_move - 1;
#endif
}
if ( num_to_read > YY_READ_BUF_SIZE )
num_to_read = YY_READ_BUF_SIZE;
/* Read in more data. */
YY_INPUT( (&yy_current_buffer->yy_ch_buf[number_to_move]),
yy_n_chars, num_to_read );
yy_current_buffer->yy_n_chars = yy_n_chars;
}
if ( yy_n_chars == 0 )
{
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
yyrestart( yyin );
}
else
{
ret_val = EOB_ACT_LAST_MATCH;
yy_current_buffer->yy_buffer_status =
YY_BUFFER_EOF_PENDING;
}
}
else
ret_val = EOB_ACT_CONTINUE_SCAN;
yy_n_chars += number_to_move;
yy_current_buffer->yy_ch_buf[yy_n_chars] = YY_END_OF_BUFFER_CHAR;
yy_current_buffer->yy_ch_buf[yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR;
yytext_ptr = &yy_current_buffer->yy_ch_buf[0];
return ret_val;
}
/* yy_get_previous_state - get the state just before the EOB char was reached */
static yy_state_type yy_get_previous_state()
{
register yy_state_type yy_current_state;
register char *yy_cp;
yy_current_state = yy_start;
for ( yy_cp = yytext_ptr + YY_MORE_ADJ; yy_cp < yy_c_buf_p; ++yy_cp )
{
register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
if ( yy_accept[yy_current_state] )
{
yy_last_accepting_state = yy_current_state;
yy_last_accepting_cpos = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 400 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
}
return yy_current_state;
}
/* yy_try_NUL_trans - try to make a transition on the NUL character
*
* synopsis
* next_state = yy_try_NUL_trans( current_state );
*/
#ifdef YY_USE_PROTOS
static yy_state_type yy_try_NUL_trans( yy_state_type yy_current_state )
#else
static yy_state_type yy_try_NUL_trans( yy_current_state )
yy_state_type yy_current_state;
#endif
{
register int yy_is_jam;
register char *yy_cp = yy_c_buf_p;
register YY_CHAR yy_c = 1;
if ( yy_accept[yy_current_state] )
{
yy_last_accepting_state = yy_current_state;
yy_last_accepting_cpos = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 400 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
yy_is_jam = (yy_current_state == 399);
return yy_is_jam ? 0 : yy_current_state;
}
#ifndef YY_NO_UNPUT
#ifdef YY_USE_PROTOS
static void yyunput( int c, register char *yy_bp )
#else
static void yyunput( c, yy_bp )
int c;
register char *yy_bp;
#endif
{
register char *yy_cp = yy_c_buf_p;
/* undo effects of setting up yytext */
*yy_cp = yy_hold_char;
if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 )
{ /* need to shift things up to make room */
/* +2 for EOB chars. */
register int number_to_move = yy_n_chars + 2;
register char *dest = &yy_current_buffer->yy_ch_buf[
yy_current_buffer->yy_buf_size + 2];
register char *source =
&yy_current_buffer->yy_ch_buf[number_to_move];
while ( source > yy_current_buffer->yy_ch_buf )
*--dest = *--source;
yy_cp += (int) (dest - source);
yy_bp += (int) (dest - source);
yy_current_buffer->yy_n_chars =
yy_n_chars = yy_current_buffer->yy_buf_size;
if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 )
YY_FATAL_ERROR( "flex scanner push-back overflow" );
}
*--yy_cp = (char) c;
yytext_ptr = yy_bp;
yy_hold_char = *yy_cp;
yy_c_buf_p = yy_cp;
}
#endif /* ifndef YY_NO_UNPUT */
#ifdef __cplusplus
static int yyinput()
#else
static int input()
#endif
{
int c;
*yy_c_buf_p = yy_hold_char;
if ( *yy_c_buf_p == YY_END_OF_BUFFER_CHAR )
{
/* yy_c_buf_p now points to the character we want to return.
* If this occurs *before* the EOB characters, then it's a
* valid NUL; if not, then we've hit the end of the buffer.
*/
if ( yy_c_buf_p < &yy_current_buffer->yy_ch_buf[yy_n_chars] )
/* This was really a NUL. */
*yy_c_buf_p = '\0';
else
{ /* need more input */
int offset = yy_c_buf_p - yytext_ptr;
++yy_c_buf_p;
switch ( yy_get_next_buffer() )
{
case EOB_ACT_LAST_MATCH:
/* This happens because yy_g_n_b()
* sees that we've accumulated a
* token and flags that we need to
* try matching the token before
* proceeding. But for input(),
* there's no matching to consider.
* So convert the EOB_ACT_LAST_MATCH
* to EOB_ACT_END_OF_FILE.
*/
/* Reset buffer status. */
yyrestart( yyin );
/* fall through */
case EOB_ACT_END_OF_FILE:
{
if ( yywrap() )
return EOF;
if ( ! yy_did_buffer_switch_on_eof )
YY_NEW_FILE;
#ifdef __cplusplus
return yyinput();
#else
return input();
#endif
}
case EOB_ACT_CONTINUE_SCAN:
yy_c_buf_p = yytext_ptr + offset;
break;
}
}
}
c = *(unsigned char *) yy_c_buf_p; /* cast for 8-bit char's */
*yy_c_buf_p = '\0'; /* preserve yytext */
yy_hold_char = *++yy_c_buf_p;
return c;
}
#ifdef YY_USE_PROTOS
void yyrestart( FILE *input_file )
#else
void yyrestart( input_file )
FILE *input_file;
#endif
{
if ( ! yy_current_buffer )
yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE );
yy_init_buffer( yy_current_buffer, input_file );
yy_load_buffer_state();
}
#ifdef YY_USE_PROTOS
void yy_switch_to_buffer( YY_BUFFER_STATE new_buffer )
#else
void yy_switch_to_buffer( new_buffer )
YY_BUFFER_STATE new_buffer;
#endif
{
if ( yy_current_buffer == new_buffer )
return;
if ( yy_current_buffer )
{
/* Flush out information for old buffer. */
*yy_c_buf_p = yy_hold_char;
yy_current_buffer->yy_buf_pos = yy_c_buf_p;
yy_current_buffer->yy_n_chars = yy_n_chars;
}
yy_current_buffer = new_buffer;
yy_load_buffer_state();
/* We don't actually know whether we did this switch during
* EOF (yywrap()) processing, but the only time this flag
* is looked at is after yywrap() is called, so it's safe
* to go ahead and always set it.
*/
yy_did_buffer_switch_on_eof = 1;
}
#ifdef YY_USE_PROTOS
void yy_load_buffer_state( void )
#else
void yy_load_buffer_state()
#endif
{
yy_n_chars = yy_current_buffer->yy_n_chars;
yytext_ptr = yy_c_buf_p = yy_current_buffer->yy_buf_pos;
yyin = yy_current_buffer->yy_input_file;
yy_hold_char = *yy_c_buf_p;
}
#ifdef YY_USE_PROTOS
YY_BUFFER_STATE yy_create_buffer( FILE *file, int size )
#else
YY_BUFFER_STATE yy_create_buffer( file, size )
FILE *file;
int size;
#endif
{
YY_BUFFER_STATE b;
b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
b->yy_ch_buf = (char *) yy_flex_alloc( b->yy_buf_size + 2 );
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_is_our_buffer = 1;
yy_init_buffer( b, file );
return b;
}
#ifdef YY_USE_PROTOS
void yy_delete_buffer( YY_BUFFER_STATE b )
#else
void yy_delete_buffer( b )
YY_BUFFER_STATE b;
#endif
{
if ( ! b )
return;
if ( b == yy_current_buffer )
yy_current_buffer = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
yy_flex_free( (void *) b->yy_ch_buf );
yy_flex_free( (void *) b );
}
#ifndef _WIN32
#include <unistd.h>
#else
#ifndef YY_ALWAYS_INTERACTIVE
#ifndef YY_NEVER_INTERACTIVE
extern int isatty YY_PROTO(( int ));
#endif
#endif
#endif
#ifdef YY_USE_PROTOS
void yy_init_buffer( YY_BUFFER_STATE b, FILE *file )
#else
void yy_init_buffer( b, file )
YY_BUFFER_STATE b;
FILE *file;
#endif
{
yy_flush_buffer( b );
b->yy_input_file = file;
b->yy_fill_buffer = 1;
#if YY_ALWAYS_INTERACTIVE
b->yy_is_interactive = 1;
#else
#if YY_NEVER_INTERACTIVE
b->yy_is_interactive = 0;
#else
b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
#endif
#endif
}
#ifdef YY_USE_PROTOS
void yy_flush_buffer( YY_BUFFER_STATE b )
#else
void yy_flush_buffer( b )
YY_BUFFER_STATE b;
#endif
{
if ( ! b )
return;
b->yy_n_chars = 0;
/* We always need two end-of-buffer characters. The first causes
* a transition to the end-of-buffer state. The second causes
* a jam in that state.
*/
b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
b->yy_buf_pos = &b->yy_ch_buf[0];
b->yy_at_bol = 1;
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == yy_current_buffer )
yy_load_buffer_state();
}
#ifndef YY_NO_SCAN_BUFFER
#ifdef YY_USE_PROTOS
YY_BUFFER_STATE yy_scan_buffer( char *base, yy_size_t size )
#else
YY_BUFFER_STATE yy_scan_buffer( base, size )
char *base;
yy_size_t size;
#endif
{
YY_BUFFER_STATE b;
if ( size < 2 ||
base[size-2] != YY_END_OF_BUFFER_CHAR ||
base[size-1] != YY_END_OF_BUFFER_CHAR )
/* They forgot to leave room for the EOB's. */
return 0;
b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = 0;
b->yy_n_chars = b->yy_buf_size;
b->yy_is_interactive = 0;
b->yy_at_bol = 1;
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
yy_switch_to_buffer( b );
return b;
}
#endif
#ifndef YY_NO_SCAN_STRING
#ifdef YY_USE_PROTOS
YY_BUFFER_STATE yy_scan_string( yyconst char *yy_str )
#else
YY_BUFFER_STATE yy_scan_string( yy_str )
yyconst char *yy_str;
#endif
{
int len;
for ( len = 0; yy_str[len]; ++len )
;
return yy_scan_bytes( yy_str, len );
}
#endif
#ifndef YY_NO_SCAN_BYTES
#ifdef YY_USE_PROTOS
YY_BUFFER_STATE yy_scan_bytes( yyconst char *bytes, int len )
#else
YY_BUFFER_STATE yy_scan_bytes( bytes, len )
yyconst char *bytes;
int len;
#endif
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n;
int i;
/* Get memory for full buffer, including space for trailing EOB's. */
n = len + 2;
buf = (char *) yy_flex_alloc( n );
if ( ! buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
for ( i = 0; i < len; ++i )
buf[i] = bytes[i];
buf[len] = buf[len+1] = YY_END_OF_BUFFER_CHAR;
b = yy_scan_buffer( buf, n );
if ( ! b )
YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
*/
b->yy_is_our_buffer = 1;
return b;
}
#endif
#ifndef YY_NO_PUSH_STATE
#ifdef YY_USE_PROTOS
static void yy_push_state( int new_state )
#else
static void yy_push_state( new_state )
int new_state;
#endif
{
if ( yy_start_stack_ptr >= yy_start_stack_depth )
{
yy_size_t new_size;
yy_start_stack_depth += YY_START_STACK_INCR;
new_size = yy_start_stack_depth * sizeof( int );
if ( ! yy_start_stack )
yy_start_stack = (int *) yy_flex_alloc( new_size );
else
yy_start_stack = (int *) yy_flex_realloc(
(void *) yy_start_stack, new_size );
if ( ! yy_start_stack )
YY_FATAL_ERROR(
"out of memory expanding start-condition stack" );
}
yy_start_stack[yy_start_stack_ptr++] = YY_START;
BEGIN(new_state);
}
#endif
#ifndef YY_NO_POP_STATE
static void yy_pop_state()
{
if ( --yy_start_stack_ptr < 0 )
YY_FATAL_ERROR( "start-condition stack underflow" );
BEGIN(yy_start_stack[yy_start_stack_ptr]);
}
#endif
#ifndef YY_NO_TOP_STATE
static int yy_top_state()
{
return yy_start_stack[yy_start_stack_ptr - 1];
}
#endif
#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif
#ifdef YY_USE_PROTOS
static void yy_fatal_error( yyconst char msg[] )
#else
static void yy_fatal_error( msg )
char msg[];
#endif
{
(void) fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
/* Redefine yyless() so it works in section 3 code. */
#undef yyless
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
yytext[yyleng] = yy_hold_char; \
yy_c_buf_p = yytext + n; \
yy_hold_char = *yy_c_buf_p; \
*yy_c_buf_p = '\0'; \
yyleng = n; \
} \
while ( 0 )
/* Internal utility routines. */
#ifndef yytext_ptr
#ifdef YY_USE_PROTOS
static void yy_flex_strncpy( char *s1, yyconst char *s2, int n )
#else
static void yy_flex_strncpy( s1, s2, n )
char *s1;
yyconst char *s2;
int n;
#endif
{
register int i;
for ( i = 0; i < n; ++i )
s1[i] = s2[i];
}
#endif
#ifdef YY_NEED_STRLEN
#ifdef YY_USE_PROTOS
static int yy_flex_strlen( yyconst char *s )
#else
static int yy_flex_strlen( s )
yyconst char *s;
#endif
{
register int n;
for ( n = 0; s[n]; ++n )
;
return n;
}
#endif
#ifdef YY_USE_PROTOS
static void *yy_flex_alloc( yy_size_t size )
#else
static void *yy_flex_alloc( size )
yy_size_t size;
#endif
{
return (void *) malloc( size );
}
#ifdef YY_USE_PROTOS
static void *yy_flex_realloc( void *ptr, yy_size_t size )
#else
static void *yy_flex_realloc( ptr, size )
void *ptr;
yy_size_t size;
#endif
{
/* The cast to (char *) in the following accommodates both
* implementations that use char* generic pointers, and those
* that use void* generic pointers. It works with the latter
* because both ANSI C and C++ allow castless assignment from
* any pointer type to void*, and deal with argument conversions
* as though doing an assignment.
*/
return (void *) realloc( (char *) ptr, size );
}
#ifdef YY_USE_PROTOS
static void yy_flex_free( void *ptr )
#else
static void yy_flex_free( ptr )
void *ptr;
#endif
{
free( ptr );
}
#if YY_MAIN
int main()
{
yylex();
return 0;
}
#endif
#line 114 "adalexer.l"
int ada_wrap ( void ) {
{
/* Silly impossible function call to stop warning of unused functions */
if ( 0 ) {
yyunput(0, "");
}
}
return 1;
}
| ddaygold/cgdb | lib/tokenizer/adalexer.c | C | gpl-2.0 | 58,434 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.