code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
|---|---|---|---|---|---|
//@HEADER
// ************************************************************************
//
// Kokkos v. 3.0
// Copyright (2020) National Technology & Engineering
// Solutions of Sandia, LLC (NTESS).
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Kokkos is licensed under 3-clause BSD terms of use:
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE
// 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.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
#define KOKKOS_IMPL_COMPILING_LIBRARY true
#include <Kokkos_Core.hpp>
namespace Kokkos {
namespace Impl {
KOKKOS_IMPL_VIEWCOPY_ETI_INST(int64_t********, LayoutRight, LayoutRight,
Experimental::ROCm, int)
KOKKOS_IMPL_VIEWCOPY_ETI_INST(int64_t********, LayoutRight, LayoutLeft,
Experimental::ROCm, int)
KOKKOS_IMPL_VIEWCOPY_ETI_INST(int64_t********, LayoutRight, LayoutStride,
Experimental::ROCm, int)
KOKKOS_IMPL_VIEWFILL_ETI_INST(int64_t********, LayoutRight, Experimental::ROCm,
int)
} // namespace Impl
} // namespace Kokkos
|
pastewka/lammps
|
lib/kokkos/core/src/eti/ROCm/Kokkos_ROCm_ViewCopyETIInst_int_int64_t_LayoutRight_Rank8.cpp
|
C++
|
gpl-2.0
| 2,682
|
#include <yafray_config.h>
#include <core_api/ray.h>
#include <core_api/color.h>
#include <core_api/volume.h>
#include <core_api/bound.h>
#include <core_api/surface.h>
#include <core_api/texture.h>
#include <core_api/environment.h>
#include <utilities/mcqmc.h>
#include <fstream>
#include <cstdlib>
__BEGIN_YAFRAY
struct renderState_t;
struct pSample_t;
class GridVolume : public DensityVolume {
public:
GridVolume(color_t sa, color_t ss, color_t le, float gg, point3d_t pmin, point3d_t pmax)
{
bBox = bound_t(pmin, pmax);
s_a = sa;
s_s = ss;
l_e = le;
g = gg;
haveS_a = (s_a.energy() > 1e-4f);
haveS_s = (s_s.energy() > 1e-4f);
haveL_e = (l_e.energy() > 1e-4f);
std::ifstream inputStream;
inputStream.open("/home/public/3dkram/cloud2_3.df3");
if(!inputStream) Y_ERROR << "GridVolume: Error opening input stream" << yendl;
inputStream.seekg(0, std::ios_base::beg);
std::ifstream::pos_type begin_pos = inputStream.tellg();
inputStream.seekg(0, std::ios_base::end);
int fileSize = static_cast<int>(inputStream.tellg() - begin_pos);
fileSize -= 6;
inputStream.seekg(0, std::ios_base::beg);
int dim[3];
for (int i = 0; i < 3; ++i) {
short i0 = 0, i1 = 0;
inputStream.read( (char*)&i0, 1 );
inputStream.read( (char*)&i1, 1 );
Y_VERBOSE << "GridVolume: " << i0 << " " << i1 << yendl;
dim[i] = (((unsigned short)i0 << 8) | (unsigned short)i1);
}
int sizePerVoxel = fileSize / (dim[0] * dim[1] * dim[2]);
Y_VERBOSE << "GridVolume: " << dim[0] << " " << dim[1] << " " << dim[2] << " " << fileSize << " " << sizePerVoxel << yendl;
sizeX = dim[0];
sizeY = dim[1];
sizeZ = dim[2];
/*
sizeX = 60;
sizeY = 60;
sizeZ = 60;
*/
grid = (float***)malloc(sizeX * sizeof(float));
for (int x = 0; x < sizeX; ++x) {
grid[x] = (float**)malloc(sizeY * sizeof(float));
for (int y = 0; y < sizeY; ++y) {
grid[x][y] = (float*)malloc(sizeZ * sizeof(float));
}
}
for (int z = 0; z < sizeZ; ++z) {
for (int y = 0; y < sizeY; ++y) {
for (int x = 0; x < sizeX; ++x) {
int voxel = 0;
inputStream.read( (char*)&voxel, 1 );
grid[x][y][z] = voxel / 255.f;
/*
float r = sizeX / 2.f;
float r2 = r*r;
float dist = sqrt((x-r)*(x-r) + (y-r)*(y-r) + (z-r)*(z-r));
grid[x][y][z] = (dist < r) ? 1.f-dist/r : 0.0f;
*/
}
}
}
Y_VERBOSE << "GridVolume: Vol.[" << s_a << ", " << s_s << ", " << l_e << "]" << yendl;
}
~GridVolume() {
Y_VERBOSE << "GridVolume: Freeing grid data" << yendl;
for (int x = 0; x < sizeX; ++x) {
for (int y = 0; y < sizeY; ++y) {
free(grid[x][y]);
}
free(grid[x]);
}
free(grid);
}
virtual float Density(point3d_t p);
static VolumeRegion* factory(paraMap_t ¶ms, renderEnvironment_t &render);
protected:
float*** grid;
int sizeX, sizeY, sizeZ;
};
inline float min(float a, float b) { return (a > b) ? b : a; }
inline float max(float a, float b) { return (a < b) ? b : a; }
float GridVolume::Density(const point3d_t p) {
float x = (p.x - bBox.a.x) / bBox.longX() * sizeX - .5f;
float y = (p.y - bBox.a.y) / bBox.longY() * sizeY - .5f;
float z = (p.z - bBox.a.z) / bBox.longZ() * sizeZ - .5f;
int x0 = max(0, floor(x));
int y0 = max(0, floor(y));
int z0 = max(0, floor(z));
int x1 = min(sizeX - 1, ceil(x));
int y1 = min(sizeY - 1, ceil(y));
int z1 = min(sizeZ - 1, ceil(z));
float xd = x - x0;
float yd = y - y0;
float zd = z - z0;
float i1 = grid[x0][y0][z0] * (1-zd) + grid[x0][y0][z1] * zd;
float i2 = grid[x0][y1][z0] * (1-zd) + grid[x0][y1][z1] * zd;
float j1 = grid[x1][y0][z0] * (1-zd) + grid[x1][y0][z1] * zd;
float j2 = grid[x1][y1][z0] * (1-zd) + grid[x1][y1][z1] * zd;
float w1 = i1 * (1 - yd) + i2 * yd;
float w2 = j1 * (1 - yd) + j2 * yd;
float dens = w1 * (1 - xd) + w2 * xd;
return dens;
}
VolumeRegion* GridVolume::factory(paraMap_t ¶ms,renderEnvironment_t &render) {
float ss = .1f;
float sa = .1f;
float le = .0f;
float g = .0f;
float min[] = {0, 0, 0};
float max[] = {0, 0, 0};
params.getParam("sigma_s", ss);
params.getParam("sigma_a", sa);
params.getParam("l_e", le);
params.getParam("g", g);
params.getParam("minX", min[0]);
params.getParam("minY", min[1]);
params.getParam("minZ", min[2]);
params.getParam("maxX", max[0]);
params.getParam("maxY", max[1]);
params.getParam("maxZ", max[2]);
GridVolume *vol = new GridVolume(color_t(sa), color_t(ss), color_t(le), g,
point3d_t(min[0], min[1], min[2]), point3d_t(max[0], max[1], max[2]));
return vol;
}
extern "C"
{
YAFRAYPLUGIN_EXPORT void registerPlugin(renderEnvironment_t &render)
{
render.registerFactory("GridVolume", GridVolume::factory);
}
}
__END_YAFRAY
|
DavidBluecame/Core
|
src/volumes/GridVolume.cc
|
C++
|
gpl-2.0
| 4,802
|
/*
* $RCSfile: JspFactory.java,v $
* $Revision: 1.1 $
* $Date: 2013-02-19 $
*
* Copyright (C) 2008 Skin, Inc. All rights reserved.
*
* This software is the proprietary information of Skin, Inc.
* Use is subject to license terms.
*/
package com.skin.ayada.runtime;
import java.io.Writer;
import java.util.Map;
import com.skin.ayada.ExpressionContext;
import com.skin.ayada.JspWriter;
import com.skin.ayada.PageContext;
/**
* <p>Title: JspFactory</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2006</p>
* @author xuesong.net
* @version 1.0
*/
public class JspFactory {
/**
* @param writer
* @return PageContext
*/
public static PageContext getPageContext(Writer writer) {
return getPageContext((Map<String, Object>)null, writer, 8192, false);
}
/**
* @param context
* @param writer
* @return PageContext
*/
public static PageContext getPageContext(Map<String, Object> context, Writer writer) {
return getPageContext(context, writer, 8192, false);
}
/**
* @param context
* @param writer
* @param buffserSize
* @param autoFlush
* @return PageContext
*/
public static PageContext getPageContext(Map<String, Object> context, Writer writer, int buffserSize, boolean autoFlush) {
JspWriter out = null;
if(writer instanceof JspWriter) {
out = (JspWriter)writer;
}
else {
out = new JspWriter(writer, buffserSize, autoFlush);
}
DefaultPageContext pageContext = new DefaultPageContext(out);
ExpressionContext expressionContext = DefaultExpressionFactory.getDefaultExpressionContext(pageContext);
pageContext.setTemplateContext(null);
pageContext.setExpressionContext(expressionContext);
pageContext.setContext(context);
return pageContext;
}
}
|
xuesong123/jsp-jstl-engine
|
src/main/java/com/skin/ayada/runtime/JspFactory.java
|
Java
|
gpl-2.0
| 1,893
|
#!/usr/bin/env python
###############################################################################
# $Id: rasterize.py 32165 2015-12-13 19:01:22Z goatbar $
#
# Project: GDAL/OGR Test Suite
# Purpose: Test RasterizeLayer() and related calls.
# Author: Frank Warmerdam <warmerdam@pobox.com>
#
###############################################################################
# Copyright (c) 2008, Frank Warmerdam <warmerdam@pobox.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
###############################################################################
import sys
sys.path.append( '../pymod' )
import gdaltest
import ogrtest
from osgeo import gdal, ogr, osr
###############################################################################
# Simple polygon rasterization.
def rasterize_1():
# Setup working spatial reference
sr_wkt = 'LOCAL_CS["arbitrary"]'
sr = osr.SpatialReference( sr_wkt )
# Create a memory raster to rasterize into.
target_ds = gdal.GetDriverByName('MEM').Create( '', 100, 100, 3,
gdal.GDT_Byte )
target_ds.SetGeoTransform( (1000,1,0,1100,0,-1) )
target_ds.SetProjection( sr_wkt )
# Create a memory layer to rasterize from.
rast_ogr_ds = \
ogr.GetDriverByName('Memory').CreateDataSource( 'wrk' )
rast_mem_lyr = rast_ogr_ds.CreateLayer( 'poly', srs=sr )
# Add a polygon.
wkt_geom = 'POLYGON((1020 1030,1020 1045,1050 1045,1050 1030,1020 1030))'
feat = ogr.Feature( rast_mem_lyr.GetLayerDefn() )
feat.SetGeometryDirectly( ogr.Geometry(wkt = wkt_geom) )
rast_mem_lyr.CreateFeature( feat )
# Add a linestring.
wkt_geom = 'LINESTRING(1000 1000, 1100 1050)'
feat = ogr.Feature( rast_mem_lyr.GetLayerDefn() )
feat.SetGeometryDirectly( ogr.Geometry(wkt = wkt_geom) )
rast_mem_lyr.CreateFeature( feat )
# Run the algorithm.
err = gdal.RasterizeLayer( target_ds, [3,2,1], rast_mem_lyr,
burn_values = [200,220,240] )
if err != 0:
print(err)
gdaltest.post_reason( 'got non-zero result code from RasterizeLayer' )
return 'fail'
# Check results.
expected = 6452
checksum = target_ds.GetRasterBand(2).Checksum()
if checksum != expected:
print(checksum)
gdaltest.post_reason( 'Did not get expected image checksum' )
gdal.GetDriverByName('GTiff').CreateCopy('tmp/rasterize_1.tif',target_ds)
return 'fail'
return 'success'
###############################################################################
# Test rasterization with ALL_TOUCHED.
def rasterize_2():
# Setup working spatial reference
sr_wkt = 'LOCAL_CS["arbitrary"]'
# Create a memory raster to rasterize into.
target_ds = gdal.GetDriverByName('MEM').Create( '', 12, 12, 3,
gdal.GDT_Byte )
target_ds.SetGeoTransform( (0,1,0,12,0,-1) )
target_ds.SetProjection( sr_wkt )
# Create a memory layer to rasterize from.
cutline_ds = ogr.Open( 'data/cutline.csv' )
# Run the algorithm.
gdal.PushErrorHandler( 'CPLQuietErrorHandler' )
err = gdal.RasterizeLayer( target_ds, [3,2,1], cutline_ds.GetLayer(0),
burn_values = [200,220,240],
options = ["ALL_TOUCHED=TRUE"] )
gdal.PopErrorHandler()
if err != 0:
print(err)
gdaltest.post_reason( 'got non-zero result code from RasterizeLayer' )
return 'fail'
# Check results.
expected = 121
checksum = target_ds.GetRasterBand(2).Checksum()
if checksum != expected:
print(checksum)
gdaltest.post_reason( 'Did not get expected image checksum' )
gdal.GetDriverByName('GTiff').CreateCopy('tmp/rasterize_2.tif',target_ds)
return 'fail'
return 'success'
###############################################################################
# Rasterization with BURN_VALUE_FROM.
def rasterize_3():
# Setup working spatial reference
sr_wkt = 'LOCAL_CS["arbitrary"]'
sr = osr.SpatialReference( sr_wkt )
# Create a memory raster to rasterize into.
target_ds = gdal.GetDriverByName('MEM').Create( '', 100, 100, 3,
gdal.GDT_Byte )
target_ds.SetGeoTransform( (1000,1,0,1100,0,-1) )
target_ds.SetProjection( sr_wkt )
# Create a memory layer to rasterize from.
rast_ogr_ds = \
ogr.GetDriverByName('Memory').CreateDataSource( 'wrk' )
rast_mem_lyr = rast_ogr_ds.CreateLayer( 'poly', srs=sr )
# Add polygons and linestrings.
wkt_geom = ['POLYGON((1020 1030 40,1020 1045 30,1050 1045 20,1050 1030 35,1020 1030 40))',
'POLYGON((1010 1046 85,1015 1055 35,1055 1060 26,1054 1048 35,1010 1046 85))',
'POLYGON((1020 1076 190,1025 1085 35,1065 1090 26,1064 1078 35,1020 1076 190),(1023 1079 5,1061 1081 35,1062 1087 26,1028 1082 35,1023 1079 85))',
'LINESTRING(1005 1000 10, 1100 1050 120)',
'LINESTRING(1000 1000 150, 1095 1050 -5, 1080 1080 200)']
for g in wkt_geom:
feat = ogr.Feature( rast_mem_lyr.GetLayerDefn() )
feat.SetGeometryDirectly( ogr.Geometry(wkt = g) )
rast_mem_lyr.CreateFeature( feat )
# Run the algorithm.
err = gdal.RasterizeLayer( target_ds, [3,2,1], rast_mem_lyr,
burn_values = [10,10,55], options = ["BURN_VALUE_FROM=Z"] )
if err != 0:
print(err)
gdaltest.post_reason( 'got non-zero result code from RasterizeLayer' )
return 'fail'
# Check results.
expected = 15006
checksum = target_ds.GetRasterBand(2).Checksum()
if checksum != expected:
print(checksum)
gdaltest.post_reason( 'Did not get expected image checksum' )
gdal.GetDriverByName('GTiff').CreateCopy('tmp/rasterize_3.tif',target_ds)
return 'fail'
return 'success'
###############################################################################
# Rasterization with ATTRIBUTE.
def rasterize_4():
# Setup working spatial reference
sr_wkt = 'LOCAL_CS["arbitrary"]'
sr = osr.SpatialReference( sr_wkt )
# Create a memory raster to rasterize into.
target_ds = gdal.GetDriverByName('MEM').Create( '', 100, 100, 3,
gdal.GDT_Byte )
target_ds.SetGeoTransform( (1000,1,0,1100,0,-1) )
target_ds.SetProjection( sr_wkt )
# Create a memory layer to rasterize from.
rast_ogr_ds = ogr.GetDriverByName('Memory').CreateDataSource( 'wrk' )
rast_mem_lyr = rast_ogr_ds.CreateLayer( 'poly', srs=sr )
# Setup Schema
ogrtest.quick_create_layer_def( rast_mem_lyr,
[ ('CELSIUS', ogr.OFTReal) ] )
# Add polygons and linestrings and a field named CELSIUS.
wkt_geom = ['POLYGON((1020 1030 40,1020 1045 30,1050 1045 20,1050 1030 35,1020 1030 40))',
'POLYGON((1010 1046 85,1015 1055 35,1055 1060 26,1054 1048 35,1010 1046 85))',
'POLYGON((1020 1076 190,1025 1085 35,1065 1090 26,1064 1078 35,1020 1076 190),(1023 1079 5,1061 1081 35,1062 1087 26,1028 1082 35,1023 1079 85))',
'LINESTRING(1005 1000 10, 1100 1050 120)',
'LINESTRING(1000 1000 150, 1095 1050 -5, 1080 1080 200)']
celsius_field_values = [50,255,60,100,180]
i = 0
for g in wkt_geom:
feat = ogr.Feature( rast_mem_lyr.GetLayerDefn() )
feat.SetGeometryDirectly( ogr.Geometry(wkt = g) )
feat.SetField( 'CELSIUS', celsius_field_values[i] )
rast_mem_lyr.CreateFeature( feat )
i = i + 1
# Run the algorithm.
err = gdal.RasterizeLayer( target_ds, [1,2,3], rast_mem_lyr,
options = ["ATTRIBUTE=CELSIUS"] )
if err != 0:
print(err)
gdaltest.post_reason( 'got non-zero result code from RasterizeLayer' )
return 'fail'
# Check results.
expected = 16265
checksum = target_ds.GetRasterBand(2).Checksum()
if checksum != expected:
print(checksum)
gdaltest.post_reason( 'Did not get expected image checksum' )
gdal.GetDriverByName('GTiff').CreateCopy('tmp/rasterize_4.tif',target_ds)
return 'fail'
return 'success'
###############################################################################
# Rasterization with MERGE_ALG=ADD.
def rasterize_5():
# Setup working spatial reference
sr_wkt = 'LOCAL_CS["arbitrary"]'
sr = osr.SpatialReference( sr_wkt )
# Create a memory raster to rasterize into.
target_ds = gdal.GetDriverByName('MEM').Create( '', 100, 100, 3,
gdal.GDT_Byte )
target_ds.SetGeoTransform( (1000,1,0,1100,0,-1) )
target_ds.SetProjection( sr_wkt )
# Create a memory layer to rasterize from.
rast_ogr_ds = \
ogr.GetDriverByName('Memory').CreateDataSource( 'wrk' )
rast_mem_lyr = rast_ogr_ds.CreateLayer( 'poly', srs=sr )
# Add polygons.
wkt_geom = 'POLYGON((1020 1030,1020 1045,1050 1045,1050 1030,1020 1030))'
feat = ogr.Feature( rast_mem_lyr.GetLayerDefn() )
feat.SetGeometryDirectly( ogr.Geometry(wkt = wkt_geom) )
rast_mem_lyr.CreateFeature( feat )
wkt_geom = 'POLYGON((1045 1050,1055 1050,1055 1020,1045 1020,1045 1050))'
feat = ogr.Feature( rast_mem_lyr.GetLayerDefn() )
feat.SetGeometryDirectly( ogr.Geometry(wkt = wkt_geom) )
rast_mem_lyr.CreateFeature( feat )
# Add linestrings.
wkt_geom = 'LINESTRING(1000 1000, 1100 1050)'
feat = ogr.Feature( rast_mem_lyr.GetLayerDefn() )
feat.SetGeometryDirectly( ogr.Geometry(wkt = wkt_geom) )
rast_mem_lyr.CreateFeature( feat )
wkt_geom = 'LINESTRING(1005 1000, 1000 1050)'
feat = ogr.Feature( rast_mem_lyr.GetLayerDefn() )
feat.SetGeometryDirectly( ogr.Geometry(wkt = wkt_geom) )
rast_mem_lyr.CreateFeature( feat )
# Run the algorithm.
err = gdal.RasterizeLayer( target_ds, [1, 2, 3], rast_mem_lyr,
burn_values = [100,110,120],
options = ["MERGE_ALG=ADD"])
if err != 0:
print(err)
gdaltest.post_reason( 'got non-zero result code from RasterizeLayer' )
return 'fail'
# Check results.
expected = 13022
checksum = target_ds.GetRasterBand(2).Checksum()
if checksum != expected:
print(checksum)
gdaltest.post_reason( 'Did not get expected image checksum' )
gdal.GetDriverByName('GTiff').CreateCopy('tmp/rasterize_5.tif',target_ds)
return 'fail'
return 'success'
gdaltest_list = [
rasterize_1,
rasterize_2,
rasterize_3,
rasterize_4,
rasterize_5,
]
if __name__ == '__main__':
gdaltest.setup_run( 'rasterize' )
gdaltest.run_tests( gdaltest_list )
gdaltest.summarize()
|
nextgis-extra/tests
|
lib_gdal/alg/rasterize.py
|
Python
|
gpl-2.0
| 11,966
|
/* Copyright (c) 2000, 2016, Oracle and/or its affiliates.
Copyright (c) 2012, 2020, MariaDB Corporation.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */
/**
@file
This file is the net layer API for the MySQL client/server protocol.
Write and read of logical packets to/from socket.
Writes are cached into net_buffer_length big packets.
Read packets are reallocated dynamicly when reading big packets.
Each logical packet has the following pre-info:
3 byte length & 1 byte package-number.
This file needs to be written in C as it's used by the libmysql client as a
C file.
*/
/*
HFTODO this must be hidden if we don't want client capabilities in
embedded library
*/
#include "mariadb.h"
#include <mysql.h>
#include <mysql_com.h>
#include <mysqld_error.h>
#include <my_sys.h>
#include <m_string.h>
#include <my_net.h>
#include <violite.h>
#include <signal.h>
#include "probes_mysql.h"
#include <debug_sync.h>
#include "proxy_protocol.h"
PSI_memory_key key_memory_NET_buff;
PSI_memory_key key_memory_NET_compress_packet;
#ifdef EMBEDDED_LIBRARY
#undef MYSQL_SERVER
#undef MYSQL_CLIENT
#define MYSQL_CLIENT
#endif /*EMBEDDED_LIBRARY */
/*
to reduce the number of ifdef's in the code
*/
#ifdef EXTRA_DEBUG
#define EXTRA_DEBUG_fprintf fprintf
#define EXTRA_DEBUG_fflush fflush
#define EXTRA_DEBUG_ASSERT DBUG_ASSERT
#else
static void inline EXTRA_DEBUG_fprintf(...) {}
#ifndef MYSQL_SERVER
static int inline EXTRA_DEBUG_fflush(...) { return 0; }
#endif
#endif /* EXTRA_DEBUG */
#ifdef MYSQL_SERVER
#include <sql_class.h>
#include <sql_connect.h>
#define MYSQL_SERVER_my_error my_error
#else
static void inline MYSQL_SERVER_my_error(...) {}
#endif
#ifndef EXTRA_DEBUG_ASSERT
# define EXTRA_DEBUG_ASSERT(X) do {} while(0)
#endif
/*
The following handles the differences when this is linked between the
client and the server.
This gives an error if a too big packet is found.
The server can change this, but because the client can't normally do this
the client should have a bigger max_allowed_packet.
*/
#if defined(_WIN32) || !defined(MYSQL_SERVER)
/* The following is because alarms doesn't work on windows. */
#ifndef NO_ALARM
#define NO_ALARM
#endif
#endif
#ifndef NO_ALARM
#include "my_pthread.h"
void sql_print_error(const char *format,...);
#else
#define DONT_USE_THR_ALARM
#endif /* NO_ALARM */
#include "thr_alarm.h"
#ifdef MYSQL_SERVER
/*
The following variables/functions should really not be declared
extern, but as it's hard to include sql_priv.h here, we have to
live with this for a while.
*/
extern ulonglong test_flags;
extern ulong bytes_sent, bytes_received, net_big_packet_count;
#ifdef HAVE_QUERY_CACHE
#define USE_QUERY_CACHE
extern void query_cache_insert(void *thd, const char *packet, size_t length,
unsigned pkt_nr);
#endif // HAVE_QUERY_CACHE
#define update_statistics(A) A
extern my_bool thd_net_is_killed(THD *thd);
/* Additional instrumentation hooks for the server */
#include "mysql_com_server.h"
#else
#define update_statistics(A)
#define thd_net_is_killed(A) 0
#endif
static my_bool net_write_buff(NET *, const uchar *, size_t len);
my_bool net_allocate_new_packet(NET *net, void *thd, uint my_flags);
/** Init with packet info. */
my_bool my_net_init(NET *net, Vio *vio, void *thd, uint my_flags)
{
DBUG_ENTER("my_net_init");
DBUG_PRINT("enter", ("my_flags: %u", my_flags));
net->vio = vio;
net->read_timeout= 0;
net->write_timeout= 0;
my_net_local_init(net); /* Set some limits */
if (net_allocate_new_packet(net, thd, my_flags))
DBUG_RETURN(1);
net->error=0; net->return_status=0;
net->pkt_nr=net->compress_pkt_nr=0;
net->last_error[0]=0;
net->compress=0; net->reading_or_writing=0;
net->where_b = net->remain_in_buf=0;
net->net_skip_rest_factor= 0;
net->last_errno=0;
net->thread_specific_malloc= MY_TEST(my_flags & MY_THREAD_SPECIFIC);
net->thd= 0;
#ifdef MYSQL_SERVER
net->extension= NULL;
net->thd= thd;
#endif
if (vio)
{
/* For perl DBI/DBD. */
net->fd= vio_fd(vio);
#if defined(MYSQL_SERVER) && !defined(_WIN32)
if (!(test_flags & TEST_BLOCKING))
{
my_bool old_mode;
vio_blocking(vio, FALSE, &old_mode);
}
#endif
vio_fastsend(vio);
}
DBUG_RETURN(0);
}
/**
Allocate and assign new net buffer
@note In case of error the old buffer left
@retval TRUE error
@retval FALSE success
*/
my_bool net_allocate_new_packet(NET *net, void *thd, uint my_flags)
{
uchar *tmp;
DBUG_ENTER("net_allocate_new_packet");
if (!(tmp= (uchar*) my_malloc(key_memory_NET_buff,
(size_t) net->max_packet +
NET_HEADER_SIZE + COMP_HEADER_SIZE + 1,
MYF(MY_WME | my_flags))))
DBUG_RETURN(1);
net->buff= tmp;
net->buff_end=net->buff+net->max_packet;
net->write_pos=net->read_pos = net->buff;
DBUG_RETURN(0);
}
void net_end(NET *net)
{
DBUG_ENTER("net_end");
my_free(net->buff);
net->buff=0;
DBUG_VOID_RETURN;
}
/** Realloc the packet buffer. */
my_bool net_realloc(NET *net, size_t length)
{
uchar *buff;
size_t pkt_length;
DBUG_ENTER("net_realloc");
DBUG_PRINT("enter",("length: %lu", (ulong) length));
if (length >= net->max_packet_size)
{
DBUG_PRINT("error", ("Packet too large. Max size: %lu",
net->max_packet_size));
/* @todo: 1 and 2 codes are identical. */
net->error= 1;
net->last_errno= ER_NET_PACKET_TOO_LARGE;
MYSQL_SERVER_my_error(ER_NET_PACKET_TOO_LARGE, MYF(0));
DBUG_RETURN(1);
}
pkt_length = (length+IO_SIZE-1) & ~(IO_SIZE-1);
/*
We must allocate some extra bytes for the end 0 and to be able to
read big compressed blocks + 1 safety byte since uint3korr() in
my_real_read() may actually read 4 bytes depending on build flags and
platform.
*/
if (!(buff= (uchar*) my_realloc(key_memory_NET_buff,
(char*) net->buff, pkt_length +
NET_HEADER_SIZE + COMP_HEADER_SIZE + 1,
MYF(MY_WME | (net->thread_specific_malloc
? MY_THREAD_SPECIFIC : 0)))))
{
/* @todo: 1 and 2 codes are identical. */
net->error= 1;
net->last_errno= ER_OUT_OF_RESOURCES;
/* In the server the error is reported by MY_WME flag. */
DBUG_RETURN(1);
}
net->buff=net->write_pos=buff;
net->buff_end=buff+(net->max_packet= (ulong) pkt_length);
DBUG_RETURN(0);
}
/**
Check if there is any data to be read from the socket.
@param sd socket descriptor
@retval
0 No data to read
@retval
1 Data or EOF to read
@retval
-1 Don't know if data is ready or not
*/
#if !defined(EMBEDDED_LIBRARY) && defined(DBUG_OFF)
static int net_data_is_ready(my_socket sd)
{
#ifdef HAVE_POLL
struct pollfd ufds;
int res;
ufds.fd= sd;
ufds.events= POLLIN | POLLPRI;
if (!(res= poll(&ufds, 1, 0)))
return 0;
if (res < 0 || !(ufds.revents & (POLLIN | POLLPRI)))
return 0;
return 1;
#else
fd_set sfds;
struct timeval tv;
int res;
#ifndef _WIN32
/* Windows uses an _array_ of 64 fd's as default, so it's safe */
if (sd >= FD_SETSIZE)
return -1;
#define NET_DATA_IS_READY_CAN_RETURN_MINUS_ONE
#endif
FD_ZERO(&sfds);
FD_SET(sd, &sfds);
tv.tv_sec= tv.tv_usec= 0;
if ((res= select((int) (sd + 1), &sfds, NULL, NULL, &tv)) < 0)
return 0;
else
return MY_TEST(res ? FD_ISSET(sd, &sfds) : 0);
#endif /* HAVE_POLL */
}
#endif /* EMBEDDED_LIBRARY */
/**
Clear (reinitialize) the NET structure for a new command.
@remark Performs debug checking of the socket buffer to
ensure that the protocol sequence is correct.
- Read from socket until there is nothing more to read. Discard
what is read.
- Initialize net for new net_read/net_write calls.
If there is anything when to read 'net_clear' is called this
normally indicates an error in the protocol. Normally one should not
need to do clear the communication buffer. If one compiles without
-DUSE_NET_CLEAR then one wins one read call / query.
When connection is properly closed (for TCP it means with
a FIN packet), then select() considers a socket "ready to read",
in the sense that there's EOF to read, but read() returns 0.
@param net NET handler
@param clear_buffer if <> 0, then clear all data from comm buff
*/
void net_clear(NET *net, my_bool clear_buffer __attribute__((unused)))
{
DBUG_ENTER("net_clear");
/*
We don't do a clear in case of not DBUG_OFF to catch bugs in the
protocol handling.
*/
#if (!defined(EMBEDDED_LIBRARY) && defined(DBUG_OFF)) || defined(USE_NET_CLEAR)
if (clear_buffer)
{
size_t count;
int ready;
while ((ready= net_data_is_ready(vio_fd(net->vio))) > 0)
{
/* The socket is ready */
if ((long) (count= vio_read(net->vio, net->buff,
(size_t) net->max_packet)) > 0)
{
DBUG_PRINT("info",("skipped %ld bytes from file: %s",
(long) count, vio_description(net->vio)));
EXTRA_DEBUG_fprintf(stderr,"Note: net_clear() skipped %ld bytes from file: %s\n",
(long) count, vio_description(net->vio));
}
else
{
DBUG_PRINT("info",("socket ready but only EOF to read - disconnected"));
net->error= 2;
break;
}
}
#ifdef NET_DATA_IS_READY_CAN_RETURN_MINUS_ONE
/* 'net_data_is_ready' returned "don't know" */
if (ready == -1)
{
/* Read unblocking to clear net */
my_bool old_mode;
if (!vio_blocking(net->vio, FALSE, &old_mode))
{
while ((long) (count= vio_read(net->vio, net->buff,
(size_t) net->max_packet)) > 0)
DBUG_PRINT("info",("skipped %ld bytes from file: %s",
(long) count, vio_description(net->vio)));
vio_blocking(net->vio, TRUE, &old_mode);
}
}
#endif /* NET_DATA_IS_READY_CAN_RETURN_MINUS_ONE */
}
#endif /* EMBEDDED_LIBRARY */
net->pkt_nr=net->compress_pkt_nr=0; /* Ready for new command */
net->write_pos=net->buff;
DBUG_VOID_RETURN;
}
/** Flush write_buffer if not empty. */
my_bool net_flush(NET *net)
{
my_bool error= 0;
DBUG_ENTER("net_flush");
if (net->buff != net->write_pos)
{
error= MY_TEST(net_real_write(net, net->buff,
(size_t) (net->write_pos - net->buff)));
net->write_pos= net->buff;
}
/* Sync packet number if using compression */
if (net->compress)
net->pkt_nr=net->compress_pkt_nr;
DBUG_RETURN(error);
}
/*****************************************************************************
** Write something to server/client buffer
*****************************************************************************/
/**
Write a logical packet with packet header.
Format: Packet length (3 bytes), packet number (1 byte)
When compression is used, a 3 byte compression length is added.
@note If compression is used, the original packet is modified!
*/
my_bool my_net_write(NET *net, const uchar *packet, size_t len)
{
uchar buff[NET_HEADER_SIZE];
if (unlikely(!net->vio)) /* nowhere to write */
return 0;
MYSQL_NET_WRITE_START(len);
/*
Big packets are handled by splitting them in packets of MAX_PACKET_LENGTH
length. The last packet is always a packet that is < MAX_PACKET_LENGTH.
(The last packet may even have a length of 0)
*/
while (len >= MAX_PACKET_LENGTH)
{
const ulong z_size = MAX_PACKET_LENGTH;
int3store(buff, z_size);
buff[3]= (uchar) net->pkt_nr++;
if (net_write_buff(net, buff, NET_HEADER_SIZE) ||
net_write_buff(net, packet, z_size))
{
MYSQL_NET_WRITE_DONE(1);
return 1;
}
packet += z_size;
len-= z_size;
}
/* Write last packet */
int3store(buff,len);
buff[3]= (uchar) net->pkt_nr++;
if (net_write_buff(net, buff, NET_HEADER_SIZE))
{
MYSQL_NET_WRITE_DONE(1);
return 1;
}
#ifndef DEBUG_DATA_PACKETS
DBUG_DUMP("packet_header", buff, NET_HEADER_SIZE);
#endif
my_bool rc= MY_TEST(net_write_buff(net, packet, len));
MYSQL_NET_WRITE_DONE(rc);
return rc;
}
/**
Send a command to the server.
The reason for having both header and packet is so that libmysql
can easy add a header to a special command (like prepared statements)
without having to re-alloc the string.
As the command is part of the first data packet, we have to do some data
juggling to put the command in there, without having to create a new
packet.
This function will split big packets into sub-packets if needed.
(Each sub packet can only be 2^24 bytes)
@param net NET handler
@param command Command in MySQL server (enum enum_server_command)
@param header Header to write after command
@param head_len Length of header
@param packet Query or parameter to query
@param len Length of packet
@retval
0 ok
@retval
1 error
*/
my_bool
net_write_command(NET *net,uchar command,
const uchar *header, size_t head_len,
const uchar *packet, size_t len)
{
size_t length=len+1+head_len; /* 1 extra byte for command */
uchar buff[NET_HEADER_SIZE+1];
uint header_size=NET_HEADER_SIZE+1;
my_bool rc;
DBUG_ENTER("net_write_command");
DBUG_PRINT("enter",("length: %lu", (ulong) len));
DBUG_EXECUTE_IF("simulate_error_on_packet_write",
{
if (command == COM_BINLOG_DUMP)
{
net->last_errno = ER_NET_ERROR_ON_WRITE;
DBUG_ASSERT(!debug_sync_set_action(
(THD *)net->thd,
STRING_WITH_LEN("now SIGNAL parked WAIT_FOR continue")));
DBUG_RETURN(true);
}
};);
MYSQL_NET_WRITE_START(length);
buff[4]=command; /* For first packet */
if (length >= MAX_PACKET_LENGTH)
{
/* Take into account that we have the command in the first header */
len= MAX_PACKET_LENGTH - 1 - head_len;
do
{
int3store(buff, MAX_PACKET_LENGTH);
buff[3]= (uchar) net->pkt_nr++;
if (net_write_buff(net, buff, header_size) ||
net_write_buff(net, header, head_len) ||
net_write_buff(net, packet, len))
{
MYSQL_NET_WRITE_DONE(1);
DBUG_RETURN(1);
}
packet+= len;
length-= MAX_PACKET_LENGTH;
len= MAX_PACKET_LENGTH;
head_len= 0;
header_size= NET_HEADER_SIZE;
} while (length >= MAX_PACKET_LENGTH);
len=length; /* Data left to be written */
}
int3store(buff,length);
buff[3]= (uchar) net->pkt_nr++;
rc= MY_TEST(net_write_buff(net, buff, header_size) ||
(head_len && net_write_buff(net, header, head_len)) ||
net_write_buff(net, packet, len) || net_flush(net));
MYSQL_NET_WRITE_DONE(rc);
DBUG_RETURN(rc);
}
/**
Caching the data in a local buffer before sending it.
Fill up net->buffer and send it to the client when full.
If the rest of the to-be-sent-packet is bigger than buffer,
send it in one big block (to avoid copying to internal buffer).
If not, copy the rest of the data to the buffer and return without
sending data.
@param net Network handler
@param packet Packet to send
@param len Length of packet
@note
The cached buffer can be sent as it is with 'net_flush()'.
In this code we have to be careful to not send a packet longer than
MAX_PACKET_LENGTH to net_real_write() if we are using the compressed
protocol as we store the length of the compressed packet in 3 bytes.
@retval
0 ok
@retval
1
*/
static my_bool
net_write_buff(NET *net, const uchar *packet, size_t len)
{
size_t left_length;
if (net->compress && net->max_packet > MAX_PACKET_LENGTH)
left_length= (MAX_PACKET_LENGTH - (net->write_pos - net->buff));
else
left_length= (net->buff_end - net->write_pos);
#ifdef DEBUG_DATA_PACKETS
DBUG_DUMP("data_written", packet, len);
#endif
if (len > left_length)
{
if (net->write_pos != net->buff)
{
/* Fill up already used packet and write it */
memcpy((char*) net->write_pos,packet,left_length);
if (net_real_write(net, net->buff,
(size_t) (net->write_pos - net->buff) + left_length))
return 1;
net->write_pos= net->buff;
packet+= left_length;
len-= left_length;
}
if (net->compress)
{
/*
We can't have bigger packets than 16M with compression
Because the uncompressed length is stored in 3 bytes
*/
left_length= MAX_PACKET_LENGTH;
while (len > left_length)
{
if (net_real_write(net, packet, left_length))
return 1;
packet+= left_length;
len-= left_length;
}
}
if (len > net->max_packet)
return net_real_write(net, packet, len) ? 1 : 0;
/* Send out rest of the blocks as full sized blocks */
}
if (len)
memcpy((char*) net->write_pos,packet,len);
net->write_pos+= len;
return 0;
}
/**
Read and write one packet using timeouts.
If needed, the packet is compressed before sending.
@todo
- TODO is it needed to set this variable if we have no socket
*/
int
net_real_write(NET *net,const uchar *packet, size_t len)
{
size_t length;
const uchar *pos,*end;
thr_alarm_t alarmed;
#ifndef NO_ALARM
ALARM alarm_buff;
#endif
uint retry_count=0;
my_bool net_blocking = vio_is_blocking(net->vio);
DBUG_ENTER("net_real_write");
#if defined(MYSQL_SERVER)
THD *thd= (THD *)net->thd;
#if defined(USE_QUERY_CACHE)
query_cache_insert(thd, (char*) packet, len, net->pkt_nr);
#endif
if (likely(thd))
{
/*
Wait until pending operations (currently it is engine
asynchronous group commit) are finished before replying
to the client, to keep durability promise.
*/
thd->async_state.wait_for_pending_ops();
}
#endif
if (unlikely(net->error == 2))
DBUG_RETURN(-1); /* socket can't be used */
net->reading_or_writing=2;
#ifdef HAVE_COMPRESS
if (net->compress)
{
size_t complen;
uchar *b;
uint header_length=NET_HEADER_SIZE+COMP_HEADER_SIZE;
if (!(b= (uchar*) my_malloc(key_memory_NET_compress_packet,
len + NET_HEADER_SIZE + COMP_HEADER_SIZE + 1,
MYF(MY_WME | (net->thread_specific_malloc
? MY_THREAD_SPECIFIC : 0)))))
{
net->error= 2;
net->last_errno= ER_OUT_OF_RESOURCES;
/* In the server, the error is reported by MY_WME flag. */
net->reading_or_writing= 0;
DBUG_RETURN(1);
}
memcpy(b+header_length,packet,len);
/* Don't compress error packets (compress == 2) */
if (net->compress == 2 || my_compress(b+header_length, &len, &complen))
complen=0;
int3store(&b[NET_HEADER_SIZE],complen);
int3store(b,len);
b[3]=(uchar) (net->compress_pkt_nr++);
len+= header_length;
packet= b;
}
#endif /* HAVE_COMPRESS */
#ifdef DEBUG_DATA_PACKETS
DBUG_DUMP("data_written", packet, len);
#endif
#ifndef NO_ALARM
thr_alarm_init(&alarmed);
if (net_blocking)
thr_alarm(&alarmed, net->write_timeout, &alarm_buff);
#else
alarmed=0;
/* Write timeout is set in my_net_set_write_timeout */
#endif /* NO_ALARM */
pos= packet;
end=pos+len;
while (pos != end)
{
if ((long) (length= vio_write(net->vio,pos,(size_t) (end-pos))) <= 0)
{
my_bool interrupted = vio_should_retry(net->vio);
#if !defined(_WIN32)
if ((interrupted || length == 0) && !thr_alarm_in_use(&alarmed))
{
if (!thr_alarm(&alarmed, net->write_timeout, &alarm_buff))
{ /* Always true for client */
my_bool old_mode;
while (vio_blocking(net->vio, TRUE, &old_mode) < 0)
{
if (vio_should_retry(net->vio) && retry_count++ < net->retry_count)
continue;
EXTRA_DEBUG_fprintf(stderr,
"%s: my_net_write: fcntl returned error %d, aborting thread\n",
my_progname,vio_errno(net->vio));
net->error= 2; /* Close socket */
net->last_errno= ER_NET_PACKET_TOO_LARGE;
MYSQL_SERVER_my_error(ER_NET_PACKET_TOO_LARGE, MYF(0));
goto end;
}
retry_count=0;
continue;
}
}
else
#endif /* !defined(_WIN32) */
if (thr_alarm_in_use(&alarmed) && !thr_got_alarm(&alarmed) &&
interrupted)
{
if (retry_count++ < net->retry_count)
continue;
EXTRA_DEBUG_fprintf(stderr, "%s: write looped, aborting thread\n",
my_progname);
}
#ifndef MYSQL_SERVER
if (vio_errno(net->vio) == SOCKET_EINTR)
{
DBUG_PRINT("warning",("Interrupted write. Retrying..."));
continue;
}
#endif /* !defined(MYSQL_SERVER) */
net->error= 2; /* Close socket */
net->last_errno= (interrupted ? ER_NET_WRITE_INTERRUPTED :
ER_NET_ERROR_ON_WRITE);
MYSQL_SERVER_my_error(net->last_errno, MYF(0));
break;
}
pos+=length;
update_statistics(thd_increment_bytes_sent(net->thd, length));
}
#ifndef _WIN32
end:
#endif
#ifdef HAVE_COMPRESS
if (net->compress)
my_free((void*) packet);
#endif
if (thr_alarm_in_use(&alarmed))
{
my_bool old_mode;
thr_end_alarm(&alarmed);
if (!net_blocking)
vio_blocking(net->vio, net_blocking, &old_mode);
}
net->reading_or_writing=0;
DBUG_RETURN(((int) (pos != end)));
}
/*****************************************************************************
** Read something from server/clinet
*****************************************************************************/
#ifndef NO_ALARM
static my_bool net_safe_read(NET *net, uchar *buff, size_t length,
thr_alarm_t *alarmed)
{
uint retry_count=0;
while (length > 0)
{
size_t tmp;
if ((long) (tmp= vio_read(net->vio, buff, length)) <= 0)
{
my_bool interrupted = vio_should_retry(net->vio);
if (!thr_got_alarm(alarmed) && interrupted)
{ /* Probably in MIT threads */
if (retry_count++ < net->retry_count)
continue;
}
return 1;
}
length-= tmp;
buff+= tmp;
}
return 0;
}
/**
Help function to clear the commuication buffer when we get a too big packet.
@param net Communication handle
@param remain Bytes to read
@param alarmed Parameter for thr_alarm()
@param alarm_buff Parameter for thr_alarm()
@retval
0 Was able to read the whole packet
@retval
1 Got mailformed packet from client
*/
static my_bool my_net_skip_rest(NET *net, uint32 remain, thr_alarm_t *alarmed,
ALARM *alarm_buff)
{
longlong limit= net->max_packet_size*net->net_skip_rest_factor;
uint32 old=remain;
DBUG_ENTER("my_net_skip_rest");
DBUG_PRINT("enter",("bytes_to_skip: %u", (uint) remain));
/* The following is good for debugging */
update_statistics(thd_increment_net_big_packet_count(net->thd, 1));
if (!thr_alarm_in_use(alarmed))
{
my_bool old_mode;
if (thr_alarm(alarmed,net->read_timeout, alarm_buff) ||
vio_blocking(net->vio, TRUE, &old_mode) < 0)
DBUG_RETURN(1); /* Can't setup, abort */
}
for (;;)
{
while (remain > 0)
{
size_t length= MY_MIN(remain, net->max_packet);
if (net_safe_read(net, net->buff, length, alarmed))
DBUG_RETURN(1);
update_statistics(thd_increment_bytes_received(net->thd, length));
remain -= (uint32) length;
limit-= length;
if (limit < 0)
DBUG_RETURN(1);
}
if (old != MAX_PACKET_LENGTH)
break;
if (net_safe_read(net, net->buff, NET_HEADER_SIZE, alarmed))
DBUG_RETURN(1);
limit-= NET_HEADER_SIZE;
old=remain= uint3korr(net->buff);
net->pkt_nr++;
}
DBUG_RETURN(0);
}
#endif /* NO_ALARM */
/**
Try to parse and process proxy protocol header.
This function is called in case MySQL packet header cannot be parsed.
It checks if proxy header was sent, and that it was send from allowed remote
host, as defined by proxy-protocol-networks parameter.
If proxy header is parsed, then THD and ACL structures and changed to indicate
the new peer address and port.
Note, that proxy header can only be sent either when the connection is established,
or as the client reply packet to
*/
#undef IGNORE /* for Windows */
typedef enum { RETRY, ABORT, IGNORE} handle_proxy_header_result;
static handle_proxy_header_result handle_proxy_header(NET *net)
{
#if !defined(MYSQL_SERVER) || defined(EMBEDDED_LIBRARY)
return IGNORE;
#else
THD *thd= (THD *)net->thd;
if (!has_proxy_protocol_header(net) || !thd ||
thd->get_command() != COM_CONNECT)
return IGNORE;
/*
Proxy information found in the first 4 bytes received so far.
Read and parse proxy header , change peer ip address and port in THD.
*/
proxy_peer_info peer_info;
if (!thd->net.vio)
{
DBUG_ASSERT(0);
return ABORT;
}
if (!is_proxy_protocol_allowed((sockaddr *)&(thd->net.vio->remote)))
{
/* proxy-protocol-networks variable needs to be set to allow this remote address */
my_printf_error(ER_HOST_NOT_PRIVILEGED, "Proxy header is not accepted from %s",
MYF(0), thd->main_security_ctx.ip);
return ABORT;
}
if (parse_proxy_protocol_header(net, &peer_info))
{
/* Failed to parse proxy header*/
my_printf_error(ER_UNKNOWN_ERROR, "Failed to parse proxy header", MYF(0));
return ABORT;
}
if (peer_info.is_local_command)
/* proxy header indicates LOCAL connection, no action necessary */
return RETRY;
/* Change peer address in THD and ACL structures.*/
uint host_errors;
return (handle_proxy_header_result)thd_set_peer_addr(thd,
&(peer_info.peer_addr), NULL, peer_info.port,
false, &host_errors);
#endif
}
/**
Reads one packet to net->buff + net->where_b.
Long packets are handled by my_net_read().
This function reallocates the net->buff buffer if necessary.
@return
Returns length of packet.
*/
static ulong
my_real_read(NET *net, size_t *complen,
my_bool header __attribute__((unused)))
{
uchar *pos;
size_t length;
uint i,retry_count=0;
ulong len=packet_error;
my_bool expect_error_packet __attribute__((unused))= 0;
thr_alarm_t alarmed;
#ifndef NO_ALARM
ALARM alarm_buff;
#endif
retry:
my_bool net_blocking=vio_is_blocking(net->vio);
uint32 remain= (net->compress ? NET_HEADER_SIZE+COMP_HEADER_SIZE :
NET_HEADER_SIZE);
#ifdef MYSQL_SERVER
size_t count= remain;
struct st_net_server *server_extension= 0;
if (header)
{
server_extension= static_cast<st_net_server*> (net->extension);
if (server_extension != NULL)
{
void *user_data= server_extension->m_user_data;
server_extension->m_before_header(net, user_data, count);
}
}
#endif
*complen = 0;
net->reading_or_writing=1;
thr_alarm_init(&alarmed);
#ifndef NO_ALARM
if (net_blocking)
thr_alarm(&alarmed,net->read_timeout,&alarm_buff);
#else
/* Read timeout is set in my_net_set_read_timeout */
#endif /* NO_ALARM */
pos = net->buff + net->where_b; /* net->packet -4 */
for (i=0 ; i < 2 ; i++)
{
while (remain > 0)
{
/* First read is done with non blocking mode */
if ((long) (length= vio_read(net->vio, pos, remain)) <= 0L)
{
my_bool interrupted = vio_should_retry(net->vio);
DBUG_PRINT("info",("vio_read returned %ld errno: %d",
(long) length, vio_errno(net->vio)));
if (i== 0 && unlikely(thd_net_is_killed((THD*) net->thd)))
{
DBUG_PRINT("info", ("thd is killed"));
len= packet_error;
net->error= 0;
net->last_errno= ER_CONNECTION_KILLED;
MYSQL_SERVER_my_error(net->last_errno, MYF(0));
goto end;
}
#if !defined(_WIN32) && defined(MYSQL_SERVER)
/*
We got an error that there was no data on the socket. We now set up
an alarm to not 'read forever', change the socket to the blocking
mode and try again
*/
if ((interrupted || length == 0) && !thr_alarm_in_use(&alarmed))
{
if (!thr_alarm(&alarmed,net->read_timeout,&alarm_buff)) /* Don't wait too long */
{
my_bool old_mode;
while (vio_blocking(net->vio, TRUE, &old_mode) < 0)
{
if (vio_should_retry(net->vio) &&
retry_count++ < net->retry_count)
continue;
DBUG_PRINT("error",
("fcntl returned error %d, aborting thread",
vio_errno(net->vio)));
EXTRA_DEBUG_fprintf(stderr,
"%s: read: fcntl returned error %d, aborting thread\n",
my_progname,vio_errno(net->vio));
len= packet_error;
net->error= 2; /* Close socket */
net->last_errno= ER_NET_FCNTL_ERROR;
MYSQL_SERVER_my_error(ER_NET_FCNTL_ERROR, MYF(0));
goto end;
}
retry_count=0;
continue;
}
}
#endif /* (!defined(_WIN32) && defined(MYSQL_SERVER) */
if (thr_alarm_in_use(&alarmed) && !thr_got_alarm(&alarmed) &&
interrupted)
{ /* Probably in MIT threads */
if (retry_count++ < net->retry_count)
continue;
EXTRA_DEBUG_fprintf(stderr, "%s: read looped with error %d, aborting thread\n",
my_progname,vio_errno(net->vio));
}
#ifndef MYSQL_SERVER
if (length != 0 && vio_errno(net->vio) == SOCKET_EINTR)
{
DBUG_PRINT("warning",("Interrupted read. Retrying..."));
continue;
}
#endif
DBUG_PRINT("error",("Couldn't read packet: remain: %u errno: %d length: %ld",
remain, vio_errno(net->vio), (long) length));
len= packet_error;
net->error= 2; /* Close socket */
net->last_errno= (vio_was_timeout(net->vio) ?
ER_NET_READ_INTERRUPTED :
ER_NET_READ_ERROR);
MYSQL_SERVER_my_error(net->last_errno, MYF(0));
goto end;
}
remain -= (uint32) length;
pos+= length;
update_statistics(thd_increment_bytes_received(net->thd, length));
}
#ifdef DEBUG_DATA_PACKETS
DBUG_DUMP("data_read", net->buff+net->where_b, length);
#endif
if (i == 0)
{ /* First parts is packet length */
size_t helping;
#ifndef DEBUG_DATA_PACKETS
DBUG_DUMP("packet_header", net->buff+net->where_b,
NET_HEADER_SIZE);
#endif
if (net->buff[net->where_b + 3] != (uchar) net->pkt_nr)
{
#ifndef MYSQL_SERVER
if (net->buff[net->where_b + 3] == (uchar) (net->pkt_nr -1))
{
/*
If the server was killed then the server may have missed the
last sent client packet and the packet numbering may be one off.
*/
DBUG_PRINT("warning", ("Found possible out of order packets"));
expect_error_packet= 1;
}
else
#endif
goto packets_out_of_order;
}
net->compress_pkt_nr= ++net->pkt_nr;
#ifdef HAVE_COMPRESS
if (net->compress)
{
/*
The following uint3korr() may read 4 bytes, so make sure we don't
read unallocated or uninitialized memory. The right-hand expression
must match the size of the buffer allocated in net_realloc().
*/
DBUG_ASSERT(net->where_b + NET_HEADER_SIZE + sizeof(uint32) <=
net->max_packet + NET_HEADER_SIZE + COMP_HEADER_SIZE + 1);
/*
If the packet is compressed then complen > 0 and contains the
number of bytes in the uncompressed packet
*/
*complen=uint3korr(&(net->buff[net->where_b + NET_HEADER_SIZE]));
}
#endif
len=uint3korr(net->buff+net->where_b);
if (!len) /* End of big multi-packet */
goto end;
helping = MY_MAX(len,*complen) + net->where_b;
/* The necessary size of net->buff */
if (helping >= net->max_packet)
{
if (net_realloc(net,helping))
{
#if defined(MYSQL_SERVER) && !defined(NO_ALARM)
if (!net->compress &&
!my_net_skip_rest(net, (uint32) len, &alarmed, &alarm_buff))
net->error= 3; /* Successfully skiped packet */
#endif
len= packet_error; /* Return error and close connection */
goto end;
}
}
pos=net->buff + net->where_b;
remain = (uint32) len;
#ifdef MYSQL_SERVER
if (server_extension != NULL)
{
void *user_data= server_extension->m_user_data;
server_extension->m_after_header(net, user_data, count, 0);
server_extension= NULL;
}
#endif
}
#ifndef MYSQL_SERVER
else if (expect_error_packet)
{
/*
This check is safe both for compressed and not compressed protocol
as for the compressed protocol errors are not compressed anymore.
*/
if (net->buff[net->where_b] != (uchar) 255)
{
/* Restore pkt_nr to original value */
net->pkt_nr--;
goto packets_out_of_order;
}
}
#endif
}
end:
if (thr_alarm_in_use(&alarmed))
{
my_bool old_mode;
thr_end_alarm(&alarmed);
if (!net_blocking)
vio_blocking(net->vio, net_blocking, &old_mode);
}
net->reading_or_writing=0;
#ifdef DEBUG_DATA_PACKETS
if (len != packet_error)
DBUG_DUMP("data_read", net->buff+net->where_b, len);
#endif
#ifdef MYSQL_SERVER
if (server_extension != NULL)
{
void *user_data= server_extension->m_user_data;
server_extension->m_after_header(net, user_data, count, 1);
DBUG_ASSERT(len == packet_error || len == 0);
}
#endif
return(len);
packets_out_of_order:
{
switch (handle_proxy_header(net)) {
case ABORT:
/* error happened, message is already written. */
len= packet_error;
goto end;
case RETRY:
goto retry;
case IGNORE:
break;
}
DBUG_PRINT("error",
("Packets out of order (Found: %d, expected %u)",
(int) net->buff[net->where_b + 3],
net->pkt_nr));
EXTRA_DEBUG_ASSERT(0);
/*
We don't make noise server side, since the client is expected
to break the protocol for e.g. --send LOAD DATA .. LOCAL where
the server expects the client to send a file, but the client
may reply with a new command instead.
*/
#ifndef MYSQL_SERVER
EXTRA_DEBUG_fflush(stdout);
EXTRA_DEBUG_fprintf(stderr,"Error: Packets out of order (Found: %d, expected %d)\n",
(int) net->buff[net->where_b + 3],
(uint) (uchar) net->pkt_nr);
EXTRA_DEBUG_fflush(stderr);
#endif
len= packet_error;
MYSQL_SERVER_my_error(ER_NET_PACKETS_OUT_OF_ORDER, MYF(0));
goto end;
}
}
/* Old interface. See my_net_read_packet() for function description */
#undef my_net_read
ulong my_net_read(NET *net)
{
return my_net_read_packet(net, 0);
}
/**
Read a packet from the client/server and return it without the internal
package header.
If the packet is the first packet of a multi-packet packet
(which is indicated by the length of the packet = 0xffffff) then
all sub packets are read and concatenated.
If the packet was compressed, its uncompressed and the length of the
uncompressed packet is returned.
read_from_server is set when the server is reading a new command
from the client.
@return
The function returns the length of the found packet or packet_error.
net->read_pos points to the read data.
*/
ulong
my_net_read_packet(NET *net, my_bool read_from_server)
{
ulong reallen = 0;
return my_net_read_packet_reallen(net, read_from_server, &reallen);
}
ulong
my_net_read_packet_reallen(NET *net, my_bool read_from_server, ulong* reallen)
{
size_t len, complen;
MYSQL_NET_READ_START();
*reallen = 0;
#ifdef HAVE_COMPRESS
if (!net->compress)
{
#endif
len = my_real_read(net,&complen, read_from_server);
if (len == MAX_PACKET_LENGTH)
{
/* First packet of a multi-packet. Concatenate the packets */
ulong save_pos = net->where_b;
size_t total_length= 0;
do
{
net->where_b += (ulong)len;
total_length += len;
len = my_real_read(net,&complen, 0);
} while (len == MAX_PACKET_LENGTH);
if (likely(len != packet_error))
len+= total_length;
net->where_b = save_pos;
}
net->read_pos = net->buff + net->where_b;
if (likely(len != packet_error))
{
net->read_pos[len]=0; /* Safeguard for mysql_use_result */
*reallen = (ulong)len;
}
MYSQL_NET_READ_DONE(0, len);
return (ulong)len;
#ifdef HAVE_COMPRESS
}
else
{
/* We are using the compressed protocol */
ulong buf_length;
ulong start_of_packet;
ulong first_packet_offset;
uint read_length, multi_byte_packet=0;
if (net->remain_in_buf)
{
buf_length= net->buf_length; /* Data left in old packet */
first_packet_offset= start_of_packet= (net->buf_length -
net->remain_in_buf);
/* Restore the character that was overwritten by the end 0 */
net->buff[start_of_packet]= net->save_char;
}
else
{
/* reuse buffer, as there is nothing in it that we need */
buf_length= start_of_packet= first_packet_offset= 0;
}
for (;;)
{
ulong packet_len;
if (buf_length - start_of_packet >= NET_HEADER_SIZE)
{
read_length = uint3korr(net->buff+start_of_packet);
if (!read_length)
{
/* End of multi-byte packet */
start_of_packet += NET_HEADER_SIZE;
break;
}
if (read_length + NET_HEADER_SIZE <= buf_length - start_of_packet)
{
if (multi_byte_packet)
{
/* Remove packet header for second packet */
memmove(net->buff + first_packet_offset + start_of_packet,
net->buff + first_packet_offset + start_of_packet +
NET_HEADER_SIZE,
buf_length - start_of_packet);
start_of_packet += read_length;
buf_length -= NET_HEADER_SIZE;
}
else
start_of_packet+= read_length + NET_HEADER_SIZE;
if (read_length != MAX_PACKET_LENGTH) /* last package */
{
multi_byte_packet= 0; /* No last zero len packet */
break;
}
multi_byte_packet= NET_HEADER_SIZE;
/* Move data down to read next data packet after current one */
if (first_packet_offset)
{
memmove(net->buff,net->buff+first_packet_offset,
buf_length-first_packet_offset);
buf_length-=first_packet_offset;
start_of_packet -= first_packet_offset;
first_packet_offset=0;
}
continue;
}
}
/* Move data down to read next data packet after current one */
if (first_packet_offset)
{
memmove(net->buff,net->buff+first_packet_offset,
buf_length-first_packet_offset);
buf_length-=first_packet_offset;
start_of_packet -= first_packet_offset;
first_packet_offset=0;
}
net->where_b=buf_length;
if ((packet_len = my_real_read(net,&complen, read_from_server))
== packet_error)
{
MYSQL_NET_READ_DONE(1, 0);
return packet_error;
}
read_from_server= 0;
if (my_uncompress(net->buff + net->where_b, packet_len,
&complen))
{
net->error= 2; /* caller will close socket */
net->last_errno= ER_NET_UNCOMPRESS_ERROR;
MYSQL_SERVER_my_error(ER_NET_UNCOMPRESS_ERROR, MYF(0));
MYSQL_NET_READ_DONE(1, 0);
return packet_error;
}
buf_length+= (ulong)complen;
*reallen += packet_len;
}
net->read_pos= net->buff+ first_packet_offset + NET_HEADER_SIZE;
net->buf_length= buf_length;
net->remain_in_buf= (ulong) (buf_length - start_of_packet);
len = ((ulong) (start_of_packet - first_packet_offset) - NET_HEADER_SIZE -
multi_byte_packet);
net->save_char= net->read_pos[len]; /* Must be saved */
net->read_pos[len]=0; /* Safeguard for mysql_use_result */
}
#endif /* HAVE_COMPRESS */
MYSQL_NET_READ_DONE(0, len);
return (ulong)len;
}
void my_net_set_read_timeout(NET *net, uint timeout)
{
DBUG_ENTER("my_net_set_read_timeout");
DBUG_PRINT("enter", ("timeout: %d", timeout));
if (net->read_timeout != timeout)
{
net->read_timeout= timeout;
if (net->vio)
vio_timeout(net->vio, 0, timeout);
}
DBUG_VOID_RETURN;
}
void my_net_set_write_timeout(NET *net, uint timeout)
{
DBUG_ENTER("my_net_set_write_timeout");
DBUG_PRINT("enter", ("timeout: %d", timeout));
if (net->write_timeout != timeout)
{
net->write_timeout= timeout;
if (net->vio)
vio_timeout(net->vio, 1, timeout);
}
DBUG_VOID_RETURN;
}
|
MariaDB/server
|
sql/net_serv.cc
|
C++
|
gpl-2.0
| 40,989
|
<?php
namespace UsingTraits;
/**
* A controller.
*/
class ProductController
{
use DeleteEntity;
/**
* @OA\Get(
* tags={"Products"},
* path="/products/{product_id}",
* @OA\Parameter(
* description="ID of product to return",
* in="path",
* name="product_id",
* required=true,
* @OA\Schema(
* type="string"
* )
* ),
* @OA\Response(
* response="default",
* description="successful operation"
* )
* )
*/
public function getProduct($id)
{
}
}
|
egbot/Symbiota
|
api/vendor/zircote/swagger-php/Examples/using-traits/ProductController.php
|
PHP
|
gpl-2.0
| 606
|
#!/bin/bash -x
echo "[Toromino's Scripts] TCleaner will clean your Downloads folder!"
mkdir $HOME/Downloads/TCleaner/
mkdir $HOME/Downloads/TCleaner/Music/
mkdir $HOME/Downloads/TCleaner/Pictures/
mkdir $HOME/Downloads/TCleaner/Compressed/
mkdir $HOME/Downloads/TCleaner/Packages/
mkdir $HOME/Downloads/TCleaner/Shell-Scripts/
mkdir $HOME/Downloads/TCleaner/Windows-Wine/
mkdir $HOME/Downloads/TCleaner/Videos/
mkdir $HOME/Downloads/TCleaner/Other/
mv $HOME/Downloads/*.mp3 $HOME/Downloads/TCleaner/Music/
mv $HOME/Downloads/*.ogg $HOME/Downloads/TCleaner/Music/
mv $HOME/Downloads/*.wav $HOME/Downloads/TCleaner/Music/
mv $HOME/Downloads/*.jpg $HOME/Downloads/TCleaner/Pictures/
mv $HOME/Downloads/*.png $HOME/Downloads/TCleaner/Pictures/
mv $HOME/Downloads/*.zip $HOME/Downloads/TCleaner/Compressed/
mv $HOME/Downloads/*.tar $HOME/Downloads/TCleaner/Compressed/
mv $HOME/Downloads/*.tar.gz $HOME/Downloads/TCleaner/Compressed/
mv $HOME/Downloads/*.run $HOME/Downloads/TCleaner/Shell-Scripts/
mv $HOME/Downloads/*.sh $HOME/Downloads/TCleaner/Shell-Scripts/
mv $HOME/Downloads/*.deb $HOME/Downloads/TCleaner/Packages/
mv $HOME/Downloads/*.rpm $HOME/Downloads/TCleaner/Packages/
mv $HOME/Downloads/*.mp4 $HOME/Downloads/TCleaner/Videos/
mv $HOME/Downloads/*.avi $HOME/Downloads/TCleaner/Videos/
mv $HOME/Downloads/*.exe $HOME/Downloads/TCleaner/Windows-Wine/
mv $HOME/Downloads/*.msi $HOME/Downloads/TCleaner/Windows-Wine/
mv $HOME/Downloads/*.bat $HOME/Downloads/TCleaner/Windows-Wine/
mv $HOME/Downloads/* $HOME/Downloads/TCleaner/Other/
|
Toromino/TCleaner
|
TCleaner.sh
|
Shell
|
gpl-2.0
| 1,547
|
<?php
/**
* @group scripts
*/
class Tests_Scripts extends EDD_UnitTestCase {
/**
* Test if all the file hooks are working.
*
* @since 2.3.6
*/
public function test_file_hooks() {
$this->assertNotFalse( has_action( 'wp_enqueue_scripts', 'edd_load_scripts' ) );
$this->assertNotFalse( has_action( 'wp_enqueue_scripts', 'edd_register_styles' ) );
$this->assertNotFalse( has_action( 'admin_enqueue_scripts', 'edd_load_admin_scripts' ) );
$this->assertNotFalse( has_action( 'admin_head', 'edd_admin_downloads_icon' ) );
}
/**
* Test that all the scripts are loaded at the checkout page.
*
* @since 2.3.6
*/
public function test_load_scripts_checkout() {
global $edd_options;
// Prepare test
$this->go_to( get_permalink( $edd_options['purchase_page'] ) );
edd_load_scripts();
$this->assertTrue( wp_script_is( 'creditCardValidator', 'enqueued' ) );
$this->assertTrue( wp_script_is( 'edd-checkout-global', 'enqueued' ) );
$this->assertTrue( wp_script_is( 'edd-ajax', 'enqueued' ) );
$this->go_to( '/' );
}
/**
* Test that the edd_register_styles() function will bail when the 'disable_styles'
* option is set to true.
*
* @since 2.3.6
*/
public function test_register_styles_bail_option() {
// Prepare test
$origin_disable_styles = edd_get_option( 'disable_styles', false );
edd_update_option( 'disable_styles', true );
// Assert
$this->assertNull( edd_register_styles() );
// Reset to origin
edd_update_option( 'disable_styles', $origin_disable_styles );
}
/**
* Test that the edd_register_styles() function will enqueue the styles.
*
* @since 2.3.6
*/
public function test_register_styles() {
edd_update_option( 'disable_styles', false );
edd_register_styles();
$this->assertTrue( wp_style_is( 'edd-styles', 'enqueued' ) );
}
/**
* Test that the edd_register_styles() function will enqueue the proper styles
* when page is checkout + ssl.
*
* @since 2.3.6
*/
public function test_register_styles_checkout_ssl() {
// Prepare test
$_SERVER['HTTPS'] = 'ON'; // Fake SSL
$this->go_to( get_permalink( edd_get_option( 'purchase_page' ) ) );
edd_update_option( 'disable_styles', false );
edd_register_styles();
$this->go_to( '/' );
unset( $_SERVER['HTTPS'] );
}
/**
* Test that the edd_load_admin_scripts() function will bail when not a EDD admin page.
*
* @since 2.3.6
*/
public function test_load_admin_scripts_bail() {
// Prepare test
global $pagenow;
$origin_pagenow = $pagenow;
$pagenow = 'dashboard';
if ( ! function_exists( 'edd_is_admin_page' ) ) {
include EDD_PLUGIN_DIR . 'includes/admin/admin-pages.php';
}
// Assert
$this->assertNull( edd_load_admin_scripts( 'dashboard' ) );
// Reset to origin
$pagenow = $origin_pagenow;
}
/**
* Test that the edd_load_admin_scripts() function will enqueue the proper styles.
*
* @since 2.3.6
*/
public function test_load_admin_scripts() {
if ( ! function_exists( 'edd_is_admin_page' ) ) {
include EDD_PLUGIN_DIR . 'includes/admin/admin-pages.php';
}
edd_load_admin_scripts( 'settings.php' );
$this->assertTrue( wp_style_is( 'jquery-chosen', 'enqueued' ) );
$this->assertTrue( wp_style_is( 'wp-color-picker', 'enqueued' ) );
$this->assertTrue( wp_style_is( 'jquery-ui-css', 'enqueued' ) );
$this->assertTrue( wp_style_is( 'thickbox', 'enqueued' ) );
$this->assertTrue( wp_style_is( 'edd-admin', 'enqueued' ) );
$this->assertTrue( wp_script_is( 'jquery-chosen', 'enqueued' ) );
$this->assertTrue( wp_script_is( 'edd-admin-scripts', 'enqueued' ) );
// $this->assertTrue( wp_script_is( 'wp-color-picker', 'enqueued' ) );
$this->assertTrue( wp_script_is( 'jquery-ui-datepicker', 'enqueued' ) );
$this->assertTrue( wp_script_is( 'jquery-ui-dialog', 'enqueued' ) );
$this->assertTrue( wp_script_is( 'jquery-flot', 'enqueued' ) );
$this->assertTrue( wp_script_is( 'media-upload', 'enqueued' ) );
$this->assertTrue( wp_script_is( 'thickbox', 'enqueued' ) );
}
}
|
easydigitaldownloads/Easy-Digital-Downloads
|
tests/tests-scripts.php
|
PHP
|
gpl-2.0
| 4,022
|
/*
* Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Assembly of Iron
Author:
SD%Complete: 100%
SDComment:
EndScriptData */
#include "ScriptPCH.h"
#include "ulduar.h"
enum Spells
{
// Any boss
SPELL_SUPERCHARGE = 61920,
SPELL_BERSERK = 47008, // Hard enrage, don't know the correct ID.
// Steelbreaker
SPELL_HIGH_VOLTAGE = 61890,
SPELL_FUSION_PUNCH = 61903,
SPELL_STATIC_DISRUPTION = 44008, //63494
SPELL_OVERWHELMING_POWER = 64637,
SPELL_ELECTRICAL_CHARGE = 61902,
// Runemaster Molgeim
SPELL_SHIELD_OF_RUNES = 62274,
SPELL_RUNE_OF_POWER = 61973,
SPELL_RUNE_OF_POWER_VISUAL = 61974,
SPELL_RUNE_OF_DEATH = 62269,
SPELL_RUNE_OF_SUMMONING = 62273,
SPELL_RUNE_OF_SUMMONING_VISUAL = 62019,
SPELL_RUNE_OF_SUMMONING_SUMMON = 62020,
SPELL_LIGHTNING_BLAST = 62054,
// Stormcaller Brundir
SPELL_CHAIN_LIGHTNING = 61879,
SPELL_OVERLOAD = 61869,
SPELL_LIGHTNING_WHIRL = 61915,
SPELL_LIGHTNING_TENDRILS = 61887,
SPELL_LIGHTNING_TENDRILS_SELF_VISUAL = 61883,
SPELL_STORMSHIELD = 64187
};
enum eEnums
{
EVENT_ENRAGE,
// Steelbreaker
EVENT_FUSION_PUNCH,
EVENT_STATIC_DISRUPTION,
EVENT_OVERWHELMING_POWER,
// Molgeim
EVENT_RUNE_OF_POWER,
EVENT_SHIELD_OF_RUNES,
EVENT_RUNE_OF_DEATH,
EVENT_RUNE_OF_SUMMONING,
EVENT_LIGHTNING_BLAST,
// Brundir
EVENT_CHAIN_LIGHTNING,
EVENT_OVERLOAD,
EVENT_LIGHTNING_WHIRL,
EVENT_LIGHTNING_TENDRILS,
EVENT_FLIGHT,
EVENT_ENDFLIGHT,
EVENT_GROUND,
EVENT_LAND,
EVENT_MOVE_POS
};
enum Actions
{
ACTION_STEELBREAKER,
ACTION_MOLGEIM,
ACTION_BRUNDIR
};
// Achievements
#define ACHIEVEMENT_ON_YOUR_SIDE RAID_MODE(2945, 2946) // TODO
#define ACHIEVEMENT_CANT_WHILE_STUNNED RAID_MODE(2947, 2948) // TODO
#define ACHIEVEMENT_CHOOSE_STEELBREAKER RAID_MODE(2941, 2944)
#define ACHIEVEMENT_CHOOSE_MOLGEIM RAID_MODE(2939, 2942)
#define ACHIEVEMENT_CHOOSE_BRUNDIR RAID_MODE(2940, 2943)
#define EMOTE_OVERLOAD "Stormcaller Brundir begins to Overload!"
enum Yells
{
SAY_STEELBREAKER_AGGRO = -1603020,
SAY_STEELBREAKER_SLAY_1 = -1603021,
SAY_STEELBREAKER_SLAY_2 = -1603022,
SAY_STEELBREAKER_POWER = -1603023,
SAY_STEELBREAKER_DEATH_1 = -1603024,
SAY_STEELBREAKER_DEATH_2 = -1603025,
SAY_STEELBREAKER_BERSERK = -1603026,
SAY_MOLGEIM_AGGRO = -1603030,
SAY_MOLGEIM_SLAY_1 = -1603031,
SAY_MOLGEIM_SLAY_2 = -1603032,
SAY_MOLGEIM_RUNE_DEATH = -1603033,
SAY_MOLGEIM_SUMMON = -1603034,
SAY_MOLGEIM_DEATH_1 = -1603035,
SAY_MOLGEIM_DEATH_2 = -1603036,
SAY_MOLGEIM_BERSERK = -1603037,
SAY_BRUNDIR_AGGRO = -1603040,
SAY_BRUNDIR_SLAY_1 = -1603041,
SAY_BRUNDIR_SLAY_2 = -1603042,
SAY_BRUNDIR_SPECIAL = -1603043,
SAY_BRUNDIR_FLIGHT = -1603044,
SAY_BRUNDIR_DEATH_1 = -1603045,
SAY_BRUNDIR_DEATH_2 = -1603046,
SAY_BRUNDIR_BERSERK = -1603047,
};
bool IsEncounterComplete(InstanceScript* pInstance, Creature* me)
{
if (!pInstance || !me)
return false;
for (uint8 i = 0; i < 3; ++i)
{
uint64 guid = pInstance->GetData64(DATA_STEELBREAKER+i);
if (!guid)
return false;
if (Creature *boss = Unit::GetCreature(*me, guid))
{
if (boss->isAlive())
return false;
}
else
return false;
}
return true;
}
// Avoid killing bosses one to one
void CallBosses(InstanceScript* pInstance, uint32 caller, Unit *who)
{
// Respawn if dead
if (Creature* Steelbreaker = who->GetCreature(*who, pInstance->GetData64(DATA_STEELBREAKER)))
if (Steelbreaker->isDead())
{
Steelbreaker->Respawn(true);
Steelbreaker->GetMotionMaster()->MoveTargetedHome();
}
if (Creature* Brundir = who->GetCreature(*who, pInstance->GetData64(DATA_BRUNDIR)))
if (Brundir->isDead())
{
Brundir->Respawn(true);
Brundir->GetMotionMaster()->MoveTargetedHome();
}
if (Creature* Molgeim = who->GetCreature(*who, pInstance->GetData64(DATA_MOLGEIM)))
if (Molgeim->isDead())
{
Molgeim->Respawn(true);
Molgeim->GetMotionMaster()->MoveTargetedHome();
}
for (uint8 i = 0; i < 3; ++i)
{
if (caller == DATA_STEELBREAKER+i) continue;
uint64 guid = pInstance->GetData64(DATA_STEELBREAKER+i);
if (!guid) return;
if (Creature* m_boss = pInstance->instance->GetCreature(guid))
{
if (m_boss->isAlive())
{
m_boss->AddThreat(who, 100.0f);
m_boss->AI()->AttackStart(who);
}
}
}
}
class boss_steelbreaker : public CreatureScript
{
public:
boss_steelbreaker() : CreatureScript("boss_steelbreaker") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new boss_steelbreakerAI (pCreature);
}
struct boss_steelbreakerAI : public ScriptedAI
{
boss_steelbreakerAI(Creature *c) : ScriptedAI(c)
{
pInstance = c->GetInstanceScript();
me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_GRIP, true);
}
EventMap events;
InstanceScript* pInstance;
uint32 phase;
void Reset()
{
events.Reset();
phase = 0;
me->RemoveAllAuras();
me->ResetLootMode();
if (pInstance)
pInstance->SetBossState(BOSS_ASSEMBLY, NOT_STARTED);
// Respawn
if (Creature* Brundir = me->GetCreature(*me, pInstance->GetData64(DATA_BRUNDIR)))
if (Brundir->isDead())
{
Brundir->Respawn(true);
Brundir->GetMotionMaster()->MoveTargetedHome();
}
if (Creature* Molgeim = me->GetCreature(*me, pInstance->GetData64(DATA_MOLGEIM)))
if (Molgeim->isDead())
{
Molgeim->Respawn(true);
Molgeim->GetMotionMaster()->MoveTargetedHome();
}
}
void EnterCombat(Unit* who)
{
DoScriptText(SAY_STEELBREAKER_AGGRO, me);
DoZoneInCombat();
CallBosses(pInstance, DATA_STEELBREAKER, who);
DoCast(me, SPELL_HIGH_VOLTAGE);
phase = 1;
events.SetPhase(phase);
events.ScheduleEvent(EVENT_ENRAGE, 900000);
events.ScheduleEvent(EVENT_FUSION_PUNCH, 15000);
}
void JustDied(Unit* /*Killer*/)
{
DoScriptText(RAND(SAY_STEELBREAKER_DEATH_1, SAY_STEELBREAKER_DEATH_2), me);
if (IsEncounterComplete(pInstance, me) && pInstance)
{
pInstance->SetBossState(BOSS_ASSEMBLY, DONE);
pInstance->DoCompleteAchievement(ACHIEVEMENT_CHOOSE_STEELBREAKER);
pInstance->DoUpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, 65195);
}
else me->SetLootRecipient(NULL);
if (Creature* Brundir = me->GetCreature(*me, pInstance->GetData64(DATA_BRUNDIR)))
if (Brundir->isAlive())
Brundir->AI()->DoAction(ACTION_BRUNDIR);
if (Creature* Molgeim = me->GetCreature(*me, pInstance->GetData64(DATA_MOLGEIM)))
if (Molgeim->isAlive())
Molgeim->AI()->DoAction(ACTION_MOLGEIM);
}
void KilledUnit(Unit * /*who*/)
{
DoScriptText(RAND(SAY_STEELBREAKER_SLAY_1,SAY_STEELBREAKER_SLAY_2), me);
if (phase == 3)
DoCast(me, SPELL_ELECTRICAL_CHARGE);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch(eventId)
{
case EVENT_ENRAGE:
DoScriptText(SAY_STEELBREAKER_BERSERK, me);
DoCast(SPELL_BERSERK);
break;
case EVENT_FUSION_PUNCH:
if (me->IsWithinMeleeRange(me->getVictim()))
DoCastVictim(SPELL_FUSION_PUNCH);
events.ScheduleEvent(EVENT_FUSION_PUNCH, urand(15000, 20000));
break;
case EVENT_STATIC_DISRUPTION:
if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(pTarget, SPELL_STATIC_DISRUPTION);
events.ScheduleEvent(EVENT_STATIC_DISRUPTION, 20000 + (rand()%20)*1000);
break;
case EVENT_OVERWHELMING_POWER:
DoScriptText(SAY_STEELBREAKER_POWER, me);
DoCastVictim(SPELL_OVERWHELMING_POWER);
events.ScheduleEvent(EVENT_OVERWHELMING_POWER, RAID_MODE(60000, 35000));
break;
}
}
DoMeleeAttackIfReady();
}
void DoAction(const int32 action)
{
switch (action)
{
case ACTION_STEELBREAKER:
me->SetFullHealth();
me->AddAura(SPELL_SUPERCHARGE, me);
++phase;
events.SetPhase(phase);
if (phase >= 2)
events.RescheduleEvent(EVENT_STATIC_DISRUPTION, 30000);
if (phase >= 3)
{
events.RescheduleEvent(EVENT_OVERWHELMING_POWER, urand(2000, 5000));
// Add HardMode Loot
me->AddLootMode(LOOT_MODE_HARD_MODE_2);
}
break;
}
}
};
};
class boss_runemaster_molgeim : public CreatureScript
{
public:
boss_runemaster_molgeim() : CreatureScript("boss_runemaster_molgeim") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new boss_runemaster_molgeimAI (pCreature);
}
struct boss_runemaster_molgeimAI : public ScriptedAI
{
boss_runemaster_molgeimAI(Creature *c) : ScriptedAI(c)
{
pInstance = c->GetInstanceScript();
me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_GRIP, true);
}
InstanceScript* pInstance;
EventMap events;
uint32 phase;
void Reset()
{
if (pInstance)
pInstance->SetBossState(BOSS_ASSEMBLY, NOT_STARTED);
events.Reset();
me->ResetLootMode();
me->RemoveAllAuras();
phase = 0;
// Respawn
if (Creature* Brundir = me->GetCreature(*me, pInstance->GetData64(DATA_BRUNDIR)))
if (Brundir->isDead())
{
Brundir->Respawn(true);
Brundir->GetMotionMaster()->MoveTargetedHome();
}
if (Creature* Steelbreaker = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER)))
if (Steelbreaker->isDead())
{
Steelbreaker->Respawn(true);
Steelbreaker->GetMotionMaster()->MoveTargetedHome();
}
}
void EnterCombat(Unit* who)
{
DoScriptText(SAY_MOLGEIM_AGGRO, me);
DoZoneInCombat();
CallBosses(pInstance, DATA_MOLGEIM, who);
phase = 1;
pInstance->SetBossState(BOSS_ASSEMBLY, IN_PROGRESS);
events.ScheduleEvent(EVENT_ENRAGE, 900000);
events.ScheduleEvent(EVENT_SHIELD_OF_RUNES, 30000);
events.ScheduleEvent(EVENT_RUNE_OF_POWER, 20000);
}
void JustDied(Unit* /*Killer*/)
{
DoScriptText(RAND(SAY_MOLGEIM_DEATH_1, SAY_MOLGEIM_DEATH_2), me);
if (IsEncounterComplete(pInstance, me) && pInstance)
{
pInstance->SetBossState(BOSS_ASSEMBLY, DONE);
pInstance->DoCompleteAchievement(ACHIEVEMENT_CHOOSE_MOLGEIM);
pInstance->DoUpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, 65195);
}
else me->SetLootRecipient(NULL);
if (Creature* Brundir = me->GetCreature(*me, pInstance->GetData64(DATA_BRUNDIR)))
if (Brundir->isAlive())
Brundir->AI()->DoAction(ACTION_BRUNDIR);
if (Creature* Steelbreaker = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER)))
if (Steelbreaker->isAlive())
Steelbreaker->AI()->DoAction(ACTION_STEELBREAKER);
}
void KilledUnit(Unit * /*who*/)
{
DoScriptText(RAND(SAY_MOLGEIM_SLAY_1,SAY_MOLGEIM_SLAY_2), me);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch(eventId)
{
case EVENT_ENRAGE:
DoScriptText(SAY_MOLGEIM_BERSERK, me);
DoCast(SPELL_BERSERK);
break;
case EVENT_RUNE_OF_POWER: // random alive friendly
{
Creature* bosschoosed;
uint32 choice = urand(0,2);
if (!pInstance) break;
bosschoosed = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER+choice));
if (!bosschoosed || !bosschoosed->isAlive())
{
choice = ((choice == 2) ? 0 : choice++);
bosschoosed = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER+choice));
if (!bosschoosed || !bosschoosed->isAlive())
{
choice = ((choice == 2) ? 0 : choice++);
bosschoosed = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER+choice));
}
}
if (!bosschoosed || !bosschoosed->isAlive())
bosschoosed = me->GetCreature(*me, pInstance->GetData64(DATA_MOLGEIM));
DoCast(bosschoosed, SPELL_RUNE_OF_POWER);
events.ScheduleEvent(EVENT_RUNE_OF_POWER, 35000);
break;
}
case EVENT_SHIELD_OF_RUNES:
DoCast(me, SPELL_SHIELD_OF_RUNES);
events.ScheduleEvent(EVENT_SHIELD_OF_RUNES, urand(60000, 80000));
break;
case EVENT_RUNE_OF_DEATH:
DoScriptText(SAY_MOLGEIM_RUNE_DEATH, me);
if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(pTarget, SPELL_RUNE_OF_DEATH);
events.ScheduleEvent(EVENT_RUNE_OF_DEATH, 30000);
break;
case EVENT_RUNE_OF_SUMMONING:
DoScriptText(SAY_MOLGEIM_SUMMON, me);
if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(pTarget, SPELL_RUNE_OF_SUMMONING);
events.ScheduleEvent(EVENT_RUNE_OF_SUMMONING, urand(40000, 50000));
break;
}
}
DoMeleeAttackIfReady();
}
void DoAction(const int32 action)
{
switch (action)
{
case ACTION_MOLGEIM:
me->SetFullHealth();
me->AddAura(SPELL_SUPERCHARGE, me);
++phase;
events.SetPhase(phase);
events.RescheduleEvent(EVENT_SHIELD_OF_RUNES, 30000);
events.RescheduleEvent(EVENT_RUNE_OF_POWER, 20000);
if (phase >= 2)
events.RescheduleEvent(EVENT_RUNE_OF_DEATH, 35000);
if (phase >= 3)
{
events.RescheduleEvent(EVENT_RUNE_OF_SUMMONING, 40000);
me->AddLootMode(LOOT_MODE_HARD_MODE_1);
}
break;
}
}
};
};
class npc_lightning_elemental : public CreatureScript
{
public:
npc_lightning_elemental() : CreatureScript("npc_lightning_elemental") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new npc_lightning_elementalAI (pCreature);
}
struct npc_lightning_elementalAI : public ScriptedAI
{
npc_lightning_elementalAI(Creature *c) : ScriptedAI(c)
{
Charge();
Casted = false;
}
bool Casted;
void Charge()
{
Unit* pTarget = me->SelectNearestTarget();
me->AddThreat(pTarget, 5000000.0f);
AttackStart(pTarget);
}
void UpdateAI(const uint32 /*diff*/)
{
if (!UpdateVictim())
return;
if (me->IsWithinMeleeRange(me->getVictim()) && !Casted)
{
me->CastSpell(me, SPELL_LIGHTNING_BLAST, true);
me->ForcedDespawn(500);
Casted = true;
}
}
};
};
class npc_rune_of_summoning : public CreatureScript
{
public:
npc_rune_of_summoning() : CreatureScript("npc_rune_of_summoning") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new npc_rune_of_summoningAI (pCreature);
}
struct npc_rune_of_summoningAI : public Scripted_NoMovementAI
{
npc_rune_of_summoningAI(Creature *c) : Scripted_NoMovementAI(c)
{
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_PACIFIED);
}
uint32 SummonTimer;
void Reset()
{
SummonTimer = 1500;
me->ForcedDespawn(12500);
DoCast(me, SPELL_RUNE_OF_SUMMONING_VISUAL);
}
void UpdateAI(const uint32 uiDiff)
{
if (SummonTimer <= uiDiff)
{
DoCast(me, SPELL_RUNE_OF_SUMMONING_SUMMON);
SummonTimer = 1500;
}
else SummonTimer -= uiDiff;
}
};
};
class npc_rune_of_power : public CreatureScript
{
public:
npc_rune_of_power() : CreatureScript("npc_rune_of_power") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new npc_rune_of_powerAI (pCreature);
}
struct npc_rune_of_powerAI : public Scripted_NoMovementAI
{
npc_rune_of_powerAI(Creature *c) : Scripted_NoMovementAI(c)
{
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_PACIFIED);
me->setFaction(16);
}
void Reset()
{
DoCast(me, SPELL_RUNE_OF_POWER_VISUAL, true);
me->ForcedDespawn(35000);
}
};
};
class boss_stormcaller_brundir : public CreatureScript
{
public:
boss_stormcaller_brundir() : CreatureScript("boss_stormcaller_brundir") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new boss_stormcaller_brundirAI (pCreature);
}
struct boss_stormcaller_brundirAI : public ScriptedAI
{
boss_stormcaller_brundirAI(Creature *c) : ScriptedAI(c)
{
pInstance = c->GetInstanceScript();
me->SetReactState(REACT_PASSIVE);
me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_GRIP, true);
}
EventMap events;
InstanceScript* pInstance;
uint32 phase;
uint32 Position;
void Reset()
{
if (pInstance)
pInstance->SetBossState(BOSS_ASSEMBLY, NOT_STARTED);
me->RemoveAllAuras();
me->ResetLootMode();
me->RemoveUnitMovementFlag(MOVEMENTFLAG_LEVITATING | MOVEMENTFLAG_WALKING);
events.Reset();
phase = 0;
// Respawn
if (Creature* Molgeim = me->GetCreature(*me, pInstance->GetData64(DATA_MOLGEIM)))
if (Molgeim->isDead())
{
Molgeim->Respawn(true);
Molgeim->GetMotionMaster()->MoveTargetedHome();
}
if (Creature* Steelbreaker = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER)))
if (Steelbreaker->isDead())
{
Steelbreaker->Respawn(true);
Steelbreaker->GetMotionMaster()->MoveTargetedHome();
}
}
void EnterCombat(Unit* who)
{
DoScriptText(SAY_BRUNDIR_AGGRO, me);
DoZoneInCombat();
CallBosses(pInstance, DATA_BRUNDIR, who);
phase = 1;
events.ScheduleEvent(EVENT_MOVE_POS, 1000);
events.ScheduleEvent(EVENT_ENRAGE, 900000);
events.ScheduleEvent(EVENT_CHAIN_LIGHTNING, 2000);
events.ScheduleEvent(EVENT_OVERLOAD, urand(60000, 120000));
}
void JustDied(Unit* /*Killer*/)
{
DoScriptText(RAND(SAY_BRUNDIR_DEATH_1, SAY_BRUNDIR_DEATH_2), me);
if (IsEncounterComplete(pInstance, me) && pInstance)
{
pInstance->SetBossState(BOSS_ASSEMBLY, DONE);
pInstance->DoCompleteAchievement(ACHIEVEMENT_CHOOSE_BRUNDIR);
pInstance->DoUpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, 65195);
if (me->GetPositionZ() > 428)
me->GetMotionMaster()->MoveFall(427.28f);
}
else me->SetLootRecipient(NULL);
if (Creature* Molgeim = me->GetCreature(*me, pInstance->GetData64(DATA_MOLGEIM)))
if (Molgeim->isAlive())
Molgeim->AI()->DoAction(ACTION_MOLGEIM);
if (Creature* Steelbreaker = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER)))
if (Steelbreaker->isAlive())
Steelbreaker->AI()->DoAction(ACTION_STEELBREAKER);
}
void KilledUnit(Unit* /*who*/)
{
DoScriptText(RAND(SAY_BRUNDIR_SLAY_1,SAY_BRUNDIR_SLAY_2), me);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STAT_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch(eventId)
{
case EVENT_MOVE_POS:
MovePos();
events.RescheduleEvent(EVENT_MOVE_POS, 10000);
break;
case EVENT_ENRAGE:
DoScriptText(SAY_BRUNDIR_BERSERK, me);
DoCast(SPELL_BERSERK);
break;
case EVENT_CHAIN_LIGHTNING:
if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(pTarget, SPELL_CHAIN_LIGHTNING);
events.ScheduleEvent(EVENT_CHAIN_LIGHTNING, urand(4000, 6000));
break;
case EVENT_OVERLOAD:
me->MonsterTextEmote(EMOTE_OVERLOAD, 0, true);
DoScriptText(SAY_BRUNDIR_SPECIAL, me);
me->GetMotionMaster()->Initialize();
DoCast(SPELL_OVERLOAD);
events.ScheduleEvent(EVENT_OVERLOAD, urand(60000, 120000));
break;
case EVENT_LIGHTNING_WHIRL:
me->GetMotionMaster()->Initialize();
DoCast(SPELL_LIGHTNING_WHIRL);
events.ScheduleEvent(EVENT_LIGHTNING_WHIRL, urand(15000, 20000));
break;
case EVENT_LIGHTNING_TENDRILS:
DoScriptText(SAY_BRUNDIR_FLIGHT, me);
DoCast(SPELL_LIGHTNING_TENDRILS);
DoCast(SPELL_LIGHTNING_TENDRILS_SELF_VISUAL);
me->AddUnitMovementFlag(MOVEMENTFLAG_LEVITATING);
me->GetMotionMaster()->MovePoint(0, me->GetPositionX(), me->GetPositionY(), 435);
events.DelayEvents(34000);
events.ScheduleEvent(EVENT_FLIGHT, 2500);
events.ScheduleEvent(EVENT_ENDFLIGHT, 28000);
events.ScheduleEvent(EVENT_LIGHTNING_TENDRILS, 90000);
break;
case EVENT_FLIGHT:
if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0))
me->GetMotionMaster()->MovePoint(0, pTarget->GetPositionX(), pTarget->GetPositionY(), 435);
events.ScheduleEvent(EVENT_FLIGHT, 6000);
break;
case EVENT_ENDFLIGHT:
me->GetMotionMaster()->MovePoint(0, 1586.920f, 119.849f, 435);
events.CancelEvent(EVENT_FLIGHT);
events.ScheduleEvent(EVENT_LAND, 4000);
break;
case EVENT_LAND:
me->GetMotionMaster()->MovePoint(0, me->GetPositionX(), me->GetPositionY(), 427.28f);
events.ScheduleEvent(EVENT_GROUND, 1500);
break;
case EVENT_GROUND:
me->RemoveAurasDueToSpell(SPELL_LIGHTNING_TENDRILS);
me->RemoveAurasDueToSpell(SPELL_LIGHTNING_TENDRILS_SELF_VISUAL);
me->RemoveUnitMovementFlag(MOVEMENTFLAG_LEVITATING);
me->SendMovementFlagUpdate();
break;
}
}
}
void DoAction(const int32 action)
{
switch (action)
{
case ACTION_BRUNDIR:
me->SetFullHealth();
me->AddAura(SPELL_SUPERCHARGE, me);
++phase;
events.SetPhase(phase);
events.RescheduleEvent(EVENT_CHAIN_LIGHTNING, urand(6000, 12000));
events.RescheduleEvent(EVENT_OVERLOAD, 40000);
if (phase >= 2)
events.RescheduleEvent(EVENT_LIGHTNING_WHIRL, urand(15000, 20000));
if (phase >= 3)
{
me->AddAura(SPELL_STORMSHIELD, me);
events.RescheduleEvent(EVENT_LIGHTNING_TENDRILS, 60000);
me->AddLootMode(LOOT_MODE_HARD_MODE_1);
}
break;
}
}
void MovePos()
{
switch(Position)
{
case 0:
me->GetMotionMaster()->MovePoint(0, 1587.28f, 97.030f, 427.28f);
break;
case 1:
me->GetMotionMaster()->MovePoint(0, 1587.18f, 121.03f, 427.28f);
break;
case 2:
me->GetMotionMaster()->MovePoint(0, 1587.34f, 142.58f, 427.28f);
break;
case 3:
me->GetMotionMaster()->MovePoint(0, 1587.18f, 121.03f, 427.28f);
break;
}
Position++;
if (Position > 3)
{
Position = 0;
}
}
};
};
void AddSC_boss_assembly_of_iron()
{
new boss_steelbreaker();
new boss_runemaster_molgeim();
new boss_stormcaller_brundir();
new npc_lightning_elemental();
new npc_rune_of_summoning();
new npc_rune_of_power();
}
|
proofrepo/MadboxpcWOW_3.0
|
src/server/scripts/Northrend/Ulduar/ulduar/boss_assembly_of_iron.cpp
|
C++
|
gpl-2.0
| 30,497
|
/**
* @file
* @author Witek902 (witek902@gmail.com)
*/
#include "PCH.hpp"
#include "Event_Input.hpp"
#include "Engine/Common/Reflection/ReflectionClassDefine.hpp"
NFE_DEFINE_POLYMORPHIC_CLASS(NFE::Scene::Event_Input)
NFE_CLASS_PARENT(NFE::Scene::Event)
NFE_END_DEFINE_CLASS()
namespace NFE {
namespace Scene {
Event_Input::Event_Input(const Input::EventData& data)
: mData(data)
{
}
} // namespace Scene
} // namespace NFE
|
nfprojects/nfengine
|
Src/Engine/Core/Scene/Events/Event_Input.cpp
|
C++
|
gpl-2.0
| 441
|
//
// GPActionDeclFloat.cs
//
// Author(s):
// Baptiste Dupy <baptiste.dupy@gmail.com>
//
// Copyright (c) 2014
//
// 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 UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace ActionTool
{
[GPActionNoInput]
[GPActionAlias("Variable/Float/Declaration")]
public class GPActionDeclFloat : GPActionVariable
{
#region Public Members
public float _value;
#endregion
#region GPActionVariable Override
public override object GetValue ()
{
return _value;
}
public override void SetValue(System.Object value)
{
_value = (float) value;
}
#endregion
}
}
|
trfd/Unity-ActionTool
|
Actions/Variables/Decl/GPActionDeclFloat.cs
|
C#
|
gpl-2.0
| 1,729
|
//$(document).ready(function() {
/* Range Slider Function */
(function($) {
$.fn.rkmd_rangeSlider = function() {
var self, slider_width, slider_offset, curnt, sliderContinuous, sliderDiscrete, range, slider;
self = $(this);
slider_width = self.outerWidth();
slider_offset = self.offset().left;
sliderContinuous = $('.slider-continuous');
sliderDiscrete = $('.slider-discrete');
if(self.hasClass('slider-continuous') === true) {
sliderContinuous.each(function(i, v) {
curnt = $(this);
curnt.append(sliderContinuous_tmplt());
range = curnt.find('input[type="range"]');
slider = curnt.find('.slider');
slider_fill = slider.find('.slider-fill');
slider_handle = slider.find('.slider-handle');
var range_val = range.val();
slider_fill.css('width', range_val +'%');
slider_handle.css('left', range_val +'%');
});
}
if(self.hasClass('slider-discrete') === true) {
sliderDiscrete.each(function(i, v) {
curnt = $(this);
curnt.append(sliderDiscrete_tmplt());
range = curnt.find('input[type="range"]');
slider = curnt.find('.slider');
slider_fill = slider.find('.slider-fill');
slider_handle = slider.find('.slider-handle');
slider_label = slider.find('.slider-label');
var range_val = parseInt(range.val());
slider_fill.css('width', range_val +'%');
slider_handle.css('left', range_val +'%');
slider_label.find('span').text(range_val);
});
}
self.on('mousedown', '.slider-handle', function(e) {
if(e.button === 2) {
return false;
}
var parents = $(this).parents('.rkmd-slider');
var slider_width = parents.outerWidth();
var slider_offset = parents.offset().left;
var check_range = parents.find('input[type="range"]').is(':disabled');
if(check_range === true) {
return false;
}
if(parents.hasClass('slider-discrete') === true) {
$(this).addClass('is-active');
}
var handlers = {
mousemove: function(e) {
var slider_new_width = e.pageX - slider_offset;
if(slider_new_width <= slider_width && !(slider_new_width < '0')) {
slider_move(parents, slider_new_width, slider_width);
}
},
mouseup: function(e) {
$(this).off(handlers);
if(parents.hasClass('slider-discrete') === true) {
parents.find('.is-active').removeClass('is-active');
}
}
};
$(document).on(handlers);
});
self.on('mousedown', '.slider', function(e) {
if(e.button === 2) {
return false;
}
var parents = $(this).parents('.rkmd-slider');
var slider_width = parents.outerWidth();
var slider_offset = parents.offset().left;
var check_range = parents.find('input[type="range"]').is(':disabled');
if(check_range === true) {
return false;
}
var slider_new_width = e.pageX - slider_offset;
if(slider_new_width <= slider_width && !(slider_new_width < '0')) {
slider_move(parents, slider_new_width, slider_width);
}
var handlers = {
mouseup: function(e) {
$(this).off(handlers);
}
};
$(document).on(handlers);
});
};
function sliderContinuous_tmplt() {
var tmplt = '<div class="slider">' +
'<div class="slider-fill"></div>' +
'<div class="slider-handle"></div>' +
'</div>';
return tmplt;
}
function sliderDiscrete_tmplt() {
var tmplt = '<div class="slider">' +
'<div class="slider-fill"></div>' +
'<div class="slider-handle"><div class="slider-label"><span>0</span></div></div>' +
'</div>';
return tmplt;
}
function slider_move(parents, newW, sliderW) {
var slider_new_val = parseInt(Math.round(newW / sliderW * 100));
var slider_fill = parents.find('.slider-fill');
var slider_handle = parents.find('.slider-handle');
var range = parents.find('input[type="range"]');
slider_fill.css('width', slider_new_val +'%');
slider_handle.css({
'left': slider_new_val +'%',
'transition': 'none',
'-webkit-transition': 'none',
'-moz-transition': 'none'
});
range.val(slider_new_val);
if(parents.hasClass('slider-discrete') === true) {
parents.find('.slider-handle span').text(slider_new_val);
}
}
}(jQuery));
/* Change Slider Color */
function change_slider_color() {
$('.color-box .show-box').on('click', function() {
$(".color-box").toggleClass("open");
});
$('.colors-list a').on('click', function() {
var curr_color = $('main').data('slider-color');
var color = $(this).data('slider-color');
var new_colot = 'slider-' + color;
$('.rkmd-slider').each(function(i, v) {
var findColor = $(this).hasClass(curr_color);
if(findColor) {
$(this).removeClass(curr_color);
$(this).addClass(new_colot);
}
$('main').data('slider-color', new_colot);
});
});
}
$('.rkmd-slider').rkmd_rangeSlider();
//window.setInterval(function(){
//$('.rkmd-slider').rkmd_rangeSlider();
//change_slider_color();
//console.log("range.js ran");
//}, 5000);
//});
|
johnfrancisgit/Chromaticity
|
js/range.js
|
JavaScript
|
gpl-2.0
| 5,426
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>DiVinE: dve_grammar.hh Source File</title>
<link href="main.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.5.6 -->
<div class="navigation" id="top">
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</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>
<li>
<form action="search.php" method="get">
<table cellspacing="0" cellpadding="0" border="0">
<tr>
<td><label> <u>S</u>earch for </label></td>
<td><input type="text" name="query" value="" size="20" accesskey="s"/></td>
</tr>
</table>
</form>
</li>
</ul>
</div>
<h1>dve_grammar.hh</h1><a href="dve__grammar_8hh.html">Go to the documentation of this file.</a><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001
<a name="l00005"></a>00005 <span class="preprocessor">#ifndef _GRAMMAR_HH_</span>
<a name="l00006"></a>00006 <span class="preprocessor"></span><span class="preprocessor">#define _GRAMMAR_HH_</span>
<a name="l00007"></a>00007 <span class="preprocessor"></span>
<a name="l00008"></a>00008 <span class="preprocessor">#ifndef DOXYGEN_PROCESSING</span>
<a name="l00009"></a>00009 <span class="preprocessor"></span><span class="preprocessor">#include <iostream></span>
<a name="l00010"></a>00010 <span class="preprocessor">#include "<a class="code" href="dve__commonparse_8hh.html">system/dve/syntax_analysis/dve_commonparse.hh</a>"</span>
<a name="l00011"></a>00011 <span class="preprocessor">#include "<a class="code" href="dve__parser_8hh.html">system/dve/syntax_analysis/dve_parser.hh</a>"</span>
<a name="l00012"></a>00012
<a name="l00013"></a>00013 <span class="keyword">namespace </span>divine <span class="comment">//We want Doxygen not to see namespace `dve'</span>
<a name="l00014"></a>00014 {
<a name="l00015"></a>00015 <span class="preprocessor">#endif //DOXYGEN_PROCESSING</span>
<a name="l00016"></a>00016 <span class="preprocessor"></span>
<a name="l00018"></a>00018 <span class="keywordtype">void</span> <a class="code" href="dve__grammar_8hh.html#ff7ee3b416744a8f5ae282acecbb680f" title="Initializes a Bison&#39;s parser of DVE files before parsing.">dve_init_parsing</a>(<a class="code" href="classdve__parser__t.html" title="Class that provides an interface to the parsing of DVE sources.">dve_parser_t</a> * <span class="keyword">const</span>, <a class="code" href="classerror__vector__t.html" title="The main class in error.hh determined for storing.">error_vector_t</a> *, std::istream & mystream);
<a name="l00020"></a>00020 <span class="keywordtype">void</span> <a class="code" href="dve__grammar_8hh.html#9a4ae30473574d0b097f8cf60f21d856" title="Initializes a Bison&#39;s parser of DVE expressions before parsing.">dve_expr_init_parsing</a>(<a class="code" href="classdve__parser__t.html" title="Class that provides an interface to the parsing of DVE sources.">dve_parser_t</a> * <span class="keyword">const</span>, <a class="code" href="classerror__vector__t.html" title="The main class in error.hh determined for storing.">error_vector_t</a> *, std::istream & mystream);
<a name="l00022"></a>00022 <span class="keywordtype">void</span> <a class="code" href="dve__grammar_8hh.html#e79721555b721c2876cf7f23044ed992" title="Initializes a Bison&#39;s parser of DVE transitions before parsing.">dve_trans_init_parsing</a>(<a class="code" href="classdve__parser__t.html" title="Class that provides an interface to the parsing of DVE sources.">dve_parser_t</a> * <span class="keyword">const</span>, <a class="code" href="classerror__vector__t.html" title="The main class in error.hh determined for storing.">error_vector_t</a> *, std::istream & mystream);
<a name="l00024"></a>00024 <span class="keywordtype">void</span> <a class="code" href="dve__grammar_8hh.html#e4ce811a05c2aae82da0eb3d6c2bd7c3" title="Initializes a Bison&#39;s parser of DVE processes before parsing.">dve_proc_init_parsing</a>(<a class="code" href="classdve__parser__t.html" title="Class that provides an interface to the parsing of DVE sources.">dve_parser_t</a> * <span class="keyword">const</span>, <a class="code" href="classerror__vector__t.html" title="The main class in error.hh determined for storing.">error_vector_t</a> *, std::istream & mystream);
<a name="l00025"></a>00025
<a name="l00026"></a>00026 <span class="preprocessor">#ifndef DOXYGEN_PROCESSING</span>
<a name="l00027"></a>00027 <span class="preprocessor"></span>};
<a name="l00028"></a>00028 <span class="preprocessor">#endif //DOXYGEN_PROCESSING</span>
<a name="l00029"></a>00029 <span class="preprocessor"></span>
<a name="l00030"></a>00030 <span class="preprocessor">#endif</span>
</pre></div></div>
<hr size="1"><small><img align="center" src="divine_mini.gif"><b> Reference Manual for Library, 2006 developed in <a href="http://www.fi.muni.cz/paradise/">ParaDiSe</a> laboratory, <a href="http://www.fi.muni.cz/">Faculty of Informatics</a>, <a href="http://www.muni.cz/">Masaryk University</a></b></small>
</body>
</html>
|
mito/Divine-state-generator
|
doc/refs/library/html/dve__grammar_8hh-source.html
|
HTML
|
gpl-2.0
| 5,459
|
/*
* Copyright (C) 2002-2015 XimpleWare, info@ximpleware.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.
*/
/*VTD-XML is protected by US patent 7133857, 7260652, an 7761459*/
package com.ximpleware.extended;
/**
* This class iterates through all text nodes of an element.
* VTDNavHuge has getText() which is inadequate for mixed content style of XML.
* text nodes include character_data and CDATA.
* This version is adapted to support extended VTD (256GB max file size)
*/
public class TextIterHuge {
private int prevLocation; //previous location of text node
protected int depth;
protected int index; // this is index for the element
protected VTDNavHuge vn;
private int lcIndex;
private int lcLower;
private int lcUpper;
/**
* TextIter constructor comment.
*/
public TextIterHuge() {
super();
vn = null;
/*sel_char_data = true;
sel_comment = true;
sel_cdata = true;*/
}
/**
* Get the index vals for the text nodes in document order.
* Creation date: (12/5/03 6:11:50 PM)
* @return int (-1 if no more left)
*/
public int getNext() {
if (vn == null)
throw new IllegalArgumentException(" VTDNav instance can't be null");
int vtdSize = vn.vtdBuffer.size();
switch (depth) {
case -1: return -1;
case 0 :
// scan forward, if none found, jump to level 1 element and scan backward until one is found
// if there isn't a level-one element, jump to the end of vtd buffer and scan backward
int sp = (prevLocation != -1) ? increment(prevLocation): index + 1;
if (vn.l1Buffer.size() != 0) {
int temp1 = vn.l1Buffer.upper32At(0);
int temp2 = vn.l1Buffer.upper32At(vn.l1Buffer.size() - 1);
lcIndex = (lcIndex != -1) ? lcIndex : 0;
while (sp < vtdSize) {
if (sp >= temp1 && sp < temp2) {
int s = vn.l1Buffer.upper32At(lcIndex);
if (sp == s) { // get to the next l1 element then do a rewind
lcIndex++;
sp = vn.l1Buffer.upper32At(lcIndex)-1;
while (vn.getTokenDepth(sp) == 0
&& vn.getTokenType(sp) != VTDNavHuge.TOKEN_STARTING_TAG) { //probe depth in here
sp--;
}
sp++; // point to the first possible node
}
if (isText(sp) == true && vn.getTokenDepth(sp)==0) {
prevLocation = sp;
return sp;
}
sp++;
} else if (sp < temp1) {
if (isText(sp) == true && vn.getTokenDepth(sp)==0) {
prevLocation = sp;
return sp;
}
sp++;
} else {
if (sp == temp2) { // get to the end of the document and do a rewind
sp = vn.vtdBuffer.size() - 1;
while (vn.getTokenDepth(sp) <= 0) {
sp--;
}
sp++;
//continue;
}
if (sp>=vtdSize)
return -1;
else if (isText(sp) == true && vn.getTokenDepth(sp)==0) {
prevLocation = sp;
return sp;
}
else if (vn.getTokenDepth(sp)>1) {
break;
}
sp++;
}
}
//prevLocation = vtdSize-1;
return -1;
// found nothing
} else {
// no child element for root, just scan right forward
while (sp < vtdSize) {
if (isText(sp) == true && vn.getTokenDepth(sp)==0) {
prevLocation = sp;
return sp;
}
sp++;
}
return -1;
}
case 1 :
if (prevLocation != -1) {
sp = increment(prevLocation) ;
} else {
// fetch lclower and lcupper
lcLower = vn.l1Buffer.lower32At(vn.l1index);
if (lcLower != -1) {
lcUpper = vn.l2Buffer.size() - 1;
int size = vn.l1Buffer.size();
for (int i = vn.l1index + 1; i < size ; i++) {
int temp = vn.l1Buffer.lower32At(i);
if (temp != 0xffffffff) {
lcUpper = temp - 1;
break;
}
}
}
sp = index + 1;
} // check for l2lower and l2upper
if (lcLower != -1) { // have at least one child element
int temp1 = vn.l2Buffer.upper32At(lcLower);
int temp2 = vn.l2Buffer.upper32At(lcUpper);
lcIndex = (lcIndex != -1) ? lcIndex : lcLower;
while (sp < vtdSize) {
int s = vn.l2Buffer.upper32At(lcIndex);
if (sp >= temp1 && sp < temp2) {
if (sp == s) {
lcIndex++;
sp = vn.l2Buffer.upper32At(lcIndex) - 1;
while (vn.getTokenDepth(sp) == 1) {
sp--;
}
sp++;
//continue;
}
if (isText(sp) == true && vn.getTokenDepth(sp)==1 ) {
prevLocation = sp;
return sp;
}
sp++;
} else if (sp < temp1) {
if (isText(sp) == true) {
prevLocation = sp;
return sp;
}
sp++;
} else {
//if (sp == temp2) { // last child element
//} else
if (isText(sp) == true && vn.getTokenDepth(sp) == 1){
//System.out.println("depth ->"+vn.getTokenDepth(sp));
prevLocation = sp;
return sp;
} else if ((vn.getTokenType(sp)==VTDNavHuge.TOKEN_STARTING_TAG
&& vn.getTokenDepth(sp) < 2 ) || vn.getTokenDepth(sp)<1) {
break;
}
sp++;
}
}
//prevLocation = vtdSize-1;
return -1;
} else { // no child element
if (sp>=vtdSize) return -1;
int d = vn.getTokenDepth(sp);
int type = vn.getTokenType(sp);
while (sp < vtdSize
&& d >= 1
&& !(d == 1 && type == VTDNavHuge.TOKEN_STARTING_TAG)) {
if (isText(sp) == true) {
prevLocation = sp;
return sp;
}
sp++;
d = vn.getTokenDepth(sp);
type = vn.getTokenType(sp);
}
//prevLocation = vtdSize-1;
return -1;
}
case 2 :
if (prevLocation != -1) {
sp = increment(prevLocation);
} else {
// fetch lclower and lcupper
lcLower = vn.l2Buffer.lower32At(vn.l2index);
if (lcLower != -1) {
lcUpper = vn.l3Buffer.size() - 1;
int size = vn.l2Buffer.size();
for (int i = vn.l2index + 1; i < size ; i++) {
int temp = vn.l2Buffer.lower32At(i);
if (temp != 0xffffffff) {
lcUpper = temp - 1;
break;
}
}
}
sp = index + 1;
} // check for l3lower and l3upper
if (lcLower != -1) { // at least one child element
int temp1 = vn.l3Buffer.intAt(lcLower);
int temp2 = vn.l3Buffer.intAt(lcUpper);
lcIndex = (lcIndex != -1) ? lcIndex : lcLower;
while (sp < vtdSize) {
int s = vn.l3Buffer.intAt(lcIndex);
//int s = vn.l2Buffer.upper32At(lcIndex);
if (sp >= temp1 && sp < temp2) {
if (sp == s) {
lcIndex++;
sp = vn.l3Buffer.intAt(lcIndex) - 1;
while (vn.getTokenDepth(sp) == 2) {
sp--;
}
sp++;
//continue;
}
if (isText(sp) == true && vn.getTokenDepth(sp)==2) {
prevLocation = sp;
return sp;
}
sp++;
} else if (sp < temp1) {
if (isText(sp) == true && vn.getTokenDepth(sp)==2) {
prevLocation = sp;
return sp;
}
sp++;
} else {
//if (sp == temp2) { // last child element
//} else
if ( isText(sp) == true && vn.getTokenDepth(sp) == 2) {
prevLocation = sp;
return sp;
} else if ((vn.getTokenType(sp)==VTDNavHuge.TOKEN_STARTING_TAG
&& vn.getTokenDepth(sp) < 3 ) || vn.getTokenDepth(sp)<2) {
break;
}
sp++;
}
}
//prevLocation = vtdSize-1;
return -1;
} else { // no child elements
if (sp>=vtdSize) return -1;
int d = vn.getTokenDepth(sp);
int type = vn.getTokenType(sp);
while (sp < vtdSize
&& d >= 2
&& !(d == 2 && type == VTDNavHuge.TOKEN_STARTING_TAG)) {
// the last condition indicates the start of the next sibling element
if (isText(sp) == true && vn.getTokenDepth(sp)==2) {
prevLocation = sp;
return sp;
}
sp++;
d = vn.getTokenDepth(sp);
type = vn.getTokenType(sp);
}
//prevLocation = vtdSize-1;
return -1;
}
default :
//int curDepth = vn.context[0];
sp = (prevLocation != -1) ? increment(prevLocation): index + 1;
if (sp>=vtdSize) return -1;
int d = vn.getTokenDepth(sp);
int type = vn.getTokenType(sp);
while (d >= depth
&& !(d == depth && type == VTDNavHuge.TOKEN_STARTING_TAG)) {
if (isText(sp) == true && d == depth) {
prevLocation = sp;
return sp;
}
sp++;
if(sp >= vtdSize)
return -1;
d = vn.getTokenDepth(sp);
type = vn.getTokenType(sp);
}
}
//prevLocation = vtdSize-1;
return -1;
}
/**
* Test whether a give token type is a TEXT.
* Creation date: (12/11/03 3:46:10 PM)
* @return boolean
* @param type int
*/
final private boolean isText(int index) {
int type = vn.getTokenType(index);
return (type == VTDNavHuge.TOKEN_CHARACTER_DATA
//|| type == vn.TOKEN_COMMENT
|| type == VTDNavHuge.TOKEN_CDATA_VAL);
}
/**
* Obtain the current navigation position and element info from VTDNav.
* So one can instantiate it once and use it for many different elements
* Creation date: (12/5/03 6:20:44 PM)
* @param v com.ximpleware.VTDNav
*/
public void touch(VTDNavHuge v) {
if (v == null)
throw new IllegalArgumentException(" VTDNav instance can't be null");
depth = v.context[0];
if (depth == -1)
index = 0;
else
index = (depth != 0) ? v.context[depth] : v.rootIndex;
vn = v;
prevLocation = -1;
lcIndex = -1;
lcUpper = -1;
lcLower = -1;
}
private int increment(int sp){
int type = vn.getTokenType(sp);
int vtdSize = vn.vtdBuffer.size();
int i=sp+1;
while(i<vtdSize &&
depth == vn.getTokenDepth(i) &&
type == vn.getTokenType(i)&&
(vn.getTokenOffset(i-1)+ (int)((vn.vtdBuffer.longAt(i-1) & VTDNavHuge.MASK_TOKEN_FULL_LEN)>>32)
== vn.getTokenOffset(i))
){
i++;
}
return i;
}
}
|
CoolBalance/vtd-xml
|
src/main/java/com/ximpleware/extended/TextIterHuge.java
|
Java
|
gpl-2.0
| 14,440
|
<html lang=fr">
<head>
<meta charset="utf-8" />
</head>
<body>
<button id="refresh-button">Refresh</button>
<table id="list-jobs"></table>
<script>
// Variables Globales
var serveurVtom = "http://192.168.99.100:30080" ; // just an example, here my docker machine IP running my vtom container
var authVtom = "VE9NOlRPTQ==" ; //base64 user:password, here TOM:TOM
var itemsVtom = [ "environment", "application", "job", "date", "host", "queue" ] ;
itemsVtom.forEach(function(item){
eval("window.API_" + item + "_LIST = null ;") ;
});
// Fonctions
function findItemById(source, id){
return source.filter(function( obj ) {
return obj.id == id;
})[ 0 ];
}
function debutAffichage(){
window.API_job_LIST.result.forEach(function(entry){
var application = findItemById(window.API_application_LIST.result, entry.applicationSId) ;
var environment = findItemById(window.API_environment_LIST.result, application.environmentSId) ;
var host = findItemById(window.API_host_LIST.result, entry.host) ;
if(!host){
var host = findItemById(window.API_host_LIST.result, application.host) ;
if(!host){
var host = findItemById(window.API_host_LIST.result, environment.host) ;
}
}
var dateVtom = findItemById(window.API_date_LIST.result, entry.date) ;
if(!dateVtom){
var dateVtom = findItemById(window.API_date_LIST.result, application.date) ;
if(!dateVtom){
var dateVtom = findItemById(window.API_date_LIST.result, environment.date) ;
}
}
var queue = findItemById(window.API_queue_LIST.result, entry.queue) ;
if(!queue){
var queue = findItemById(window.API_queue_LIST.result, application.queue) ;
if(!queue){
var queue = findItemById(window.API_queue_LIST.result, environment.queue) ;
}
}
var tableListJobs = document.querySelector('table#list-jobs') ;
var this_tr = document.createElement("tr");
this_tr.innerHTML = "<td>" + environment.name + "</td>" +
"<td>" + application.name + "</td>" +
"<td>" + entry.name + "</td>" +
"<td>" + dateVtom.name + "</td>" +
"<td>" + queue.name + "</td>" +
"<td>" + host.name + "</td>" +
"<td>" + entry.Script + "</td>" ;
if(entry.Parameters){
this_tr.innerHTML = this_tr.innerHTML + "<td>" ;
entry.Parameters.forEach(function(parameter){
this_tr.innerHTML = this_tr.innerHTML + parameter + "<br>" ;
});
this_tr.innerHTML = this_tr.innerHTML + "</td>" ;
}
tableListJobs.appendChild(this_tr);
}); //eof foreach job list
} // eof debutAffichage
function getItemsVtom(){
if(typeof(Storage) !== "undefined") {
var isAllItemsInStorage = true ;
itemsVtom.forEach(function(item){
if(sessionStorage["API_"+item+"_LIST"]){
eval('window.API_'+item+'_LIST = JSON.parse(sessionStorage.getItem("API_'+item+'_LIST")) ;') ;
}else{
isAllItemsInStorage = false ;
}
});
if(! isAllItemsInStorage){
getItemsVtomAPI() ;
}
}else{
getItemsVtomAPI() ;
}
} // eof getItemsVtom
function removeItemsFromSessionStorage(){
itemsVtom.forEach(function(item){
sessionStorage.removeItem("API_"+item+"_LIST");
});
}
// http://www.html5rocks.com/en/tutorials/cors/
// cross domain
function getItemsVtomAPI(){
itemsVtom.forEach(function(item){
eval('var xhr'+item+' = new XMLHttpRequest();') ;
var strCode = 'xhr'+item+'.onreadystatechange = function(){' +
'var status = xhr'+item+'.status;' +
'if (status == 200) {'+
'if(xhr'+item+'.response != null) {' +
'window.API_'+item+'_LIST = xhr'+item+'.response ;' +
'if(typeof(Storage) !== "undefined") {' +
'sessionStorage.setItem("API_'+item+'_LIST",JSON.stringify(window.API_'+item+'_LIST)) ;' +
'}' +
'}' +
'}' +
'}' ;
eval(strCode);
eval('xhr'+item+".open('GET', serveurVtom + '/api/"+item+"/getAll',true);") ;
eval('xhr'+item+".responseType = 'json';") ;
eval('xhr'+item+".setRequestHeader('Authorization', 'Basic ' + authVtom);");
eval('xhr'+item+'.send();') ;
});
} // eof getItemsVtomAPI
// On récupère les items
getItemsVtom() ;
function _isAllItemsLoaded(){
console.log((new Date()).getTime()); // debug to make sure we pass through this
var isAllItemsLoaded = true ;
itemsVtom.forEach(function(item){
if(eval('window.API_'+item+'_LIST') == null){
isAllItemsLoaded = false ;
}else if(eval('window.API_'+item+'_LIST.rc') == 4){
isAllItemsLoaded = false ;
console.log(eval('window.API_'+item+'_LIST.errmsg')) ;
clearInterval(window.intervalDebutAffichage);
}
});
if( isAllItemsLoaded )
{
console.log("loaded"); // debug to make sure we pass through this
clearInterval(window.intervalDebutAffichage);
debutAffichage();
return true ;
}else{
return false ;
}
}
if(! _isAllItemsLoaded()){ // si les items ne sont pas chargés au démarrage, on lance une boucle interval
// On vérifie qu'on a bien chargé toutes les données, on affiche quand c'est ok
window.intervalDebutAffichage = setInterval(_isAllItemsLoaded,1000);
// quoi qu'il arrive on sort de la boucle au bout de x secondes
setTimeout(function(){
clearInterval(window.intervalDebutAffichage);
}, 60000);
}
// Events
// Refresh data
document.querySelector('#refresh-button').addEventListener('click',function(e){
removeItemsFromSessionStorage();
window.location = window.location ;
}) ;
</script>
</body>
</html>
|
thomas-asnar/thomas-asnar.github.io
|
wp-content/uploads/list_all_jobs.html
|
HTML
|
gpl-2.0
| 5,311
|
<?php
include_once('admin/class-emma-settings.php');
include_once('widget/class-widget.php');
include_once('shortcode/class-shortcode.php');
include_once('class-emma-api.php');
include_once('class-form.php');
/**
* Main Class for the Emma Emarketing Plugin
*
* long desc
* @package Emma_Emarketing
* @author ah so
* @version 1.0
* @abstract
* @copyright 2012
*/
class Emma_Emarketing {
/*
* the constructor
* Fired during plugins_loaded (very very early),
* only actions and filters,
*
*/
function __construct() {
$emma_settings = new Emma_Settings();
// Add shortcode support for widgets
add_filter('widget_text', 'do_shortcode');
}
} // end Class Emma_Emarketing
|
samanthavandapuye/tease
|
wp-content/plugins/emma-emarketing-plugin/class-emma-emarketing.php
|
PHP
|
gpl-2.0
| 737
|
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark 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
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest05161")
public class BenchmarkTest05161 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request );
String param = scr.getTheParameter("foo");
String bar;
// Simple if statement that assigns param to bar on true condition
int i = 196;
if ( (500/42) + i > 200 )
bar = param;
else bar = "This should never happen";
String cmd = org.owasp.benchmark.helpers.Utils.getOSCommandString("echo") + bar;
String[] argsEnv = { "Foo=bar" };
Runtime r = Runtime.getRuntime();
try {
Process p = r.exec(cmd, argsEnv, new java.io.File(System.getProperty("user.dir")));
org.owasp.benchmark.helpers.Utils.printOSCommandResults(p);
} catch (IOException e) {
System.out.println("Problem executing cmdi - TestCase");
throw new ServletException(e);
}
}
}
|
iammyr/Benchmark
|
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest05161.java
|
Java
|
gpl-2.0
| 2,337
|
/***************************************************************************
* Copyright (C) 2006 by Michael Ambrus *
* michael.ambrus@maquet.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 STYPES_GNU_POWERPCSIM_H
#define STYPES_GNU_POWERPCSIM_H
#include "stypes-gnu_powerpc-eabi.h"
#endif
|
mambrus/tinker
|
src/arch/powerpc/stypes-gnu_powerpc-eabisim.h
|
C
|
gpl-2.0
| 1,574
|
package com.numhero.client.mvp.document;
import com.google.gwt.resources.client.ResourcePrototype;
import com.google.gwt.core.client.GWT;
public class com_numhero_client_mvp_document_InvoicePanel_InvoiceUiBinderImpl_GenBundle_en_InlineClientBundleGenerator implements com.numhero.client.mvp.document.InvoicePanel_InvoiceUiBinderImpl_GenBundle {
public ResourcePrototype[] getResources() {
return new ResourcePrototype[] {
};
}
public native ResourcePrototype getResource(String name) /*-{
switch (name) {
}
return null;
}-*/;
}
|
midaboghetich/netnumero
|
gen/com/numhero/client/mvp/document/com_numhero_client_mvp_document_InvoicePanel_InvoiceUiBinderImpl_GenBundle_en_InlineClientBundleGenerator.java
|
Java
|
gpl-2.0
| 561
|
<?php global $user; ?>
<article<?php print $attributes; ?>>
<?php print render($title_prefix); ?>
<?php if (!$page && $title): ?>
<header>
<h2<?php print $title_attributes; ?>><a href="<?php print $node_url ?>" title="<?php print $title ?>"><?php print $title ?></a></h2>
</header>
<?php endif; ?>
<?php print render($title_suffix); ?>
<div<?php print $content_attributes; ?>>
<div class="row">
<div class="col-sm-6">
<div class="panel panel-notitle">
<div class="panel-body">
<?php print render($content['stato_bene']); ?>
<div class="row">
<div class="col-sm-4">
<?php print render($content['field_fotografia']) ?>
</div>
<div class="col-sm-8">
<div class="profile-title">
<h1><?php print $title ; ?></h1>
</div>
<div class="row">
<div class="col-sm-12">
<?php
print render($content['field_tipologia']);
print render($content['field_progetto_collegato']);
print render($content['og_group_ref']);
?>
</div>
</div>
</div>
</div>
</div>
<?php if(count(array_intersect(array('redazione', 'administrator'), array_values($user->roles))) > 0): ?>
<div class="panel-footer">
<h3>Azioni redazione</h3>
<div class="action-links">
<?php print l('Aggiungi patto di collaborazione', 'node/add/patto-di-collaborazione', array('query' => array('field_contenuto_collegato' => $node->nid))); ?>
</div>
</div>
<?php endif; ?>
</div>
<?php if(isset($content['body'])): ?>
<div class="panel">
<div class="panel-heading">
<h2 class="panel-title"><?php print t('Descrizione'); ?></h2>
</div>
<div class="panel-body">
<?php print render($content['body']); ?>
</div>
</div>
<?php endif; ?>
<?php if(isset($content['field_motivazione_bene'])): ?>
<div class="panel">
<div class="panel-heading">
<h2 class="panel-title"><?php print t('Motivazione dell\'individuazione come Bene Comune'); ?></h2>
</div>
<div class="panel-body">
<?php print render($content['field_motivazione_bene']); ?>
</div>
</div>
<?php endif; ?>
</div>
<div class="col-sm-6">
<?php
print render($content['field_geo']);
?>
<?php
$view = views_get_view('patti_di_collaborazione');
$view->set_display('block');
$view->set_arguments(array($node->nid));
$view->pre_execute();
$view->execute();
if (!empty($view->result)) :
?>
<div class="panel">
<div class="panel-heading">
<h2 class="panel-title"><?php print $view->get_title() ?></h2>
</div>
<div class="panel-body">
<?php print $view->preview(); ?>
</div>
</div>
<?php endif; $view->destroy();?>
<?php if(!empty($field_link_a_risorse_online_di_i)): ?>
<div class="panel">
<div class="panel-heading">
<h2 class="panel-title"><?php print t('Link a risorse online di interesse specifico'); ?></h2>
</div>
<div class="panel-body">
<?php print render($content['field_link_a_risorse_online_di_i']); ?>
</div>
</div>
<?php endif; ?>
</div>
</div>
</div>
</article>
|
ComuneBologna/comunita
|
sites/comunita/themes/comunita_theme/templates/node--bene-comune.tpl.php
|
PHP
|
gpl-2.0
| 3,768
|
<?php
/*
Simple class to let themes add dependencies on plugins in ways they might find useful
Example usage:
$test = new Theme_Plugin_Dependency( 'simple-facebook-connect', 'http://ottopress.com/wordpress-plugins/simple-facebook-connect/' );
if ( $test->check_active() )
echo 'SFC is installed and activated!';
else if ( $test->check() )
echo 'SFC is installed, but not activated. <a href="'.$test->activate_link().'">Click here to activate the plugin.</a>';
else if ( $install_link = $test->install_link() )
echo 'SFC is not installed. <a href="'.$install_link.'">Click here to install the plugin.</a>';
else
echo 'SFC is not installed and could not be found in the Plugin Directory. Please install this plugin manually.';
*/
if (!class_exists('Theme_Plugin_Dependency')) {
class Theme_Plugin_Dependency {
// input information from the theme
var $slug;
var $uri;
// installed plugins and uris of them
private $plugins; // holds the list of plugins and their info
private $uris; // holds just the URIs for quick and easy searching
// both slug and PluginURI are required for checking things
function __construct( $slug, $uri ) {
$this->slug = $slug;
$this->uri = $uri;
if ( empty( $this->plugins ) )
$this->plugins = get_plugins();
if ( empty( $this->uris ) )
$this->uris = wp_list_pluck($this->plugins, 'PluginURI');
// echo '<pre>';
// print_r($this->uris);
// echo '</pre>';
}
// return true if installed, false if not
function check() {
return in_array($this->uri, $this->uris);
}
// return true if installed and activated, false if not
function check_active() {
$plugin_file = $this->get_plugin_file();
if ($plugin_file) return is_plugin_active($plugin_file);
return false;
}
// gives a link to activate the plugin
function activate_link() {
$plugin_file = $this->get_plugin_file();
if ($plugin_file) return wp_nonce_url(self_admin_url('plugins.php?action=activate&plugin='.$plugin_file), 'activate-plugin_'.$plugin_file);
return false;
}
// return a nonced installation link for the plugin. checks wordpress.org to make sure it's there first.
function install_link() {
include_once ABSPATH . 'wp-admin/includes/plugin-install.php';
$info = plugins_api('plugin_information', array('slug' => $this->slug ));
if ( is_wp_error( $info ) )
return false; // plugin not available from wordpress.org
return wp_nonce_url(self_admin_url('update.php?action=install-plugin&plugin=' . $this->slug), 'install-plugin_' . $this->slug);
}
// return array key of plugin if installed, false if not, private because this isn't needed for themes, generally
private function get_plugin_file() {
return array_search($this->uri, $this->uris);
}
}
}
/**
+ * options "Add scripts to head" and "add scripts to footer"
+ *
+ * @package X2
+ * @since 1.5
+ */
// add to head function - hooks the stuff to bp_head
function x2_cap_add_to_head() {
global $cap;
echo $cap->add_to_head;
}
add_action('bp_head', 'x2_cap_add_to_head', 20);
// add to footer function - hooks the stuff to wp_footer
function x2_cap_add_to_footer() {
global $cap;
echo $cap->add_to_footer;
}
add_action('wp_footer', 'x2_cap_add_to_footer', 20);
function back_to_top(){
global $cap;
//if($cap->menu_waypoints == true) {
?>
<footer>
<nav>
<ul>
<li><a class="top" href="#" title="Back to top">Top</a></li>
</ul>
</nav>
</footer>
<?php }
//}
function waypoints_js(){
global $cap;
if($cap->menu_waypoints == true) { ?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('.top').addClass('hidden');
jQuery.waypoints.settings.scrollThrottle = 300;
jQuery('#outerrim').waypoint(function(event, direction) {
jQuery('.top').toggleClass('hidden', direction === "up");
}, {
offset: '-100%'
}).find('#access').waypoint(function(event, direction) {
jQuery('#access').toggleClass('sticky', direction === "down");
if(direction == 'up'){
jQuery('#nav-logo').animate({ opacity: 1},0, function() {
jQuery(this).hide('200');
});
jQuery(".wrapcheck").removeClass("inner");
}
if(direction == 'down'){
jQuery('#nav-logo').animate({ opacity: 1},0, function() {
jQuery(this).show('200');
});
jQuery(".wrapcheck").addClass("inner");
}
event.stopPropagation();
});
});
</script>
<?php
} else { ?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('.top').addClass('hidden');
jQuery.waypoints.settings.scrollThrottle = 300;
jQuery('#outerrim').waypoint(function(event, direction) {
jQuery('.top').toggleClass('hidden', direction === "up");
}, {
offset: '-100%'
})
});
</script>
<?php
}
}
// this function adds the needed class "icon-white" if color scheme is dark or black..
function white_icon_class() {
if ( x2_get_color_scheme() == 'dark' || x2_get_color_scheme() == 'black' ) {
echo 'icon-white';
}
}
function add_home_to_nav(){ ?>
<div id="nav-logo">
<ul>
<li id="nav-home"<?php if ( is_home() ) : ?> class="page_item current-menu-item"<?php endif; ?>>
<a href="<?php echo site_url() ?>" title="<?php _e( 'Home', 'x2' ) ?>"><i class="icon-home <?php white_icon_class() ?>"></i></a>
</li>
</ul>
</div>
<?php }
// opens the inner wrap in the top menu - if needed
function open_inner_wrap_in_menu_top() {
global $cap;
if( $cap->header_width == "full-width" || $cap->menu_top_stay_on_top == true )
echo "<div class=\"inner\">";
}
// closes the inner wrap in the top menu - if needed
function close_inner_wrap_in_menu_top() {
global $cap;
if( $cap->header_width == "full-width" || $cap->menu_top_stay_on_top == true )
echo "</div>";
}
// the flying widget!
function out_of_site_widget(){
global $cap;
if($cap->out_of_content_widget == false) { ?>
<script>
var name = "#out_of_site_widget";
var menuYloc = null;
jQuery(document).ready(function(){
menuYloc = parseInt(jQuery(name).css("top").substring(0,jQuery(name).css("top").indexOf("px")))
jQuery(window).scroll(function () {
offset = menuYloc+jQuery(document).scrollTop()+"px";
jQuery(name).animate({top:offset},{duration:1000,queue:false});
});
});
</script>
<?php } ?>
<div id="out_of_site_widget" class=".visible-desktop">
<?php dynamic_sidebar( 'out_of_content' )?>
</div>
<?php }
// body badge function, if the option is set
function body_badge(){
global $cap;
if ( $cap->body_badge_show != "hide" ) {
// add a link around if a url is set
if ( $cap->body_badge_link != "" ) {
?><a class="body_badge_link" href="<?php echo $cap->body_badge_link; ?>"><?php
}
// only the badge body will be added anyway
?><div class="badge_body"><?php
// add the text only if something != "just my image" is set
if ( $cap->body_badge_show != "just my image" ) {
?><div class="badge_text"><?php echo $cap->body_badge_text; ?></div><?php
}
// close the badge body anyway
?></div><?php
// close the link around if a url was set
if ( $cap->body_badge_link != "" ) {
?></a><?php
}
}
}
function get_the_post_thumbnail_src($img)
{
return (preg_match('~\bsrc="([^"]++)"~', $img, $matches)) ? $matches[1] : '';
}
/**
* check if it's a child theme or parent theme and return the correct path
*
* @package x2
* @since 1.0
*/
function x2_require_path($path){
x2::require_path($path);
}
/**
* get the right img for the slideshow shadow
*
* @package x2
* @since 1.0
*/
function x2_slider_shadow() {
global $cap;
if ($cap->slideshow_shadow == "shadow") {
return "slider-shadow.png";
} else {
return "slider-shadow-sharp.png";
}
}
/**
* define new excerpt length
*
* @package x2
* @since 1.0
*/
function x2_excerpt_length() {
global $cap;
$excerpt_length = 30;
if($cap->excerpt_length){
$excerpt_length = $cap->excerpt_length;
}
return $excerpt_length;
}
/**
* change the profile tab order
*
* @package x2
* @since 1.0
*/
add_action( 'bp_init', 'x2_change_profile_tab_order' );
function x2_change_profile_tab_order() {
global $bp, $cap;
if($cap->bp_profiles_nav_order == ''){
$cap->bp_default_navigation = true;
return;
}
$order = $cap->bp_profiles_nav_order;
$order = str_replace(' ','',trim($order));
$order = explode(",", $order);
$i = 1;
$bp->bp_nav = x2_filter_custom_menu($bp->bp_nav, $order);
foreach($order as $item) {
// check this such component actually exists
if(!bp_is_active($item)){
continue;
}
$bp->bp_nav[$item]['position'] = $i;
$i ++;
}
}
/**
* change the groups tab order
*
* @package x2
* @since 1.0
*/
add_action('bp_init', 'x2_change_groups_tab_order');
function x2_change_groups_tab_order() {
global $bp, $cap;
// In BP 1.3, bp_options_nav for groups is keyed by group slug instead of by 'groups', to
// differentiate it from the top-level groups directories and the groups subtab of member
// profiles
$group_slug = isset( $bp->groups->current_group->slug ) ? $bp->groups->current_group->slug : false;
if($cap->bp_groups_nav_order == ''){
$cap->bp_default_navigation = true;
return;
}
$order = $cap->bp_groups_nav_order;
$order = str_replace(' ','',$order);
$order = explode(",", $order);
$i = 1;
$bp->bp_options_nav[$group_slug] = x2_filter_custom_menu($bp->bp_options_nav[$group_slug], $order);
if(!empty($bp->bp_options_nav[$group_slug])){
foreach($order as $item) {
if(!array_key_exists($item, $bp->bp_options_nav[$group_slug])){
continue;
}
$bp->bp_options_nav[$group_slug][$item]['position'] = $i;
$i ++;
}
}
}
/**
* Remove menu items wihich not included to custom list
* @param array $menu default menu
* @param array $custom_items list of items
* @return array new menu items
*/
function x2_filter_custom_menu($menu, $custom_items){
if(is_array($custom_items) && is_array($menu)){
return array_intersect_key($menu, array_flip($custom_items));
}
return $menu;
}
/**
* This function here defines the defaults for the main theme colors - if no other specific color is set ;)
* It's used only one time - in the beginning of style.php.
*
* @package x2
* @since 0.1
*/
function x2_switch_css(){
global $cap;
if(isset( $_GET['show_style']))
$cap->style_css = $_GET['show_style'];
switch ($cap->style_css){
case 'dark':
if( $cap->bg_body_color == '' ) $cap->bg_body_color = '393939';
if( $cap->bg_container_color == '' ) $cap->bg_container_color = '393939';
if( $cap->bg_container_alt_color == '' ) $cap->bg_container_alt_color = '232323';
if( $cap->bg_details_color == '' ) $cap->bg_details_color = '282828';
if( $cap->bg_details_hover_color == '' ) $cap->bg_details_hover_color = '333333';
if( $cap->font_color == '' ) $cap->font_color = 'aaaaaa';
if( $cap->font_alt_color == '' ) $cap->font_alt_color = '777777';
if( $cap->link_color == '' ) $cap->link_color = 'b7c366';
break;
case 'white':
if( $cap->bg_body_color == '' ) $cap->bg_body_color = 'ffffff';
if( $cap->bg_container_color == '' ) $cap->bg_container_color = 'ffffff';
if( $cap->bg_container_alt_color == '' ) $cap->bg_container_alt_color = 'e3e3e3';
if( $cap->bg_details_color == '' ) $cap->bg_details_color = 'f1f1f1';
if( $cap->bg_details_hover_color == '' ) $cap->bg_details_hover_color = 'f9f9f9';
if( $cap->font_color == '' ) $cap->font_color = '777777';
if( $cap->font_alt_color == '' ) $cap->font_alt_color = 'aaaaaa';
if( $cap->link_color == '' ) $cap->link_color = '6ba090';
break;
case 'black':
if( $cap->bg_body_color == '' ) $cap->bg_body_color = '040404';
if( $cap->bg_container_color == '' ) $cap->bg_container_color = '040404';
if( $cap->bg_container_alt_color == '' ) $cap->bg_container_alt_color = '222222';
if( $cap->bg_details_color == '' ) $cap->bg_details_color = '121212';
if( $cap->bg_details_hover_color == '' ) $cap->bg_details_hover_color = '181818';
if( $cap->font_color == '' ) $cap->font_color = '696969';
if( $cap->font_alt_color == '' ) $cap->font_alt_color = '444444';
if( $cap->link_color == '' ) $cap->link_color = '2b9c83';
break;
case 'light':
if( $cap->bg_body_color == '' ) $cap->bg_body_color = 'f9f9f9';
if( $cap->bg_container_color == '' ) $cap->bg_container_color = 'f9f9f9';
if( $cap->bg_container_alt_color == '' ) $cap->bg_container_alt_color = 'dedede';
if( $cap->bg_details_color == '' ) $cap->bg_details_color = 'e7e7e7';
if( $cap->bg_details_hover_color == '' ) $cap->bg_details_hover_color = 'f1f1f1';
if( $cap->font_color == '' ) $cap->font_color = '777777';
if( $cap->font_alt_color == '' ) $cap->font_alt_color = 'aaaaaa';
if( $cap->link_color == '' ) $cap->link_color = '74a4a3';
break;
case 'natural':
if( $cap->bg_body_color == '' ) $cap->bg_body_color = 'e9e6d8';
if( $cap->bg_container_color == '' ) $cap->bg_container_color = 'e9e6d8';
if( $cap->bg_container_alt_color == '' ) $cap->bg_container_alt_color = 'cec7ab';
if( $cap->bg_details_color == '' ) $cap->bg_details_color = 'dcd6bd';
if( $cap->bg_details_hover_color == '' ) $cap->bg_details_hover_color = 'e3dec8';
if( $cap->font_color == '' ) $cap->font_color = '79735d';
if( $cap->font_alt_color == '' ) $cap->font_alt_color = '999177';
if( $cap->link_color == '' ) $cap->link_color = 'c3874a';
break;
default:
if( $cap->bg_body_color == '' ) $cap->bg_body_color = 'f9f9f9';
if( $cap->bg_container_color == '' ) $cap->bg_container_color = 'f9f9f9';
if( $cap->bg_container_alt_color == '' ) $cap->bg_container_alt_color = 'dedede';
if( $cap->bg_details_color == '' ) $cap->bg_details_color = 'e7e7e7';
if( $cap->bg_details_hover_color == '' ) $cap->bg_details_hover_color = 'f1f1f1';
if( $cap->font_color == '' ) $cap->font_color = '777777';
if( $cap->font_alt_color == '' ) $cap->font_alt_color = 'aaaaaa';
if( $cap->link_color == '' ) $cap->link_color = '74a4a3';
break;
}
return TRUE;
}
/**
* find out the right color scheme and create the array of css elements with the hex codes
*
* @package x2
* @since 1.0
*/
function x2_color_scheme(){
echo x2_get_color_scheme();
}
function x2_get_color_scheme(){
global $cap;
if(isset( $_GET['show_style']))
$cap->style_css = $_GET['show_style'];
switch ($cap->style_css){
case 'dark':
$color = 'dark';
break;
case 'light':
$color = 'light';
break;
case 'white':
$color = 'white';
break;
case 'black':
$color = 'black';
break;
case 'natural':
$color = 'natural';
break;
default:
$color = 'white';
break;
}
return $color;
}
function x2_the_loop( $template, $tk_query_id, $show_pagination){
switch ($template) {
case 'default':
get_template_part( 'loop-default' );
break;
case 'bubble':
get_template_part( 'loop-bubbles' );
break;
case 'image_caption':
get_template_part( 'loop-featured-image-caption' );
break;
default:
if(function_exists('tk_loop_designer_the_loop')){
tk_loop_designer_the_loop( $template, $tk_query_id, $show_pagination );
} else {
get_template_part( 'loop-default' );
}
break;
}
}
?>
|
jubjunior/Wordpress
|
wp-content/themes/x2/core/includes/helper-functions.php
|
PHP
|
gpl-2.0
| 16,806
|
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/iTunesStoreUI.framework/iTunesStoreUI
*/
#import <iTunesStoreUI/iTunesStoreUI-Structs.h>
#import <iTunesStoreUI/SUImageModifier.h>
@interface SUFrameAdjustmentImageModifier : SUImageModifier {
BOOL _shouldSizeDownToFit; // 4 = 0x4
unsigned _sizingMask; // 8 = 0x8
}
@property(assign, nonatomic) unsigned sizingMask; // G=0x27d05; S=0x27d15; @synthesize=_sizingMask
@property(assign, nonatomic) BOOL shouldSizeDownToFit; // G=0x27d25; S=0x27d35; @synthesize=_shouldSizeDownToFit
// declared property setter: - (void)setShouldSizeDownToFit:(BOOL)sizeDownToFit; // 0x27d35
// declared property getter: - (BOOL)shouldSizeDownToFit; // 0x27d25
// declared property setter: - (void)setSizingMask:(unsigned)mask; // 0x27d15
// declared property getter: - (unsigned)sizingMask; // 0x27d05
- (BOOL)scalesImage; // 0x27d01
- (CGRect)imageFrameForImage:(id)image currentFrame:(CGRect)frame finalSize:(CGSize)size; // 0x27be9
- (BOOL)isEqual:(id)equal; // 0x27b81
@end
|
kokoabim/iOSOpenDev-Framework-Header-Files
|
iTunesStoreUI.framework/Headers/SUFrameAdjustmentImageModifier.h
|
C
|
gpl-2.0
| 1,065
|
<?php get_header(); ?>
<?php
$options = get_option('sf_dante_options');
$default_show_page_heading = $options['default_show_page_heading'];
$default_page_heading_bg_alt = $options['default_page_heading_bg_alt'];
$default_sidebar_config = $options['default_sidebar_config'];
$default_left_sidebar = $options['default_left_sidebar'];
$default_right_sidebar = $options['default_right_sidebar'];
$pb_active = get_post_meta($post->ID, '_spb_js_status', true);
$show_page_title = get_post_meta($post->ID, 'sf_page_title', true);
$page_title_style = get_post_meta($post->ID, 'sf_page_title_style', true);
$page_title = get_post_meta($post->ID, 'sf_page_title_one', true);
$page_subtitle = get_post_meta($post->ID, 'sf_page_subtitle', true);
$page_title_bg = get_post_meta($post->ID, 'sf_page_title_bg', true);
$fancy_title_image = rwmb_meta('sf_page_title_image', 'type=image&size=full');
$page_title_text_style = get_post_meta($post->ID, 'sf_page_title_text_style', true);
$fancy_title_image_url = "";
if ($show_page_title == "") {
$show_page_title = $default_show_page_heading;
}
if ($page_title_bg == "") {
$page_title_bg = $default_page_heading_bg_alt;
}
if ($page_title == "") {
$page_title = get_the_title();
}
foreach ($fancy_title_image as $detail_image) {
$fancy_title_image_url = $detail_image['url'];
break;
}
if (!$fancy_title_image) {
$fancy_title_image = get_post_thumbnail_id();
$fancy_title_image_url = wp_get_attachment_url( $fancy_title_image, 'full' );
}
$sidebar_config = get_post_meta($post->ID, 'sf_sidebar_config', true);
$left_sidebar = get_post_meta($post->ID, 'sf_left_sidebar', true);
$right_sidebar = get_post_meta($post->ID, 'sf_right_sidebar', true);
if ($sidebar_config == "") {
$sidebar_config = $default_sidebar_config;
}
if ($left_sidebar == "") {
$left_sidebar = $default_left_sidebar;
}
if ($right_sidebar == "") {
$right_sidebar = $default_right_sidebar;
}
sf_set_sidebar_global($sidebar_config);
$page_wrap_class = $post_class_extra = '';
if ($sidebar_config == "left-sidebar") {
$page_wrap_class = 'has-left-sidebar has-one-sidebar row';
$post_class_extra = 'col-sm-8';
} else if ($sidebar_config == "right-sidebar") {
$page_wrap_class = 'has-right-sidebar has-one-sidebar row';
$post_class_extra = 'col-sm-8';
} else if ($sidebar_config == "both-sidebars") {
$page_wrap_class = 'has-both-sidebars row';
$post_class_extra = 'col-sm-9';
} else {
$page_wrap_class = 'has-no-sidebar';
}
$remove_breadcrumbs = get_post_meta($post->ID, 'sf_no_breadcrumbs', true);
$remove_bottom_spacing = get_post_meta($post->ID, 'sf_no_bottom_spacing', true);
$remove_top_spacing = get_post_meta($post->ID, 'sf_no_top_spacing', true);
if ($remove_bottom_spacing) {
$page_wrap_class .= ' no-bottom-spacing';
}
if ($remove_top_spacing) {
$page_wrap_class .= ' no-top-spacing';
}
$options = get_option('sf_dante_options');
$disable_pagecomments = false;
if (isset($options['disable_pagecomments']) && $options['disable_pagecomments'] == 1) {
$disable_pagecomments = true;
}
?>
<?php if ($show_page_title) { ?>
<div class="container">
<div class="row">
<?php if ($page_title_style == "fancy") { ?>
<?php if ($fancy_title_image_url != "") { ?>
<div class="page-heading fancy-heading col-sm-12 clearfix alt-bg <?php echo $page_title_text_style; ?>-style fancy-image" style="background-image: url(<?php echo $fancy_title_image_url; ?>);">
<?php } else { ?>
<div class="page-heading fancy-heading col-sm-12 clearfix alt-bg <?php echo $page_title_bg; ?>">
<?php } ?>
<div class="heading-text">
<h1 class="entry-title"><?php echo $page_title; ?></h1>
<?php if ($page_subtitle) { ?>
<h3><?php echo $page_subtitle; ?></h3>
<?php } ?>
</div>
</div>
<?php } else { ?>
<div class="page-heading col-sm-12 clearfix alt-bg <?php echo $page_title_bg; ?>">
<div class="heading-text">
<h1 class="entry-title"><?php echo $page_title; ?></h1>
</div>
<?php
// BREADCRUMBS
if (!$remove_breadcrumbs) {
echo sf_breadcrumbs();
}
?>
</div>
<?php } ?>
</div>
</div>
<?php } ?>
<?php if ($sidebar_config != "no-sidebars" || $pb_active != "true") { ?>
<div class="container">
<?php } ?>
<div class="inner-page-wrap <?php echo $page_wrap_class; ?> clearfix">
<?php if (have_posts()) : the_post(); ?>
<!-- OPEN page -->
<div <?php post_class('clearfix ' . $post_class_extra); ?> id="<?php the_ID(); ?>">
<?php if ($sidebar_config == "both-sidebars") { ?>
<div class="row">
<div class="page-content col-sm-8">
<?php the_content(); ?>
<div class="link-pages"><?php wp_link_pages(); ?></div>
<?php if ( comments_open() && !$disable_pagecomments ) { ?>
<div id="comment-area">
<?php comments_template('', true); ?>
</div>
<?php } ?>
</div>
<aside class="sidebar left-sidebar col-sm-4">
<?php dynamic_sidebar($left_sidebar); ?>
</aside>
</div>
<?php } else { ?>
<div class="page-content clearfix">
<?php the_content(); ?>
<div class="link-pages"><?php wp_link_pages(); ?></div>
<?php if ( comments_open() && !$disable_pagecomments ) { ?>
<?php if ($sidebar_config == "no-sidebars" && $pb_active == "true") { ?>
<div id="comment-area" class="container">
<?php } else { ?>
<div id="comment-area">
<?php } ?>
<?php comments_template('', true); ?>
</div>
<?php } ?>
</div>
<?php } ?>
<!-- CLOSE page -->
</div>
<?php endif; ?>
<?php if ($sidebar_config == "left-sidebar") { ?>
<aside class="sidebar left-sidebar col-sm-4">
<?php dynamic_sidebar($left_sidebar); ?>
</aside>
<?php } else if ($sidebar_config == "right-sidebar") { ?>
<aside class="sidebar right-sidebar col-sm-4">
<?php dynamic_sidebar($right_sidebar); ?>
</aside>
<?php } else if ($sidebar_config == "both-sidebars") { ?>
<aside class="sidebar right-sidebar col-sm-3">
<?php dynamic_sidebar($right_sidebar); ?>
</aside>
<?php } ?>
</div>
<?php if ($sidebar_config != "no-sidebars" || $pb_active != "true") { ?>
</div>
<?php } ?>
<!--// WordPress Hook //-->
<?php get_footer(); ?>
|
roycocup/enclothed
|
wp-content/themes/dante/page.php
|
PHP
|
gpl-2.0
| 6,214
|
cmd_sound/pci/emu10k1/built-in.o := rm -f sound/pci/emu10k1/built-in.o; ar rcs sound/pci/emu10k1/built-in.o
|
Existed/kernel-2.6.35.14
|
sound/pci/emu10k1/.built-in.o.cmd
|
Batchfile
|
gpl-2.0
| 109
|
<?php
/**
* TOP API: taobao.traderates.search request
*
* @author auto create
* @since 1.0, 2012-03-21 12:35:10
*/
class TraderatesSearchRequest
{
/**
* 商品的数字id
**/
private $numIid;
/**
* 当前页
**/
private $pageNo;
/**
* 每页显示的条数,允许值:5、10、20、40
**/
private $pageSize;
/**
* 商品所属的卖家nick
**/
private $sellerNick;
private $apiParas = array();
public function setNumIid($numIid)
{
$this->numIid = $numIid;
$this->apiParas["num_iid"] = $numIid;
}
public function getNumIid()
{
return $this->numIid;
}
public function setPageNo($pageNo)
{
$this->pageNo = $pageNo;
$this->apiParas["page_no"] = $pageNo;
}
public function getPageNo()
{
return $this->pageNo;
}
public function setPageSize($pageSize)
{
$this->pageSize = $pageSize;
$this->apiParas["page_size"] = $pageSize;
}
public function getPageSize()
{
return $this->pageSize;
}
public function setSellerNick($sellerNick)
{
$this->sellerNick = $sellerNick;
$this->apiParas["seller_nick"] = $sellerNick;
}
public function getSellerNick()
{
return $this->sellerNick;
}
public function getApiMethodName()
{
return "taobao.traderates.search";
}
public function getApiParas()
{
return $this->apiParas;
}
public function check()
{
RequestCheckUtil::checkNotNull($this->numIid,"numIid");
RequestCheckUtil::checkMinValue($this->pageNo,1,"pageNo");
RequestCheckUtil::checkMaxValue($this->pageSize,40,"pageSize");
RequestCheckUtil::checkMinValue($this->pageSize,1,"pageSize");
RequestCheckUtil::checkNotNull($this->sellerNick,"sellerNick");
RequestCheckUtil::checkMaxLength($this->sellerNick,32,"sellerNick");
}
}
|
gxk9933/guoxk-blog
|
html/test_taobaoke/sdk/top/request/TraderatesSearchRequest.php
|
PHP
|
gpl-2.0
| 1,739
|
//
// FrameSpec.cpp
// Messaging
//
// Created by Dave Meehan on 21/04/2014.
// Copyright (c) 2014 Replicated Solutions Limited. All rights reserved.
//
#include <ZingBDD/ZingBDD.h>
#include "Frame.h"
#include <string.h>
namespace Messaging { namespace Specs {
describe(Frame, {
context("default constructor", {
Frame frame;
context("size", {
it("has size of zero", {
expect(frame.size()).should.equal(0);
});
});
});
context("size constructor", {
size_t expectedSize = 64;
Frame frame(expectedSize);
it("has expected size", {
expect(frame.size()).should.equal(expectedSize);
});
});
context("string constructor", {
char expectedData[] = "this is a test";
Frame frame(expectedData);
it("has expected size", {
expect(strlen(frame.data<char>())).should.equal(strlen(expectedData));
});
it("has expected data", {
expect(strcmp(frame.data<char>(), expectedData)).should.equal(0);
});
});
context("transmission", {
Context ctx;
Socket client(ctx, Socket::Type::request);
Socket server(ctx, Socket::Type::reply);
server.bind("inproc://test");
client.connect("inproc://test");
it("can send and receive", {
char expectedData[] = "this is a test";
Frame outbound(expectedData);
outbound.send(client, Frame::block::none, Frame::more::none);
Frame inbound;
inbound.receive(server, Frame::block::none);
expect(strcmp(inbound.data<char>(), expectedData)).should.equal(0);
});
});
});
} }
|
dmeehan1968/Playground
|
Messaging/Tests/FrameSpec.cpp
|
C++
|
gpl-2.0
| 2,391
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace thetaskmanager {
public partial class register {
/// <summary>
/// registerForm control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm registerForm;
/// <summary>
/// lblName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblName;
/// <summary>
/// tbFName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox tbFName;
/// <summary>
/// RequiredFieldValidator1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;
/// <summary>
/// lblLName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblLName;
/// <summary>
/// tbLName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox tbLName;
/// <summary>
/// RequiredFieldValidator5 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator5;
/// <summary>
/// lblUsername control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblUsername;
/// <summary>
/// tbUsername control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox tbUsername;
/// <summary>
/// RequiredFieldValidator2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator2;
/// <summary>
/// lblPassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblPassword;
/// <summary>
/// tbPassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox tbPassword;
/// <summary>
/// RequiredFieldValidator3 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator3;
/// <summary>
/// lblConfirmPassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblConfirmPassword;
/// <summary>
/// tbConfirmPassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox tbConfirmPassword;
/// <summary>
/// RequiredFieldValidator4 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator4;
/// <summary>
/// CompareValidator1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CompareValidator CompareValidator1;
/// <summary>
/// btRegister control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btRegister;
/// <summary>
/// lblRegistrationMessages control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblRegistrationMessages;
}
}
|
thetaskmanager/thetaskmanager
|
register.aspx.designer.cs
|
C#
|
gpl-2.0
| 6,820
|
/*
* This file is part of the coreboot project.
*
* Copyright (C) 2016 Intel Corp.
* (Written by Lance Zhao <lijian.zhao@intel.com> for Intel Corp.)
*
* 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.
*/
#ifndef __SOC_STONEYRIDGE_ACPI_H__
#define __SOC_STONEYRIDGE_ACPI_H__
#include <arch/acpi.h>
#if IS_ENABLED(CONFIG_STONEYRIDGE_LEGACY_FREE)
#define FADT_BOOT_ARCH ACPI_FADT_LEGACY_FREE
#else
#define FADT_BOOT_ARCH (ACPI_FADT_LEGACY_DEVICES | ACPI_FADT_8042)
#endif
#ifndef FADT_PM_PROFILE
#define FADT_PM_PROFILE PM_UNSPECIFIED
#endif
unsigned long southbridge_write_acpi_tables(struct device *device,
unsigned long current, struct acpi_rsdp *rsdp);
void southbridge_inject_dsdt(struct device *device);
const char *soc_acpi_name(const struct device *dev);
#endif /* __SOC_STONEYRIDGE_ACPI_H__ */
|
MattDevo/coreboot
|
src/soc/amd/stoneyridge/include/soc/acpi.h
|
C
|
gpl-2.0
| 1,270
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; CONSOLE_01_INPUT_TERMINAL
; library driver for input terminals
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; Library input console driver that implements the
; CONSOLE_01_INPUT input terminal features.
;
; ;;;;;;;;;;;;;;;;;;;;
; DRIVER CLASS DIAGRAM
; ;;;;;;;;;;;;;;;;;;;;
;
; CONSOLE_01_INPUT_TERMINAL (root, abstract)
;
; The deriving driver must implement one message generated
; by this driver to complete an input terminal.
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MESSAGES CONSUMED FROM STDIO
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * STDIO_MSG_GETC
; * STDIO_MSG_EATC
; * STDIO_MSG_READ
; * STDIO_MSG_SEEK
; * STDIO_MSG_FLSH
; * STDIO_MSG_ICTL
; * STDIO_MSG_CLOS
;
; Others result in enotsup_zc.
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MESSAGES GENERATED FOR DERIVED DRIVERS
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * ITERM_MSG_GETC
;
; Read the keyboard device and return the char read.
;
; enter: ix = & FDSTRUCT.JP
; exit: a = char after character set translation
; carry set on error with hl=0 (err) or -1 (eof)
; can use: af, bc, de, hl
;
; If this message is implemented, the driver is complete.
;
; * ITERM_MSG_INTERRUPT
;
; Indicate whether character should interrupt line editing.
;
; enter: c = ascii code
; exit: carry reset indicates line editing should terminate
; can use: af, bc, de, hl
;
; Default is to return with carry set.
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MESSAGES GENERATED FOR CONSOLE_01_OUTPUT_TERMINAL
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * ITERM_MSG_PUTC
;
; Input terminal is generating a char to print that
; should not be subject to tty emulation.
;
; enter : c = ascii code
; can use: af, bc, de, hl, ix
;
; * ITERM_MSG_PRINT_CURSOR
;
; Input terminal is printing the cursor.
;
; enter : c = cursor ascii code (CHAR_CURSOR_UC or CHAR_CURSOR_LC)
; can use: af, bc, de, hl, ix
;
; * ITERM_MSG_ERASE_CURSOR
;
; Input terminal is backspacing to erase the cursor.
;
; enter : de = char *edit_buffer
; bc = int edit_buffer_len >= 0
; can use: af, bc, de, hl, ix
;
; Note: The cursor char is not stored in the buffer.
;
; * ITERM_MSG_ERASE_CURSOR_PWD
;
; Input terminal is backspacing to erase the cursor in password mode.
;
; enter : e = CHAR_PASSWORD
; bc = int edit_buffer_len >= 0
; can use: af, bc, de, hl, ix
;
; Note: The cursor char is not stored in the buffer.
;
; * ITERM_MSG_BS
;
; Backspace: erase the last char of the edit buffer.
;
; enter : de = char *edit_buffer
; bc = int edit_buffer_len > 0
; can use: af, bc, de, hl, ix
;
; * ITERM_MSG_BS_PWD
;
; Backspace: erase the last char. The input terminal
; is in password mode so all characters are printed
; to screen as CHAR_PASSWORD.
;
; enter : e = CHAR_PASSWORD
; bc = int edit_buffer_len > 0
; can use: af, bc, de, hl, ix
;
; * ITERM_MSG_READLINE_BEGIN
;
; Notification: The input terminal is starting
; a new edit line.
;
; can use: af, bc, de, hl, ix
;
; * ITERM_MSG_READLINE_END
;
; Notification: The input terminal has finished
; the edit line.
;
; can use: af, bc, de, hl, ix
;
; * ITERM_MSG_BELL
;
; Sound bell to indicate edit buffer limit reached.
;
; can use: af, bc, de, hl, ix
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; IOCTLs UNDERSTOOD BY THIS DRIVER
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * IOCTL_RESET
;
; * IOCTL_ITERM_TIE
; Attach input device to a different output terminal (0 to disconnect)
;
; * IOCTL_ITERM_GET_EDITBUF
; Copies edit buffer details to user program
;
; * IOCTL_ITERM_SET_EDITBUF
; Writes edit buffer details into driver
;
; * IOCTL_ITERM_ECHO
; enable / disable echo mode
;
; * IOCTL_ITERM_PASS
; enable / disable password mode
;
; * IOCTL_ITERM_LINE
; enable / disable line editing mode
;
; * IOCTL_ITERM_COOK
; enable / disable cook mode
;
; * IOCTL_ITERM_CAPS
; set / reset caps lock
;
; * IOCTL_ITERM_CRLF
; enable / disable crlf processing
;
; * IOCTL_ITERM_CURS
; enable / disable cursor in line mode
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;
; BYTES RESERVED IN FDSTRUCT
; ;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; offset (wrt FDSTRUCT.JP) description
;
; 8..13 mutex
; 14..15 FDSTRUCT *oterm (connected output terminal, 0 if none)
; 16 pending_char
; 17..18 read_index (index of next char to read from edit buffer)
; 19..24 b_array (manages edit buffer)
SECTION code_driver
SECTION code_driver_terminal_input
PUBLIC console_01_input_terminal
EXTERN STDIO_MSG_GETC, STDIO_MSG_EATC, STDIO_MSG_READ
EXTERN STDIO_MSG_SEEK, STDIO_MSG_FLSH, STDIO_MSG_ICTL
EXTERN STDIO_MSG_CLOS, ITERM_MSG_INTERRUPT
EXTERN console_01_input_stdio_msg_getc, console_01_input_stdio_msg_eatc
EXTERN console_01_input_stdio_msg_read, console_01_input_stdio_msg_seek
EXTERN console_01_input_stdio_msg_flsh, console_01_input_stdio_msg_ictl
EXTERN error_zc, error_znc, error_enotsup_zc
console_01_input_terminal:
cp STDIO_MSG_GETC
jp z, console_01_input_stdio_msg_getc
cp ITERM_MSG_INTERRUPT
jp z, error_zc ; line editing is not interrupted
cp STDIO_MSG_EATC
jp z, console_01_input_stdio_msg_eatc
cp STDIO_MSG_READ
jp z, console_01_input_stdio_msg_read
cp STDIO_MSG_SEEK
jp z, console_01_input_stdio_msg_seek
cp STDIO_MSG_FLSH
jp z, console_01_input_stdio_msg_flsh
cp STDIO_MSG_ICTL
jp z, console_01_input_stdio_msg_ictl
cp STDIO_MSG_CLOS
jp z, error_znc ; do nothing and report no error
jp error_enotsup_zc ; hl = 0 puts FILE stream in error state
|
bitfixer/bitfixer
|
dg/z88dk/libsrc/_DEVELOPMENT/drivers/terminal/console_01/input/console_01_input_terminal.asm
|
Assembly
|
gpl-2.0
| 5,757
|
--素早いアンコウ
function c88686573.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(88686573,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(c88686573.condition)
e1:SetTarget(c88686573.target)
e1:SetOperation(c88686573.operation)
c:RegisterEffect(e1)
end
function c88686573.condition(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousLocation(LOCATION_HAND+LOCATION_DECK)
end
function c88686573.filter(c,e,tp)
return c:IsSetCard(0x78) and not c:IsCode(88686573) and c:IsLevelBelow(3) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c88686573.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c88686573.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c88686573.operation(e,tp,eg,ep,ev,re,r,rp)
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if ft<=0 then return end
if ft>2 then ft=2 end
if Duel.IsPlayerAffectedByEffect(tp,59822133) then ft=1 end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c88686573.filter,tp,LOCATION_DECK,0,1,ft,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
|
Fluorohydride/ygopro-scripts
|
c88686573.lua
|
Lua
|
gpl-2.0
| 1,479
|
<hr>
<footer>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<ul class="list-inline text-center">
<li>
<a href="#">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-twitter fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
<li>
<a href="#">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-facebook fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
<li>
<a href="#">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-github fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
</ul>
<p class="copyright text-muted">Copyright © Your Website 2014</p>
</div>
</div>
</div>
</footer>
|
manishkiozen/WebCms
|
resources/views/blog/includes/footer.blade.php
|
PHP
|
gpl-2.0
| 1,468
|
/*
* Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
*/
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode* root)
{
vector<vector<int> > res;
if (root == NULL)
return res;
queue<TreeNode*> node_queue;
queue<TreeNode*> root_queue;
int level = 0;
node_queue.push(root);
while (!node_queue.empty())
{
res.push_back(vector<int>());
while (!node_queue.empty())
{
TreeNode* node = node_queue.front();
root_queue.push(node);
node_queue.pop();
}
while (!root_queue.empty())
{
TreeNode* node = root_queue.front();
res[level].push_back(node->val);
root_queue.pop();
if (node->left)
node_queue.push(node->left);
if (node->right)
node_queue.push(node->right);
}
if (level % 2 == 1)
reverse(res[level].begin(), res[level].end());
++level;
}
return res;
}
};
|
ts25504/LeetCode
|
src/103.Binary_Tree_Zigzag_Level_Order_Traversal.h
|
C
|
gpl-2.0
| 1,308
|
# These are some tools I am creating to help me build the map for the game. They are a work in progress.
# I am also learning python, so I apologize in advance if I do dumb things.
# Right now this consists of just two classes: locations and coordinate systems.
# As I have it implemented here, a coordinate system is simply a group of locations.
# I'm sure there is more I could do, for instance linking a coordinate system to a location so that
# you could, for example, enter a house (a location on a larger map) and get a coordinate system
# for more detailed movement inside the house. Right now this is very possible to do,
# but it has to be implemented outside of the class.
import array
import os
import sys
class location:
farDesc = "" # For Descriptions of locations from far away
nearDesc = "" # For descriptions of locations from close-up
name = ""
items = [] # I am investigating this, but apparently you can't use the "append" function with items and characters
# when there is an array of locations, i.e. a coordSystem locationArray. Don't know why this is.
characters = []
has_nEntrance = True
has_eEntrance = True
has_sEntrance = True
has_wEntrance = True
has_uEntrance = True
has_dEntrance = True
isCoordSys = False
def __init__(self):
self.farDesc = ""
self.nearDesc = ""
self.name = ""
self.items = []
self.characters = []
self.isCoordSys = False # save time so that we don't have to check for a matching coordSys for every
# single location
class coordSystem:
name = ""
xMax = 0
yMax = 0
zMax = 0
_locationArray = [] # I have it as a "private variable" (as far as they exist in Python) to avoid confusion:
# as the implementation stands, you have to access the array in the order of [z][y][x], but
# most people are used to the opposite ordering. Rather than screw around with naming and
# perhaps add confusion, I want people to only ever access the array by get and set methods.
def getLocation(self, x, y, z):
return self._locationArray[z][y][x]
def __init__(self, name, xMax, yMax, zMax):
self.name = name
self.xMax = xMax
self.yMax = yMax
self.zMax = zMax
self._locationArray = [[[location() for x in range(xMax)] for x in range(yMax)] for x in range(zMax)]
#The above line is weird, but I can't think of a better way to initialize an array of arrays
|
nickdab/pygame
|
maptools.py
|
Python
|
gpl-2.0
| 2,622
|
'''
This file is part of the lenstractor project.
Copyright 2012 David W. Hogg (NYU) and Phil Marshall (Oxford).
Description
-----------
Wrapper class for tractor operation, to enable high level options (ie sampling or optimization).
To-do
-----
- debug, test
'''
import numpy as np
import os,subprocess
import tractor
import lenstractor
import emcee
emcee_defaults = {}
import pylab as plt
# ============================================================================
class LensTractor():
'''
PURPOSE
Optimize or sample a Lens or Nebula model using the Tractor.
COMMENTS
INPUTS
data A list of tractor.images
model A model (including a list of tractor.sources)
by A mode of operation ['optimizing','sampling']
using The required settings
survey The name of the survey being worked on
plot Make plots if desired
OUTPUTS
BUGS
HISTORY
2014-04-17 Started Marshall & Agnello (UCSB)
'''
# ----------------------------------------------------------------------------
def __init__(self,dataset,model,outstem,survey,counter=0,vb=0,noplots=True):
self.name = 'LensTractor'
self.survey = survey
self.settings = {}
# Optimization settings:
# self.settings['Nrounds'] = 5
# self.settings['Nsteps_optimizing_catalog'] = 100
# self.settings['Nsteps_optimizing_PSFs'] = 2
# Sampling settings:
self.settings['Nwalkers_per_dim'] = 8
self.settings['Nsnapshots'] = 3
self.settings['Nsteps_per_snapshot'] = 5000
self.settings['Restart'] = True
self.model = model
self.vb = vb
self.noplots = noplots
self.plot_all = True
self.outstem = outstem.split('.')[0]
self.bestpars = None
self.maxlnp = None
self.minchisq = None
self.psteps = None
self.counter = counter
# self.chug = tractor.Tractor(dataset)
self.chug = lenstractor.Trattore(dataset)
for src in self.model.srcs:
self.chug.addSource(src)
# Freeze the PSFs, wcs and photocal, leaving the sky and sources:
self.chug.thawParam('catalog')
for image in self.chug.getImages():
image.thawParams('sky')
image.freezeParams('photocal')
image.freezeParams('wcs')
image.freezeParams('psf')
# Plot initial state:
if not self.noplots:
self.plot_state('progress-%02d_initial_'%self.counter+self.model.name)
return None
# ----------------------------------------------------------------------------
# Drive the LensTractor. We have both steepest ascent and MCMC capability.
# Try a mixture!
def drive(self,by='cunning_and_guile'):
self.method = by
if self.method == 'sampling':
self.sample()
elif self.method == 'optimizing':
if self.model.flavor == 'Nebula':
# First optimize to get the Nebula model about right, at fixed PSF:
self.settings['Nrounds'] = 2
self.settings['Nsteps_optimizing_catalog'] = 100000
self.settings['Nsteps_optimizing_PSFs'] = 0
self.optimize()
# Now optimize PSF at fixed model:
self.settings['Nrounds'] = 1
self.settings['Nsteps_optimizing_catalog'] = 0
self.settings['Nsteps_optimizing_PSFs'] = 2
self.optimize()
# Refine Nebula model at best PSF:
self.settings['Nrounds'] = 2
self.settings['Nsteps_optimizing_catalog'] = 10000
self.settings['Nsteps_optimizing_PSFs'] = 0
self.optimize()
elif self.model.flavor == 'Lens':
# PSF is already optimized, during Nebula run.
# Just do the lens part:
self.settings['Nrounds'] = 2
self.settings['Nsteps_optimizing_catalog'] = 10000
self.settings['Nsteps_optimizing_PSFs'] = 0
self.optimize()
else: # Apply cunning and guile! Both optimization and sampling.
# First optimize to get the fluxes about right:
self.settings['Nrounds'] = 1
self.settings['Nsteps_optimizing_catalog'] = 100000
self.settings['Nsteps_optimizing_PSFs'] = 0
self.optimize()
# Now optimize PSF at fixed model:
self.settings['Nrounds'] = 1
self.settings['Nsteps_optimizing_catalog'] = 0
self.settings['Nsteps_optimizing_PSFs'] = 2
self.optimize()
self.settings['Nrounds'] = 1
self.settings['Nsteps_optimizing_catalog'] = 10000
self.settings['Nsteps_optimizing_PSFs'] = 0
self.optimize()
# Now draw a few samples to shuffle the positions:
self.settings['Nsnapshots'] = 1
self.settings['Nwalkers_per_dim'] = 4
self.settings['Nsteps_per_snapshot'] = 2500
self.settings['Restart'] = True
self.sample()
# Now optimize to refine model and PSF:
self.settings['Nrounds'] = 1
self.settings['Nsteps_optimizing_catalog'] = 50000
self.settings['Nsteps_optimizing_PSFs'] = 0
self.optimize()
self.settings['Nrounds'] = 1
self.settings['Nsteps_optimizing_catalog'] = 0
self.settings['Nsteps_optimizing_PSFs'] = 2
self.optimize()
self.settings['Nrounds'] = 1
self.settings['Nsteps_optimizing_catalog'] = 10000
self.settings['Nsteps_optimizing_PSFs'] = 0
self.optimize()
self.getBIC()
return None
# ----------------------------------------------------------------------------
# Fit the model to the image data by maximizing the posterior PDF
# ("optimizing") with respect to the parameters.
def optimize(self):
Nrounds = self.settings['Nrounds']
Nsteps_optimizing_catalog = self.settings['Nsteps_optimizing_catalog']
Nsteps_optimizing_PSFs = self.settings['Nsteps_optimizing_PSFs']
if self.vb:
print " "
print "Optimizing model:"
print " - no. of iterations per round to be spent on catalog: ",Nsteps_optimizing_catalog
print " - no. of iterations per round to be spent on PSFs: ",Nsteps_optimizing_PSFs
print " - no. of rounds: ",Nrounds
for round in range(Nrounds):
self.counter += 1
if self.vb: print "Fitting "+self.model.name+": seconds out, round",round
if self.vb:
print "Fitting "+self.model.name+": Catalog parameters to be optimized are:",self.chug.getParamNames()
print "Fitting "+self.model.name+": Initial values are:",self.chug.getParams()
print "Fitting "+self.model.name+": Step sizes:",self.chug.getStepSizes()
# Optimize sources:
for i in range(Nsteps_optimizing_catalog):
dlnp,X,a = self.chug.optimize(damp=3,shared_params=False)
# print "Fitting "+self.model.name+": at step",k,"parameter values are:",self.chug.getParams()
if self.vb:
print "Progress: counter,dlnp = ",self.counter,dlnp
print ""
print "Catalog parameters:",self.chug.getParamNames()
print "Catalog values:",self.chug.getParams()
if dlnp == 0:
print "Converged? Exiting..."
# Although this only leaves *this* loop...
break
if not self.noplots:
self.plot_state('progress-%02d_optimizing_'%self.counter+self.model.name)
if Nsteps_optimizing_PSFs > 0:
# Freeze the sources and calibration, and thaw the psfs:
if self.vb: print "Freezing catalog..."
self.chug.freezeParams('catalog')
for image in self.chug.getImages():
if self.vb: print "Thawing PSF..."
image.thawParams('psf')
if self.vb: print "Freezing photocal, WCS, sky (just to make sure...)"
image.freezeParams('photocal', 'wcs', 'sky')
if self.vb:
print "Fitting PSF: After thawing, zeroth PSF = ",self.chug.getImage(0).psf
print "Fitting PSF: PSF parameters to be optimized are:",self.chug.getParamNames()
print "Fitting PSF: Initial values are:",self.chug.getParams()
print "Fitting PSF: Step sizes:",self.chug.getStepSizes()
# Optimize everything that is not frozen:
for i in range(Nsteps_optimizing_PSFs):
dlnp,X,a = self.chug.optimize(shared_params=False)
if self.vb: print "Fitting PSF: at counter =",self.counter,"parameter values are:",self.chug.getParams()
self.counter += 1
if self.vb: print "Fitting PSF: After optimizing, zeroth PSF = ",self.chug.getImage(0).psf
if not self.noplots: self.plot_state(
'progress-%02d_optimizing_PSF_for_'%self.counter+self.model.name)
# Freeze the psf again, and thaw the sources:
if self.vb: print "Re-thawing catalog..."
self.chug.thawParams('catalog')
for image in self.chug.getImages():
if self.vb: print "Re-freezing PSF..."
image.freezeParams('psf')
if self.vb: print "Re-freezing photocal, WCS, sky (just to make sure...)"
image.freezeParams('photocal', 'wcs', 'sky')
# Save the best parameters!
self.maxlnp = self.chug.getLogProb()
self.bestpars = self.chug.getParams()
if self.vb: print "Optimizer: Best parameters: ",self.maxlnp,self.bestpars
self.minchisq = -2.0*self.chug.getLogLikelihood()
if self.vb: print "Optimizer: chisq at highest lnprob point: ",self.minchisq
return None
# ----------------------------------------------------------------------------
# Fit the model to the image data by drawing samples from the posterior PDF
# that have high probability density: note, this is not really sampling,
# its *sampling to optimize*...
def sample(self):
if self.vb:
print "Sampling model parameters with Emcee:"
# Magic numbers:
Nwalkers_per_dim = self.settings['Nwalkers_per_dim']
Nsnapshots = self.settings['Nsnapshots']
Nsteps_per_snapshot = self.settings['Nsteps_per_snapshot']
Restart = self.settings['Restart']
# Get the thawed parameters:
p0 = np.array(self.chug.getParams())
if self.vb: print 'Tractor parameters:'
for i,parname in enumerate(self.chug.getParamNames()):
print ' ', parname, '=', p0[i]
Ndim = len(p0)
if self.vb: print 'Number of parameter space dimensions: ',Ndim
# Make an emcee sampler that uses our tractor to compute its logprob:
Nw = Nwalkers_per_dim*Ndim # 8*ndim
sampler = emcee.EnsembleSampler(Nw, Ndim, self.chug, threads=4)
# Start the walkers off near the initialisation point -
# We need it to be ~1 pixel in position, and not too much
# flux restriction... But use any psteps we already have!
if self.psteps is None:
if self.model.name=='Lens':
# The following gets us 0.05" in dec:
self.psteps = np.zeros_like(p0) + 0.00001
# This could be optimized, to allow more initial freedom in eg flux.
else:
# Good first guess should be some fraction of the optimization step sizes:
self.psteps = 0.01*np.array(self.chug.getStepSizes())
if self.vb: print "Initial size (in each dimension) of sample ball = ",self.psteps
#pp = emcee.EnsembleSampler.sampleBall(p0, self.psteps, Nw)
pp = emcee.utils.sample_ball(p0, self.psteps, Nw)
rstate = None
lnp = None
# Take a few steps - memory leaks fast! (~10Mb per sec)
for snapshot in range(1,Nsnapshots+1):
self.counter += 1
if self.vb: print 'Emcee: MCMC snapshot:', snapshot
t0 = tractor.Time()
pp,lnp,rstate = sampler.run_mcmc(pp, Nsteps_per_snapshot, lnprob0=lnp, rstate0=rstate)
if self.vb: print 'Emcee: Mean acceptance fraction after', sampler.iterations, 'iterations =',np.mean(sampler.acceptance_fraction)
t_mcmc = (tractor.Time() - t0)
if self.vb: print 'Emcee: Runtime:', t_mcmc
# Find the current best sample, and sample ball:
self.maxlnp = np.max(lnp)
best = np.where(lnp == self.maxlnp)
self.bestpars = np.ravel(pp[best,:])
if self.vb: print "Emcee: Best parameters: ",self.maxlnp,self.bestpars
self.minchisq = -2.0*self.chug.getLogLikelihood()
if self.vb: print "Emcee: chisq at highest lnprob point: ",self.minchisq
if not self.noplots:
self.chug.setParams(self.bestpars)
self.plot_state('progress-%02d_sampling_'%self.counter+self.model.name)
if Restart:
# Make a new sample ball centred on the current best point,
# and with width given by the standard deviations in each
# dimension:
self.chug.setParams(self.bestpars)
p0 = np.array(self.chug.getParams())
self.psteps = np.std(pp,axis=0)
# pp = emcee.EnsembleSampler.sampleBall(p0, self.psteps, Nw)
pp = emcee.utils.sample_ball(p0, self.psteps, Nw)
rstate = None
lnp = None
if self.vb: print 'Emcee: total run time', t_mcmc, 'sec'
return None
# ----------------------------------------------------------------------------
def getBIC(self):
self.K = len(self.bestpars)
self.N = self.chug.getNdata()
self.BIC = self.minchisq + self.K*np.log(1.0*self.N)
return self.BIC
# ----------------------------------------------------------------------------
def write_catalog(self):
# Get parameter names and values:
parnames = self.chug.getParamNames()
values = np.array(np.outer(1,self.bestpars))
# Get image names:
imgnames = []
for image in self.chug.getImages():
imgnames.append(image.name)
# Set catalog file name:
outfile = self.outstem+'_'+self.model.name+'.cat'
# Open up a new file, over-writing any old one:
try: os.remove(outfile)
except OSError: pass
output = open(outfile,'w')
# Write header:
hdr = []
hdr.append('# LensTractor output parameter catalog')
# hdr.append('# ')
# hdr.append('# Date: %s' % datestring)
hdr.append('# ')
hdr.append('# Model: %s' % self.model.name)
hdr.append('# Notes:')
hdr.append('# * First source is always the galaxy, point sources follow')
for ii,imgname in enumerate(imgnames):
hdr.append('# * images.image%d = %s' % (ii,imgname))
hdr.append('# ')
# Last line contains the parameter names:
nameline = "# "
for name in parnames:
nameline += name+" "
hdr.append(nameline)
# Write to file:
for line in hdr:
output.write("%s\n" % line)
# Close file:
output.close()
np.savetxt('junk', values)
cat = subprocess.call("cat junk >> " + outfile, shell=True)
rm = subprocess.call("rm junk", shell=True)
if cat != 0 or rm != 0:
print "Error: write subprocesses failed in some way :-/"
sys.exit()
return outfile
# ----------------------------------------------------------------------------
def set_cookie(self,outstem,result):
outfile = self.outstem+'_result.cookie'
# Open up a new file, over-writing any old one:
try: os.remove(outfile)
except OSError: pass
output = open(outfile,'w')
# Write result to file:
output.write("%s\n" % result)
# Close file:
output.close()
return outfile
# ----------------------------------------------------------------------------
# Plot progress.
def plot_state(self,suffix):
'''
Make all the plots we need to assess the state of the LensTractor.
Mainly, a multi-panel figure of image, synthetic image and chi, for
each image being modelled.
self.chug is a Tractor object, containing a list of images.
'''
if self.plot_all:
# Make one giant plot with all progress panels on it, and
# save it to PNG:
# Plotting setup:
px,py = 4,len(self.chug.images)
figprops = dict(figsize=(5*px,5*py), dpi=128)
adjustprops = dict(\
left=0.05,\
bottom=0.05,\
right=0.95,\
top=0.95,\
wspace=0.1,\
hspace=0.1)
# Start the plot:
fig = plt.figure(**figprops)
fig.subplots_adjust(**adjustprops)
plt.clf()
plt.gray()
counter = 0
# Name the plot file:
pngfile = self.outstem+'_'+suffix+'.png'
else:
# Make one plot per image, and save each to PNG.
# Plotting setup:
px,py = 2,2
figprops = dict(figsize=(5*px,5*py), dpi=128)
adjustprops = dict(\
left=0.05,\
bottom=0.05,\
right=0.95,\
top=0.95,\
wspace=0.1,\
hspace=0.1)
# Loop over images, making plots:
for i,image in enumerate(self.chug.images):
if image.name is None:
imname = suffix+str(i)
else:
imname = image.name
chi = self.chug.getChiImage(i)
if self.survey == 'PS1':
ima, chia, psfa = lenstractor.PS1_imshow_settings(image,chi)
elif self.survey == 'KIDS':
ima, chia, psfa = lenstractor.KIDS_imshow_settings(image,chi)
else:
# Do the same as for PS1
scale = np.sqrt(np.median(1.0/image.invvar[image.invvar > 0.0]))
ima = dict(interpolation='nearest', origin='lower',
vmin=-100.*scale, vmax=3.*scale)
chia = dict(interpolation='nearest', origin='lower',
vmin=-5., vmax=5.)
psfa = dict(interpolation='nearest', origin='lower')
if not self.plot_all:
# Start a new plot:
fig = plt.figure(**figprops)
fig.subplots_adjust(**adjustprops)
plt.clf()
plt.gray()
counter = 0
# 1) Data Image
counter += 1
plt.subplot(py,px,counter)
plt.imshow(-image.data, **ima)
self.tidyup_plot()
plt.title('Observed image')
# Overlay image filter in lower left corner
plt.text(1,1,image.photocal.bandname+'-band')
# Figure out how to get this in bottom right hand corner instead
# 2) Predicted image
counter += 1
plt.subplot(py,px,counter)
model = self.chug.getModelImages()[i]
plt.imshow(-model, **ima)
self.tidyup_plot()
# Overlay cartoon of model:
self.model.plot(image.wcs,image.photocal.bandname)
plt.title('Predicted image')
# Overlay name of model in lower left corner
plt.text(1,1,self.model.name)
# Figure out how to get this in top left hand corner instead
# 3) Normalised residual
counter += 1
plt.subplot(py,px,counter)
plt.imshow(-chi, **chia)
self.tidyup_plot()
if self.survey == 'KIDS':
# It is not clear why the residual image is not in units of
# sigma. Perhaps this causes problems in the modelling.
# This code is not refactored into kids.py since it should
# not be necessary in the first place.
plt.title('Residuals (flexible scale)')
else:
plt.title('Residuals ($\pm 5\sigma$)')
# Overlay quantified goodness of fit, in sigma from acceptable...
# TBI!
# 4) PSF image
counter += 1
plt.subplot(py,px,counter)
psfimage = image.psf.getPointSourcePatch(*model.shape).patch
plt.imshow(-psfimage, **psfa)
self.tidyup_plot()
plt.title('PSF')
if not self.plot_all:
# Save this image's plot:
pngfile = imname+'_'+suffix+'.png'
plt.savefig(pngfile)
if self.vb:
print "Progress snapshot saved to "+pngfile
if self.plot_all:
# Save the giant plot:
plt.savefig(pngfile)
if self.vb:
print "Progress snapshot saved to "+pngfile
return
# ----------------------------------------------------------------------------
# Turn off the axis ticks and labels:
def tidyup_plot(self):
ax = plt.gca()
ax.xaxis.set_ticks([])
ax.yaxis.set_ticks([])
return
# ============================================================================
if __name__ == '__main__':
pass
|
davidwhogg/LensTractor
|
lenstractor/driver.py
|
Python
|
gpl-2.0
| 21,961
|
<?php
/**
* 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; under version 2
* of the License (non-upgradable).
*
* 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) 2015 (original work) Open Assessment Technologies SA;
*
*
*/
namespace oat\tao\model\requiredAction\implementation;
use oat\tao\model\requiredAction\RequiredActionAbstract;
use oat\tao\model\routing\FlowController;
/**
* Class RequiredAction
*
* RequiredAction is action which should be executed by user before performing any activities in the TAO
*
* @package oat\tao\model\requiredAction\implementation
*/
class RequiredActionRedirectUrlPart extends RequiredActionAbstract
{
/**
* Route to be ignored
*
* @var array
*/
protected $excludedRoutes = [
[
'extension' => 'tao',
'module' => 'ClientConfig',
'action' => 'config',
]
];
/**
* Array of url parts
*
* @var array
*/
protected $url;
/**
* RequiredActionRedirectUrlPart constructor.
* @param string $name
* @param array $rules
* @param array $url
*/
public function __construct($name, array $rules, array $url)
{
parent::__construct($name, $rules);
$this->url = $url;
}
/**
* Execute an action
*
* @param array $params
* @return string The callback url
*/
public function execute(array $params = [])
{
$context = \Context::getInstance();
$excludedRoutes = $this->getExcludedRoutes();
$currentRoute = [
'extension' => $context->getExtensionName(),
'module' => $context->getModuleName(),
'action' => $context->getActionName(),
];
if (! in_array($currentRoute, $excludedRoutes)) {
$currentUrl = \common_http_Request::currentRequest()->getUrl();
$transformedUrl = $this->getTransformedUrl($params);
$url = $transformedUrl . (parse_url($transformedUrl, PHP_URL_QUERY) ? '&' : '?') . 'return_url=' . urlencode($currentUrl);
$flowController = new FlowController();
$flowController->redirect($url);
}
}
/**
* @see \oat\oatbox\PhpSerializable::__toPhpCode()
*/
public function __toPhpCode()
{
$class = get_class($this);
$name = $this->name;
$rules = \common_Utils::toHumanReadablePhpString($this->getRules());
$url = \common_Utils::toHumanReadablePhpString($this->url);
return "new $class(
'$name',
$rules,
$url
)";
}
/**
* Get url string from $this->url
*
* @param array $params
* @return string
*/
protected function getTransformedUrl(array $params = [])
{
return call_user_func_array('_url', array_merge($this->url, [$params]));
}
/**
* Some actions should not be redirected (such as retrieving requireJs config)
*
* @return array
*/
protected function getExcludedRoutes()
{
$result = $this->excludedRoutes;
$resolver = new \Resolver($this->getTransformedUrl());
$result[] = [
'extension' => $resolver->getExtensionFromURL(),
'module' => $resolver->getModule(),
'action' => $resolver->getAction(),
];
return $result;
}
}
|
oat-sa/tao-core
|
models/classes/requiredAction/implementation/RequiredActionRedirectUrlPart.php
|
PHP
|
gpl-2.0
| 3,945
|
/**
*/
package components.provider;
import components.Association;
import components.ComponentsPackage;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ViewerNotification;
/**
* This is the item provider adapter for a {@link components.Association} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class AssociationItemProvider
extends ClassifierItemProvider
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AssociationItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addTargetPropertyDescriptor(object);
addSourcePropertyDescriptor(object);
addLowerBoundPropertyDescriptor(object);
addUpperBoundPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Target feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addTargetPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Association_target_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Association_target_feature", "_UI_Association_type"),
ComponentsPackage.Literals.ASSOCIATION__TARGET,
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Source feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addSourcePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Association_source_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Association_source_feature", "_UI_Association_type"),
ComponentsPackage.Literals.ASSOCIATION__SOURCE,
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Lower Bound feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addLowerBoundPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Association_lowerBound_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Association_lowerBound_feature", "_UI_Association_type"),
ComponentsPackage.Literals.ASSOCIATION__LOWER_BOUND,
true,
false,
false,
ItemPropertyDescriptor.INTEGRAL_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Upper Bound feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addUpperBoundPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Association_upperBound_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Association_upperBound_feature", "_UI_Association_type"),
ComponentsPackage.Literals.ASSOCIATION__UPPER_BOUND,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This returns Association.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/Association"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((Association)object).getName();
return label == null || label.length() == 0 ?
getString("_UI_Association_type") :
getString("_UI_Association_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(Association.class)) {
case ComponentsPackage.ASSOCIATION__LOWER_BOUND:
case ComponentsPackage.ASSOCIATION__UPPER_BOUND:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
}
|
peterbartha/j2eecm
|
edu.bme.vik.iit.j2eecm.edit/src/components/provider/AssociationItemProvider.java
|
Java
|
gpl-2.0
| 6,415
|
/*
* Copyright (c) 1992, 1993
* The Regents of the University of California. All rights reserved.
*
* This software was developed by the Computer Systems Engineering group
* at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
* contributed to Berkeley.
*
* All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Lawrence Berkeley Laboratory.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)fpu_div.c 8.1 (Berkeley) 6/11/93
* $NetBSD: fpu_div.c,v 1.2 1994/11/20 20:52:38 deraadt Exp $
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: release/8.2.0/lib/libc/sparc64/fpu/fpu_div.c 205896 2010-03-30 19:06:31Z marius $");
/*
* Perform an FPU divide (return x / y).
*/
#include <sys/types.h>
#include <machine/frame.h>
#include <machine/fp.h>
#include <machine/fsr.h>
#include "fpu_arith.h"
#include "fpu_emu.h"
#include "fpu_extern.h"
/*
* Division of normal numbers is done as follows:
*
* x and y are floating point numbers, i.e., in the form 1.bbbb * 2^e.
* If X and Y are the mantissas (1.bbbb's), the quotient is then:
*
* q = (X / Y) * 2^((x exponent) - (y exponent))
*
* Since X and Y are both in [1.0,2.0), the quotient's mantissa (X / Y)
* will be in [0.5,2.0). Moreover, it will be less than 1.0 if and only
* if X < Y. In that case, it will have to be shifted left one bit to
* become a normal number, and the exponent decremented. Thus, the
* desired exponent is:
*
* left_shift = x->fp_mant < y->fp_mant;
* result_exp = x->fp_exp - y->fp_exp - left_shift;
*
* The quotient mantissa X/Y can then be computed one bit at a time
* using the following algorithm:
*
* Q = 0; -- Initial quotient.
* R = X; -- Initial remainder,
* if (left_shift) -- but fixed up in advance.
* R *= 2;
* for (bit = FP_NMANT; --bit >= 0; R *= 2) {
* if (R >= Y) {
* Q |= 1 << bit;
* R -= Y;
* }
* }
*
* The subtraction R -= Y always removes the uppermost bit from R (and
* can sometimes remove additional lower-order 1 bits); this proof is
* left to the reader.
*
* This loop correctly calculates the guard and round bits since they are
* included in the expanded internal representation. The sticky bit
* is to be set if and only if any other bits beyond guard and round
* would be set. From the above it is obvious that this is true if and
* only if the remainder R is nonzero when the loop terminates.
*
* Examining the loop above, we can see that the quotient Q is built
* one bit at a time ``from the top down''. This means that we can
* dispense with the multi-word arithmetic and just build it one word
* at a time, writing each result word when it is done.
*
* Furthermore, since X and Y are both in [1.0,2.0), we know that,
* initially, R >= Y. (Recall that, if X < Y, R is set to X * 2 and
* is therefore at in [2.0,4.0).) Thus Q is sure to have bit FP_NMANT-1
* set, and R can be set initially to either X - Y (when X >= Y) or
* 2X - Y (when X < Y). In addition, comparing R and Y is difficult,
* so we will simply calculate R - Y and see if that underflows.
* This leads to the following revised version of the algorithm:
*
* R = X;
* bit = FP_1;
* D = R - Y;
* if (D >= 0) {
* result_exp = x->fp_exp - y->fp_exp;
* R = D;
* q = bit;
* bit >>= 1;
* } else {
* result_exp = x->fp_exp - y->fp_exp - 1;
* q = 0;
* }
* R <<= 1;
* do {
* D = R - Y;
* if (D >= 0) {
* q |= bit;
* R = D;
* }
* R <<= 1;
* } while ((bit >>= 1) != 0);
* Q[0] = q;
* for (i = 1; i < 4; i++) {
* q = 0, bit = 1 << 31;
* do {
* D = R - Y;
* if (D >= 0) {
* q |= bit;
* R = D;
* }
* R <<= 1;
* } while ((bit >>= 1) != 0);
* Q[i] = q;
* }
*
* This can be refined just a bit further by moving the `R <<= 1'
* calculations to the front of the do-loops and eliding the first one.
* The process can be terminated immediately whenever R becomes 0, but
* this is relatively rare, and we do not bother.
*/
struct fpn *
__fpu_div(fe)
struct fpemu *fe;
{
struct fpn *x = &fe->fe_f1, *y = &fe->fe_f2;
u_int q, bit;
u_int r0, r1, r2, r3, d0, d1, d2, d3, y0, y1, y2, y3;
FPU_DECL_CARRY
/*
* Since divide is not commutative, we cannot just use ORDER.
* Check either operand for NaN first; if there is at least one,
* order the signalling one (if only one) onto the right, then
* return it. Otherwise we have the following cases:
*
* Inf / Inf = NaN, plus NV exception
* Inf / num = Inf [i.e., return x #]
* Inf / 0 = Inf [i.e., return x #]
* 0 / Inf = 0 [i.e., return x #]
* 0 / num = 0 [i.e., return x #]
* 0 / 0 = NaN, plus NV exception
* num / Inf = 0 #
* num / num = num (do the divide)
* num / 0 = Inf #, plus DZ exception
*
* # Sign of result is XOR of operand signs.
*/
if (ISNAN(x) || ISNAN(y)) {
ORDER(x, y);
return (y);
}
if (ISINF(x) || ISZERO(x)) {
if (x->fp_class == y->fp_class)
return (__fpu_newnan(fe));
x->fp_sign ^= y->fp_sign;
return (x);
}
x->fp_sign ^= y->fp_sign;
if (ISINF(y)) {
x->fp_class = FPC_ZERO;
return (x);
}
if (ISZERO(y)) {
fe->fe_cx = FSR_DZ;
x->fp_class = FPC_INF;
return (x);
}
/*
* Macros for the divide. See comments at top for algorithm.
* Note that we expand R, D, and Y here.
*/
#define SUBTRACT /* D = R - Y */ \
FPU_SUBS(d3, r3, y3); FPU_SUBCS(d2, r2, y2); \
FPU_SUBCS(d1, r1, y1); FPU_SUBC(d0, r0, y0)
#define NONNEGATIVE /* D >= 0 */ \
((int)d0 >= 0)
#ifdef FPU_SHL1_BY_ADD
#define SHL1 /* R <<= 1 */ \
FPU_ADDS(r3, r3, r3); FPU_ADDCS(r2, r2, r2); \
FPU_ADDCS(r1, r1, r1); FPU_ADDC(r0, r0, r0)
#else
#define SHL1 \
r0 = (r0 << 1) | (r1 >> 31), r1 = (r1 << 1) | (r2 >> 31), \
r2 = (r2 << 1) | (r3 >> 31), r3 <<= 1
#endif
#define LOOP /* do ... while (bit >>= 1) */ \
do { \
SHL1; \
SUBTRACT; \
if (NONNEGATIVE) { \
q |= bit; \
r0 = d0, r1 = d1, r2 = d2, r3 = d3; \
} \
} while ((bit >>= 1) != 0)
#define WORD(r, i) /* calculate r->fp_mant[i] */ \
q = 0; \
bit = 1 << 31; \
LOOP; \
(x)->fp_mant[i] = q
/* Setup. Note that we put our result in x. */
r0 = x->fp_mant[0];
r1 = x->fp_mant[1];
r2 = x->fp_mant[2];
r3 = x->fp_mant[3];
y0 = y->fp_mant[0];
y1 = y->fp_mant[1];
y2 = y->fp_mant[2];
y3 = y->fp_mant[3];
bit = FP_1;
SUBTRACT;
if (NONNEGATIVE) {
x->fp_exp -= y->fp_exp;
r0 = d0, r1 = d1, r2 = d2, r3 = d3;
q = bit;
bit >>= 1;
} else {
x->fp_exp -= y->fp_exp + 1;
q = 0;
}
LOOP;
x->fp_mant[0] = q;
WORD(x, 1);
WORD(x, 2);
WORD(x, 3);
x->fp_sticky = r0 | r1 | r2 | r3;
return (x);
}
|
mohammadhamad/mhh
|
contrib/libc-28a76ac905060290c2c7a744a771b6c018b21434/src/lib/libc/lib/libc/sparc64/fpu/fpu_div.c
|
C
|
gpl-2.0
| 8,119
|
/**********************************************************************************************************************
* Copyright (c) 2015. Lorem ipsum dolor sit amet, consectetur adipiscing elit. *
* Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. *
* Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. *
* Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. *
* Vestibulum commodo. Ut rhoncus gravida arcu. *
**********************************************************************************************************************/
package z.z.w.test.common.core.notify;
/**************************************************************************
* <pre>
* FileName: IDataManipulation
* Desc:
* author: Z_Z.W - myhongkongzhen@gmail.com
* version: 2015-12-28 23:54
* LastChange: 2015-12-28 23:54
* History:
* </pre>
**************************************************************************/
public interface IDataManipulation< T >
{
void operating( T t );
}
|
myhongkongzhen/pro-study-jdk
|
src/main/java/z/z/w/test/common/core/notify/IDataManipulation.java
|
Java
|
gpl-2.0
| 1,312
|
# -*- coding: utf-8 -*-
import json
import datetime
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from misc.decorators import staff_required, common_ajax_response, verify_permission
from common import cache, debug, page
from message.interface import GlobalNoticeBase
#--------------------------------- 缓存管理
@verify_permission('')
def caches(request, template_name='admin/caches.html'):
indexes = [{'name': cache.CACHE_INDEX[k][0], 'value': k} for k in cache.CACHE_INDEX.keys()]
descs = [{'name': cache.CACHE_KEYS_DESC[k], 'value': k} for k in cache.CACHE_KEYS_DESC.keys()]
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
@verify_permission('modify_cache')
@common_ajax_response
def modify_cache(request):
index = request.REQUEST.get('index')
key = request.REQUEST.get('key_name')
value = request.REQUEST.get('key_value', '')
expire = request.REQUEST.get('key_expire', 3600)
try:
c = cache.Cache(cache.CACHE_INDEX[index][1])
c.set(key, value, expire)
return 0, u'修改成功!'
except Exception, e:
debug.get_debug_detail(e)
return 1, u'系统错误!'
@verify_permission('remove_cache')
@common_ajax_response
def remove_cache(request):
index = request.REQUEST.get('index')
key = request.REQUEST.get('key_name')
try:
c = cache.Cache(cache.CACHE_INDEX[index][1])
c.delete(key)
return 0, u'删除成功!'
except Exception, e:
debug.get_debug_detail(e)
return 1, u'系统错误!'
@verify_permission('get_cache')
@common_ajax_response
def get_cache(request):
index = request.REQUEST.get('index')
key = request.REQUEST.get('key_name')
try:
c = cache.Cache(cache.CACHE_INDEX[index][1])
return 0, [c.get(key) or '', c.ttl(key) or 0]
except Exception, e:
debug.get_debug_detail(e)
return 1, u'系统错误!'
#--------------------------------- 全站通告
@verify_permission('')
def notice(request, template_name='admin/notice.html'):
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
@verify_permission('query_notice')
def search_notice(request):
data = []
gnb = GlobalNoticeBase()
page_index = int(request.REQUEST.get('page_index'))
page_objs = page.Cpt(gnb.get_all_global_notice(), count=10, page=page_index).info
num = 10 * (page_index - 1)
for obj in page_objs[0]:
num += 1
data.append({
'num': num,
'notice_id': obj.id,
'content': obj.content,
'start_time': str(obj.start_time),
'end_time': str(obj.end_time),
'level': obj.level,
'state': True if (obj.end_time - datetime.datetime.now()).total_seconds > 0 else False
})
return HttpResponse(
json.dumps({'data': data, 'page_count': page_objs[4], 'total_count': page_objs[5]}),
mimetype='application/json'
)
@verify_permission('add_notice')
@common_ajax_response
def add_notice(request):
content = request.REQUEST.get('content')
start_time = request.REQUEST.get('start_time')
end_time = request.REQUEST.get('end_time')
level = request.REQUEST.get('level')
return GlobalNoticeBase().create_global_notice(
content, start_time, end_time, request.user.id, level)
@verify_permission('query_notice')
def get_notice_by_id(request):
notice_id = request.REQUEST.get('notice_id')
data = ''
obj = GlobalNoticeBase().get_notice_by_id(notice_id)
if obj:
data = {
'num': 1,
'notice_id': obj.id,
'content': obj.content,
'start_time': str(obj.start_time)[:10],
'end_time': str(obj.end_time)[:10],
'level': obj.level,
'state': True if (obj.end_time - datetime.datetime.now()).total_seconds > 0 else False
}
return HttpResponse(json.dumps(data), mimetype='application/json')
@verify_permission('modify_notice')
@common_ajax_response
def modify_notice(request):
notice_id = request.REQUEST.get('notice_id')
content = request.REQUEST.get('content')
start_time = request.REQUEST.get('start_time')
end_time = request.REQUEST.get('end_time')
level = request.REQUEST.get('level')
return GlobalNoticeBase().modify_global_notice(
notice_id, content=content, start_time=start_time, end_time=end_time, level=level)
@verify_permission('remove_notice')
@common_ajax_response
def remove_notice(request):
notice_id = request.REQUEST.get('notice_id')
return GlobalNoticeBase().remove_global_notice(notice_id)
|
lantianlz/zx
|
www/admin/views_tools.py
|
Python
|
gpl-2.0
| 4,764
|
/*
* wowhead basic.js
* adapted to phpbb
*
*/
window.onload = resizeIfOdd;
window.onresize = forceBrowserEven;
function resizeIfOdd(){
if(navigator.userAgent.indexOf('Firefox/3') != -1 ||
navigator.userAgent.indexOf('WebKit') != -1)
if(document.documentElement.clientWidth % 2 == 1)
window.resizeBy(-1,0);
};
function forceBrowserEven(){
window.setTimeout('resizeIfOdd()',5);
};
if (typeof $WH == "undefined") {
var $WH = {}
}
if ((whPos = document.domain.indexOf(".wowhead.com")) != -1) {
document.domain = document.domain.substring(whPos + 1)
}
$WH.$E = function(a) {
if (!a) {
if (typeof event != "undefined") {
a = event
} else {
return null
}
}
if (a.which) {
a._button = a.which
} else {
a._button = a.button;
if ($WH.Browser.ie6789 && a._button) {
if (a._button & 4) {
a._button = 2
} else {
if (a._button & 2) {
a._button = 3
}
}
} else {
a._button = a.button + 1
}
}
a._target = a.target ? a.target : a.srcElement;
a._wheelDelta = a.wheelDelta ? a.wheelDelta : -a.detail;
return a
};
$WH.$A = function(c) {
var e = [];
for ( var d = 0, b = c.length; d < b; ++d) {
e.push(c[d])
}
return e
};
if (!Function.prototype.bind) {
Function.prototype.bind = function() {
var c = this, a = $WH.$A(arguments), b = a.shift();
return function() {
return c.apply(b, a.concat($WH.$A(arguments)))
}
}
}
$WH.bindfunc = function() {
args = $WH.$A(arguments);
var b = args.shift();
var a = args.shift();
return function() {
return b.apply(a, args.concat($WH.$A(arguments)))
}
};
if (!String.prototype.ltrim) {
String.prototype.ltrim = function() {
return this.replace(/^\s*/, "")
}
}
if (!String.prototype.rtrim) {
String.prototype.rtrim = function() {
return this.replace(/\s*$/, "")
}
}
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.ltrim().rtrim()
}
}
if (!String.prototype.removeAllWhitespace) {
String.prototype.removeAllWhitespace = function() {
return this.replace("/s+/g", "")
}
}
$WH.strcmp = function(d, c) {
if (d == c) {
return 0
}
if (d == null) {
return -1
}
if (c == null) {
return 1
}
var f = parseFloat(d);
var e = parseFloat(c);
if (!isNaN(f) && !isNaN(e) && f != e) {
return f < e ? -1 : 1
}
if (typeof d == "string" && typeof c == "string") {
return d.localeCompare(c)
}
return d < c ? -1 : 1
};
$WH.trim = function(a) {
return a.replace(/(^\s*|\s*$)/g, "")
};
$WH.rtrim = function(c, d) {
var b = c.length;
while (--b > 0 && c.charAt(b) == d) {
}
c = c.substring(0, b + 1);
if (c == d) {
c = "";
}
return c
};
$WH.sprintf = function(b) {
var a;
for (a = 1, len = arguments.length; a < len; ++a) {
b = b.replace("$" + a, arguments[a])
}
return b
};
$WH.sprintfa = function(b) {
var a;
for (a = 1, len = arguments.length; a < len; ++a) {
b = b.replace(new RegExp("\\$" + a, "g"), arguments[a])
}
return b
};
$WH.sprintfo = function(c) {
if (typeof c == "object" && c.length) {
var a = c;
c = a[0];
var b;
for (b = 1; b < a.length; ++b) {
c = c.replace("$" + b, a[b])
}
return c
}
};
$WH.str_replace = function(e, d, c) {
while (e.indexOf(d) != -1) {
e = e.replace(d, c)
}
return e
};
$WH.urlencode = function(a) {
a = encodeURIComponent(a);
a = $WH.str_replace(a, "+", "%2B");
return a
};
$WH.urlencode2 = function(a) {
a = encodeURIComponent(a);
a = $WH.str_replace(a, "%20", "+");
a = $WH.str_replace(a, "%3D", "=");
return a
};
$WH.number_format = function(a) {
x = ("" + parseFloat(a)).split(".");
a = x[0];
x = x.length > 1 ? "." + x[1] : "";
if (a.length <= 3) {
return a + x
}
return $WH.number_format(a.substr(0, a.length - 3)) + ","
+ a.substr(a.length - 3) + x
};
$WH.is_array = function(b) {
return !!(b && b.constructor == Array)
};
$WH.in_array = function(c, g, h, e) {
if (c == null) {
return -1
}
if (h) {
return $WH.in_arrayf(c, g, h, e)
}
for ( var d = e || 0, b = c.length; d < b; ++d) {
if (c[d] == g) {
return d
}
}
return -1
};
$WH.in_arrayf = function(c, g, h, e) {
for ( var d = e || 0, b = c.length; d < b; ++d) {
if (h(c[d]) == g) {
return d
}
}
return -1
};
$WH.rs = function() {
var e = $WH.rs.random;
var b = "";
for ( var a = 0; a < 16; a++) {
var d = Math.floor(Math.random() * e.length);
if (a == 0 && d < 11) {
d += 10
}
b += e.substring(d, d + 1)
}
return b
};
$WH.rs.random = "0123456789abcdefghiklmnopqrstuvwxyz";
$WH.isset = function(a) {
return typeof window[a] != "undefined"
};
if (!$WH.isset("console")) {
console = {
log : function() {
}
}
}
$WH.array_walk = function(d, h, c) {
var g;
for ( var e = 0, b = d.length; e < b; ++e) {
g = h(d[e], c, d, e);
if (g != null) {
d[e] = g
}
}
};
$WH.array_apply = function(d, h, c) {
var g;
for ( var e = 0, b = d.length; e < b; ++e) {
h(d[e], c, d, e)
}
};
$WH.array_filter = function(c, g) {
var e = [];
for ( var d = 0, b = c.length; d < b; ++d) {
if (g(c[d])) {
e.push(c[d])
}
}
return e
};
$WH.array_index = function(c, e, g, h) {
if (!$WH.is_array(c)) {
return false
}
if (!c.__R || h) {
c.__R = {};
if (!g) {
g = function(a) {
return a
}
}
for ( var d = 0, b = c.length; d < b; ++d) {
c.__R[g(c[d])] = d
}
}
return (e == null ? c.__R : !isNaN(c.__R[e]))
};
$WH.array_compare = function(d, c) {
if (d.length != c.length) {
return false
}
var g = {};
for ( var f = d.length; f >= 0; --f) {
g[d[f]] = true
}
var e = true;
for ( var f = c.length; f >= 0; --f) {
if (g[c[f]] === undefined) {
e = false
}
}
return e
};
$WH.array_unique = function(b) {
var c = [];
var e = {};
for ( var d = b.length - 1; d >= 0; --d) {
e[b[d]] = 1
}
for ( var d in e) {
c.push(d)
}
return c
};
$WH.ge = function(a) {
if (typeof a != "string") {
return a
}
return document.getElementById(a)
};
$WH.gE = function(a, b) {
return a.getElementsByTagName(b)
};
$WH.ce = function(d, b, e) {
var a = document.createElement(d);
if (b) {
$WH.cOr(a, b)
}
if (e) {
$WH.ae(a, e)
}
return a
};
$WH.de = function(a) {
if (!a || !a.parentNode) {
return
}
a.parentNode.removeChild(a)
};
$WH.ae = function(a, b) {
if ($WH.is_array(b)) {
$WH.array_apply(b, a.appendChild.bind(a));
return b
} else {
return a.appendChild(b)
}
};
$WH.aef = function(a, b) {
return a.insertBefore(b, a.firstChild)
};
$WH.ee = function(a, b) {
if (!b) {
b = 0
}
while (a.childNodes[b]) {
a.removeChild(a.childNodes[b])
}
};
$WH.ct = function(a) {
return document.createTextNode(a)
};
$WH.st = function(a, b) {
if (a.firstChild && a.firstChild.nodeType == 3) {
a.firstChild.nodeValue = b
} else {
$WH.aef(a, $WH.ct(b))
}
};
$WH.nw = function(a) {
a.style.whiteSpace = "nowrap"
};
$WH.rf = function() {
return false
};
$WH.rf2 = function(a) {
a = $WH.$E(a);
if (a.ctrlKey || a.shiftKey || a.altKey || a.metaKey) {
return
}
return false
};
$WH.tb = function() {
this.blur()
};
$WH.aE = function(b, c, a) {
if ($WH.Browser.ie6789) {
b.attachEvent("on" + c, a)
} else {
b.addEventListener(c, a, false)
}
};
$WH.dE = function(b, c, a) {
if ($WH.Browser.ie6789) {
b.detachEvent("on" + c, a)
} else {
b.removeEventListener(c, a, false)
}
};
$WH.sp = function(a) {
if (!a) {
a = event
}
if ($WH.Browser.ie6789) {
a.cancelBubble = true
} else {
a.stopPropagation()
}
};
$WH.sc = function(h, j, d, f, g) {
var e = new Date();
var c = h + "=" + escape(d) + "; ";
e.setDate(e.getDate() + j);
c += "expires=" + e.toUTCString() + "; ";
if (f) {
c += "path=" + f + "; "
}
if (g) {
c += "domain=" + g + "; "
}
document.cookie = c;
$WH.gc(h);
$WH.gc.C[h] = d
};
$WH.dc = function(a) {
$WH.sc(a, -1);
$WH.gc.C[a] = null
};
$WH.gc = function(f) {
if ($WH.gc.I == null) {
var e = unescape(document.cookie).split("; ");
$WH.gc.C = {};
for ( var c = 0, a = e.length; c < a; ++c) {
var g = e[c].indexOf("="), b, d;
if (g != -1) {
b = e[c].substr(0, g);
d = e[c].substr(g + 1)
} else {
b = e[c];
d = ""
}
$WH.gc.C[b] = d
}
$WH.gc.I = 1
}
if (!f) {
return $WH.gc.C
} else {
return $WH.gc.C[f]
}
};
$WH.ns = function(a) {
if ($WH.Browser.ie6789) {
a.onfocus = $WH.tb;
a.onmousedown = a.onselectstart = a.ondragstart = $WH.rf
}
};
$WH.eO = function(b) {
for ( var a in b) {
delete b[a]
}
};
$WH.dO = function(a) {
function b() {
}
b.prototype = a;
return new b
};
$WH.cO = function(c, a) {
for ( var b in a) {
if (a[b] !== null && typeof a[b] == "object" && a[b].length) {
c[b] = a[b].slice(0)
} else {
c[b] = a[b]
}
}
return c
};
$WH.cOr = function(c, a) {
for ( var b in a) {
if (typeof a[b] == "object") {
if (a[b].length) {
c[b] = a[b].slice(0)
} else {
if (!c[b]) {
c[b] = {}
}
$WH.cOr(c[b], a[b])
}
} else {
c[b] = a[b]
}
}
return c
};
$WH.Browser = {
ie : !!(window.attachEvent && !window.opera),
opera : !!window.opera,
safari : navigator.userAgent.indexOf("Safari") != -1,
firefox : navigator.userAgent.indexOf("Firefox") != -1,
chrome : navigator.userAgent.indexOf("Chrome") != -1
};
$WH.Browser.ie9 = $WH.Browser.ie
&& navigator.userAgent.indexOf("MSIE 9.0") != -1;
$WH.Browser.ie8 = $WH.Browser.ie
&& navigator.userAgent.indexOf("MSIE 8.0") != -1 && !$WH.Browser.ie9;
$WH.Browser.ie7 = $WH.Browser.ie
&& navigator.userAgent.indexOf("MSIE 7.0") != -1 && !$WH.Browser.ie8;
$WH.Browser.ie6 = $WH.Browser.ie
&& navigator.userAgent.indexOf("MSIE 6.0") != -1 && !$WH.Browser.ie7;
$WH.Browser.ie67 = $WH.Browser.ie6 || $WH.Browser.ie7;
$WH.Browser.ie678 = $WH.Browser.ie67 || $WH.Browser.ie8;
$WH.Browser.ie6789 = $WH.Browser.ie678 || $WH.Browser.ie9;
$WH.OS = {
windows : navigator.appVersion.indexOf("Windows") != -1,
mac : navigator.appVersion.indexOf("Macintosh") != -1,
linux : navigator.appVersion.indexOf("Linux") != -1
};
$WH.g_getWindowSize = function() {
var a = 0, b = 0;
if (document.documentElement
&& (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
a = document.documentElement.clientWidth;
b = document.documentElement.clientHeight
} else {
if (document.body
&& (document.body.clientWidth || document.body.clientHeight)) {
a = document.body.clientWidth;
b = document.body.clientHeight
} else {
if (typeof window.innerWidth == "number") {
a = window.innerWidth;
b = window.innerHeight
}
}
}
return {
w : a,
h : b
}
};
$WH.g_getScroll = function() {
var a = 0, b = 0;
if (typeof (window.pageYOffset) == "number") {
a = window.pageXOffset;
b = window.pageYOffset
} else {
if (document.body
&& (document.body.scrollLeft || document.body.scrollTop)) {
a = document.body.scrollLeft;
b = document.body.scrollTop
} else {
if (document.documentElement
&& (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
a = document.documentElement.scrollLeft;
b = document.documentElement.scrollTop
}
}
}
return {
x : a,
y : b
}
};
$WH.g_getCursorPos = function(c) {
var a, d;
if (window.innerHeight) {
a = c.pageX;
d = c.pageY
} else {
var b = $WH.g_getScroll();
a = c.clientX + b.x;
d = c.clientY + b.y
}
return {
x : a,
y : d
}
};
$WH.ac = function(c, d) {
var a = 0, g = 0, b;
while (c) {
a += c.offsetLeft;
g += c.offsetTop;
b = c.parentNode;
while (b && b != c.offsetParent && b.offsetParent) {
if (b.scrollLeft || b.scrollTop) {
a -= (b.scrollLeft | 0);
g -= (b.scrollTop | 0);
break
}
b = b.parentNode
}
c = c.offsetParent
}
if ($WH.isset("Lightbox") && Lightbox.isVisible()) {
d = true
}
if (d) {
var f = $WH.g_getScroll();
a += f.x;
g += f.y
}
var e = [ a, g ];
e.x = a;
e.y = g;
return e
};
$WH.g_scrollTo = function(c, b) {
var m, l = $WH.g_getWindowSize(), o = $WH.g_getScroll(), j = l.w, e = l.h, g = o.x, d = o.y;
c = $WH.ge(c);
if (b == null) {
b = []
} else {
if (typeof b == "number") {
b = [ b ]
}
}
m = b.length;
if (m == 0) {
b[0] = b[1] = b[2] = b[3] = 0
} else {
if (m == 1) {
b[1] = b[2] = b[3] = b[0]
} else {
if (m == 2) {
b[2] = b[0];
b[3] = b[1]
} else {
if (m == 3) {
b[3] = b[1]
}
}
}
}
m = $WH.ac(c);
var a = m[0] - b[3], h = m[1] - b[0], k = m[0] + c.offsetWidth + b[1], f = m[1]
+ c.offsetHeight + b[2];
if (k - a > j || a < g) {
g = a
} else {
if (k - j > g) {
g = k - j
}
}
if (f - h > e || h < d) {
d = h
} else {
if (f - e > d) {
d = f - e
}
}
scrollTo(g, d)
};
$WH.g_createReverseLookupJson = function(b) {
var c = {};
for ( var a in b) {
c[b[a]] = a
}
return c
};
$WH.g_getLocaleFromDomain = function(a) {
var c = $WH.g_getLocaleFromDomain.L;
if (a) {
var b = a.indexOf(".");
if (b != -1) {
a = a.substring(0, b)
}
}
return (c[a] ? c[a] : 0)
};
$WH.g_getLocaleFromDomain.L = {
fr : 2,
de : 3,
es : 6,
ru : 7,
www : 0
};
$WH.g_getDomainFromLocale = function(a) {
var b;
if ($WH.g_getDomainFromLocale.L) {
b = $WH.g_getDomainFromLocale.L
} else {
b = $WH.g_getDomainFromLocale.L = $WH
.g_createReverseLookupJson($WH.g_getLocaleFromDomain.L)
}
return (b[a] ? b[a] : "www")
};
$WH.g_getIdFromTypeName = function(a) {
var b = $WH.g_getIdFromTypeName.L;
return (b[a] ? b[a] : -1)
};
$WH.g_getIdFromTypeName.L = {
npc : 1,
object : 2,
item : 3,
itemset : 4,
quest : 5,
spell : 6,
zone : 7,
faction : 8,
pet : 9,
achievement : 10,
title : 11,
statistic : 16,
profile : 100,
"transmog-set" : 101
};
$WH.g_ajaxIshRequest = function(b) {
var c = document.getElementsByTagName("head")[0], a = $WH.g_getGets();
if (a.refresh != null) {
if (a.refresh.length) {
b += ("&refresh=" + a.refresh)
} else {
b += "&refresh"
}
}
if (a.locale != null) {
b += "&locale=" + a.locale
}
if (a.ptr != null) {
b += "&ptr"
}
$WH.ae(c, $WH.ce("script", {
type : "text/javascript",
src : b,
charset : "utf8"
}))
};
$WH.g_getGets = function() {
if ($WH.g_getGets.C != null) {
return $WH.g_getGets.C
}
var b = $WH.g_getQueryString();
var a = $WH.g_parseQueryString(b);
$WH.g_getGets.C = a;
return a
};
$WH.g_getQueryString = function() {
var a = "";
if (location.pathname) {
a += location.pathname.substr(1)
}
if (location.search) {
if (location.pathname) {
a += "&"
}
a += location.search.substr(1)
}
return a
};
$WH.g_parseQueryString = function(e) {
e = decodeURIComponent(e);
var d = e.split("&");
var c = {};
for ( var b = 0, a = d.length; b < a; ++b) {
$WH.g_splitQueryParam(d[b], c)
}
return c
};
$WH.g_splitQueryParam = function(c, d) {
var e = c.indexOf("=");
var a;
var b;
if (e != -1) {
a = c.substr(0, e);
b = c.substr(e + 1)
} else {
a = c;
b = ""
}
d[a] = b
};
$WH.g_createRect = function(d, c, a, b) {
return {
l : d,
t : c,
r : d + a,
b : c + b
}
};
$WH.g_intersectRect = function(d, c) {
return !(d.l >= c.r || c.l >= d.r || d.t >= c.b || c.t >= d.b)
};
$WH.g_convertRatingToPercent = function(h, b, g, d) {
var f = $WH.g_convertRatingToPercent.RB, e = $WH.g_convertRatingToPercent.LH;
if (h < 0) {
h = 1
} else {
if (h > 85) {
h = 85
}
}
if ((b == 12 || b == 13 || b == 14 || b == 15) && h < 34) {
h = 34
}
if ((b == 28 || b == 36) && (d == 2 || d == 6 || d == 7 || d == 11)) {
f[b] /= 1.3
}
if (g < 0) {
g = 0
}
var a;
if (!f || f[b] == null) {
a = 0
} else {
var c;
if (h > 80) {
c = e[h]
} else {
if (h > 70) {
c = (82 / 52) * Math.pow((131 / 63), ((h - 70) / 10))
} else {
if (h > 60) {
c = (82 / (262 - 3 * h))
} else {
if (h > 10) {
c = ((h - 8) / 52)
} else {
c = 2 / 52
}
}
}
}
a = g / f[b] / c
}
return a
};
$WH.g_statToJson = {
0 : "mana",
1 : "health",
3 : "agi",
4 : "str",
5 : "int",
6 : "spi",
7 : "sta",
8 : "energy",
9 : "rage",
10 : "focus",
13 : "dodgertng",
14 : "parryrtng",
16 : "mlehitrtng",
17 : "rgdhitrtng",
18 : "splhitrtng",
19 : "mlecritstrkrtng",
20 : "rgdcritstrkrtng",
21 : "splcritstrkrtng",
22 : "_mlehitrtng",
23 : "_rgdhitrtng",
24 : "_splhitrtng",
25 : "_mlecritstrkrtng",
26 : "_rgdcritstrkrtng",
27 : "_splcritstrkrtng",
28 : "mlehastertng",
29 : "rgdhastertng",
30 : "splhastertng",
31 : "hitrtng",
32 : "critstrkrtng",
33 : "_hitrtng",
34 : "_critstrkrtng",
35 : "resirtng",
36 : "hastertng",
37 : "exprtng",
38 : "atkpwr",
39 : "rgdatkpwr",
41 : "splheal",
42 : "spldmg",
43 : "manargn",
44 : "armorpenrtng",
45 : "splpwr",
46 : "healthrgn",
47 : "splpen",
49 : "mastrtng",
50 : "armor",
51 : "firres",
52 : "frores",
53 : "holres",
54 : "shares",
55 : "natres",
56 : "arcres"
};
$WH.g_jsonToStat = {};
for ( var i in $WH.g_statToJson) {
$WH.g_jsonToStat[$WH.g_statToJson[i]] = i
}
$WH.g_individualToGlobalStat = {
16 : 31,
17 : 31,
18 : 31,
19 : 32,
20 : 32,
21 : 32,
22 : 33,
23 : 33,
24 : 33,
25 : 34,
26 : 34,
27 : 34,
28 : 36,
29 : 36,
30 : 36
};
$WH.g_convertScalingFactor = function(c, b, g, d, k) {
var f = $WH.g_convertScalingFactor.SV;
var e = $WH.g_convertScalingFactor.SD;
if (!f[c]) {
if (g_user.roles & U_GROUP_ADMIN) {
alert("There are no item scaling values for level " + c)
}
return (k ? {} : 0)
}
var j = {}, h = f[c], a = e[g];
if (!a || !(d >= 0 && d <= 9)) {
j.v = h[b]
} else {
j.n = $WH.g_statToJson[a[d]];
j.s = a[d];
j.v = Math.floor(h[b] * a[d + 10] / 10000)
}
return (k ? j : j.v)
};
if (!$WH.wowheadRemote) {
$WH.g_ajaxIshRequest("/data=item-scaling")
}
$WH.g_convertScalingSpell = function(b, g) {
var j = {}, f = $WH.g_convertScalingSpell.SV, d = $WH.g_convertScalingSpell.SD, a, k;
if (!d[g]) {
if (g_user.roles & U_GROUP_ADMIN) {
alert("There are no spell scaling distributions for dist " + g)
}
return j
}
if (!f[b]) {
if (g_user.roles & U_GROUP_ADMIN) {
alert("There are no spell scaling values for level " + b)
}
return j
}
a = d[g];
if (!a[3]) {
if (g_user.roles & U_GROUP_ADMIN) {
alert("This spell should not scale at all")
}
return j
} else {
if (a[3] == -1) {
if (g_user.roles & U_GROUP_ADMIN) {
alert("This spell should use the generic scaling distribution 12")
}
a[3] = 12
}
}
if (!f[b][a[3] - 1]) {
if (g_user.roles & U_GROUP_ADMIN) {
alert("Unknown category for spell scaling " + a[3])
}
return j
}
k = f[b][a[3] - 1];
k *= (Math.min(b, a[14]) + (a[13] * Math.max(0, b - a[14]))) / b;
j.cast = Math.min(a[1], a[1] > 0 && b > 1 ? a[0]
+ (((b - 1) * (a[1] - a[0])) / (a[2] - 1)) : a[0]);
j.effects = {};
for ( var c = 0; c < 3; ++c) {
var l = a[4 + c], h = a[7 + c], e = a[10 + c], m = j.effects[c + 1] = {};
m.avg = l * k * (a[1] > 0 ? j.cast / a[1] : 1);
m.min = Math.round(m.avg) - Math.floor(m.avg * h / 2);
m.max = Math.round(m.avg) + Math.floor(m.avg * h / 2);
m.pts = Math.round(e * k);
m.avg = Math.max(Math.ceil(l), Math.round(m.avg))
}
j.cast = Math.round(j.cast / 10) / 100;
return j
};
if (!$WH.wowheadRemote) {
$WH.g_ajaxIshRequest("/data=spell-scaling")
}
$WH.g_getDataSource = function() {
if ($WH.isset("g_pageInfo")) {
switch (g_pageInfo.type) {
case 3:
if ($WH.isset("g_items")) {
return g_items
}
case 6:
if ($WH.isset("g_spells")) {
return g_spells
}
}
}
return []
};
$WH.g_setJsonItemLevel = function(o, b) {
if (!o.scadist || !o.scaflags) {
return
}
o.bonuses = o.bonuses || {};
var f = o.scaflags & 255, h = (o.scaflags >> 8) & 255, l = (o.scaflags & (1 << 16)) != 0, k = (o.scaflags & (1 << 17)) != 0, a = (o.scaflags & (1 << 18)) != 0, d;
switch (f) {
case 5:
case 1:
case 7:
case 17:
d = 7;
break;
case 3:
case 12:
d = 8;
break;
case 16:
case 11:
d = 9;
break;
case 15:
d = 10;
break;
case 23:
case 21:
case 22:
case 13:
d = 11;
break;
default:
d = -1
}
if (d >= 0) {
for ( var e = 0; e < 10; ++e) {
var m = $WH.g_convertScalingFactor(b, d, o.scadist, e, 1);
if (m.n) {
o[m.n] = m.v
}
o.bonuses[m.s] = m.v
}
}
if (a) {
o.splpwr = o.bonuses[45] = $WH.g_convertScalingFactor(b, 6)
}
if (l) {
switch (f) {
case 3:
o.armor = $WH.g_convertScalingFactor(b, 11 + h);
break;
case 5:
o.armor = $WH.g_convertScalingFactor(b, 15 + h);
break;
case 1:
o.armor = $WH.g_convertScalingFactor(b, 19 + h);
break;
case 7:
o.armor = $WH.g_convertScalingFactor(b, 23 + h);
break;
case 16:
o.armor = $WH.g_convertScalingFactor(b, 28);
break;
default:
o.armor = 0
}
}
if (k) {
var j = (o.mledps ? "mle" : "rgd"), g;
switch (f) {
case 23:
case 21:
case 22:
case 13:
o.dps = o[j + "dps"] = $WH.g_convertScalingFactor(b, a ? 2 : 0);
g = 0.3;
break;
case 17:
o.dps = o[j + "dps"] = $WH.g_convertScalingFactor(b, a ? 3 : 1);
g = 0.2;
break;
case 15:
o.dps = o[j + "dps"] = $WH.g_convertScalingFactor(b, h == 19 ? 5
: 4);
g = 0.3;
break;
default:
o.dps = o[j + "dps"] = 0;
g = 0
}
o.dmgmin = o[j + "dmgmin"] = Math.floor(o.dps * o.speed * (1 - g));
o.dmgmax = o[j + "dmgmax"] = Math.floor(o.dps * o.speed * (1 + g))
}
if (o.gearscore != null) {
if (o._gearscore == null) {
o._gearscore = o.gearscore
}
var c = Math.min(85, b + 1);
if (c >= 70) {
n = ((c - 70) * 9.5) + 105
} else {
if (c >= 60) {
n = ((c - 60) * 4.5) + 60
} else {
n = c + 5
}
}
o.gearscore = (o._gearscore * n) / 1.8
}
};
$WH.g_setJsonSpellLevel = function(a, b) {
if (!a.scadist) {
return
}
$WH.cO(a, $WH.g_convertScalingSpell(b, a.scadist))
};
$WH.g_getJsonReforge = function(b, c) {
if (!c) {
if (!$WH.g_reforgeStats) {
return []
}
if (!b.__reforge) {
b.__reforge = {}
}
if (!b.__reforge.all) {
b.__reforge.all = [];
for ( var c in $WH.g_reforgeStats) {
var d = $WH.g_getJsonReforge(b, c);
if (d.amount) {
b.__reforge.all.push(d)
}
}
}
return b.__reforge.all
}
if (!$WH.g_reforgeStats || !$WH.g_reforgeStats[c]) {
return {}
}
if (!b.__statidx) {
b.__statidx = {};
for ( var a in b) {
if ($WH.g_individualToGlobalStat[$WH.g_jsonToStat[a]]) {
b.__statidx[$WH.g_individualToGlobalStat[$WH.g_jsonToStat[a]]] = b[a]
} else {
b.__statidx[$WH.g_jsonToStat[a]] = b[a]
}
}
}
if (!b.__reforge) {
b.__reforge = {}
}
if (!b.__reforge[c]) {
var d = b.__reforge[c] = $WH.dO($WH.g_reforgeStats[c]);
b.__reforge[c].amount = Math.floor(d.v
* (b.__statidx[d.i1] && !b.__statidx[d.i2] ? b.__statidx[d.i1]
: 0))
}
return b.__reforge[c]
};
$WH.g_setTooltipLevel = function(g, a, l) {
var h = typeof g;
if (h == "number") {
var e = $WH.g_getDataSource();
if (e[g] && e[g][(l ? "buff_" : "tooltip_") + Locale.getName()]) {
g = e[g][(l ? "buff_" : "tooltip_") + Locale.getName()]
} else {
return g
}
} else {
if (h != "string") {
return g
}
}
h = g.match(/<!--\?([0-9:]*)-->/);
if (!h) {
return g
}
h = h[1].split(":");
var a = Math.min(parseInt(h[2]), Math.max(parseInt(h[1]), a)), b = parseInt(h[4]) || 0;
if (b) {
if (!g.match(/<!--pts[0-9](:[0-9])?-->/g)) {
var k = parseInt(h[5]) || 0, c = g.match(/<!--spd-->(\d\.\d+)/);
if (c) {
c = parseFloat(c[1]) || 0
}
var j = {
scadist : b,
scaflags : k,
speed : c
};
$WH.g_setJsonItemLevel(j, a);
g = g.replace(/(<!--asc(\d+)-->)([^<]+)/, function(p, m, o) {
h = o;
if (a < 40 && (o == 3 || o == 4)) {
--h
}
return m + g_itemset_types[h]
});
g = g.replace(/(<!--dmg-->)\d+(\D+)\d+/, function(p, m, o) {
return m + j.dmgmin + o + j.dmgmax
});
g = g.replace(/(<!--dps-->\D*?)(\d+\.\d)/, function(o, m) {
return m + j.dps.toFixed(1)
});
g = g.replace(/(<!--amr-->)\d+/, function(o, m) {
return m + j.armor
});
g = g
.replace(
/<span><!--stat(\d+)-->[-+]\d+(\D*?)<\/span>(<!--e-->)?(<!--ps-->)?(<br ?\/?>)?/gi,
function(r, o, m, t, u, p) {
var q, s = j.bonuses[o];
if (s) {
s = (s > 0 ? "+" : "-") + s;
q = "";
p = (p ? "<br />" : "")
} else {
s = "+0";
q = ' style="display: none"';
p = (p ? "<!--br-->" : "")
}
return "<span" + q + "><!--stat" + o + "-->"
+ s + m + "</span>" + (t || "")
+ (u || "") + p
});
g = g
.replace(
/<span class="q2">(.*?)<!--rtg(\d+)-->\d+(.*?)<\/span>(<br \/>)?/gi,
function(m, q, s, u, r, o, v) {
var p, t = j.bonuses[$WH.g_individualToGlobalStat[s]
|| s];
if (t) {
p = "";
v = (v ? "<br />" : "")
} else {
p = ' style="display: none"';
v = (v ? "<!--br-->" : "")
}
return '<span class="q2"' + p + ">" + q
+ "<!--rtg" + s + "-->" + t + u
+ "</span>" + v
})
} else {
var j = {
scadist : b
};
$WH.g_setJsonSpellLevel(j, a);
g = g.replace(/<!--cast-->\d+\.\d+/, "<!--cast-->" + j.cast);
if (j.effects) {
for ( var d = 1; d < 4; ++d) {
var f = j.effects[d];
g = g.replace(new RegExp("<!--pts" + d + "(:0)?-->(.+?)<",
"g"), "<!--pts" + d + "$1-->"
+ (f.min == f.max ? f.avg : f.min + " to " + f.max)
+ "<");
g = g.replace(
new RegExp("<!--pts" + d + ":1-->(.+?)<", "g"),
"<!--pts" + d + ":1-->" + f.min + "<");
g = g.replace(
new RegExp("<!--pts" + d + ":2-->(.+?)<", "g"),
"<!--pts" + d + ":2-->" + f.max + "<");
g = g.replace(new RegExp("<!--pts" + d
+ ":3:(\\d+)-->(.+?)<", "g"), function(o, m) {
return "<!--pts" + d + ":3:" + m + "-->" + (f.avg * m)
+ "<"
});
g = g.replace(
new RegExp("<!--pts" + d + ":4-->(.+?)<", "g"),
"<!--pts" + d + ":4-->" + f.pts + "<")
}
}
}
}
g = g.replace(/<!--ppl(\d+):(\d+):(\d+):(\d+)-->\s*\d+/gi, function(p, m,
o, q, r) {
return "<!--ppl"
+ m
+ ":"
+ o
+ ":"
+ q
+ ":"
+ r
+ "-->"
+ Math.round(parseInt(q) + (Math.min(Math.max(a, m), o) - m)
* r / 100)
});
g = g.replace(/(<!--rtg%(\d+)-->)([\.0-9]+)/g, function(p, m, q, o) {
h = g.match(new RegExp("<!--rtg" + q + "-->(\\d+)"));
if (!h) {
return p
}
return m + Math.round($WH.g_convertRatingToPercent(a, q, h[1]) * 100)
/ 100
});
g = g.replace(/(<!--\?\d+:\d+:\d+:)\d+/, "$1" + a);
g = g.replace(/<!--lvl-->\d+/g, "<!--lvl-->" + a);
return g
};
$WH.g_setTooltipSpells = function(h, e, g, c) {
var k = {}, j = "<!--sp([0-9]+):[01]-->.+?<!--sp\\1-->", d;
if (e == null) {
e = []
}
if (c == null) {
c = {}
}
for ( var b = 0; b < e.length; ++b) {
k[e[b]] = 1
}
if (d = h.match(new RegExp(j, "g"))) {
for ( var b = 0; b < d.length; ++b) {
var a = d[b].match(j)[1];
k[a] = (k[a] | 0);
if (c[a] == null) {
c[a] = -1
}
c[a]++;
if (g[a] == null || g[a][c[a]] == null || g[a][c[a]][k[a]] == null) {
continue
}
var f = g[a][c[a]][k[a]];
f = $WH.g_setTooltipSpells(f, e, g, c);
h = h.replace(d[b], "<!--sp" + a + ":" + k[a] + "-->" + f
+ "<!--sp" + a + "-->")
}
}
return h
};
$WH.g_enhanceTooltip = function(h, l, j, d, o, m, e) {
var k = typeof h, c;
if (k == "number") {
var g = $WH.g_getDataSource(), a = h;
if (g[a] && g[a][(o ? "buff_" : "tooltip_") + Locale.getName()]) {
h = g[a][(o ? "buff_" : "tooltip_") + Locale.getName()];
c = g[a][(o ? "buff" : "") + "spells_" + Locale.getName()];
if (c) {
h = $WH.g_setTooltipSpells(h, m, c)
}
} else {
return h
}
} else {
if (k != "string") {
return h
}
}
if (j) {
var b = $WH.g_getGets();
if (b.lvl) {
h = $WH.g_setTooltipLevel(h, b.lvl, o)
}
}
if (l) {
h = h
.replace(
/<span class="q2"><!--addamr(\d+)--><span>.*?<\/span><\/span>/i,
function(p, q) {
return '<span class="q2 tip" onmouseover="$WH.Tooltip.showAtCursor(event, $WH.sprintf(LANG.tooltip_armorbonus, '
+ q
+ '), 0, 0, \'q\')" onmousemove="$WH.Tooltip.cursorUpdate(event)" onmouseout="$WH.Tooltip.hide()">'
+ p + "</span>"
});
h = h
.replace(
/\(([^\)]*?<!--lvl-->[^\(]*?)\)/gi,
function(q, p) {
return '(<a href="javascript:;" onmousedown="return false" class="tip" style="color: white; cursor: pointer" onclick="$WH.g_staticTooltipLevelClick(this, null, 0)" onmouseover="$WH.Tooltip.showAtCursor(event, \'<span class=\\\'q2\\\'>\' + LANG.tooltip_changelevel + \'</span>\')" onmousemove="$WH.Tooltip.cursorUpdate(event)" onmouseout="$WH.Tooltip.hide()">'
+ p + "</a>)"
})
}
if (d && Slider) {
if (o && o.slider) {
o.bufftip = this
} else {
var k = h.match(/<!--\?(\d+):(\d+):(\d+):(\d+)/);
if (k && k[2] != k[3]) {
this.slider = Slider.init(d, {
minValue : parseInt(k[2]),
maxValue : parseInt(k[3]),
onMove : $WH.g_tooltipSliderMove.bind(this)
});
Slider.setValue(this.slider, parseInt(k[4]));
this.slider.onmouseover = function(p) {
$WH.Tooltip.showAtCursor(p, LANG.tooltip_changelevel2, 0,
0, "q2")
};
this.slider.onmousemove = $WH.Tooltip.cursorUpdate;
this.slider.onmouseout = $WH.Tooltip.hide
}
}
}
if (e) {
if (o && o.modified) {
o.bufftip = this
} else {
for ( var f in c) {
if (!g_spells[f] || $WH.in_array(m, f) != -1) {
continue
}
$(e).append('<input type="checkbox" id="known-' + f + '" />')
.append(
'<label for="known-'
+ f
+ '"><a rel="spell='
+ f
+ "&know="
+ f
+ '">'
+ g_spells[f]["name_"
+ Locale.getName()]
+ (g_spells[f]["rank_"
+ Locale.getName()] ? " ("
+ g_spells[f]["rank_"
+ Locale.getName()]
+ ")" : "") + "</a></label>")
.append("<br />");
$("#known-" + f).change($WH.g_tooltipSpellsChange.bind(this))
}
}
this.modified = [ e, c, m ];
$(e).toggle(!$(e).is(":empty"))
}
return h
};
$WH.g_staticTooltipLevelClick = function(b, a, g, j) {
while (b.className.indexOf("tooltip") == -1) {
b = b.parentNode
}
var h = b.innerHTML;
h = h.match(/<!--\?(\d+):(\d+):(\d+):(\d+)/);
if (!h) {
return
}
var k = parseInt(h[1]), e = parseInt(h[2]), f = parseInt(h[3]), d = parseInt(h[4]);
if (e >= f) {
return
}
if (!a) {
a = prompt($WH.sprintf(LANG.prompt_ratinglevel, e, f), d)
}
a = parseInt(a);
if (isNaN(a)) {
return
}
if (a == d || a < e || a > f) {
return
}
var c = $WH.g_getDataSource();
h = $WH.g_setTooltipLevel(c[k][(j ? "buff_" : "tooltip_")
+ Locale.getName()], a, j);
h = $WH.g_enhanceTooltip(h, true);
b.innerHTML = "<table><tr><td>"
+ h
+ '</td><th style="background-position: top right"></th></tr><tr><th style="background-position: bottom left"></th><th style="background-position: bottom right"></th></tr></table>';
$WH.Tooltip.fixSafe(b, 1, 1);
if (b.slider && !g) {
Slider.setValue(b.slider, a)
}
if (!j) {
($WH.g_tooltipSpellsChange.bind(b))()
}
};
$WH.g_tooltipSliderMove = function(c, b, a) {
$WH.g_staticTooltipLevelClick(this, a.value, 1);
if (this.bufftip) {
$WH.g_staticTooltipLevelClick(this.bufftip, a.value, 1, 1)
}
$WH.Tooltip.hide()
};
$WH.g_tooltipSpellsChange = function() {
if (!this.modified) {
return
}
var c = this.modified[0], a = this.modified[1], b = [];
$.each($("input:checked", c), function(d, e) {
b.push(parseInt(e.id.replace("known-", "")))
});
this.modified[2] = b;
this.innerHTML = $WH.g_setTooltipSpells(this.innerHTML, b, a);
if (this.bufftip) {
($WH.g_tooltipSpellsChange.bind(this.bufftip))()
}
};
$WH.Tooltip = {
create : function(j, l) {
var g = $WH.ce("div"), o = $WH.ce("table"), b = $WH.ce("tbody"), f = $WH
.ce("tr"), c = $WH.ce("tr"), a = $WH.ce("td"), m = $WH.ce("th"), k = $WH
.ce("th"), h = $WH.ce("th");
g.className = "wowhead-tooltip";
m.style.backgroundPosition = "top right";
k.style.backgroundPosition = "bottom left";
h.style.backgroundPosition = "bottom right";
if (j) {
a.innerHTML = j
}
$WH.ae(f, a);
$WH.ae(f, m);
$WH.ae(b, f);
$WH.ae(c, k);
$WH.ae(c, h);
$WH.ae(b, c);
$WH.ae(o, b);
if (!l) {
$WH.Tooltip.icon = $WH.ce("p");
/*$WH.Tooltip.icon.style.visibility = "hidden";*/
$WH.ae($WH.Tooltip.icon, $WH.ce("div"));
$WH.ae(g, $WH.Tooltip.icon)
}
$WH.ae(g, o);
if (!l) {
var e = $WH.ce("div");
e.className = "wowhead-tooltip-powered";
$WH.ae(g, e);
$WH.Tooltip.logo = e
}
return g
},
getMultiPartHtml : function(b, a) {
return "<table><tr><td>" + b + "</td></tr></table><table><tr><td>" + a
+ "</td></tr></table>"
},
fix : function(d, b, f) {
var e = $WH.gE(d, "table")[0], h = $WH.gE(e, "td")[0], g = h.childNodes;
d.className = $WH.trim(d.className.replace("tooltip-slider", ""));
if (g.length >= 2 && g[0].nodeName == "TABLE"
&& g[1].nodeName == "TABLE") {
g[0].style.whiteSpace = "nowrap";
var a = parseInt(d.style.width);
if (!d.slider || !a) {
if (g[1].offsetWidth > 300) {
a = Math.max(300, g[0].offsetWidth) + 20
} else {
a = Math.max(g[0].offsetWidth, g[1].offsetWidth) + 20
}
}
a = Math.min(320, a);
if (a > 20) {
d.style.width = a + "px";
g[0].style.width = g[1].style.width = "100%";
if (d.slider) {
Slider.setSize(d.slider, a - 6);
d.className += " tooltip-slider"
}
if (!b && d.offsetHeight > document.body.clientHeight) {
e.className = "shrink"
}
}
}
if (f) {
d.style.visibility = "visible"
}
},
fixSafe : function(c, b, a) {
$WH.Tooltip.fix(c, b, a)
},
append : function(c, b) {
var c = $WH.ge(c);
var a = $WH.Tooltip.create(b);
$WH.ae(c, a);
$WH.Tooltip.fixSafe(a, 1, 1)
},
prepare : function() {
if ($WH.Tooltip.tooltip) {
return
}
var a = $WH.Tooltip.create();
a.style.position = "absolute";
a.style.left = a.style.top = "-2323px";
$WH.ae(document.body, a);
$WH.Tooltip.tooltip = a;
$WH.Tooltip.tooltipTable = $WH.gE(a, "table")[0];
$WH.Tooltip.tooltipTd = $WH.gE(a, "td")[0];
var a = $WH.Tooltip.create(null, true);
a.style.position = "absolute";
a.style.left = a.style.top = "-2323px";
$WH.ae(document.body, a);
$WH.Tooltip.tooltip2 = a;
$WH.Tooltip.tooltipTable2 = $WH.gE(a, "table")[0];
$WH.Tooltip.tooltipTd2 = $WH.gE(a, "td")[0]
},
set : function(c, b) {
var a = $WH.Tooltip.tooltip;
a.style.width = "550px";
a.style.left = "-2323px";
a.style.top = "-2323px";
if (c.nodeName) {
$WH.ee($WH.Tooltip.tooltipTd);
$WH.ae($WH.Tooltip.tooltipTd, c)
} else {
$WH.Tooltip.tooltipTd.innerHTML = c
}
a.style.display = "";
$WH.Tooltip.fix(a, 0, 0);
if (b) {
$WH.Tooltip.showSecondary = true;
var a = $WH.Tooltip.tooltip2;
a.style.width = "550px";
a.style.left = "-2323px";
a.style.top = "-2323px";
if (b.nodeName) {
$WH.ee($WH.Tooltip.tooltipTd2);
$WH.ae($WH.Tooltip.tooltipTd2, b)
} else {
$WH.Tooltip.tooltipTd2.innerHTML = b
}
a.style.display = "";
$WH.Tooltip.fix(a, 0, 0)
} else {
$WH.Tooltip.showSecondary = false
}
},
moveTests : [ [ null, null ], [ null, false ], [ false, null ],
[ false, false ] ],
move : function(q, p, e, r, d, b) {
if (!$WH.Tooltip.tooltipTable) {
return
}
var o = $WH.Tooltip.tooltip, j = $WH.Tooltip.tooltipTable.offsetWidth, c = $WH.Tooltip.tooltipTable.offsetHeight, l = $WH.Tooltip.tooltip2, g = $WH.Tooltip.showSecondary ? $WH.Tooltip.tooltipTable2.offsetWidth
: 0, a = $WH.Tooltip.showSecondary ? $WH.Tooltip.tooltipTable2.offsetHeight
: 0, s;
o.style.width = j + "px";
l.style.width = g + "px";
var m, f;
for ( var h = 0, k = $WH.Tooltip.moveTests.length; h < k; ++h) {
s = $WH.Tooltip.moveTests[h];
m = $WH.Tooltip.moveTest(q, p, e, r, d, b, s[0], s[1]);
if ($WH.isset("Ads") && !Ads.intersect(m)) {
f = true;
break
} else {
if (!$WH.isset("Ads")) {
break
}
}
}
if ($WH.isset("Ads") && !f) {
Ads.intersect(m, true)
}
o.style.left = m.l + "px";
o.style.top = m.t + "px";
o.style.visibility = "visible";
if ($WH.Tooltip.showSecondary) {
l.style.left = m.l + j + "px";
l.style.top = m.t + "px";
l.style.visibility = "visible"
}
},
moveTest : function(e, o, r, C, c, a, q, b) {
var m = e, A = o, g = $WH.Tooltip.tooltip, k = $WH.Tooltip.tooltipTable.offsetWidth, t = $WH.Tooltip.tooltipTable.offsetHeight, p = $WH.Tooltip.tooltip2, B = $WH.Tooltip.showSecondary ? $WH.Tooltip.tooltipTable2.offsetWidth
: 0, f = $WH.Tooltip.showSecondary ? $WH.Tooltip.tooltipTable2.offsetHeight
: 0, j = $WH.g_getWindowSize(), l = $WH.g_getScroll(), h = j.w, s = j.h, d = l.x, z = l.y, y = d, w = z, v = d
+ h, u = z + s;
if (q == null) {
q = (e + r + k + B <= v)
}
if (b == null) {
b = (o - Math.max(t, f) >= w)
}
if (q) {
e += r + c
} else {
e = Math.max(e - (k + B), y) - c
}
if (b) {
o -= Math.max(t, f) + a
} else {
o += C + a
}
if (e < y) {
e = y
} else {
if (e + k + B > v) {
e = v - (k + B)
}
}
if (o < w) {
o = w
} else {
if (o + Math.max(t, f) > u) {
o = Math.max(z, u - Math.max(t, f))
}
}
if ($WH.Tooltip.iconVisible) {
if (m >= e - 48 && m <= e && A >= o - 4 && A <= o + 48) {
o -= 48 - (A - o)
}
}
return $WH.g_createRect(e, o, k, t)
},
show : function(g, f, d, b, c, e) {
if ($WH.Tooltip.disabled) {
return
}
if (!d || d < 1) {
d = 1
}
if (!b || b < 1) {
b = 1
}
if (c) {
f = '<span class="' + c + '">' + f + "</span>"
}
var a = $WH.ac(g);
$WH.Tooltip.prepare();
$WH.Tooltip.set(f, e);
$WH.Tooltip.move(a.x, a.y, g.offsetWidth, g.offsetHeight, d, b)
},
showAtCursor : function(f, g, c, a, b, d) {
if ($WH.Tooltip.disabled) {
return
}
if (!c || c < 10) {
c = 10
}
if (!a || a < 10) {
a = 10
}
if (b) {
g = '<span class="' + b + '">' + g + "</span>";
if (d) {
d = '<span class="' + b + '">' + d + "</span>"
}
}
f = $WH.$E(f);
var h = $WH.g_getCursorPos(f);
$WH.Tooltip.prepare();
$WH.Tooltip.set(g, d);
$WH.Tooltip.move(h.x, h.y, 0, 0, c, a)
},
showAtXY : function(e, a, f, c, b, d) {
if ($WH.Tooltip.disabled) {
return
}
$WH.Tooltip.prepare();
$WH.Tooltip.set(e, d);
$WH.Tooltip.move(a, f, 0, 0, c, b)
},
cursorUpdate : function(b, a, d) {
if ($WH.Tooltip.disabled || !$WH.Tooltip.tooltip) {
return
}
b = $WH.$E(b);
if (!a || a < 10) {
a = 10
}
if (!d || d < 10) {
d = 10
}
var c = $WH.g_getCursorPos(b);
$WH.Tooltip.move(c.x, c.y, 0, 0, a, d)
},
hide : function() {
if ($WH.Tooltip.tooltip) {
$WH.Tooltip.tooltip.style.display = "none";
$WH.Tooltip.tooltip.visibility = "hidden";
$WH.Tooltip.tooltipTable.className = "";
$WH.Tooltip.setIcon(null);
if ($WH.isset("Ads")) {
Ads.restoreHidden()
}
}
if ($WH.Tooltip.tooltip2) {
$WH.Tooltip.tooltip2.style.display = "none";
$WH.Tooltip.tooltip2.visibility = "hidden";
$WH.Tooltip.tooltipTable2.className = ""
}
},
setIcon : function(a) {
$WH.Tooltip.prepare();
if (a) {
$WH.Tooltip.icon.style.backgroundImage = "url(https://wowimg.zamimg.com/images/wow/icons/medium/"
+ a.toLowerCase() + ".jpg)";
$WH.Tooltip.icon.style.visibility = "visible"
} else {
$WH.Tooltip.icon.style.backgroundImage = "none";
$WH.Tooltip.icon.style.visibility = "hidden"
}
$WH.Tooltip.iconVisible = a ? 1 : 0
}
};
if ($WH.isset("$WowheadPower")) {
$WowheadPower.init()
}
$WH.g_getProfileIcon = function(d, e, a, g, c, b) {
var f = {
10 : {
6 : 1,
3 : 1,
8 : 1,
2 : 1,
5 : 1,
4 : 1,
9 : 1
},
11 : {
6 : 1,
3 : 1,
8 : 1,
2 : 1,
5 : 1,
7 : 1,
1 : 1
},
3 : {
6 : 1,
3 : 1,
2 : 1,
5 : 1,
4 : 1,
1 : 1
},
7 : {
6 : 1,
8 : 1,
4 : 1,
9 : 1,
1 : 1
},
1 : {
6 : 1,
8 : 1,
2 : 1,
5 : 1,
4 : 1,
9 : 1,
1 : 1
},
4 : {
6 : 1,
11 : 1,
3 : 1,
5 : 1,
4 : 1,
1 : 1
},
2 : {
6 : 1,
3 : 1,
4 : 1,
7 : 1,
9 : 1,
1 : 1
},
6 : {
6 : 1,
11 : 1,
3 : 1,
7 : 1,
1 : 1
},
8 : {
6 : 1,
3 : 1,
8 : 1,
5 : 1,
4 : 1,
7 : 1,
1 : 1
},
5 : {
6 : 1,
8 : 1,
5 : 1,
4 : 1,
9 : 1,
1 : 1
}
};
if (c) {
return isNaN(c) ? c : "/profile=avatar" + (b ? "&size=" + b : "")
+ "&id=" + c + (b == "tiny" ? ".gif" : ".jpg")
}
if (!g_file_races[d] || !g_file_classes[e] || !g_file_genders[a] || !f[d]
|| !f[d][e] || (e == 6 && g < 55)) {
return "inv_misc_questionmark"
}
return "chr_" + g_file_races[d] + "_" + g_file_genders[a] + "_"
+ g_file_classes[e] + "0"
+ (g > 59 ? (Math.floor((g - 60) / 10) + 2) : 1)
};
|
bbDKP/bbTips
|
root/adm/style/dkp/bbtips/basic.js
|
JavaScript
|
gpl-2.0
| 40,700
|
-- ATS Navcomp Version info
version_info =
{
["de6b99ef3f79191fd27d59b0"] =
{
name = "ChatGrabberMain", version = 2.25, page = "http://zen.trekmush.org/ats/beta/",
filename = "ATS_Chatgrabber.xml", infopage = "http://zen.trekmush.org/chatgrabber/",
whatsnew = "(2.25) Fix crashbug with older versions of MC.",
},
["981f20859e43e90c624fa1ff"] =
{
name = "ChatGrabberSlave1", version = 2.25, page = "http://zen.trekmush.org/ats/beta/",
filename = "ATS_ChatgrabberSlave1.xml", infopage = "http://zen.trekmush.org/chatgrabber/",
},
["d183a293b696885487d3ad83"] =
{
name = "ChatGrabberSlave2", version = 2.25, page = "http://zen.trekmush.org/ats/beta/",
filename = "ATS_ChatgrabberSlave2.xml", infopage = "http://zen.trekmush.org/chatgrabber/",
},
["8e3fd4f9c269365839520477"] =
{
name = "ATS_Navcomp", version = 1.63, page = "http://zen.trekmush.org/ats/beta/",
filename = "ATS_Navcomp.xml", infopage = "http://zen.trekmush.org/ats-navcomp/",
whatsnew = "Add Thieurull to conduit list.",
},
["1ec11b537d60054d832b896a"] =
{
name = "QUpdater", version = 0.93, page = "http://zen.trekmush.org/ats/beta/",
filename = "QUpdater.xml", infopage = "http://zen.trekmush.org/qupdater/",
},
["57a49cca2ef1da0b52498a94"] =
{
name = "ShieldStatus", version = 1.14, page = "http://zen.trekmush.org/ats/beta/",
filename = "ATS_ShieldStatus.xml",
requires = { "GMCP_handler.xml" },
whatsnew = "v1.14 - Now throttles data pulses when you are idling.",
},
["14f4885e803e076273a4767a"] =
{
name = "Paste_As_MUSH", version = 1.22, page = "http://zen.trekmush.org/ats/beta/",
filename = "Paste_As_MUSH.xml", infopage = nil,
},
["NavcompData"] =
{
name = "NavComp Database", version = 2.19, page = "http://zen.trekmush.org/ats/beta/",
filename = "atsdata.json", infopage = "http://zen.trekmush.org/ats-navcomp/",
},
["f92c816b178f0707847fcd1d"] =
{
name = "WeaponBar 2.0 ALPHA", version = 2.06, page = "http://zen.trekmush.org/ats/beta/",
filename = "ATS_WeaponBarTest.xml", infopage = nil,
whatsnew = "(2.0) Use the right-click menu to add/edit/delete buttons and bars.(v2.05) Added Preset-Save. New bars appear center screen.",
requires = { "DisruptorCannon.png", "TricobaltAft.png", "Tricobalt.png" },
},
--[[
["74f8c420df7d59ad5aa66246"] =
{
name = "GMCP ALPHA DO NOT INSTALL", version = 1.0, page = "http://zen.trekmush.org/ats/beta/",
filename = "GMCP_handler.xml", infopage = nil,
whatsnew = "Testing. Don't install without being told to do so.",
requires = { "gmcphelper.lua" },
},
--]]
}
--[[
ats_navcomp_info = {
plugin_version = "1.15",
db_version = "1.03",
release_date = "12/23/14 9:24am EDT",
release_url = "http://zen.trekmush.org/mediawiki/index.php/ATS_Nav_Comp_Plugin",
description = [==[
* (Pre-1.15)Added support for unofficial borders (e.g. QI'Tomer, Beeblebrox, etc.)
* (Pre-1.15)Debugmode can now be toggled by typing 'atsdebug' (defaults to off)
* (Pre-1.15)Some fixes here and there, including speed optimizations.
* (Pre-1.15)Added spam filter test code (only works if you don't have chatgrabber installed)
* (Pre-1.15)near sorts nearest objects by distance, from nearest to furthest
* (1.15) You can now click on planet names from the 'plot/from' command, to see nearby objects.
* (1.16) Fixed a few more bugs. Adds condense scan option. (Accessibility)
* (1.16) Lots of command name changes, see 'nchelp' to see the updated list.
* (1.16) Fixed stats tracker. You should do 'spacestats clear' after updating or weird things may happen.
* (1.16) Now filters Tractor spam as well -- Note if you have chatgrabber installed, it handles this function
* If you have chatgrabber installed, but do not have subspace going to a miniwindow, spam filtering WILL NOT WORK.
]==],
db_description = [==[
* Fixes
* Adds support for the unofficial borders.
*** DO NOT USE THIS DB WITH NON BETA NAVCOMP. IT WILL CRASH.
*** INFACT, YOU MAY CRASH UNLESS YOU UPDATE TO BETA 1.14!
]==],
}
--]]
|
mike347/ATSPlugins
|
versioninfo.lua
|
Lua
|
gpl-2.0
| 4,094
|
#ifndef _SCSI_SCSI_CMND_H
#define _SCSI_SCSI_CMND_H
#include <linux/dma-mapping.h>
#include <linux/blkdev.h>
#include <linux/list.h>
#include <linux/types.h>
#include <linux/timer.h>
#include <linux/scatterlist.h>
struct Scsi_Host;
struct scsi_device;
struct scsi_driver;
/*
* MAX_COMMAND_SIZE is:
* The longest fixed-length SCSI CDB as per the SCSI standard.
* fixed-length means: commands that their size can be determined
* by their opcode and the CDB does not carry a length specifier, (unlike
* the VARIABLE_LENGTH_CMD(0x7f) command). This is actually not exactly
* true and the SCSI standard also defines extended commands and
* vendor specific commands that can be bigger than 16 bytes. The kernel
* will support these using the same infrastructure used for VARLEN CDB's.
* So in effect MAX_COMMAND_SIZE means the maximum size command scsi-ml
* supports without specifying a cmd_len by ULD's
*/
#define MAX_COMMAND_SIZE 16
#if (MAX_COMMAND_SIZE > BLK_MAX_CDB)
# error MAX_COMMAND_SIZE can not be bigger than BLK_MAX_CDB
#endif
struct scsi_data_buffer {
struct sg_table table;
unsigned length;
int resid;
};
/* embedded in scsi_cmnd */
struct scsi_pointer {
char *ptr; /* data pointer */
int this_residual; /* left in this buffer */
struct scatterlist *buffer; /* which buffer */
int buffers_residual; /* how many buffers left */
dma_addr_t dma_handle;
volatile int Status;
volatile int Message;
volatile int have_data_in;
volatile int sent_command;
volatile int phase;
};
struct scsi_cmnd {
struct scsi_device *device;
struct list_head list; /* scsi_cmnd participates in queue lists */
struct list_head eh_entry; /* entry for the host eh_cmd_q */
int eh_eflags; /* Used by error handlr */
/*
* A SCSI Command is assigned a nonzero serial_number before passed
* to the driver's queue command function. The serial_number is
* cleared when scsi_done is entered indicating that the command
* has been completed. It is a bug for LLDDs to use this number
* for purposes other than printk (and even that is only useful
* for debugging).
*/
unsigned long serial_number;
/*
* This is set to jiffies as it was when the command was first
* allocated. It is used to time how long the command has
* been outstanding
*/
unsigned long jiffies_at_alloc;
int retries;
int allowed;
unsigned char prot_op;
unsigned char prot_type;
unsigned short cmd_len;
enum dma_data_direction sc_data_direction;
/* These elements define the operation we are about to perform */
unsigned char *cmnd;
/* These elements define the operation we ultimately want to perform */
struct scsi_data_buffer sdb;
struct scsi_data_buffer *prot_sdb;
unsigned underflow; /* Return error if less than
this amount is transferred */
unsigned transfersize; /* How much we are guaranteed to
transfer with each SCSI transfer
(ie, between disconnect /
reconnects. Probably == sector
size */
struct request *request; /* The command we are
working on */
#define SCSI_SENSE_BUFFERSIZE 96
unsigned char *sense_buffer;
/* obtained by REQUEST SENSE when
* CHECK CONDITION is received on original
* command (auto-sense) */
/* Low-level done function - can be used by low-level driver to point
* to completion function. Not used by mid/upper level code. */
void (*scsi_done) (struct scsi_cmnd *);
/*
* The following fields can be written to by the host specific code.
* Everything else should be left alone.
*/
struct scsi_pointer SCp; /* Scratchpad used by some host adapters */
unsigned char *host_scribble; /* The host adapter is allowed to
* call scsi_malloc and get some memory
* and hang it here. The host adapter
* is also expected to call scsi_free
* to release this memory. (The memory
* obtained by scsi_malloc is guaranteed
* to be at an address < 16Mb). */
int result; /* Status code from lower level driver */
unsigned char tag; /* SCSI-II queued command tag */
};
static inline struct scsi_driver *scsi_cmd_to_driver(struct scsi_cmnd *cmd)
{
return *(struct scsi_driver **)cmd->request->rq_disk->private_data;
}
extern struct scsi_cmnd *scsi_get_command(struct scsi_device *, gfp_t);
extern struct scsi_cmnd *__scsi_get_command(struct Scsi_Host *, gfp_t);
extern void scsi_put_command(struct scsi_cmnd *);
extern void __scsi_put_command(struct Scsi_Host *, struct scsi_cmnd *,
struct device *);
extern void scsi_finish_command(struct scsi_cmnd *cmd);
extern void *scsi_kmap_atomic_sg(struct scatterlist *sg, int sg_count,
size_t *offset, size_t *len);
extern void scsi_kunmap_atomic_sg(void *virt);
extern int scsi_init_io(struct scsi_cmnd *cmd, gfp_t gfp_mask);
extern void scsi_release_buffers(struct scsi_cmnd *cmd);
extern int scsi_dma_map(struct scsi_cmnd *cmd);
extern void scsi_dma_unmap(struct scsi_cmnd *cmd);
struct scsi_cmnd *scsi_allocate_command(gfp_t gfp_mask);
void scsi_free_command(gfp_t gfp_mask, struct scsi_cmnd *cmd);
static inline unsigned scsi_sg_count(struct scsi_cmnd *cmd)
{
return cmd->sdb.table.nents;
}
static inline struct scatterlist *scsi_sglist(struct scsi_cmnd *cmd)
{
return cmd->sdb.table.sgl;
}
static inline unsigned scsi_bufflen(struct scsi_cmnd *cmd)
{
return cmd->sdb.length;
}
static inline void scsi_set_resid(struct scsi_cmnd *cmd, int resid)
{
cmd->sdb.resid = resid;
}
static inline int scsi_get_resid(struct scsi_cmnd *cmd)
{
return cmd->sdb.resid;
}
#define scsi_for_each_sg(cmd, sg, nseg, __i) \
for_each_sg(scsi_sglist(cmd), sg, nseg, __i)
static inline int scsi_bidi_cmnd(struct scsi_cmnd *cmd)
{
return blk_bidi_rq(cmd->request) &&
(cmd->request->next_rq->special != NULL);
}
static inline struct scsi_data_buffer *scsi_in(struct scsi_cmnd *cmd)
{
return scsi_bidi_cmnd(cmd) ?
cmd->request->next_rq->special : &cmd->sdb;
}
static inline struct scsi_data_buffer *scsi_out(struct scsi_cmnd *cmd)
{
return &cmd->sdb;
}
static inline int scsi_sg_copy_from_buffer(struct scsi_cmnd *cmd,
void *buf, int buflen)
{
return sg_copy_from_buffer(scsi_sglist(cmd), scsi_sg_count(cmd),
buf, buflen);
}
static inline int scsi_sg_copy_to_buffer(struct scsi_cmnd *cmd,
void *buf, int buflen)
{
return sg_copy_to_buffer(scsi_sglist(cmd), scsi_sg_count(cmd),
buf, buflen);
}
/*
* The operations below are hints that tell the controller driver how
* to handle I/Os with DIF or similar types of protection information.
*/
enum scsi_prot_operations {
/* Normal I/O */
SCSI_PROT_NORMAL = 0,
/* OS-HBA: Protected, HBA-Target: Unprotected */
SCSI_PROT_READ_INSERT,
SCSI_PROT_WRITE_STRIP,
/* OS-HBA: Unprotected, HBA-Target: Protected */
SCSI_PROT_READ_STRIP,
SCSI_PROT_WRITE_INSERT,
/* OS-HBA: Protected, HBA-Target: Protected */
SCSI_PROT_READ_PASS,
SCSI_PROT_WRITE_PASS,
};
static inline void scsi_set_prot_op(struct scsi_cmnd *scmd, unsigned char op)
{
scmd->prot_op = op;
}
static inline unsigned char scsi_get_prot_op(struct scsi_cmnd *scmd)
{
return scmd->prot_op;
}
/*
* The controller usually does not know anything about the target it
* is communicating with. However, when DIX is enabled the controller
* must be know target type so it can verify the protection
* information passed along with the I/O.
*/
enum scsi_prot_target_type {
SCSI_PROT_DIF_TYPE0 = 0,
SCSI_PROT_DIF_TYPE1,
SCSI_PROT_DIF_TYPE2,
SCSI_PROT_DIF_TYPE3,
};
static inline void scsi_set_prot_type(struct scsi_cmnd *scmd, unsigned char type)
{
scmd->prot_type = type;
}
static inline unsigned char scsi_get_prot_type(struct scsi_cmnd *scmd)
{
return scmd->prot_type;
}
static inline sector_t scsi_get_lba(struct scsi_cmnd *scmd)
{
return blk_rq_pos(scmd->request);
}
static inline unsigned scsi_prot_sg_count(struct scsi_cmnd *cmd)
{
return cmd->prot_sdb ? cmd->prot_sdb->table.nents : 0;
}
static inline struct scatterlist *scsi_prot_sglist(struct scsi_cmnd *cmd)
{
return cmd->prot_sdb ? cmd->prot_sdb->table.sgl : NULL;
}
static inline struct scsi_data_buffer *scsi_prot(struct scsi_cmnd *cmd)
{
return cmd->prot_sdb;
}
#define scsi_for_each_prot_sg(cmd, sg, nseg, __i) \
for_each_sg(scsi_prot_sglist(cmd), sg, nseg, __i)
static inline void set_msg_byte(struct scsi_cmnd *cmd, char status)
{
cmd->result |= status << 8;
}
static inline void set_host_byte(struct scsi_cmnd *cmd, char status)
{
cmd->result |= status << 16;
}
static inline void set_driver_byte(struct scsi_cmnd *cmd, char status)
{
cmd->result |= status << 24;
}
#endif /* _SCSI_SCSI_CMND_H */
|
jthatch12/STi
|
include/scsi/scsi_cmnd.h
|
C
|
gpl-2.0
| 8,588
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_08) on Tue Jun 03 16:15:29 GMT-05:00 2008 -->
<TITLE>
Uses of Class soot.jimple.parser.node.TTransient (Soot API)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Class soot.jimple.parser.node.TTransient (Soot API)";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../soot/jimple/parser/node/TTransient.html" title="class in soot.jimple.parser.node"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?soot/jimple/parser/node//class-useTTransient.html" target="_top"><B>FRAMES</B></A>
<A HREF="TTransient.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>soot.jimple.parser.node.TTransient</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../soot/jimple/parser/node/TTransient.html" title="class in soot.jimple.parser.node">TTransient</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#soot.jimple.parser.analysis"><B>soot.jimple.parser.analysis</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#soot.jimple.parser.node"><B>soot.jimple.parser.node</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="soot.jimple.parser.analysis"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../soot/jimple/parser/node/TTransient.html" title="class in soot.jimple.parser.node">TTransient</A> in <A HREF="../../../../../soot/jimple/parser/analysis/package-summary.html">soot.jimple.parser.analysis</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../soot/jimple/parser/analysis/package-summary.html">soot.jimple.parser.analysis</A> with parameters of type <A HREF="../../../../../soot/jimple/parser/node/TTransient.html" title="class in soot.jimple.parser.node">TTransient</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>Analysis.</B><B><A HREF="../../../../../soot/jimple/parser/analysis/Analysis.html#caseTTransient(soot.jimple.parser.node.TTransient)">caseTTransient</A></B>(<A HREF="../../../../../soot/jimple/parser/node/TTransient.html" title="class in soot.jimple.parser.node">TTransient</A> node)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>AnalysisAdapter.</B><B><A HREF="../../../../../soot/jimple/parser/analysis/AnalysisAdapter.html#caseTTransient(soot.jimple.parser.node.TTransient)">caseTTransient</A></B>(<A HREF="../../../../../soot/jimple/parser/node/TTransient.html" title="class in soot.jimple.parser.node">TTransient</A> node)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<A NAME="soot.jimple.parser.node"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../soot/jimple/parser/node/TTransient.html" title="class in soot.jimple.parser.node">TTransient</A> in <A HREF="../../../../../soot/jimple/parser/node/package-summary.html">soot.jimple.parser.node</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../soot/jimple/parser/node/package-summary.html">soot.jimple.parser.node</A> that return <A HREF="../../../../../soot/jimple/parser/node/TTransient.html" title="class in soot.jimple.parser.node">TTransient</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../soot/jimple/parser/node/TTransient.html" title="class in soot.jimple.parser.node">TTransient</A></CODE></FONT></TD>
<TD><CODE><B>ATransientModifier.</B><B><A HREF="../../../../../soot/jimple/parser/node/ATransientModifier.html#getTransient()">getTransient</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../soot/jimple/parser/node/package-summary.html">soot.jimple.parser.node</A> with parameters of type <A HREF="../../../../../soot/jimple/parser/node/TTransient.html" title="class in soot.jimple.parser.node">TTransient</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ATransientModifier.</B><B><A HREF="../../../../../soot/jimple/parser/node/ATransientModifier.html#setTransient(soot.jimple.parser.node.TTransient)">setTransient</A></B>(<A HREF="../../../../../soot/jimple/parser/node/TTransient.html" title="class in soot.jimple.parser.node">TTransient</A> node)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Constructors in <A HREF="../../../../../soot/jimple/parser/node/package-summary.html">soot.jimple.parser.node</A> with parameters of type <A HREF="../../../../../soot/jimple/parser/node/TTransient.html" title="class in soot.jimple.parser.node">TTransient</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../soot/jimple/parser/node/ATransientModifier.html#ATransientModifier(soot.jimple.parser.node.TTransient)">ATransientModifier</A></B>(<A HREF="../../../../../soot/jimple/parser/node/TTransient.html" title="class in soot.jimple.parser.node">TTransient</A> _transient_)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../soot/jimple/parser/node/TTransient.html" title="class in soot.jimple.parser.node"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?soot/jimple/parser/node//class-useTTransient.html" target="_top"><B>FRAMES</B></A>
<A HREF="TTransient.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
|
BuddhaLabs/DeD-OSX
|
soot/soot-2.3.0/doc/soot/jimple/parser/node/class-use/TTransient.html
|
HTML
|
gpl-2.0
| 11,717
|
package Web::App::Screen;
use strict;
use Carp::Assert;
use Data::Dumper;
sub new {
my $class = shift;
my $id = shift;
my $self = {
'id' => $id,
'init-calls' => [],
'process-calls' => [],
'use-modules' => [],
'subscreens' => [],
# 'presentation' => ,
};
bless $self, $class;
return $self;
}
sub add_call {
my $self = shift;
my @functions = @_;
push @{$self -> {'init-calls'}}, @functions;
push @{$self -> {'process-calls'}}, @functions;
}
sub add_init_call {
my $self = shift;
my @functions = @_;
push @{$self -> {'init-calls'}}, @functions;
}
sub add_process_call {
my $self = shift;
my @functions = @_;
push @{ $self -> {'process-calls'} }, @functions;
}
sub add_use_module {
my $self = shift;
my @mod = @_;
push @{ $self -> {'use-modules'} }, @mod;
}
sub presentation_type {
my $self = shift;
my $received_type = shift;
if ( not defined $received_type ) {
return $self -> {presentation} {type};
} else {
assert( $received_type );
$self -> {presentation} {type} = $received_type;
}
}
sub presentation_file {
my $self = shift;
my $received_filename = shift;
if ( not defined $received_filename ) {
return $self -> {presentation} {file};
} else {
assert( $received_filename );
$self -> {presentation} {file} = $received_filename;
}
}
1;
|
kurmanka/acis.r
|
lib/Web/App/Screen.pm
|
Perl
|
gpl-2.0
| 1,412
|
/* $Id: pjsua_acc.c 5579 2017-04-07 04:00:30Z nanang $ */
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <pjsua-lib/pjsua.h>
#include <pjsua-lib/pjsua_internal.h>
#define THIS_FILE "pjsua_acc.c"
enum
{
OUTBOUND_UNKNOWN, // status unknown
OUTBOUND_WANTED, // initiated in registration
OUTBOUND_ACTIVE, // got positive response from server
OUTBOUND_NA // not wanted or got negative response from server
};
static void schedule_reregistration(pjsua_acc *acc);
static void keep_alive_timer_cb(pj_timer_heap_t *th, pj_timer_entry *te);
/*
* Get number of current accounts.
*/
PJ_DEF(unsigned) pjsua_acc_get_count(void)
{
return pjsua_var.acc_cnt;
}
/*
* Check if the specified account ID is valid.
*/
PJ_DEF(pj_bool_t) pjsua_acc_is_valid(pjsua_acc_id acc_id)
{
return acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc) &&
pjsua_var.acc[acc_id].valid;
}
/*
* Set default account
*/
PJ_DEF(pj_status_t) pjsua_acc_set_default(pjsua_acc_id acc_id)
{
pjsua_var.default_acc = acc_id;
return PJ_SUCCESS;
}
/*
* Get default account.
*/
PJ_DEF(pjsua_acc_id) pjsua_acc_get_default(void)
{
return pjsua_var.default_acc;
}
/*
* Copy account configuration.
*/
PJ_DEF(void) pjsua_acc_config_dup( pj_pool_t *pool,
pjsua_acc_config *dst,
const pjsua_acc_config *src)
{
unsigned i;
pj_memcpy(dst, src, sizeof(pjsua_acc_config));
pj_strdup_with_null(pool, &dst->id, &src->id);
pj_strdup_with_null(pool, &dst->reg_uri, &src->reg_uri);
pj_strdup_with_null(pool, &dst->force_contact, &src->force_contact);
pj_strdup_with_null(pool, &dst->reg_contact_params,
&src->reg_contact_params);
pj_strdup_with_null(pool, &dst->contact_params, &src->contact_params);
pj_strdup_with_null(pool, &dst->contact_uri_params,
&src->contact_uri_params);
pj_strdup_with_null(pool, &dst->pidf_tuple_id, &src->pidf_tuple_id);
pj_strdup_with_null(pool, &dst->rfc5626_instance_id,
&src->rfc5626_instance_id);
pj_strdup_with_null(pool, &dst->rfc5626_reg_id, &src->rfc5626_reg_id);
dst->proxy_cnt = src->proxy_cnt;
for (i=0; i<src->proxy_cnt; ++i)
pj_strdup_with_null(pool, &dst->proxy[i], &src->proxy[i]);
dst->reg_timeout = src->reg_timeout;
dst->reg_delay_before_refresh = src->reg_delay_before_refresh;
dst->cred_count = src->cred_count;
for (i=0; i<src->cred_count; ++i) {
pjsip_cred_dup(pool, &dst->cred_info[i], &src->cred_info[i]);
}
pj_list_init(&dst->reg_hdr_list);
if (!pj_list_empty(&src->reg_hdr_list)) {
const pjsip_hdr *hdr;
hdr = src->reg_hdr_list.next;
while (hdr != &src->reg_hdr_list) {
pj_list_push_back(&dst->reg_hdr_list, pjsip_hdr_clone(pool, hdr));
hdr = hdr->next;
}
}
pj_list_init(&dst->sub_hdr_list);
if (!pj_list_empty(&src->sub_hdr_list)) {
const pjsip_hdr *hdr;
hdr = src->sub_hdr_list.next;
while (hdr != &src->sub_hdr_list) {
pj_list_push_back(&dst->sub_hdr_list, pjsip_hdr_clone(pool, hdr));
hdr = hdr->next;
}
}
pjsip_auth_clt_pref_dup(pool, &dst->auth_pref, &src->auth_pref);
pjsua_transport_config_dup(pool, &dst->rtp_cfg, &src->rtp_cfg);
pjsua_ice_config_dup(pool, &dst->ice_cfg, &src->ice_cfg);
pjsua_turn_config_dup(pool, &dst->turn_cfg, &src->turn_cfg);
pj_strdup(pool, &dst->ka_data, &src->ka_data);
}
/*
* Calculate CRC of proxy list.
*/
static pj_uint32_t calc_proxy_crc(const pj_str_t proxy[], pj_size_t cnt)
{
pj_crc32_context ctx;
unsigned i;
pj_crc32_init(&ctx);
for (i=0; i<cnt; ++i) {
pj_crc32_update(&ctx, (pj_uint8_t*)proxy[i].ptr, proxy[i].slen);
}
return pj_crc32_final(&ctx);
}
/*
* Initialize a new account (after configuration is set).
*/
static pj_status_t initialize_acc(unsigned acc_id)
{
pjsua_acc_config *acc_cfg = &pjsua_var.acc[acc_id].cfg;
pjsua_acc *acc = &pjsua_var.acc[acc_id];
pjsip_name_addr *name_addr;
pjsip_sip_uri *sip_reg_uri;
pj_status_t status;
unsigned i;
/* Need to parse local_uri to get the elements: */
name_addr = (pjsip_name_addr*)
pjsip_parse_uri(acc->pool, acc_cfg->id.ptr,
acc_cfg->id.slen,
PJSIP_PARSE_URI_AS_NAMEADDR);
if (name_addr == NULL) {
pjsua_perror(THIS_FILE, "Invalid local URI",
PJSIP_EINVALIDURI);
return PJSIP_EINVALIDURI;
}
/* Local URI MUST be a SIP or SIPS: */
if (!PJSIP_URI_SCHEME_IS_SIP(name_addr) &&
!PJSIP_URI_SCHEME_IS_SIPS(name_addr))
{
acc->display = name_addr->display;
acc->user_part = name_addr->display;
acc->srv_domain = pj_str("");
acc->srv_port = 0;
} else {
pjsip_sip_uri *sip_uri;
/* Get the SIP URI object: */
sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(name_addr);
/* Save the user and domain part. These will be used when finding an
* account for incoming requests.
*/
acc->display = name_addr->display;
acc->user_part = sip_uri->user;
acc->srv_domain = sip_uri->host;
acc->srv_port = 0;
/* Escape user part (ticket #2010) */
if (acc->user_part.slen) {
const pjsip_parser_const_t *pconst;
char buf[PJSIP_MAX_URL_SIZE];
pj_str_t user_part;
pconst = pjsip_parser_const();
pj_strset(&user_part, buf, sizeof(buf));
pj_strncpy_escape(&user_part, &sip_uri->user, sizeof(buf),
&pconst->pjsip_USER_SPEC_LENIENT);
if (user_part.slen > acc->user_part.slen)
pj_strdup(acc->pool, &acc->user_part, &user_part);
}
}
acc->is_sips = PJSIP_URI_SCHEME_IS_SIPS(name_addr);
/* Parse registrar URI, if any */
if (acc_cfg->reg_uri.slen) {
pjsip_uri *reg_uri;
reg_uri = pjsip_parse_uri(acc->pool, acc_cfg->reg_uri.ptr,
acc_cfg->reg_uri.slen, 0);
if (reg_uri == NULL) {
pjsua_perror(THIS_FILE, "Invalid registrar URI",
PJSIP_EINVALIDURI);
return PJSIP_EINVALIDURI;
}
/* Registrar URI MUST be a SIP or SIPS: */
if (!PJSIP_URI_SCHEME_IS_SIP(reg_uri) &&
!PJSIP_URI_SCHEME_IS_SIPS(reg_uri))
{
pjsua_perror(THIS_FILE, "Invalid registar URI",
PJSIP_EINVALIDSCHEME);
return PJSIP_EINVALIDSCHEME;
}
sip_reg_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(reg_uri);
} else {
sip_reg_uri = NULL;
}
if (sip_reg_uri) {
acc->srv_port = sip_reg_uri->port;
}
/* Create Contact header if not present. */
//if (acc_cfg->contact.slen == 0) {
// acc_cfg->contact = acc_cfg->id;
//}
/* Build account route-set from outbound proxies and route set from
* account configuration.
*/
pj_list_init(&acc->route_set);
if (!pj_list_empty(&pjsua_var.outbound_proxy)) {
pjsip_route_hdr *r;
r = pjsua_var.outbound_proxy.next;
while (r != &pjsua_var.outbound_proxy) {
pj_list_push_back(&acc->route_set,
pjsip_hdr_shallow_clone(acc->pool, r));
r = r->next;
}
}
for (i=0; i<acc_cfg->proxy_cnt; ++i) {
pj_str_t hname = { "Route", 5};
pjsip_route_hdr *r;
pj_str_t tmp;
pj_strdup_with_null(acc->pool, &tmp, &acc_cfg->proxy[i]);
r = (pjsip_route_hdr*)
pjsip_parse_hdr(acc->pool, &hname, tmp.ptr, tmp.slen, NULL);
if (r == NULL) {
pjsua_perror(THIS_FILE, "Invalid URI in account route set",
PJ_EINVAL);
return PJ_EINVAL;
}
pj_list_push_back(&acc->route_set, r);
}
/* Concatenate credentials from account config and global config */
acc->cred_cnt = 0;
for (i=0; i<acc_cfg->cred_count; ++i) {
acc->cred[acc->cred_cnt++] = acc_cfg->cred_info[i];
}
for (i=0; i<pjsua_var.ua_cfg.cred_count &&
acc->cred_cnt < PJ_ARRAY_SIZE(acc->cred); ++i)
{
acc->cred[acc->cred_cnt++] = pjsua_var.ua_cfg.cred_info[i];
}
/* If account's ICE and TURN customization is not set, then
* initialize it with the settings from the global media config.
*/
if (acc->cfg.ice_cfg_use == PJSUA_ICE_CONFIG_USE_DEFAULT) {
pjsua_ice_config_from_media_config(NULL, &acc->cfg.ice_cfg,
&pjsua_var.media_cfg);
}
if (acc->cfg.turn_cfg_use == PJSUA_TURN_CONFIG_USE_DEFAULT) {
pjsua_turn_config_from_media_config(NULL, &acc->cfg.turn_cfg,
&pjsua_var.media_cfg);
}
/* If ICE is enabled, add "+sip.ice" media feature tag in account's
* contact params.
*/
#if PJSUA_ADD_ICE_TAGS
if (acc_cfg->ice_cfg.enable_ice) {
pj_ssize_t new_len;
pj_str_t new_prm;
new_len = acc_cfg->contact_params.slen + 10;
new_prm.ptr = (char*)pj_pool_alloc(acc->pool, new_len);
pj_strcpy(&new_prm, &acc_cfg->contact_params);
pj_strcat2(&new_prm, ";+sip.ice");
acc_cfg->contact_params = new_prm;
}
#endif
status = pjsua_pres_init_acc(acc_id);
if (status != PJ_SUCCESS)
return status;
/* If SIP outbound is enabled, generate instance and reg ID if they are
* not specified
*/
if (acc_cfg->use_rfc5626) {
if (acc_cfg->rfc5626_instance_id.slen==0) {
const pj_str_t *hostname;
pj_uint32_t hval;
pj_size_t pos;
char instprm[] = ";+sip.instance=\"<urn:uuid:00000000-0000-0000-0000-0000CCDDEEFF>\"";
hostname = pj_gethostname();
pos = pj_ansi_strlen(instprm) - 10;
hval = pj_hash_calc(0, hostname->ptr, (unsigned)hostname->slen);
pj_val_to_hex_digit( ((char*)&hval)[0], instprm+pos+0);
pj_val_to_hex_digit( ((char*)&hval)[1], instprm+pos+2);
pj_val_to_hex_digit( ((char*)&hval)[2], instprm+pos+4);
pj_val_to_hex_digit( ((char*)&hval)[3], instprm+pos+6);
pj_strdup2(acc->pool, &acc->rfc5626_instprm, instprm);
} else {
const char *prmname = ";+sip.instance=\"";
pj_size_t len;
len = pj_ansi_strlen(prmname) + acc_cfg->rfc5626_instance_id.slen + 1;
acc->rfc5626_instprm.ptr = (char*)pj_pool_alloc(acc->pool, len+1);
pj_ansi_snprintf(acc->rfc5626_instprm.ptr, len+1,
"%s%.*s\"",
prmname,
(int)acc_cfg->rfc5626_instance_id.slen,
acc_cfg->rfc5626_instance_id.ptr);
acc->rfc5626_instprm.slen = len;
}
if (acc_cfg->rfc5626_reg_id.slen==0) {
acc->rfc5626_regprm = pj_str(";reg-id=1");
} else {
const char *prmname = ";reg-id=";
pj_size_t len;
len = pj_ansi_strlen(prmname) + acc_cfg->rfc5626_reg_id.slen;
acc->rfc5626_regprm.ptr = (char*)pj_pool_alloc(acc->pool, len+1);
pj_ansi_snprintf(acc->rfc5626_regprm.ptr, len+1,
"%s%.*s\"",
prmname,
(int)acc_cfg->rfc5626_reg_id.slen,
acc_cfg->rfc5626_reg_id.ptr);
acc->rfc5626_regprm.slen = len;
}
acc->rfc5626_status = OUTBOUND_WANTED;
}
/* Mark account as valid */
pjsua_var.acc[acc_id].valid = PJ_TRUE;
/* Insert account ID into account ID array, sorted by priority */
for (i=0; i<pjsua_var.acc_cnt; ++i) {
if ( pjsua_var.acc[pjsua_var.acc_ids[i]].cfg.priority <
pjsua_var.acc[acc_id].cfg.priority)
{
break;
}
}
pj_array_insert(pjsua_var.acc_ids, sizeof(pjsua_var.acc_ids[0]),
pjsua_var.acc_cnt, i, &acc_id);
if (acc_cfg->transport_id != PJSUA_INVALID_ID)
acc->tp_type = pjsua_var.tpdata[acc_cfg->transport_id].type;
return PJ_SUCCESS;
}
/*
* Add a new account to pjsua.
*/
PJ_DEF(pj_status_t) pjsua_acc_add( const pjsua_acc_config *cfg,
pj_bool_t is_default,
pjsua_acc_id *p_acc_id)
{
pjsua_acc *acc;
unsigned i, id;
pj_status_t status = PJ_SUCCESS;
PJ_ASSERT_RETURN(cfg, PJ_EINVAL);
PJ_ASSERT_RETURN(pjsua_var.acc_cnt < PJ_ARRAY_SIZE(pjsua_var.acc),
PJ_ETOOMANY);
/* Must have a transport */
PJ_ASSERT_RETURN(pjsua_var.tpdata[0].data.ptr != NULL, PJ_EINVALIDOP);
PJ_LOG(4,(THIS_FILE, "Adding account: id=%.*s",
(int)cfg->id.slen, cfg->id.ptr));
pj_log_push_indent();
PJSUA_LOCK();
/* Find empty account id. */
for (id=0; id < PJ_ARRAY_SIZE(pjsua_var.acc); ++id) {
if (pjsua_var.acc[id].valid == PJ_FALSE)
break;
}
/* Expect to find a slot */
PJ_ASSERT_ON_FAIL( id < PJ_ARRAY_SIZE(pjsua_var.acc),
{PJSUA_UNLOCK(); return PJ_EBUG;});
acc = &pjsua_var.acc[id];
/* Create pool for this account. */
if (acc->pool)
pj_pool_reset(acc->pool);
else
acc->pool = pjsua_pool_create("acc%p", 512, 256);
/* Copy config */
pjsua_acc_config_dup(acc->pool, &pjsua_var.acc[id].cfg, cfg);
/* Normalize registration timeout and refresh delay */
if (pjsua_var.acc[id].cfg.reg_uri.slen) {
if (pjsua_var.acc[id].cfg.reg_timeout == 0) {
pjsua_var.acc[id].cfg.reg_timeout = PJSUA_REG_INTERVAL;
}
if (pjsua_var.acc[id].cfg.reg_delay_before_refresh == 0) {
pjsua_var.acc[id].cfg.reg_delay_before_refresh =
PJSIP_REGISTER_CLIENT_DELAY_BEFORE_REFRESH;
}
}
/* Check the route URI's and force loose route if required */
for (i=0; i<acc->cfg.proxy_cnt; ++i) {
status = normalize_route_uri(acc->pool, &acc->cfg.proxy[i]);
if (status != PJ_SUCCESS) {
PJSUA_UNLOCK();
pj_log_pop_indent();
return status;
}
}
/* Get CRC of account proxy setting */
acc->local_route_crc = calc_proxy_crc(acc->cfg.proxy, acc->cfg.proxy_cnt);
/* Get CRC of global outbound proxy setting */
acc->global_route_crc=calc_proxy_crc(pjsua_var.ua_cfg.outbound_proxy,
pjsua_var.ua_cfg.outbound_proxy_cnt);
status = initialize_acc(id);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Error adding account", status);
pj_pool_release(acc->pool);
acc->pool = NULL;
PJSUA_UNLOCK();
pj_log_pop_indent();
return status;
}
if (is_default)
pjsua_var.default_acc = id;
if (p_acc_id)
*p_acc_id = id;
pjsua_var.acc_cnt++;
PJSUA_UNLOCK();
PJ_LOG(4,(THIS_FILE, "Account %.*s added with id %d",
(int)cfg->id.slen, cfg->id.ptr, id));
/* If accounts has registration enabled, start registration */
if (pjsua_var.acc[id].cfg.reg_uri.slen) {
if (pjsua_var.acc[id].cfg.register_on_acc_add)
pjsua_acc_set_registration(id, PJ_TRUE);
} else {
/* Otherwise subscribe to MWI, if it's enabled */
if (pjsua_var.acc[id].cfg.mwi_enabled)
pjsua_start_mwi(id, PJ_TRUE);
/* Start publish too */
if (acc->cfg.publish_enabled)
pjsua_pres_init_publish_acc(id);
}
pj_log_pop_indent();
return PJ_SUCCESS;
}
/*
* Add local account
*/
PJ_DEF(pj_status_t) pjsua_acc_add_local( pjsua_transport_id tid,
pj_bool_t is_default,
pjsua_acc_id *p_acc_id)
{
pjsua_acc_config cfg;
pjsua_transport_data *t = &pjsua_var.tpdata[tid];
const char *beginquote, *endquote;
char transport_param[32];
char uri[PJSIP_MAX_URL_SIZE];
pjsua_acc_id acc_id;
pj_status_t status;
/* ID must be valid */
PJ_ASSERT_RETURN(tid>=0 && tid<(int)PJ_ARRAY_SIZE(pjsua_var.tpdata),
PJ_EINVAL);
/* Transport must be valid */
PJ_ASSERT_RETURN(t->data.ptr != NULL, PJ_EINVAL);
pjsua_acc_config_default(&cfg);
/* Lower the priority of local account */
--cfg.priority;
/* Enclose IPv6 address in square brackets */
if (t->type & PJSIP_TRANSPORT_IPV6) {
beginquote = "[";
endquote = "]";
} else {
beginquote = endquote = "";
}
/* Don't add transport parameter if it's UDP */
if (t->type!=PJSIP_TRANSPORT_UDP && t->type!=PJSIP_TRANSPORT_UDP6) {
pj_ansi_snprintf(transport_param, sizeof(transport_param),
";transport=%s",
pjsip_transport_get_type_name(t->type));
} else {
transport_param[0] = '\0';
}
/* Build URI for the account */
pj_ansi_snprintf(uri, PJSIP_MAX_URL_SIZE,
"<sip:%s%.*s%s:%d%s>",
beginquote,
(int)t->local_name.host.slen,
t->local_name.host.ptr,
endquote,
t->local_name.port,
transport_param);
cfg.id = pj_str(uri);
status = pjsua_acc_add(&cfg, is_default, &acc_id);
if (status == PJ_SUCCESS) {
pjsua_var.acc[acc_id].tp_type = t->type;
if (p_acc_id)
*p_acc_id = acc_id;
}
return status;
}
/*
* Set arbitrary data to be associated with the account.
*/
PJ_DEF(pj_status_t) pjsua_acc_set_user_data(pjsua_acc_id acc_id,
void *user_data)
{
PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc),
PJ_EINVAL);
PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, PJ_EINVALIDOP);
PJSUA_LOCK();
pjsua_var.acc[acc_id].cfg.user_data = user_data;
PJSUA_UNLOCK();
return PJ_SUCCESS;
}
/*
* Retrieve arbitrary data associated with the account.
*/
PJ_DEF(void*) pjsua_acc_get_user_data(pjsua_acc_id acc_id)
{
PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc),
NULL);
PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, NULL);
return pjsua_var.acc[acc_id].cfg.user_data;
}
/*
* Delete account.
*/
PJ_DEF(pj_status_t) pjsua_acc_del(pjsua_acc_id acc_id)
{
pjsua_acc *acc;
unsigned i;
PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc),
PJ_EINVAL);
PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, PJ_EINVALIDOP);
PJ_LOG(4,(THIS_FILE, "Deleting account %d..", acc_id));
pj_log_push_indent();
PJSUA_LOCK();
acc = &pjsua_var.acc[acc_id];
/* Cancel keep-alive timer, if any */
if (acc->ka_timer.id) {
pjsip_endpt_cancel_timer(pjsua_var.endpt, &acc->ka_timer);
acc->ka_timer.id = PJ_FALSE;
}
if (acc->ka_transport) {
pjsip_transport_dec_ref(acc->ka_transport);
acc->ka_transport = NULL;
}
/* Cancel any re-registration timer */
if (acc->auto_rereg.timer.id) {
acc->auto_rereg.timer.id = PJ_FALSE;
pjsua_cancel_timer(&acc->auto_rereg.timer);
}
/* Delete registration */
if (acc->regc != NULL) {
pjsua_acc_set_registration(acc_id, PJ_FALSE);
if (acc->regc) {
pjsip_regc_destroy(acc->regc);
}
acc->regc = NULL;
}
/* Terminate mwi subscription */
if (acc->cfg.mwi_enabled) {
acc->cfg.mwi_enabled = PJ_FALSE;
pjsua_start_mwi(acc_id, PJ_FALSE);
}
/* Delete server presence subscription */
pjsua_pres_delete_acc(acc_id, 0);
/* Release account pool */
if (acc->pool) {
pj_pool_release(acc->pool);
acc->pool = NULL;
}
/* Invalidate */
acc->valid = PJ_FALSE;
acc->contact.slen = 0;
acc->reg_mapped_addr.slen = 0;
acc->rfc5626_status = OUTBOUND_UNKNOWN;
pj_bzero(&acc->via_addr, sizeof(acc->via_addr));
acc->via_tp = NULL;
acc->next_rtp_port = 0;
/* Remove from array */
for (i=0; i<pjsua_var.acc_cnt; ++i) {
if (pjsua_var.acc_ids[i] == acc_id)
break;
}
if (i != pjsua_var.acc_cnt) {
pj_array_erase(pjsua_var.acc_ids, sizeof(pjsua_var.acc_ids[0]),
pjsua_var.acc_cnt, i);
--pjsua_var.acc_cnt;
}
/* Leave the calls intact, as I don't think calls need to
* access account once it's created
*/
/* Update default account */
if (pjsua_var.default_acc == acc_id)
pjsua_var.default_acc = 0;
PJSUA_UNLOCK();
PJ_LOG(4,(THIS_FILE, "Account id %d deleted", acc_id));
pj_log_pop_indent();
return PJ_SUCCESS;
}
/* Get config */
PJ_DEF(pj_status_t) pjsua_acc_get_config(pjsua_acc_id acc_id,
pj_pool_t *pool,
pjsua_acc_config *acc_cfg)
{
PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc)
&& pjsua_var.acc[acc_id].valid, PJ_EINVAL);
//this now would not work due to corrupt header list
//pj_memcpy(acc_cfg, &pjsua_var.acc[acc_id].cfg, sizeof(*acc_cfg));
pjsua_acc_config_dup(pool, acc_cfg, &pjsua_var.acc[acc_id].cfg);
return PJ_SUCCESS;
}
/* Compare two SIP headers. Return zero if equal */
static int pjsip_hdr_cmp(const pjsip_hdr *h1, const pjsip_hdr *h2)
{
char buf1[PJSIP_MAX_URL_SIZE];
char buf2[PJSIP_MAX_URL_SIZE];
pj_str_t p1, p2;
p1.ptr = buf1;
p1.slen = 0;
p2.ptr = buf2;
p2.slen = 0;
p1.slen = pjsip_hdr_print_on((void*)h1, buf1, sizeof(buf1));
if (p1.slen < 0)
p1.slen = 0;
p2.slen = pjsip_hdr_print_on((void*)h2, buf2, sizeof(buf2));
if (p2.slen < 0)
p2.slen = 0;
return pj_strcmp(&p1, &p2);
}
/* Update SIP header list from another list. Return PJ_TRUE if
* the list has been updated */
static pj_bool_t update_hdr_list(pj_pool_t *pool, pjsip_hdr *dst,
const pjsip_hdr *src)
{
pjsip_hdr *dst_i;
const pjsip_hdr *src_i;
pj_bool_t changed = PJ_FALSE;
/* Remove header that's no longer needed */
for (dst_i = dst->next; dst_i != dst; ) {
for (src_i = src->next; src_i != src; src_i = src_i->next) {
if (pjsip_hdr_cmp(dst_i, src_i) == 0)
break;
}
if (src_i == src) {
pjsip_hdr *next = dst_i->next;
pj_list_erase(dst_i);
changed = PJ_TRUE;
dst_i = next;
} else {
dst_i = dst_i->next;
}
}
/* Add new header */
for (src_i = src->next; src_i != src; src_i = src_i->next) {
for (dst_i = dst->next; dst_i != dst; dst_i = dst_i->next) {
if (pjsip_hdr_cmp(dst_i, src_i) == 0)
break;
}
if (dst_i == dst) {
dst_i = pjsip_hdr_clone(pool, src_i);
pj_list_push_back(dst, dst_i);
changed = PJ_TRUE;
}
}
return changed;
}
/*
* Modify account information.
*/
PJ_DEF(pj_status_t) pjsua_acc_modify( pjsua_acc_id acc_id,
const pjsua_acc_config *cfg)
{
pjsua_acc *acc;
pjsip_name_addr *id_name_addr = NULL;
pjsip_sip_uri *id_sip_uri = NULL;
pjsip_sip_uri *reg_sip_uri = NULL;
pj_uint32_t local_route_crc, global_route_crc;
pjsip_route_hdr global_route;
pjsip_route_hdr local_route;
pj_str_t acc_proxy[PJSUA_ACC_MAX_PROXIES];
pj_bool_t update_reg = PJ_FALSE;
pj_bool_t unreg_first = PJ_FALSE;
pj_bool_t update_mwi = PJ_FALSE;
pj_status_t status = PJ_SUCCESS;
PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc),
PJ_EINVAL);
PJ_LOG(4,(THIS_FILE, "Modifying account %d", acc_id));
pj_log_push_indent();
PJSUA_LOCK();
acc = &pjsua_var.acc[acc_id];
if (!acc->valid) {
status = PJ_EINVAL;
goto on_return;
}
/* == Validate first == */
/* Account id */
if (pj_strcmp(&acc->cfg.id, &cfg->id)) {
/* Need to parse id to get the elements: */
id_name_addr = (pjsip_name_addr*)
pjsip_parse_uri(acc->pool, cfg->id.ptr, cfg->id.slen,
PJSIP_PARSE_URI_AS_NAMEADDR);
if (id_name_addr == NULL) {
status = PJSIP_EINVALIDURI;
pjsua_perror(THIS_FILE, "Invalid local URI", status);
goto on_return;
}
/* URI MUST be a SIP or SIPS: */
if (!PJSIP_URI_SCHEME_IS_SIP(id_name_addr) &&
!PJSIP_URI_SCHEME_IS_SIPS(id_name_addr))
{
status = PJSIP_EINVALIDSCHEME;
pjsua_perror(THIS_FILE, "Invalid local URI", status);
goto on_return;
}
/* Get the SIP URI object: */
id_sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(id_name_addr);
}
/* Registrar URI */
if (pj_strcmp(&acc->cfg.reg_uri, &cfg->reg_uri) && cfg->reg_uri.slen) {
pjsip_uri *reg_uri;
/* Need to parse reg_uri to get the elements: */
reg_uri = pjsip_parse_uri(acc->pool, cfg->reg_uri.ptr,
cfg->reg_uri.slen, 0);
if (reg_uri == NULL) {
status = PJSIP_EINVALIDURI;
pjsua_perror(THIS_FILE, "Invalid registrar URI", status);
goto on_return;
}
/* Registrar URI MUST be a SIP or SIPS: */
if (!PJSIP_URI_SCHEME_IS_SIP(reg_uri) &&
!PJSIP_URI_SCHEME_IS_SIPS(reg_uri))
{
status = PJSIP_EINVALIDSCHEME;
pjsua_perror(THIS_FILE, "Invalid registar URI", status);
goto on_return;
}
reg_sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(reg_uri);
}
/* REGISTER header list */
if (update_hdr_list(acc->pool, &acc->cfg.reg_hdr_list, &cfg->reg_hdr_list)) {
update_reg = PJ_TRUE;
unreg_first = PJ_TRUE;
}
/* SUBSCRIBE header list */
update_hdr_list(acc->pool, &acc->cfg.sub_hdr_list, &cfg->sub_hdr_list);
/* Global outbound proxy */
global_route_crc = calc_proxy_crc(pjsua_var.ua_cfg.outbound_proxy,
pjsua_var.ua_cfg.outbound_proxy_cnt);
if (global_route_crc != acc->global_route_crc) {
pjsip_route_hdr *r;
/* Copy from global outbound proxies */
pj_list_init(&global_route);
r = pjsua_var.outbound_proxy.next;
while (r != &pjsua_var.outbound_proxy) {
pj_list_push_back(&global_route,
pjsip_hdr_shallow_clone(acc->pool, r));
r = r->next;
}
}
/* Account proxy */
local_route_crc = calc_proxy_crc(cfg->proxy, cfg->proxy_cnt);
if (local_route_crc != acc->local_route_crc) {
pjsip_route_hdr *r;
unsigned i;
/* Validate the local route and save it to temporary var */
pj_list_init(&local_route);
for (i=0; i<cfg->proxy_cnt; ++i) {
pj_str_t hname = { "Route", 5};
pj_strdup_with_null(acc->pool, &acc_proxy[i], &cfg->proxy[i]);
status = normalize_route_uri(acc->pool, &acc_proxy[i]);
if (status != PJ_SUCCESS)
goto on_return;
r = (pjsip_route_hdr*)
pjsip_parse_hdr(acc->pool, &hname, acc_proxy[i].ptr,
acc_proxy[i].slen, NULL);
if (r == NULL) {
status = PJSIP_EINVALIDURI;
pjsua_perror(THIS_FILE, "Invalid URI in account route set",
status);
goto on_return;
}
pj_list_push_back(&local_route, r);
}
/* Recalculate the CRC again after route URI normalization */
local_route_crc = calc_proxy_crc(acc_proxy, cfg->proxy_cnt);
}
/* == Apply the new config == */
/* Account ID. */
if (id_name_addr && id_sip_uri) {
pj_strdup_with_null(acc->pool, &acc->cfg.id, &cfg->id);
pj_strdup_with_null(acc->pool, &acc->display, &id_name_addr->display);
pj_strdup_with_null(acc->pool, &acc->user_part, &id_sip_uri->user);
pj_strdup_with_null(acc->pool, &acc->srv_domain, &id_sip_uri->host);
acc->srv_port = 0;
acc->is_sips = PJSIP_URI_SCHEME_IS_SIPS(id_name_addr);
update_reg = PJ_TRUE;
unreg_first = PJ_TRUE;
}
/* User data */
acc->cfg.user_data = cfg->user_data;
/* Priority */
if (acc->cfg.priority != cfg->priority) {
unsigned i;
acc->cfg.priority = cfg->priority;
/* Resort accounts priority */
for (i=0; i<pjsua_var.acc_cnt; ++i) {
if (pjsua_var.acc_ids[i] == acc_id)
break;
}
pj_assert(i < pjsua_var.acc_cnt);
pj_array_erase(pjsua_var.acc_ids, sizeof(acc_id),
pjsua_var.acc_cnt, i);
for (i=0; i<pjsua_var.acc_cnt; ++i) {
if (pjsua_var.acc[pjsua_var.acc_ids[i]].cfg.priority <
acc->cfg.priority)
{
break;
}
}
pj_array_insert(pjsua_var.acc_ids, sizeof(acc_id),
pjsua_var.acc_cnt, i, &acc_id);
}
/* MWI */
if (acc->cfg.mwi_enabled != cfg->mwi_enabled) {
acc->cfg.mwi_enabled = cfg->mwi_enabled;
update_mwi = PJ_TRUE;
}
if (acc->cfg.mwi_expires != cfg->mwi_expires && cfg->mwi_expires > 0) {
acc->cfg.mwi_expires = cfg->mwi_expires;
update_mwi = PJ_TRUE;
}
/* PIDF tuple ID */
if (pj_strcmp(&acc->cfg.pidf_tuple_id, &cfg->pidf_tuple_id))
pj_strdup_with_null(acc->pool, &acc->cfg.pidf_tuple_id,
&cfg->pidf_tuple_id);
/* Publish */
acc->cfg.publish_opt = cfg->publish_opt;
acc->cfg.unpublish_max_wait_time_msec = cfg->unpublish_max_wait_time_msec;
if (acc->cfg.publish_enabled != cfg->publish_enabled) {
acc->cfg.publish_enabled = cfg->publish_enabled;
if (!acc->cfg.publish_enabled)
pjsua_pres_unpublish(acc, 0);
else
update_reg = PJ_TRUE;
}
/* Force contact URI */
if (pj_strcmp(&acc->cfg.force_contact, &cfg->force_contact)) {
pj_strdup_with_null(acc->pool, &acc->cfg.force_contact,
&cfg->force_contact);
update_reg = PJ_TRUE;
unreg_first = PJ_TRUE;
}
/* Register contact params */
if (pj_strcmp(&acc->cfg.reg_contact_params, &cfg->reg_contact_params)) {
pj_strdup_with_null(acc->pool, &acc->cfg.reg_contact_params,
&cfg->reg_contact_params);
update_reg = PJ_TRUE;
}
/* Contact param */
if (pj_strcmp(&acc->cfg.contact_params, &cfg->contact_params)) {
pj_strdup_with_null(acc->pool, &acc->cfg.contact_params,
&cfg->contact_params);
update_reg = PJ_TRUE;
}
/* Contact URI params */
if (pj_strcmp(&acc->cfg.contact_uri_params, &cfg->contact_uri_params)) {
pj_strdup_with_null(acc->pool, &acc->cfg.contact_uri_params,
&cfg->contact_uri_params);
update_reg = PJ_TRUE;
}
/* Reliable provisional response */
acc->cfg.require_100rel = cfg->require_100rel;
/* Session timer */
acc->cfg.use_timer = cfg->use_timer;
acc->cfg.timer_setting = cfg->timer_setting;
/* Transport */
if (acc->cfg.transport_id != cfg->transport_id) {
acc->cfg.transport_id = cfg->transport_id;
update_reg = PJ_TRUE;
unreg_first = PJ_TRUE;
}
/* Update keep-alive */
if (acc->cfg.ka_interval != cfg->ka_interval ||
pj_strcmp(&acc->cfg.ka_data, &cfg->ka_data))
{
pjsip_transport *ka_transport = acc->ka_transport;
if (acc->ka_timer.id) {
pjsip_endpt_cancel_timer(pjsua_var.endpt, &acc->ka_timer);
acc->ka_timer.id = PJ_FALSE;
}
if (acc->ka_transport) {
pjsip_transport_dec_ref(acc->ka_transport);
acc->ka_transport = NULL;
}
acc->cfg.ka_interval = cfg->ka_interval;
if (cfg->ka_interval) {
if (ka_transport) {
/* Keep-alive has been running so we can just restart it */
pj_time_val delay;
pjsip_transport_add_ref(ka_transport);
acc->ka_transport = ka_transport;
acc->ka_timer.cb = &keep_alive_timer_cb;
acc->ka_timer.user_data = (void*)acc;
delay.sec = acc->cfg.ka_interval;
delay.msec = 0;
status = pjsua_schedule_timer(&acc->ka_timer, &delay);
if (status == PJ_SUCCESS) {
acc->ka_timer.id = PJ_TRUE;
} else {
pjsip_transport_dec_ref(ka_transport);
acc->ka_transport = NULL;
pjsua_perror(THIS_FILE, "Error starting keep-alive timer",
status);
}
} else {
/* Keep-alive has not been running, we need to (re)register
* first.
*/
update_reg = PJ_TRUE;
}
}
}
if (pj_strcmp(&acc->cfg.ka_data, &cfg->ka_data))
pj_strdup(acc->pool, &acc->cfg.ka_data, &cfg->ka_data);
#if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0)
acc->cfg.use_srtp = cfg->use_srtp;
acc->cfg.srtp_secure_signaling = cfg->srtp_secure_signaling;
acc->cfg.srtp_optional_dup_offer = cfg->srtp_optional_dup_offer;
#endif
#if defined(PJMEDIA_STREAM_ENABLE_KA) && (PJMEDIA_STREAM_ENABLE_KA != 0)
acc->cfg.use_stream_ka = cfg->use_stream_ka;
#endif
/* Use of proxy */
if (acc->cfg.reg_use_proxy != cfg->reg_use_proxy) {
acc->cfg.reg_use_proxy = cfg->reg_use_proxy;
update_reg = PJ_TRUE;
unreg_first = PJ_TRUE;
}
/* Global outbound proxy */
if (global_route_crc != acc->global_route_crc) {
unsigned i;
pj_size_t rcnt;
/* Remove the outbound proxies from the route set */
rcnt = pj_list_size(&acc->route_set);
for (i=0; i < rcnt - acc->cfg.proxy_cnt; ++i) {
pjsip_route_hdr *r = acc->route_set.next;
pj_list_erase(r);
}
/* Insert the outbound proxies to the beginning of route set */
pj_list_merge_first(&acc->route_set, &global_route);
/* Update global route CRC */
acc->global_route_crc = global_route_crc;
update_reg = PJ_TRUE;
unreg_first = PJ_TRUE;
}
/* Account proxy */
if (local_route_crc != acc->local_route_crc) {
unsigned i;
/* Remove the current account proxies from the route set */
for (i=0; i < acc->cfg.proxy_cnt; ++i) {
pjsip_route_hdr *r = acc->route_set.prev;
pj_list_erase(r);
}
/* Insert new proxy setting to the route set */
pj_list_merge_last(&acc->route_set, &local_route);
/* Update the proxy setting */
acc->cfg.proxy_cnt = cfg->proxy_cnt;
for (i = 0; i < cfg->proxy_cnt; ++i)
acc->cfg.proxy[i] = acc_proxy[i];
/* Update local route CRC */
acc->local_route_crc = local_route_crc;
update_reg = PJ_TRUE;
unreg_first = PJ_TRUE;
}
/* Credential info */
{
unsigned i;
pj_bool_t cred_changed = PJ_FALSE;
/* Selective update credential info. */
for (i = 0; i < cfg->cred_count; ++i) {
unsigned j;
pjsip_cred_info ci;
/* Find if this credential is already listed */
for (j = i; j < acc->cfg.cred_count; ++j) {
if (pjsip_cred_info_cmp(&acc->cfg.cred_info[j],
&cfg->cred_info[i]) == 0)
{
/* Found, but different index/position, swap */
if (j != i) {
ci = acc->cfg.cred_info[i];
acc->cfg.cred_info[i] = acc->cfg.cred_info[j];
acc->cfg.cred_info[j] = ci;
}
break;
}
}
/* Not found, insert this */
if (j == acc->cfg.cred_count) {
cred_changed = PJ_TRUE;
/* If account credential is full, discard the last one. */
if (acc->cfg.cred_count == PJ_ARRAY_SIZE(acc->cfg.cred_info)) {
pj_array_erase(acc->cfg.cred_info, sizeof(pjsip_cred_info),
acc->cfg.cred_count, acc->cfg.cred_count-1);
acc->cfg.cred_count--;
}
/* Insert this */
pjsip_cred_info_dup(acc->pool, &ci, &cfg->cred_info[i]);
pj_array_insert(acc->cfg.cred_info, sizeof(pjsip_cred_info),
acc->cfg.cred_count, i, &ci);
}
}
acc->cfg.cred_count = cfg->cred_count;
/* Concatenate credentials from account config and global config */
acc->cred_cnt = 0;
for (i=0; i<acc->cfg.cred_count; ++i) {
acc->cred[acc->cred_cnt++] = acc->cfg.cred_info[i];
}
for (i=0; i<pjsua_var.ua_cfg.cred_count &&
acc->cred_cnt < PJ_ARRAY_SIZE(acc->cred); ++i)
{
acc->cred[acc->cred_cnt++] = pjsua_var.ua_cfg.cred_info[i];
}
if (cred_changed) {
update_reg = PJ_TRUE;
unreg_first = PJ_TRUE;
}
}
/* Authentication preference */
acc->cfg.auth_pref.initial_auth = cfg->auth_pref.initial_auth;
if (pj_strcmp(&acc->cfg.auth_pref.algorithm, &cfg->auth_pref.algorithm)) {
pj_strdup_with_null(acc->pool, &acc->cfg.auth_pref.algorithm,
&cfg->auth_pref.algorithm);
update_reg = PJ_TRUE;
unreg_first = PJ_TRUE;
}
/* Registration */
if (acc->cfg.reg_timeout != cfg->reg_timeout) {
acc->cfg.reg_timeout = cfg->reg_timeout;
if (acc->regc != NULL)
pjsip_regc_update_expires(acc->regc, acc->cfg.reg_timeout);
update_reg = PJ_TRUE;
}
acc->cfg.unreg_timeout = cfg->unreg_timeout;
acc->cfg.allow_contact_rewrite = cfg->allow_contact_rewrite;
acc->cfg.reg_retry_interval = cfg->reg_retry_interval;
acc->cfg.reg_first_retry_interval = cfg->reg_first_retry_interval;
acc->cfg.reg_retry_random_interval = cfg->reg_retry_random_interval;
acc->cfg.drop_calls_on_reg_fail = cfg->drop_calls_on_reg_fail;
acc->cfg.register_on_acc_add = cfg->register_on_acc_add;
if (acc->cfg.reg_delay_before_refresh != cfg->reg_delay_before_refresh) {
acc->cfg.reg_delay_before_refresh = cfg->reg_delay_before_refresh;
if (acc->regc != NULL)
pjsip_regc_set_delay_before_refresh(acc->regc,
cfg->reg_delay_before_refresh);
}
/* Allow via rewrite */
if (acc->cfg.allow_via_rewrite != cfg->allow_via_rewrite) {
if (acc->regc != NULL) {
if (cfg->allow_via_rewrite) {
pjsip_regc_set_via_sent_by(acc->regc, &acc->via_addr,
acc->via_tp);
} else
pjsip_regc_set_via_sent_by(acc->regc, NULL, NULL);
}
if (acc->publish_sess != NULL) {
if (cfg->allow_via_rewrite) {
pjsip_publishc_set_via_sent_by(acc->publish_sess,
&acc->via_addr, acc->via_tp);
} else
pjsip_publishc_set_via_sent_by(acc->publish_sess, NULL, NULL);
}
acc->cfg.allow_via_rewrite = cfg->allow_via_rewrite;
}
/* Normalize registration timeout and refresh delay */
if (acc->cfg.reg_uri.slen ) {
if (acc->cfg.reg_timeout == 0) {
acc->cfg.reg_timeout = PJSUA_REG_INTERVAL;
}
if (acc->cfg.reg_delay_before_refresh == 0) {
acc->cfg.reg_delay_before_refresh =
PJSIP_REGISTER_CLIENT_DELAY_BEFORE_REFRESH;
}
}
/* Registrar URI */
if (pj_strcmp(&acc->cfg.reg_uri, &cfg->reg_uri)) {
if (cfg->reg_uri.slen) {
pj_strdup_with_null(acc->pool, &acc->cfg.reg_uri, &cfg->reg_uri);
if (reg_sip_uri)
acc->srv_port = reg_sip_uri->port;
}
update_reg = PJ_TRUE;
unreg_first = PJ_TRUE;
}
/* SIP outbound setting */
if (acc->cfg.use_rfc5626 != cfg->use_rfc5626 ||
pj_strcmp(&acc->cfg.rfc5626_instance_id, &cfg->rfc5626_instance_id) ||
pj_strcmp(&acc->cfg.rfc5626_reg_id, &cfg->rfc5626_reg_id))
{
update_reg = PJ_TRUE;
}
/* Video settings */
acc->cfg.vid_in_auto_show = cfg->vid_in_auto_show;
acc->cfg.vid_out_auto_transmit = cfg->vid_out_auto_transmit;
acc->cfg.vid_wnd_flags = cfg->vid_wnd_flags;
acc->cfg.vid_cap_dev = cfg->vid_cap_dev;
acc->cfg.vid_rend_dev = cfg->vid_rend_dev;
acc->cfg.vid_stream_rc_cfg = cfg->vid_stream_rc_cfg;
/* Media settings */
if (pj_stricmp(&acc->cfg.rtp_cfg.public_addr, &cfg->rtp_cfg.public_addr) ||
pj_stricmp(&acc->cfg.rtp_cfg.bound_addr, &cfg->rtp_cfg.bound_addr))
{
pjsua_transport_config_dup(acc->pool, &acc->cfg.rtp_cfg,
&cfg->rtp_cfg);
} else {
pj_str_t p_addr = acc->cfg.rtp_cfg.public_addr;
pj_str_t b_addr = acc->cfg.rtp_cfg.bound_addr;
/* ..to save memory by not using the pool */
acc->cfg.rtp_cfg = cfg->rtp_cfg;
acc->cfg.rtp_cfg.public_addr = p_addr;
acc->cfg.rtp_cfg.bound_addr = b_addr;
}
acc->cfg.ipv6_media_use = cfg->ipv6_media_use;
/* STUN and Media customization */
if (acc->cfg.sip_stun_use != cfg->sip_stun_use) {
acc->cfg.sip_stun_use = cfg->sip_stun_use;
update_reg = PJ_TRUE;
}
acc->cfg.media_stun_use = cfg->media_stun_use;
/* ICE settings */
acc->cfg.ice_cfg_use = cfg->ice_cfg_use;
switch (acc->cfg.ice_cfg_use) {
case PJSUA_ICE_CONFIG_USE_DEFAULT:
/* Copy ICE settings from media settings so that we don't need to
* check the media config if we look for ICE config.
*/
pjsua_ice_config_from_media_config(NULL, &acc->cfg.ice_cfg,
&pjsua_var.media_cfg);
break;
case PJSUA_ICE_CONFIG_USE_CUSTOM:
pjsua_ice_config_dup(acc->pool, &acc->cfg.ice_cfg, &cfg->ice_cfg);
break;
}
/* TURN settings */
acc->cfg.turn_cfg_use = cfg->turn_cfg_use;
switch (acc->cfg.turn_cfg_use) {
case PJSUA_TURN_CONFIG_USE_DEFAULT:
/* Copy TURN settings from media settings so that we don't need to
* check the media config if we look for TURN config.
*/
pjsua_turn_config_from_media_config(NULL, &acc->cfg.turn_cfg,
&pjsua_var.media_cfg);
break;
case PJSUA_TURN_CONFIG_USE_CUSTOM:
pjsua_turn_config_dup(acc->pool, &acc->cfg.turn_cfg,
&cfg->turn_cfg);
break;
}
acc->cfg.use_srtp = cfg->use_srtp;
/* Call hold type */
acc->cfg.call_hold_type = cfg->call_hold_type;
/* Unregister first */
if (unreg_first) {
status = pjsua_acc_set_registration(acc->index, PJ_FALSE);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Ignored failure in unregistering the "
"old account setting in modifying account", status);
/* Not really sure if we should return error */
status = PJ_SUCCESS;
}
if (acc->regc != NULL) {
pjsip_regc_destroy(acc->regc);
acc->regc = NULL;
acc->contact.slen = 0;
acc->reg_mapped_addr.slen = 0;
acc->rfc5626_status = OUTBOUND_UNKNOWN;
}
if (!cfg->reg_uri.slen) {
/* Reg URI still needed, delay unset after sending unregister. */
pj_bzero(&acc->cfg.reg_uri, sizeof(acc->cfg.reg_uri));
}
}
/* Update registration */
if (update_reg) {
/* If accounts has registration enabled, start registration */
if (acc->cfg.reg_uri.slen) {
status = pjsua_acc_set_registration(acc->index, PJ_TRUE);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Failed to register with new account "
"setting in modifying account", status);
goto on_return;
}
}
}
/* Update MWI subscription */
if (update_mwi) {
status = pjsua_start_mwi(acc_id, PJ_TRUE);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Failed in starting MWI subscription for "
"new account setting in modifying account", status);
}
}
on_return:
PJSUA_UNLOCK();
pj_log_pop_indent();
return status;
}
/*
* Modify account's presence status to be advertised to remote/presence
* subscribers.
*/
PJ_DEF(pj_status_t) pjsua_acc_set_online_status( pjsua_acc_id acc_id,
pj_bool_t is_online)
{
PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc),
PJ_EINVAL);
PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, PJ_EINVALIDOP);
PJ_LOG(4,(THIS_FILE, "Acc %d: setting online status to %d..",
acc_id, is_online));
pj_log_push_indent();
pjsua_var.acc[acc_id].online_status = is_online;
pj_bzero(&pjsua_var.acc[acc_id].rpid, sizeof(pjrpid_element));
pjsua_pres_update_acc(acc_id, PJ_FALSE);
pj_log_pop_indent();
return PJ_SUCCESS;
}
/*
* Set online status with extended information
*/
PJ_DEF(pj_status_t) pjsua_acc_set_online_status2( pjsua_acc_id acc_id,
pj_bool_t is_online,
const pjrpid_element *pr)
{
PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc),
PJ_EINVAL);
PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, PJ_EINVALIDOP);
PJ_LOG(4,(THIS_FILE, "Acc %d: setting online status to %d..",
acc_id, is_online));
pj_log_push_indent();
PJSUA_LOCK();
pjsua_var.acc[acc_id].online_status = is_online;
pjrpid_element_dup(pjsua_var.acc[acc_id].pool, &pjsua_var.acc[acc_id].rpid, pr);
PJSUA_UNLOCK();
pjsua_pres_update_acc(acc_id, PJ_TRUE);
pj_log_pop_indent();
return PJ_SUCCESS;
}
/* Create reg_contact, mainly for SIP outbound */
static void update_regc_contact(pjsua_acc *acc)
{
pjsua_acc_config *acc_cfg = &acc->cfg;
pj_bool_t need_outbound = PJ_FALSE;
const pj_str_t tcp_param = pj_str(";transport=tcp");
const pj_str_t tls_param = pj_str(";transport=tls");
if (!acc_cfg->use_rfc5626)
goto done;
/* Check if outbound has been requested and rejected */
if (acc->rfc5626_status == OUTBOUND_NA)
goto done;
if (pj_stristr(&acc->contact, &tcp_param)==NULL &&
pj_stristr(&acc->contact, &tls_param)==NULL)
{
/* Currently we can only do SIP outbound for TCP
* and TLS.
*/
goto done;
}
/* looks like we can use outbound */
need_outbound = PJ_TRUE;
done:
{
pj_ssize_t len;
pj_str_t reg_contact;
acc->rfc5626_status = OUTBOUND_WANTED;
len = acc->contact.slen + acc->cfg.reg_contact_params.slen +
(need_outbound?
(acc->rfc5626_instprm.slen + acc->rfc5626_regprm.slen): 0);
if (len > acc->contact.slen) {
reg_contact.ptr = (char*) pj_pool_alloc(acc->pool, len);
pj_strcpy(®_contact, &acc->contact);
if (need_outbound) {
acc->rfc5626_status = OUTBOUND_WANTED;
/* Need to use outbound, append the contact with
* +sip.instance and reg-id parameters.
*/
pj_strcat(®_contact, &acc->rfc5626_regprm);
pj_strcat(®_contact, &acc->rfc5626_instprm);
} else {
acc->rfc5626_status = OUTBOUND_NA;
}
pj_strcat(®_contact, &acc->cfg.reg_contact_params);
acc->reg_contact = reg_contact;
PJ_LOG(4,(THIS_FILE,
"Contact for acc %d updated: %.*s",
acc->index,
(int)acc->reg_contact.slen,
acc->reg_contact.ptr));
} else {
/* Outbound is not needed/wanted for the account and there's
* no custom registration Contact params. acc->reg_contact
* is set to the same as acc->contact.
*/
acc->reg_contact = acc->contact;
acc->rfc5626_status = OUTBOUND_NA;
}
}
}
/* Check if IP is private IP address */
static pj_bool_t is_private_ip(const pj_str_t *addr)
{
const pj_str_t private_net[] =
{
{ "10.", 3 },
{ "127.", 4 },
{ "172.16.", 7 }, { "172.17.", 7 }, { "172.18.", 7 }, { "172.19.", 7 },
{ "172.20.", 7 }, { "172.21.", 7 }, { "172.22.", 7 }, { "172.23.", 7 },
{ "172.24.", 7 }, { "172.25.", 7 }, { "172.26.", 7 }, { "172.27.", 7 },
{ "172.28.", 7 }, { "172.29.", 7 }, { "172.30.", 7 }, { "172.31.", 7 },
{ "192.168.", 8 }
};
unsigned i;
for (i=0; i<PJ_ARRAY_SIZE(private_net); ++i) {
if (pj_strncmp(addr, &private_net[i], private_net[i].slen)==0)
return PJ_TRUE;
}
return PJ_FALSE;
}
/* Update NAT address from the REGISTER response */
static pj_bool_t acc_check_nat_addr(pjsua_acc *acc,
int contact_rewrite_method,
struct pjsip_regc_cbparam *param)
{
pjsip_transport *tp;
const pj_str_t *via_addr;
pj_pool_t *pool;
int rport;
pjsip_sip_uri *uri;
pjsip_via_hdr *via;
pj_sockaddr contact_addr;
pj_sockaddr recv_addr = {{0}};
pj_status_t status;
pj_bool_t matched;
pj_str_t srv_ip;
pjsip_contact_hdr *contact_hdr;
const pj_str_t STR_CONTACT = { "Contact", 7 };
tp = param->rdata->tp_info.transport;
/* Get the received and rport info */
via = param->rdata->msg_info.via;
if (via->rport_param < 1) {
/* Remote doesn't support rport */
rport = via->sent_by.port;
if (rport==0) {
pjsip_transport_type_e tp_type;
tp_type = (pjsip_transport_type_e) tp->key.type;
rport = pjsip_transport_get_default_port_for_type(tp_type);
}
} else
rport = via->rport_param;
if (via->recvd_param.slen != 0)
via_addr = &via->recvd_param;
else
via_addr = &via->sent_by.host;
/* If allow_via_rewrite is enabled, we save the Via "received" address
* from the response, if either of the following condition is met:
* - the Via "received" address differs from saved one (or we haven't
* saved any yet)
* - transport is different
* - only the port has changed, AND either the received address is
* public IP or allow_contact_rewrite is 2
*/
if (acc->cfg.allow_via_rewrite &&
(pj_strcmp(&acc->via_addr.host, via_addr) || acc->via_tp != tp ||
(acc->via_addr.port != rport &&
(!is_private_ip(via_addr) || acc->cfg.allow_contact_rewrite == 2))))
{
if (pj_strcmp(&acc->via_addr.host, via_addr))
pj_strdup(acc->pool, &acc->via_addr.host, via_addr);
acc->via_addr.port = rport;
acc->via_tp = tp;
pjsip_regc_set_via_sent_by(acc->regc, &acc->via_addr, acc->via_tp);
if (acc->publish_sess != NULL) {
pjsip_publishc_set_via_sent_by(acc->publish_sess,
&acc->via_addr, acc->via_tp);
}
}
/* Save mapped address if needed */
if (acc->cfg.allow_sdp_nat_rewrite &&
pj_strcmp(&acc->reg_mapped_addr, via_addr))
{
pj_strdup(acc->pool, &acc->reg_mapped_addr, via_addr);
}
/* Only update if account is configured to auto-update */
if (acc->cfg.allow_contact_rewrite == PJ_FALSE)
return PJ_FALSE;
/* If SIP outbound is active, no need to update */
if (acc->rfc5626_status == OUTBOUND_ACTIVE) {
PJ_LOG(4,(THIS_FILE, "Acc %d has SIP outbound active, no need to "
"update registration Contact", acc->index));
return PJ_FALSE;
}
#if 0
// Always update
// See http://lists.pjsip.org/pipermail/pjsip_lists.pjsip.org/2008-March/002178.html
/* For UDP, only update if STUN is enabled (for now).
* For TCP/TLS, always check.
*/
if ((tp->key.type == PJSIP_TRANSPORT_UDP &&
(pjsua_var.ua_cfg.stun_domain.slen != 0 ||
(pjsua_var.ua_cfg.stun_host.slen != 0)) ||
(tp->key.type == PJSIP_TRANSPORT_TCP) ||
(tp->key.type == PJSIP_TRANSPORT_TLS))
{
/* Yes we will check */
} else {
return PJ_FALSE;
}
#endif
/* Compare received and rport with the URI in our registration */
pool = pjsua_pool_create("tmp", 512, 512);
contact_hdr = (pjsip_contact_hdr*)
pjsip_parse_hdr(pool, &STR_CONTACT, acc->contact.ptr,
acc->contact.slen, NULL);
pj_assert(contact_hdr != NULL);
uri = (pjsip_sip_uri*) contact_hdr->uri;
pj_assert(uri != NULL);
uri = (pjsip_sip_uri*) pjsip_uri_get_uri(uri);
if (uri->port == 0) {
pjsip_transport_type_e tp_type;
tp_type = (pjsip_transport_type_e) tp->key.type;
uri->port = pjsip_transport_get_default_port_for_type(tp_type);
}
/* Convert IP address strings into sockaddr for comparison.
* (http://trac.pjsip.org/repos/ticket/863)
*/
status = pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &uri->host,
&contact_addr);
if (status == PJ_SUCCESS)
status = pj_sockaddr_parse(pj_AF_UNSPEC(), 0, via_addr,
&recv_addr);
if (status == PJ_SUCCESS) {
/* Compare the addresses as sockaddr according to the ticket above,
* but only if they have the same family (ipv4 vs ipv4, or
* ipv6 vs ipv6)
*/
matched = (contact_addr.addr.sa_family != recv_addr.addr.sa_family) ||
(uri->port == rport &&
pj_sockaddr_cmp(&contact_addr, &recv_addr)==0);
} else {
/* Compare the addresses as string, as before */
matched = (uri->port == rport &&
pj_stricmp(&uri->host, via_addr)==0);
}
if (matched) {
/* Address doesn't change */
pj_pool_release(pool);
return PJ_FALSE;
}
/* Get server IP */
srv_ip = pj_str(param->rdata->pkt_info.src_name);
/* At this point we've detected that the address as seen by registrar.
* has changed.
*/
/* Do not switch if both Contact and server's IP address are
* public but response contains private IP. A NAT in the middle
* might have messed up with the SIP packets. See:
* http://trac.pjsip.org/repos/ticket/643
*
* This exception can be disabled by setting allow_contact_rewrite
* to 2. In this case, the switch will always be done whenever there
* is difference in the IP address in the response.
*/
if (acc->cfg.allow_contact_rewrite != 2 && !is_private_ip(&uri->host) &&
!is_private_ip(&srv_ip) && is_private_ip(via_addr))
{
/* Don't switch */
pj_pool_release(pool);
return PJ_FALSE;
}
/* Also don't switch if only the port number part is different, and
* the Via received address is private.
* See http://trac.pjsip.org/repos/ticket/864
*/
if (acc->cfg.allow_contact_rewrite != 2 &&
pj_sockaddr_cmp(&contact_addr, &recv_addr)==0 &&
is_private_ip(via_addr))
{
/* Don't switch */
pj_pool_release(pool);
return PJ_FALSE;
}
PJ_LOG(3,(THIS_FILE, "IP address change detected for account %d "
"(%.*s:%d --> %.*s:%d). Updating registration "
"(using method %d)",
acc->index,
(int)uri->host.slen,
uri->host.ptr,
uri->port,
(int)via_addr->slen,
via_addr->ptr,
rport,
contact_rewrite_method));
pj_assert(contact_rewrite_method == PJSUA_CONTACT_REWRITE_UNREGISTER ||
contact_rewrite_method == PJSUA_CONTACT_REWRITE_NO_UNREG ||
contact_rewrite_method == PJSUA_CONTACT_REWRITE_ALWAYS_UPDATE);
if (contact_rewrite_method == PJSUA_CONTACT_REWRITE_UNREGISTER) {
/* Unregister current contact */
pjsua_acc_set_registration(acc->index, PJ_FALSE);
if (acc->regc != NULL) {
pjsip_regc_destroy(acc->regc);
acc->regc = NULL;
acc->contact.slen = 0;
}
}
/*
* Build new Contact header
*/
{
const char *ob = ";ob";
char *tmp;
const char *beginquote, *endquote;
char transport_param[32];
int len;
pj_bool_t secure;
secure = pjsip_transport_get_flag_from_type(tp->key.type) &
PJSIP_TRANSPORT_SECURE;
/* Enclose IPv6 address in square brackets */
if (tp->key.type & PJSIP_TRANSPORT_IPV6) {
beginquote = "[";
endquote = "]";
} else {
beginquote = endquote = "";
}
/* Don't add transport parameter if it's UDP */
if (tp->key.type != PJSIP_TRANSPORT_UDP &&
tp->key.type != PJSIP_TRANSPORT_UDP6)
{
pj_ansi_snprintf(transport_param, sizeof(transport_param),
";transport=%s",
pjsip_transport_get_type_name(
(pjsip_transport_type_e)tp->key.type));
} else {
transport_param[0] = '\0';
}
tmp = (char*) pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
len = pj_ansi_snprintf(tmp, PJSIP_MAX_URL_SIZE,
"<%s:%.*s%s%s%.*s%s:%d%s%.*s%s>%.*s",
((secure && acc->is_sips)? "sips" : "sip"),
(int)acc->user_part.slen,
acc->user_part.ptr,
(acc->user_part.slen? "@" : ""),
beginquote,
(int)via_addr->slen,
via_addr->ptr,
endquote,
rport,
transport_param,
(int)acc->cfg.contact_uri_params.slen,
acc->cfg.contact_uri_params.ptr,
(acc->cfg.use_rfc5626? ob: ""),
(int)acc->cfg.contact_params.slen,
acc->cfg.contact_params.ptr);
if (len < 1 || len >= PJSIP_MAX_URL_SIZE) {
PJ_LOG(1,(THIS_FILE, "URI too long"));
pj_pool_release(pool);
return PJ_FALSE;
}
pj_strdup2_with_null(acc->pool, &acc->contact, tmp);
update_regc_contact(acc);
/* Always update, by http://trac.pjsip.org/repos/ticket/864. */
/* Since the Via address will now be overwritten to the correct
* address by https://trac.pjsip.org/repos/ticket/1537, we do
* not need to update the transport address.
*/
/*
pj_strdup_with_null(tp->pool, &tp->local_name.host, via_addr);
tp->local_name.port = rport;
*/
}
if (contact_rewrite_method == PJSUA_CONTACT_REWRITE_NO_UNREG &&
acc->regc != NULL)
{
pjsip_regc_update_contact(acc->regc, 1, &acc->reg_contact);
}
/* Perform new registration */
if (contact_rewrite_method < PJSUA_CONTACT_REWRITE_ALWAYS_UPDATE) {
pjsua_acc_set_registration(acc->index, PJ_TRUE);
}
pj_pool_release(pool);
return PJ_TRUE;
}
/* Check and update Service-Route header */
static void update_service_route(pjsua_acc *acc, pjsip_rx_data *rdata)
{
pjsip_generic_string_hdr *hsr = NULL;
pjsip_route_hdr *hr, *h;
const pj_str_t HNAME = { "Service-Route", 13 };
const pj_str_t HROUTE = { "Route", 5 };
pjsip_uri *uri[PJSUA_ACC_MAX_PROXIES];
unsigned i, uri_cnt = 0;
pj_size_t rcnt;
/* Find and parse Service-Route headers */
for (;;) {
char saved;
int parsed_len;
/* Find Service-Route header */
hsr = (pjsip_generic_string_hdr*)
pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &HNAME, hsr);
if (!hsr)
break;
/* Parse as Route header since the syntax is similar. This may
* return more than one headers.
*/
saved = hsr->hvalue.ptr[hsr->hvalue.slen];
hsr->hvalue.ptr[hsr->hvalue.slen] = '\0';
hr = (pjsip_route_hdr*)
pjsip_parse_hdr(rdata->tp_info.pool, &HROUTE, hsr->hvalue.ptr,
hsr->hvalue.slen, &parsed_len);
hsr->hvalue.ptr[hsr->hvalue.slen] = saved;
if (hr == NULL) {
/* Error */
PJ_LOG(1,(THIS_FILE, "Error parsing Service-Route header"));
return;
}
/* Save each URI in the result */
h = hr;
do {
if (!PJSIP_URI_SCHEME_IS_SIP(h->name_addr.uri) &&
!PJSIP_URI_SCHEME_IS_SIPS(h->name_addr.uri))
{
PJ_LOG(1,(THIS_FILE,"Error: non SIP URI in Service-Route: %.*s",
(int)hsr->hvalue.slen, hsr->hvalue.ptr));
return;
}
uri[uri_cnt++] = h->name_addr.uri;
h = h->next;
} while (h != hr && uri_cnt != PJ_ARRAY_SIZE(uri));
if (h != hr) {
PJ_LOG(1,(THIS_FILE, "Error: too many Service-Route headers"));
return;
}
/* Prepare to find next Service-Route header */
hsr = hsr->next;
if ((void*)hsr == (void*)&rdata->msg_info.msg->hdr)
break;
}
if (uri_cnt == 0)
return;
/*
* Update account's route set
*/
/* First remove all routes which are not the outbound proxies */
rcnt = pj_list_size(&acc->route_set);
if (rcnt != pjsua_var.ua_cfg.outbound_proxy_cnt + acc->cfg.proxy_cnt) {
for (i=pjsua_var.ua_cfg.outbound_proxy_cnt + acc->cfg.proxy_cnt,
hr=acc->route_set.prev;
i<rcnt;
++i)
{
pjsip_route_hdr *prev = hr->prev;
pj_list_erase(hr);
hr = prev;
}
}
/* Then append the Service-Route URIs */
for (i=0; i<uri_cnt; ++i) {
hr = pjsip_route_hdr_create(acc->pool);
hr->name_addr.uri = (pjsip_uri*)pjsip_uri_clone(acc->pool, uri[i]);
pj_list_push_back(&acc->route_set, hr);
}
/* Done */
PJ_LOG(4,(THIS_FILE, "Service-Route updated for acc %d with %d URI(s)",
acc->index, uri_cnt));
}
/* Keep alive timer callback */
static void keep_alive_timer_cb(pj_timer_heap_t *th, pj_timer_entry *te)
{
pjsua_acc *acc;
pjsip_tpselector tp_sel;
pj_time_val delay;
char addrtxt[PJ_INET6_ADDRSTRLEN];
pj_status_t status;
PJ_UNUSED_ARG(th);
PJSUA_LOCK();
te->id = PJ_FALSE;
acc = (pjsua_acc*) te->user_data;
/* Select the transport to send the packet */
pj_bzero(&tp_sel, sizeof(tp_sel));
tp_sel.type = PJSIP_TPSELECTOR_TRANSPORT;
tp_sel.u.transport = acc->ka_transport;
PJ_LOG(5,(THIS_FILE,
"Sending %d bytes keep-alive packet for acc %d to %s",
acc->cfg.ka_data.slen, acc->index,
pj_sockaddr_print(&acc->ka_target, addrtxt, sizeof(addrtxt),3)));
/* Send raw packet */
status = pjsip_tpmgr_send_raw(pjsip_endpt_get_tpmgr(pjsua_var.endpt),
acc->ka_transport->key.type, &tp_sel,
NULL, acc->cfg.ka_data.ptr,
acc->cfg.ka_data.slen,
&acc->ka_target, acc->ka_target_len,
NULL, NULL);
if (status != PJ_SUCCESS && status != PJ_EPENDING) {
pjsua_perror(THIS_FILE, "Error sending keep-alive packet", status);
}
/* Check just in case keep-alive has been disabled. This shouldn't happen
* though as when ka_interval is changed this timer should have been
* cancelled.
*/
if (acc->cfg.ka_interval == 0)
goto on_return;
/* Reschedule next timer */
delay.sec = acc->cfg.ka_interval;
delay.msec = 0;
status = pjsip_endpt_schedule_timer(pjsua_var.endpt, te, &delay);
if (status == PJ_SUCCESS) {
te->id = PJ_TRUE;
} else {
pjsua_perror(THIS_FILE, "Error starting keep-alive timer", status);
}
on_return:
PJSUA_UNLOCK();
}
/* Update keep-alive for the account */
static void update_keep_alive(pjsua_acc *acc, pj_bool_t start,
struct pjsip_regc_cbparam *param)
{
/* In all cases, stop keep-alive timer if it's running. */
if (acc->ka_timer.id) {
pjsip_endpt_cancel_timer(pjsua_var.endpt, &acc->ka_timer);
acc->ka_timer.id = PJ_FALSE;
if (acc->ka_transport) {
pjsip_transport_dec_ref(acc->ka_transport);
acc->ka_transport = NULL;
}
}
if (start) {
pj_time_val delay;
pj_status_t status;
/* Only do keep-alive if:
* - ka_interval is not zero in the account, and
* - transport is UDP.
*
* Previously we only enabled keep-alive when STUN is enabled, since
* we thought that keep-alive is only needed in Internet situation.
* But it has been discovered that Windows Firewall on WinXP also
* needs to be kept-alive, otherwise incoming packets will be dropped.
* So because of this, now keep-alive is always enabled for UDP,
* regardless of whether STUN is enabled or not.
*
* Note that this applies only for UDP. For TCP/TLS, the keep-alive
* is done by the transport layer.
*/
if (/*pjsua_var.stun_srv.ipv4.sin_family == 0 ||*/
acc->cfg.ka_interval == 0 ||
(param->rdata->tp_info.transport->key.type &
~PJSIP_TRANSPORT_IPV6)!= PJSIP_TRANSPORT_UDP)
{
/* Keep alive is not necessary */
return;
}
/* Save transport and destination address. */
acc->ka_transport = param->rdata->tp_info.transport;
pjsip_transport_add_ref(acc->ka_transport);
/* https://trac.pjsip.org/repos/ticket/1607:
* Calculate the destination address from the original request. Some
* (broken) servers send the response using different source address
* than the one that receives the request, which is forbidden by RFC
* 3581.
*/
{
pjsip_transaction *tsx;
pjsip_tx_data *req;
tsx = pjsip_rdata_get_tsx(param->rdata);
PJ_ASSERT_ON_FAIL(tsx, return);
req = tsx->last_tx;
pj_memcpy(&acc->ka_target, &req->tp_info.dst_addr,
req->tp_info.dst_addr_len);
acc->ka_target_len = req->tp_info.dst_addr_len;
}
/* Setup and start the timer */
acc->ka_timer.cb = &keep_alive_timer_cb;
acc->ka_timer.user_data = (void*)acc;
delay.sec = acc->cfg.ka_interval;
delay.msec = 0;
status = pjsip_endpt_schedule_timer(pjsua_var.endpt, &acc->ka_timer,
&delay);
if (status == PJ_SUCCESS) {
acc->ka_timer.id = PJ_TRUE;
PJ_LOG(4,(THIS_FILE, "Keep-alive timer started for acc %d, "
"destination:%s:%d, interval:%ds",
acc->index,
param->rdata->pkt_info.src_name,
param->rdata->pkt_info.src_port,
acc->cfg.ka_interval));
} else {
acc->ka_timer.id = PJ_FALSE;
pjsip_transport_dec_ref(acc->ka_transport);
acc->ka_transport = NULL;
pjsua_perror(THIS_FILE, "Error starting keep-alive timer", status);
}
}
}
/* Update the status of SIP outbound registration request */
static void update_rfc5626_status(pjsua_acc *acc, pjsip_rx_data *rdata)
{
pjsip_require_hdr *hreq;
const pj_str_t STR_OUTBOUND = {"outbound", 8};
unsigned i;
if (acc->rfc5626_status == OUTBOUND_UNKNOWN) {
goto on_return;
}
hreq = rdata->msg_info.require;
if (!hreq) {
acc->rfc5626_status = OUTBOUND_NA;
goto on_return;
}
for (i=0; i<hreq->count; ++i) {
if (pj_stricmp(&hreq->values[i], &STR_OUTBOUND)==0) {
acc->rfc5626_status = OUTBOUND_ACTIVE;
goto on_return;
}
}
/* Server does not support outbound */
acc->rfc5626_status = OUTBOUND_NA;
on_return:
if (acc->rfc5626_status != OUTBOUND_ACTIVE) {
acc->reg_contact = acc->contact;
}
PJ_LOG(4,(THIS_FILE, "SIP outbound status for acc %d is %s",
acc->index, (acc->rfc5626_status==OUTBOUND_ACTIVE?
"active": "not active")));
}
static void regc_tsx_cb(struct pjsip_regc_tsx_cb_param *param)
{
pjsua_acc *acc = (pjsua_acc*) param->cbparam.token;
PJSUA_LOCK();
if (param->cbparam.regc != acc->regc) {
PJSUA_UNLOCK();
return;
}
pj_log_push_indent();
/* Check if we should do NAT bound address check for contact rewrite.
* Note that '!contact_rewritten' check here is to avoid overriding
* the current contact generated from last 2xx.
*/
if (!acc->contact_rewritten &&
(acc->cfg.contact_rewrite_method &
PJSUA_CONTACT_REWRITE_ALWAYS_UPDATE) ==
PJSUA_CONTACT_REWRITE_ALWAYS_UPDATE &&
param->cbparam.code >= 400 &&
param->cbparam.rdata)
{
if (acc_check_nat_addr(acc, PJSUA_CONTACT_REWRITE_ALWAYS_UPDATE,
¶m->cbparam))
{
param->contact_cnt = 1;
param->contact[0] = acc->reg_contact;
/* Don't set 'contact_rewritten' to PJ_TRUE here to allow
* further check of NAT bound address in 2xx response.
*/
}
}
PJSUA_UNLOCK();
pj_log_pop_indent();
}
/*
* This callback is called by pjsip_regc when outgoing register
* request has completed.
*/
static void regc_cb(struct pjsip_regc_cbparam *param)
{
pjsua_acc *acc = (pjsua_acc*) param->token;
PJSUA_LOCK();
if (param->regc != acc->regc) {
PJSUA_UNLOCK();
return;
}
pj_log_push_indent();
/*
* Print registration status.
*/
if (param->status!=PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "SIP registration error",
param->status);
pjsip_regc_destroy(acc->regc);
acc->regc = NULL;
acc->contact.slen = 0;
acc->reg_mapped_addr.slen = 0;
acc->rfc5626_status = OUTBOUND_UNKNOWN;
/* Stop keep-alive timer if any. */
update_keep_alive(acc, PJ_FALSE, NULL);
} else if (param->code < 0 || param->code >= 300) {
PJ_LOG(2, (THIS_FILE, "SIP registration failed, status=%d (%.*s)",
param->code,
(int)param->reason.slen, param->reason.ptr));
pjsip_regc_destroy(acc->regc);
acc->regc = NULL;
acc->contact.slen = 0;
acc->reg_mapped_addr.slen = 0;
acc->rfc5626_status = OUTBOUND_UNKNOWN;
/* Stop keep-alive timer if any. */
update_keep_alive(acc, PJ_FALSE, NULL);
} else if (PJSIP_IS_STATUS_IN_CLASS(param->code, 200)) {
/* Update auto registration flag */
acc->auto_rereg.active = PJ_FALSE;
acc->auto_rereg.attempt_cnt = 0;
if (param->expiration < 1) {
pjsip_regc_destroy(acc->regc);
acc->regc = NULL;
acc->contact.slen = 0;
acc->reg_mapped_addr.slen = 0;
acc->rfc5626_status = OUTBOUND_UNKNOWN;
/* Reset pointer to registration transport */
//acc->auto_rereg.reg_tp = NULL;
/* Stop keep-alive timer if any. */
update_keep_alive(acc, PJ_FALSE, NULL);
PJ_LOG(3,(THIS_FILE, "%s: unregistration success",
pjsua_var.acc[acc->index].cfg.id.ptr));
} else {
/* Check and update SIP outbound status first, since the result
* will determine if we should update re-registration
*/
update_rfc5626_status(acc, param->rdata);
/* Check NAT bound address if it hasn't been done before */
if (!acc->contact_rewritten &&
acc_check_nat_addr(acc, (acc->cfg.contact_rewrite_method & 3),
param))
{
PJSUA_UNLOCK();
pj_log_pop_indent();
/* Avoid another check of NAT bound address */
acc->contact_rewritten = PJ_TRUE;
return;
}
/* Check and update Service-Route header */
update_service_route(acc, param->rdata);
PJ_LOG(3, (THIS_FILE,
"%s: registration success, status=%d (%.*s), "
"will re-register in %d seconds",
pjsua_var.acc[acc->index].cfg.id.ptr,
param->code,
(int)param->reason.slen, param->reason.ptr,
param->expiration));
/* Start keep-alive timer if necessary. */
update_keep_alive(acc, PJ_TRUE, param);
/* Send initial PUBLISH if it is enabled */
if (acc->cfg.publish_enabled && acc->publish_sess==NULL)
pjsua_pres_init_publish_acc(acc->index);
/* Subscribe to MWI, if it's enabled */
if (acc->cfg.mwi_enabled)
pjsua_start_mwi(acc->index, PJ_FALSE);
}
} else {
PJ_LOG(4, (THIS_FILE, "SIP registration updated status=%d", param->code));
}
acc->reg_last_err = param->status;
acc->reg_last_code = param->code;
/* Reaching this point means no contact rewrite, so reset the flag */
acc->contact_rewritten = PJ_FALSE;
/* Check if we need to auto retry registration. Basically, registration
* failure codes triggering auto-retry are those of temporal failures
* considered to be recoverable in relatively short term.
*/
if (acc->cfg.reg_retry_interval &&
(param->code == PJSIP_SC_REQUEST_TIMEOUT ||
param->code == PJSIP_SC_INTERNAL_SERVER_ERROR ||
param->code == PJSIP_SC_BAD_GATEWAY ||
param->code == PJSIP_SC_SERVICE_UNAVAILABLE ||
param->code == PJSIP_SC_SERVER_TIMEOUT ||
param->code == PJSIP_SC_TEMPORARILY_UNAVAILABLE ||
PJSIP_IS_STATUS_IN_CLASS(param->code, 600))) /* Global failure */
{
schedule_reregistration(acc);
}
/* Call the registration status callback */
if (pjsua_var.ua_cfg.cb.on_reg_state) {
(*pjsua_var.ua_cfg.cb.on_reg_state)(acc->index);
}
if (pjsua_var.ua_cfg.cb.on_reg_state2) {
pjsua_reg_info reg_info;
pjsip_regc_info rinfo;
pjsip_regc_get_info(param->regc, &rinfo);
reg_info.cbparam = param;
reg_info.regc = param->regc;
reg_info.renew = !param->is_unreg;
(*pjsua_var.ua_cfg.cb.on_reg_state2)(acc->index, ®_info);
}
PJSUA_UNLOCK();
pj_log_pop_indent();
}
/*
* Initialize client registration.
*/
static pj_status_t pjsua_regc_init(int acc_id)
{
pjsua_acc *acc;
pj_pool_t *pool;
pj_status_t status;
PJ_ASSERT_RETURN(pjsua_acc_is_valid(acc_id), PJ_EINVAL);
acc = &pjsua_var.acc[acc_id];
if (acc->cfg.reg_uri.slen == 0) {
PJ_LOG(3,(THIS_FILE, "Registrar URI is not specified"));
return PJ_SUCCESS;
}
/* Destroy existing session, if any */
if (acc->regc) {
pjsip_regc_destroy(acc->regc);
acc->regc = NULL;
acc->contact.slen = 0;
acc->reg_mapped_addr.slen = 0;
acc->rfc5626_status = OUTBOUND_UNKNOWN;
}
/* initialize SIP registration if registrar is configured */
status = pjsip_regc_create( pjsua_var.endpt,
acc, ®c_cb, &acc->regc);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Unable to create client registration",
status);
return status;
}
pool = pjsua_pool_create("tmpregc", 512, 512);
if (acc->contact.slen == 0) {
pj_str_t tmp_contact;
status = pjsua_acc_create_uac_contact( pool, &tmp_contact,
acc_id, &acc->cfg.reg_uri);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Unable to generate suitable Contact header"
" for registration",
status);
pjsip_regc_destroy(acc->regc);
pj_pool_release(pool);
acc->regc = NULL;
return status;
}
pj_strdup_with_null(acc->pool, &acc->contact, &tmp_contact);
update_regc_contact(acc);
}
status = pjsip_regc_init( acc->regc,
&acc->cfg.reg_uri,
&acc->cfg.id,
&acc->cfg.id,
1, &acc->reg_contact,
acc->cfg.reg_timeout);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE,
"Client registration initialization error",
status);
pjsip_regc_destroy(acc->regc);
pj_pool_release(pool);
acc->regc = NULL;
acc->contact.slen = 0;
acc->reg_mapped_addr.slen = 0;
acc->rfc5626_status = OUTBOUND_UNKNOWN;
return status;
}
pjsip_regc_set_reg_tsx_cb(acc->regc, regc_tsx_cb);
/* If account is locked to specific transport, then set transport to
* the client registration.
*/
if (pjsua_var.acc[acc_id].cfg.transport_id != PJSUA_INVALID_ID) {
pjsip_tpselector tp_sel;
pjsua_init_tpselector(pjsua_var.acc[acc_id].cfg.transport_id, &tp_sel);
pjsip_regc_set_transport(acc->regc, &tp_sel);
}
/* Set credentials
*/
if (acc->cred_cnt) {
pjsip_regc_set_credentials( acc->regc, acc->cred_cnt, acc->cred);
}
/* Set delay before registration refresh */
pjsip_regc_set_delay_before_refresh(acc->regc,
acc->cfg.reg_delay_before_refresh);
/* Set authentication preference */
pjsip_regc_set_prefs(acc->regc, &acc->cfg.auth_pref);
/* Set route-set
*/
if (acc->cfg.reg_use_proxy) {
pjsip_route_hdr route_set;
const pjsip_route_hdr *r;
pj_list_init(&route_set);
if (acc->cfg.reg_use_proxy & PJSUA_REG_USE_OUTBOUND_PROXY) {
r = pjsua_var.outbound_proxy.next;
while (r != &pjsua_var.outbound_proxy) {
pj_list_push_back(&route_set, pjsip_hdr_shallow_clone(pool, r));
r = r->next;
}
}
if (acc->cfg.reg_use_proxy & PJSUA_REG_USE_ACC_PROXY &&
acc->cfg.proxy_cnt)
{
int cnt = acc->cfg.proxy_cnt;
pjsip_route_hdr *pos = route_set.prev;
int i;
r = acc->route_set.prev;
for (i=0; i<cnt; ++i) {
pj_list_push_front(pos, pjsip_hdr_shallow_clone(pool, r));
r = r->prev;
}
}
if (!pj_list_empty(&route_set))
pjsip_regc_set_route_set( acc->regc, &route_set );
}
/* Add custom request headers specified in the account config */
pjsip_regc_add_headers(acc->regc, &acc->cfg.reg_hdr_list);
/* Add other request headers. */
if (pjsua_var.ua_cfg.user_agent.slen) {
pjsip_hdr hdr_list;
const pj_str_t STR_USER_AGENT = { "User-Agent", 10 };
pjsip_generic_string_hdr *h;
pj_list_init(&hdr_list);
h = pjsip_generic_string_hdr_create(pool, &STR_USER_AGENT,
&pjsua_var.ua_cfg.user_agent);
pj_list_push_back(&hdr_list, (pjsip_hdr*)h);
pjsip_regc_add_headers(acc->regc, &hdr_list);
}
/* If SIP outbound is used, add "Supported: outbound, path header" */
if (acc->rfc5626_status == OUTBOUND_WANTED ||
acc->rfc5626_status == OUTBOUND_ACTIVE)
{
pjsip_hdr hdr_list;
pjsip_supported_hdr *hsup;
pj_list_init(&hdr_list);
hsup = pjsip_supported_hdr_create(pool);
pj_list_push_back(&hdr_list, hsup);
hsup->count = 2;
hsup->values[0] = pj_str("outbound");
hsup->values[1] = pj_str("path");
pjsip_regc_add_headers(acc->regc, &hdr_list);
}
pj_pool_release(pool);
return PJ_SUCCESS;
}
pj_bool_t pjsua_sip_acc_is_using_ipv6(pjsua_acc_id acc_id)
{
pjsua_acc *acc = &pjsua_var.acc[acc_id];
return (acc->tp_type & PJSIP_TRANSPORT_IPV6) == PJSIP_TRANSPORT_IPV6;
}
pj_bool_t pjsua_sip_acc_is_using_stun(pjsua_acc_id acc_id)
{
pjsua_acc *acc = &pjsua_var.acc[acc_id];
return acc->cfg.sip_stun_use != PJSUA_STUN_USE_DISABLED &&
pjsua_var.ua_cfg.stun_srv_cnt != 0;
}
pj_bool_t pjsua_media_acc_is_using_stun(pjsua_acc_id acc_id)
{
pjsua_acc *acc = &pjsua_var.acc[acc_id];
return acc->cfg.media_stun_use != PJSUA_STUN_USE_DISABLED &&
pjsua_var.ua_cfg.stun_srv_cnt != 0;
}
/*
* Update registration or perform unregistration.
*/
PJ_DEF(pj_status_t) pjsua_acc_set_registration( pjsua_acc_id acc_id,
pj_bool_t renew)
{
pjsua_acc *acc;
pj_status_t status = 0;
pjsip_tx_data *tdata = 0;
PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc),
PJ_EINVAL);
PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, PJ_EINVALIDOP);
PJ_LOG(4,(THIS_FILE, "Acc %d: setting %sregistration..",
acc_id, (renew? "" : "un")));
pj_log_push_indent();
PJSUA_LOCK();
acc = &pjsua_var.acc[acc_id];
/* Cancel any re-registration timer */
if (pjsua_var.acc[acc_id].auto_rereg.timer.id) {
pjsua_var.acc[acc_id].auto_rereg.timer.id = PJ_FALSE;
pjsua_cancel_timer(&pjsua_var.acc[acc_id].auto_rereg.timer);
}
/* Reset pointer to registration transport */
// Do not reset this here, as if currently there is another registration
// on progress, this registration will fail but transport pointer will
// become NULL which will prevent transport to be destroyed immediately
// after disconnected (which may cause iOS app getting killed (see #1482).
//pjsua_var.acc[acc_id].auto_rereg.reg_tp = NULL;
if (renew) {
if (pjsua_var.acc[acc_id].regc == NULL) {
status = pjsua_regc_init(acc_id);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Unable to create registration",
status);
goto on_return;
}
}
if (!pjsua_var.acc[acc_id].regc) {
status = PJ_EINVALIDOP;
goto on_return;
}
status = pjsip_regc_register(pjsua_var.acc[acc_id].regc, 1,
&tdata);
if (0 && status == PJ_SUCCESS && pjsua_var.acc[acc_id].cred_cnt) {
pjsip_authorization_hdr *h;
char *uri;
int d;
uri = (char*) pj_pool_alloc(tdata->pool, acc->cfg.reg_uri.slen+10);
d = pjsip_uri_print(PJSIP_URI_IN_REQ_URI, tdata->msg->line.req.uri,
uri, acc->cfg.reg_uri.slen+10);
pj_assert(d > 0);
PJ_UNUSED_ARG(d);
h = pjsip_authorization_hdr_create(tdata->pool);
h->scheme = pj_str("Digest");
h->credential.digest.username = acc->cred[0].username;
h->credential.digest.realm = acc->srv_domain;
h->credential.digest.uri = pj_str(uri);
h->credential.digest.algorithm = pj_str("md5");
pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)h);
}
} else {
if (pjsua_var.acc[acc_id].regc == NULL) {
PJ_LOG(3,(THIS_FILE, "Currently not registered"));
status = PJ_EINVALIDOP;
goto on_return;
}
pjsua_pres_unpublish(&pjsua_var.acc[acc_id], 0);
status = pjsip_regc_unregister(pjsua_var.acc[acc_id].regc, &tdata);
}
if (status == PJ_SUCCESS) {
if (pjsua_var.acc[acc_id].cfg.allow_via_rewrite &&
pjsua_var.acc[acc_id].via_addr.host.slen > 0)
{
pjsip_regc_set_via_sent_by(pjsua_var.acc[acc_id].regc,
&pjsua_var.acc[acc_id].via_addr,
pjsua_var.acc[acc_id].via_tp);
} else if (!pjsua_sip_acc_is_using_stun(acc_id)) {
/* Choose local interface to use in Via if acc is not using
* STUN
*/
pjsua_acc_get_uac_addr(acc_id, tdata->pool,
&acc->cfg.reg_uri,
&tdata->via_addr,
NULL, NULL,
&tdata->via_tp);
}
//pjsua_process_msg_data(tdata, NULL);
status = pjsip_regc_send( pjsua_var.acc[acc_id].regc, tdata );
}
/* Update pointer to registration transport */
if (status == PJ_SUCCESS) {
/* Variable auto_rereg.reg_tp is currently unused since it may differ
* with the transport used by regc (for example, when a resolver is
* employed). A more reliable way is to query the regc directly
* when needed.
*/
//pjsip_regc_info reg_info;
//pjsip_regc_get_info(pjsua_var.acc[acc_id].regc, ®_info);
//pjsua_var.acc[acc_id].auto_rereg.reg_tp = reg_info.transport;
if (pjsua_var.ua_cfg.cb.on_reg_started) {
(*pjsua_var.ua_cfg.cb.on_reg_started)(acc_id, renew);
}
if (pjsua_var.ua_cfg.cb.on_reg_started2) {
pjsua_reg_info rinfo;
rinfo.cbparam = NULL;
rinfo.regc = pjsua_var.acc[acc_id].regc;
rinfo.renew = renew;
(*pjsua_var.ua_cfg.cb.on_reg_started2)(acc_id, &rinfo);
}
}
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Unable to create/send REGISTER",
status);
} else {
PJ_LOG(4,(THIS_FILE, "Acc %d: %s sent", acc_id,
(renew? "Registration" : "Unregistration")));
}
on_return:
PJSUA_UNLOCK();
pj_log_pop_indent();
return status;
}
/*
* Get account information.
*/
PJ_DEF(pj_status_t) pjsua_acc_get_info( pjsua_acc_id acc_id,
pjsua_acc_info *info)
{
pjsua_acc *acc = &pjsua_var.acc[acc_id];
pjsua_acc_config *acc_cfg = &pjsua_var.acc[acc_id].cfg;
PJ_ASSERT_RETURN(info != NULL, PJ_EINVAL);
PJ_ASSERT_RETURN(pjsua_acc_is_valid(acc_id), PJ_EINVAL);
pj_bzero(info, sizeof(pjsua_acc_info));
PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc),
PJ_EINVAL);
PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, PJ_EINVALIDOP);
PJSUA_LOCK();
if (pjsua_var.acc[acc_id].valid == PJ_FALSE) {
PJSUA_UNLOCK();
return PJ_EINVALIDOP;
}
info->id = acc_id;
info->is_default = (pjsua_var.default_acc == acc_id);
info->acc_uri = acc_cfg->id;
info->has_registration = (acc->cfg.reg_uri.slen > 0);
info->online_status = acc->online_status;
pj_memcpy(&info->rpid, &acc->rpid, sizeof(pjrpid_element));
if (info->rpid.note.slen)
info->online_status_text = info->rpid.note;
else if (info->online_status)
info->online_status_text = pj_str("Online");
else
info->online_status_text = pj_str("Offline");
if (acc->reg_last_code) {
if (info->has_registration) {
info->status = (pjsip_status_code) acc->reg_last_code;
info->status_text = *pjsip_get_status_text(acc->reg_last_code);
if (acc->reg_last_err)
info->reg_last_err = acc->reg_last_err;
} else {
info->status = (pjsip_status_code) 0;
info->status_text = pj_str("not registered");
}
} else if (acc->cfg.reg_uri.slen) {
info->status = PJSIP_SC_TRYING;
info->status_text = pj_str("In Progress");
} else {
info->status = (pjsip_status_code) 0;
info->status_text = pj_str("does not register");
}
if (acc->regc) {
pjsip_regc_info regc_info;
pjsip_regc_get_info(acc->regc, ®c_info);
info->expires = regc_info.next_reg;
} else {
info->expires = -1;
}
PJSUA_UNLOCK();
return PJ_SUCCESS;
}
/*
* Enum accounts all account ids.
*/
PJ_DEF(pj_status_t) pjsua_enum_accs(pjsua_acc_id ids[],
unsigned *count )
{
unsigned i, c;
PJ_ASSERT_RETURN(ids && *count, PJ_EINVAL);
PJSUA_LOCK();
for (i=0, c=0; c<*count && i<PJ_ARRAY_SIZE(pjsua_var.acc); ++i) {
if (!pjsua_var.acc[i].valid)
continue;
ids[c] = i;
++c;
}
*count = c;
PJSUA_UNLOCK();
return PJ_SUCCESS;
}
/*
* Enum accounts info.
*/
PJ_DEF(pj_status_t) pjsua_acc_enum_info( pjsua_acc_info info[],
unsigned *count )
{
unsigned i, c;
PJ_ASSERT_RETURN(info && *count, PJ_EINVAL);
PJSUA_LOCK();
for (i=0, c=0; c<*count && i<PJ_ARRAY_SIZE(pjsua_var.acc); ++i) {
if (!pjsua_var.acc[i].valid)
continue;
pjsua_acc_get_info(i, &info[c]);
++c;
}
*count = c;
PJSUA_UNLOCK();
return PJ_SUCCESS;
}
/*
* This is an internal function to find the most appropriate account to
* used to reach to the specified URL.
*/
PJ_DEF(pjsua_acc_id) pjsua_acc_find_for_outgoing(const pj_str_t *url)
{
pj_str_t tmp;
pjsip_uri *uri;
pjsip_sip_uri *sip_uri;
pj_pool_t *tmp_pool;
unsigned i;
PJSUA_LOCK();
tmp_pool = pjsua_pool_create("tmpacc10", 256, 256);
pj_strdup_with_null(tmp_pool, &tmp, url);
uri = pjsip_parse_uri(tmp_pool, tmp.ptr, tmp.slen, 0);
if (!uri) {
pj_pool_release(tmp_pool);
PJSUA_UNLOCK();
return pjsua_var.default_acc;
}
if (!PJSIP_URI_SCHEME_IS_SIP(uri) &&
!PJSIP_URI_SCHEME_IS_SIPS(uri))
{
/* Return the first account with proxy */
for (i=0; i<PJ_ARRAY_SIZE(pjsua_var.acc); ++i) {
if (!pjsua_var.acc[i].valid)
continue;
if (!pj_list_empty(&pjsua_var.acc[i].route_set))
break;
}
if (i != PJ_ARRAY_SIZE(pjsua_var.acc)) {
/* Found rather matching account */
pj_pool_release(tmp_pool);
PJSUA_UNLOCK();
return i;
}
/* Not found, use default account */
pj_pool_release(tmp_pool);
PJSUA_UNLOCK();
return pjsua_var.default_acc;
}
sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(uri);
/* Find matching domain AND port */
for (i=0; i<pjsua_var.acc_cnt; ++i) {
unsigned acc_id = pjsua_var.acc_ids[i];
if (pj_stricmp(&pjsua_var.acc[acc_id].srv_domain, &sip_uri->host)==0 &&
pjsua_var.acc[acc_id].srv_port == sip_uri->port)
{
pj_pool_release(tmp_pool);
PJSUA_UNLOCK();
return acc_id;
}
}
/* If no match, try to match the domain part only */
for (i=0; i<pjsua_var.acc_cnt; ++i) {
unsigned acc_id = pjsua_var.acc_ids[i];
if (pj_stricmp(&pjsua_var.acc[acc_id].srv_domain, &sip_uri->host)==0)
{
pj_pool_release(tmp_pool);
PJSUA_UNLOCK();
return acc_id;
}
}
/* Still no match, just use default account */
pj_pool_release(tmp_pool);
PJSUA_UNLOCK();
return pjsua_var.default_acc;
}
/*
* This is an internal function to find the most appropriate account to be
* used to handle incoming calls.
*/
PJ_DEF(pjsua_acc_id) pjsua_acc_find_for_incoming(pjsip_rx_data *rdata)
{
pjsip_uri *uri;
pjsip_sip_uri *sip_uri;
pjsua_acc_id id = PJSUA_INVALID_ID;
unsigned i;
/* Check that there's at least one account configured */
PJ_ASSERT_RETURN(pjsua_var.acc_cnt!=0, pjsua_var.default_acc);
uri = rdata->msg_info.to->uri;
PJSUA_LOCK();
/* Use Req URI if To URI is not SIP */
if (!PJSIP_URI_SCHEME_IS_SIP(uri) &&
!PJSIP_URI_SCHEME_IS_SIPS(uri))
{
if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG)
uri = rdata->msg_info.msg->line.req.uri;
else
goto on_return;
}
/* Just return default account if both To and Req URI are not SIP: */
if (!PJSIP_URI_SCHEME_IS_SIP(uri) &&
!PJSIP_URI_SCHEME_IS_SIPS(uri))
{
goto on_return;
}
sip_uri = (pjsip_sip_uri*)pjsip_uri_get_uri(uri);
/* Find account which has matching username and domain. */
for (i=0; i < pjsua_var.acc_cnt; ++i) {
unsigned acc_id = pjsua_var.acc_ids[i];
pjsua_acc *acc = &pjsua_var.acc[acc_id];
if (acc->valid && pj_stricmp(&acc->user_part, &sip_uri->user)==0 &&
pj_stricmp(&acc->srv_domain, &sip_uri->host)==0)
{
/* Match ! */
id = acc_id;
goto on_return;
}
}
/* No matching account, try match domain part only. */
for (i=0; i < pjsua_var.acc_cnt; ++i) {
unsigned acc_id = pjsua_var.acc_ids[i];
pjsua_acc *acc = &pjsua_var.acc[acc_id];
if (acc->valid && pj_stricmp(&acc->srv_domain, &sip_uri->host)==0) {
/* Match ! */
id = acc_id;
goto on_return;
}
}
/* No matching account, try match user part (and transport type) only. */
for (i=0; i < pjsua_var.acc_cnt; ++i) {
unsigned acc_id = pjsua_var.acc_ids[i];
pjsua_acc *acc = &pjsua_var.acc[acc_id];
if (acc->valid && pj_stricmp(&acc->user_part, &sip_uri->user)==0) {
if (acc->tp_type != PJSIP_TRANSPORT_UNSPECIFIED &&
acc->tp_type != rdata->tp_info.transport->key.type)
{
continue;
}
/* Match ! */
id = acc_id;
goto on_return;
}
}
on_return:
PJSUA_UNLOCK();
/* Still no match, use default account */
if (id == PJSUA_INVALID_ID)
id = pjsua_var.default_acc;
/* Invoke account find callback */
if (pjsua_var.ua_cfg.cb.on_acc_find_for_incoming)
(*pjsua_var.ua_cfg.cb.on_acc_find_for_incoming)(rdata, &id);
/* Verify if the specified account id is valid */
if (!pjsua_acc_is_valid(id))
id = pjsua_var.default_acc;
return id;
}
/*
* Create arbitrary requests for this account.
*/
PJ_DEF(pj_status_t) pjsua_acc_create_request(pjsua_acc_id acc_id,
const pjsip_method *method,
const pj_str_t *target,
pjsip_tx_data **p_tdata)
{
pjsip_tx_data *tdata;
pjsua_acc *acc;
pjsip_route_hdr *r;
pj_status_t status;
PJ_ASSERT_RETURN(method && target && p_tdata, PJ_EINVAL);
PJ_ASSERT_RETURN(pjsua_acc_is_valid(acc_id), PJ_EINVAL);
acc = &pjsua_var.acc[acc_id];
status = pjsip_endpt_create_request(pjsua_var.endpt, method, target,
&acc->cfg.id, target,
NULL, NULL, -1, NULL, &tdata);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Unable to create request", status);
return status;
}
/* Copy routeset */
r = acc->route_set.next;
while (r != &acc->route_set) {
pjsip_msg_add_hdr(tdata->msg,
(pjsip_hdr*)pjsip_hdr_clone(tdata->pool, r));
r = r->next;
}
/* If account is locked to specific transport, then set that transport to
* the transmit data.
*/
if (pjsua_var.acc[acc_id].cfg.transport_id != PJSUA_INVALID_ID) {
pjsip_tpselector tp_sel;
pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel);
pjsip_tx_data_set_transport(tdata, &tp_sel);
}
/* If via_addr is set, use this address for the Via header. */
if (pjsua_var.acc[acc_id].cfg.allow_via_rewrite &&
pjsua_var.acc[acc_id].via_addr.host.slen > 0)
{
tdata->via_addr = pjsua_var.acc[acc_id].via_addr;
tdata->via_tp = pjsua_var.acc[acc_id].via_tp;
} else if (!pjsua_sip_acc_is_using_stun(acc_id)) {
/* Choose local interface to use in Via if acc is not using
* STUN
*/
pjsua_acc_get_uac_addr(acc_id, tdata->pool,
target,
&tdata->via_addr,
NULL, NULL,
&tdata->via_tp);
}
/* Done */
*p_tdata = tdata;
return PJ_SUCCESS;
}
/*
* Internal:
* determine if an address is a valid IP address, and if it is,
* return the IP version (4 or 6).
*/
static int get_ip_addr_ver(const pj_str_t *host)
{
pj_in_addr dummy;
pj_in6_addr dummy6;
/* First check if this is an IPv4 address */
if (pj_inet_pton(pj_AF_INET(), host, &dummy) == PJ_SUCCESS)
return 4;
/* Then check if this is an IPv6 address */
if (pj_inet_pton(pj_AF_INET6(), host, &dummy6) == PJ_SUCCESS)
return 6;
/* Not an IP address */
return 0;
}
/* Get local transport address suitable to be used for Via or Contact address
* to send request to the specified destination URI.
*/
pj_status_t pjsua_acc_get_uac_addr(pjsua_acc_id acc_id,
pj_pool_t *pool,
const pj_str_t *dst_uri,
pjsip_host_port *addr,
pjsip_transport_type_e *p_tp_type,
int *secure,
const void **p_tp)
{
pjsua_acc *acc;
pjsip_sip_uri *sip_uri;
pj_status_t status;
pjsip_transport_type_e tp_type = PJSIP_TRANSPORT_UNSPECIFIED;
unsigned flag;
pjsip_tpselector tp_sel;
pjsip_tpmgr *tpmgr;
pjsip_tpmgr_fla2_param tfla2_prm;
PJ_ASSERT_RETURN(pjsua_acc_is_valid(acc_id), PJ_EINVAL);
acc = &pjsua_var.acc[acc_id];
/* If route-set is configured for the account, then URI is the
* first entry of the route-set.
*/
if (!pj_list_empty(&acc->route_set)) {
sip_uri = (pjsip_sip_uri*)
pjsip_uri_get_uri(acc->route_set.next->name_addr.uri);
} else {
pj_str_t tmp;
pjsip_uri *uri;
pj_strdup_with_null(pool, &tmp, dst_uri);
uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0);
if (uri == NULL)
return PJSIP_EINVALIDURI;
/* For non-SIP scheme, route set should be configured */
if (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri))
return PJSIP_ENOROUTESET;
sip_uri = (pjsip_sip_uri*)pjsip_uri_get_uri(uri);
}
/* Get transport type of the URI */
if (PJSIP_URI_SCHEME_IS_SIPS(sip_uri))
tp_type = PJSIP_TRANSPORT_TLS;
else if (sip_uri->transport_param.slen == 0) {
tp_type = PJSIP_TRANSPORT_UDP;
} else
tp_type = pjsip_transport_get_type_from_name(&sip_uri->transport_param);
if (tp_type == PJSIP_TRANSPORT_UNSPECIFIED)
return PJSIP_EUNSUPTRANSPORT;
/* If destination URI specifies IPv6 or account is configured to use IPv6,
* then set transport type to use IPv6 as well.
*/
if (pj_strchr(&sip_uri->host, ':') || pjsua_sip_acc_is_using_ipv6(acc_id))
tp_type = (pjsip_transport_type_e)(((int)tp_type) |
PJSIP_TRANSPORT_IPV6);
flag = pjsip_transport_get_flag_from_type(tp_type);
/* Init transport selector. */
pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel);
/* Get local address suitable to send request from */
pjsip_tpmgr_fla2_param_default(&tfla2_prm);
tfla2_prm.tp_type = tp_type;
tfla2_prm.tp_sel = &tp_sel;
tfla2_prm.dst_host = sip_uri->host;
tfla2_prm.local_if = (!pjsua_sip_acc_is_using_stun(acc_id) ||
(flag & PJSIP_TRANSPORT_RELIABLE));
tpmgr = pjsip_endpt_get_tpmgr(pjsua_var.endpt);
status = pjsip_tpmgr_find_local_addr2(tpmgr, pool, &tfla2_prm);
if (status != PJ_SUCCESS)
return status;
/* Set this as default return value. This may be changed below
* for TCP/TLS
*/
addr->host = tfla2_prm.ret_addr;
addr->port = tfla2_prm.ret_port;
/* For TCP/TLS, acc may request to specify source port */
if (acc->cfg.contact_use_src_port) {
pjsip_host_info dinfo;
pjsip_transport *tp = NULL;
pj_addrinfo ai;
pj_bool_t log_written = PJ_FALSE;
status = pjsip_get_dest_info((pjsip_uri*)sip_uri, NULL,
pool, &dinfo);
if (status==PJ_SUCCESS && (dinfo.flag & PJSIP_TRANSPORT_RELIABLE)==0) {
/* Not TCP or TLS. No need to do this */
status = PJ_EINVALIDOP;
log_written = PJ_TRUE;
}
if (status==PJ_SUCCESS &&
get_ip_addr_ver(&dinfo.addr.host)==0 &&
pjsua_var.ua_cfg.nameserver_count)
{
/* If nameserver is configured, PJSIP will resolve destinations
* by their DNS SRV record first. On the other hand, we will
* resolve destination with DNS A record via pj_getaddrinfo().
* They may yield different IP addresses, hence causing different
* TCP/TLS connection to be created and hence different source
* address.
*/
PJ_LOG(4,(THIS_FILE, "Warning: cannot use source TCP/TLS socket"
" address for Contact when nameserver is configured."));
status = PJ_ENOTSUP;
log_written = PJ_TRUE;
}
if (status == PJ_SUCCESS) {
unsigned cnt=1;
int af = pj_AF_UNSPEC();
if (pjsua_sip_acc_is_using_ipv6(acc_id) ||
(dinfo.type & PJSIP_TRANSPORT_IPV6))
{
af = pj_AF_INET6();
}
status = pj_getaddrinfo(af, &dinfo.addr.host, &cnt, &ai);
if (cnt == 0) {
status = PJ_ENOTSUP;
} else if ((dinfo.type & PJSIP_TRANSPORT_IPV6)==0 &&
ai.ai_addr.addr.sa_family == pj_AF_INET6())
{
/* Destination is a hostname and account is not bound to IPv6,
* but hostname resolution reveals that it has IPv6 address,
* so let's use IPv6 transport type.
*/
dinfo.type |= PJSIP_TRANSPORT_IPV6;
tp_type |= PJSIP_TRANSPORT_IPV6;
}
}
if (status == PJ_SUCCESS) {
pjsip_tx_data tdata;
int addr_len = pj_sockaddr_get_len(&ai.ai_addr);
pj_uint16_t port = (pj_uint16_t)dinfo.addr.port;
/* Create a dummy tdata to inform remote host name to transport */
pj_bzero(&tdata, sizeof(tdata));
pj_strdup(pool, &tdata.dest_info.name, &dinfo.addr.host);
if (port==0) {
port = (dinfo.flag & PJSIP_TRANSPORT_SECURE) ? 5061 : 5060;
}
pj_sockaddr_set_port(&ai.ai_addr, port);
status = pjsip_endpt_acquire_transport2(pjsua_var.endpt,
dinfo.type,
&ai.ai_addr,
addr_len,
&tp_sel,
&tdata, &tp);
}
if (status == PJ_SUCCESS && (tp->local_name.port == 0 ||
tp->local_name.host.slen==0 ||
*tp->local_name.host.ptr=='0'))
{
/* Trap zero port or "0.0.0.0" address. */
/* The TCP/TLS transport is still connecting and unfortunately
* this OS doesn't report the bound local address in this state.
*/
PJ_LOG(4,(THIS_FILE, "Unable to get transport local port "
"for Contact address (OS doesn't support)"));
status = PJ_ENOTSUP;
log_written = PJ_TRUE;
}
if (status == PJ_SUCCESS) {
/* Got the local transport address */
pj_strdup(pool, &addr->host, &tp->local_name.host);
addr->port = tp->local_name.port;
}
if (tp) {
/* Here the transport's ref counter WILL reach zero. But the
* transport will NOT get destroyed because it should have an
* idle timer.
*/
pjsip_transport_dec_ref(tp);
tp = NULL;
}
if (status != PJ_SUCCESS && !log_written) {
PJ_PERROR(4,(THIS_FILE, status, "Unable to use source local "
"TCP socket address for Contact"));
}
status = PJ_SUCCESS;
}
if (p_tp_type)
*p_tp_type = tp_type;
if (secure) {
*secure = (flag & PJSIP_TRANSPORT_SECURE) != 0;
}
if (p_tp)
*p_tp = tfla2_prm.ret_tp;
return PJ_SUCCESS;
}
PJ_DEF(pj_status_t) pjsua_acc_create_uac_contact( pj_pool_t *pool,
pj_str_t *contact,
pjsua_acc_id acc_id,
const pj_str_t *suri)
{
pjsua_acc *acc;
pj_status_t status;
pjsip_transport_type_e tp_type;
pjsip_host_port addr;
int secure;
const char *beginquote, *endquote;
char transport_param[32];
const char *ob = ";ob";
PJ_ASSERT_RETURN(pjsua_acc_is_valid(acc_id), PJ_EINVAL);
acc = &pjsua_var.acc[acc_id];
/* If force_contact is configured, then use use it */
if (acc->cfg.force_contact.slen) {
*contact = acc->cfg.force_contact;
return PJ_SUCCESS;
}
status = pjsua_acc_get_uac_addr(acc_id, pool, suri, &addr,
&tp_type, &secure, NULL);
if (status != PJ_SUCCESS)
return status;
/* Enclose IPv6 address in square brackets */
if (tp_type & PJSIP_TRANSPORT_IPV6) {
beginquote = "[";
endquote = "]";
} else {
beginquote = endquote = "";
}
/* Don't add transport parameter if it's UDP */
if (tp_type!=PJSIP_TRANSPORT_UDP && tp_type!=PJSIP_TRANSPORT_UDP6) {
pj_ansi_snprintf(transport_param, sizeof(transport_param),
";transport=%s",
pjsip_transport_get_type_name(tp_type));
} else {
transport_param[0] = '\0';
}
/* Create the contact header */
contact->ptr = (char*)pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
contact->slen = pj_ansi_snprintf(contact->ptr, PJSIP_MAX_URL_SIZE,
"%s%.*s%s<%s:%.*s%s%s%.*s%s:%d%s%.*s%s>%.*s",
(acc->display.slen?"\"" : ""),
(int)acc->display.slen,
acc->display.ptr,
(acc->display.slen?"\" " : ""),
((secure && acc->is_sips)? "sips" : "sip"),
(int)acc->user_part.slen,
acc->user_part.ptr,
(acc->user_part.slen?"@":""),
beginquote,
(int)addr.host.slen,
addr.host.ptr,
endquote,
addr.port,
transport_param,
(int)acc->cfg.contact_uri_params.slen,
acc->cfg.contact_uri_params.ptr,
(acc->cfg.use_rfc5626? ob: ""),
(int)acc->cfg.contact_params.slen,
acc->cfg.contact_params.ptr);
if (contact->slen < 1 || contact->slen >= (int)PJSIP_MAX_URL_SIZE)
return PJ_ETOOSMALL;
return PJ_SUCCESS;
}
PJ_DEF(pj_status_t) pjsua_acc_create_uas_contact( pj_pool_t *pool,
pj_str_t *contact,
pjsua_acc_id acc_id,
pjsip_rx_data *rdata )
{
/*
* Section 12.1.1, paragraph about using SIPS URI in Contact.
* If the request that initiated the dialog contained a SIPS URI
* in the Request-URI or in the top Record-Route header field value,
* if there was any, or the Contact header field if there was no
* Record-Route header field, the Contact header field in the response
* MUST be a SIPS URI.
*/
pjsua_acc *acc;
pjsip_sip_uri *sip_uri;
pj_status_t status;
pjsip_transport_type_e tp_type = PJSIP_TRANSPORT_UNSPECIFIED;
pj_str_t local_addr;
pjsip_tpselector tp_sel;
pjsip_tpmgr *tpmgr;
pjsip_tpmgr_fla2_param tfla2_prm;
unsigned flag;
int secure;
int local_port;
const char *beginquote, *endquote;
char transport_param[32];
PJ_ASSERT_RETURN(pjsua_acc_is_valid(acc_id), PJ_EINVAL);
acc = &pjsua_var.acc[acc_id];
/* If force_contact is configured, then use use it */
if (acc->cfg.force_contact.slen) {
*contact = acc->cfg.force_contact;
return PJ_SUCCESS;
}
/* If Record-Route is present, then URI is the top Record-Route. */
if (rdata->msg_info.record_route) {
sip_uri = (pjsip_sip_uri*)
pjsip_uri_get_uri(rdata->msg_info.record_route->name_addr.uri);
} else {
pjsip_hdr *pos = NULL;
pjsip_contact_hdr *h_contact;
pjsip_uri *uri = NULL;
/* Otherwise URI is Contact URI.
* Iterate the Contact URI until we find sip: or sips: scheme.
*/
do {
h_contact = (pjsip_contact_hdr*)
pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT,
pos);
if (h_contact) {
if (h_contact->uri)
uri = (pjsip_uri*) pjsip_uri_get_uri(h_contact->uri);
else
uri = NULL;
if (!uri || (!PJSIP_URI_SCHEME_IS_SIP(uri) &&
!PJSIP_URI_SCHEME_IS_SIPS(uri)))
{
pos = (pjsip_hdr*)h_contact->next;
if (pos == &rdata->msg_info.msg->hdr)
h_contact = NULL;
} else {
break;
}
}
} while (h_contact);
/* Or if Contact URI is not present, take the remote URI from
* the From URI.
*/
if (uri == NULL)
uri = (pjsip_uri*) pjsip_uri_get_uri(rdata->msg_info.from->uri);
/* Can only do sip/sips scheme at present. */
if (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri))
return PJSIP_EINVALIDREQURI;
sip_uri = (pjsip_sip_uri*)pjsip_uri_get_uri(uri);
}
/* Get transport type of the URI */
if (PJSIP_URI_SCHEME_IS_SIPS(sip_uri))
tp_type = PJSIP_TRANSPORT_TLS;
else if (sip_uri->transport_param.slen == 0) {
tp_type = PJSIP_TRANSPORT_UDP;
} else
tp_type = pjsip_transport_get_type_from_name(&sip_uri->transport_param);
if (tp_type == PJSIP_TRANSPORT_UNSPECIFIED)
return PJSIP_EUNSUPTRANSPORT;
/* If destination URI specifies IPv6 or account is configured to use IPv6
* or the transport being used to receive data is an IPv6 transport,
* then set transport type to use IPv6 as well.
*/
if (pj_strchr(&sip_uri->host, ':') ||
pjsua_sip_acc_is_using_ipv6(acc_id) ||
(rdata->tp_info.transport->key.type & PJSIP_TRANSPORT_IPV6))
{
tp_type = (pjsip_transport_type_e)
(((int)tp_type) | PJSIP_TRANSPORT_IPV6);
}
flag = pjsip_transport_get_flag_from_type(tp_type);
secure = (flag & PJSIP_TRANSPORT_SECURE) != 0;
/* Init transport selector. */
pjsua_init_tpselector(pjsua_var.acc[acc_id].cfg.transport_id, &tp_sel);
/* Get local address suitable to send request from */
pjsip_tpmgr_fla2_param_default(&tfla2_prm);
tfla2_prm.tp_type = tp_type;
tfla2_prm.tp_sel = &tp_sel;
tfla2_prm.dst_host = sip_uri->host;
tfla2_prm.local_if = (!pjsua_sip_acc_is_using_stun(acc_id) ||
(flag & PJSIP_TRANSPORT_RELIABLE));
tpmgr = pjsip_endpt_get_tpmgr(pjsua_var.endpt);
status = pjsip_tpmgr_find_local_addr2(tpmgr, pool, &tfla2_prm);
if (status != PJ_SUCCESS)
return status;
local_addr = tfla2_prm.ret_addr;
local_port = tfla2_prm.ret_port;
/* Enclose IPv6 address in square brackets */
if (tp_type & PJSIP_TRANSPORT_IPV6) {
beginquote = "[";
endquote = "]";
} else {
beginquote = endquote = "";
}
/* Don't add transport parameter if it's UDP */
if (tp_type!=PJSIP_TRANSPORT_UDP && tp_type!=PJSIP_TRANSPORT_UDP6) {
pj_ansi_snprintf(transport_param, sizeof(transport_param),
";transport=%s",
pjsip_transport_get_type_name(tp_type));
} else {
transport_param[0] = '\0';
}
/* Create the contact header */
contact->ptr = (char*) pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
contact->slen = pj_ansi_snprintf(contact->ptr, PJSIP_MAX_URL_SIZE,
"%s%.*s%s<%s:%.*s%s%s%.*s%s:%d%s%.*s>%.*s",
(acc->display.slen?"\"" : ""),
(int)acc->display.slen,
acc->display.ptr,
(acc->display.slen?"\" " : ""),
((secure && acc->is_sips)? "sips" : "sip"),
(int)acc->user_part.slen,
acc->user_part.ptr,
(acc->user_part.slen?"@":""),
beginquote,
(int)local_addr.slen,
local_addr.ptr,
endquote,
local_port,
transport_param,
(int)acc->cfg.contact_uri_params.slen,
acc->cfg.contact_uri_params.ptr,
(int)acc->cfg.contact_params.slen,
acc->cfg.contact_params.ptr);
if (contact->slen < 1 || contact->slen >= (int)PJSIP_MAX_URL_SIZE)
return PJ_ETOOSMALL;
return PJ_SUCCESS;
}
PJ_DEF(pj_status_t) pjsua_acc_set_transport( pjsua_acc_id acc_id,
pjsua_transport_id tp_id)
{
pjsua_acc *acc;
PJ_ASSERT_RETURN(pjsua_acc_is_valid(acc_id), PJ_EINVAL);
acc = &pjsua_var.acc[acc_id];
PJ_ASSERT_RETURN(tp_id >= 0 && tp_id < (int)PJ_ARRAY_SIZE(pjsua_var.tpdata),
PJ_EINVAL);
acc->cfg.transport_id = tp_id;
acc->tp_type = pjsua_var.tpdata[tp_id].type;
return PJ_SUCCESS;
}
/* Auto re-registration timeout callback */
static void auto_rereg_timer_cb(pj_timer_heap_t *th, pj_timer_entry *te)
{
pjsua_acc *acc;
pj_status_t status;
PJ_UNUSED_ARG(th);
acc = (pjsua_acc*) te->user_data;
pj_assert(acc);
PJSUA_LOCK();
/* Check if the reregistration timer is still valid, e.g: while waiting
* timeout timer application might have deleted the account or disabled
* the auto-reregistration.
*/
if (!acc->valid || !acc->auto_rereg.active ||
acc->cfg.reg_retry_interval == 0)
{
goto on_return;
}
/* Start re-registration */
acc->auto_rereg.attempt_cnt++;
status = pjsua_acc_set_registration(acc->index, PJ_TRUE);
if (status != PJ_SUCCESS)
schedule_reregistration(acc);
on_return:
PJSUA_UNLOCK();
}
/* Schedule reregistration for specified account. Note that the first
* re-registration after a registration failure will be done immediately.
* Also note that this function should be called within PJSUA mutex.
*/
static void schedule_reregistration(pjsua_acc *acc)
{
pj_time_val delay;
pj_assert(acc);
/* Validate the account and re-registration feature status */
if (!acc->valid || acc->cfg.reg_retry_interval == 0) {
return;
}
/* If configured, disconnect calls of this account after the first
* reregistration attempt failed.
*/
if (acc->cfg.drop_calls_on_reg_fail && acc->auto_rereg.attempt_cnt >= 1)
{
unsigned i, cnt;
for (i = 0, cnt = 0; i < pjsua_var.ua_cfg.max_calls; ++i) {
if (pjsua_var.calls[i].acc_id == acc->index) {
pjsua_call_hangup(i, 0, NULL, NULL);
++cnt;
}
}
if (cnt) {
PJ_LOG(3, (THIS_FILE, "Disconnecting %d call(s) of account #%d "
"after reregistration attempt failed",
cnt, acc->index));
}
}
/* Cancel any re-registration timer */
if (acc->auto_rereg.timer.id) {
acc->auto_rereg.timer.id = PJ_FALSE;
pjsua_cancel_timer(&acc->auto_rereg.timer);
}
/* Update re-registration flag */
acc->auto_rereg.active = PJ_TRUE;
/* Set up timer for reregistration */
acc->auto_rereg.timer.cb = &auto_rereg_timer_cb;
acc->auto_rereg.timer.user_data = acc;
/* Reregistration attempt. The first attempt will be done immediately. */
delay.sec = acc->auto_rereg.attempt_cnt? acc->cfg.reg_retry_interval :
acc->cfg.reg_first_retry_interval;
delay.msec = 0;
/* Randomize interval by +/- reg_retry_random_interval, if configured */
if (acc->cfg.reg_retry_random_interval) {
long rand_ms = acc->cfg.reg_retry_random_interval * 1000;
if (delay.sec >= (long)acc->cfg.reg_retry_random_interval) {
delay.msec = -rand_ms + (pj_rand() % (rand_ms * 2));
} else {
delay.sec = 0;
delay.msec = (pj_rand() % (delay.sec * 1000 + rand_ms));
}
}
pj_time_val_normalize(&delay);
PJ_LOG(4,(THIS_FILE,
"Scheduling re-registration retry for acc %d in %u seconds..",
acc->index, delay.sec));
acc->auto_rereg.timer.id = PJ_TRUE;
if (pjsua_schedule_timer(&acc->auto_rereg.timer, &delay) != PJ_SUCCESS)
acc->auto_rereg.timer.id = PJ_FALSE;
}
/* Internal function to perform auto-reregistration on transport
* connection/disconnection events.
*/
void pjsua_acc_on_tp_state_changed(pjsip_transport *tp,
pjsip_transport_state state,
const pjsip_transport_state_info *info)
{
unsigned i;
PJ_UNUSED_ARG(info);
/* Only care for transport disconnection events */
if (state != PJSIP_TP_STATE_DISCONNECTED)
return;
PJ_LOG(4,(THIS_FILE, "Disconnected notification for transport %s",
tp->obj_name));
pj_log_push_indent();
/* Shutdown this transport, to make sure that the transport manager
* will create a new transport for reconnection.
*/
pjsip_transport_shutdown(tp);
PJSUA_LOCK();
/* Enumerate accounts using this transport and perform actions
* based on the transport state.
*/
for (i = 0; i < PJ_ARRAY_SIZE(pjsua_var.acc); ++i) {
pjsua_acc *acc = &pjsua_var.acc[i];
/* Skip if this account is not valid. */
if (!acc->valid)
continue;
/* Release transport immediately if regc is using it
* See https://trac.pjsip.org/repos/ticket/1481
*/
if (acc->regc) {
pjsip_regc_info reg_info;
pjsip_regc_get_info(acc->regc, ®_info);
if (reg_info.transport != tp)
continue;
pjsip_regc_release_transport(pjsua_var.acc[i].regc);
/* Schedule reregistration for this account */
if (acc->cfg.reg_retry_interval) {
schedule_reregistration(acc);
}
}
}
PJSUA_UNLOCK();
pj_log_pop_indent();
}
|
ZiberLTD/windows
|
pjsip/src/pjsua-lib/pjsua_acc.c
|
C
|
gpl-2.0
| 107,703
|
<?php $captcha_word = 'R75S'; ?>
|
CoordCulturaDigital-Minc/setoriais
|
wp-content/plugins/si-captcha-for-wordpress/captcha/temp/sQ5mnMOQmEJcMCR2.php
|
PHP
|
gpl-2.0
| 32
|
/* This file is part of the KDE project
Copyright (C) 2004 David Faure <faure@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kio_trash.h"
#include <kio/job.h>
#include <kapplication.h>
#include <kdebug.h>
#include <klocale.h>
#include <klargefile.h>
#include <kcmdlineargs.h>
#include <kmimetype.h>
#include <kprocess.h>
#include <dcopclient.h>
#include <qdatastream.h>
#include <qtextstream.h>
#include <qfile.h>
#include <qeventloop.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
static const KCmdLineOptions options[] =
{
{ "+protocol", I18N_NOOP( "Protocol name" ), 0 },
{ "+pool", I18N_NOOP( "Socket name" ), 0 },
{ "+app", I18N_NOOP( "Socket name" ), 0 },
KCmdLineLastOption
};
extern "C" {
int KDE_EXPORT kdemain( int argc, char **argv )
{
//KInstance instance( "kio_trash" );
// KApplication is necessary to use kio_file
putenv(strdup("SESSION_MANAGER="));
KApplication::disableAutoDcopRegistration();
KCmdLineArgs::init(argc, argv, "kio_trash", 0, 0, 0, 0);
KCmdLineArgs::addCmdLineOptions( options );
KApplication app( false, false );
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
TrashProtocol slave( args->arg(0), args->arg(1), args->arg(2) );
slave.dispatchLoop();
return 0;
}
}
#define INIT_IMPL \
if ( !impl.init() ) { \
error( impl.lastErrorCode(), impl.lastErrorMessage() ); \
return; \
}
TrashProtocol::TrashProtocol( const QCString& protocol, const QCString &pool, const QCString &app)
: SlaveBase(protocol, pool, app )
{
struct passwd *user = getpwuid( getuid() );
if ( user )
m_userName = QString::fromLatin1(user->pw_name);
struct group *grp = getgrgid( getgid() );
if ( grp )
m_groupName = QString::fromLatin1(grp->gr_name);
}
TrashProtocol::~TrashProtocol()
{
}
void TrashProtocol::restore( const KURL& trashURL )
{
int trashId;
QString fileId, relativePath;
bool ok = TrashImpl::parseURL( trashURL, trashId, fileId, relativePath );
if ( !ok ) {
error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( trashURL.prettyURL() ) );
return;
}
TrashedFileInfo info;
ok = impl.infoForFile( trashId, fileId, info );
if ( !ok ) {
error( impl.lastErrorCode(), impl.lastErrorMessage() );
return;
}
KURL dest;
dest.setPath( info.origPath );
if ( !relativePath.isEmpty() )
dest.addPath( relativePath );
// Check that the destination directory exists, to improve the error code in case it doesn't.
const QString destDir = dest.directory();
KDE_struct_stat buff;
if ( KDE_lstat( QFile::encodeName( destDir ), &buff ) == -1 ) {
error( KIO::ERR_SLAVE_DEFINED,
i18n( "The directory %1 does not exist anymore, so it is not possible to restore this item to its original location. "
"You can either recreate that directory and use the restore operation again, or drag the item anywhere else to restore it." ).arg( destDir ) );
return;
}
copyOrMove( trashURL, dest, false /*overwrite*/, Move );
}
void TrashProtocol::rename( const KURL &oldURL, const KURL &newURL, bool overwrite )
{
INIT_IMPL;
kdDebug()<<"TrashProtocol::rename(): old="<<oldURL<<" new="<<newURL<<" overwrite=" << overwrite<<endl;
if ( oldURL.protocol() == "trash" && newURL.protocol() == "trash" ) {
error( KIO::ERR_CANNOT_RENAME, oldURL.prettyURL() );
return;
}
copyOrMove( oldURL, newURL, overwrite, Move );
}
void TrashProtocol::copy( const KURL &src, const KURL &dest, int /*permissions*/, bool overwrite )
{
INIT_IMPL;
kdDebug()<<"TrashProtocol::copy(): " << src << " " << dest << endl;
if ( src.protocol() == "trash" && dest.protocol() == "trash" ) {
error( KIO::ERR_UNSUPPORTED_ACTION, i18n( "This file is already in the trash bin." ) );
return;
}
copyOrMove( src, dest, overwrite, Copy );
}
void TrashProtocol::copyOrMove( const KURL &src, const KURL &dest, bool overwrite, CopyOrMove action )
{
if ( src.protocol() == "trash" && dest.isLocalFile() ) {
// Extracting (e.g. via dnd). Ignore original location stored in info file.
int trashId;
QString fileId, relativePath;
bool ok = TrashImpl::parseURL( src, trashId, fileId, relativePath );
if ( !ok ) {
error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( src.prettyURL() ) );
return;
}
const QString destPath = dest.path();
if ( QFile::exists( destPath ) ) {
if ( overwrite ) {
ok = QFile::remove( destPath );
Q_ASSERT( ok ); // ### TODO
} else {
error( KIO::ERR_FILE_ALREADY_EXIST, destPath );
return;
}
}
if ( action == Move ) {
kdDebug() << "calling moveFromTrash(" << destPath << " " << trashId << " " << fileId << ")" << endl;
ok = impl.moveFromTrash( destPath, trashId, fileId, relativePath );
} else { // Copy
kdDebug() << "calling copyFromTrash(" << destPath << " " << trashId << " " << fileId << ")" << endl;
ok = impl.copyFromTrash( destPath, trashId, fileId, relativePath );
}
if ( !ok ) {
error( impl.lastErrorCode(), impl.lastErrorMessage() );
} else {
if ( action == Move && relativePath.isEmpty() )
(void)impl.deleteInfo( trashId, fileId );
finished();
}
return;
} else if ( src.isLocalFile() && dest.protocol() == "trash" ) {
QString dir = dest.directory();
//kdDebug() << "trashing a file to " << dir << endl;
// Trashing a file
// We detect the case where this isn't normal trashing, but
// e.g. if kwrite tries to save (moving tempfile over destination)
if ( dir.length() <= 1 && src.fileName() == dest.fileName() ) // new toplevel entry
{
const QString srcPath = src.path();
// In theory we should use TrashImpl::parseURL to give the right filename to createInfo,
// in case the trash URL didn't contain the same filename as srcPath.
// But this can only happen with copyAs/moveAs, not available in the GUI
// for the trash (New/... or Rename from iconview/listview).
int trashId;
QString fileId;
if ( !impl.createInfo( srcPath, trashId, fileId ) ) {
error( impl.lastErrorCode(), impl.lastErrorMessage() );
} else {
bool ok;
if ( action == Move ) {
kdDebug() << "calling moveToTrash(" << srcPath << " " << trashId << " " << fileId << ")" << endl;
ok = impl.moveToTrash( srcPath, trashId, fileId );
} else { // Copy
kdDebug() << "calling copyToTrash(" << srcPath << " " << trashId << " " << fileId << ")" << endl;
ok = impl.copyToTrash( srcPath, trashId, fileId );
}
if ( !ok ) {
(void)impl.deleteInfo( trashId, fileId );
error( impl.lastErrorCode(), impl.lastErrorMessage() );
} else {
// Inform caller of the final URL. Used by konq_undo.
const KURL url = impl.makeURL( trashId, fileId, QString::null );
setMetaData( "trashURL-" + srcPath, url.url() );
finished();
}
}
return;
} else {
kdDebug() << "returning KIO::ERR_ACCESS_DENIED, it's not allowed to add a file to an existing trash directory" << endl;
// It's not allowed to add a file to an existing trash directory.
error( KIO::ERR_ACCESS_DENIED, dest.prettyURL() );
return;
}
} else
error( KIO::ERR_UNSUPPORTED_ACTION, "should never happen" );
}
static void addAtom(KIO::UDSEntry& entry, unsigned int ID, long long l, const QString& s = QString::null)
{
KIO::UDSAtom atom;
atom.m_uds = ID;
atom.m_long = l;
atom.m_str = s;
entry.append(atom);
}
void TrashProtocol::createTopLevelDirEntry(KIO::UDSEntry& entry)
{
entry.clear();
addAtom(entry, KIO::UDS_NAME, 0, ".");
addAtom(entry, KIO::UDS_FILE_TYPE, S_IFDIR);
addAtom(entry, KIO::UDS_ACCESS, 0700);
addAtom(entry, KIO::UDS_MIME_TYPE, 0, "inode/directory");
addAtom(entry, KIO::UDS_USER, 0, m_userName);
addAtom(entry, KIO::UDS_GROUP, 0, m_groupName);
}
void TrashProtocol::stat(const KURL& url)
{
INIT_IMPL;
const QString path = url.path();
if( path.isEmpty() || path == "/" ) {
// The root is "virtual" - it's not a single physical directory
KIO::UDSEntry entry;
createTopLevelDirEntry( entry );
statEntry( entry );
finished();
} else {
int trashId;
QString fileId, relativePath;
bool ok = TrashImpl::parseURL( url, trashId, fileId, relativePath );
if ( !ok ) {
// ######## do we still need this?
kdDebug() << k_funcinfo << url << " looks fishy, returning does-not-exist" << endl;
// A URL like trash:/file simply means that CopyJob is trying to see if
// the destination exists already (it made up the URL by itself).
error( KIO::ERR_DOES_NOT_EXIST, url.prettyURL() );
//error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( url.prettyURL() ) );
return;
}
const QString filePath = impl.physicalPath( trashId, fileId, relativePath );
if ( filePath.isEmpty() ) {
error( impl.lastErrorCode(), impl.lastErrorMessage() );
return;
}
QString fileName = filePath.section('/', -1, -1, QString::SectionSkipEmpty);
QString fileURL = QString::null;
if ( url.path().length() > 1 ) {
fileURL = url.url();
}
KIO::UDSEntry entry;
TrashedFileInfo info;
ok = impl.infoForFile( trashId, fileId, info );
if ( ok )
ok = createUDSEntry( filePath, fileName, fileURL, entry, info );
if ( !ok ) {
error( KIO::ERR_COULD_NOT_STAT, url.prettyURL() );
}
statEntry( entry );
finished();
}
}
void TrashProtocol::del( const KURL &url, bool /*isfile*/ )
{
int trashId;
QString fileId, relativePath;
bool ok = TrashImpl::parseURL( url, trashId, fileId, relativePath );
if ( !ok ) {
error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( url.prettyURL() ) );
return;
}
ok = relativePath.isEmpty();
if ( !ok ) {
error( KIO::ERR_ACCESS_DENIED, url.prettyURL() );
return;
}
ok = impl.del(trashId, fileId);
if ( !ok ) {
error( impl.lastErrorCode(), impl.lastErrorMessage() );
return;
}
finished();
}
void TrashProtocol::listDir(const KURL& url)
{
INIT_IMPL;
kdDebug() << "listdir: " << url << endl;
if ( url.path().length() <= 1 ) {
listRoot();
return;
}
int trashId;
QString fileId;
QString relativePath;
bool ok = TrashImpl::parseURL( url, trashId, fileId, relativePath );
if ( !ok ) {
error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( url.prettyURL() ) );
return;
}
//was: const QString physicalPath = impl.physicalPath( trashId, fileId, relativePath );
// Get info for deleted directory - the date of deletion and orig path will be used
// for all the items in it, and we need the physicalPath.
TrashedFileInfo info;
ok = impl.infoForFile( trashId, fileId, info );
if ( !ok || info.physicalPath.isEmpty() ) {
error( impl.lastErrorCode(), impl.lastErrorMessage() );
return;
}
if ( !relativePath.isEmpty() ) {
info.physicalPath += "/";
info.physicalPath += relativePath;
}
// List subdir. Can't use kio_file here since we provide our own info...
kdDebug() << k_funcinfo << "listing " << info.physicalPath << endl;
QStrList entryNames = impl.listDir( info.physicalPath );
totalSize( entryNames.count() );
KIO::UDSEntry entry;
QStrListIterator entryIt( entryNames );
for (; entryIt.current(); ++entryIt) {
QString fileName = QFile::decodeName( entryIt.current() );
if ( fileName == ".." )
continue;
const QString filePath = info.physicalPath + "/" + fileName;
// shouldn't be necessary
//const QString url = TrashImpl::makeURL( trashId, fileId, relativePath + "/" + fileName );
entry.clear();
TrashedFileInfo infoForItem( info );
infoForItem.origPath += '/';
infoForItem.origPath += fileName;
if ( ok && createUDSEntry( filePath, fileName, QString::null /*url*/, entry, infoForItem ) ) {
listEntry( entry, false );
}
}
entry.clear();
listEntry( entry, true );
finished();
}
bool TrashProtocol::createUDSEntry( const QString& physicalPath, const QString& fileName, const QString& url, KIO::UDSEntry& entry, const TrashedFileInfo& info )
{
QCString physicalPath_c = QFile::encodeName( physicalPath );
KDE_struct_stat buff;
if ( KDE_lstat( physicalPath_c, &buff ) == -1 ) {
kdWarning() << "couldn't stat " << physicalPath << endl;
return false;
}
if (S_ISLNK(buff.st_mode)) {
char buffer2[ 1000 ];
int n = readlink( physicalPath_c, buffer2, 1000 );
if ( n != -1 ) {
buffer2[ n ] = 0;
}
addAtom( entry, KIO::UDS_LINK_DEST, 0, QFile::decodeName( buffer2 ) );
// Follow symlink
// That makes sense in kio_file, but not in the trash, especially for the size
// #136876
#if 0
if ( KDE_stat( physicalPath_c, &buff ) == -1 ) {
// It is a link pointing to nowhere
buff.st_mode = S_IFLNK | S_IRWXU | S_IRWXG | S_IRWXO;
buff.st_mtime = 0;
buff.st_atime = 0;
buff.st_size = 0;
}
#endif
}
mode_t type = buff.st_mode & S_IFMT; // extract file type
mode_t access = buff.st_mode & 07777; // extract permissions
access &= 07555; // make it readonly, since it's in the trashcan
addAtom( entry, KIO::UDS_NAME, 0, fileName );
addAtom( entry, KIO::UDS_FILE_TYPE, type );
if ( !url.isEmpty() )
addAtom( entry, KIO::UDS_URL, 0, url );
KMimeType::Ptr mt = KMimeType::findByPath( physicalPath, buff.st_mode );
addAtom( entry, KIO::UDS_MIME_TYPE, 0, mt->name() );
addAtom( entry, KIO::UDS_ACCESS, access );
addAtom( entry, KIO::UDS_SIZE, buff.st_size );
addAtom( entry, KIO::UDS_USER, 0, m_userName ); // assumption
addAtom( entry, KIO::UDS_GROUP, 0, m_groupName ); // assumption
addAtom( entry, KIO::UDS_MODIFICATION_TIME, buff.st_mtime );
addAtom( entry, KIO::UDS_ACCESS_TIME, buff.st_atime ); // ## or use it for deletion time?
addAtom( entry, KIO::UDS_EXTRA, 0, info.origPath );
addAtom( entry, KIO::UDS_EXTRA, 0, info.deletionDate.toString( Qt::ISODate ) );
return true;
}
void TrashProtocol::listRoot()
{
INIT_IMPL;
const TrashedFileInfoList lst = impl.list();
totalSize( lst.count() );
KIO::UDSEntry entry;
createTopLevelDirEntry( entry );
listEntry( entry, false );
for ( TrashedFileInfoList::ConstIterator it = lst.begin(); it != lst.end(); ++it ) {
const KURL url = TrashImpl::makeURL( (*it).trashId, (*it).fileId, QString::null );
KURL origURL;
origURL.setPath( (*it).origPath );
entry.clear();
if ( createUDSEntry( (*it).physicalPath, origURL.fileName(), url.url(), entry, *it ) )
listEntry( entry, false );
}
entry.clear();
listEntry( entry, true );
finished();
}
void TrashProtocol::special( const QByteArray & data )
{
INIT_IMPL;
QDataStream stream( data, IO_ReadOnly );
int cmd;
stream >> cmd;
switch (cmd) {
case 1:
if ( impl.emptyTrash() )
finished();
else
error( impl.lastErrorCode(), impl.lastErrorMessage() );
break;
case 2:
impl.migrateOldTrash();
finished();
break;
case 3:
{
KURL url;
stream >> url;
restore( url );
break;
}
default:
kdWarning(7116) << "Unknown command in special(): " << cmd << endl;
error( KIO::ERR_UNSUPPORTED_ACTION, QString::number(cmd) );
break;
}
}
void TrashProtocol::put( const KURL& url, int /*permissions*/, bool /*overwrite*/, bool /*resume*/ )
{
INIT_IMPL;
kdDebug() << "put: " << url << endl;
// create deleted file. We need to get the mtime and original location from metadata...
// Maybe we can find the info file for url.fileName(), in case ::rename() was called first, and failed...
error( KIO::ERR_ACCESS_DENIED, url.prettyURL() );
}
void TrashProtocol::get( const KURL& url )
{
INIT_IMPL;
kdDebug() << "get() : " << url << endl;
if ( !url.isValid() ) {
kdDebug() << kdBacktrace() << endl;
error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( url.url() ) );
return;
}
if ( url.path().length() <= 1 ) {
error( KIO::ERR_IS_DIRECTORY, url.prettyURL() );
return;
}
int trashId;
QString fileId;
QString relativePath;
bool ok = TrashImpl::parseURL( url, trashId, fileId, relativePath );
if ( !ok ) {
error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( url.prettyURL() ) );
return;
}
const QString physicalPath = impl.physicalPath( trashId, fileId, relativePath );
if ( physicalPath.isEmpty() ) {
error( impl.lastErrorCode(), impl.lastErrorMessage() );
return;
}
// Usually we run jobs in TrashImpl (for e.g. future kdedmodule)
// But for this one we wouldn't use DCOP for every bit of data...
KURL fileURL;
fileURL.setPath( physicalPath );
KIO::Job* job = KIO::get( fileURL );
connect( job, SIGNAL( data( KIO::Job*, const QByteArray& ) ),
this, SLOT( slotData( KIO::Job*, const QByteArray& ) ) );
connect( job, SIGNAL( mimetype( KIO::Job*, const QString& ) ),
this, SLOT( slotMimetype( KIO::Job*, const QString& ) ) );
connect( job, SIGNAL( result(KIO::Job *) ),
this, SLOT( jobFinished(KIO::Job *) ) );
qApp->eventLoop()->enterLoop();
}
void TrashProtocol::slotData( KIO::Job*, const QByteArray&arr )
{
data( arr );
}
void TrashProtocol::slotMimetype( KIO::Job*, const QString& mt )
{
mimeType( mt );
}
void TrashProtocol::jobFinished( KIO::Job* job )
{
if ( job->error() )
error( job->error(), job->errorText() );
else
finished();
qApp->eventLoop()->exitLoop();
}
#if 0
void TrashProtocol::mkdir( const KURL& url, int /*permissions*/ )
{
INIT_IMPL;
// create info about deleted dir
// ############ Problem: we don't know the original path.
// Let's try to avoid this case (we should get to copy() instead, for local files)
kdDebug() << "mkdir: " << url << endl;
QString dir = url.directory();
if ( dir.length() <= 1 ) // new toplevel entry
{
// ## we should use TrashImpl::parseURL to give the right filename to createInfo
int trashId;
QString fileId;
if ( !impl.createInfo( url.path(), trashId, fileId ) ) {
error( impl.lastErrorCode(), impl.lastErrorMessage() );
} else {
if ( !impl.mkdir( trashId, fileId, permissions ) ) {
(void)impl.deleteInfo( trashId, fileId );
error( impl.lastErrorCode(), impl.lastErrorMessage() );
} else
finished();
}
} else {
// Well it's not allowed to add a directory to an existing deleted directory.
error( KIO::ERR_ACCESS_DENIED, url.prettyURL() );
}
}
#endif
#include "kio_trash.moc"
|
iegor/kdebase
|
kioslave/trash/kio_trash.cpp
|
C++
|
gpl-2.0
| 20,976
|
import unittest
from mock import Mock
import os
from katello.tests.core.action_test_utils import CLIOptionTestCase, CLIActionTestCase
from katello.tests.core.repo import repo_data
import katello.client.core.repo
from katello.client.core.repo import Status
from katello.client.api.utils import ApiDataError
class RequiredCLIOptionsTests(CLIOptionTestCase):
#repo is defined by either (org, product, repo_name, env name) or repo_id
action = Status()
disallowed_options = [
('--name=repo1', '--product=product1'),
('--org=ACME', '--name=repo1'),
('--org=ACME', '--product=product1'),
(),
]
allowed_options = [
('--org=ACME', '--name=repo1', '--product=product1'),
('--id=repo_id1', ),
]
class RepoStatusTest(CLIActionTestCase):
ORG_NAME = "org_1"
PROD_NAME = "product_1"
REPO = repo_data.REPOS[0]
ENV_NAME = "env_1"
OPTIONS_WITH_ID = {
'id': REPO['id'],
}
OPTIONS_WITH_NAME = {
'name': REPO['name'],
'product': PROD_NAME,
'org': ORG_NAME,
'environment': ENV_NAME,
}
repo = None
def setUp(self):
self.set_action(Status())
self.set_module(katello.client.core.repo)
self.mock_printer()
self.mock_options(self.OPTIONS_WITH_NAME)
self.mock(self.action.api, 'repo', self.REPO)
self.mock(self.action.api, 'last_sync_status', repo_data.SYNC_RESULT_WITHOUT_ERROR)
self.repo = self.mock(self.module, 'get_repo', self.REPO).return_value
def tearDown(self):
self.restore_mocks()
def test_finds_repo_by_id(self):
self.mock_options(self.OPTIONS_WITH_ID)
self.run_action()
self.action.api.repo.assert_called_once_with(self.REPO['id'])
def test_finds_repo_by_name(self):
self.mock_options(self.OPTIONS_WITH_NAME)
self.run_action()
self.module.get_repo.assert_called_once_with(self.ORG_NAME,
self.REPO['name'],
self.PROD_NAME, None,
None, self.ENV_NAME,
False, None, None, None)
def test_returns_with_error_when_no_repo_found(self):
self.mock_options(self.OPTIONS_WITH_NAME)
self.mock(self.module, 'get_repo').side_effect = ApiDataError()
self.run_action(os.EX_DATAERR)
def test_it_calls_last_sync_status_api(self):
self.run_action()
self.action.api.last_sync_status.assert_called_once_with(self.REPO['id'])
def test_it_does_not_set_progress_for_not_running_sync(self):
self.run_action()
self.assertRaises(KeyError, lambda: self.repo['progress'] )
def test_it_sets_progress_for_running_sync(self):
self.mock(self.action.api, 'last_sync_status', repo_data.SYNC_RUNNING_RESULT)
self.run_action()
self.assertTrue(isinstance(self.repo['progress'], str))
|
Katello/katello-cli
|
test/katello/tests/core/repo/repo_status_test.py
|
Python
|
gpl-2.0
| 3,038
|
<?php
/**
* Created by PhpStorm.
* User: tiemanntan
* Date: 16/11/15
* Time: 16:51
*/
class Nextorder_Yandexmetrica_Block_Adminhtml_System_Config_Result
extends Mage_Adminhtml_Block_Abstract
implements Varien_Data_Form_Element_Renderer_Interface{
public function render(Varien_Data_Form_Element_Abstract $element){
$countID = Mage::helper('yandexmetrica/data')->getCountID();
$resultURL = "https://metrika.yandex.ru/dashboard?id=". $countID;
$html ="<button type='button' id='result'><a style='color:white' href='". $resultURL ."'>Analyse Result bei Yandex Dashboard</a></button>";
return $html;
}
}
|
fatalerrortan/Magento_Yandexmetrica
|
app/code/local/Nextorder/Yandexmetrica/Block/Adminhtml/System/Config/Result.php
|
PHP
|
gpl-2.0
| 657
|
/*
* Player - One Hell of a Robot Server
* Copyright (C) 2010
* Mayte Lázaro, Alejandro R. Mosteo
*
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef SUB_OPT_H_
#define SUB_OPT_H_
#include "transf.hh"
void EIFnn(Matrix H, Matrix G, Matrix h, Matrix S, Matrix &F, Matrix &N);
void CalculateEstimationEIFnn(Matrix Fk, Matrix Nk, Matrix &x, Matrix &P);
#endif /* SUB_OPT_H_ */
|
swem/player-git-svn
|
server/drivers/localization/ekfvloc/sub_opt.hh
|
C++
|
gpl-2.0
| 1,106
|
/*
* linux/include/asm-arm/arch-davinci/memory.h
*
* BRIEF MODULE DESCRIPTION
* DAVINCI Virtual memory definitions
*
* Copyright (C) 2004 Texas Instruments.
*
* 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 SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE AUTHOR 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.
*
* 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.
*
*/
#ifndef __ASM_ARCH_MEMORY_H
#define __ASM_ARCH_MEMORY_H
/**************************************************************************
* Included Files
**************************************************************************/
#include <asm/arch/hardware.h>
#include <linux/version.h> /* for KERNEL_VERSION() */
#include <linux/bsp_config.h> /* for CONFIG_DSP_START_ADDR */
/**************************************************************************
* Definitions
**************************************************************************/
/* Task size: 3GB */
#define TASK_SIZE UL(0xbf000000)
/* TASK_SIZE_26 has moved to asm-arm/memory.h */
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,15)
#define TASK_SIZE_26 (0x04000000UL)
#endif
/* This decides where the kernel will search for a free chunk of vm
* space during mmap's.
*/
#define TASK_UNMAPPED_BASE (0x40000000)
/*#define TASK_UNMAPPED_BASE (TASK_SIZE / 3)*/
/* The start of physical memory available to the kernel. This value
* is used in the arch-specific bootup code like setup_arch &
* bootmem_init. This may or may not be the start of physical memory;
* There may be memory reserved "in front" of the kernel for other
* purposes.
*/
#define DAVINCI_DDR_BASE 0x80000000
#define DAVINCI_RESET_VECTOR_BASE 0x00000000
#define DAVINCI_IRAM_BASE 0x00008000 /* ARM Internal RAM (Data) */
#define DAVINCI_IRAM_VIRT 0xe1000000
#define DAVINCI_PERI_PADDR 0x01c00000
#define DAVINCI_PERI_VADDR 0xe1400000
#define DAVINCI_PERI_SIZE 0x00400000
/* DaVinci Peripheral Base Address */
#define DAVINCI_PERI_ADDR(x) ((x) - DAVINCI_PERI_PADDR + DAVINCI_PERI_VADDR)
#define PHYS_OFFSET DAVINCI_DDR_BASE
/*
* Ingenient memory layout
*/
#define DSP_L1DSRAM_PADDR 0x11800000
#define DSP_L1DSRAM_SIZE SZ_8M
#define INGENIENT_REBOOT_FLAG_OFFSET (SZ_16K-SZ_1K)
#define INGENIENT_REBOOT_FLAG_PADDR (DAVINCI_IRAM_BASE+INGENIENT_REBOOT_FLAG_OFFSET)
#define INGENIENT_REBOOT_FLAG_VADDR (DAVINCI_IRAM_VIRT+DAVINCI_IRAM_BASE+INGENIENT_REBOOT_FLAG_OFFSET)
#if defined( CONFIG_DSP_START_ADDR )
#define DSP_START CONFIG_DSP_START_ADDR
#else
#define DSP_START (DAVINCI_DDR_BASE + (3*SZ_16M))
#endif
#define DSP_SIZE ((PHYS_SDRAM_1)+(PHYS_SDRAM_1_SIZE)-(DSP_START))
#define DSP_IPC_START (DSP_START - SZ_8K)
#define DSP_IPC_SIZE SZ_8K
#define IMEM_START virt_to_phys(high_memory)
#define IMEM_SIZE (DSP_IPC_START - IMEM_START)
#define DAVINCI_FLASH_VIRT 0xe1500000
#define DSP_IPC_BOOTMEM_BASE 0xe2500000
#define DSP_L1DSRAM_BASE 0xe2600000
#define DSP_IPC_BASE (DSP_IPC_BOOTMEM_BASE + DSP_IPC_BOOTMEM_SIZE - DSP_IPC_SIZE)
#define IMEM_BASE imanage_imem_base // ioremap'ed address
#ifndef __ASSEMBLY__
extern unsigned long IMEM_BASE;
#endif
#define INGENIENT_INTERNAL_ILOG_OFFSET SZ_8K
#define INGENIENT_INTERNAL_ILOG_VADDR (DAVINCI_IRAM_VIRT + DAVINCI_IRAM_BASE + INGENIENT_INTERNAL_ILOG_OFFSET)
#define INGENIENT_INTERNAL_ILOG_PADDR (DAVINCI_IRAM_BASE + INGENIENT_INTERNAL_ILOG_OFFSET)
#define INGENIENT_INTERNAL_ILOG_MAX_SIZE (INGENIENT_REBOOT_FLAG_OFFSET-INGENIENT_INTERNAL_ILOG_OFFSET)
/* Macros for DSP VA2PA, PA2VA, and Straight writes */
#define __dsp(a) (DSP_BASE + a)
#define __dsp_v2p(a) ((a) - DSP_BASE + DSP_START)
#define __dsp_p2v(a) ((a) - DSP_START + DSP_BASE)
/* Macros for IMEM */
#define __imem(a) (IMEM_BASE + a)
#define __imem_v2p(a) ((a) - IMEM_BASE + IMEM_START)
#define __imem_p2v(a) ((a) - IMEM_START + IMEM_BASE)
/*
* Bus address is physical address
*/
#define __virt_to_bus(x) __virt_to_phys(x)
#define __bus_to_virt(x) __phys_to_virt(x)
#endif /* __ASM_ARCH_MEMORY_H */
|
gerboland/linux-2.6.15-neuros-eabi
|
include/asm-arm/arch-davinci/memory.h
|
C
|
gpl-2.0
| 5,211
|
//SpikeStream includes
#include "Globals.h"
#include "NetworkDisplay.h"
#include "ConnectionGroupModel.h"
#include "SpikeStreamException.h"
using namespace spikestream;
//Qt includes
#include <QDebug>
#include <QIcon>
/*! Constructor */
ConnectionGroupModel::ConnectionGroupModel() : QAbstractTableModel(){
connect(Globals::getEventRouter(), SIGNAL(networkChangedSignal()), this, SLOT(loadConnectionGroups()));
connect(Globals::getEventRouter(), SIGNAL(showAllOrNoneConnectionsSignal()), this, SLOT(showAllOrNone()));
}
/*! Destructor */
ConnectionGroupModel::~ConnectionGroupModel(){
}
/*--------------------------------------------------------*/
/*------- PUBLIC METHODS -------*/
/*--------------------------------------------------------*/
/*! Clears the list of selected neuron groups */
void ConnectionGroupModel::clearSelection(){
selectionMap.clear();
}
/*! Inherited from QAbstractTableModel. Returns the number of columns in the model */
int ConnectionGroupModel::columnCount(const QModelIndex&) const{
return NUM_COLS;
}
/*! Inherited from QAbstractTableModel. Returns the data at the specified model index
ready to be displayed in the way requested */
QVariant ConnectionGroupModel::data(const QModelIndex & index, int role) const{
//Return invalid index if index is invalid or no network loaded
if (!index.isValid())
return QVariant();
if(!Globals::networkLoaded())
return QVariant();
//Check rows and columns are in range
if (index.row() < 0 || index.row() >= rowCount() || index.column() < 0 || index.column() >= columnCount())
return QVariant();
//Return appropriate data
if (role == Qt::DisplayRole){
if(index.column() == ID_COL)
return conGrpInfoList[index.row()].getID();
if(index.column() == DESC_COL)
return conGrpInfoList[index.row()].getDescription();
if(index.column() == SIZE_COL)
return conGrpSizeList[index.row()];
if(index.column() == FROM_NEUR_ID_COL)
return conGrpInfoList[index.row()].getFromNeuronGroupID();
if(index.column() == T0_NEUR_ID_COL)
return conGrpInfoList[index.row()].getToNeuronGroupID();
if(index.column() == SYNAPSE_TYPE_COL)
return conGrpInfoList[index.row()].getSynapseTypeID();
}
//Icons
if (role == Qt::DecorationRole){
if(index.column() == VIS_COL ){
if(Globals::getNetworkDisplay()->connectionGroupVisible(conGrpInfoList[index.row()].getID()))
return QIcon(Globals::getSpikeStreamRoot() + "/images/visible.xpm");
return QIcon(Globals::getSpikeStreamRoot() + "/images/hidden.xpm");
}
if(index.column() == PARAM_COL){
return QIcon(Globals::getSpikeStreamRoot() + "/images/parameters.xpm");
}
}
if(role == Qt::SizeHintRole){
if(index.column() == PARAM_COL){
return QSize(50, 18);
}
}
//Check boxes
if(role == Qt::CheckStateRole){
if(index.column() == SELECT_COL){
if(selectionMap.contains(index.row())){
return true;
}
else {
return false;
}
}
}
//If we have reached this point ignore request
return QVariant();
}
/*! Returns the connection group info corresponding to a particular row or throws
an exception if this cannot be found. */
ConnectionGroupInfo ConnectionGroupModel::getInfo(const QModelIndex & index){
if(index.row() >= conGrpInfoList.size())
throw SpikeStreamException("Index out of range: " + QString::number(index.row()));
return conGrpInfoList[index.row()];
}
/*! Returns the parameters associated with a connection group */
QHash<QString, double> ConnectionGroupModel::getParameters(int row){
if(row >= rowCount())
throw SpikeStreamException("Failed to get parameters: row out of range: " + QString::number(row));
return conGrpInfoList[row].getParameterMap();
}
/*! Returns the IDs of the selected neuron groups */
QList<unsigned int> ConnectionGroupModel::getSelectedConnectionGroupIDs(){
//Double check lengths
if(conGrpInfoList.size() < selectionMap.size())
throw SpikeStreamException("There are more selected indexes than indexes");
QList<unsigned int> conGrpIDList;
foreach(unsigned int index, selectionMap.keys()){
conGrpIDList.append(conGrpInfoList.at(index).getID());
}
//Return list
return conGrpIDList;
}
/*! Reloads the list of connection groups */
void ConnectionGroupModel::reload(){
loadConnectionGroups();
}
/*! Selects all or none of the connection groups */
void ConnectionGroupModel::selectAllOrNone(){
//Deselect all groups
if(selectionMap.size() == conGrpInfoList.size()){
selectionMap.clear();
}
//Select all groups
else{
for(int i=0; i<conGrpInfoList.size(); ++i)
selectionMap[i] = true;
}
reset();
}
/*! Shows all or none of the connection groups */
void ConnectionGroupModel::showAllOrNone(){
//Make all groups visible if there are none showing
QList<unsigned> visConGrpIds = Globals::getNetworkDisplay()->getVisibleConnectionGroupIDs();
if(visConGrpIds.isEmpty()){
for(int i=0; i<conGrpInfoList.size(); ++i)
visConGrpIds.append(conGrpInfoList.at(i).getID());
}
//One or more is hidden: make all groups invisible
else{
visConGrpIds.clear();
}
Globals::getNetworkDisplay()->setVisibleConnectionGroupIDs(visConGrpIds);
reset();
}
/*! Inherited from QAbstractTableModel */
bool ConnectionGroupModel::setData(const QModelIndex& index, const QVariant&, int) {
if (!index.isValid() || !Globals::networkLoaded())
return false;
if (index.row() < 0 || index.row() >= rowCount())
return false;
//Change visibility of neuron group
if(index.column() == VIS_COL){
unsigned int tmpConGrpID = conGrpInfoList[index.row()].getID();
if(Globals::getNetworkDisplay()->connectionGroupVisible(tmpConGrpID))
Globals::getNetworkDisplay()->setConnectionGroupVisibility(tmpConGrpID, false);
else
Globals::getNetworkDisplay()->setConnectionGroupVisibility(tmpConGrpID, true);
//Emit signal that data has changed and return true to indicate data set succesfully.
emit dataChanged(index, index);
return true;
}
//Change selection status of connection group
if(index.column() == SELECT_COL){
if(selectionMap.contains(index.row()))
selectionMap.remove(index.row());
else
selectionMap[index.row()] = true;
reset();
return true;
}
//If we have reached this point no data has been set
return false;
}
/*! Inherited from QAbstractTableModel. Returns the header data */
QVariant ConnectionGroupModel::headerData(int section, Qt::Orientation orientation, int role) const{
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Horizontal){
if(section == ID_COL)
return "ID";
if(section == DESC_COL)
return "Description";
if(section == SIZE_COL)
return "Size";
if(section == FROM_NEUR_ID_COL)
return "From";
if(section == T0_NEUR_ID_COL)
return "To";
if(section == SYNAPSE_TYPE_COL)
return "Synapse Type";
if(section == PARAM_COL)
return "Parameters";
}
return QVariant();//QString("Roow %1").arg(section);
}
/*! Inherited from QAbstractTableModel. Returns the number of rows in the model. */
int ConnectionGroupModel::rowCount(const QModelIndex&) const{
return conGrpInfoList.size();
}
/*! Reloads the current list of connection groups if a network is present */
void ConnectionGroupModel::loadConnectionGroups(){
//Clear current list of neuron group information
conGrpInfoList.clear();
conGrpSizeList.clear();
//Get list of current connection group info
if(Globals::networkLoaded())
conGrpInfoList = Globals::getNetwork()->getConnectionGroupsInfo();
//Load up sizes of connection groups
for(int i=0; i<conGrpInfoList.size(); ++i)
conGrpSizeList.append( Globals::getNetwork()->getConnectionCount( conGrpInfoList.at(i).getID() ) );
//Sanity check
if(conGrpInfoList.size() != conGrpSizeList.size())
qCritical()<<"Mismatch between list of connection group info and list of connection group size.";
//Instruct listening classes to reload data
this->reset();
}
|
nico202/spikestream
|
applicationlibrary/src/models/ConnectionGroupModel.cpp
|
C++
|
gpl-2.0
| 7,961
|
<?php
// Copyright 2013 Toby Zerner, Simon Zerner
// This file is part of esoTalk. Please see the included license file for usage information.
if (!defined("IN_ESOTALK")) {
exit;
}
ET::$pluginInfo["Debug"] = array(
"name" => "Debug",
"description" => "Shows useful debugging information, such as SQL queries, to administrators.",
"version" => ESOTALK_VERSION,
"author" => "esoTalk Team",
"authorEmail" => "support@esotalk.org",
"authorURL" => "http://esotalk.org",
"license" => "GPLv2"
);
/**
* Debug Plugin
*
* Shows useful debugging information, such as SQL queries, to administrators.
*/
class ETPlugin_Debug extends ETPlugin {
/**
* The time at which the current query started running.
* @var int
*/
private $queryStartTime;
/**
* An application backtrace taken before a query is executed, and used to work out which model/method the
* query came from.
* @var array
*/
private $backtrace;
/**
* An array of queries that have been executed.
* @var array
*/
private $queries = array();
/**
* Initialize the plugin: turn esoTalk's debug config variable on.
*
* @return void
*/
public function init()
{
parent::init();
// Turn debug mode on.
if (!ET::$session->isAdmin()) {
return;
}
ET::$config["esoTalk.debug"] = true;
}
/**
* On all controller initializations, add the debug CSS file to the page.
*
* @return void
*/
public function handler_init()
{
if (!ET::$session->isAdmin()) {
return;
}
ET::$controller->addCSSFile($this->resource("debug.css"), true);
ET::$controller->addJSFile($this->resource("debug.js"), true);
}
/**
* Store the current time (before a query is executed) so we can work out how long it took when it finishes.
*
* @return void
*/
public function handler_database_beforeQuery($sender, $query)
{
if (is_object(ET::$session) and !ET::$session->isAdmin()) {
return;
}
$this->queryStartTime = microtime(true);
$this->backtrace = debug_backtrace();
}
/**
* Work out how long the query took to run and add it to the log.
*
* @return void
*/
public function handler_database_afterQuery($sender, $result)
{
if (is_object(ET::$session) and !ET::$session->isAdmin()) {
return;
}
// The sixth item in the backtrace is typically the model. Screw being reliable.
$item = $this->backtrace[6];
$method = isset($item["class"]) ? $item["class"] . "::" : "";
$method .= $item["function"] . "()";
// Store the query in our queries array.
$this->queries[] = array($result->queryString, round(microtime(true) - $this->queryStartTime, 4), $method);
}
/**
* Render the debug area at the bottom of the page.
*
* @return void
*/
function handler_pageEnd($sender)
{
// Don't proceed if the user is not permitted to see the debug information!
if (!ET::$session->isAdmin()) {
return;
}
// Stop the page loading timer.
$end = microtime(true);
$time = round($end - PAGE_START_TIME, 4);
// Output the debug area.
echo "<div id='debug'>
<div id='debugHdr'><h2>".sprintf(T("Page loaded in %s seconds"), $time) . "</h2></div>";
// Include the geshi library so we can syntax-highlight MySQL queries.
include "geshi/geshi.php";
echo "<h3><a href='#' onclick='$(\"#debugQueries\").slideToggle(\"fast\");return false'>" . T("MySQL queries") . " (<span id='debugQueriesCount'>" . count($this->queries) . "</span>)</a></h3>
<div id='debugQueries' class='section'>";
foreach ($this->queries as $query) {
$geshi = new GeSHi(trim($query[0]), "mysql");
$geshi->set_header_type(GESHI_HEADER_PRE);
echo "<div><strong>" . $query[2] . "</strong> <span class='queryTime subText" . ($query[1] > 0.5 ? " warning" : "") . "'>" . $query[1] . "s</span>" . $geshi->parse_code() . "</div>";
}
$this->queries = array();
// Output POST + GET + FILES information.
echo "</div>
<h3><a href='#' onclick='$(\"#debugPostGetFiles\").slideToggle(\"fast\");return false'>".T("POST + GET + FILES information") . "</a></h3>
<div id='debugPostGetFiles' class='section'>
<p style='white-space:pre' class='fixed' id='debugPost'>\$_POST = ";
echo sanitizeHTML(print_r($_POST, true));
echo "</p><p style='white-space:pre' class='fixed' id='debugGet'>\$_GET = ";
echo sanitizeHTML(print_r($_GET, true));
echo "</p><p style='white-space:pre' class='fixed' id='debugFiles'>\$_FILES = ";
echo sanitizeHTML(print_r($_FILES, true));
echo "</p>
</div>";
// Output SESSION + COOKIE information.
echo "<h3><a href='#' onclick='$(\"#debugSessionCookie\").slideToggle(\"fast\");return false'>" . T("SESSION + COOKIE information") . "</a></h3>
<div id='debugSessionCookie' class='section'><p style='white-space:pre' class='fixed' id='debugSession'>\$_SESSION = ";
echo sanitizeHTML(print_r($_SESSION, true));
echo "</p><p style='white-space:pre' class='fixed' id='debugCookie'>\$_COOKIE = ";
echo sanitizeHTML(print_r($_COOKIE, true));
echo "</p></div>";
// Hide all panels by default.
echo "<script>
$(function() {
$('#debug .section').hide();
});
</script>";
}
// Construct and process the settings form.
public function settings($sender)
{
// Set up the settings form.
$form = ETFactory::make("form");
$form->action = URL("admin/plugins/settings/Debug");
// If the form was submitted...
if ($form->validPostBack("upgradeDB")) {
// Run the upgrade process.
ET::upgradeModel()->upgrade();
// Upgrade plugins as well.
foreach (ET::$plugins as $name => $plugin) {
$plugin->setup(C("$name.version"));
}
$sender->message(T("message.upgradeSuccessful"), "success");
$sender->redirect(URL("admin/plugins"));
}
$sender->data("debugSettingsForm", $form);
return $this->view("settings");
}
}
|
Felli/fireside
|
addons/plugins/Debug/plugin.php
|
PHP
|
gpl-2.0
| 6,463
|
/**
* Copyright 2011 Kurtis L. Nusbaum
*
* This file is part of UDJ.
*
* UDJ 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.
*
* UDJ 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 UDJ. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ActivePlaylistView.hpp"
#include "ActivePlaylistModel.hpp"
#include "Utils.hpp"
#include "Logger.hpp"
#include <QHeaderView>
#include <QSqlRecord>
#include <QAction>
#include <QMenu>
#include <QContextMenuEvent>
namespace UDJ{
ActivePlaylistView::ActivePlaylistView(DataStore* dataStore, QWidget* parent):
QTableView(parent),
dataStore(dataStore)
{
setContextMenuPolicy(Qt::CustomContextMenu);
setFocusPolicy(Qt::TabFocus);
setEditTriggers(QAbstractItemView::NoEditTriggers);
model = new ActivePlaylistModel(getDataQuery(), dataStore, this);
horizontalHeader()->setStretchLastSection(true);
createActions();
setModel(model);
setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::ContiguousSelection);
configureHeaders();
connect(
dataStore,
SIGNAL(activePlaylistModified()),
model,
SLOT(refresh()));
connect(
this,
SIGNAL(activated(const QModelIndex&)),
this,
SLOT(setCurrentSong(const QModelIndex&)));
connect(this, SIGNAL(customContextMenuRequested(const QPoint&)),
this, SLOT(handleContextMenuRequest(const QPoint&)));
connect(
selectionModel(),
SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),
this,
SLOT(handleSelectionChange(const QItemSelection&, const QItemSelection&)));
}
void ActivePlaylistView::configureHeaders(){
QSqlRecord record = model->record();
int idIndex = record.indexOf(DataStore::getActivePlaylistLibIdColName());
int downVoteIndex = record.indexOf(DataStore::getDownVoteColName());
int upVoteIndex = record.indexOf(DataStore::getUpVoteColName());
int adderNameIndex = record.indexOf(DataStore::getAdderUsernameColName());
int timeAddedIndex = record.indexOf(DataStore::getTimeAddedColName());
setColumnHidden(idIndex, true);
model->setHeaderData(
downVoteIndex, Qt::Horizontal, tr("Down Votes"), Qt::DisplayRole);
model->setHeaderData(
upVoteIndex, Qt::Horizontal, tr("Up Votes"), Qt::DisplayRole);
model->setHeaderData(
adderNameIndex, Qt::Horizontal, tr("Adder"), Qt::DisplayRole);
model->setHeaderData(
timeAddedIndex, Qt::Horizontal, tr("Time Added"), Qt::DisplayRole);
}
void ActivePlaylistView::setCurrentSong(const QModelIndex& index){
Logger::instance()->log("Manual setting of current song");
QSqlRecord songToPlayRecord = model->record(index.row());
QVariant data =
songToPlayRecord.value(DataStore::getActivePlaylistLibIdColName());
selectionModel()->clearSelection();
dataStore->setCurrentSong(data.value<library_song_id_t>());
}
void ActivePlaylistView::createActions(){
removeSongAction = new QAction(tr("Remove Song"), this);
connect(
removeSongAction,
SIGNAL(triggered()),
this,
SLOT(removeSongs()));
}
void ActivePlaylistView::handleContextMenuRequest(const QPoint& /*pos*/){
QMenu contextMenu(this);
contextMenu.addAction(removeSongAction);
QAction *selected = contextMenu.exec(QCursor::pos());
if(selected==NULL){
selectionModel()->clearSelection();
}
}
void ActivePlaylistView::removeSongs(){
QSet<library_song_id_t> toRemove =
Utils::getSelectedIds<library_song_id_t>(
this,
model,
DataStore::getActivePlaylistLibIdColName());
dataStore->removeSongsFromActivePlaylist(toRemove);
selectionModel()->clearSelection();
}
void ActivePlaylistView::handleSelectionChange(
const QItemSelection& selected,
const QItemSelection& /*deselected*/)
{
if(selected.indexes().size() == 0){
connect(
dataStore,
SIGNAL(activePlaylistModified()),
model,
SLOT(refresh()));
}
else{
disconnect(
dataStore,
SIGNAL(activePlaylistModified()),
model,
SLOT(refresh()));
}
}
void ActivePlaylistView::focusOutEvent(QFocusEvent *event){
if(event->reason() != Qt::PopupFocusReason){
selectionModel()->clearSelection();
}
}
} //end namespace
|
klnusbaum/UDJ-Desktop-Client
|
src/ActivePlaylistView.cpp
|
C++
|
gpl-2.0
| 4,615
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Board Class Library")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("QUT")]
[assembly: AssemblyProduct("Board Class Library")]
[assembly: AssemblyCopyright("Copyright © QUT 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("db88e36f-8def-4e67-9836-e3aa9cb610ea")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
Jaydak54/assignment4
|
HareAndTortoise/Board Class Library/Properties/AssemblyInfo.cs
|
C#
|
gpl-2.0
| 1,420
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import gtk # @UnusedImport
import gtk.glade
import gobject
from lib.pycsb19 import recibo
from lib.pycsb19 import ordenante
import sqlite3 as sqlite
import time
class Remesas:
def __init__(self):
self.Llamada=""
self.NifOrdenante=""
self.CodRemesa=""
self.fecha=""
glRemesas=gtk.glade.XML("./gld/remesas.glade")
self.ventana=glRemesas.get_widget("Remesas")
self.ventana.connect("destroy", self.Salir)
self.tvRecibos=glRemesas.get_widget("tvRecibos")
self.tvRecibos.connect("button_press_event",self.SacaCampos)
self.tNombre=glRemesas.get_widget("tNombre")
self.tOrdenante=glRemesas.get_widget("tOrdenante")
self.tImporte=glRemesas.get_widget("tImporte")
self.fecha=glRemesas.get_widget("tFecha")
self.btnOrdenante=glRemesas.get_widget("btnSeleccionar")
self.btnOrdenante.connect("clicked", self.SelOrdenante)
self.btnSalir=glRemesas.get_widget("btnSalir")
self.btnSalir.connect("clicked", self.Salir)
self.btnAnadir=glRemesas.get_widget("btnAnadir")
self.btnAnadir.connect("clicked", self.Anadir)
self.btnEliminar=glRemesas.get_widget("btnEliminar")
self.btnEliminar.connect("clicked", self.Eliminar)
self.btnModificar=glRemesas.get_widget("btnModificar")
self.btnModificar.connect("clicked", self.Modificar)
self.btnImprimir=glRemesas.get_widget("btnImprimir")
self.btnImprimir.connect("clicked", self.Imprimir)
self.btnGenerar=glRemesas.get_widget("btnGenerar")
self.btnGenerar.connect("clicked", self.Generar)
self.btnAyuda=glRemesas.get_widget("btnAyuda")
# self.btnAyuda.connect("clicked", self.Ayuda)
data=gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING)
data.clear()
self.tvRecibos.set_model(data)
column = gtk.TreeViewColumn("Cod ", gtk.CellRendererText(), text=0)
self.tvRecibos.append_column(column)
column = gtk.TreeViewColumn("Cliente ", gtk.CellRendererText(), text=1)
self.tvRecibos.append_column(column)
render=gtk.CellRendererText()
render.set_property('xalign', 1.0)
column = gtk.TreeViewColumn("Importe", render, text=2)
self.tvRecibos.append_column(column)
def AbreDb(self):
self.conexion=sqlite.connect(db="./dbCsb19/db", mode=077) # @UndefinedVariable
def CierraDb(self):
self.conexion.close()
def SacaCampos(self,widget,event):
if event.type==5:
self.Modificar(widget)
def MiraRemesa(self,Nombre):
con=sqlite.connect(db="./dbCsb19/db", mode=077) # @UndefinedVariable
cursor = con.cursor()
#Mira a ver si ya existe la remesa
sql="Select count(codigo) from remesas where titulo='"+self.tNombre.get_text()+"'"
cursor.execute(sql)
if int(cursor.fetchall()[0][0])<>0:
#no hay ninguno dado de alta
sql="Select titulo, ordenante, importe, codigo from remesas where titulo='"+Nombre+"'"
cursor.execute(sql)
for x in cursor.fetchall():
item=[]
for n in x:
item.append(n)
# En item[2] esta el importe
self.tImporte.set_text(str(item[2]))
self.NifOrdenante=item[1]
self.CodRemesa=str(item[3])
# miramos el nombre del ordenante
sql="Select nombre from ordenantes where nif='"+item[1].split(":")[0]+"' and sufijo='"+item[1].split(":")[1]+"'"
cursor.execute(sql)
self.tOrdenante.set_text(cursor.fetchall()[0][0])
#Mira el detalle
#Si no hay ningun detalle pasa de mirar mas porque si no da error
sql="SELECT count(codigo) FROM det_remesas"
cursor.execute(sql)
if int(cursor.fetchall()[0][0])<>0:
sql="SELECT det_remesas.indice, clientes.nombre, det_remesas.importe FROM det_remesas,clientes WHERE clientes.codigo=det_remesas.cliente AND det_remesas.codigo='"+self.CodRemesa+"'"
cursor.execute(sql)
for x in cursor.fetchall():
item=[]
numero=0
for n in x:
numero=numero+1
if numero==3:
#Todo este rollo es para completar el importe con dos decimales en el treeview
cadena=str(n)
if cadena.find(".")==-1:
cadena=cadena+".00"
elif (len(cadena)-1)-cadena.find(".")<2:
cadena=cadena+"0"
item.append(cadena)
else:
item.append(n)
self.VisualizaDatos(item)
con.close()
def Eliminar(self, widget):
if self.tvRecibos.get_selection().get_selected()[1]<>None:
store=self.tvRecibos.get_model()
self.AbreDb()
c = self.conexion.cursor()
#Borramos el recibo
sql="delete from det_remesas where codigo="+self.CodRemesa+" and indice="+store[self.tvRecibos.get_cursor()[0][0]][0]
c.execute(sql)
self.conexion.commit()
#Miramos a ver cuanto es el importe de la remesa ahora
sql="Select sum(importe) from det_remesas where codigo='"+self.CodRemesa+"'"
c.execute(sql)
Importe=0.0
Importe=float(c.fetchall()[0][0])
#Mete el importe en la casilla del importe
self.tImporte.set_text(str(Importe))
#Actualiza el importe en la base de datos de remesa
sql="UPDATE remesas SET importe="+str(Importe)+" WHERE codigo="+self.CodRemesa
c.execute(sql)
self.conexion.commit()
self.CierraDb()
store.remove(self.tvRecibos.get_selection().get_selected()[1])
self.tvRecibos.set_model(store)
else:
d=gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK,"Debe de seleccionar una recibo para poder eliminarlo")
d.connect('response', lambda dialog, response: dialog.destroy())
d.show()
def MiraOrdenante(self):
if self.Otro.CodOrdenante<>"x":
if self.Otro.CodOrdenante<>"":
self.tOrdenante.set_text(self.Otro.NomOrdenante)
self.NifOrdenante=self.Otro.CodOrdenante
self.AbreDb()
cursor = self.conexion.cursor()
#Hay que mirar a ver si es la primera remesa de la base de datos
sql="Select count(codigo) from remesas"
cursor.execute(sql)
if int(cursor.fetchall()[0][0])==0:
#Es la primera remesa asin que el codigo es = 1 y solo hay que darla de alta
codigo="1"
self.CodRemesa=codigo
sql="insert into remesas(codigo, titulo, ordenante, generada, importe) values("+codigo+",'" +self.tNombre.get_text()+"','"+self.NifOrdenante+"','NO',0)"
cursor.execute(sql)
self.conexion.commit()
else:
#Mira a ver si ya existe la remesa por si es una modificacion del ordenante
sql="Select count(codigo) from remesas where titulo='"+self.tNombre.get_text()+"'"
cursor.execute(sql)
if int(cursor.fetchall()[0][0])==0:
#"no hay ninguno dado de alta"
# "Ahora miramos a ver cual es el ultimo codigo dado de alta y le sumamos 1"
sql="Select max(codigo) from remesas"
cursor.execute(sql)
codigo=str(int(cursor.fetchall()[0][0])+1)
self.CodRemesa=codigo
#Ahora la damos de alta
sql="insert into remesas(codigo, titulo, ordenante, generada, importe) values("+codigo+",'" +self.tNombre.get_text()+"','"+self.NifOrdenante+"','NO',0)"
cursor.execute(sql)
self.conexion.commit()
else:
# "ya esta dado de alta, Hay que hace un Update Tabla"
sql="Select codigo from remesas where titulo='"+self.tNombre.get_text()+"'"
cursor.execute(sql)
codigo=str(cursor.fetchall()[0][0])
self.CodRemesa=codigo
sql="UPDATE remesas SET titulo='" +self.tNombre.get_text()+"', ordenante='"+self.NifOrdenante+"' WHERE codigo="+codigo
cursor.execute(sql)
self.conexion.commit()
self.CierraDb()
return 0
else:
return 1
def VisualizaDatos(self,Datos):
store=gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING) # @UnusedVariable
store=self.tvRecibos.get_model()
itr=store.append()
store.set(itr,0,Datos[0],1,Datos[1],2,Datos[2])
self.tvRecibos.set_model(store)
def MiraRecibos(self):
#Aqui se graban los recibos que devuelve la pantalla de recibos
if self.VenRecibos.Llamada<>"remesas":
if self.VenRecibos.Llamada<>"Salir":
#Saca el codigo de la remesa en el improbable caso de que no exista
if self.CodRemesa=="":
self.AbreDb()
cursor = self.conexion.cursor()
sql="Select codigo from remesas where titulo='"+self.tNombre.get_text()+"'"
cursor.execute(sql)
self.CodRemesa=str(cursor.fetchall()[0][0])
self.CierraDb()
#lo primero es saber si es una modificacion de un recibo
if self.VenRecibos.Modificacion<>"":
#Es una modificacion
self.AbreDb()
cursor = self.conexion.cursor()
indice=self.VenRecibos.Modificacion
#Modificamos los datos del recibo
#sql="Update det_remesas SET cliente=?, importe=?, conceptos=? WHERE codigo='"+self.CodRemesa+"' AND indice='"+indice+"'"
#cursor.execute(sql, (self.VenRecibos.CodCliente,float(self.VenRecibos.Importe),self.VenRecibos.Conceptos))
sql="Update det_remesas SET cliente='"+self.VenRecibos.CodCliente+"', importe="+self.VenRecibos.Importe+", conceptos='"+self.VenRecibos.Conceptos+"' WHERE codigo="+self.CodRemesa+" AND indice="+indice
cursor.execute(sql)
self.conexion.commit()
cursor = self.conexion.cursor()
#Miramos a ver cuanto es el importe de la remesa ahora
sql="Select sum(importe) from det_remesas where codigo="+self.CodRemesa
cursor.execute(sql)
Importe=float(cursor.fetchall()[0][0])
#Mete el importe en la casilla del importe
self.tImporte.set_text(str(Importe))
cursor = self.conexion.cursor()
#Actualiza el importe en la base de datos de remesa
sql="UPDATE remesas SET importe="+str(Importe)+" WHERE codigo="+self.CodRemesa
cursor.execute(sql)
#sql="UPDATE remesas SET importe=? WHERE codigo=?"
#cursor.execute(sql,(Importe,self.CodRemesa))
self.conexion.commit()
#Carga los datos en el treeview
store=gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING)
self.tvRecibos.set_model(store)
self.MiraRemesa(self.tNombre.get_text())
self.CierraDb()
else:
#Es un recibo nuevo
self.AbreDb()
cursor = self.conexion.cursor()
#miramos a ver si es el primer recibo de esta remesa (si el importe es 0)
sql="SELECT sum(importe) FROM remesas WHERE codigo="+self.CodRemesa
cursor.execute(sql)
if float(cursor.fetchall()[0][0])==0:
#Es el primero asin que le ponemos el numero 1
indice=1
else:
#No es el primero
#Miramos a ver el codigo que le corresponde a este recibo
sql="SELECT max(indice) FROM det_remesas WHERE codigo='"+self.CodRemesa+"'"
cursor.execute(sql)
indice=str(int(cursor.fetchall()[0][0])+1)
#A�adimos los datos del recibo
#sql="insert into det_remesas (codigo,indice, cliente, importe, conceptos) values (?,?,?,?,?)"
#cursor.execute(sql, (str(self.CodRemesa),indice , self.VenRecibos.CodCliente, str(self.VenRecibos.Importe), self.VenRecibos.Conceptos))
sql="insert into det_remesas (codigo, indice, cliente, importe, conceptos) values ("+str(self.CodRemesa)+","+str(indice)+",'"+self.VenRecibos.CodCliente+"',"+str(self.VenRecibos.Importe)+",'"+self.VenRecibos.Conceptos+"')"
cursor.execute(sql)
self.conexion.commit()
sql="SELECT sum(importe) FROM det_remesas WHERE codigo='"+self.CodRemesa+"'"
cursor.execute(sql)
Importe = float(cursor.fetchall()[0][0])
self.tImporte.set_text(str(Importe))
#Actualiza el importe en la base de datos de remesa
sql="UPDATE remesas SET importe="+str(Importe)+" WHERE codigo='"+self.CodRemesa+"'"
cursor.execute(sql)
self.conexion.commit()
#Mete los datos del recibo en el TreeView
store=gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING)
self.tvRecibos.set_model(store)
self.MiraRemesa(self.tNombre.get_text())
self.CierraDb()
else:
pass
# print "salio por aqui"
return 0
else:
#print "no Es distinto"
return 1
def SelOrdenante(self,widget):
#Se llama a la pantalla del ordenante
self.Otro=ordenante.Ordenante()
self.Otro.Llamada="remesas"
#self.Otro.ventana.set_modal(True)
self.Otro.CodOrdenante="x"
self.timeout= gtk.timeout_add(250, self.MiraOrdenante)
def Anadir(self,widget):
if self.tNombre.get_text()=="":
self.Dialogo("No se puede anadir un recibo si no se le ha dado un nombre a la remesa",2)
elif self.tOrdenante.get_text()=="":
self.Dialogo("No se puede anadir un recibo si no se ha selecionado el ordenante",2)
else:
self.VenRecibos=recibo.Recibo()
self.VenRecibos.Llamada="remesas"
self.VenRecibos.Modificacion=""
self.VenRecibos.Remesa=self.tNombre.get_text()
#self.VenRecibos.ventana.set_modal(True)
self.timeout= gtk.timeout_add(250, self.MiraRecibos)
def Modificar(self,widget):
store=gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_STRING) # @UnusedVariable
store=self.tvRecibos.get_model()
if self.tvRecibos.get_cursor()[0]<>None:
self.VenRecibos=recibo.Recibo()
self.VenRecibos.Llamada="remesas"
#Mete el numero de recibo de la remesa
self.VenRecibos.Modificacion=store[self.tvRecibos.get_cursor()[0][0]][0]
self.AbreDb()
cClientes = self.conexion.cursor()
sql="SELECT codigo, nombre, banco, oficina, dc, cuenta FROM clientes WHERE nombre='"+store[self.tvRecibos.get_cursor()[0][0]][1]+"'"
cClientes.execute(sql)
pp=[]
pp=cClientes.fetchone()
CodCliente=pp[0]
self.VenRecibos.tCodCliente.set_text(CodCliente)
self.VenRecibos.tNomCliente.set_text(pp[1])
self.VenRecibos.tBanco.set_text(pp[2])
self.VenRecibos.tOficina.set_text(pp[3])
self.VenRecibos.tDc.set_text(pp[4])
self.VenRecibos.tCuenta.set_text(pp[5])
self.VenRecibos.tImporte.set_text(store[self.tvRecibos.get_cursor()[0][0]][2])
cDetalle = self.conexion.cursor()
sql="SELECT codigo, cliente, importe, conceptos FROM det_remesas WHERE codigo="+self.CodRemesa+" AND indice="+store[self.tvRecibos.get_cursor()[0][0]][0]
cDetalle.execute(sql)
n=cDetalle.fetchone()[3].split("�")
self.VenRecibos.tConcepto1.set_text(n[0])
self.VenRecibos.tConcepto2.set_text(n[1])
self.VenRecibos.tConcepto3.set_text(n[2])
self.VenRecibos.tConcepto4.set_text(n[3])
self.VenRecibos.tConcepto5.set_text(n[4])
self.VenRecibos.tConcepto6.set_text(n[5])
self.VenRecibos.tConcepto7.set_text(n[6])
self.VenRecibos.tConcepto8.set_text(n[7])
self.VenRecibos.tConcepto9.set_text(n[8])
self.VenRecibos.tConcepto10.set_text(n[9])
self.VenRecibos.tConcepto11.set_text(n[10])
self.VenRecibos.tConcepto12.set_text(n[11])
self.VenRecibos.tConcepto13.set_text(n[12])
self.VenRecibos.tConcepto14.set_text(n[13])
self.VenRecibos.tConcepto15.set_text(n[14])
self.VenRecibos.tConcepto16.set_text(n[15])
self.VenRecibos.Remesa=self.tNombre.get_text()
#self.VenRecibos.ventana.set_modal(True)
self.timeout= gtk.timeout_add(250, self.MiraRecibos)
self.CierraDb()
else:
d=gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK,"Debe de seleccionar un recibo para poder abrirlo")
d.connect('response', lambda dialog, response: dialog.destroy())
d.show()
def Imprimir(self,widget):
pass
def Espacios(self,Numero):
d=""
for n in range(0,Numero): # @UnusedVariable
d=d+" "
return d
def Ceros(self,Numero):
d=""
for n in range(0,Numero): # @UnusedVariable
d=d+"0"
return d
def Generar(self,widget):
self.Fiche = gtk.FileSelection("Seleccionar Fichero")
self.Fiche.connect("destroy", self.CerrarAbrirFichero)
self.Fiche.ok_button.connect("clicked", self.FicheroSeleccionado)
self.Fiche.cancel_button.connect("clicked", self.CerrarAbrirFichero)
self.Fiche.set_filename("")
self.Fiche.set_modal(True)
self.Fiche.show()
def CerrarAbrirFichero(self,widget):
self.Fiche.destroy()
def FicheroSeleccionado(self, widget):
#Cerramos la ventana de seleccionar fichero
if self.Fiche.get_filename()[len(self.Fiche.get_filename())-1:len(self.Fiche.get_filename())]<>'\\':
self.GrabaCSB(self.Fiche.get_filename())
else:
d=gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK,"Debe de introducir el nombre de un fichero para poder grabarlo")
d.connect('response', lambda dialog, response: dialog.destroy())
d.show()
self.Fiche.destroy()
def GrabaCSB(self,Fichero):
#Aqui se crea el fichero con el formato CSB19
self.AbreDb()
f=open(Fichero,"w")
#Cabecera de presentador
cur=self.conexion.cursor()
sql="SELECT ordenante FROM remesas WHERE codigo="+self.CodRemesa
cur.execute(sql)
ordenante=cur.fetchall()[0][0]
rem=self.conexion.cursor()
sql="SELECT nif, sufijo, nombre, banco, oficina, dc, cuenta FROM ordenantes WHERE nif='"+ordenante.split(":")[0]+"' and sufijo='"+ordenante.split(":")[1]+"'"
rem.execute(sql)
Linea=rem.fetchall()[0]
nif=Linea[0]
sufijo=Linea[1]
nombre=Linea[2]
banco=Linea[3]
oficina=Linea[4]
dc=Linea[5]
cuenta=Linea[6]
#a�o, mes, dia
dia=str(time.localtime()[2])
if len(dia)<2:
dia="0"+dia
mes=str(time.localtime()[1])
if len(mes)<2:
mes="0"+mes
ano=str(time.localtime()[0])[2:4]
FechaConfeccion=dia+mes+ano
#FechaCargo=FechaConfeccion
FechaCargo=self.fecha.get_text()
#Cambiar la FechaCargo por el valor del texto (casi nada...)
if len(nombre)<40:
nombre=nombre+self.Espacios(40-len(nombre))
Cadena="5180"+nif+sufijo+FechaConfeccion+self.Espacios(6)+nombre+self.Espacios(20)+banco+oficina+self.Espacios(12)+self.Espacios(40)+"***PyCsb19****"+"\r\n"
f.write(Cadena)
#Cabecera de Ordenante
Cadena="5380"+nif+sufijo+FechaConfeccion+FechaCargo+nombre+banco+oficina+dc+cuenta+self.Espacios(8)+"01"+self.Espacios(10)+self.Espacios(40)+"***PyCsb19****"+"\r\n"
f.write(Cadena)
#Registros de recibos
rec=self.conexion.cursor()
sql="SELECT indice, cliente, importe, conceptos FROM det_remesas WHERE codigo="+self.CodRemesa
rec.execute(sql)
nNumDomiciliaciones=0
nSuma=0.0
nNumRegistrosOrdenante=2 #Se pone con dos porque el fichero ya tiene las 2 cabeceras escritas
for remesa in rec.fetchall():
#El indice lo voy a utilizar para el codigo de devolucion
Indice=str(remesa[0])
nNumDomiciliaciones=nNumDomiciliaciones+1
if len(Indice)<6:
Indice=Indice+self.Espacios(6-len(Indice))
elif len(Indice)>6:
Indice=Indice[0:5]
Cliente=remesa[1]
nSuma=nSuma+remesa[2]
Importe=str(remesa[2])
if Importe.find(".")==-1:
Importe=Importe+self.Ceros(2)
else:
if len(Importe.split(".")[1])<2:
Importe=Importe.split(".")[0]+Importe.split(".")[1]+self.Ceros(2-len(Importe.split(".")[1]))
elif len(Importe.split(".")[1])>2:
Importe=Importe.split(".")[0]+Importe.split(".")[1][0:1]
else:
Importe=Importe.split(".")[0]+Importe.split(".")[1]
if len(Importe)<10:
Importe=self.Ceros(10-len(Importe))+Importe
Conceptos=[]
for n in remesa[3].split("�"):
if len(n)==0:
dato=""
elif len(n)<40:
dato=n+self.Espacios(40-len(n))
elif len(n)>40:
dato=n[0:40]
else:
dato=n
Conceptos.append(dato)
#Vamos a por los datos del cliente
cli=self.conexion.cursor()
sql="SELECT codigo, nif, nombre, direccion, ciudad, cp, banco, oficina, dc, cuenta FROM clientes WHERE codigo='"+Cliente+"'"
cli.execute(sql)
c=cli.fetchall()[0]
if len(c[0])<12:
CodCliente=c[0]+self.Espacios(12-len(c[0]))
else:
CodCliente=c[0]
#El nif lo voy a utilizar para el codigo de referencia interna
NifCliente=c[1]
if len(NifCliente)<10:
NifCliente=NifCliente+self.Espacios(10-len(NifCliente))
if len(c[2])<40:
NombreCliente=c[2]+self.Espacios(40-len(c[2]))
else:
NombreCliente=c[2]
DireCliente=c[3] # @UnusedVariable
CiudadCliente=c[4] # @UnusedVariable
CpCliente=c[5] # @UnusedVariable
BancoCliente=c[6]
OficinaCliente=c[7]
DcCliente=c[8]
CuentaCliente=c[9]
if len(Conceptos[0])<40:
Conceptos[0]=Conceptos[0]+self.Espacios(40-len(Conceptos[0]))
if len(Conceptos[0])>40:
Conceptos[0]=Conceptos[0][0:40]
Cadena="5680"+nif+sufijo+CodCliente+NombreCliente+BancoCliente+OficinaCliente+DcCliente+CuentaCliente+Importe+Indice+NifCliente+Conceptos[0]+self.Espacios(8)+"\r\n"
f.write(Cadena)
nNumRegistrosOrdenante=nNumRegistrosOrdenante+1
#Vamos a ver que pasa con los otros conceptos.
if len(Conceptos[1])<>0 or len(Conceptos[2])<>0 or len(Conceptos[3])<>0:
if len(Conceptos[1])<>40:
Conceptos[1]=Conceptos[1]+self.Espacios(40-len(Conceptos[1]))
if len(Conceptos[2])<>40:
Conceptos[2]=Conceptos[2]+self.Espacios(40-len(Conceptos[2]))
if len(Conceptos[3])<>40:
Conceptos[3]=Conceptos[3]+self.Espacios(40-len(Conceptos[3]))
Cadena="5681"+nif+sufijo+CodCliente+Conceptos[1]+Conceptos[2]+Conceptos[3]+self.Espacios(14)+"\r\n"
f.write(Cadena)
nNumRegistrosOrdenante=nNumRegistrosOrdenante+1
if len(Conceptos[4])<>0 or len(Conceptos[5])<>0 or len(Conceptos[6])<>0:
if len(Conceptos[4])<>40:
Conceptos[4]=Conceptos[4]+self.Espacios(40-len(Conceptos[4]))
if len(Conceptos[5])<>40:
Conceptos[5]=Conceptos[5]+self.Espacios(40-len(Conceptos[5]))
if len(Conceptos[6])<>40:
Conceptos[6]=Conceptos[6]+self.Espacios(40-len(Conceptos[6]))
Cadena="5682"+nif+sufijo+CodCliente+Conceptos[4]+Conceptos[5]+Conceptos[6]+self.Espacios(14)+"\r\n"
f.write(Cadena)
nNumRegistrosOrdenante=nNumRegistrosOrdenante+1
if len(Conceptos[7])<>0 or len(Conceptos[8])<>0 or len(Conceptos[9])<>0:
if len(Conceptos[7])<>40:
Conceptos[7]=Conceptos[7]+self.Espacios(40-len(Conceptos[7]))
if len(Conceptos[8])<>40:
Conceptos[8]=Conceptos[8]+self.Espacios(40-len(Conceptos[8]))
if len(Conceptos[9])<>40:
Conceptos[9]=Conceptos[9]+self.Espacios(40-len(Conceptos[9]))
Cadena="5683"+nif+sufijo+CodCliente+Conceptos[7]+Conceptos[8]+Conceptos[9]+self.Espacios(14)+"\r\n"
f.write(Cadena)
nNumRegistrosOrdenante=nNumRegistrosOrdenante+1
if len(Conceptos[10])<>0 or len(Conceptos[11])<>0 or len(Conceptos[12])<>0:
if len(Conceptos[10])<>40:
Conceptos[10]=Conceptos[10]+self.Espacios(40-len(Conceptos[10]))
if len(Conceptos[11])<>40:
Conceptos[11]=Conceptos[11]+self.Espacios(40-len(Conceptos[11]))
if len(Conceptos[12])<>40:
Conceptos[12]=Conceptos[12]+self.Espacios(40-len(Conceptos[12]))
Cadena="5684"+nif+sufijo+CodCliente+Conceptos[10]+Conceptos[11]+Conceptos[12]+self.Espacios(14)+"\r\n"
f.write(Cadena)
nNumRegistrosOrdenante=nNumRegistrosOrdenante+1
if len(Conceptos[13])<>0 or len(Conceptos[14])<>0 or len(Conceptos[15])<>0:
if len(Conceptos[13])<>40:
Conceptos[13]=Conceptos[13]+self.Espacios(40-len(Conceptos[13]))
if len(Conceptos[14])<>40:
Conceptos[14]=Conceptos[14]+self.Espacios(40-len(Conceptos[14]))
if len(Conceptos[15])<>40:
Conceptos[15]=Conceptos[15]+self.Espacios(40-len(Conceptos[15]))
Cadena="5685"+nif+sufijo+CodCliente+Conceptos[13]+Conceptos[14]+Conceptos[15]+self.Espacios(14)+"\r\n"
f.write(Cadena)
nNumRegistrosOrdenante=nNumRegistrosOrdenante+1
#La linea de datos del cliente no se implementa de monento
#Cadena="5686"+nif+sufijo+CodCliente
#Linea de totales de ordenante
Suma=str(nSuma)
if Suma.find(".")==-1:
Suma=Suma+self.Ceros(2)
else:
if len(Suma.split(".")[1])<2:
Suma=Suma.split(".")[0]+Suma.split(".")[1]+self.Ceros(2-len(Suma.split(".")[1]))
elif len(Suma.split(".")[1])>2:
Suma=Suma.split(".")[0]+Suma.split(".")[1][0:1]
else:
Suma=Suma.split(".")[0]+Suma.split(".")[1]
if len(Suma)<10:
Suma=self.Ceros(10-len(Suma))+Suma
NumDomiciliaciones=str(nNumDomiciliaciones)
if len(NumDomiciliaciones)<10:
NumDomiciliaciones=self.Ceros(10-len(NumDomiciliaciones))+NumDomiciliaciones
NumRegistrosOrdenante=str(nNumRegistrosOrdenante)
if len(NumRegistrosOrdenante)<10:
NumRegistrosOrdenante=self.Ceros(10-len(NumRegistrosOrdenante))+NumRegistrosOrdenante
Cadena="5880"+nif+sufijo+self.Espacios(12)+self.Espacios(40)+self.Espacios(20)+Suma+self.Espacios(6)+NumDomiciliaciones+NumRegistrosOrdenante+self.Espacios(20)+"*****PyCsb19******"+"\r\n"
f.write(Cadena)
nNumRegistrosOrdenante=nNumRegistrosOrdenante+1
NumRegistrosOrdenante=str(nNumRegistrosOrdenante+1)
if len(NumRegistrosOrdenante)<10:
NumRegistrosOrdenante=self.Ceros(10-len(NumRegistrosOrdenante))+NumRegistrosOrdenante
#Linea de total general
Cadena="5980"+nif+sufijo+self.Espacios(12)+self.Espacios(40)+"0001"+self.Espacios(16)+Suma+self.Espacios(6)+NumDomiciliaciones+NumRegistrosOrdenante+self.Espacios(20)+"*****PyCsb19******"+"\r\n"
f.write(Cadena)
f.close()
self.CierraDb()
self.Dialogo("El fichero se ha generado correctamente",1)
def Dialogo(self, msg, Tipo):
if Tipo==1:
dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK,msg)
elif Tipo==2:
dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_CLOSE,msg)
elif Tipo==3:
dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO,msg)
elif Tipo==4:
dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL,msg)
dialog.connect('response', lambda dialog, response: dialog.destroy())
dialog.show()
return dialog
def Salir(self,*args):
#True
if self.Llamada<>"":
self.ventana.hide()
self.Cliente=""
self.Importe=""
self.Llamada=""
return True
else:
gtk.main_quit()
def Main(self):
self.Llamada=""
gtk.main()
if __name__ == "__main__":
gtk.rc_parse("gtkrc.txt")
ven = Remesas()
ven.Main()
|
pacoqueen/ginn
|
ginn/lib/pycsb19/remesas.py
|
Python
|
gpl-2.0
| 32,357
|
<?php
/**
* @version $Id: rokpad.php 9100 2013-04-03 23:19:42Z djamil $
* @author RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2013 RocketTheme, LLC
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*/
defined('_JEXEC') or die;
/**
*
*/
class plgEditorRokPad extends JPlugin
{
/**
* @var bool
*/
protected static $_assets = false;
/**
* @var string
*/
protected $_version = '2.1.4';
/**
* @var string
*/
protected $_basepath = '/plugins/editors/rokpad/';
/**
* @var
*/
protected $_acepath;
/**
* @param $subject
* @param $config
*/
public function __construct(&$subject, $config)
{
parent::__construct($subject, $config);
$this->loadLanguage();
}
/**
* @return string
*/
public function onInit()
{
JHtml::_('behavior.framework', true);
$document = JFactory::getDocument();
$this->_basepath = JURI::root(true) . $this->_basepath;
$this->_acepath = $this->_basepath . 'ace/';
if (!self::$_assets) {
/*
$document->addStyleSheet($this->_basepath . 'assets/css/rokpad.css'.$this->_appendCacheToken());
$document->addScript($this->_acepath . 'ace.js'.$this->_appendCacheToken());
$document->addScript($this->_basepath . 'assets/js/rokpad.js'.$this->_appendCacheToken());
*/
$document->addScriptDeclaration($this->getJSParams());
$this->compileLess();
$this->compileJS();
self::$_assets = true;
}
return '';
}
/**
* @param $id
*
* @return string
*/
public function onSave($id)
{
return "RokPadData.insertion.onSave('".$id."');\n";
}
/**
* @param $id
*
* @return string
*/
public function onGetContent($id)
{
return "RokPadData.insertion.onGetContent('".$id."');\n";
}
/**
* @param $id
* @param $content
*
* @return string
*/
public function onSetContent($id, $content)
{
return "RokPadData.insertion.onSetContent('".$id."', ".$content.");\n";
}
/**
* @return bool
*/
public function onGetInsertMethod()
{
static $done = false;
// Do this only once.
if (!$done) {
$done = true;
$doc = JFactory::getDocument();
$js = "\tfunction jInsertEditorText(text, editor) {\n
RokPadData.insertion.onGetInsertMethod(text, editor);\n
}\n";
$doc->addScriptDeclaration($js);
}
return true;
}
/**
* @param $name
* @param $content
* @param $width
* @param $height
* @param $col
* @param $row
* @param bool $buttons
* @param null $id
* @param null $asset
* @param null $author
* @param array $params
*
* @return string
*/
public function onDisplay($name, $content, $width, $height, $col, $row, $buttons = true, $id = null, $asset = null, $author = null, $params = array())
{
if (empty($id)) $id = $name;
$buttons = $this->_displayButtons($id, $buttons, $asset, $author);
$html = array();
$html[] = '<div class="rokpad-editor-wrapper" data-rokpad-editor="' . $id . '">';
$html[] = ' <div class="rokpad-toolbar">';
$html[] = ' <ul class="rok-left">';
$html[] = ' <li><div class="rok-button rok-button-primary rokpad-tip" data-original-title="Ajax Save" data-placement="below-left" data-rokpad-save><i class="rokpad-icon-save"></i> save</div></li>';
$html[] = ' <li class="rok-buttons-group">';
$html[] = ' <div class="rok-button rok-button-disabled rokpad-tip" data-original-title="Undo" data-placement="below" data-rokpad-undo><i class="rokpad-icon-undo"></i></div>';
$html[] = ' <div class="rok-button rok-button-disabled rokpad-tip" data-original-title="Redo" data-placement="below" data-rokpad-redo><i class="rokpad-icon-redo"></i></div>';
$html[] = ' </li>';
$html[] = ' <li><div class="rok-button rokpad-tip" data-original-title="Find..." data-placement="below" data-rokpad-find><i class="rokpad-icon-search"></i></div></li>';
$html[] = ' <li>';
$html[] = ' <div class="rok-dropdown-group">';
$html[] = ' <div class="rok-button" data-rokpad-toggle="extras"><i class="rokpad-icon-more"></i><span class="caret"></span></div>';
$html[] = ' <ul class="rok-dropdown" data-rokpad-dropdown="extras">';
$html[] = ' <li><a href="#" data-rokpad-goto>Goto Line...</a></li>';
$html[] = ' <li><a href="#" data-rokpad-find-replace>Find and Replace...</a></li>';
$html[] = ' <li class="divider"></li>';
$html[] = ' <li><a href="#" data-rokpad-beautify>Beautify HTML</a></li>';
$html[] = ' </ul>';
$html[] = ' </div>';
$html[] = ' </li>';
$html[] = ' </ul>';
$html[] = ' <ul class="rok-right">';
$html[] = ' <li>';
$html[] = ' <div class="rok-popover-group">';
$html[] = ' <div class="rok-button rokpad-tip" data-original-title="Editor Settings" data-placement="below" data-rokpad-toggle="settings"><i class="rokpad-icon-settings"></i></div>';
$html[] = ' <div class="rok-popover" data-rokpad-popover="settings">';
$html[] = ' <ul class="options">';
$html[] = ' <li><span class="title">Theme</span><span class="input"><select data-rokpad-options="theme" class="chzn-done"></select></span></li>';
$html[] = ' <li><span class="title">Font Size</span><span class="input"><select data-rokpad-options="font-size" class="chzn-done"></select></span></li>';
$html[] = ' <li><span class="title">Code Folding</span><span class="input"><select data-rokpad-options="fold-style" class="chzn-done"><option value="manual">Manual</option><option value="markbegin">Mark Begin</option><option value="markbeginend">Mark Begin and End</option></select></span></li>';
$html[] = ' <li><span class="title">Soft Wrap</span><span class="input"><select data-rokpad-options="use-wrap-mode" class="chzn-done"><option value="off">Off</option><option value="40">40 Chars</option><option value="80">80 Chars</option><option value="free">Free</option></select></span></li>';
$html[] = ' <li><span class="title-checkbox">Full Line Selection</span><span class="input"><input type="checkbox" data-rokpad-options="selection-style" /></span></li>';
$html[] = ' <li><span class="title-checkbox">Highlight Active Line</span><span class="input"><input type="checkbox" data-rokpad-options="highlight-active-line" /></span></li>';
$html[] = ' <li><span class="title-checkbox">Show Invisibles</span><span class="input"><input type="checkbox" data-rokpad-options="show-invisibles" /></span></li>';
$html[] = ' <li><span class="title-checkbox">Show Gutter</span><span class="input"><input type="checkbox" data-rokpad-options="show-gutter" /></span></li>';
$html[] = ' <li><span class="title-checkbox">Show Print Margin</span><span class="input"><input type="checkbox" data-rokpad-options="show-print-margin" /></span></li>';
$html[] = ' <li><span class="title-checkbox">Highlight Selected Word</span><span class="input"><input type="checkbox" data-rokpad-options="highlight-selected-word" /></span></li>';
$html[] = ' <li><span class="title-checkbox">Autohide Fold Widgets</span><span class="input"><input type="checkbox" data-rokpad-options="fade-fold-widgets" /></span></li>';
$html[] = ' <li><span class="title-checkbox">Autosave</span><span class="input"><input type="checkbox" data-rokpad-options="autosave-enabled" /> <input type="text" data-rokpad-options="autosave-time" /> mins</span></li>';
$html[] = ' </ul>';
$html[] = ' <div class="rok-popover-arrow"></div>';
$html[] = ' </div>';
$html[] = ' </div>';
$html[] = ' </li>';
$html[] = ' <li>';
$html[] = ' <div class="rok-popover-group">';
$html[] = ' <div class="rok-button rokpad-tip" data-original-title="Keyboard Shortcuts" data-placement="below" data-rokpad-toggle="keyboard"><i class="rokpad-icon-keyboard"></i></div>';
$html[] = ' <div class="rok-popover rok-popover-keyboard" data-rokpad-popover="keyboard">';
$html[] = ' <ul class="keyboard">';
$html[] = ' <li class="rokpad-keyboard-mac">';
$html[] = ' <span class="rokpad-kbd-win"></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">L</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Center selection</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">U</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">U</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Change to uppser case</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">U</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">U</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Change to lower case</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">ALT</span> + <span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">OPT</span> + <span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Copy lines down</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">ALT</span> + <span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">OPT</span> + <span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Copy lines up</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">S</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">S</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Save</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">F</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">F</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Find</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">E</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">E</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Use selection for find</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">K</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">G</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Find next</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">K</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">G</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Find previous</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">0</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">0</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Fold all</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">0</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">0</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Unfold all</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">↓</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">N</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Go line down</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">↑</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">P</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Go line up</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">END</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">END</span> <br /><span class="rokpad-key">⌘</span> + <span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Go to end</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">←</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">←</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">B</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Go to left</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">L</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">L</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Goto line</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">→</span> <br /><span class="rokpad-key">END</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">→</span> <br /><span class="rokpad-key">END</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">E</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Goto to line end</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">←</span> <br /><span class="rokpad-key">HOME</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">←</span> <br /><span class="rokpad-key">HOME</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">A</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Goto to line start</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">PAGEDOWN</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">PAGEDOWN</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">V</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Goto to page down</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">PAGEUP</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">PAGEUP</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Goto to page up</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">→</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">→</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">F</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Go to right</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">HOME</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">HOME</span> <br /><span class="rokpad-key">⌘</span> + <span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Go to start</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">←</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">←</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Go to word left</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">→</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">→</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Go to word right</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">TAB</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">TAB</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Indent</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Move lines down</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Move lines up</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">TAB</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">TAB</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Outdent</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">INS</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">INSERT</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Overwrite</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac">';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">PAGEDOWN</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Pagedown</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac">';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">PAGEUP</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Pageup</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">Z</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">Y</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">Z</span> <br /><span class="rokpad-key">⌘</span> + <span class="rokpad-key">Y</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Redo</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">D</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">D</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Remove line</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac">';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">K</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Remove to line end</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac">';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">BACKSPACE</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Remove to line start</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac">';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">BACKSPACE</span> <br /> <span class="rokpad-key">CTRL</span> + <span class="rokpad-key">ALT</span> + <span class="rokpad-key">BACKSPACE</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Remove word left</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac">';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">DELETE</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Remove word right</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">A</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">A</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select all</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select down</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">←</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">←</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select left</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">END</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">END</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select line end</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">HOME</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">HOME</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select line start</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">PAGEDOWN</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">PAGEDOWN</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select page down</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">PAGEUP</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">PAGEUP</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select page up</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">→</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">→</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select right</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">END</span> <br /> <span class="rokpad-key">ALT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select to end</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">→</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">→</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select to line end</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">←</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">←</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select to line start</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">HOME</span> <br /> <span class="rokpad-key">ALT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select to start</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select up</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">←</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">←</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select word left</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">→</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">→</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select word right</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac">';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">O</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Split line</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">7</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">7</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Toggle comment</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">T</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">T</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Transpose letters</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">Z</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">Z</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Undo</span>';
$html[] = ' </li>';
$html[] = ' </ul>';
$html[] = ' <div class="rok-popover-arrow"></div>';
$html[] = ' </div>';
$html[] = ' </div>';
$html[] = ' </li>';
$html[] = ' <li><div class="rok-button rokpad-tip" data-original-title="Fullscreen / Windowed" data-placement="below-right" data-rokpad-fullscreen><i class="rokpad-icon-fullscreen"></i></div></li>';
//$html[] = ' <li><div class="rok-button rok-button-red"></div></li>';
//$html[] = ' <li><div class="rok-button rok-button-black"></div></li>';
$html[] = ' </ul>';
$html[] = ' </div>';
$html[] = ' <div class="rokpad-shortcodes">';
$html[] = ' <ul>';
$html[] = ' <li data-rokpad-shortcode="<h1>{data}{cur}</h1>" class="rokpad-tip" data-original-title="Heading 1" data-placement="below-left"><i class="rokpad-icon-h1"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<h2>{data}{cur}</h2>" class="rokpad-tip" data-original-title="Heading 2" data-placement="below"><i class="rokpad-icon-h2"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<h3>{data}{cur}</h3>" class="rokpad-tip" data-original-title="Heading 3" data-placement="below"><i class="rokpad-icon-h3"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<strong>{data}{cur}</strong>" class="rokpad-tip" data-original-title="Bold/Strong Text" data-placement="below"><i class="rokpad-icon-bold"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<em>{data}{cur}</em>" class="rokpad-tip" data-original-title="Emphasized Text" data-placement="below"><i class="rokpad-icon-italic"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<u>{data}{cur}</u>" class="rokpad-tip" data-original-title="Underlined Text" data-placement="below"><i class="rokpad-icon-underline"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<ol>{n}{t}<li>{data}{cur}</li>{n}</ol>" class="rokpad-tip" data-original-title="Ordered List" data-placement="below"><i class="rokpad-icon-olist"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<ul>{n}{t}<li>{data}{cur}</li>{n}</ul>" class="rokpad-tip" data-original-title="Unordered List" data-placement="below"><i class="rokpad-icon-ulist"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<img src=\'{cur}\' alt=\'{data}\' />" class="rokpad-tip" data-original-title="Image" data-placement="below"><i class="rokpad-icon-image"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<p>{data}{cur}</p>" class="rokpad-tip" data-original-title="Paragraph" data-placement="below"><i class="rokpad-icon-paragraph"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<a href=\'{cur}\'>{data}</a>" class="rokpad-tip" data-original-title="Link" data-placement="below"><i class="rokpad-icon-link"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<hr />" class="rokpad-tip" data-original-title="Horizontal Rule (<hr />)" data-placement="below"><i class="rokpad-icon-hr"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<{cur}>{data}</{cur}>" class="rokpad-tip" data-original-title="Universal Tag. Click and start typing the desired tag (ie, div). Hit ESC when done." data-placement="below"><i class="rokpad-icon-universal"></i></li>';
$html[] = ' </ul>';
$html[] = ' </div>';
$html[] = ' <div class="rokpad-editor-container" data-rokpad-container>';
$html[] = ' <div id="' . $id . '-rokpad-editor" class="rokpad-editor"></div>';
$html[] = ' <textarea data-rokpad-original class="rokpad-editor-original" name="' . $name . '" id="' . $id . '" cols="' . $col . '" rows="' . $row . '">' . $content . '</textarea>';
$html[] = ' </div>';
$html[] = ' <div class="rokpad-actionbar" data-rokpad-actionbar>';
$html[] = ' <ul>';
$html[] = ' <li class="rokpad-column-1">';
$html[] = ' <div class="rok-buttons-group">';
$html[] = ' <div class="rok-button rok-button-unchecked rokpad-tip" data-original-title="Regular Expression" data-placement="above-left" data-rokpad-action-setting="regExp"><i class="rokpad-icon-regexp"></i></div>';
$html[] = ' <div class="rok-button rok-button-unchecked rokpad-tip" data-original-title="Case Sensitive" data-placement="above" data-rokpad-action-setting="caseSensitive"><i class="rokpad-icon-casesensi"></i></div>';
$html[] = ' <div class="rok-button rok-button-unchecked rokpad-tip" data-original-title="Whole Word" data-placement="above" data-rokpad-action-setting="wholeWord"><i class="rokpad-icon-wholeword"></i></div>';
$html[] = ' </div>';
$html[] = ' <div class="rok-buttons-group">';
$html[] = ' <div class="rok-button rok-button-unchecked rokpad-tip" data-original-title="Reverse Direction" data-placement="above" data-rokpad-action-setting="backwards"><i class="rokpad-icon-reversedir"></i></div>';
$html[] = ' <div class="rok-button rok-button-unchecked rokpad-tip" data-original-title="Wrap" data-placement="above" data-rokpad-action-setting="wrap"><i class="rokpad-icon-wrap"></i></div>';
$html[] = ' <div class="rok-button rok-button-unchecked rokpad-tip" data-original-title="In Selection" data-placement="above" data-rokpad-action-setting="scope"><i class="rokpad-icon-inselection"></i></div>';
$html[] = ' </div>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-column-2">';
$html[] = ' <div class="rok-input-wrapper rok-input-row-1" data-rokpad-action-method="find"><input type="text" placeholder="Find..." /></div>';
$html[] = ' <div class="rok-input-wrapper rok-input-row-1" data-rokpad-action-method="goto"><input type="text" placeholder="Goto Line..." /></div>';
$html[] = ' <div class="rok-input-wrapper rok-input-row-2" data-rokpad-action-method="replace"><input type="text" placeholder="Replace..." /></div>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-column-3">';
$html[] = ' <div class="rok-input-row-1">';
$html[] = ' <div class="rok-buttons-group">';
$html[] = ' <div class="rok-button rok-button-noicon" data-rokpad-action="find">Find</div>';
$html[] = ' <div class="rok-button rok-button-noicon" data-rokpad-action="findAll">All</div>';
$html[] = ' </div>';
$html[] = ' <div class="rok-buttons-group">';
$html[] = ' <div class="rok-button rokpad-tip" data-original-title="Find Previous" data-placement="above" data-rokpad-action="findPrevious"><i class="rokpad-icon-prev"></i></div>';
$html[] = ' <div class="rok-button rokpad-tip" data-original-title="Find Next" data-placement="above-right" data-rokpad-action="findNext"><i class="rokpad-icon-next"></i></div>';
$html[] = ' </div>';
$html[] = ' <div class="rok-button rok-button-noicon" data-rokpad-action="goto">Goto Line</div>';
$html[] = ' </div>';
$html[] = ' <div class="rok-input-row-2">';
$html[] = ' <div class="rok-buttons-group">';
$html[] = ' <div class="rok-button rok-button-noicon" data-rokpad-action="replace">Replace</div>';
$html[] = ' <div class="rok-button rok-button-noicon" data-rokpad-action="replaceAll">All</div>';
$html[] = ' </div>';
$html[] = ' </div>';
$html[] = ' </li>';
$html[] = ' </ul>';
$html[] = ' </div>';
$html[] = ' <div class="rokpad-statusbar">';
$html[] = ' <ul data-rokpad-dropdown="mode" class="rok-dropdown">';
$html[] = ' <li data-rokpad-mode="css"><a href="#">CSS</a></li>';
$html[] = ' <li data-rokpad-mode="html"><a href="#">HTML</a></li>';
$html[] = ' <li data-rokpad-mode="javascript"><a href="#">JavaScript</a></li>';
$html[] = ' <li data-rokpad-mode="json"><a href="#">JSON</a></li>';
$html[] = ' <li data-rokpad-mode="less"><a href="#">LESS</a></li>';
$html[] = ' <li data-rokpad-mode="markdown"><a href="#">Markdown</a></li>';
$html[] = ' <li data-rokpad-mode="php"><a href="#">PHP</a></li>';
$html[] = ' <li data-rokpad-mode="sql"><a href="#">SQL</a></li>';
$html[] = ' <li data-rokpad-mode="text"><a href="#">Plain Text</a></li>';
$html[] = ' <li data-rokpad-mode="textile"><a href="#">Textile</a></li>';
$html[] = ' <li data-rokpad-mode="xml"><a href="#">XML</a></li>';
$html[] = ' </ul>';
$html[] = ' <ul data-rokpad-dropdown="tabs" class="rok-dropdown">';
$html[] = ' <li data-rokpad-softtabs="0"><a href="#">Indent Using Spaces</a></li>';
$html[] = ' <li class="divider"></li>';
$html[] = ' <li data-rokpad-tabsize="1"><a href="#">Tab Width: 1</a></li>';
$html[] = ' <li data-rokpad-tabsize="2"><a href="#">Tab Width: 2</a></li>';
$html[] = ' <li data-rokpad-tabsize="3"><a href="#">Tab Width: 3</a></li>';
$html[] = ' <li data-rokpad-tabsize="4"><a href="#">Tab Width: 4</a></li>';
$html[] = ' <li data-rokpad-tabsize="5"><a href="#">Tab Width: 5</a></li>';
$html[] = ' <li data-rokpad-tabsize="6"><a href="#">Tab Width: 6</a></li>';
$html[] = ' <li data-rokpad-tabsize="7"><a href="#">Tab Width: 7</a></li>';
$html[] = ' <li data-rokpad-tabsize="8"><a href="#">Tab Width: 8</a></li>';
$html[] = ' </ul>';
$html[] = ' <ul class="rok-left">';
$html[] = ' <li data-rokpad-lastsave>Last save: <span data-rokpad-savedate>never</span></li>';
$html[] = ' </ul>';
$html[] = ' <ul class="rok-right">';
$html[] = ' <li data-rokpad-tabsize data-rokpad-toggle="tabs">Tab Size: <span>4</span></li>';
$html[] = ' <li class="divider"></li>';
$html[] = ' <li data-rokpad-mode data-rokpad-toggle="mode">Mode: <span>HTML</span></li>';
$html[] = ' </ul>';
$html[] = ' </div>';
$html[] = '</div>';
$html[] = $buttons;
$output = "";
$output .= implode("\n", $html);
return $output;
}
/**
* @param $name
* @param $buttons
* @param $asset
* @param $author
*
* @return string
*/
protected function _displayButtons($name, $buttons, $asset, $author)
{
// Load modal popup behavior
JHtml::_('behavior.modal', 'a.modal-button');
$args['name'] = $name;
$args['event'] = 'onGetInsertMethod';
$return = '';
$results[] = $this->update($args);
foreach ($results as $result) {
if (is_string($result) && trim($result)) {
$return .= $result;
}
}
if (is_array($buttons) || (is_bool($buttons) && $buttons)) {
$results = $this->_subject->getButtons($name, $buttons, $asset, $author);
$version = new JVersion();
if (version_compare($version->getShortVersion(), '3.0', '>=')) {
/*
* This will allow plugins to attach buttons or change the behavior on the fly using AJAX
*/
$return .= "\n<div id=\"editor-xtd-buttons\" class=\"btn-toolbar pull-left\">\n";
$return .= "\n<div class=\"btn-toolbar\">\n";
foreach ($results as $button)
{
/*
* Results should be an object
*/
if ( $button->get('name') ) {
$modal = ($button->get('modal')) ? ' class="modal-button btn"' : null;
$href = ($button->get('link')) ? ' class="btn" href="'.JURI::base().$button->get('link').'"' : null;
$onclick = ($button->get('onclick')) ? ' onclick="'.$button->get('onclick').'"' : '';
$title = ($button->get('title')) ? $button->get('title') : $button->get('text');
$return .= '<a' . $modal . ' title="' . $title . '"' . $href . $onclick . ' rel="' . $button->get('options')
. '"><i class="icon-' . $button->get('name'). '"></i> ' . $button->get('text') . "</a>\n";
}
}
$return .= "</div>\n";
$return .= "</div>\n";
} else {
// This will allow plugins to attach buttons or change the behavior on the fly using AJAX
$return .= "\n".'<div id="editor-xtd-buttons"><div class="btn-toolbar pull-left rokpad-clearfix">'."\n";
foreach ($results as $button) {
// Results should be an object
if ($button->get('name')) {
$modal = ($button->get('modal')) ? 'class="modal-button"' : null;
$href = ($button->get('link')) ? 'href="' . JURI::base() . $button->get('link') . '"' : null;
$onclick = ($button->get('onclick')) ? 'onclick="' . $button->get('onclick') . '"' : null;
$title = ($button->get('title')) ? $button->get('title') : $button->get('text');
$return .= "\n".'<div class="button2-left"><div class="' . $button->get('name') . '">';
$return .= '<a ' . $modal . ' title="' . $title . '" ' . $href . ' ' . $onclick . ' rel="' . $button->get('options') . '">';
$return .= $button->get('text') . '</a>'."\n".'</div>'."\n".'</div>'."\n";
}
}
$return .= '</div></div>'."\n";
}
}
return $return;
}
/**
* @return string
*/
protected function _appendCacheToken()
{
return '?cache=' . $this->_version;
}
/**
*
*/
protected function compileLess()
{
$document = JFactory::getDocument();
$assets = JPATH_PLUGINS . DIRECTORY_SEPARATOR . 'editors' . DIRECTORY_SEPARATOR . 'rokpad' . DIRECTORY_SEPARATOR . 'assets';
@include_once($assets . '/less/mixins/lessc.inc.php');
if (defined('DEV') && DEV) {
try {
$css_file = $assets . '/styles/rokpad.css';
@unlink($css_file);
lessc::ccompile($assets . '/less/global.less', $css_file);
} catch (exception $e) {
JError::raiseError('LESS Compiler', $e->getMessage());
}
}
$document->addStyleSheet($this->_basepath . 'assets/styles/rokpad.css' . $this->_appendCacheToken());
}
/**
*
*/
protected function compileJS()
{
$document = JFactory::getDocument();
$rokpad = JPATH_PLUGINS . DIRECTORY_SEPARATOR . 'editors' . DIRECTORY_SEPARATOR . 'rokpad';
if (defined('DEV') && DEV) {
$buffer = "";
$assets = $rokpad . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR;
$app = $rokpad . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'application' . DIRECTORY_SEPARATOR;
$files = array(
$assets . 'moofx',
$app. 'respond', $app . 'jstorage', $app . 'beautify-html', $app . 'Twipsy',
$app . 'RokPad', $app . 'RokPad.ACE', $app. 'RokPad.Functs'
);
foreach ($files as $file) {
$file = $file . '.js';
$content = false;
if (file_exists($file)) $content = file_get_contents($file);
$buffer .= (!$content) ? "\n\n !!! File not Found: " . $file . " !!! \n\n" : $content;
}
file_put_contents($assets . 'rokpad.js', $buffer);
}
$document->addScript($this->_basepath . 'ace/ace.js' . $this->_appendCacheToken());
$document->addScript($this->_basepath . 'assets/js/rokpad.js' . $this->_appendCacheToken());
}
/**
* @return string
*/
protected function getJSParams()
{
$document = JFactory::getDocument();
$params = $this->params->toArray();
if (!array_key_exists('theme', $params)) {
$params = array(
'theme' => 'fluidvision',
'font-size' => '12px',
'fold-style' => 'markbeginend',
'use-wrap-mode' => 'free',
'selection-style' => '1',
'highlight-active-line' => '1',
'highlight-selected-word' => '1',
'show-invisibles' => '0',
'show-gutter' => '1',
'show-print-margin' => '1',
'fade-fold-widgets' => '0',
'autosave-enabled' => '0',
'autosave-time' => '5'
);
}
$data = "";
$data .= "var RokPadDefaultSettings = {";
foreach ($params as $param => $value) {
$data .= "'" . $param . "': '" . $value . "', ";
}
$data = substr($data, 0, strlen($data) - 2);
$data .= "}, RokPadAcePath = '".$this->_acepath."';";
return $data;
}
}
|
cnpisit/myangkorpeopel
|
plugins/editors/rokpad/rokpad.php
|
PHP
|
gpl-2.0
| 50,100
|
package se.stagehand.effects.compound
import se.stagehand.swing.lib.EffectGUI
import se.stagehand.lib.scripting.Effect
import se.stagehand.swing.lib.TargetedPlayerEffectItem
import scala.swing.BoxPanel
import scala.swing.Orientation
import se.stagehand.swing.lib.EditorEffectItem
import scala.swing.BorderPanel
import se.stagehand.swing.lib.AddEffectsButton
import scala.swing.Button
import se.stagehand.lib.scripting.Targets
import scala.swing.Swing
import scala.swing.FlowPanel
import se.stagehand.swing.lib.GUIManager
import se.stagehand.swing.lib.PlayerEffectItem
import se.stagehand.swing.gui.Resizable
object CompoundGUI extends EffectGUI {
val peer = classOf[CompoundEffect]
def editorItem(effect: Effect) = new CompoundEditorItem(checkEffect[CompoundEffect](effect))
def playerItem(effect: Effect) = new CompoundPlayerItem(checkEffect[CompoundEffect](effect))
}
class CompoundEditorItem(e: CompoundEffect) extends BoxPanel(Orientation.Horizontal) with EditorEffectItem[CompoundEffect] {
def effect = e
val effectList = new BoxPanel(Orientation.Vertical) {
border = Swing.EtchedBorder(Swing.Raised)
}
val addButton:Button = new AddEffectsButton(this,effectList,(gui,comp) => {
effect.addEffect(comp)
effectList.contents += gui
refresh
}, (c) => {
c != effect.getClass && !effect.effects.map(_.getClass()).contains(c)
})
contents += effectList
contents += new FlowPanel { contents += addButton }
effect.effects.foreach(e => {
val gui = GUIManager.componentByID[EditorEffectItem[_]](e.id)
gui match {
case Some(g) => {
effectList.contents += g
}
case None => {
effectList.contents += GUIManager.editorItem(e)
}
}
})
refresh
}
class CompoundPlayerItem(e: CompoundEffect) extends TargetedPlayerEffectItem[CompoundEffect](e) {
private def me = this
def effectItem = bp
border = Swing.EtchedBorder(Swing.Raised)
private def bp = new BoxPanel(Orientation.Vertical) {
border = Swing.EtchedBorder(Swing.Raised)
for (e <- effect.effects) {
val item = GUIManager.getGUI[EffectGUI](e.getClass).playerItem(e)
item.asInstanceOf[PlayerEffectItem[_ <: Effect]] match {
case e: TargetedPlayerEffectItem[_] => contents += e.effectItem
case e => contents += e
}
item.refresh
}
refresh
}
}
|
evilcandybag/Stagehand-compound-effect
|
src/main/scala/se/stagehand/effects/compound/CompoundGUI.scala
|
Scala
|
gpl-2.0
| 2,381
|
<?php
$cfg = require __DIR__ . '/../vendor/mediawiki/mediawiki-phan-config/src/config.php';
$cfg['directory_list'] = array_merge(
$cfg['directory_list'],
[
'../../extensions/MobileFrontend',
'../../extensions/VisualEditor',
'../../extensions/CentralAuth',
'../../extensions/CirrusSearch',
]
);
$cfg['exclude_analysis_directory_list'] = array_merge(
$cfg['exclude_analysis_directory_list'],
[
'../../extensions/MobileFrontend',
'../../extensions/VisualEditor',
'../../extensions/CentralAuth',
'../../extensions/CirrusSearch',
]
);
return $cfg;
|
wikimedia/mediawiki-extensions-GettingStarted
|
.phan/config.php
|
PHP
|
gpl-2.0
| 569
|
package app.astrosoft.ui.cal;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;
import javax.swing.*;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import javax.swing.plaf.basic.BasicArrowButton;
import app.astrosoft.ui.util.UIUtil;
public class JCalendarCombo extends JPanel implements Observer {
public static final int SUNDAY = 0;
public static final int MONDAY = 1;
private boolean condition;
private JWindow window;
private JCalendar calendar;
private JTextField textField;
private int startYear;
private int endYear;
public JCalendarCombo( ) {
condition = false;
startYear = 1801;
endYear = 2099;
calendar = new JCalendar( );
initializeJCalendarCombo( );
}
public JCalendarCombo( int firstDay, boolean showCurrentDate ) {
condition = false;
startYear = 1801;
endYear = 2099;
calendar = new JCalendar( firstDay, showCurrentDate );
initializeJCalendarCombo( );
}
public JCalendarCombo(
int firstDay, boolean showCurrentDate, int startYear, int endYear ) {
condition = false;
this.startYear = startYear;
this.endYear = endYear;
calendar =
new JCalendar( firstDay, showCurrentDate, startYear, endYear );
initializeJCalendarCombo( );
}
private final void initializeJCalendarCombo( ) {
textField = new JTextField( 10 );
textField.setEditable( false );
textField.setBackground( new Color( 255, 255, 255 ) );
javax.swing.JButton button =
new BasicArrowButton(
5, new Color( 255, 255, 255 ), new Color( 0, 0, 0 ),
new Color( 0, 0, 0 ), new Color( 0, 0, 0 ) );
setLayout( new BorderLayout( ) );
add( textField, "Center" );
add( button, "East" );
setSelectedDate( );
button.addActionListener(
new ActionListener( ) {
public void actionPerformed( ActionEvent e ) {
if ( !condition ) {
condition = true;
window =
new JWindow(
( Window ) textField.getTopLevelAncestor( ) );
window.getContentPane( ).setLayout(
new BorderLayout( ) );
//window.getContentPane().setBackground(new Color(0,0,0));
calendar.initializeCalendar( );
window.getContentPane( ).add( calendar, "Center" );
window.pack( );
UIUtil.setWindowLocation(window, textField);
// TODO: Remove later since this is replaced by UIUtil.setWindowLocation();
/*Point textFieldLocation =
textField.getLocationOnScreen( );
Dimension size = textField.getSize( );
Dimension windowSize = window.getSize( );
Dimension screenSize =
Toolkit.getDefaultToolkit( ).getScreenSize( );
if (
( ( textFieldLocation.x
- ( windowSize.width - size.width ) ) <= 0 )
&& ( ( textFieldLocation.y + size.height
+ windowSize.height ) >= screenSize.height ) ) {
window.setLocation(
0, textFieldLocation.y - windowSize.height );
} else if (
( textFieldLocation.x
- ( windowSize.width - size.width ) ) <= 0 ) {
window.setLocation(
0, textFieldLocation.y + size.height );
} else if (
( textFieldLocation.y + size.height
+ windowSize.height ) >= screenSize.height ) {
window.setLocation(
textFieldLocation.x
- ( windowSize.width - size.width ),
textFieldLocation.y - windowSize.height );
} else {
window.setLocation(
textFieldLocation.x
- ( windowSize.width - size.width ),
textFieldLocation.y + size.height );
}*/
window.setVisible( true );
} else {
window.dispose( );
setSelectedDate( );
condition = false;
}
}
} );
addAncestorListener(
new AncestorListener( ) {
public void ancestorAdded( AncestorEvent e ) {
if ( condition ) {
condition = false;
setSelectedDate( );
window.dispose( );
}
}
public void ancestorMoved( AncestorEvent e ) {
if ( condition ) {
condition = false;
setSelectedDate( );
window.dispose( );
}
}
public void ancestorRemoved( AncestorEvent e ) {
if ( condition ) {
condition = false;
setSelectedDate( );
window.dispose( );
}
}
} );
calendar.buttonItemListener.addObserver( this );
}
private final void setSelectedDate( ) {
textField.setText(
calendar.getDay( ) + "/" + calendar.getMonth( ) + "/"
+ calendar.getYear( ) );
condition = false;
}
public final void setSelectedDate( int year, int month, int day ) {
calendar.setDay( ( new Integer( day ) ).toString( ) );
calendar.setMonth( ( new Integer( month ) ).toString( ) );
calendar.setYear( ( new Integer( year ) ).toString( ) );
calendar.showCalendarForDate( year, month );
textField.setText(
calendar.getDay( ) + "/" + calendar.getMonth( ) + "/"
+ calendar.getYear( ) );
condition = false;
}
public final String getSelectedDate( ) {
return textField.getText( );
}
public final String getSelectedDay( ) {
return calendar.getDay( );
}
public final String getSelectedMonth( ) {
return calendar.getMonth( );
}
public final String getSelectedYear( ) {
return calendar.getYear( );
}
public void update( Observable observable, Object object ) {
window.dispose( );
setSelectedDate( );
}
}
|
erajasekar/Astrosoft
|
src/app/astrosoft/ui/cal/JCalendarCombo.java
|
Java
|
gpl-2.0
| 7,350
|
#ifndef IMAGE_H
#define IMAGE_H
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <string>
#include <string.h>
namespace Aurora
{
namespace Graphics
{
enum ImageLocation
{
Ram,
Vram
};
class Image
{
public:
int _width;
int _height;
int _textureWidth;
int _textureHeight;
unsigned int _id;
unsigned int _id2;
unsigned char *_pixels;
std::string _fileName;
Image();
~Image();
bool loadImageFromFile(std::string fileName);
bool loadImageFromMemory(std::string newName,void *data,std::size_t size);
unsigned int getColour(int x,int y);
void getColour(int x,int y,unsigned char &r,unsigned char &g,unsigned char &b,unsigned char &a);
};
}
}
#endif
|
DrakonPL/MultiCraft
|
Aurora/Aurora/Graphics/Image.h
|
C
|
gpl-2.0
| 739
|
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>schrodinger.application.desmond.ffiostructure._FFIOPosFBHW</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
>2015-2Schrodinger Python API</th>
</tr></table></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
<a href="schrodinger-module.html">Package schrodinger</a> ::
<a href="schrodinger.application-module.html">Package application</a> ::
<a href="schrodinger.application.desmond-module.html">Package desmond</a> ::
<a href="schrodinger.application.desmond.ffiostructure-module.html">Module ffiostructure</a> ::
Class _FFIOPosFBHW
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="schrodinger.application.desmond.ffiostructure._FFIOPosFBHW-class.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<!-- ==================== CLASS DESCRIPTION ==================== -->
<h1 class="epydoc">Class _FFIOPosFBHW</h1><p class="nomargin-top"></p>
<pre class="base-tree">
<a href="object-class.html">object</a> --+
|
<a href="schrodinger.application.desmond.ffiostructure._FFIOSubBlock-class.html" onclick="show_private();">_FFIOSubBlock</a> --+
|
<strong class="uidshort">_FFIOPosFBHW</strong>
</pre>
<hr />
<p>A class to make access of mmffio position flat bottom properties more
pythonic.</p>
<!-- ==================== NESTED CLASSES ==================== -->
<a name="section-NestedClasses"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Nested Classes</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-NestedClasses"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="schrodinger.application.desmond.ffiostructure._FFIOSubBlockMeta-class.html" class="summary-name">__metaclass__</a><br />
A meta-class to different ffio sub block type classses.
</td>
</tr>
</table>
<!-- ==================== INSTANCE METHODS ==================== -->
<a name="section-InstanceMethods"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Instance Methods</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-InstanceMethods"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.application.desmond.ffiostructure._FFIOSubBlock-class.html" onclick="show_private();">_FFIOSubBlock</a></code></b>:
<code><a href="schrodinger.application.desmond.ffiostructure._FFIOSubBlock-class.html#__eq__">__eq__</a></code>,
<code><a href="schrodinger.application.desmond.ffiostructure._FFIOSubBlock-class.html#__hash__">__hash__</a></code>,
<code><a href="schrodinger.application.desmond.ffiostructure._FFIOSubBlock-class.html#__init__">__init__</a></code>,
<code><a href="schrodinger.application.desmond.ffiostructure._FFIOSubBlock-class.html#__int__">__int__</a></code>,
<code><a href="schrodinger.application.desmond.ffiostructure._FFIOSubBlock-class.html#__ne__">__ne__</a></code>,
<code><a href="schrodinger.application.desmond.ffiostructure._FFIOSubBlock-class.html#__str__">__str__</a></code>
</p>
<div class="private"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.application.desmond.ffiostructure._FFIOSubBlock-class.html" onclick="show_private();">_FFIOSubBlock</a></code></b> (private):
<code><a href="schrodinger.application.desmond.ffiostructure._FFIOSubBlock-class.html#_getIndex" onclick="show_private();">_getIndex</a></code>,
<code><a href="schrodinger.application.desmond.ffiostructure._FFIOSubBlock-class.html#_getProperty" onclick="show_private();">_getProperty</a></code>
</p></div>
<p class="indent-wrapped-lines"><b>Inherited from <code><a href="object-class.html">object</a></code></b>:
<code><a href="object-class.html#__delattr__">__delattr__</a></code>,
<code><a href="object-class.html#__format__">__format__</a></code>,
<code><a href="object-class.html#__getattribute__">__getattribute__</a></code>,
<code><a href="object-class.html#__new__">__new__</a></code>,
<code><a href="object-class.html#__reduce__">__reduce__</a></code>,
<code><a href="object-class.html#__reduce_ex__">__reduce_ex__</a></code>,
<code><a href="object-class.html#__repr__">__repr__</a></code>,
<code><a href="object-class.html#__setattr__">__setattr__</a></code>,
<code><a href="object-class.html#__sizeof__">__sizeof__</a></code>,
<code><a href="object-class.html#__subclasshook__">__subclasshook__</a></code>
</p>
</td>
</tr>
</table>
<!-- ==================== CLASS VARIABLES ==================== -->
<a name="section-ClassVariables"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Class Variables</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-ClassVariables"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="block_type"></a><span class="summary-name">block_type</span> = <code title="'posfbhw'"><code class="variable-quote">'</code><code class="variable-string">posfbhw</code><code class="variable-quote">'</code></code><br />
hash(x)
</td>
</tr>
</table>
<!-- ==================== PROPERTIES ==================== -->
<a name="section-Properties"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Properties</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Properties"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="schrodinger.application.desmond.ffiostructure._FFIOPosFBHW-class.html#ai" class="summary-name">ai</a><br />
posfbhw ai
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="schrodinger.application.desmond.ffiostructure._FFIOPosFBHW-class.html#fc" class="summary-name">fc</a><br />
posfbhw fc
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="schrodinger.application.desmond.ffiostructure._FFIOPosFBHW-class.html#sigma" class="summary-name">sigma</a><br />
posfbhw sigma
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="schrodinger.application.desmond.ffiostructure._FFIOPosFBHW-class.html#x0" class="summary-name">x0</a><br />
posfbhw x0
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="schrodinger.application.desmond.ffiostructure._FFIOPosFBHW-class.html#y0" class="summary-name">y0</a><br />
posfbhw y0
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="schrodinger.application.desmond.ffiostructure._FFIOPosFBHW-class.html#z0" class="summary-name">z0</a><br />
posfbhw z0
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.application.desmond.ffiostructure._FFIOSubBlock-class.html" onclick="show_private();">_FFIOSubBlock</a></code></b>:
<code><a href="schrodinger.application.desmond.ffiostructure._FFIOSubBlock-class.html#index">index</a></code>,
<code><a href="schrodinger.application.desmond.ffiostructure._FFIOSubBlock-class.html#property">property</a></code>
</p>
<p class="indent-wrapped-lines"><b>Inherited from <code><a href="object-class.html">object</a></code></b>:
<code><a href="object-class.html#__class__">__class__</a></code>
</p>
</td>
</tr>
</table>
<!-- ==================== PROPERTY DETAILS ==================== -->
<a name="section-PropertyDetails"></a>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Property Details</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-PropertyDetails"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
</table>
<a name="ai"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<h3 class="epydoc">ai</h3>
<p>posfbhw ai</p>
<dl class="fields">
<dt>Get Method:</dt>
<dd class="value"><span class="summary-sig"><i>unreachable</i>._get(<span class="summary-sig-arg">self</span>)</span>
</dd>
<dt>Set Method:</dt>
<dd class="value"><span class="summary-sig"><i>unreachable</i>._set(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span>
</dd>
</dl>
</td></tr></table>
</div>
<a name="fc"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<h3 class="epydoc">fc</h3>
<p>posfbhw fc</p>
<dl class="fields">
<dt>Get Method:</dt>
<dd class="value"><span class="summary-sig"><i>unreachable</i>._get(<span class="summary-sig-arg">self</span>)</span>
</dd>
<dt>Set Method:</dt>
<dd class="value"><span class="summary-sig"><i>unreachable</i>._set(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span>
</dd>
</dl>
</td></tr></table>
</div>
<a name="sigma"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<h3 class="epydoc">sigma</h3>
<p>posfbhw sigma</p>
<dl class="fields">
<dt>Get Method:</dt>
<dd class="value"><span class="summary-sig"><i>unreachable</i>._get(<span class="summary-sig-arg">self</span>)</span>
</dd>
<dt>Set Method:</dt>
<dd class="value"><span class="summary-sig"><i>unreachable</i>._set(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span>
</dd>
</dl>
</td></tr></table>
</div>
<a name="x0"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<h3 class="epydoc">x0</h3>
<p>posfbhw x0</p>
<dl class="fields">
<dt>Get Method:</dt>
<dd class="value"><span class="summary-sig"><i>unreachable</i>._get(<span class="summary-sig-arg">self</span>)</span>
</dd>
<dt>Set Method:</dt>
<dd class="value"><span class="summary-sig"><i>unreachable</i>._set(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span>
</dd>
</dl>
</td></tr></table>
</div>
<a name="y0"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<h3 class="epydoc">y0</h3>
<p>posfbhw y0</p>
<dl class="fields">
<dt>Get Method:</dt>
<dd class="value"><span class="summary-sig"><i>unreachable</i>._get(<span class="summary-sig-arg">self</span>)</span>
</dd>
<dt>Set Method:</dt>
<dd class="value"><span class="summary-sig"><i>unreachable</i>._set(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span>
</dd>
</dl>
</td></tr></table>
</div>
<a name="z0"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<h3 class="epydoc">z0</h3>
<p>posfbhw z0</p>
<dl class="fields">
<dt>Get Method:</dt>
<dd class="value"><span class="summary-sig"><i>unreachable</i>._get(<span class="summary-sig-arg">self</span>)</span>
</dd>
<dt>Set Method:</dt>
<dd class="value"><span class="summary-sig"><i>unreachable</i>._set(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">value</span>)</span>
</dd>
</dl>
</td></tr></table>
</div>
<br />
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
>2015-2Schrodinger Python API</th>
</tr></table></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0.1 on Sat May 9 06:31:09 2015
</td>
<td align="right" class="footer">
<a target="mainFrame" href="http://epydoc.sourceforge.net"
>http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
// -->
</script>
</body>
</html>
|
platinhom/ManualHom
|
Schrodinger/Schrodinger_2015-2_docs/python_api/api/schrodinger.application.desmond.ffiostructure._FFIOPosFBHW-class.html
|
HTML
|
gpl-2.0
| 17,501
|
/* $Id: ldrkStuff.cpp $ */
/** @file
* IPRT - Binary Image Loader, kLdr Interface.
*/
/*
* Copyright (C) 2006-2007 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.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#define LOG_GROUP RTLOGGROUP_LDR
#include <iprt/ldr.h>
#include "internal/iprt.h"
#include <iprt/file.h>
#include <iprt/alloc.h>
#include <iprt/alloca.h>
#include <iprt/assert.h>
#include <iprt/string.h>
#include <iprt/path.h>
#include <iprt/log.h>
#include <iprt/param.h>
#include <iprt/err.h>
#include "internal/ldr.h"
#define KLDR_ALREADY_INCLUDE_STD_TYPES
#define KLDR_NO_KLDR_H_INCLUDES
#include <k/kLdr.h>
#include <k/kRdrAll.h>
#include <k/kErr.h>
#include <k/kErrors.h>
#include <k/kMagics.h>
/*******************************************************************************
* Structures and Typedefs *
*******************************************************************************/
/**
* kLdr file provider.
*/
typedef struct RTKLDRRDR
{
/** The core. */
KRDR Core;
/** The IPRT bit reader. */
PRTLDRREADER pReader;
} RTKLDRRDR, *PRTKLDRRDR;
/**
* IPRT module.
*/
typedef struct RTLDRMODKLDR
{
/** The Core module structure. */
RTLDRMODINTERNAL Core;
/** The kLdr module. */
PKLDRMOD pMod;
} RTLDRMODKLDR, *PRTLDRMODKLDR;
/**
* Arguments for a RTLDRMODKLDR callback wrapper.
*/
typedef struct RTLDRMODKLDRARGS
{
union
{
PFNRT pfn;
PFNRTLDRENUMDBG pfnEnumDbgInfo;
PFNRTLDRENUMSYMS pfnEnumSyms;
PFNRTLDRIMPORT pfnGetImport;
} u;
void *pvUser;
const void *pvBits;
PRTLDRMODKLDR pMod;
int rc;
} RTLDRMODKLDRARGS, *PRTLDRMODKLDRARGS;
/**
* Converts a kLdr error code to an IPRT one.
*/
static int rtkldrConvertError(int krc)
{
if (!krc)
return VINF_SUCCESS;
switch (krc)
{
case KERR_INVALID_PARAMETER: return VERR_INVALID_PARAMETER;
case KERR_INVALID_HANDLE: return VERR_INVALID_HANDLE;
case KERR_NO_MEMORY: return VERR_NO_MEMORY;
case KLDR_ERR_UNKNOWN_FORMAT:
case KLDR_ERR_MZ_NOT_SUPPORTED: return VERR_MZ_EXE_NOT_SUPPORTED;
case KLDR_ERR_NE_NOT_SUPPORTED: return VERR_NE_EXE_NOT_SUPPORTED;
case KLDR_ERR_LX_NOT_SUPPORTED: return VERR_LX_EXE_NOT_SUPPORTED;
case KLDR_ERR_LE_NOT_SUPPORTED: return VERR_LE_EXE_NOT_SUPPORTED;
case KLDR_ERR_PE_NOT_SUPPORTED: return VERR_PE_EXE_NOT_SUPPORTED;
case KLDR_ERR_ELF_NOT_SUPPORTED: return VERR_ELF_EXE_NOT_SUPPORTED;
case KLDR_ERR_MACHO_NOT_SUPPORTED: return VERR_INVALID_EXE_SIGNATURE;
case KLDR_ERR_AOUT_NOT_SUPPORTED: return VERR_AOUT_EXE_NOT_SUPPORTED;
case KLDR_ERR_MODULE_NOT_FOUND: return VERR_MODULE_NOT_FOUND;
case KLDR_ERR_PREREQUISITE_MODULE_NOT_FOUND: return VERR_MODULE_NOT_FOUND;
case KLDR_ERR_MAIN_STACK_ALLOC_FAILED: return VERR_NO_MEMORY;
case KERR_BUFFER_OVERFLOW: return VERR_BUFFER_OVERFLOW;
case KLDR_ERR_SYMBOL_NOT_FOUND: return VERR_SYMBOL_NOT_FOUND;
case KLDR_ERR_FORWARDER_SYMBOL: return VERR_BAD_EXE_FORMAT;
case KLDR_ERR_BAD_FIXUP: AssertMsgFailedReturn(("KLDR_ERR_BAD_FIXUP\n"), VERR_BAD_EXE_FORMAT);
case KLDR_ERR_IMPORT_ORDINAL_OUT_OF_BOUNDS: return VERR_BAD_EXE_FORMAT;
case KLDR_ERR_NO_DEBUG_INFO: return VERR_FILE_NOT_FOUND;
case KLDR_ERR_ALREADY_MAPPED: return VERR_WRONG_ORDER;
case KLDR_ERR_NOT_MAPPED: return VERR_WRONG_ORDER;
case KLDR_ERR_ADDRESS_OVERFLOW: return VERR_NUMBER_TOO_BIG;
case KLDR_ERR_TODO: return VERR_NOT_IMPLEMENTED;
case KLDR_ERR_NOT_LOADED_DYNAMICALLY:
case KCPU_ERR_ARCH_CPU_NOT_COMPATIBLE:
case KLDR_ERR_TOO_LONG_FORWARDER_CHAIN:
case KLDR_ERR_MODULE_TERMINATING:
case KLDR_ERR_PREREQUISITE_MODULE_TERMINATING:
case KLDR_ERR_MODULE_INIT_FAILED:
case KLDR_ERR_PREREQUISITE_MODULE_INIT_FAILED:
case KLDR_ERR_MODULE_INIT_FAILED_ALREADY:
case KLDR_ERR_PREREQUISITE_MODULE_INIT_FAILED_ALREADY:
case KLDR_ERR_PREREQUISITE_RECURSED_TOO_DEEPLY:
case KLDR_ERR_THREAD_ATTACH_FAILED:
case KRDR_ERR_TOO_MANY_MAPPINGS:
case KLDR_ERR_NOT_DLL:
case KLDR_ERR_NOT_EXE:
AssertMsgFailedReturn(("krc=%d (%#x): %s\n", krc, krc, kErrName(krc)), VERR_GENERAL_FAILURE);
case KLDR_ERR_PE_UNSUPPORTED_MACHINE:
case KLDR_ERR_PE_BAD_FILE_HEADER:
case KLDR_ERR_PE_BAD_OPTIONAL_HEADER:
case KLDR_ERR_PE_BAD_SECTION_HEADER:
case KLDR_ERR_PE_BAD_FORWARDER:
case KLDR_ERR_PE_FORWARDER_IMPORT_NOT_FOUND:
case KLDR_ERR_PE_BAD_FIXUP:
case KLDR_ERR_PE_BAD_IMPORT:
AssertMsgFailedReturn(("krc=%d (%#x): %s\n", krc, krc, kErrName(krc)), VERR_GENERAL_FAILURE);
case KLDR_ERR_LX_BAD_HEADER:
case KLDR_ERR_LX_BAD_LOADER_SECTION:
case KLDR_ERR_LX_BAD_FIXUP_SECTION:
case KLDR_ERR_LX_BAD_OBJECT_TABLE:
case KLDR_ERR_LX_BAD_PAGE_MAP:
case KLDR_ERR_LX_BAD_ITERDATA:
case KLDR_ERR_LX_BAD_ITERDATA2:
case KLDR_ERR_LX_BAD_BUNDLE:
case KLDR_ERR_LX_NO_SONAME:
case KLDR_ERR_LX_BAD_SONAME:
case KLDR_ERR_LX_BAD_FORWARDER:
case KLDR_ERR_LX_NRICHAIN_NOT_SUPPORTED:
AssertMsgFailedReturn(("krc=%d (%#x): %s\n", krc, krc, kErrName(krc)), VERR_GENERAL_FAILURE);
case KLDR_ERR_MACHO_OTHER_ENDIAN_NOT_SUPPORTED:
case KLDR_ERR_MACHO_BAD_HEADER:
case KLDR_ERR_MACHO_UNSUPPORTED_FILE_TYPE:
case KLDR_ERR_MACHO_UNSUPPORTED_MACHINE:
case KLDR_ERR_MACHO_BAD_LOAD_COMMAND:
case KLDR_ERR_MACHO_UNKNOWN_LOAD_COMMAND:
case KLDR_ERR_MACHO_UNSUPPORTED_LOAD_COMMAND:
case KLDR_ERR_MACHO_BAD_SECTION:
case KLDR_ERR_MACHO_UNSUPPORTED_SECTION:
#ifdef KLDR_ERR_MACHO_UNSUPPORTED_INIT_SECTION
case KLDR_ERR_MACHO_UNSUPPORTED_INIT_SECTION:
case KLDR_ERR_MACHO_UNSUPPORTED_TERM_SECTION:
#endif
case KLDR_ERR_MACHO_UNKNOWN_SECTION:
case KLDR_ERR_MACHO_BAD_SECTION_ORDER:
case KLDR_ERR_MACHO_BIT_MIX:
case KLDR_ERR_MACHO_BAD_OBJECT_FILE:
case KLDR_ERR_MACHO_BAD_SYMBOL:
case KLDR_ERR_MACHO_UNSUPPORTED_FIXUP_TYPE:
AssertMsgFailedReturn(("krc=%d (%#x): %s\n", krc, krc, kErrName(krc)), VERR_GENERAL_FAILURE);
default:
if (RT_FAILURE(krc))
return krc;
AssertMsgFailedReturn(("krc=%d (%#x): %s\n", krc, krc, kErrName(krc)), VERR_NO_TRANSLATION);
}
}
/**
* Converts a IPRT error code to an kLdr one.
*/
static int rtkldrConvertErrorFromIPRT(int rc)
{
if (RT_SUCCESS(rc))
return 0;
switch (rc)
{
case VERR_NO_MEMORY: return KERR_NO_MEMORY;
case VERR_INVALID_PARAMETER: return KERR_INVALID_PARAMETER;
case VERR_INVALID_HANDLE: return KERR_INVALID_HANDLE;
case VERR_BUFFER_OVERFLOW: return KERR_BUFFER_OVERFLOW;
default:
return rc;
}
}
/** @copydoc KLDRRDROPS::pfnCreate
* @remark This is a dummy which isn't used. */
static int rtkldrRdr_Create( PPKRDR ppRdr, const char *pszFilename)
{
NOREF(ppRdr); NOREF(pszFilename);
AssertReleaseFailed();
return -1;
}
/** @copydoc KLDRRDROPS::pfnDestroy */
static int rtkldrRdr_Destroy( PKRDR pRdr)
{
PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
int rc = pReader->pfnDestroy(pReader);
return rtkldrConvertErrorFromIPRT(rc);
}
/** @copydoc KLDRRDROPS::pfnRead */
static int rtkldrRdr_Read( PKRDR pRdr, void *pvBuf, KSIZE cb, KFOFF off)
{
PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
int rc = pReader->pfnRead(pReader, pvBuf, cb, off);
return rtkldrConvertErrorFromIPRT(rc);
}
/** @copydoc KLDRRDROPS::pfnAllMap */
static int rtkldrRdr_AllMap( PKRDR pRdr, const void **ppvBits)
{
PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
int rc = pReader->pfnMap(pReader, ppvBits);
return rtkldrConvertErrorFromIPRT(rc);
}
/** @copydoc KLDRRDROPS::pfnAllUnmap */
static int rtkldrRdr_AllUnmap(PKRDR pRdr, const void *pvBits)
{
PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
int rc = pReader->pfnUnmap(pReader, pvBits);
return rtkldrConvertErrorFromIPRT(rc);
}
/** @copydoc KLDRRDROPS::pfnSize */
static KFOFF rtkldrRdr_Size( PKRDR pRdr)
{
PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
return (KFOFF)pReader->pfnSize(pReader);
}
/** @copydoc KLDRRDROPS::pfnTell */
static KFOFF rtkldrRdr_Tell( PKRDR pRdr)
{
PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
return (KFOFF)pReader->pfnTell(pReader);
}
/** @copydoc KLDRRDROPS::pfnName */
static const char * rtkldrRdr_Name(PKRDR pRdr)
{
PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
return pReader->pfnLogName(pReader);
}
/** @copydoc KLDRRDROPS::pfnNativeFH */
static KIPTR rtkldrRdr_NativeFH(PKRDR pRdr)
{
NOREF(pRdr);
AssertFailed();
return -1;
}
/** @copydoc KLDRRDROPS::pfnPageSize */
static KSIZE rtkldrRdr_PageSize(PKRDR pRdr)
{
NOREF(pRdr);
return PAGE_SIZE;
}
/** @copydoc KLDRRDROPS::pfnMap */
static int rtkldrRdr_Map( PKRDR pRdr, void **ppvBase, KU32 cSegments, PCKLDRSEG paSegments, KBOOL fFixed)
{
//PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
NOREF(pRdr); NOREF(ppvBase); NOREF(cSegments); NOREF(paSegments); NOREF(fFixed);
AssertFailed();
return -1;
}
/** @copydoc KLDRRDROPS::pfnRefresh */
static int rtkldrRdr_Refresh( PKRDR pRdr, void *pvBase, KU32 cSegments, PCKLDRSEG paSegments)
{
//PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
NOREF(pRdr); NOREF(pvBase); NOREF(cSegments); NOREF(paSegments);
AssertFailed();
return -1;
}
/** @copydoc KLDRRDROPS::pfnProtect */
static int rtkldrRdr_Protect( PKRDR pRdr, void *pvBase, KU32 cSegments, PCKLDRSEG paSegments, KBOOL fUnprotectOrProtect)
{
//PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
NOREF(pRdr); NOREF(pvBase); NOREF(cSegments); NOREF(paSegments); NOREF(fUnprotectOrProtect);
AssertFailed();
return -1;
}
/** @copydoc KLDRRDROPS::pfnUnmap */
static int rtkldrRdr_Unmap( PKRDR pRdr, void *pvBase, KU32 cSegments, PCKLDRSEG paSegments)
{
//PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
NOREF(pRdr); NOREF(pvBase); NOREF(cSegments); NOREF(paSegments);
AssertFailed();
return -1;
}
/** @copydoc KLDRRDROPS::pfnDone */
static void rtkldrRdr_Done( PKRDR pRdr)
{
NOREF(pRdr);
//PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
}
/**
* The file reader operations.
* We provide our own based on IPRT instead of using the kLdr ones.
*/
extern "C" const KRDROPS g_kLdrRdrFileOps;
extern "C" const KRDROPS g_kLdrRdrFileOps =
{
/* .pszName = */ "IPRT",
/* .pNext = */ NULL,
/* .pfnCreate = */ rtkldrRdr_Create,
/* .pfnDestroy = */ rtkldrRdr_Destroy,
/* .pfnRead = */ rtkldrRdr_Read,
/* .pfnAllMap = */ rtkldrRdr_AllMap,
/* .pfnAllUnmap = */ rtkldrRdr_AllUnmap,
/* .pfnSize = */ rtkldrRdr_Size,
/* .pfnTell = */ rtkldrRdr_Tell,
/* .pfnName = */ rtkldrRdr_Name,
/* .pfnNativeFH = */ rtkldrRdr_NativeFH,
/* .pfnPageSize = */ rtkldrRdr_PageSize,
/* .pfnMap = */ rtkldrRdr_Map,
/* .pfnRefresh = */ rtkldrRdr_Refresh,
/* .pfnProtect = */ rtkldrRdr_Protect,
/* .pfnUnmap = */ rtkldrRdr_Unmap,
/* .pfnDone = */ rtkldrRdr_Done,
/* .u32Dummy = */ 42
};
/** @copydoc RTLDROPS::pfnClose */
static DECLCALLBACK(int) rtkldr_Close(PRTLDRMODINTERNAL pMod)
{
PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod;
int rc = kLdrModClose(pModkLdr);
return rtkldrConvertError(rc);
}
/** @copydoc RTLDROPS::pfnDone */
static DECLCALLBACK(int) rtkldr_Done(PRTLDRMODINTERNAL pMod)
{
PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod;
int rc = kLdrModMostlyDone(pModkLdr);
return rtkldrConvertError(rc);
}
/** @copydoc FNKLDRMODENUMSYMS */
static int rtkldrEnumSymbolsWrapper(PKLDRMOD pMod, uint32_t iSymbol,
const char *pchSymbol, KSIZE cchSymbol, const char *pszVersion,
KLDRADDR uValue, uint32_t fKind, void *pvUser)
{
PRTLDRMODKLDRARGS pArgs = (PRTLDRMODKLDRARGS)pvUser;
NOREF(pMod); NOREF(pszVersion); NOREF(fKind);
/* If not zero terminated we'll have to use a temporary buffer. */
const char *pszSymbol = pchSymbol;
if (pchSymbol && pchSymbol[cchSymbol])
{
char *psz = (char *)alloca(cchSymbol + 1);
memcpy(psz, pchSymbol, cchSymbol);
psz[cchSymbol] = '\0';
pszSymbol = psz;
}
#if defined(RT_OS_OS2) || defined(RT_OS_DARWIN)
/* skip the underscore prefix. */
if (*pszSymbol == '_')
pszSymbol++;
#endif
int rc = pArgs->u.pfnEnumSyms(&pArgs->pMod->Core, pszSymbol, iSymbol, uValue, pArgs->pvUser);
if (RT_FAILURE(rc))
return rc; /* don't bother converting. */
return 0;
}
/** @copydoc RTLDROPS::pfnEnumSymbols */
static DECLCALLBACK(int) rtkldr_EnumSymbols(PRTLDRMODINTERNAL pMod, unsigned fFlags, const void *pvBits, RTUINTPTR BaseAddress,
PFNRTLDRENUMSYMS pfnCallback, void *pvUser)
{
PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod;
RTLDRMODKLDRARGS Args;
Args.pvUser = pvUser;
Args.u.pfnEnumSyms = pfnCallback;
Args.pMod = (PRTLDRMODKLDR)pMod;
Args.pvBits = pvBits;
Args.rc = VINF_SUCCESS;
int rc = kLdrModEnumSymbols(pModkLdr, pvBits, BaseAddress,
fFlags & RTLDR_ENUM_SYMBOL_FLAGS_ALL ? KLDRMOD_ENUM_SYMS_FLAGS_ALL : 0,
rtkldrEnumSymbolsWrapper, &Args);
if (Args.rc != VINF_SUCCESS)
rc = Args.rc;
else
rc = rtkldrConvertError(rc);
return rc;
}
/** @copydoc RTLDROPS::pfnGetImageSize */
static DECLCALLBACK(size_t) rtkldr_GetImageSize(PRTLDRMODINTERNAL pMod)
{
PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod;
return kLdrModSize(pModkLdr);
}
/** @copydoc FNKLDRMODGETIMPORT */
static int rtkldrGetImportWrapper(PKLDRMOD pMod, uint32_t iImport, uint32_t iSymbol, const char *pchSymbol, KSIZE cchSymbol,
const char *pszVersion, PKLDRADDR puValue, uint32_t *pfKind, void *pvUser)
{
PRTLDRMODKLDRARGS pArgs = (PRTLDRMODKLDRARGS)pvUser;
NOREF(pMod); NOREF(pszVersion); NOREF(pfKind);
/* If not zero terminated we'll have to use a temporary buffer. */
const char *pszSymbol = pchSymbol;
if (pchSymbol && pchSymbol[cchSymbol])
{
char *psz = (char *)alloca(cchSymbol + 1);
memcpy(psz, pchSymbol, cchSymbol);
psz[cchSymbol] = '\0';
pszSymbol = psz;
}
#if defined(RT_OS_OS2) || defined(RT_OS_DARWIN)
/* skip the underscore prefix. */
if (*pszSymbol == '_')
pszSymbol++;
#endif
/* get the import module name - TODO: cache this */
const char *pszModule = NULL;
if (iImport != NIL_KLDRMOD_IMPORT)
{
char *pszBuf = (char *)alloca(64);
int rc = kLdrModGetImport(pMod, pArgs->pvBits, iImport, pszBuf, 64);
if (rc)
return rc;
pszModule = pszBuf;
}
/* do the query */
RTUINTPTR Value;
int rc = pArgs->u.pfnGetImport(&pArgs->pMod->Core, pszModule, pszSymbol, pszSymbol ? ~0 : iSymbol, &Value, pArgs->pvUser);
if (RT_SUCCESS(rc))
{
*puValue = Value;
return 0;
}
return rtkldrConvertErrorFromIPRT(rc);
}
/** @copydoc RTLDROPS::pfnGetBits */
static DECLCALLBACK(int) rtkldr_GetBits(PRTLDRMODINTERNAL pMod, void *pvBits, RTUINTPTR BaseAddress,
PFNRTLDRIMPORT pfnGetImport, void *pvUser)
{
PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod;
RTLDRMODKLDRARGS Args;
Args.pvUser = pvUser;
Args.u.pfnGetImport = pfnGetImport;
Args.pMod = (PRTLDRMODKLDR)pMod;
Args.pvBits = pvBits;
Args.rc = VINF_SUCCESS;
int rc = kLdrModGetBits(pModkLdr, pvBits, BaseAddress, rtkldrGetImportWrapper, &Args);
if (Args.rc != VINF_SUCCESS)
rc = Args.rc;
else
rc = rtkldrConvertError(rc);
return rc;
}
/** @copydoc RTLDROPS::pfnRelocate */
static DECLCALLBACK(int) rtkldr_Relocate(PRTLDRMODINTERNAL pMod, void *pvBits, RTUINTPTR NewBaseAddress,
RTUINTPTR OldBaseAddress, PFNRTLDRIMPORT pfnGetImport, void *pvUser)
{
PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod;
RTLDRMODKLDRARGS Args;
Args.pvUser = pvUser;
Args.u.pfnGetImport = pfnGetImport;
Args.pMod = (PRTLDRMODKLDR)pMod;
Args.pvBits = pvBits;
Args.rc = VINF_SUCCESS;
int rc = kLdrModRelocateBits(pModkLdr, pvBits, NewBaseAddress, OldBaseAddress, rtkldrGetImportWrapper, &Args);
if (Args.rc != VINF_SUCCESS)
rc = Args.rc;
else
rc = rtkldrConvertError(rc);
return rc;
}
/** @copydoc RTLDROPS::pfnGetSymbolEx */
static DECLCALLBACK(int) rtkldr_GetSymbolEx(PRTLDRMODINTERNAL pMod, const void *pvBits, RTUINTPTR BaseAddress,
const char *pszSymbol, RTUINTPTR *pValue)
{
PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod;
KLDRADDR uValue;
#if defined(RT_OS_OS2) || defined(RT_OS_DARWIN)
/*
* Add underscore prefix.
*/
if (pszSymbol)
{
size_t cch = strlen(pszSymbol);
char *psz = (char *)alloca(cch + 2);
memcpy(psz + 1, pszSymbol, cch + 1);
*psz = '_';
pszSymbol = psz;
}
#endif
int rc = kLdrModQuerySymbol(pModkLdr, pvBits, BaseAddress,
NIL_KLDRMOD_SYM_ORDINAL, pszSymbol, strlen(pszSymbol), NULL,
NULL, NULL, &uValue, NULL);
if (!rc)
{
*pValue = uValue;
return VINF_SUCCESS;
}
return rtkldrConvertError(rc);
}
/** @copydoc FNKLDRENUMDBG */
static int rtkldrEnumDbgInfoWrapper(PKLDRMOD pMod, KU32 iDbgInfo, KLDRDBGINFOTYPE enmType, KI16 iMajorVer, KI16 iMinorVer,
const char *pszPartNm, KLDRFOFF offFile, KLDRADDR LinkAddress, KLDRSIZE cb,
const char *pszExtFile, void *pvUser)
{
PRTLDRMODKLDRARGS pArgs = (PRTLDRMODKLDRARGS)pvUser;
NOREF(pMod);
RTLDRDBGINFOTYPE enmMyType;
switch (enmType)
{
case KLDRDBGINFOTYPE_UNKNOWN: enmMyType = RTLDRDBGINFOTYPE_UNKNOWN; break;
case KLDRDBGINFOTYPE_STABS: enmMyType = RTLDRDBGINFOTYPE_STABS; break;
case KLDRDBGINFOTYPE_DWARF: enmMyType = RTLDRDBGINFOTYPE_DWARF; break;
case KLDRDBGINFOTYPE_CODEVIEW: enmMyType = RTLDRDBGINFOTYPE_CODEVIEW; break;
case KLDRDBGINFOTYPE_WATCOM: enmMyType = RTLDRDBGINFOTYPE_WATCOM; break;
case KLDRDBGINFOTYPE_HLL: enmMyType = RTLDRDBGINFOTYPE_HLL; break;
default:
AssertFailed();
enmMyType = RTLDRDBGINFOTYPE_UNKNOWN;
break;
}
int rc = pArgs->u.pfnEnumDbgInfo(&pArgs->pMod->Core, iDbgInfo, enmMyType, iMajorVer, iMinorVer, pszPartNm,
offFile, LinkAddress, cb, pszExtFile, pArgs->pvUser);
if (RT_FAILURE(rc))
return rc; /* don't bother converting. */
return 0;
}
/** @copydoc RTLDROPS::pfnEnumDbgInfo */
static DECLCALLBACK(int) rtkldr_EnumDbgInfo(PRTLDRMODINTERNAL pMod, const void *pvBits,
PFNRTLDRENUMDBG pfnCallback, void *pvUser)
{
PRTLDRMODKLDR pThis = (PRTLDRMODKLDR)pMod;
RTLDRMODKLDRARGS Args;
Args.pvUser = pvUser;
Args.u.pfnEnumDbgInfo = pfnCallback;
Args.pvBits = pvBits;
Args.pMod = pThis;
Args.rc = VINF_SUCCESS;
int rc = kLdrModEnumDbgInfo(pThis->pMod, pvBits, rtkldrEnumDbgInfoWrapper, &Args);
if (Args.rc != VINF_SUCCESS)
rc = Args.rc;
return rc;
}
/** @copydoc RTLDROPS::pfnEnumSegments. */
static DECLCALLBACK(int) rtkldr_EnumSegments(PRTLDRMODINTERNAL pMod, PFNRTLDRENUMSEGS pfnCallback, void *pvUser)
{
PRTLDRMODKLDR pThis = (PRTLDRMODKLDR)pMod;
uint32_t const cSegments = pThis->pMod->cSegments;
PCKLDRSEG paSegments = &pThis->pMod->aSegments[0];
for (uint32_t iSeg = 0; iSeg < cSegments; iSeg++)
{
RTLDRSEG Seg;
Seg.pchName = paSegments[iSeg].pchName;
Seg.cchName = paSegments[iSeg].cchName;
Seg.SelFlat = paSegments[iSeg].SelFlat;
Seg.Sel16bit = paSegments[iSeg].Sel16bit;
Seg.fFlags = paSegments[iSeg].fFlags;
AssertCompile(KLDRSEG_FLAG_16BIT == RTLDRSEG_FLAG_16BIT );
AssertCompile(KLDRSEG_FLAG_OS2_ALIAS16 == RTLDRSEG_FLAG_OS2_ALIAS16);
AssertCompile(KLDRSEG_FLAG_OS2_CONFORM == RTLDRSEG_FLAG_OS2_CONFORM);
AssertCompile(KLDRSEG_FLAG_OS2_IOPL == RTLDRSEG_FLAG_OS2_IOPL );
switch (paSegments[iSeg].enmProt)
{
default:
AssertMsgFailed(("%d\n", paSegments[iSeg].enmProt));
case KPROT_NOACCESS:
Seg.fProt = 0;
break;
case KPROT_READONLY: Seg.fProt = RTMEM_PROT_READ; break;
case KPROT_READWRITE: Seg.fProt = RTMEM_PROT_READ | RTMEM_PROT_WRITE; break;
case KPROT_WRITECOPY: Seg.fProt = RTMEM_PROT_WRITE; break;
case KPROT_EXECUTE: Seg.fProt = RTMEM_PROT_EXEC; break;
case KPROT_EXECUTE_READ: Seg.fProt = RTMEM_PROT_EXEC | RTMEM_PROT_READ; break;
case KPROT_EXECUTE_READWRITE: Seg.fProt = RTMEM_PROT_EXEC | RTMEM_PROT_READ | RTMEM_PROT_WRITE; break;
case KPROT_EXECUTE_WRITECOPY: Seg.fProt = RTMEM_PROT_EXEC | RTMEM_PROT_WRITE; break;
}
Seg.cb = paSegments[iSeg].cb;
Seg.Alignment = paSegments[iSeg].Alignment;
Seg.LinkAddress = paSegments[iSeg].LinkAddress;
Seg.offFile = paSegments[iSeg].offFile;
Seg.cbFile = paSegments[iSeg].cbFile;
Seg.RVA = paSegments[iSeg].RVA;
Seg.cbMapped = paSegments[iSeg].cbMapped;
int rc = pfnCallback(pMod, &Seg, pvUser);
if (rc != VINF_SUCCESS)
return rc;
}
return VINF_SUCCESS;
}
/** @copydoc RTLDROPS::pfnLinkAddressToSegOffset. */
static DECLCALLBACK(int) rtkldr_LinkAddressToSegOffset(PRTLDRMODINTERNAL pMod, RTLDRADDR LinkAddress,
uint32_t *piSeg, PRTLDRADDR poffSeg)
{
PRTLDRMODKLDR pThis = (PRTLDRMODKLDR)pMod;
uint32_t const cSegments = pThis->pMod->cSegments;
PCKLDRSEG paSegments = &pThis->pMod->aSegments[0];
for (uint32_t iSeg = 0; iSeg < cSegments; iSeg++)
{
KLDRADDR offSeg = LinkAddress - paSegments[iSeg].LinkAddress;
if ( offSeg < paSegments[iSeg].cbMapped
|| offSeg < paSegments[iSeg].cb)
{
*piSeg = iSeg;
*poffSeg = offSeg;
return VINF_SUCCESS;
}
}
return VERR_LDR_INVALID_LINK_ADDRESS;
}
/** @copydoc RTLDROPS::pfnLinkAddressToRva. */
static DECLCALLBACK(int) rtkldr_LinkAddressToRva(PRTLDRMODINTERNAL pMod, RTLDRADDR LinkAddress, PRTLDRADDR pRva)
{
PRTLDRMODKLDR pThis = (PRTLDRMODKLDR)pMod;
uint32_t const cSegments = pThis->pMod->cSegments;
PCKLDRSEG paSegments = &pThis->pMod->aSegments[0];
for (uint32_t iSeg = 0; iSeg < cSegments; iSeg++)
{
KLDRADDR offSeg = LinkAddress - paSegments[iSeg].LinkAddress;
if ( offSeg < paSegments[iSeg].cbMapped
|| offSeg < paSegments[iSeg].cb)
{
*pRva = paSegments[iSeg].RVA + offSeg;
return VINF_SUCCESS;
}
}
return VERR_LDR_INVALID_RVA;
}
/** @copydoc RTLDROPS::pfnSegOffsetToRva. */
static DECLCALLBACK(int) rtkldr_SegOffsetToRva(PRTLDRMODINTERNAL pMod, uint32_t iSeg, RTLDRADDR offSeg,
PRTLDRADDR pRva)
{
PRTLDRMODKLDR pThis = (PRTLDRMODKLDR)pMod;
if (iSeg >= pThis->pMod->cSegments)
return VERR_LDR_INVALID_SEG_OFFSET;
PCKLDRSEG const pSegment = &pThis->pMod->aSegments[iSeg];
if ( offSeg > pSegment->cbMapped
&& offSeg > pSegment->cb
&& ( pSegment->cbFile < 0
|| offSeg > (uint64_t)pSegment->cbFile))
return VERR_LDR_INVALID_SEG_OFFSET;
*pRva = pSegment->RVA + offSeg;
return VINF_SUCCESS;
}
/** @copydoc RTLDROPS::pfnRvaToSegOffset. */
static DECLCALLBACK(int) rtkldr_RvaToSegOffset(PRTLDRMODINTERNAL pMod, RTLDRADDR Rva,
uint32_t *piSeg, PRTLDRADDR poffSeg)
{
PRTLDRMODKLDR pThis = (PRTLDRMODKLDR)pMod;
uint32_t const cSegments = pThis->pMod->cSegments;
PCKLDRSEG paSegments = &pThis->pMod->aSegments[0];
for (uint32_t iSeg = 0; iSeg < cSegments; iSeg++)
{
KLDRADDR offSeg = Rva - paSegments[iSeg].RVA;
if ( offSeg < paSegments[iSeg].cbMapped
|| offSeg < paSegments[iSeg].cb)
{
*piSeg = iSeg;
*poffSeg = offSeg;
return VINF_SUCCESS;
}
}
return VERR_LDR_INVALID_RVA;
}
/**
* Operations for a kLdr module.
*/
static const RTLDROPS g_rtkldrOps =
{
"kLdr",
rtkldr_Close,
NULL,
rtkldr_Done,
rtkldr_EnumSymbols,
/* ext */
rtkldr_GetImageSize,
rtkldr_GetBits,
rtkldr_Relocate,
rtkldr_GetSymbolEx,
rtkldr_EnumDbgInfo,
rtkldr_EnumSegments,
rtkldr_LinkAddressToSegOffset,
rtkldr_LinkAddressToRva,
rtkldr_SegOffsetToRva,
rtkldr_RvaToSegOffset,
42
};
/**
* Open a image using kLdr.
*
* @returns iprt status code.
* @param pReader The loader reader instance which will provide the raw image bits.
* @param fFlags Reserved, MBZ.
* @param enmArch CPU architecture specifier for the image to be loaded.
* @param phLdrMod Where to store the handle.
*/
int rtldrkLdrOpen(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, PRTLDRMOD phLdrMod)
{
/* Convert enmArch to k-speak. */
KCPUARCH enmCpuArch;
switch (enmArch)
{
case RTLDRARCH_WHATEVER:
enmCpuArch = KCPUARCH_UNKNOWN;
break;
case RTLDRARCH_X86_32:
enmCpuArch = KCPUARCH_X86_32;
break;
case RTLDRARCH_AMD64:
enmCpuArch = KCPUARCH_AMD64;
break;
default:
return VERR_INVALID_PARAMETER;
}
/* Create a rtkldrRdr_ instance. */
PRTKLDRRDR pRdr = (PRTKLDRRDR)RTMemAllocZ(sizeof(*pRdr));
if (!pRdr)
return VERR_NO_MEMORY;
pRdr->Core.u32Magic = KRDR_MAGIC;
pRdr->Core.pOps = &g_kLdrRdrFileOps;
pRdr->pReader = pReader;
/* Try open it. */
PKLDRMOD pMod;
int krc = kLdrModOpenFromRdr(&pRdr->Core, fFlags, enmCpuArch, &pMod);
if (!krc)
{
/* Create a module wrapper for it. */
PRTLDRMODKLDR pNewMod = (PRTLDRMODKLDR)RTMemAllocZ(sizeof(*pNewMod));
if (pNewMod)
{
pNewMod->Core.u32Magic = RTLDRMOD_MAGIC;
pNewMod->Core.eState = LDR_STATE_OPENED;
pNewMod->Core.pOps = &g_rtkldrOps;
pNewMod->pMod = pMod;
*phLdrMod = &pNewMod->Core;
#ifdef LOG_ENABLED
Log(("rtldrkLdrOpen: '%s' (%s) %u segments\n",
pMod->pszName, pMod->pszFilename, pMod->cSegments));
for (unsigned iSeg = 0; iSeg < pMod->cSegments; iSeg++)
{
Log(("Segment #%-2u: RVA=%08llx cb=%08llx '%.*s'\n", iSeg,
pMod->aSegments[iSeg].RVA,
pMod->aSegments[iSeg].cb,
pMod->aSegments[iSeg].cchName,
pMod->aSegments[iSeg].pchName));
}
#endif
return VINF_SUCCESS;
}
kLdrModClose(pMod);
krc = KERR_NO_MEMORY;
}
return rtkldrConvertError(krc);
}
|
VirtualMonitor/VirtualMonitor
|
src/VBox/Runtime/common/ldr/ldrkStuff.cpp
|
C++
|
gpl-2.0
| 30,065
|
/*
* binkleyforce -- unix FTN mailer project
*
* Copyright (c) 1998-2000 Alexander Belkin, 2:5020/1398.11
*
* 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.
*
* $Id$
*/
#include "includes.h"
#include "confread.h"
#include "logger.h"
#include "util.h"
#include "outbound.h"
s_exttab outtab[] =
{
{ ".iut", TYPE_NETMAIL, FLAVOR_IMMED, ACTION_UNLINK },
{ ".cut", TYPE_NETMAIL, FLAVOR_CRASH, ACTION_UNLINK },
{ ".dut", TYPE_NETMAIL, FLAVOR_DIRECT, ACTION_UNLINK },
{ ".out", TYPE_NETMAIL, FLAVOR_NORMAL, ACTION_UNLINK },
{ ".hut", TYPE_NETMAIL, FLAVOR_HOLD, ACTION_UNLINK },
{ ".ikt", TYPE_NETMAIL, FLAVOR_IMMED, ACTION_UNLINK },
{ ".ckt", TYPE_NETMAIL, FLAVOR_CRASH, ACTION_UNLINK },
{ ".dkt", TYPE_NETMAIL, FLAVOR_DIRECT, ACTION_UNLINK },
{ ".pkt", TYPE_NETMAIL, FLAVOR_NORMAL, ACTION_UNLINK },
{ ".hkt", TYPE_NETMAIL, FLAVOR_HOLD, ACTION_UNLINK },
{ ".ilo", TYPE_FLOFILE, FLAVOR_IMMED, ACTION_NOTHING },
{ ".clo", TYPE_FLOFILE, FLAVOR_CRASH, ACTION_NOTHING },
{ ".dlo", TYPE_FLOFILE, FLAVOR_DIRECT, ACTION_NOTHING },
{ ".flo", TYPE_FLOFILE, FLAVOR_NORMAL, ACTION_NOTHING },
{ ".hlo", TYPE_FLOFILE, FLAVOR_HOLD, ACTION_NOTHING },
{ ".req", TYPE_REQUEST, FLAVOR_NONE, ACTION_NOTHING },
{ NULL, 0, 0, 0 }
};
s_exttab exttab[] =
{
{ ".tic", TYPE_TICFILE, FLAVOR_NORMAL, ACTION_TRUNCATE },
{ ".su?", TYPE_ARCMAIL, FLAVOR_NORMAL, ACTION_TRUNCATE },
{ ".mo?", TYPE_ARCMAIL, FLAVOR_NORMAL, ACTION_TRUNCATE },
{ ".tu?", TYPE_ARCMAIL, FLAVOR_NORMAL, ACTION_TRUNCATE },
{ ".we?", TYPE_ARCMAIL, FLAVOR_NORMAL, ACTION_TRUNCATE },
{ ".th?", TYPE_ARCMAIL, FLAVOR_NORMAL, ACTION_TRUNCATE },
{ ".fr?", TYPE_ARCMAIL, FLAVOR_NORMAL, ACTION_TRUNCATE },
{ ".sa?", TYPE_ARCMAIL, FLAVOR_NORMAL, ACTION_TRUNCATE },
{ NULL, 0, 0, 0 }
};
/*****************************************************************************
* Devide full outbound path on "root" directory, there other oubound
* directories created, and main outbound directory name
*
* Arguments:
* path pointer to the null-terminated outbound path string
* out_root pointer to the pointer for the resulting root directory
* out_main pointer to the pointer for the resulting main outbound
* name w/o path
*
* Return value:
* Zero on success (*out_root and *out_main must be freed)
*/
int out_get_root(const char *path, char **out_root, char **out_main)
{
char *p, *outb;
ASSERT(path != NULL && out_root != NULL && out_main != NULL);
*out_root = NULL;
*out_main = NULL;
outb = (char *)xstrcpy(path);
p = outb + strlen(outb) - 1;
if( *p == DIRSEPCHR )
*p = '\0';
/* Ohh.. where is no full path for outbound directory */
if( (p=strrchr(outb, DIRSEPCHR)) == NULL )
{
free(outb);
return -1;
}
*p = '\0';
*out_main = xstrcpy(p+1);
*out_root = xstrcat(outb, "/");
DEB((D_OUTBOUND, "out_getroot: out_root \"%s\", out_main \"%s\"",
*out_root, *out_main));
return 0;
}
/*****************************************************************************
* Scan Binkley Style Outbound directory, for each file for requested
* addresses call callback function
*
* Arguments:
* callback pointer to the callback information structure
* fa_list pointer to the requested addresses list
* addr current address (most time it is partially filled)
* path path for the outbound to scan
* point point number for the current outbound
*
* Return value:
* Zero on success
*/
static int out_scan_bso_dir(s_outbound_callback_data *callback,
const s_falist *fa_list, s_faddr *addr, const char *path, int point)
{
DIR *dir;
struct dirent *dirent;
char *p;
const s_falist *alst;
ASSERT(callback);
ASSERT(callback->dest);
ASSERT(addr && path);
DEB((D_OUTBOUND, "out_scan_bso_dir: BSO: scan dir \"%s\"", path));
if( (dir=opendir(path)) == NULL )
{
logerr("can't open outbound directory \"%s\"", path);
return(1);
}
while( (dirent=readdir(dir)) != NULL )
{
if( strlen(dirent->d_name) == 12 &&
strspn(dirent->d_name, "0123456789abcdefABCDEF") == 8 )
{
if((strncasecmp(dirent->d_name+8, ".PNT", 4) != 0) &&
( strncasecmp(dirent->d_name+8, ".REQ", 4) != 0) &&
( strncasecmp(dirent->d_name+10, "UT", 2) != 0) &&
( strncasecmp(dirent->d_name+10, "LO", 2) != 0) ) continue;
if( point == 0 && strncasecmp(dirent->d_name+8, ".PNT", 4) == 0 )
{
DEB((D_OUTBOUND, "scan_dir: BSO: found point directory \"%s\"",
dirent->d_name));
/*
* Congratulation, we found point's direcory
*/
sscanf(dirent->d_name, "%04x%04x", &addr->net, &addr->node);
for( alst = fa_list; alst; alst = alst->next )
if( addr->net == alst->addr.net
&& addr->node == alst->addr.node )
break;
if( alst || !fa_list )
{
p = string_concat(path, dirent->d_name, "/", NULL);
out_scan_bso_dir(callback, fa_list, addr, p, 1);
if( p ) { free(p); p = NULL; }
}
}
else
{
if( point )
{
sscanf(dirent->d_name, "%08x", &addr->point);
}
else
{
addr->point = 0;
sscanf(dirent->d_name, "%04x%04x", &addr->net, &addr->node);
}
/* Check, does we really need in this file? */
for( alst = fa_list; alst && ftn_addrcomp(*addr, alst->addr);
alst = alst->next );
if( alst || !fa_list )
{
callback->path = string_concat(path, dirent->d_name, NULL);
callback->addr = *addr;
callback->type = OUTB_TYPE_BSO;
callback->flavor = -1;
callback->callback(callback);
if( callback->path )
free(callback->path);
}
}
}
}
closedir(dir);
return(0);
}
static int out_scan_bso(s_outbound_callback_data *callback,
const s_falist *mailfor, const char *path)
{
DIR *dir;
struct dirent *dirent;
const s_falist *alst;
s_faddr addr;
char *newpath;
char *out_root = NULL; /* Root for outbound directories tree */
char *out_main = NULL; /* Main outbound directory name */
int len;
ASSERT(path);
if( out_get_root(path, &out_root, &out_main) )
return -1;
ASSERT(out_root && out_main);
if( (dir = opendir(out_root)) == NULL )
{
logerr("can't open outbound directory \"%s\"", out_root);
free(out_root); free(out_main);
return -1;
}
/* Scan outbound (only 4D) */
while( (dirent = readdir(dir)) )
{
memset(&addr, '\0', sizeof(s_faddr));
if( strcmp(dirent->d_name, out_main) == 0 )
{
/* Our main outbound */
s_cval_entry *cfptr = conf_first(cf_address);
if( cfptr )
addr.zone = cfptr->d.falist.addr.zone;
else
addr.zone = 666;
}
else if( strncmp(dirent->d_name, out_main, len=strlen(out_main)) == 0
&& dirent->d_name[len] == '.'
&& strspn(dirent->d_name+len+1,"0123456789abcdefABCDEF") == 3 )
{
/* Ooutbound with zone ext. (like /outbound.308/) */
sscanf(dirent->d_name+len+1, "%03x", &addr.zone);
}
if( addr.zone )
{
for( alst = mailfor;
alst && addr.zone != alst->addr.zone;
alst = alst->next );
if( alst || mailfor == NULL )
{
newpath = string_concat(out_root, dirent->d_name, "/", NULL);
out_scan_bso_dir(callback, mailfor, &addr, newpath, 0);
free(newpath);
}
}
}
closedir(dir);
free(out_root);
free(out_main);
return 0;
}
static int out_parse_name_lbox(s_faddr *addr, const char *filename)
{
s_faddr tmp;
ASSERT(addr && filename);
memset(&tmp, '\0', sizeof(s_faddr));
if( sscanf(filename, "%d.%d.%d.%d",
&tmp.zone, &tmp.net, &tmp.node, &tmp.point) == 4 )
{
*addr = tmp;
return 0;
}
return -1;
}
static int out_scan_fbox_dir(s_outbound_callback_data *callback,
const char *path, s_faddr addr, int flavor)
{
DIR *dir;
struct dirent *dirent;
if( (dir = opendir(path)) == NULL )
{
logerr("can't open filebox directory \"%s\"", path);
return -1;
}
while( (dirent = readdir(dir)) )
{
callback->path = string_concat(path, dirent->d_name, NULL);
if( is_regfile(callback->path) )
{
callback->addr = addr;
callback->type = OUTB_TYPE_FBOX;
callback->flavor = flavor;
callback->callback(callback);
}
free(callback->path);
callback->path = NULL;
}
closedir(dir);
return 0;
}
static int out_scan_lbox(s_outbound_callback_data *callback,
const s_falist *mailfor, const char *path)
{
DIR *dir;
struct dirent *dirent;
const s_falist *alst;
s_faddr addr;
char *newpath;
if( (dir = opendir(path)) == NULL )
{
logerr("can't open filebox directory \"%s\"", path);
return -1;
}
while( (dirent = readdir(dir)) )
{
if( out_parse_name_lbox(&addr, dirent->d_name) == 0 )
{
if( mailfor )
{
/* Scan only this fileboxes */
for( alst = mailfor;
alst && ftn_addrcomp(addr, alst->addr);
alst = alst->next );
if( alst )
{
newpath = string_concat(path, dirent->d_name, "/", NULL);
(void)out_scan_fbox_dir(callback, newpath, addr, FLAVOR_HOLD);
free(newpath);
}
}
else
{
/* Scan all fileboxes */
newpath = string_concat(path, dirent->d_name, "/", NULL);
(void)out_scan_fbox_dir(callback, newpath, addr, FLAVOR_HOLD);
free(newpath);
}
}
}
closedir(dir);
return 0;
}
/*****************************************************************************
* Parse file name from AmigaDos Style Outbound
*
* Arguments:
* name pointer to the null-terminated file name
* addr pointer to the memory where to store resulting address
*
* Return value:
* Zero on success
*/
int out_parse_name_aso(s_faddr *addr, const char *filename)
{
s_faddr tmp;
ASSERT(addr && filename);
memset(&tmp, '\0', sizeof(s_faddr));
if( sscanf(filename, "%d.%d.%d.%d.%*s", &tmp.zone,
&tmp.net, &tmp.node, &tmp.point) == 4 )
{
*addr = tmp;
return 0;
}
return -1;
}
static int out_scan_aso(s_outbound_callback_data *callback,
const s_falist *mailfor, const char *path)
{
DIR *dir;
struct dirent *dirent;
const s_falist *alst;
s_faddr addr = { FALSE, 0, 0, 0, 0, "" };
#ifdef DEBUG
char abuf[BF_MAXADDRSTR+1];
#endif
ASSERT(callback);
ASSERT(callback->dest);
ASSERT(path);
DEB((D_OUTBOUND, "out_scandir_aso: scan dir \"%s\"", path));
if( (dir = opendir(path)) == NULL )
{
logerr("can't open outbound directory \"%s\"", path);
return -1;
}
while( (dirent = readdir(dir)) )
{
memset(&addr, '\0', sizeof(s_faddr));
if( out_parse_name_aso(&addr, dirent->d_name) == 0 )
{
DEB((D_OUTBOUND, "out_scandir_aso: file \"%s\" for address %s",
dirent->d_name, ftn_addrstr(abuf, addr)));
for( alst = mailfor; alst && ftn_addrcomp(addr, alst->addr);
alst = alst->next );
if( alst || !mailfor )
{
callback->path = string_concat(path, dirent->d_name, NULL);
callback->addr = addr;
callback->type = OUTB_TYPE_ASO;
callback->flavor = -1;
callback->callback(callback);
if( callback->path )
free(callback->path);
}
}
}
closedir(dir);
return 0;
}
/* ------------------------------------------------------------------------- */
/* Scan outbound for addresses fa_list, use handler proc */
/* ------------------------------------------------------------------------- */
int out_scan(s_outbound_callback_data *callback, const s_falist *fa_list)
{
const s_falist *alst;
s_faddr addr = { FALSE, 0, 0, 0, 0, "" };
s_cval_entry *cfptr;
char *path;
ASSERT(callback);
ASSERT(callback->callback);
ASSERT(callback->dest);
/*
* 1st - try out 4D outbound
*/
path = conf_string(cf_outbound_directory);
if( path && *path )
(void)out_scan_bso(callback, fa_list, path);
/*
* 2th - Scan domain outbounds
*/
for( cfptr = conf_first(cf_domain); cfptr; cfptr = conf_next(cfptr) )
{
memset(&addr, '\0', sizeof(s_faddr));
for( alst = fa_list; alst; alst = alst->next )
{
if( cfptr->d.domain.zone == alst->addr.zone
|| alst->addr.zone == -1 )
{
addr.zone = cfptr->d.domain.zone;
out_scan_bso_dir(callback, fa_list, &addr,
cfptr->d.domain.path, 0);
break;
}
}
}
/*
* 3th - Scan AmigaDOS outbound
*/
path = conf_string(cf_amiga_outbound_directory);
if( path && *path )
(void)out_scan_aso(callback, fa_list, path);
/*
* 4th - Scan personal fileboxes
*/
if( fa_list )
{
/* Scan only listed fileboxes */
for( cfptr = conf_first(cf_filebox); cfptr; cfptr = conf_next(cfptr) )
{
for( alst = fa_list; alst; alst = alst->next )
{
if( !ftn_addrcomp(alst->addr, cfptr->d.filebox.addr) )
out_scan_fbox_dir(callback, cfptr->d.filebox.path,
cfptr->d.filebox.addr, cfptr->d.filebox.flavor);
}
}
}
else
{
/* Scan all fileboxes */
for( cfptr = conf_first(cf_filebox); cfptr; cfptr = conf_next(cfptr) )
out_scan_fbox_dir(callback, cfptr->d.filebox.path,
cfptr->d.filebox.addr, cfptr->d.filebox.flavor);
}
/*
* 5th - Scan "long" fileboxes
*/
path = conf_string(cf_filebox_directory);
if( path && *path )
(void)out_scan_lbox(callback, fa_list, path);
return(0);
}
|
zotrix/binkleyforce
|
source/bforce/outb_scan.c
|
C
|
gpl-2.0
| 13,258
|
/* Definitions for BSD-style memory management.
Copyright (C) 1994-2000, 2003, 2004, 2005 Free Software Foundation, Inc.
This file is part of the GNU C Library.
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. */
#ifndef _SYS_MMAN_H
#define _SYS_MMAN_H 1
#include <features.h>
#include <sys/types.h>
#define __need_size_t
#include <stddef.h>
#include <bits/mman.h>
/* Return value of `mmap' in case of an error. */
#define MAP_FAILED ((void *) -1)
__BEGIN_DECLS
/* Map addresses starting near ADDR and extending for LEN bytes. from
OFFSET into the file FD describes according to PROT and FLAGS. If ADDR
is nonzero, it is the desired mapping address. If the MAP_FIXED bit is
set in FLAGS, the mapping will be at ADDR exactly (which must be
page-aligned); otherwise the system chooses a convenient nearby address.
The return value is the actual mapping address chosen or MAP_FAILED
for errors (in which case `errno' is set). A successful `mmap' call
deallocates any previous mapping for the affected region. */
#ifndef __USE_FILE_OFFSET64
extern void *mmap (void *__addr, size_t __len, int __prot,
int __flags, int __fd, __off_t __offset) __THROW;
#else
# ifdef __REDIRECT_NTH
extern void * __REDIRECT_NTH (mmap,
(void *__addr, size_t __len, int __prot,
int __flags, int __fd, __off64_t __offset),
mmap64);
# else
# define mmap mmap64
# endif
#endif
#ifdef __USE_LARGEFILE64
extern void *mmap64 (void *__addr, size_t __len, int __prot,
int __flags, int __fd, __off64_t __offset) __THROW;
#endif
/* Deallocate any mapping for the region starting at ADDR and extending LEN
bytes. Returns 0 if successful, -1 for errors (and sets errno). */
extern int munmap (void *__addr, size_t __len) __THROW;
/* Change the memory protection of the region starting at ADDR and
extending LEN bytes to PROT. Returns 0 if successful, -1 for errors
(and sets errno). */
extern int mprotect (void *__addr, size_t __len, int __prot) __THROW;
/* Synchronize the region starting at ADDR and extending LEN bytes with the
file it maps. Filesystem operations on a file being mapped are
unpredictable before this is done. Flags are from the MS_* set.
This function is a cancellation point and therefore not marked with
__THROW. */
extern int msync (void *__addr, size_t __len, int __flags);
#ifdef __USE_BSD
/* Advise the system about particular usage patterns the program follows
for the region starting at ADDR and extending LEN bytes. */
extern int madvise (void *__addr, size_t __len, int __advice) __THROW;
#endif
#ifdef __USE_XOPEN2K
/* This is the POSIX name for this function. */
extern int posix_madvise (void *__addr, size_t __len, int __advice) __THROW;
#endif
/* Guarantee all whole pages mapped by the range [ADDR,ADDR+LEN) to
be memory resident. */
extern int mlock (__const void *__addr, size_t __len) __THROW;
/* Unlock whole pages previously mapped by the range [ADDR,ADDR+LEN). */
extern int munlock (__const void *__addr, size_t __len) __THROW;
/* Cause all currently mapped pages of the process to be memory resident
until unlocked by a call to the `munlockall', until the process exits,
or until the process calls `execve'. */
extern int mlockall (int __flags) __THROW;
/* All currently mapped pages of the process' address space become
unlocked. */
extern int munlockall (void) __THROW;
#ifdef __USE_MISC
/* mincore returns the memory residency status of the pages in the
current process's address space specified by [start, start + len).
The status is returned in a vector of bytes. The least significant
bit of each byte is 1 if the referenced page is in memory, otherwise
it is zero. */
extern int mincore (void *__start, size_t __len, unsigned char *__vec)
__THROW;
#endif
#ifdef __USE_GNU
/* Remap pages mapped by the range [ADDR,ADDR+OLD_LEN) to new length
NEW_LEN. If MREMAP_MAYMOVE is set in FLAGS the returned address
may differ from ADDR. If MREMAP_FIXED is set in FLAGS the function
takes another paramter which is a fixed address at which the block
resides after a successful call. */
extern void *mremap (void *__addr, size_t __old_len, size_t __new_len,
int __flags, ...) __THROW;
/* Remap arbitrary pages of a shared backing store within an existing
VMA. */
extern int remap_file_pages (void *__start, size_t __size, int __prot,
size_t __pgoff, int __flags) __THROW;
#endif
/* Open shared memory segment. */
extern int shm_open (__const char *__name, int __oflag, mode_t __mode);
/* Remove shared memory segment. */
extern int shm_unlink (__const char *__name);
__END_DECLS
#endif /* sys/mman.h */
|
www220/rt-thread-my
|
bsp/easyarm-imx283a/module/usr/include/sys/mman.h
|
C
|
gpl-2.0
| 5,407
|
<?php
/*
Twando.com Free PHP Twitter Application
http://www.twando.com/
*/
if (!$content_id) {
exit;
}
global $q1a, $pass_msg;
?>
<h2>Tweet Settings for <?=htmlentities($q1a['screen_name'])?></h2>
<?php
if ($q1a['id'] == "") {
echo mainFuncs::push_response(7);
} else {
//List all options here
?>
<div class="tab_row">
<div class="tab_main" id="tab1">
<a href="javascript:ajax_tweet_settings_tab('tab1');">Post Quick Tweet</a>
</div><div class="tab_main" id="tab2">
<a href="javascript:ajax_tweet_settings_tab('tab2');">Scheduled Tweets</a>
</div><div class="tab_main" id="tab3">
<a href="javascript:ajax_tweet_settings_tab('tab3');">Schedule a Tweet</a>
</div><div class="tab_main" id="tab3">
<a href="javascript:ajax_tweet_settings_tab('tab5');">Schedule a Tweet With Image</a>
</div><div class="tab_main" id="tab4">
<a href="javascript:ajax_tweet_settings_tab('tab4');">Bulk CSV Tweet Upload</a>
</div>
</div>
<br style="clear: both;" />
<div id="update_div">
</div>
<form>
<input type="hidden" name="twitter_id" id="twitter_id" value="<?=$q1a['id']?>" />
<input type="hidden" name="page_id" id="page_id" value="1" />
<input type="hidden" name="pass_msg" id="pass_msg" value="<?=$pass_msg?>" />
</form>
<form method="post" action="" name="deltweet" id="deltweet">
<input type="hidden" name="a" id="a" value="deletetweet" />
<input type="hidden" name="deltweet_id" id="deltweet_id" value="" />
</form>
<form method="post" action="" name="edittweet" id="edittweet">
<input type="hidden" name="a" id="a" value="edittweet" />
<input type="hidden" name="edittweet_id" id="edittweet_id" value="" />
<input type="hidden" name="everyday" id="everyday" value="" />
</form>
<?php
//End of valid id
}
?>
<br style="clear: both;" />
<a href="<?=BASE_LINK_URL?>">Return to main admin screen</a>
|
txt3rob/twando
|
inc/content/english/tweet_settings.php
|
PHP
|
gpl-2.0
| 1,874
|
#ifndef SUPERINT_H
#define SUPERINT_H
#include<string>
class superint
{
public:
superint();
superint(int);
superint(const char*);
superint(const std::string);
std::string strint;
std::string tostr(void);
int toint(void);
superint operator +(superint);
superint operator +(std::string);
superint operator +(const char*);
superint operator +(int);
superint operator -(superint);
superint operator -(std::string);
superint operator -(const char*);
superint operator -(int);
superint operator *(superint);
superint operator *(std::string);
superint operator *(const char*);
superint operator *(int);
superint operator /(superint);
superint operator /(std::string);
superint operator /(const char*);
superint operator /(int);
superint operator %(superint);
superint operator %(std::string);
superint operator %(const char*);
superint operator %(int);
void operator =(superint);
void operator =(std::string);
void operator =(const char*);
void operator =(int);
int operator <(superint);
int operator <=(superint);
int operator >(superint);
int operator >=(superint);
int operator ==(superint);
int operator !=(superint);
//友员
friend superint operator -(superint);
friend std::ostream& operator <<(std::ostream&,const superint&);
friend std::istream& operator >>(std::istream&,superint&);
private:
};
#endif // SUPERINT_H
|
Minerwwm/superint
|
superint.h
|
C
|
gpl-2.0
| 1,494
|
/*
expr.h
expression construction and manipulations
Copyright (C) 2001 Bill Currie <bill@taniwha.org>
Author: Bill Currie <bill@taniwha.org>
Date: 2001/06/15
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:
Free Software Foundation, Inc.
59 Temple Place - Suite 330
Boston, MA 02111-1307, USA
*/
#ifndef __expr_h
#define __expr_h
#include "QF/pr_comp.h"
/** \defgroup qfcc_expr Expressions
\ingroup qfcc
*/
//@{
/** Type of the exression node in an expression tree.
*/
typedef enum {
ex_error, ///< error expression. used to signal an error
ex_state, ///< state expression (::ex_state_t)
ex_bool, ///< short circuit boolean logic expression (::ex_bool_t)
ex_label, ///< goto/branch label (::ex_label_t)
ex_labelref, ///< label reference (::ex_labelref_t)
ex_block, ///< statement block expression (::ex_block_t)
ex_expr, ///< binary expression (::ex_expr_t)
ex_uexpr, ///< unary expression (::ex_expr_t)
ex_symbol, ///< non-temporary variable (::symbol_t)
ex_temp, ///< temporary variable (::ex_temp_t)
ex_nil, ///< umm, nil, null. nuff said (0 of any type)
ex_value, ///< constant value (::ex_value_t)
} expr_type;
/** Binary and unary expressions.
This is used for both binary and unary expressions. Unary expressions do
not use e2. The opcode is generally the parser token for the expression,
though special codes are used for non-math expressions.
*/
typedef struct ex_expr_s {
int op; ///< op-code of this expression
struct type_s *type; ///< the type of the result of this expression
struct expr_s *e1; ///< left side of binary, sole of unary
struct expr_s *e2; ///< right side of binary, null for unary
} ex_expr_t;
typedef struct ex_label_s {
struct ex_label_s *next;
struct reloc_s *refs; ///< relocations associated with this label
struct sblock_s *dest; ///< the location of this label if known
const char *name; ///< the name of this label
int used; ///< label is used as a target
struct daglabel_s *daglabel;
} ex_label_t;
typedef struct {
ex_label_t *label;
} ex_labelref_t;
typedef struct {
struct expr_s *head; ///< the first expression in the block
struct expr_s **tail; ///< last expression in the block, for appending
struct expr_s *result; ///< the result of this block if non-void
int is_call; ///< this block exprssion forms a function call
} ex_block_t;
typedef struct {
struct expr_s *expr;
struct operand_s *op; ///< The operand for the temporary variable, if
///< allocated
struct type_s *type; ///< The type of the temporary variable.
} ex_temp_t;
/** Pointer constant expression.
Represent a pointer to an absolute address in data space.
*/
typedef struct ex_pointer_s {
int val;
struct type_s *type;
struct def_s *def;
} ex_pointer_t;
typedef struct ex_func_s {
int val;
struct type_s *type;
} ex_func_t;
typedef struct {
int size;
struct expr_s *e[1];
} ex_list_t;
typedef struct {
ex_list_t *true_list;
ex_list_t *false_list;
struct expr_s *e;
} ex_bool_t;
/** State expression used for think function state-machines.
State expressions are of the form <code>[framenum, nextthink]</code>
(standard) or <code>[framenum, nextthink, timestep]</code> (QF extension)
and come before the opening brace of the function. If the state
expression is of the former form, then \c step will be null. Normally,
\c framenum and \c nextthink must be constant (though \c nextthink may
be a forward reference), but qfcc allows both \c framenum and
\c nextthink, and also \c timestep, to be variable.
\par From qcc:
States are special functions made for convenience. They
automatically set frame, nextthink (implicitly), and think (allowing
forward definitions).
\verbatim
void() name = [framenum, nextthink] {code};
\endverbatim
expands to:
\verbatim
void name ()
{
self.frame=framenum;
self.nextthink = time + 0.1;
self.think = nextthink
[code]
};
\endverbatim
Although the above expansion shows three expressions, a state expression
using constant values is just one instruction: either
<code>state framenum, nextthink</code> (standard) or
<code>state.f framenum, nextthink, timestep</code> (QF, optional).
*/
typedef struct {
struct expr_s *frame; ///< the frame to which to change in this state
struct expr_s *think; ///< think function for the next state
struct expr_s *step; ///< time step until the next state
} ex_state_t;
typedef struct ex_value_s {
struct ex_value_s *next;
struct daglabel_s *daglabel;///< dag label for this value
etype_t type;
union {
const char *string_val; ///< string constant
float float_val; ///< float constant
float vector_val[3]; ///< vector constant
int entity_val; ///< entity constant
ex_func_t func_val; ///< function constant
ex_pointer_t pointer; ///< pointer constant
float quaternion_val[4]; ///< quaternion constant
int integer_val; ///< integer constant
unsigned uinteger_val; ///< unsigned integer constant
short short_val; ///< short constant
} v;
} ex_value_t;
#define POINTER_VAL(p) (((p).def ? (p).def->offset : 0) + (p).val)
typedef struct expr_s {
struct expr_s *next; ///< the next expression in a block expression
expr_type type; ///< the type of the result of this expression
int line; ///< source line that generated this expression
string_t file; ///< source file that generated this expression
int printid; ///< avoid duplicate output when printing
unsigned paren:1; ///< the expression is enclosed in ()
unsigned rvalue:1; ///< the expression is on the right side of =
union {
ex_label_t label; ///< label expression
ex_labelref_t labelref; ///< label reference expression (&)
ex_state_t state; ///< state expression
ex_bool_t bool; ///< boolean logic expression
ex_block_t block; ///< statement block expression
ex_expr_t expr; ///< binary or unary expression
struct symbol_s *symbol; ///< symbol reference expression
ex_temp_t temp; ///< temporary variable expression
ex_value_t *value; ///< constant value
} e;
} expr_t;
extern struct type_s *ev_types[];
/** Report a type mismatch error.
\a e1 is used for reporting the file and line number of the error.
\param e1 Left side expression. Used for reporting the type.
\param e2 Right side expression. Used for reporting the type.
\param op The opcode of the expression.
\return \a e1 with its type set to ex_error.
*/
expr_t *type_mismatch (expr_t *e1, expr_t *e2, int op);
expr_t *param_mismatch (expr_t *e, int param, const char *fn,
struct type_s *t1, struct type_s *t2);
expr_t *cast_error (expr_t *e, struct type_s *t1, struct type_s *t2);
expr_t *test_error (expr_t *e, struct type_s *t);
extern expr_t *local_expr;
/** Get the type descriptor of the expression result.
\param e The expression from which to get the result type.
\return Pointer to the type description, or null if the expression
type (expr_t::type) is inappropriate.
*/
struct type_s *get_type (expr_t *e);
/** Get the basic type code of the expression result.
\param e The expression from which to get the result type.
\return Pointer to the type description, or ev_type_count if
get_type() returns null.
*/
etype_t extract_type (expr_t *e);
/** Create a new expression node.
Sets the source file and line number information. The expression node is
otherwise raw. This function is generally not used directly.
\return The new expression node.
*/
expr_t *new_expr (void);
/** Create a deep copy of an expression tree.
\param e The root of the expression tree to copy.
\return A new expression tree giving the same expression.
*/
expr_t *copy_expr (expr_t *e);
/** Create a new label name.
The label name is guaranteed to to the compilation. It is made up of the
name of the current function plus an incrementing number. The number is
not reset between functions.
\return The string representing the label name.
*/
const char *new_label_name (void);
/** Create a new label expression node.
The label name is set using new_label_name().
\return The new label expression (::ex_label_t) node.
*/
expr_t *new_label_expr (void);
/** Create a new label reference expression node.
Used for taking the address of a label (eg. jump tables).
The label's \a used field is incremented.
\return The new label reference expression (::ex_labelref_t) node.
*/
expr_t *new_label_ref (ex_label_t *label);
/** Create a new state expression node.
The label name is set using new_label_name(), and the label is linked
into the global list of labels for later resolution.
\param frame The expression giving the frame number.
\param think The expression giving the think function.
\param step The expression giving the time step value, or null if
no time-step is specified (standard form).
\return The new state expression (::ex_state_t) node.
*/
expr_t *new_state_expr (expr_t *frame, expr_t *think, expr_t *step);
expr_t *new_bool_expr (ex_list_t *true_list, ex_list_t *false_list, expr_t *e);
/** Create a new statement block expression node.
The returned block expression is empty. Use append_expr() to add
expressions to the block expression.
\return The new block expression (::ex_block_t) node.
*/
expr_t *new_block_expr (void);
/** Create a new binary expression node node.
If either \a e1 or \a e2 are error expressions, then that expression will
be returned instead of a new binary expression.
\param op The op-ccode of the binary expression.
\param e1 The left side of the binary expression.
\param e2 The right side of the binary expression.
\return The new binary expression node (::ex_expr_t) if neither
\a e1 nor \a e2 are error expressions, otherwise the
expression that is an error expression.
*/
expr_t *new_binary_expr (int op, expr_t *e1, expr_t *e2);
/** Create a new unary expression node node.
If \a e1 is an error expression, then it will be returned instead of a
new binary expression.
\param op The op-code of the unary expression.
\param e1 The "right" side of the expression.
\return The new unary expression node (::ex_expr_t) if \a e1
is not an error expression, otherwise \a e1.
*/
expr_t *new_unary_expr (int op, expr_t *e1);
/** Create a new symbol reference (non-temporary variable) expression node.
\return The new symbol reference expression node (::symbol_t).
*/
expr_t *new_symbol_expr (struct symbol_s *symbol);
/** Create a new temporary variable expression node.
Does not allocate a new temporary variable.
The ex_temp_t::users field will be 0.
\param type The type of the temporary variable.
\return The new temporary variable expression node (ex_temp_t).
*/
expr_t *new_temp_def_expr (struct type_s *type);
/** Create a new nil expression node.
nil represents 0 of any type.
\return The new nil expression node.
*/
expr_t *new_nil_expr (void);
/** Create a new value expression node.
\param value The value to put in the expression node.
\return The new value expression.
*/
expr_t *new_value_expr (ex_value_t *value);
/** Create a new symbol expression node from a name.
\param name The name for the symbol.
\return The new symbol expression.
*/
expr_t *new_name_expr (const char *name);
/** Create a new string constant expression node.
\param string_val The string constant being represented.
\return The new string constant expression node
(expr_t::e::string_val).
*/
expr_t *new_string_expr (const char *string_val);
const char *expr_string (expr_t *e);
/** Create a new float constant expression node.
\param float_val The float constant being represented.
\return The new float constant expression node
(expr_t::e::float_val).
*/
expr_t *new_float_expr (float float_val);
float expr_float (expr_t *e);
/** Create a new vector constant expression node.
\param vector_val The vector constant being represented.
\return The new vector constant expression node
(expr_t::e::vector_val).
*/
expr_t *new_vector_expr (const float *vector_val);
const float *expr_vector (expr_t *e);
/** Create a new entity constant expression node.
\param entity_val The entity constant being represented.
\return The new entity constant expression node
(expr_t::e::entity_val).
*/
expr_t *new_entity_expr (int entity_val);
/** Create a new field constant expression node.
\param field_val XXX
\param type The type of the field.
\param def
\return The new field constant expression node
(expr_t::e::field_val).
*/
expr_t *new_field_expr (int field_val, struct type_s *type, struct def_s *def);
/** Create a new function constant expression node.
\param func_val The function constant being represented.
\param type The type of the function
\return The new function constant expression node
(expr_t::e::func_val).
*/
expr_t *new_func_expr (int func_val, struct type_s *type);
/** Create a new pointer constant expression node.
\param val The pointer constant (address) being represented. XXX
\param type The type of the referenced value.
\param def
\return The new pointer constant expression node
(expr_t::e::pointer_val).
*/
expr_t *new_pointer_expr (int val, struct type_s *type, struct def_s *def);
/** Create a new quaternion constant expression node.
\param quaternion_val The quaternion constant being represented.
\return The new quaternion constant expression node
(expr_t::e::quaternion_val).
*/
expr_t *new_quaternion_expr (const float *quaternion_val);
const float *expr_quaternion (expr_t *e);
/** Create a new integer constant expression node.
\param integer_val The integer constant being represented.
\return The new integer constant expression node
(expr_t::e::integer_val).
*/
expr_t *new_integer_expr (int integer_val);
int expr_integer (expr_t *e);
/** Create a new integer constant expression node.
\param uinteger_val The integer constant being represented.
\return The new integer constant expression node
(expr_t::e::integer_val).
*/
expr_t *new_uinteger_expr (unsigned uinteger_val);
unsigned expr_uinteger (expr_t *e);
/** Create a new short constant expression node.
\param short_val The short constant being represented.
\return The new short constant expression node
(expr_t::e::short_val).
*/
expr_t *new_short_expr (short short_val);
short expr_short (expr_t *e);
/** Check of the expression refers to a constant value.
\param e The expression to check.
\return True if the expression is constant.
*/
int is_constant (expr_t *e);
/** Return a value expression representing the constant stored in \a e.
If \a e does not represent a constant, or \a e is already a value or
nil expression, then \a e is returned rather than a new expression.
\param e The expression from which to extract the value.
\return A new expression holding the value of \a e or \e itself.
*/
expr_t *constant_expr (expr_t *e);
/** Check if the op-code is a comparison.
\param op The op-code to check.
\return True if the op-code is a comparison operator.
*/
int is_compare (int op);
/** Check if the op-code is a math operator.
\param op The op-code to check.
\return True if the op-code is a math operator.
*/
int is_math_op (int op);
/** Check if the op-code is a logic operator.
\param op The op-code to check.
\return True if the op-code is a logic operator.
*/
int is_logic (int op);
int is_string_val (expr_t *e);
int is_float_val (expr_t *e);
int is_vector_val (expr_t *e);
int is_quaternion_val (expr_t *e);
int is_integer_val (expr_t *e);
int is_short_val (expr_t *e);
/** Create a reference to the global <code>.self</code> entity variable.
This is used for <code>\@self</code>.
\return A new expression referencing the <code>.self</code> def.
*/
expr_t *new_self_expr (void);
/** Create a reference to the <code>.this</code> entity field.
This is used for <code>\@this</code>.
\return A new expression referencing the <code>.this</code> def.
*/
expr_t *new_this_expr (void);
/** Create an expression of the correct type that references the return slot.
\param type The type of the reference to the return slot.
\return A new expression referencing the return slot.
*/
expr_t *new_ret_expr (struct type_s *type);
expr_t *new_alias_expr (struct type_s *type, expr_t *expr);
/** Create an expression of the correct type that references the specified
parameter slot.
\param type The type of the reference to the parameter slot.
\param num The index of the parameter (0-7).
\return A new expression referencing the parameter slot.
*/
expr_t *new_param_expr (struct type_s *type, int num);
/** Create an expression representing a block copy.
This is used for structure assignments.
\param e1 Destination of move.
\param e2 Source of move.
\param type type giving size of move.
\param indirect Move uses dereferenced pointers.
\return A new expression representing the move.
*/
expr_t *new_move_expr (expr_t *e1, expr_t *e2, struct type_s *type,
int indirect);
/** Convert a name to an expression of the appropriate type.
Converts the expression in-place. If the exprssion is not a name
expression (ex_name), no converision takes place.
\param e The expression to convert.
*/
void convert_name (expr_t *e);
expr_t *append_expr (expr_t *block, expr_t *e);
void print_expr (expr_t *e);
void dump_dot_expr (void *e, const char *filename);
void convert_int (expr_t *e);
void convert_short (expr_t *e);
void convert_short_int (expr_t *e);
void convert_nil (expr_t *e, struct type_s *t);
expr_t *test_expr (expr_t *e);
void backpatch (ex_list_t *list, expr_t *label);
expr_t *convert_bool (expr_t *e, int block);
expr_t *bool_expr (int op, expr_t *label, expr_t *e1, expr_t *e2);
expr_t *binary_expr (int op, expr_t *e1, expr_t *e2);
expr_t *asx_expr (int op, expr_t *e1, expr_t *e2);
expr_t *unary_expr (int op, expr_t *e);
expr_t *build_function_call (expr_t *fexpr, struct type_s *ftype,
expr_t *params);
expr_t *function_expr (expr_t *e1, expr_t *e2);
struct function_s;
expr_t *branch_expr (int op, expr_t *test, expr_t *label);
expr_t *goto_expr (expr_t *label);
expr_t *return_expr (struct function_s *f, expr_t *e);
expr_t *conditional_expr (expr_t *cond, expr_t *e1, expr_t *e2);
expr_t *incop_expr (int op, expr_t *e, int postop);
expr_t *array_expr (expr_t *array, expr_t *index);
expr_t *pointer_expr (expr_t *pointer);
expr_t *address_expr (expr_t *e1, expr_t *e2, struct type_s *t);
expr_t *build_if_statement (expr_t *test, expr_t *s1, expr_t *els, expr_t *s2);
expr_t *build_while_statement (expr_t *test, expr_t *statement,
expr_t *break_label, expr_t *continue_label);
expr_t *build_do_while_statement (expr_t *statement, expr_t *test,
expr_t *break_label, expr_t *continue_label);
expr_t *build_for_statement (expr_t *init, expr_t *test, expr_t *next,
expr_t *statement,
expr_t *break_label, expr_t *continue_label);
expr_t *build_state_expr (expr_t *frame, expr_t *think, expr_t *step);
expr_t *think_expr (struct symbol_s *think_sym);
expr_t *assign_expr (expr_t *e1, expr_t *e2);
expr_t *cast_expr (struct type_s *t, expr_t *e);
const char *get_op_string (int op);
struct keywordarg_s;
struct class_type_s;
expr_t *selector_expr (struct keywordarg_s *selector);
expr_t *protocol_expr (const char *protocol);
expr_t *encode_expr (struct type_s *type);
expr_t *super_expr (struct class_type_s *class_type);
expr_t *message_expr (expr_t *receiver, struct keywordarg_s *message);
expr_t *sizeof_expr (expr_t *expr, struct type_s *type);
expr_t *fold_constants (expr_t *e);
//@}
#endif//__expr_h
|
EIREXE/Quakeforge-gcw0
|
tools/qfcc/include/expr.h
|
C
|
gpl-2.0
| 20,337
|
/* $Id: pjsip.h 2394 2008-12-23 17:27:53Z bennylp $ */
/*
* Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
* 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 __PJSIP_H__
#define __PJSIP_H__
/* Base types. */
#include <pjsip/sip_types.h>
#include <pjsip/sip_errno.h>
/* Messaging and parsing. */
#include <pjsip/sip_uri.h>
#include <pjsip/sip_tel_uri.h>
#include <pjsip/sip_msg.h>
#include <pjsip/sip_parser.h>
/* Core */
#include <pjsip/sip_event.h>
#include <pjsip/sip_module.h>
#include <pjsip/sip_endpoint.h>
#include <pjsip/sip_util.h>
/* Transport layer */
#include <pjsip/sip_transport.h>
#include <pjsip/sip_transport_udp.h>
#include <pjsip/sip_transport_loop.h>
#include <pjsip/sip_transport_tcp.h>
#include <pjsip/sip_transport_tls.h>
#include <pjsip/sip_resolve.h>
/* Authentication. */
#include <pjsip/sip_auth.h>
#include <pjsip/sip_auth_aka.h>
/* Transaction layer. */
#include <pjsip/sip_transaction.h>
/* UA Layer. */
#include <pjsip/sip_ua_layer.h>
#include <pjsip/sip_dialog.h>
#endif /* __PJSIP_H__ */
|
kaaustubh/pjsip
|
pjsip/include/pjsip.h
|
C
|
gpl-2.0
| 1,782
|
/* BenchMARS88.h
*
* Copyright (C) 2005-2006 Jens Gutzeit <jens@jgutzeit.de>
*
* 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 COREWAR_BENCHMARKING_MARS88__H
#define COREWAR_BENCHMARKING_MARS88__H
u32_t *run_88(insn_t *core, warrior_t *warriors, u32_t coresize,
u32_t maxprocesses, u32_t maxcycles, u32_t mindistance,
u32_t numrounds, u32_t seed);
u32_t *p_run_88(insn_t *core, warrior_t *warriors, u32_t coresize,
u32_t maxprocesses, u32_t maxcycles, u32_t mindistance);
u32_t *mw_run_88(insn_t *core, u32_t numwarriors, warrior_t *warriors,
u32_t coresize, u32_t maxprocesses, u32_t maxcycles,
u32_t mindistance, u32_t numrounds, u32_t seed);
#endif /* COREWAR_BENCHMARKING_MARS88__H */
|
ProgVal/PyCorewar
|
src/BenchMARS88.h
|
C
|
gpl-2.0
| 1,416
|
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Contains the DB_common base class
*
* PHP versions 4 and 5
*
* LICENSE: This source file is subject to version 3.0 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_0.txt. If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to license@php.net so we can mail you a copy immediately.
*
* @category Database
* @package DB
* @author Stig Bakken <ssb@php.net>
* @author Tomas V.V. Cox <cox@idecnet.com>
* @author Daniel Convissor <danielc@php.net>
* @copyright 1997-2005 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version CVS: $Id$
* @link http://pear.php.net/package/DB
*/
/**
* Obtain the PEAR class so it can be extended from
*/
require_once dirname(__FILE__).'/../PEAR.php';
/**
* DB_common is the base class from which each database driver class extends
*
* All common methods are declared here. If a given DBMS driver contains
* a particular method, that method will overload the one here.
*
* @category Database
* @package DB
* @author Stig Bakken <ssb@php.net>
* @author Tomas V.V. Cox <cox@idecnet.com>
* @author Daniel Convissor <danielc@php.net>
* @copyright 1997-2005 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version Release: @package_version@
* @link http://pear.php.net/package/DB
*/
class DB_common extends PEAR
{
// {{{ properties
/**
* The current default fetch mode
* @var integer
*/
var $fetchmode = DB_FETCHMODE_ORDERED;
/**
* The name of the class into which results should be fetched when
* DB_FETCHMODE_OBJECT is in effect
*
* @var string
*/
var $fetchmode_object_class = 'stdClass';
/**
* Was a connection present when the object was serialized()?
* @var bool
* @see DB_common::__sleep(), DB_common::__wake()
*/
var $was_connected = null;
/**
* The most recently executed query
* @var string
*/
var $last_query = '';
/**
* Run-time configuration options
*
* The 'optimize' option has been deprecated. Use the 'portability'
* option instead.
*
* @var array
* @see DB_common::setOption()
*/
var $options = array(
'result_buffering' => 500,
'persistent' => false,
'ssl' => false,
'debug' => 0,
'seqname_format' => '%s_seq',
'autofree' => false,
'portability' => DB_PORTABILITY_NONE,
'optimize' => 'performance', // Deprecated. Use 'portability'.
);
/**
* The parameters from the most recently executed query
* @var array
* @since Property available since Release 1.7.0
*/
var $last_parameters = array();
/**
* The elements from each prepared statement
* @var array
*/
var $prepare_tokens = array();
/**
* The data types of the various elements in each prepared statement
* @var array
*/
var $prepare_types = array();
/**
* The prepared queries
* @var array
*/
var $prepared_queries = array();
// }}}
// {{{ DB_common
/**
* This constructor calls <kbd>$this->PEAR('DB_Error')</kbd>
*
* @return void
*/
function DB_common()
{
$this->PEAR('DB_Error');
}
// }}}
// {{{ __sleep()
/**
* Automatically indicates which properties should be saved
* when PHP's serialize() function is called
*
* @return array the array of properties names that should be saved
*/
function __sleep()
{
if ($this->connection) {
// Don't disconnect(), people use serialize() for many reasons
$this->was_connected = true;
} else {
$this->was_connected = false;
}
if (isset($this->autocommit)) {
return array('autocommit',
'dbsyntax',
'dsn',
'features',
'fetchmode',
'fetchmode_object_class',
'options',
'was_connected',
);
} else {
return array('dbsyntax',
'dsn',
'features',
'fetchmode',
'fetchmode_object_class',
'options',
'was_connected',
);
}
}
// }}}
// {{{ __wakeup()
/**
* Automatically reconnects to the database when PHP's unserialize()
* function is called
*
* The reconnection attempt is only performed if the object was connected
* at the time PHP's serialize() function was run.
*
* @return void
*/
function __wakeup()
{
if ($this->was_connected) {
$this->connect($this->dsn, $this->options);
}
}
// }}}
// {{{ __toString()
/**
* Automatic string conversion for PHP 5
*
* @return string a string describing the current PEAR DB object
*
* @since Method available since Release 1.7.0
*/
function __toString()
{
$info = strtolower(get_class($this));
$info .= ': (phptype=' . $this->phptype .
', dbsyntax=' . $this->dbsyntax .
')';
if ($this->connection) {
$info .= ' [connected]';
}
return $info;
}
// }}}
// {{{ toString()
/**
* DEPRECATED: String conversion method
*
* @return string a string describing the current PEAR DB object
*
* @deprecated Method deprecated in Release 1.7.0
*/
function toString()
{
return $this->__toString();
}
// }}}
// {{{ quoteString()
/**
* DEPRECATED: Quotes a string so it can be safely used within string
* delimiters in a query
*
* @param string $string the string to be quoted
*
* @return string the quoted string
*
* @see DB_common::quoteSmart(), DB_common::escapeSimple()
* @deprecated Method deprecated some time before Release 1.2
*/
function quoteString($string)
{
$string = $this->quote($string);
if ($string{0} == "'") {
return substr($string, 1, -1);
}
return $string;
}
// }}}
// {{{ quote()
/**
* DEPRECATED: Quotes a string so it can be safely used in a query
*
* @param string $string the string to quote
*
* @return string the quoted string or the string <samp>NULL</samp>
* if the value submitted is <kbd>null</kbd>.
*
* @see DB_common::quoteSmart(), DB_common::escapeSimple()
* @deprecated Deprecated in release 1.6.0
*/
function quote($string = null)
{
return ($string === null) ? 'NULL'
: "'" . str_replace("'", "''", $string) . "'";
}
// }}}
// {{{ quoteIdentifier()
/**
* Quotes a string so it can be safely used as a table or column name
*
* Delimiting style depends on which database driver is being used.
*
* NOTE: just because you CAN use delimited identifiers doesn't mean
* you SHOULD use them. In general, they end up causing way more
* problems than they solve.
*
* Portability is broken by using the following characters inside
* delimited identifiers:
* + backtick (<kbd>`</kbd>) -- due to MySQL
* + double quote (<kbd>"</kbd>) -- due to Oracle
* + brackets (<kbd>[</kbd> or <kbd>]</kbd>) -- due to Access
*
* Delimited identifiers are known to generally work correctly under
* the following drivers:
* + mssql
* + mysql
* + mysqli
* + oci8
* + odbc(access)
* + odbc(db2)
* + pgsql
* + sqlite
* + sybase (must execute <kbd>set quoted_identifier on</kbd> sometime
* prior to use)
*
* InterBase doesn't seem to be able to use delimited identifiers
* via PHP 4. They work fine under PHP 5.
*
* @param string $str the identifier name to be quoted
*
* @return string the quoted identifier
*
* @since Method available since Release 1.6.0
*/
function quoteIdentifier($str)
{
return '"' . str_replace('"', '""', $str) . '"';
}
// }}}
// {{{ quoteSmart()
/**
* Formats input so it can be safely used in a query
*
* The output depends on the PHP data type of input and the database
* type being used.
*
* @param mixed $in the data to be formatted
*
* @return mixed the formatted data. The format depends on the input's
* PHP type:
* <ul>
* <li>
* <kbd>input</kbd> -> <samp>returns</samp>
* </li>
* <li>
* <kbd>null</kbd> -> the string <samp>NULL</samp>
* </li>
* <li>
* <kbd>integer</kbd> or <kbd>double</kbd> -> the unquoted number
* </li>
* <li>
* <kbd>bool</kbd> -> output depends on the driver in use
* Most drivers return integers: <samp>1</samp> if
* <kbd>true</kbd> or <samp>0</samp> if
* <kbd>false</kbd>.
* Some return strings: <samp>TRUE</samp> if
* <kbd>true</kbd> or <samp>FALSE</samp> if
* <kbd>false</kbd>.
* Finally one returns strings: <samp>T</samp> if
* <kbd>true</kbd> or <samp>F</samp> if
* <kbd>false</kbd>. Here is a list of each DBMS,
* the values returned and the suggested column type:
* <ul>
* <li>
* <kbd>dbase</kbd> -> <samp>T/F</samp>
* (<kbd>Logical</kbd>)
* </li>
* <li>
* <kbd>fbase</kbd> -> <samp>TRUE/FALSE</samp>
* (<kbd>BOOLEAN</kbd>)
* </li>
* <li>
* <kbd>ibase</kbd> -> <samp>1/0</samp>
* (<kbd>SMALLINT</kbd>) [1]
* </li>
* <li>
* <kbd>ifx</kbd> -> <samp>1/0</samp>
* (<kbd>SMALLINT</kbd>) [1]
* </li>
* <li>
* <kbd>msql</kbd> -> <samp>1/0</samp>
* (<kbd>INTEGER</kbd>)
* </li>
* <li>
* <kbd>mssql</kbd> -> <samp>1/0</samp>
* (<kbd>BIT</kbd>)
* </li>
* <li>
* <kbd>mysql</kbd> -> <samp>1/0</samp>
* (<kbd>TINYINT(1)</kbd>)
* </li>
* <li>
* <kbd>mysqli</kbd> -> <samp>1/0</samp>
* (<kbd>TINYINT(1)</kbd>)
* </li>
* <li>
* <kbd>oci8</kbd> -> <samp>1/0</samp>
* (<kbd>NUMBER(1)</kbd>)
* </li>
* <li>
* <kbd>odbc</kbd> -> <samp>1/0</samp>
* (<kbd>SMALLINT</kbd>) [1]
* </li>
* <li>
* <kbd>pgsql</kbd> -> <samp>TRUE/FALSE</samp>
* (<kbd>BOOLEAN</kbd>)
* </li>
* <li>
* <kbd>sqlite</kbd> -> <samp>1/0</samp>
* (<kbd>INTEGER</kbd>)
* </li>
* <li>
* <kbd>sybase</kbd> -> <samp>1/0</samp>
* (<kbd>TINYINT(1)</kbd>)
* </li>
* </ul>
* [1] Accommodate the lowest common denominator because not all
* versions of have <kbd>BOOLEAN</kbd>.
* </li>
* <li>
* other (including strings and numeric strings) ->
* the data with single quotes escaped by preceeding
* single quotes, backslashes are escaped by preceeding
* backslashes, then the whole string is encapsulated
* between single quotes
* </li>
* </ul>
*
* @see DB_common::escapeSimple()
* @since Method available since Release 1.6.0
*/
function quoteSmart($in)
{
if (is_int($in) || is_double($in)) {
return $in;
} elseif (is_bool($in)) {
return $in ? 1 : 0;
} elseif (is_null($in)) {
return 'NULL';
} else {
return "'" . $this->escapeSimple($in) . "'";
}
}
// }}}
// {{{ escapeSimple()
/**
* Escapes a string according to the current DBMS's standards
*
* In SQLite, this makes things safe for inserts/updates, but may
* cause problems when performing text comparisons against columns
* containing binary data. See the
* {@link http://php.net/sqlite_escape_string PHP manual} for more info.
*
* @param string $str the string to be escaped
*
* @return string the escaped string
*
* @see DB_common::quoteSmart()
* @since Method available since Release 1.6.0
*/
function escapeSimple($str)
{
return str_replace("'", "''", $str);
}
// }}}
// {{{ provides()
/**
* Tells whether the present driver supports a given feature
*
* @param string $feature the feature you're curious about
*
* @return bool whether this driver supports $feature
*/
function provides($feature)
{
return $this->features[$feature];
}
// }}}
// {{{ setFetchMode()
/**
* Sets the fetch mode that should be used by default for query results
*
* @param integer $fetchmode DB_FETCHMODE_ORDERED, DB_FETCHMODE_ASSOC
* or DB_FETCHMODE_OBJECT
* @param string $object_class the class name of the object to be returned
* by the fetch methods when the
* DB_FETCHMODE_OBJECT mode is selected.
* If no class is specified by default a cast
* to object from the assoc array row will be
* done. There is also the posibility to use
* and extend the 'DB_row' class.
*
* @see DB_FETCHMODE_ORDERED, DB_FETCHMODE_ASSOC, DB_FETCHMODE_OBJECT
*/
function setFetchMode($fetchmode, $object_class = 'stdClass')
{
switch ($fetchmode) {
case DB_FETCHMODE_OBJECT:
$this->fetchmode_object_class = $object_class;
case DB_FETCHMODE_ORDERED:
case DB_FETCHMODE_ASSOC:
$this->fetchmode = $fetchmode;
break;
default:
return $this->raiseError('invalid fetchmode mode');
}
}
// }}}
// {{{ setOption()
/**
* Sets run-time configuration options for PEAR DB
*
* Options, their data types, default values and description:
* <ul>
* <li>
* <var>autofree</var> <kbd>boolean</kbd> = <samp>false</samp>
* <br />should results be freed automatically when there are no
* more rows?
* </li><li>
* <var>result_buffering</var> <kbd>integer</kbd> = <samp>500</samp>
* <br />how many rows of the result set should be buffered?
* <br />In mysql: mysql_unbuffered_query() is used instead of
* mysql_query() if this value is 0. (Release 1.7.0)
* <br />In oci8: this value is passed to ocisetprefetch().
* (Release 1.7.0)
* </li><li>
* <var>debug</var> <kbd>integer</kbd> = <samp>0</samp>
* <br />debug level
* </li><li>
* <var>persistent</var> <kbd>boolean</kbd> = <samp>false</samp>
* <br />should the connection be persistent?
* </li><li>
* <var>portability</var> <kbd>integer</kbd> = <samp>DB_PORTABILITY_NONE</samp>
* <br />portability mode constant (see below)
* </li><li>
* <var>seqname_format</var> <kbd>string</kbd> = <samp>%s_seq</samp>
* <br />the sprintf() format string used on sequence names. This
* format is applied to sequence names passed to
* createSequence(), nextID() and dropSequence().
* </li><li>
* <var>ssl</var> <kbd>boolean</kbd> = <samp>false</samp>
* <br />use ssl to connect?
* </li>
* </ul>
*
* -----------------------------------------
*
* PORTABILITY MODES
*
* These modes are bitwised, so they can be combined using <kbd>|</kbd>
* and removed using <kbd>^</kbd>. See the examples section below on how
* to do this.
*
* <samp>DB_PORTABILITY_NONE</samp>
* turn off all portability features
*
* This mode gets automatically turned on if the deprecated
* <var>optimize</var> option gets set to <samp>performance</samp>.
*
*
* <samp>DB_PORTABILITY_LOWERCASE</samp>
* convert names of tables and fields to lower case when using
* <kbd>get*()</kbd>, <kbd>fetch*()</kbd> and <kbd>tableInfo()</kbd>
*
* This mode gets automatically turned on in the following databases
* if the deprecated option <var>optimize</var> gets set to
* <samp>portability</samp>:
* + oci8
*
*
* <samp>DB_PORTABILITY_RTRIM</samp>
* right trim the data output by <kbd>get*()</kbd> <kbd>fetch*()</kbd>
*
*
* <samp>DB_PORTABILITY_DELETE_COUNT</samp>
* force reporting the number of rows deleted
*
* Some DBMS's don't count the number of rows deleted when performing
* simple <kbd>DELETE FROM tablename</kbd> queries. This portability
* mode tricks such DBMS's into telling the count by adding
* <samp>WHERE 1=1</samp> to the end of <kbd>DELETE</kbd> queries.
*
* This mode gets automatically turned on in the following databases
* if the deprecated option <var>optimize</var> gets set to
* <samp>portability</samp>:
* + fbsql
* + mysql
* + mysqli
* + sqlite
*
*
* <samp>DB_PORTABILITY_NUMROWS</samp>
* enable hack that makes <kbd>numRows()</kbd> work in Oracle
*
* This mode gets automatically turned on in the following databases
* if the deprecated option <var>optimize</var> gets set to
* <samp>portability</samp>:
* + oci8
*
*
* <samp>DB_PORTABILITY_ERRORS</samp>
* makes certain error messages in certain drivers compatible
* with those from other DBMS's
*
* + mysql, mysqli: change unique/primary key constraints
* DB_ERROR_ALREADY_EXISTS -> DB_ERROR_CONSTRAINT
*
* + odbc(access): MS's ODBC driver reports 'no such field' as code
* 07001, which means 'too few parameters.' When this option is on
* that code gets mapped to DB_ERROR_NOSUCHFIELD.
* DB_ERROR_MISMATCH -> DB_ERROR_NOSUCHFIELD
*
* <samp>DB_PORTABILITY_NULL_TO_EMPTY</samp>
* convert null values to empty strings in data output by get*() and
* fetch*(). Needed because Oracle considers empty strings to be null,
* while most other DBMS's know the difference between empty and null.
*
*
* <samp>DB_PORTABILITY_ALL</samp>
* turn on all portability features
*
* -----------------------------------------
*
* Example 1. Simple setOption() example
* <code>
* $db->setOption('autofree', true);
* </code>
*
* Example 2. Portability for lowercasing and trimming
* <code>
* $db->setOption('portability',
* DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_RTRIM);
* </code>
*
* Example 3. All portability options except trimming
* <code>
* $db->setOption('portability',
* DB_PORTABILITY_ALL ^ DB_PORTABILITY_RTRIM);
* </code>
*
* @param string $option option name
* @param mixed $value value for the option
*
* @return int DB_OK on success. A DB_Error object on failure.
*
* @see DB_common::$options
*/
function setOption($option, $value)
{
if (isset($this->options[$option])) {
$this->options[$option] = $value;
/*
* Backwards compatibility check for the deprecated 'optimize'
* option. Done here in case settings change after connecting.
*/
if ($option == 'optimize') {
if ($value == 'portability') {
switch ($this->phptype) {
case 'oci8':
$this->options['portability'] =
DB_PORTABILITY_LOWERCASE |
DB_PORTABILITY_NUMROWS;
break;
case 'fbsql':
case 'mysql':
case 'mysqli':
case 'sqlite':
$this->options['portability'] =
DB_PORTABILITY_DELETE_COUNT;
break;
}
} else {
$this->options['portability'] = DB_PORTABILITY_NONE;
}
}
return DB_OK;
}
return $this->raiseError("unknown option $option");
}
// }}}
// {{{ getOption()
/**
* Returns the value of an option
*
* @param string $option the option name you're curious about
*
* @return mixed the option's value
*/
function getOption($option)
{
if (isset($this->options[$option])) {
return $this->options[$option];
}
return $this->raiseError("unknown option $option");
}
// }}}
// {{{ prepare()
/**
* Prepares a query for multiple execution with execute()
*
* Creates a query that can be run multiple times. Each time it is run,
* the placeholders, if any, will be replaced by the contents of
* execute()'s $data argument.
*
* Three types of placeholders can be used:
* + <kbd>?</kbd> scalar value (i.e. strings, integers). The system
* will automatically quote and escape the data.
* + <kbd>!</kbd> value is inserted 'as is'
* + <kbd>&</kbd> requires a file name. The file's contents get
* inserted into the query (i.e. saving binary
* data in a db)
*
* Example 1.
* <code>
* $sth = $db->prepare('INSERT INTO tbl (a, b, c) VALUES (?, !, &)');
* $data = array(
* "John's text",
* "'it''s good'",
* 'filename.txt'
* );
* $res = $db->execute($sth, $data);
* </code>
*
* Use backslashes to escape placeholder characters if you don't want
* them to be interpreted as placeholders:
* <pre>
* "UPDATE foo SET col=? WHERE col='over \& under'"
* </pre>
*
* With some database backends, this is emulated.
*
* {@internal ibase and oci8 have their own prepare() methods.}}
*
* @param string $query the query to be prepared
*
* @return mixed DB statement resource on success. A DB_Error object
* on failure.
*
* @see DB_common::execute()
*/
function prepare($query)
{
$tokens = preg_split('/((?<!\\\)[&?!])/', $query, -1,
PREG_SPLIT_DELIM_CAPTURE);
$token = 0;
$types = array();
$newtokens = array();
foreach ($tokens as $val) {
switch ($val) {
case '?':
$types[$token++] = DB_PARAM_SCALAR;
break;
case '&':
$types[$token++] = DB_PARAM_OPAQUE;
break;
case '!':
$types[$token++] = DB_PARAM_MISC;
break;
default:
$newtokens[] = preg_replace('/\\\([&?!])/', "\\1", $val);
}
}
$this->prepare_tokens[] = &$newtokens;
end($this->prepare_tokens);
$k = key($this->prepare_tokens);
$this->prepare_types[$k] = $types;
$this->prepared_queries[$k] = implode(' ', $newtokens);
return $k;
}
// }}}
// {{{ autoPrepare()
/**
* Automaticaly generates an insert or update query and pass it to prepare()
*
* @param string $table the table name
* @param array $table_fields the array of field names
* @param int $mode a type of query to make:
* DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE
* @param string $where for update queries: the WHERE clause to
* append to the SQL statement. Don't
* include the "WHERE" keyword.
*
* @return resource the query handle
*
* @uses DB_common::prepare(), DB_common::buildManipSQL()
*/
function autoPrepare($table, $table_fields, $mode = DB_AUTOQUERY_INSERT,
$where = false)
{
$query = $this->buildManipSQL($table, $table_fields, $mode, $where);
if (DB::isError($query)) {
return $query;
}
return $this->prepare($query);
}
// }}}
// {{{ autoExecute()
/**
* Automaticaly generates an insert or update query and call prepare()
* and execute() with it
*
* @param string $table the table name
* @param array $fields_values the associative array where $key is a
* field name and $value its value
* @param int $mode a type of query to make:
* DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE
* @param string $where for update queries: the WHERE clause to
* append to the SQL statement. Don't
* include the "WHERE" keyword.
*
* @return mixed a new DB_result object for successful SELECT queries
* or DB_OK for successul data manipulation queries.
* A DB_Error object on failure.
*
* @uses DB_common::autoPrepare(), DB_common::execute()
*/
function autoExecute($table, $fields_values, $mode = DB_AUTOQUERY_INSERT,
$where = false)
{
$sth = $this->autoPrepare($table, array_keys($fields_values), $mode,
$where);
if (DB::isError($sth)) {
return $sth;
}
$ret =& $this->execute($sth, array_values($fields_values));
$this->freePrepared($sth);
return $ret;
}
// }}}
// {{{ buildManipSQL()
/**
* Produces an SQL query string for autoPrepare()
*
* Example:
* <pre>
* buildManipSQL('table_sql', array('field1', 'field2', 'field3'),
* DB_AUTOQUERY_INSERT);
* </pre>
*
* That returns
* <samp>
* INSERT INTO table_sql (field1,field2,field3) VALUES (?,?,?)
* </samp>
*
* NOTES:
* - This belongs more to a SQL Builder class, but this is a simple
* facility.
* - Be carefull! If you don't give a $where param with an UPDATE
* query, all the records of the table will be updated!
*
* @param string $table the table name
* @param array $table_fields the array of field names
* @param int $mode a type of query to make:
* DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE
* @param string $where for update queries: the WHERE clause to
* append to the SQL statement. Don't
* include the "WHERE" keyword.
*
* @return string the sql query for autoPrepare()
*/
function buildManipSQL($table, $table_fields, $mode, $where = false)
{
if (count($table_fields) == 0) {
return $this->raiseError(DB_ERROR_NEED_MORE_DATA);
}
$first = true;
switch ($mode) {
case DB_AUTOQUERY_INSERT:
$values = '';
$names = '';
foreach ($table_fields as $value) {
if ($first) {
$first = false;
} else {
$names .= ',';
$values .= ',';
}
$names .= $value;
$values .= '?';
}
return "INSERT INTO $table ($names) VALUES ($values)";
case DB_AUTOQUERY_UPDATE:
$set = '';
foreach ($table_fields as $value) {
if ($first) {
$first = false;
} else {
$set .= ',';
}
$set .= "$value = ?";
}
$sql = "UPDATE $table SET $set";
if ($where) {
$sql .= " WHERE $where";
}
return $sql;
default:
return $this->raiseError(DB_ERROR_SYNTAX);
}
}
// }}}
// {{{ execute()
/**
* Executes a DB statement prepared with prepare()
*
* Example 1.
* <code>
* $sth = $db->prepare('INSERT INTO tbl (a, b, c) VALUES (?, !, &)');
* $data = array(
* "John's text",
* "'it''s good'",
* 'filename.txt'
* );
* $res =& $db->execute($sth, $data);
* </code>
*
* @param resource $stmt a DB statement resource returned from prepare()
* @param mixed $data array, string or numeric data to be used in
* execution of the statement. Quantity of items
* passed must match quantity of placeholders in
* query: meaning 1 placeholder for non-array
* parameters or 1 placeholder per array element.
*
* @return mixed a new DB_result object for successful SELECT queries
* or DB_OK for successul data manipulation queries.
* A DB_Error object on failure.
*
* {@internal ibase and oci8 have their own execute() methods.}}
*
* @see DB_common::prepare()
*/
function &execute($stmt, $data = array())
{
$realquery = $this->executeEmulateQuery($stmt, $data);
if (DB::isError($realquery)) {
return $realquery;
}
$result = $this->simpleQuery($realquery);
if ($result === DB_OK || DB::isError($result)) {
return $result;
} else {
$tmp =& new DB_result($this, $result);
return $tmp;
}
}
// }}}
// {{{ executeEmulateQuery()
/**
* Emulates executing prepared statements if the DBMS not support them
*
* @param resource $stmt a DB statement resource returned from execute()
* @param mixed $data array, string or numeric data to be used in
* execution of the statement. Quantity of items
* passed must match quantity of placeholders in
* query: meaning 1 placeholder for non-array
* parameters or 1 placeholder per array element.
*
* @return mixed a string containing the real query run when emulating
* prepare/execute. A DB_Error object on failure.
*
* @access protected
* @see DB_common::execute()
*/
function executeEmulateQuery($stmt, $data = array())
{
$stmt = (int)$stmt;
$data = (array)$data;
$this->last_parameters = $data;
if (count($this->prepare_types[$stmt]) != count($data)) {
$this->last_query = $this->prepared_queries[$stmt];
return $this->raiseError(DB_ERROR_MISMATCH);
}
$realquery = $this->prepare_tokens[$stmt][0];
$i = 0;
foreach ($data as $value) {
if ($this->prepare_types[$stmt][$i] == DB_PARAM_SCALAR) {
$realquery .= $this->quoteSmart($value);
} elseif ($this->prepare_types[$stmt][$i] == DB_PARAM_OPAQUE) {
$fp = @fopen($value, 'rb');
if (!$fp) {
return $this->raiseError(DB_ERROR_ACCESS_VIOLATION);
}
$realquery .= $this->quoteSmart(fread($fp, filesize($value)));
fclose($fp);
} else {
$realquery .= $value;
}
$realquery .= $this->prepare_tokens[$stmt][++$i];
}
return $realquery;
}
// }}}
// {{{ executeMultiple()
/**
* Performs several execute() calls on the same statement handle
*
* $data must be an array indexed numerically
* from 0, one execute call is done for every "row" in the array.
*
* If an error occurs during execute(), executeMultiple() does not
* execute the unfinished rows, but rather returns that error.
*
* @param resource $stmt query handle from prepare()
* @param array $data numeric array containing the
* data to insert into the query
*
* @return int DB_OK on success. A DB_Error object on failure.
*
* @see DB_common::prepare(), DB_common::execute()
*/
function executeMultiple($stmt, $data)
{
foreach ($data as $value) {
$res =& $this->execute($stmt, $value);
if (DB::isError($res)) {
return $res;
}
}
return DB_OK;
}
// }}}
// {{{ freePrepared()
/**
* Frees the internal resources associated with a prepared query
*
* @param resource $stmt the prepared statement's PHP resource
* @param bool $free_resource should the PHP resource be freed too?
* Use false if you need to get data
* from the result set later.
*
* @return bool TRUE on success, FALSE if $result is invalid
*
* @see DB_common::prepare()
*/
function freePrepared($stmt, $free_resource = true)
{
$stmt = (int)$stmt;
if (isset($this->prepare_tokens[$stmt])) {
unset($this->prepare_tokens[$stmt]);
unset($this->prepare_types[$stmt]);
unset($this->prepared_queries[$stmt]);
return true;
}
return false;
}
// }}}
// {{{ modifyQuery()
/**
* Changes a query string for various DBMS specific reasons
*
* It is defined here to ensure all drivers have this method available.
*
* @param string $query the query string to modify
*
* @return string the modified query string
*
* @access protected
* @see DB_mysql::modifyQuery(), DB_oci8::modifyQuery(),
* DB_sqlite::modifyQuery()
*/
function modifyQuery($query)
{
return $query;
}
// }}}
// {{{ modifyLimitQuery()
/**
* Adds LIMIT clauses to a query string according to current DBMS standards
*
* It is defined here to assure that all implementations
* have this method defined.
*
* @param string $query the query to modify
* @param int $from the row to start to fetching (0 = the first row)
* @param int $count the numbers of rows to fetch
* @param mixed $params array, string or numeric data to be used in
* execution of the statement. Quantity of items
* passed must match quantity of placeholders in
* query: meaning 1 placeholder for non-array
* parameters or 1 placeholder per array element.
*
* @return string the query string with LIMIT clauses added
*
* @access protected
*/
function modifyLimitQuery($query, $from, $count, $params = array())
{
return $query;
}
// }}}
// {{{ query()
/**
* Sends a query to the database server
*
* The query string can be either a normal statement to be sent directly
* to the server OR if <var>$params</var> are passed the query can have
* placeholders and it will be passed through prepare() and execute().
*
* @param string $query the SQL query or the statement to prepare
* @param mixed $params array, string or numeric data to be used in
* execution of the statement. Quantity of items
* passed must match quantity of placeholders in
* query: meaning 1 placeholder for non-array
* parameters or 1 placeholder per array element.
*
* @return mixed a new DB_result object for successful SELECT queries
* or DB_OK for successul data manipulation queries.
* A DB_Error object on failure.
*
* @see DB_result, DB_common::prepare(), DB_common::execute()
*/
function &query($query, $params = array())
{
if (sizeof($params) > 0) {
$sth = $this->prepare($query);
if (DB::isError($sth)) {
return $sth;
}
$ret =& $this->execute($sth, $params);
$this->freePrepared($sth, false);
return $ret;
} else {
$this->last_parameters = array();
$result = $this->simpleQuery($query);
if ($result === DB_OK || DB::isError($result)) {
return $result;
} else {
$tmp =& new DB_result($this, $result);
return $tmp;
}
}
}
// }}}
// {{{ limitQuery()
/**
* Generates and executes a LIMIT query
*
* @param string $query the query
* @param intr $from the row to start to fetching (0 = the first row)
* @param int $count the numbers of rows to fetch
* @param mixed $params array, string or numeric data to be used in
* execution of the statement. Quantity of items
* passed must match quantity of placeholders in
* query: meaning 1 placeholder for non-array
* parameters or 1 placeholder per array element.
*
* @return mixed a new DB_result object for successful SELECT queries
* or DB_OK for successul data manipulation queries.
* A DB_Error object on failure.
*/
function &limitQuery($query, $from, $count, $params = array())
{
$query = $this->modifyLimitQuery($query, $from, $count, $params);
if (DB::isError($query)){
return $query;
}
$result =& $this->query($query, $params);
if (is_a($result, 'DB_result')) {
$result->setOption('limit_from', $from);
$result->setOption('limit_count', $count);
}
return $result;
}
// }}}
// {{{ getOne()
/**
* Fetches the first column of the first row from a query result
*
* Takes care of doing the query and freeing the results when finished.
*
* @param string $query the SQL query
* @param mixed $params array, string or numeric data to be used in
* execution of the statement. Quantity of items
* passed must match quantity of placeholders in
* query: meaning 1 placeholder for non-array
* parameters or 1 placeholder per array element.
*
* @return mixed the returned value of the query.
* A DB_Error object on failure.
*/
function &getOne($query, $params = array())
{
$params = (array)$params;
// modifyLimitQuery() would be nice here, but it causes BC issues
if (sizeof($params) > 0) {
$sth = $this->prepare($query);
if (DB::isError($sth)) {
return $sth;
}
$res =& $this->execute($sth, $params);
$this->freePrepared($sth);
} else {
$res =& $this->query($query);
}
if (DB::isError($res)) {
return $res;
}
$err = $res->fetchInto($row, DB_FETCHMODE_ORDERED);
$res->free();
if ($err !== DB_OK) {
return $err;
}
return $row[0];
}
// }}}
// {{{ getRow()
/**
* Fetches the first row of data returned from a query result
*
* Takes care of doing the query and freeing the results when finished.
*
* @param string $query the SQL query
* @param mixed $params array, string or numeric data to be used in
* execution of the statement. Quantity of items
* passed must match quantity of placeholders in
* query: meaning 1 placeholder for non-array
* parameters or 1 placeholder per array element.
* @param int $fetchmode the fetch mode to use
*
* @return array the first row of results as an array.
* A DB_Error object on failure.
*/
function &getRow($query, $params = array(),
$fetchmode = DB_FETCHMODE_DEFAULT)
{
// compat check, the params and fetchmode parameters used to
// have the opposite order
if (!is_array($params)) {
if (is_array($fetchmode)) {
if ($params === null) {
$tmp = DB_FETCHMODE_DEFAULT;
} else {
$tmp = $params;
}
$params = $fetchmode;
$fetchmode = $tmp;
} elseif ($params !== null) {
$fetchmode = $params;
$params = array();
}
}
// modifyLimitQuery() would be nice here, but it causes BC issues
if (sizeof($params) > 0) {
$sth = $this->prepare($query);
if (DB::isError($sth)) {
return $sth;
}
$res =& $this->execute($sth, $params);
$this->freePrepared($sth);
} else {
$res =& $this->query($query);
}
if (DB::isError($res)) {
return $res;
}
$err = $res->fetchInto($row, $fetchmode);
$res->free();
if ($err !== DB_OK) {
return $err;
}
return $row;
}
// }}}
// {{{ getCol()
/**
* Fetches a single column from a query result and returns it as an
* indexed array
*
* @param string $query the SQL query
* @param mixed $col which column to return (integer [column number,
* starting at 0] or string [column name])
* @param mixed $params array, string or numeric data to be used in
* execution of the statement. Quantity of items
* passed must match quantity of placeholders in
* query: meaning 1 placeholder for non-array
* parameters or 1 placeholder per array element.
*
* @return array the results as an array. A DB_Error object on failure.
*
* @see DB_common::query()
*/
function &getCol($query, $col = 0, $params = array())
{
$params = (array)$params;
if (sizeof($params) > 0) {
$sth = $this->prepare($query);
if (DB::isError($sth)) {
return $sth;
}
$res =& $this->execute($sth, $params);
$this->freePrepared($sth);
} else {
$res =& $this->query($query);
}
if (DB::isError($res)) {
return $res;
}
$fetchmode = is_int($col) ? DB_FETCHMODE_ORDERED : DB_FETCHMODE_ASSOC;
if (!is_array($row = $res->fetchRow($fetchmode))) {
$ret = array();
} else {
if (!array_key_exists($col, $row)) {
$ret =& $this->raiseError(DB_ERROR_NOSUCHFIELD);
} else {
$ret = array($row[$col]);
while (is_array($row = $res->fetchRow($fetchmode))) {
$ret[] = $row[$col];
}
}
}
$res->free();
if (DB::isError($row)) {
$ret = $row;
}
return $ret;
}
// }}}
// {{{ getAssoc()
/**
* Fetches an entire query result and returns it as an
* associative array using the first column as the key
*
* If the result set contains more than two columns, the value
* will be an array of the values from column 2-n. If the result
* set contains only two columns, the returned value will be a
* scalar with the value of the second column (unless forced to an
* array with the $force_array parameter). A DB error code is
* returned on errors. If the result set contains fewer than two
* columns, a DB_ERROR_TRUNCATED error is returned.
*
* For example, if the table "mytable" contains:
*
* <pre>
* ID TEXT DATE
* --------------------------------
* 1 'one' 944679408
* 2 'two' 944679408
* 3 'three' 944679408
* </pre>
*
* Then the call getAssoc('SELECT id,text FROM mytable') returns:
* <pre>
* array(
* '1' => 'one',
* '2' => 'two',
* '3' => 'three',
* )
* </pre>
*
* ...while the call getAssoc('SELECT id,text,date FROM mytable') returns:
* <pre>
* array(
* '1' => array('one', '944679408'),
* '2' => array('two', '944679408'),
* '3' => array('three', '944679408')
* )
* </pre>
*
* If the more than one row occurs with the same value in the
* first column, the last row overwrites all previous ones by
* default. Use the $group parameter if you don't want to
* overwrite like this. Example:
*
* <pre>
* getAssoc('SELECT category,id,name FROM mytable', false, null,
* DB_FETCHMODE_ASSOC, true) returns:
*
* array(
* '1' => array(array('id' => '4', 'name' => 'number four'),
* array('id' => '6', 'name' => 'number six')
* ),
* '9' => array(array('id' => '4', 'name' => 'number four'),
* array('id' => '6', 'name' => 'number six')
* )
* )
* </pre>
*
* Keep in mind that database functions in PHP usually return string
* values for results regardless of the database's internal type.
*
* @param string $query the SQL query
* @param bool $force_array used only when the query returns
* exactly two columns. If true, the values
* of the returned array will be one-element
* arrays instead of scalars.
* @param mixed $params array, string or numeric data to be used in
* execution of the statement. Quantity of
* items passed must match quantity of
* placeholders in query: meaning 1
* placeholder for non-array parameters or
* 1 placeholder per array element.
* @param int $fetchmode the fetch mode to use
* @param bool $group if true, the values of the returned array
* is wrapped in another array. If the same
* key value (in the first column) repeats
* itself, the values will be appended to
* this array instead of overwriting the
* existing values.
*
* @return array the associative array containing the query results.
* A DB_Error object on failure.
*/
function &getAssoc($query, $force_array = false, $params = array(),
$fetchmode = DB_FETCHMODE_DEFAULT, $group = false)
{
$params = (array)$params;
if (sizeof($params) > 0) {
$sth = $this->prepare($query);
if (DB::isError($sth)) {
return $sth;
}
$res =& $this->execute($sth, $params);
$this->freePrepared($sth);
} else {
$res =& $this->query($query);
}
if (DB::isError($res)) {
return $res;
}
if ($fetchmode == DB_FETCHMODE_DEFAULT) {
$fetchmode = $this->fetchmode;
}
$cols = $res->numCols();
if ($cols < 2) {
$tmp =& $this->raiseError(DB_ERROR_TRUNCATED);
return $tmp;
}
$results = array();
if ($cols > 2 || $force_array) {
// return array values
// XXX this part can be optimized
if ($fetchmode == DB_FETCHMODE_ASSOC) {
while (is_array($row = $res->fetchRow(DB_FETCHMODE_ASSOC))) {
reset($row);
$key = current($row);
unset($row[key($row)]);
if ($group) {
$results[$key][] = $row;
} else {
$results[$key] = $row;
}
}
} elseif ($fetchmode == DB_FETCHMODE_OBJECT) {
while ($row = $res->fetchRow(DB_FETCHMODE_OBJECT)) {
$arr = get_object_vars($row);
$key = current($arr);
if ($group) {
$results[$key][] = $row;
} else {
$results[$key] = $row;
}
}
} else {
while (is_array($row = $res->fetchRow(DB_FETCHMODE_ORDERED))) {
// we shift away the first element to get
// indices running from 0 again
$key = array_shift($row);
if ($group) {
$results[$key][] = $row;
} else {
$results[$key] = $row;
}
}
}
if (DB::isError($row)) {
$results = $row;
}
} else {
// return scalar values
while (is_array($row = $res->fetchRow(DB_FETCHMODE_ORDERED))) {
if ($group) {
$results[$row[0]][] = $row[1];
} else {
$results[$row[0]] = $row[1];
}
}
if (DB::isError($row)) {
$results = $row;
}
}
$res->free();
return $results;
}
// }}}
// {{{ getAll()
/**
* Fetches all of the rows from a query result
*
* @param string $query the SQL query
* @param mixed $params array, string or numeric data to be used in
* execution of the statement. Quantity of
* items passed must match quantity of
* placeholders in query: meaning 1
* placeholder for non-array parameters or
* 1 placeholder per array element.
* @param int $fetchmode the fetch mode to use:
* + DB_FETCHMODE_ORDERED
* + DB_FETCHMODE_ASSOC
* + DB_FETCHMODE_ORDERED | DB_FETCHMODE_FLIPPED
* + DB_FETCHMODE_ASSOC | DB_FETCHMODE_FLIPPED
*
* @return array the nested array. A DB_Error object on failure.
*/
function &getAll($query, $params = array(),
$fetchmode = DB_FETCHMODE_DEFAULT)
{
// compat check, the params and fetchmode parameters used to
// have the opposite order
if (!is_array($params)) {
if (is_array($fetchmode)) {
if ($params === null) {
$tmp = DB_FETCHMODE_DEFAULT;
} else {
$tmp = $params;
}
$params = $fetchmode;
$fetchmode = $tmp;
} elseif ($params !== null) {
$fetchmode = $params;
$params = array();
}
}
if (sizeof($params) > 0) {
$sth = $this->prepare($query);
if (DB::isError($sth)) {
return $sth;
}
$res =& $this->execute($sth, $params);
$this->freePrepared($sth);
} else {
$res =& $this->query($query);
}
if ($res === DB_OK || DB::isError($res)) {
return $res;
}
$results = array();
while (DB_OK === $res->fetchInto($row, $fetchmode)) {
if ($fetchmode & DB_FETCHMODE_FLIPPED) {
foreach ($row as $key => $val) {
$results[$key][] = $val;
}
} else {
$results[] = $row;
}
}
$res->free();
if (DB::isError($row)) {
$tmp =& $this->raiseError($row);
return $tmp;
}
return $results;
}
// }}}
// {{{ autoCommit()
/**
* Enables or disables automatic commits
*
* @param bool $onoff true turns it on, false turns it off
*
* @return int DB_OK on success. A DB_Error object if the driver
* doesn't support auto-committing transactions.
*/
function autoCommit($onoff = false)
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
// }}}
// {{{ commit()
/**
* Commits the current transaction
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
function commit()
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
// }}}
// {{{ rollback()
/**
* Reverts the current transaction
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
function rollback()
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
// }}}
// {{{ numRows()
/**
* Determines the number of rows in a query result
*
* @param resource $result the query result idenifier produced by PHP
*
* @return int the number of rows. A DB_Error object on failure.
*/
function numRows($result)
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
// }}}
// {{{ affectedRows()
/**
* Determines the number of rows affected by a data maniuplation query
*
* 0 is returned for queries that don't manipulate data.
*
* @return int the number of rows. A DB_Error object on failure.
*/
function affectedRows()
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
// }}}
// {{{ getSequenceName()
/**
* Generates the name used inside the database for a sequence
*
* The createSequence() docblock contains notes about storing sequence
* names.
*
* @param string $sqn the sequence's public name
*
* @return string the sequence's name in the backend
*
* @access protected
* @see DB_common::createSequence(), DB_common::dropSequence(),
* DB_common::nextID(), DB_common::setOption()
*/
function getSequenceName($sqn)
{
return sprintf($this->getOption('seqname_format'),
preg_replace('/[^a-z0-9_.]/i', '_', $sqn));
}
// }}}
// {{{ nextId()
/**
* Returns the next free id in a sequence
*
* @param string $seq_name name of the sequence
* @param boolean $ondemand when true, the seqence is automatically
* created if it does not exist
*
* @return int the next id number in the sequence.
* A DB_Error object on failure.
*
* @see DB_common::createSequence(), DB_common::dropSequence(),
* DB_common::getSequenceName()
*/
function nextId($seq_name, $ondemand = true)
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
// }}}
// {{{ createSequence()
/**
* Creates a new sequence
*
* The name of a given sequence is determined by passing the string
* provided in the <var>$seq_name</var> argument through PHP's sprintf()
* function using the value from the <var>seqname_format</var> option as
* the sprintf()'s format argument.
*
* <var>seqname_format</var> is set via setOption().
*
* @param string $seq_name name of the new sequence
*
* @return int DB_OK on success. A DB_Error object on failure.
*
* @see DB_common::dropSequence(), DB_common::getSequenceName(),
* DB_common::nextID()
*/
function createSequence($seq_name)
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
// }}}
// {{{ dropSequence()
/**
* Deletes a sequence
*
* @param string $seq_name name of the sequence to be deleted
*
* @return int DB_OK on success. A DB_Error object on failure.
*
* @see DB_common::createSequence(), DB_common::getSequenceName(),
* DB_common::nextID()
*/
function dropSequence($seq_name)
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
// }}}
// {{{ raiseError()
/**
* Communicates an error and invoke error callbacks, etc
*
* Basically a wrapper for PEAR::raiseError without the message string.
*
* @param mixed integer error code, or a PEAR error object (all
* other parameters are ignored if this parameter is
* an object
* @param int error mode, see PEAR_Error docs
* @param mixed if error mode is PEAR_ERROR_TRIGGER, this is the
* error level (E_USER_NOTICE etc). If error mode is
* PEAR_ERROR_CALLBACK, this is the callback function,
* either as a function name, or as an array of an
* object and method name. For other error modes this
* parameter is ignored.
* @param string extra debug information. Defaults to the last
* query and native error code.
* @param mixed native error code, integer or string depending the
* backend
*
* @return object the PEAR_Error object
*
* @see PEAR_Error
*/
function &raiseError($code = DB_ERROR, $mode = null, $options = null,
$userinfo = null, $nativecode = null)
{
// The error is yet a DB error object
if (is_object($code)) {
// because we the static PEAR::raiseError, our global
// handler should be used if it is set
if ($mode === null && !empty($this->_default_error_mode)) {
$mode = $this->_default_error_mode;
$options = $this->_default_error_options;
}
$tmp = PEAR::raiseError($code, null, $mode, $options,
null, null, true);
return $tmp;
}
if ($userinfo === null) {
$userinfo = $this->last_query;
}
if ($nativecode) {
$userinfo .= ' [nativecode=' . trim($nativecode) . ']';
} else {
$userinfo .= ' [DB Error: ' . DB::errorMessage($code) . ']';
}
$tmp = PEAR::raiseError(null, $code, $mode, $options, $userinfo,
'DB_Error', true);
return $tmp;
}
// }}}
// {{{ errorNative()
/**
* Gets the DBMS' native error code produced by the last query
*
* @return mixed the DBMS' error code. A DB_Error object on failure.
*/
function errorNative()
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
// }}}
// {{{ errorCode()
/**
* Maps native error codes to DB's portable ones
*
* Uses the <var>$errorcode_map</var> property defined in each driver.
*
* @param string|int $nativecode the error code returned by the DBMS
*
* @return int the portable DB error code. Return DB_ERROR if the
* current driver doesn't have a mapping for the
* $nativecode submitted.
*/
function errorCode($nativecode)
{
if (isset($this->errorcode_map[$nativecode])) {
return $this->errorcode_map[$nativecode];
}
// Fall back to DB_ERROR if there was no mapping.
return DB_ERROR;
}
// }}}
// {{{ errorMessage()
/**
* Maps a DB error code to a textual message
*
* @param integer $dbcode the DB error code
*
* @return string the error message corresponding to the error code
* submitted. FALSE if the error code is unknown.
*
* @see DB::errorMessage()
*/
function errorMessage($dbcode)
{
return DB::errorMessage($this->errorcode_map[$dbcode]);
}
// }}}
// {{{ tableInfo()
/**
* Returns information about a table or a result set
*
* The format of the resulting array depends on which <var>$mode</var>
* you select. The sample output below is based on this query:
* <pre>
* SELECT tblFoo.fldID, tblFoo.fldPhone, tblBar.fldId
* FROM tblFoo
* JOIN tblBar ON tblFoo.fldId = tblBar.fldId
* </pre>
*
* <ul>
* <li>
*
* <kbd>null</kbd> (default)
* <pre>
* [0] => Array (
* [table] => tblFoo
* [name] => fldId
* [type] => int
* [len] => 11
* [flags] => primary_key not_null
* )
* [1] => Array (
* [table] => tblFoo
* [name] => fldPhone
* [type] => string
* [len] => 20
* [flags] =>
* )
* [2] => Array (
* [table] => tblBar
* [name] => fldId
* [type] => int
* [len] => 11
* [flags] => primary_key not_null
* )
* </pre>
*
* </li><li>
*
* <kbd>DB_TABLEINFO_ORDER</kbd>
*
* <p>In addition to the information found in the default output,
* a notation of the number of columns is provided by the
* <samp>num_fields</samp> element while the <samp>order</samp>
* element provides an array with the column names as the keys and
* their location index number (corresponding to the keys in the
* the default output) as the values.</p>
*
* <p>If a result set has identical field names, the last one is
* used.</p>
*
* <pre>
* [num_fields] => 3
* [order] => Array (
* [fldId] => 2
* [fldTrans] => 1
* )
* </pre>
*
* </li><li>
*
* <kbd>DB_TABLEINFO_ORDERTABLE</kbd>
*
* <p>Similar to <kbd>DB_TABLEINFO_ORDER</kbd> but adds more
* dimensions to the array in which the table names are keys and
* the field names are sub-keys. This is helpful for queries that
* join tables which have identical field names.</p>
*
* <pre>
* [num_fields] => 3
* [ordertable] => Array (
* [tblFoo] => Array (
* [fldId] => 0
* [fldPhone] => 1
* )
* [tblBar] => Array (
* [fldId] => 2
* )
* )
* </pre>
*
* </li>
* </ul>
*
* The <samp>flags</samp> element contains a space separated list
* of extra information about the field. This data is inconsistent
* between DBMS's due to the way each DBMS works.
* + <samp>primary_key</samp>
* + <samp>unique_key</samp>
* + <samp>multiple_key</samp>
* + <samp>not_null</samp>
*
* Most DBMS's only provide the <samp>table</samp> and <samp>flags</samp>
* elements if <var>$result</var> is a table name. The following DBMS's
* provide full information from queries:
* + fbsql
* + mysql
*
* If the 'portability' option has <samp>DB_PORTABILITY_LOWERCASE</samp>
* turned on, the names of tables and fields will be lowercased.
*
* @param object|string $result DB_result object from a query or a
* string containing the name of a table.
* While this also accepts a query result
* resource identifier, this behavior is
* deprecated.
* @param int $mode either unused or one of the tableInfo modes:
* <kbd>DB_TABLEINFO_ORDERTABLE</kbd>,
* <kbd>DB_TABLEINFO_ORDER</kbd> or
* <kbd>DB_TABLEINFO_FULL</kbd> (which does both).
* These are bitwise, so the first two can be
* combined using <kbd>|</kbd>.
*
* @return array an associative array with the information requested.
* A DB_Error object on failure.
*
* @see DB_common::setOption()
*/
function tableInfo($result, $mode = null)
{
/*
* If the DB_<driver> class has a tableInfo() method, that one
* overrides this one. But, if the driver doesn't have one,
* this method runs and tells users about that fact.
*/
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
// }}}
// {{{ getTables()
/**
* Lists the tables in the current database
*
* @return array the list of tables. A DB_Error object on failure.
*
* @deprecated Method deprecated some time before Release 1.2
*/
function getTables()
{
return $this->getListOf('tables');
}
// }}}
// {{{ getListOf()
/**
* Lists internal database information
*
* @param string $type type of information being sought.
* Common items being sought are:
* tables, databases, users, views, functions
* Each DBMS's has its own capabilities.
*
* @return array an array listing the items sought.
* A DB DB_Error object on failure.
*/
function getListOf($type)
{
$sql = $this->getSpecialQuery($type);
if ($sql === null) {
$this->last_query = '';
return $this->raiseError(DB_ERROR_UNSUPPORTED);
} elseif (is_int($sql) || DB::isError($sql)) {
// Previous error
return $this->raiseError($sql);
} elseif (is_array($sql)) {
// Already the result
return $sql;
}
// Launch this query
return $this->getCol($sql);
}
// }}}
// {{{ getSpecialQuery()
/**
* Obtains the query string needed for listing a given type of objects
*
* @param string $type the kind of objects you want to retrieve
*
* @return string the SQL query string or null if the driver doesn't
* support the object type requested
*
* @access protected
* @see DB_common::getListOf()
*/
function getSpecialQuery($type)
{
return $this->raiseError(DB_ERROR_UNSUPPORTED);
}
// }}}
// {{{ _rtrimArrayValues()
/**
* Right-trims all strings in an array
*
* @param array $array the array to be trimmed (passed by reference)
*
* @return void
*
* @access protected
*/
function _rtrimArrayValues(&$array)
{
foreach ($array as $key => $value) {
if (is_string($value)) {
$array[$key] = rtrim($value);
}
}
}
// }}}
// {{{ _convertNullArrayValuesToEmpty()
/**
* Converts all null values in an array to empty strings
*
* @param array $array the array to be de-nullified (passed by reference)
*
* @return void
*
* @access protected
*/
function _convertNullArrayValuesToEmpty(&$array)
{
foreach ($array as $key => $value) {
if (is_null($value)) {
$array[$key] = '';
}
}
}
// }}}
}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
*/
?>
|
mikexstudios/xcomic
|
includes/DB/common.php
|
PHP
|
gpl-2.0
| 69,476
|
package conf;
/**
* Enthält die Konfigurationseinstellungen
* @author CreaByte
*
*/
public final class Conf {
/**
* Frames pro Sekunde
*/
public static final int fps = 22;
/**
* Standard-Zeitschritt für die Simulation
*/
public static final long defaultTimeStep = 1000/fps; // 22fps
/**
* Effektive Umrechnung Längeneinheiten in Pixel
* LINKS OBEN ist der Nullpunkt "der Welt"
*/
public static double pixelPerMeter=4;
public static final double MAX_ZOOM=10,MIN_ZOOM=0.01;
public static int convertToPixel(double meters) {
return (int)(meters * pixelPerMeter);
}
/**
* Typische Größen
*/
public static final double carWidth = 1.5; // Meter
public static final double carLength = 3; // Meter
public static final double laneWidth = 3; // Meter
/**
* Typische Größen für die Autobewegung
*/
public static final double L = 10; // [m] Typische Längeneinheit
public static final double V = 10; // [km/h] Typische Geschwindigkeit
public static final double T = L/V; // [h] Typische Zeiteinheit
public static final double d = 1; // [m] Standard-Sicherheitsabstand
public static final double c = 1; // [] Wie schnell wird beim auffahren gebremst?
public static final double v0 = 10; // [km/h] Standard - Wunschgeschwindigkeit
public static final double tau = 1; // [Sek] Standard - Relaxionszeit in (wie schnell p
public static final double a = 3.85; // [m/s²] Typische Längeneinheit in Metern
public static final double minCarDistance = 2; // Meter
public static final double eyeSight = 10; // Meter
/**
* Grenze der Stationen zum Rand des Stadtgebiets in Meter
*/
public static final double border = 4; // Meter
public static int random(int max) {
return (int)Math.round(Math.random() * max);
}
}
|
rondiplomatico/traffic
|
src/conf/Conf.java
|
Java
|
gpl-2.0
| 1,922
|
/*
* (c) Copyright 2009-2013 by Volker Bergmann. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, is permitted under the terms of the
* GNU General Public License.
*
* For redistributing this software or a derivative work under a license other
* than the GPL-compatible Free Software License as defined by the Free
* Software Foundation or approved by OSI, you must first obtain a commercial
* license to this software product from Volker Bergmann.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* WITHOUT A WARRANTY OF ANY KIND. ALL EXPRESS OR IMPLIED CONDITIONS,
* REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE
* HEREBY EXCLUDED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.databene.benerator.wrapper;
import org.databene.benerator.Generator;
/**
* Converts the {@link Number} products of another {@link Generator} to {@link Integer}.<br/>
* <br/>
* Created at 23.06.2009 22:58:26
* @since 0.6.0
* @author Volker Bergmann
*/
public class AsIntegerGeneratorWrapper<E extends Number> extends GeneratorWrapper<E, Integer> {
public AsIntegerGeneratorWrapper(Generator<E> source) {
super(source);
}
@Override
public Class<Integer> getGeneratedType() {
return Integer.class;
}
@Override
public ProductWrapper<Integer> generate(ProductWrapper<Integer> wrapper) {
assertInitialized();
ProductWrapper<E> tmp = generateFromSource();
if (tmp == null)
return null;
E unwrappedValue = tmp.unwrap();
return wrapper.wrap(unwrappedValue != null ? unwrappedValue.intValue() : null);
}
}
|
raphaelfeng/benerator
|
src/org/databene/benerator/wrapper/AsIntegerGeneratorWrapper.java
|
Java
|
gpl-2.0
| 2,256
|
-- | Some shared utilites.
module Shared (
breakAround
, firstTrue
, ErrorOr, forceError
, asHex
, Hash(..), emptyHash, hashAsHex
, isHashString
, fromHex
, splitMSB
, strictifyBS, makeBS
, trace
) where
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import Control.Monad.Error
import Data.Bits
import Data.Char
import Data.Word
import Debug.Trace
-- | An alias for @Either String a@, for things that may fail with a String.
type ErrorOr a = Either String a
-- | Force an ErrorOr to either a monad failure or the ok value.
forceError :: (MonadIO m) => ErrorOr a -> m a
forceError (Left err) = fail err
forceError (Right ok) = return ok
-- | A SHA-1 hash.
newtype Hash = Hash B.ByteString deriving Eq
instance Show Hash where
show (Hash bs) = "[Hash " ++ asHex bs ++ "]"
-- | Special magic value for "none such file".
emptyHash :: Hash
emptyHash = Hash $ B.pack (replicate 20 0)
-- | Dump a ByteString as a String of hexidecimal characters.
asHex :: B.ByteString -> String
asHex str = foldr hex "" $ B.unpack str where
hex :: Word8 -> String -> String
hex c rest = hexNybble (c `shiftR` 4) : hexNybble (c .&. 0xF) : rest
hexNybble :: Word8 -> Char
hexNybble c = ("0123456789abcdef" !! fromIntegral c)
-- | Parse a string of hex into a ByteString.
fromHex :: String -> B.ByteString
fromHex = B.pack . bytes where
bytes (x1:x2:rest) = parseHex x1 x2 : bytes rest
bytes [] = []
parseHex x1 x2 = fromIntegral (digitToInt x1 * 16 + digitToInt x2)
-- | A hash as a hex string.
hashAsHex :: Hash -> String
hashAsHex (Hash bs) = asHex bs
-- | Test whether a string looks like a hash (40 chars long, all hex).
isHashString :: String -> Bool
isHashString str = length str == 40 && all isHexDigit str
-- |Like @break@, but drops the matched item.
breakAround :: Eq a => (a -> Bool) -> [a] -> ([a], [a])
breakAround pred list = (before, after) where
(before, rest) = break pred list
after = case rest of
(x:xs) | pred x -> xs
_ -> after
-- |firstTrue takes a list of things to do and gives you back the first one
-- that produces a result. (XXX this is probably the composition of some
-- other monadic operators -- which?)
firstTrue :: Monad m => [m (Maybe a)] -> m (Maybe a)
firstTrue [] = return Nothing
firstTrue (x:xs) = do
test <- x
case test of
Just _ -> return test
Nothing -> firstTrue xs
-- |Split a byte into a (Bool, Word8) pair that has the most significant bit
-- and the lower 7 bits. This is a common pattern in Git bit-packing schemes.
splitMSB :: Word8 -> (Bool, Word8)
splitMSB byte = (msb, bits) where
msb = (byte .&. 0x80) /= 0
bits = byte .&. 0x7F
-- |Convert a ByteString.Lazy to a strict ByteString.
strictifyBS :: BL.ByteString -> B.ByteString
strictifyBS = B.concat . BL.toChunks
-- | Convert a String into a strict ByteString.
makeBS :: String -> B.ByteString
makeBS = B.pack . map (fromIntegral . fromEnum)
|
martine/gat
|
Shared.hs
|
Haskell
|
gpl-2.0
| 2,969
|
/* Copyright (C) 1993, 1994, 1998 Aladdin Enterprises. All rights reserved.
This software is provided AS-IS with no warranty, either express or
implied.
This software is distributed under license and may not be copied,
modified or distributed except as expressly authorized under the terms
of the license contained in the file LICENSE in this distribution.
For more information about licensing, please refer to
http://www.ghostscript.com/licensing/. For information on
commercial licensing, go to http://www.artifex.com/licensing/ or
contact Artifex Software, Inc., 101 Lucas Valley Road #110,
San Rafael, CA 94903, U.S.A., +1(415)492-9861.
*/
/* $Id: iutil2.h,v 1.6 2002/06/16 04:47:10 lpd Exp $ */
/* Interface to procedures in iutil2.c */
#ifndef iutil2_INCLUDED
# define iutil2_INCLUDED
/* ------ Password utilities ------ */
/* Define the password structure. */
/* NOTE: MAX_PASSWORD must match the initial password lengths in gs_lev2.ps. */
#define MAX_PASSWORD 64 /* must be at least 11 */
typedef struct password_s {
uint size;
byte data[MAX_PASSWORD];
} password;
# define NULL_PASSWORD {0, {0}}
/* Transmit a password to or from a parameter list. */
int param_read_password(gs_param_list *, const char *, password *);
int param_write_password(gs_param_list *, const char *, const password *);
/* Check a password from a parameter list. */
/* Return 0 if OK, 1 if not OK, or an error code. */
int param_check_password(gs_param_list *, const password *);
/* Read a password from, or write a password into, a dictionary */
/* (presumably systemdict). */
int dict_read_password(password *, const ref *, const char *);
int dict_write_password(const password *, ref *, const char *, bool);
#endif /* iutil2_INCLUDED */
|
brho/plan9
|
sys/src/cmd/gs/src/iutil2.h
|
C
|
gpl-2.0
| 1,773
|
from bs4 import BeautifulSoup
import urllib.request
html = urllib.request.urlopen('http://www.nlotto.co.kr/common.do?method=main’')
soup = BeautifulSoup(html)
hoi = soup.find("span", id="lottoDrwNo")
numbers=[]
for n in range(1,7):
strV ="drwtNo" + str(n)
first = soup.find('img', id=strV)['alt']
numbers.append(first)
bonus = soup.find('img', id="bnusNo")['alt']
print('Lotto numbers')
print(hoi.string + "results")
print(" ".join(numbers))
print('Bonus_number: '+bonus)
|
YongJang/PythonTelegram
|
examples/referenced/a.py
|
Python
|
gpl-2.0
| 497
|
<?php
$lang['plugin']['categories'] = array(
'subject' => 'Kategorie'
);
?>
|
evacchi/flatpress
|
fp-plugins/categories/lang/lang.cs-cz.php
|
PHP
|
gpl-2.0
| 89
|
package polarbear.acceptance.order;
import static com.polarbear.util.Constants.ResultState.*;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static polarbear.acceptance.Request.anRequest;
import static polarbear.integration.service.order.assertutil.AssertUtil.assertThatOrder;
import static polarbear.integration.service.order.factory.ExpectOrderFactory.expectOrder2;
import static polarbear.test.util.Constants.ORDER_DETAIL_URL;
import static polarbear.test.util.Constants.ORDER_SIGN_URL;
import static polarbear.test.util.JsonResultConvertUtil.resultBody;
import static polarbear.test.util.JsonResultConvertUtil.resultState;
import static polarbear.test.util.LoginEncoder.encodeLoginUser;
import static polarbear.testdata.acceptance.testdata.OrderAcceptanceTestDataFactory.*;
import static polarbear.testdata.acceptance.testdata.UserAcceptanceTestDataFactory.createUser1;
import java.io.UnsupportedEncodingException;
import org.junit.Test;
import polarbear.acceptance.Request.ResultCallback;
import com.polarbear.domain.Order;
import com.polarbear.util.JsonResult;
import com.polarbear.util.Constants.ORDER_STATE;
import com.polarbear.web.login.front.LoginController;
public class SignOrderTest {
@Test
public void shouldSuccessWhenSignOrder() {
final String signOrderId = createUser1_2ProductDeliveryOrder2().getId().toString();
anRequest(ORDER_SIGN_URL)
.withCookie(LoginController.USER_LOGIN_COOKIE, encodeLoginUser(createUser1()))
.addParams("orderId", signOrderId)
.post(new ResultCallback() {
public void onSuccess(JsonResult jsonResult) throws UnsupportedEncodingException {
assertThat(resultState(jsonResult), is(SUCCESS));
assertOrder(signOrderId);
}
});
}
@Test
public void shouldFailWhenSignOrderInCancleState() {
final String signOrderId = createUser1_2ProductUnpayOrder1().getId().toString();
anRequest(ORDER_SIGN_URL)
.withCookie(LoginController.USER_LOGIN_COOKIE, encodeLoginUser(createUser1()))
.addParams("orderId", signOrderId)
.post(new ResultCallback() {
public void onSuccess(JsonResult jsonResult) throws UnsupportedEncodingException {
assertThat(resultState(jsonResult), is(ORDER_OPREATE_ERR));
}
});
}
private void assertOrder(String orderId) {
anRequest(ORDER_DETAIL_URL)
.withCookie(LoginController.USER_LOGIN_COOKIE, encodeLoginUser(createUser1()))
.addParams("orderId", orderId)
.post(new ResultCallback() {
public void onSuccess(JsonResult jsonResult) throws UnsupportedEncodingException {
assertThat(resultState(jsonResult), is(SUCCESS));
Order actOrder = resultBody(jsonResult, Order.class);
assertThatOrder(actOrder, expectOrder2(ORDER_STATE.SUCCESS));
}
});
}
}
|
polargull/polar
|
polarbear/src/test/java/polarbear/acceptance/order/SignOrderTest.java
|
Java
|
gpl-2.0
| 3,093
|
<?php
/**
* @copyright Copyright(c) 2010 jooyea.net
* @file curd_action.php
* @brief 实现系统的自动增删改查
* @author webning
* @date 2010-12-23
* @version 0.6
*/
/**
* @brief 完成用户的自动增加删除修改功能DURD类
* @class ICURDAction
*/
class ICURDAction extends IAction
{
/**
* @brief 处理curd动作
* @return String
*/
public function curd()
{
$action = $this->id;
$controller = $this->controller;
$curdinfo = $this->initinfo();
if(is_array($curdinfo))
{
$modelName = $curdinfo['model'];
$key = $curdinfo['key'];
$actions = $curdinfo['actions'];
switch($action)
{
case 'add':
case 'upd':
{
if(method_exists($controller,'getValidate')) $validate = $controller->getValidate();
else $validate =null;
if($validate!=null)
{
$formValidate = new IFormValidation($validate);
$data = $formValidate->run();
}
$model = new IModel($modelName);
if(isset($data) && $data!==null)
{
$model->setData($data[$modelName]);
if($action = 'add') $flag = $model->add();
else $flag = $model->upd("$key = '".IReq::get($key)."'");
}
if(isset($flag) && $flag)
{
$_GET['action'] = $actions['success'];
}
else
{
$_GET['action'] = $actions['fail'];
}
$controller->run();
return true;
}
case 'del':
{
$model = new IModel($modelName);
$flag = $model->del("$key = '".IReq::get($key)."'");
if($flag)
{
$_GET['action']=$actions['success'];
}
else
{
$_GET['action'] = $actions['fail'];
}
$controller->run();
return true;
}
case 'get':
{
$model = new IModel($modelName);
$rs = $model->getObj("$key = '".IReq::get($key)."'");
echo JSON::encode($rs);
return false;
}
}
}
}
/**
* @brief 分析curd的配置信息
* @return mixed
*/
private function initinfo()
{
$action = $this->id;
$controller = $this->controller;
if(method_exists($controller,'curd'))
{
$curdinfo = $controller->curd();
$modelName = isset($curdinfo['model'])?$curdinfo['model']:null;
if($modelName !==null)
{
$key = isset($curdinfo['key'])?$curdinfo['key']:'id';
$actions = isset($curdinfo['actions'])?$curdinfo['actions']:null;
if(is_array($actions))
{
if(isset($actions[$action]))
{
$current = $actions[$action];
}
else
{
$current = isset($actions['*'])?$actions['*']:null;
}
if($current!==null)
{
$fail = isset($current['fail'])?$current['fail']:(isset($current[1])?$current[1]:'index');
$success = isset($current['success'])?$current['success']:(isset($current[0])?$current[0]:'index');
return array('model'=>$modelName,'key'=>$key, 'actions' =>array('success'=>$success,'fail'=>$fail) );
}
else
{
throw new IException('class '.get_class($controller).' have curd error');
}
}
}
}
return null;
}
/**
* @brief Action的运行方法
*/
public function run()
{
$this->curd();
}
}
?>
|
zatol/iws
|
lib/web/action/curd_action.php
|
PHP
|
gpl-2.0
| 4,566
|
<?php
namespace CirrusSearch\Search;
use CirrusSearch\Search\Fetch\FetchPhaseConfigBuilder;
use Elastica\ResultSet as ElasticaResultSet;
/**
* Result type for a full text search.
*/
final class FullTextResultsType extends BaseResultsType {
/**
* @var bool
*/
private $searchContainedSyntax;
/**
* @var FetchPhaseConfigBuilder
*/
private $fetchPhaseBuilder;
/**
* @var TitleHelper
*/
private $titleHelper;
/**
* @var string[] list of extra fields to extract
*/
private $extraFieldsToExtract;
/**
* @param FetchPhaseConfigBuilder $fetchPhaseBuilder
* @param bool $searchContainedSyntax
* @param TitleHelper $titleHelper
* @param string[] $extraFieldsToExtract
*/
public function __construct(
FetchPhaseConfigBuilder $fetchPhaseBuilder,
$searchContainedSyntax,
TitleHelper $titleHelper,
array $extraFieldsToExtract = []
) {
$this->fetchPhaseBuilder = $fetchPhaseBuilder;
$this->searchContainedSyntax = $searchContainedSyntax;
$this->titleHelper = $titleHelper;
$this->extraFieldsToExtract = $extraFieldsToExtract;
}
/**
* @return false|string|array corresponding to Elasticsearch source filtering syntax
*/
public function getSourceFiltering() {
return array_merge(
parent::getSourceFiltering(),
[ 'redirect.*', 'timestamp', 'text_bytes' ],
$this->extraFieldsToExtract
);
}
/**
* @return array
*/
public function getStoredFields() {
return [ "text.word_count" ]; // word_count is only a stored field and isn't part of the source.
}
/**
* Setup highlighting.
* Don't fragment title because it is small.
* Get just one fragment from the text because that is all we will display.
* Get one fragment from redirect title and heading each or else they
* won't be sorted by score.
*
* @param array $extraHighlightFields (deprecated and ignored)
* @return array|null of highlighting configuration
*/
public function getHighlightingConfiguration( array $extraHighlightFields = [] ) {
$this->fetchPhaseBuilder->configureDefaultFullTextFields();
return $this->fetchPhaseBuilder->buildHLConfig();
}
/**
* @param ElasticaResultSet $result
* @return CirrusSearchResultSet
*/
public function transformElasticsearchResult( ElasticaResultSet $result ) {
// Should we make this a concrete class?
return new class( $this->titleHelper, $this->fetchPhaseBuilder, $result, $this->searchContainedSyntax, $this->extraFieldsToExtract )
extends BaseCirrusSearchResultSet {
/** @var TitleHelper */
private $titleHelper;
/** @var FullTextCirrusSearchResultBuilder */
private $resultBuilder;
/** @var ElasticaResultSet */
private $results;
/** @var bool */
private $searchContainedSyntax;
public function __construct(
TitleHelper $titleHelper,
FetchPhaseConfigBuilder $builder,
ElasticaResultSet $results,
$searchContainedSyntax,
array $extraFieldsToExtract
) {
$this->titleHelper = $titleHelper;
$this->resultBuilder = new FullTextCirrusSearchResultBuilder( $this->titleHelper,
$builder->getHLFieldsPerTargetAndPriority(), $extraFieldsToExtract );
$this->results = $results;
$this->searchContainedSyntax = $searchContainedSyntax;
}
/**
* @inheritDoc
*/
protected function transformOneResult( \Elastica\Result $result ) {
return $this->resultBuilder->build( $result );
}
/**
* @return \Elastica\ResultSet|null
*/
public function getElasticaResultSet() {
return $this->results;
}
/**
* @inheritDoc
*/
public function searchContainedSyntax() {
return $this->searchContainedSyntax;
}
protected function getTitleHelper(): TitleHelper {
return $this->titleHelper;
}
};
}
/**
* @param FetchPhaseConfigBuilder $builder
* @return FullTextResultsType
*/
public function withFetchPhaseBuilder( FetchPhaseConfigBuilder $builder ): FullTextResultsType {
return new self( $builder, $this->searchContainedSyntax, $this->titleHelper );
}
/**
* @return CirrusSearchResultSet
*/
public function createEmptyResult() {
return BaseCirrusSearchResultSet::emptyResultSet();
}
}
|
wikimedia/mediawiki-extensions-CirrusSearch
|
includes/Search/FullTextResultsType.php
|
PHP
|
gpl-2.0
| 4,137
|
namespace L2dotNET.GameService.network.l2send
{
class AutoAttackStop : GameServerNetworkPacket
{
private int sId;
public AutoAttackStop(int sId)
{
this.sId = sId;
}
protected internal override void write()
{
writeC(0x2c);
writeD(sId);
}
}
}
|
domis045/L2dotNET
|
src/L2dotNET.Game/network/serverpackets/AutoAttackStop.cs
|
C#
|
gpl-2.0
| 350
|
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark 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
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest20813")
public class BenchmarkTest20813 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request );
String param = scr.getTheValue("foo");
String bar = doSomething(param);
String a1 = "";
String a2 = "";
String osName = System.getProperty("os.name");
if (osName.indexOf("Windows") != -1) {
a1 = "cmd.exe";
a2 = "/c";
} else {
a1 = "sh";
a2 = "-c";
}
String[] args = {a1, a2, "echo", bar};
String[] argsEnv = { "foo=bar" };
Runtime r = Runtime.getRuntime();
try {
Process p = r.exec(args, argsEnv);
org.owasp.benchmark.helpers.Utils.printOSCommandResults(p);
} catch (IOException e) {
System.out.println("Problem executing cmdi - TestCase");
throw new ServletException(e);
}
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
java.util.List<String> valuesList = new java.util.ArrayList<String>( );
valuesList.add("safe");
valuesList.add( param );
valuesList.add( "moresafe" );
valuesList.remove(0); // remove the 1st safe value
String bar = valuesList.get(0); // get the param value
return bar;
}
}
|
iammyr/Benchmark
|
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest20813.java
|
Java
|
gpl-2.0
| 2,749
|
# Makefile.in generated by automake 1.11.1 from Makefile.am.
# common/Makefile. Generated from Makefile.in by configure.
# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
# 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation,
# Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
pkgdatadir = $(datadir)/mdm
pkgincludedir = $(includedir)/mdm
pkglibdir = $(libdir)/mdm
pkglibexecdir = $(libexecdir)/mdm
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(program_transform_name)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
build_triplet = x86_64-pc-linux-gnu
host_triplet = x86_64-pc-linux-gnu
libexec_PROGRAMS = mdm-crash-logger$(EXEEXT)
noinst_PROGRAMS = test-settings-server$(EXEEXT) \
test-settings-client$(EXEEXT) test-log$(EXEEXT) \
$(am__EXEEXT_1)
subdir = common
DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \
$(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \
$(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \
$(top_srcdir)/m4/mate-doc-utils.m4 $(top_srcdir)/acinclude.m4 \
$(top_srcdir)/configure.ac
am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
$(ACLOCAL_M4)
mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs
CONFIG_HEADER = $(top_builddir)/config.h
CONFIG_CLEAN_FILES =
CONFIG_CLEAN_VPATH_FILES =
LTLIBRARIES = $(noinst_LTLIBRARIES)
am__DEPENDENCIES_1 =
libmdmcommon_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
$(am__DEPENDENCIES_1)
am__libmdmcommon_la_SOURCES_DIST = mdm-address.h mdm-address.c \
mdm-common.h mdm-common.c mdm-common-unknown-origin.h \
mdm-common-unknown-origin.c mdm-profile.c mdm-profile.h \
mdm-settings.c mdm-settings.h mdm-settings-backend.c \
mdm-settings-backend.h mdm-settings-desktop-backend.c \
mdm-settings-desktop-backend.h mdm-settings-keys.h \
mdm-settings-utils.h mdm-settings-utils.c \
mdm-settings-direct.c mdm-settings-direct.h \
mdm-settings-client.h mdm-settings-client.c mdm-log.h \
mdm-log.c mdm-md5.h mdm-md5.c mdm-signal-handler.h \
mdm-signal-handler.c mkdtemp.c mkdtemp.h
#am__objects_1 = libmdmcommon_la-mkdtemp.lo
am__objects_2 =
am_libmdmcommon_la_OBJECTS = libmdmcommon_la-mdm-address.lo \
libmdmcommon_la-mdm-common.lo \
libmdmcommon_la-mdm-common-unknown-origin.lo \
libmdmcommon_la-mdm-profile.lo libmdmcommon_la-mdm-settings.lo \
libmdmcommon_la-mdm-settings-backend.lo \
libmdmcommon_la-mdm-settings-desktop-backend.lo \
libmdmcommon_la-mdm-settings-utils.lo \
libmdmcommon_la-mdm-settings-direct.lo \
libmdmcommon_la-mdm-settings-client.lo \
libmdmcommon_la-mdm-log.lo libmdmcommon_la-mdm-md5.lo \
libmdmcommon_la-mdm-signal-handler.lo $(am__objects_1) \
$(am__objects_2)
nodist_libmdmcommon_la_OBJECTS = libmdmcommon_la-mdm-marshal.lo
libmdmcommon_la_OBJECTS = $(am_libmdmcommon_la_OBJECTS) \
$(nodist_libmdmcommon_la_OBJECTS)
AM_V_lt = $(am__v_lt_$(V))
am__v_lt_ = $(am__v_lt_$(AM_DEFAULT_VERBOSITY))
am__v_lt_0 = --silent
libmdmcommon_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \
$(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \
$(libmdmcommon_la_CFLAGS) $(CFLAGS) $(libmdmcommon_la_LDFLAGS) \
$(LDFLAGS) -o $@
am__installdirs = "$(DESTDIR)$(libexecdir)" "$(DESTDIR)$(mdmdir)"
am__EXEEXT_1 =
PROGRAMS = $(libexec_PROGRAMS) $(noinst_PROGRAMS)
am_mdm_crash_logger_OBJECTS = \
mdm_crash_logger-mdm-crash-logger.$(OBJEXT)
mdm_crash_logger_OBJECTS = $(am_mdm_crash_logger_OBJECTS)
mdm_crash_logger_DEPENDENCIES = $(am__DEPENDENCIES_1)
am_test_log_OBJECTS = test-log.$(OBJEXT) $(am__objects_2)
test_log_OBJECTS = $(am_test_log_OBJECTS)
test_log_DEPENDENCIES = libmdmcommon.la $(am__DEPENDENCIES_1) \
$(am__DEPENDENCIES_1)
am_test_settings_client_OBJECTS = test-settings-client.$(OBJEXT) \
$(am__objects_2)
test_settings_client_OBJECTS = $(am_test_settings_client_OBJECTS)
test_settings_client_DEPENDENCIES = libmdmcommon.la \
$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
am_test_settings_server_OBJECTS = test-settings-server.$(OBJEXT) \
$(am__objects_2)
test_settings_server_OBJECTS = $(am_test_settings_server_OBJECTS)
test_settings_server_DEPENDENCIES = libmdmcommon.la \
$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
DEFAULT_INCLUDES = -I. -I$(top_builddir)
depcomp = $(SHELL) $(top_srcdir)/depcomp
am__depfiles_maybe = depfiles
am__mv = mv -f
COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
$(AM_CFLAGS) $(CFLAGS)
AM_V_CC = $(am__v_CC_$(V))
am__v_CC_ = $(am__v_CC_$(AM_DEFAULT_VERBOSITY))
am__v_CC_0 = @echo " CC " $@;
AM_V_at = $(am__v_at_$(V))
am__v_at_ = $(am__v_at_$(AM_DEFAULT_VERBOSITY))
am__v_at_0 = @
CCLD = $(CC)
LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
$(AM_LDFLAGS) $(LDFLAGS) -o $@
AM_V_CCLD = $(am__v_CCLD_$(V))
am__v_CCLD_ = $(am__v_CCLD_$(AM_DEFAULT_VERBOSITY))
am__v_CCLD_0 = @echo " CCLD " $@;
AM_V_GEN = $(am__v_GEN_$(V))
am__v_GEN_ = $(am__v_GEN_$(AM_DEFAULT_VERBOSITY))
am__v_GEN_0 = @echo " GEN " $@;
SOURCES = $(libmdmcommon_la_SOURCES) $(nodist_libmdmcommon_la_SOURCES) \
$(mdm_crash_logger_SOURCES) $(test_log_SOURCES) \
$(test_settings_client_SOURCES) \
$(test_settings_server_SOURCES)
DIST_SOURCES = $(am__libmdmcommon_la_SOURCES_DIST) \
$(mdm_crash_logger_SOURCES) $(test_log_SOURCES) \
$(test_settings_client_SOURCES) \
$(test_settings_server_SOURCES)
am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
am__vpath_adj = case $$p in \
$(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
*) f=$$p;; \
esac;
am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
am__install_max = 40
am__nobase_strip_setup = \
srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
am__nobase_strip = \
for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
am__nobase_list = $(am__nobase_strip_setup); \
for p in $$list; do echo "$$p $$p"; done | \
sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
$(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
if (++n[$$2] == $(am__install_max)) \
{ print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
END { for (dir in files) print dir, files[dir] }'
am__base_list = \
sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
DATA = $(mdm_DATA)
ETAGS = etags
CTAGS = ctags
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
ACLOCAL = ${SHELL} /home/gfunkmonk/Desktop/tmp/mdm/mate-display-manager-1.0.8/missing --run aclocal-1.11
ALL_LINGUAS =
AMTAR = ${SHELL} /home/gfunkmonk/Desktop/tmp/mdm/mate-display-manager-1.0.8/missing --run tar
AM_DEFAULT_VERBOSITY = 1
APPLET_CFLAGS = -pthread -DMATECORBA2=1 -I/usr/include/dbus-1.0 -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/gtk-2.0 -I/usr/lib/x86_64-linux-gnu/gtk-2.0/include -I/usr/include/atk-1.0 -I/usr/include/cairo -I/usr/include/gdk-pixbuf-2.0 -I/usr/include/pango-1.0 -I/usr/include/gio-unix-2.0/ -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng12 -I/usr/include/libdrm -I/usr/include/gail-1.0 -I/usr/include/panel-2.0 -I/usr/include/mateconf/2 -I/usr/include/libmatecomponentui-2.0 -I/usr/include/matecorba-2.0 -I/usr/include/libxml2 -I/usr/include/libmatecomponent-2.0 -I/usr/include/libmatecanvas-2.0 -I/usr/include/libmate-2.0 -I/usr/include/matecomponent-activation-2.0 -I/usr/include/libart-2.0 -I/usr/include/mate-vfs-2.0 -I/usr/lib/mate-vfs-2.0/include
APPLET_LIBS = -pthread -ldbus-glib-1 -ldbus-1 -lpthread -lmate-panel-applet-2 -lmateconf-2 -lmatecomponentui-2 -lmatecanvas-2 -lmate-2 -lpopt -lart_lgpl_2 -lgtk-x11-2.0 -lgdk-x11-2.0 -latk-1.0 -lgio-2.0 -lpangoft2-1.0 -lpangocairo-1.0 -lgdk_pixbuf-2.0 -lcairo -lpango-1.0 -lfreetype -lfontconfig -lmatecomponent-2 -lmatecomponent-activation -lgmodule-2.0 -lMateCORBA-2 -lgobject-2.0 -lgthread-2.0 -lrt -lglib-2.0
AR = ar
AT_BINDIR = ${bindir}
AT_SPI_REGISTRYD_DIR = /usr/lib/at-spi
AUTOCONF = ${SHELL} /home/gfunkmonk/Desktop/tmp/mdm/mate-display-manager-1.0.8/missing --run autoconf
AUTOHEADER = ${SHELL} /home/gfunkmonk/Desktop/tmp/mdm/mate-display-manager-1.0.8/missing --run autoheader
AUTOMAKE = ${SHELL} /home/gfunkmonk/Desktop/tmp/mdm/mate-display-manager-1.0.8/missing --run automake-1.11
AWK = mawk
BINDIR = /usr/bin
CANBERRA_GTK_CFLAGS = -pthread -D_REENTRANT -I/usr/include/gtk-2.0 -I/usr/lib/x86_64-linux-gnu/gtk-2.0/include -I/usr/include/atk-1.0 -I/usr/include/cairo -I/usr/include/gdk-pixbuf-2.0 -I/usr/include/pango-1.0 -I/usr/include/gio-unix-2.0/ -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng12 -I/usr/include/libdrm
CANBERRA_GTK_LIBS = -pthread -lcanberra-gtk -lcanberra -lgtk-x11-2.0 -lgdk-x11-2.0 -latk-1.0 -lgio-2.0 -lpangoft2-1.0 -lpangocairo-1.0 -lgdk_pixbuf-2.0 -lcairo -lpango-1.0 -lfreetype -lfontconfig -lgobject-2.0 -lgmodule-2.0 -lgthread-2.0 -lrt -lglib-2.0
CATALOGS =
CATOBJEXT = .gmo
CC = gcc
CCDEPMODE = depmode=none
CFLAGS = -g -O2 -g -O2 -Wall
CHECK_CFLAGS =
CHECK_LIBS = -lcheck
COMMON_CFLAGS = -pthread -DMATECORBA2=1 -I/usr/include/dbus-1.0 -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/polkit-1 -I/usr/include/mateconf/2 -I/usr/include/matecorba-2.0
COMMON_LIBS = -pthread -ldbus-glib-1 -ldbus-1 -lpthread -lpolkit-gobject-1 -lgio-2.0 -lgobject-2.0 -lgmodule-2.0 -lgthread-2.0 -lrt -lmateconf-2 -lglib-2.0
CPP = gcc -E
CPPFLAGS =
CXX = g++
CXXCPP = g++ -E
CXXDEPMODE = depmode=none
CXXFLAGS = -g -O2 -g -O2 -Wall
CYGPATH_W = echo
DAEMON_CFLAGS = -pthread -I/usr/include/dbus-1.0 -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/polkit-1
DAEMON_LIBS = -pthread -ldbus-glib-1 -ldbus-1 -lpthread -lpolkit-gobject-1 -lgio-2.0 -lgobject-2.0 -lgmodule-2.0 -lgthread-2.0 -lrt -lglib-2.0
DATADIR = /usr/share
DATADIRNAME = share
DBUS_SYS_DIR = /etc/dbus-1/system.d
DEBUG_CFLAGS = -DG_ENABLE_DEBUG
DEFS = -DHAVE_CONFIG_H
DEPDIR = .deps
DISTCHECK_CONFIGURE_FLAGS = --disable-scrollkeeper
DLLTOOL = false
DOC_USER_FORMATS =
DSYMUTIL =
DUMPBIN =
ECHO_C =
ECHO_N = -n
ECHO_T =
EGREP = /bin/grep -E
EXEEXT =
EXTRA_CHOOSER_LIBS =
EXTRA_DAEMON_LIBS = -lutil -lutil -lutil -lselinux -lattr
EXTRA_DYNAMIC_LIBS =
EXTRA_FLEXI_LIBS =
EXTRA_GREETER_LIBS =
EXTRA_SETUP_LIBS =
EXTRA_SLAVE_LIBS =
EXTRA_TEST_LIBS =
EXTRA_XNEST_LIBS =
FGREP = /bin/grep -F
GETTEXT_PACKAGE = mdm
GLIB_GENMARSHAL = /usr/bin/glib-genmarshal
GMOFILES =
GMSGFMT = /usr/bin/msgfmt
GREP = /bin/grep
GTHREAD_CFLAGS = -pthread -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include
GTHREAD_LIBS = -pthread -lgthread-2.0 -lrt -lglib-2.0
GTK_CFLAGS = -pthread -I/usr/include/gtk-2.0 -I/usr/lib/x86_64-linux-gnu/gtk-2.0/include -I/usr/include/atk-1.0 -I/usr/include/cairo -I/usr/include/gdk-pixbuf-2.0 -I/usr/include/pango-1.0 -I/usr/include/gio-unix-2.0/ -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng12 -I/usr/include/libdrm
GTK_LIBS = -pthread -lgtk-x11-2.0 -lgdk-x11-2.0 -latk-1.0 -lgio-2.0 -lpangoft2-1.0 -lpangocairo-1.0 -lgdk_pixbuf-2.0 -lcairo -lpango-1.0 -lfreetype -lfontconfig -lgobject-2.0 -lgmodule-2.0 -lgthread-2.0 -lrt -lglib-2.0
HAVE_LIBXKLAVIER =
HAVE_PAM =
HELP_DIR = ${datadir}/mate/help
INSTALL = /usr/bin/install -c
INSTALL_DATA = ${INSTALL} -m 644
INSTALL_PROGRAM = ${INSTALL}
INSTALL_SCRIPT = ${INSTALL}
INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
INSTOBJEXT = .mo
INTLLIBS =
INTLTOOL_EXTRACT = /usr/bin/intltool-extract
INTLTOOL_MERGE = /usr/bin/intltool-merge
INTLTOOL_PERL = /usr/bin/perl
INTLTOOL_UPDATE = /usr/bin/intltool-update
LANG_CONFIG_FILE = $(sysconfdir)/sysconfig/i18n
LD = /usr/bin/ld -m elf_x86_64
LDFLAGS = -Wl,-Bsymbolic-functions
LIBDIR = /usr/lib
LIBEXECDIR = /usr/lib/mate-display-manager
LIBOBJS =
LIBS =
LIBTOOL = $(SHELL) $(top_builddir)/libtool
LIBWRAP_LIBS = -lwrap
LIBXKLAVIER_CFLAGS = -pthread -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/libxml2
LIBXKLAVIER_LIBS = -lxklavier
LIPO =
LN_S = ln -s
LOCALSTATEDIR = /var
LTLIBOBJS =
MAINT = #
MAKEINFO = ${SHELL} /home/gfunkmonk/Desktop/tmp/mdm/mate-display-manager-1.0.8/missing --run makeinfo
MANIFEST_TOOL = :
MATECONFTOOL = /usr/bin/mateconftool-2
MATECONF_CFLAGS = -pthread -DMATECORBA2=1 -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/mateconf/2 -I/usr/include/matecorba-2.0
MATECONF_LIBS = -lmateconf-2 -lglib-2.0
MATECONF_SCHEMA_CONFIG_SOURCE = xml:merged:/etc/mateconf/mateconf.xml.defaults
MATECONF_SCHEMA_FILE_DIR = $(sysconfdir)/mateconf/schemas
MDMCHOOSER = mdmchooser
MDMSETUP_CFLAGS = -pthread -I/usr/include/dbus-1.0 -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/gtk-2.0 -I/usr/lib/x86_64-linux-gnu/gtk-2.0/include -I/usr/include/atk-1.0 -I/usr/include/cairo -I/usr/include/gdk-pixbuf-2.0 -I/usr/include/pango-1.0 -I/usr/include/gio-unix-2.0/ -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng12 -I/usr/include/libdrm
MDMSETUP_LIBS = -pthread -Wl,--export-dynamic -ldbus-glib-1 -ldbus-1 -lpthread -lgtk-x11-2.0 -lgdk-x11-2.0 -latk-1.0 -lgio-2.0 -lpangoft2-1.0 -lpangocairo-1.0 -lgdk_pixbuf-2.0 -lcairo -lpango-1.0 -lfreetype -lfontconfig -lgobject-2.0 -lgthread-2.0 -lgmodule-2.0 -lrt -lglib-2.0
MDM_CUSTOM_CONF = ${mdmconfdir}/custom.conf
MDM_DEFAULTS_CONF = ${datadir}/mdm/defaults.conf
MDM_GROUPNAME = mdm
MDM_OLD_CONF = ${mdmconfdir}/mdm.conf
MDM_PID_FILE = /var/run/mdm.pid
MDM_SCREENSHOT_DIR = /var/run/mdm/greeter
MDM_SESSION_DEFAULT_PATH = /usr/local/bin:/usr/bin:/bin:/usr/games
MDM_USERNAME = mdm
MDM_WORKING_DIR = /var/lib/gdm
MDM_XAUTH_DIR = /var/run/mdm
MKDIR_P = /bin/mkdir -p
MKINSTALLDIRS = ./mkinstalldirs
MSGFMT = /usr/bin/msgfmt
MSGFMT_OPTS = -c
MSGMERGE = /usr/bin/msgmerge
NM = /usr/bin/nm -B
NMEDIT =
OBJDUMP = objdump
OBJEXT = o
OMF_DIR = ${datadir}/omf
OTOOL =
OTOOL64 =
PACKAGE = mdm
PACKAGE_BUGREPORT = http://bugzilla.mate.org/enter_bug.cgi?product=mdm
PACKAGE_NAME = mdm
PACKAGE_STRING = mdm 1.0.8
PACKAGE_TARNAME = mdm
PACKAGE_URL =
PACKAGE_VERSION = 1.0.8
PAM_LIBS = -lpam
PAM_PREFIX = ${sysconfdir}
PATH_SEPARATOR = :
PKG_CONFIG = /usr/bin/pkg-config
PKG_CONFIG_LIBDIR =
PKG_CONFIG_PATH =
PLUGIN_LIBTOOL_FLAGS = -export_dynamic -module -avoid-version
POFILES =
POSUB = po
PO_IN_DATADIR_FALSE =
PO_IN_DATADIR_TRUE =
RANLIB = ranlib
RBAC_LIBS =
SBINDIR = /usr/sbin
SED = /bin/sed
SET_MAKE =
SET_SESSION_CFLAGS = -pthread -I/usr/include/dbus-1.0 -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include
SET_SESSION_LIBS = -pthread -ldbus-glib-1 -ldbus-1 -lpthread -lgobject-2.0 -lgthread-2.0 -lrt -lglib-2.0
SHELL = /bin/bash
SIMPLE_CHOOSER_CFLAGS = -pthread -DMATECORBA2=1 -I/usr/include/dbus-1.0 -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/gtk-2.0 -I/usr/lib/x86_64-linux-gnu/gtk-2.0/include -I/usr/include/atk-1.0 -I/usr/include/cairo -I/usr/include/gdk-pixbuf-2.0 -I/usr/include/pango-1.0 -I/usr/include/gio-unix-2.0/ -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng12 -I/usr/include/libdrm -I/usr/include/mateconf/2 -I/usr/include/matecorba-2.0
SIMPLE_CHOOSER_LIBS = -pthread -ldbus-glib-1 -ldbus-1 -lpthread -lgtk-x11-2.0 -lgdk-x11-2.0 -latk-1.0 -lgio-2.0 -lpangoft2-1.0 -lpangocairo-1.0 -lgdk_pixbuf-2.0 -lcairo -lpango-1.0 -lfreetype -lfontconfig -lgobject-2.0 -lgmodule-2.0 -lgthread-2.0 -lrt -lmateconf-2 -lglib-2.0
SIMPLE_GREETER_CFLAGS = -pthread -DMATECORBA2=1 -I/usr/include/dbus-1.0 -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/gtk-2.0 -I/usr/lib/x86_64-linux-gnu/gtk-2.0/include -I/usr/include/atk-1.0 -I/usr/include/cairo -I/usr/include/gdk-pixbuf-2.0 -I/usr/include/pango-1.0 -I/usr/include/gio-unix-2.0/ -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng12 -I/usr/include/libdrm -I/usr/include/mateconf/2 -I/usr/include/matecorba-2.0
SIMPLE_GREETER_LIBS = -pthread -ldbus-glib-1 -ldbus-1 -lpthread -lgtk-x11-2.0 -lgdk-x11-2.0 -latk-1.0 -lgio-2.0 -lpangoft2-1.0 -lpangocairo-1.0 -lgdk_pixbuf-2.0 -lcairo -lpango-1.0 -lfreetype -lgobject-2.0 -lgmodule-2.0 -lgthread-2.0 -lrt -lmateconf-2 -lglib-2.0 -lfontconfig -lX11 -lm
SOUND_PROGRAM =
STRIP = strip
SYSCONFDIR = /etc
UPOWER =
UPOWER_CFLAGS = -pthread -I/usr/include/dbus-1.0 -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/libupower-glib
UPOWER_LIBS = -pthread -lupower-glib -lgobject-2.0 -lgthread-2.0 -lrt -lglib-2.0
USE_NLS = yes
VERSION = 1.0.8
WARN_CFLAGS = -Wall -Wmissing-prototypes
WITH_CONSOLE_KIT =
XDMCP_LIBS = -lXdmcp
XEVIE_OPTION =
XGETTEXT = /usr/bin/xgettext
XINERAMA_LIBS = -lXinerama
XLIB_CFLAGS =
XLIB_LIBS = -lX11 -lXau
XMKMF =
XSESSION_SHELL = /bin/sh
X_CFLAGS =
X_CONFIG_OPTIONS = -audit 0
X_EXTRA_LIBS = -lXext -lXi
X_LIBS =
X_PATH = /usr/bin
X_PRE_LIBS = -lSM -lICE
X_SERVER = /usr/bin/Xorg
X_SERVER_PATH = /usr/bin
X_XNEST_CMD =
X_XNEST_CONFIG_OPTIONS =
X_XNEST_UNSCALED_FONTPATH = true
abs_builddir = /home/gfunkmonk/Desktop/tmp/mdm/mate-display-manager-1.0.8/common
abs_srcdir = /home/gfunkmonk/Desktop/tmp/mdm/mate-display-manager-1.0.8/common
abs_top_builddir = /home/gfunkmonk/Desktop/tmp/mdm/mate-display-manager-1.0.8
abs_top_srcdir = /home/gfunkmonk/Desktop/tmp/mdm/mate-display-manager-1.0.8
ac_ct_AR = ar
ac_ct_CC = gcc
ac_ct_CXX = g++
ac_ct_DUMPBIN =
am__include = include
am__leading_dot = .
am__quote =
am__tar = ${AMTAR} chof - "$$tardir"
am__untar = ${AMTAR} xf -
authdir = /var/mdm
bindir = ${exec_prefix}/bin
build = x86_64-pc-linux-gnu
build_alias = x86_64-linux-gnu
build_cpu = x86_64
build_os = linux-gnu
build_vendor = pc
builddir = .
cachedir = /var/cache/mdm
datadir = ${datarootdir}
datarootdir = ${prefix}/share
dmconfdir = /etc/dm
docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
dvidir = ${docdir}
exec_prefix = ${prefix}
host = x86_64-pc-linux-gnu
host_alias =
host_cpu = x86_64
host_os = linux-gnu
host_vendor = pc
htmldir = ${docdir}
includedir = ${prefix}/include
infodir = ${prefix}/share/info
install_sh = ${SHELL} /home/gfunkmonk/Desktop/tmp/mdm/mate-display-manager-1.0.8/install-sh
libdir = ${exec_prefix}/lib
libexecdir = ${prefix}/lib/mate-display-manager
localedir = ${datarootdir}/locale
localstatedir = /var
logdir = /var/log/mdm
mandir = ${prefix}/share/man
mdmconfdir = ${sysconfdir}/${sysconfsubdir}
mdmlocaledir = ${sysconfdir}/${sysconfsubdir}
mkdir_p = /bin/mkdir -p
oldincludedir = /usr/include
pdfdir = ${docdir}
pixmapdir = ${datarootdir}/pixmaps
prefix = /usr
program_transform_name = s,x,x,
psdir = ${docdir}
sbindir = ${exec_prefix}/sbin
sharedstatedir = ${prefix}/com
srcdir = .
sysconfdir = /etc
sysconfsubdir = mdm
target_alias =
top_build_prefix = ../
top_builddir = ..
top_srcdir = ..
NULL =
AM_CPPFLAGS = \
-I. \
-I.. \
-DMATELOCALEDIR=\""$(datadir)/locale"\" \
-DAUTHDIR=\"$(authdir)\" \
-DBINDIR=\"$(bindir)\" \
-DDATADIR=\"$(datadir)\" \
-DDMCONFDIR=\"$(dmconfdir)\" \
-DMDMCONFDIR=\"$(mdmconfdir)\" \
-DMDMLOCALEDIR=\"$(mdmlocaledir)\" \
-DLIBDIR=\"$(libdir)\" \
-DLIBEXECDIR=\"$(libexecdir)\" \
-DLOGDIR=\"$(logdir)\" \
-DPIXMAPDIR=\"$(pixmapdir)\" \
-DSBINDIR=\"$(sbindir)\" \
-DMATELOCALEDIR=\""$(datadir)/locale"\" \
-DMDM_DEFAULTS_CONF=\"$(MDM_DEFAULTS_CONF)\" \
-DMDM_CUSTOM_CONF=\"$(MDM_CUSTOM_CONF)\" \
-DMDM_OLD_CONF=\"$(MDM_OLD_CONF)\" \
$(COMMON_CFLAGS) \
$(NULL)
noinst_LTLIBRARIES = \
libmdmcommon.la \
$(NULL)
BUILT_SOURCES = \
mdm-settings-glue.h \
mdm-marshal.c \
mdm-marshal.h \
$(NULL)
mdmdir = $(datadir)/mdm
mdm_DATA = gdb-cmd
mdm_crash_logger_SOURCES = mdm-crash-logger.c
mdm_crash_logger_CPPFLAGS = \
$(AM_CPPFLAGS) \
$(GTHREAD_CFLAGS) \
-DG_DISABLE_DEPRECATED \
-DBINDIR=\"$(bindir)\" \
-DSBINDIR=\"$(sbindir)\" \
-DDATADIR=\"$(datadir)\" \
-DSYSCONFDIR=\"$(sysconfdir)\" \
-DLOCALSTATEDIR=\"$(localstatedir)\" \
$(NULL)
mdm_crash_logger_LDADD = $(GTHREAD_LIBS)
MKDTEMP_FILES =
#MKDTEMP_FILES = mkdtemp.c mkdtemp.h
libmdmcommon_la_SOURCES = \
mdm-address.h \
mdm-address.c \
mdm-common.h \
mdm-common.c \
mdm-common-unknown-origin.h \
mdm-common-unknown-origin.c \
mdm-profile.c \
mdm-profile.h \
mdm-settings.c \
mdm-settings.h \
mdm-settings-backend.c \
mdm-settings-backend.h \
mdm-settings-desktop-backend.c \
mdm-settings-desktop-backend.h \
mdm-settings-keys.h \
mdm-settings-utils.h \
mdm-settings-utils.c \
mdm-settings-direct.c \
mdm-settings-direct.h \
mdm-settings-client.h \
mdm-settings-client.c \
mdm-log.h \
mdm-log.c \
mdm-md5.h \
mdm-md5.c \
mdm-signal-handler.h \
mdm-signal-handler.c \
$(MKDTEMP_FILES) \
$(NULL)
nodist_libmdmcommon_la_SOURCES = \
mdm-marshal.c \
mdm-marshal.h
libmdmcommon_la_CPPFLAGS = \
$(AM_CPPFLAGS) \
$(DISABLE_DEPRECATED_CFLAGS) \
$(NULL)
libmdmcommon_la_CFLAGS = \
$(COMMON_CFLAGS) \
$(NULL)
libmdmcommon_la_LIBADD = \
$(COMMON_LIBS) \
$(NULL)
libmdmcommon_la_LDFLAGS = \
-export-dynamic \
$(NULL)
test_log_SOURCES = \
test-log.c \
$(NULL)
test_log_LDADD = \
libmdmcommon.la \
$(COMMON_LIBS) \
$(NULL)
test_settings_server_SOURCES = \
test-settings-server.c \
$(NULL)
test_settings_server_LDADD = \
libmdmcommon.la \
$(COMMON_LIBS) \
$(NULL)
test_settings_client_SOURCES = \
test-settings-client.c \
$(NULL)
test_settings_client_LDADD = \
libmdmcommon.la \
$(COMMON_LIBS) \
$(NULL)
CLEANFILES = \
$(BUILT_SOURCES) \
$(NULL)
EXTRA_DIST = \
mdm-settings.xml \
mdm-marshal.list \
mkdtemp.c \
mkdtemp.h \
$(mdm_DATA) \
$(NULL)
all: $(BUILT_SOURCES)
$(MAKE) $(AM_MAKEFLAGS) all-am
.SUFFIXES:
.SUFFIXES: .c .lo .o .obj
$(srcdir)/Makefile.in: # $(srcdir)/Makefile.am $(am__configure_deps)
@for dep in $?; do \
case '$(am__configure_deps)' in \
*$$dep*) \
( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
&& { if test -f $@; then exit 0; else break; fi; }; \
exit 1;; \
esac; \
done; \
echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu common/Makefile'; \
$(am__cd) $(top_srcdir) && \
$(AUTOMAKE) --gnu common/Makefile
.PRECIOUS: Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
@case '$?' in \
*config.status*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
*) \
echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
esac;
$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(top_srcdir)/configure: # $(am__configure_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(ACLOCAL_M4): # $(am__aclocal_m4_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(am__aclocal_m4_deps):
clean-noinstLTLIBRARIES:
-test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES)
@list='$(noinst_LTLIBRARIES)'; for p in $$list; do \
dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
test "$$dir" != "$$p" || dir=.; \
echo "rm -f \"$${dir}/so_locations\""; \
rm -f "$${dir}/so_locations"; \
done
libmdmcommon.la: $(libmdmcommon_la_OBJECTS) $(libmdmcommon_la_DEPENDENCIES)
$(AM_V_CCLD)$(libmdmcommon_la_LINK) $(libmdmcommon_la_OBJECTS) $(libmdmcommon_la_LIBADD) $(LIBS)
install-libexecPROGRAMS: $(libexec_PROGRAMS)
@$(NORMAL_INSTALL)
test -z "$(libexecdir)" || $(MKDIR_P) "$(DESTDIR)$(libexecdir)"
@list='$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=; \
for p in $$list; do echo "$$p $$p"; done | \
sed 's/$(EXEEXT)$$//' | \
while read p p1; do if test -f $$p || test -f $$p1; \
then echo "$$p"; echo "$$p"; else :; fi; \
done | \
sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
-e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
sed 'N;N;N;s,\n, ,g' | \
$(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \
{ d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \
if ($$2 == $$4) files[d] = files[d] " " $$1; \
else { print "f", $$3 "/" $$4, $$1; } } \
END { for (d in files) print "f", d, files[d] }' | \
while read type dir files; do \
if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \
test -z "$$files" || { \
echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(libexecdir)$$dir'"; \
$(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(libexecdir)$$dir" || exit $$?; \
} \
; done
uninstall-libexecPROGRAMS:
@$(NORMAL_UNINSTALL)
@list='$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=; \
files=`for p in $$list; do echo "$$p"; done | \
sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
-e 's/$$/$(EXEEXT)/' `; \
test -n "$$list" || exit 0; \
echo " ( cd '$(DESTDIR)$(libexecdir)' && rm -f" $$files ")"; \
cd "$(DESTDIR)$(libexecdir)" && rm -f $$files
clean-libexecPROGRAMS:
@list='$(libexec_PROGRAMS)'; test -n "$$list" || exit 0; \
echo " rm -f" $$list; \
rm -f $$list || exit $$?; \
test -n "$(EXEEXT)" || exit 0; \
list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
echo " rm -f" $$list; \
rm -f $$list
clean-noinstPROGRAMS:
@list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \
echo " rm -f" $$list; \
rm -f $$list || exit $$?; \
test -n "$(EXEEXT)" || exit 0; \
list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
echo " rm -f" $$list; \
rm -f $$list
mdm-crash-logger$(EXEEXT): $(mdm_crash_logger_OBJECTS) $(mdm_crash_logger_DEPENDENCIES)
@rm -f mdm-crash-logger$(EXEEXT)
$(AM_V_CCLD)$(LINK) $(mdm_crash_logger_OBJECTS) $(mdm_crash_logger_LDADD) $(LIBS)
test-log$(EXEEXT): $(test_log_OBJECTS) $(test_log_DEPENDENCIES)
@rm -f test-log$(EXEEXT)
$(AM_V_CCLD)$(LINK) $(test_log_OBJECTS) $(test_log_LDADD) $(LIBS)
test-settings-client$(EXEEXT): $(test_settings_client_OBJECTS) $(test_settings_client_DEPENDENCIES)
@rm -f test-settings-client$(EXEEXT)
$(AM_V_CCLD)$(LINK) $(test_settings_client_OBJECTS) $(test_settings_client_LDADD) $(LIBS)
test-settings-server$(EXEEXT): $(test_settings_server_OBJECTS) $(test_settings_server_DEPENDENCIES)
@rm -f test-settings-server$(EXEEXT)
$(AM_V_CCLD)$(LINK) $(test_settings_server_OBJECTS) $(test_settings_server_LDADD) $(LIBS)
mostlyclean-compile:
-rm -f *.$(OBJEXT)
distclean-compile:
-rm -f *.tab.c
#include ./$(DEPDIR)/libmdmcommon_la-mdm-address.Plo
#include ./$(DEPDIR)/libmdmcommon_la-mdm-common-unknown-origin.Plo
#include ./$(DEPDIR)/libmdmcommon_la-mdm-common.Plo
#include ./$(DEPDIR)/libmdmcommon_la-mdm-log.Plo
#include ./$(DEPDIR)/libmdmcommon_la-mdm-marshal.Plo
#include ./$(DEPDIR)/libmdmcommon_la-mdm-md5.Plo
#include ./$(DEPDIR)/libmdmcommon_la-mdm-profile.Plo
#include ./$(DEPDIR)/libmdmcommon_la-mdm-settings-backend.Plo
#include ./$(DEPDIR)/libmdmcommon_la-mdm-settings-client.Plo
#include ./$(DEPDIR)/libmdmcommon_la-mdm-settings-desktop-backend.Plo
#include ./$(DEPDIR)/libmdmcommon_la-mdm-settings-direct.Plo
#include ./$(DEPDIR)/libmdmcommon_la-mdm-settings-utils.Plo
#include ./$(DEPDIR)/libmdmcommon_la-mdm-settings.Plo
#include ./$(DEPDIR)/libmdmcommon_la-mdm-signal-handler.Plo
#include ./$(DEPDIR)/libmdmcommon_la-mkdtemp.Plo
#include ./$(DEPDIR)/mdm_crash_logger-mdm-crash-logger.Po
#include ./$(DEPDIR)/test-log.Po
#include ./$(DEPDIR)/test-settings-client.Po
#include ./$(DEPDIR)/test-settings-server.Po
.c.o:
# $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
# $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
$(AM_V_CC) \
# source='$<' object='$@' libtool=no
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(COMPILE) -c $<
.c.obj:
# $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
# $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
$(AM_V_CC) \
# source='$<' object='$@' libtool=no
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(COMPILE) -c `$(CYGPATH_W) '$<'`
.c.lo:
# $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
# $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
$(AM_V_CC) \
# source='$<' object='$@' libtool=yes
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(LTCOMPILE) -c -o $@ $<
libmdmcommon_la-mdm-address.lo: mdm-address.c
# $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -MT libmdmcommon_la-mdm-address.lo -MD -MP -MF $(DEPDIR)/libmdmcommon_la-mdm-address.Tpo -c -o libmdmcommon_la-mdm-address.lo `test -f 'mdm-address.c' || echo '$(srcdir)/'`mdm-address.c
# $(AM_V_at)$(am__mv) $(DEPDIR)/libmdmcommon_la-mdm-address.Tpo $(DEPDIR)/libmdmcommon_la-mdm-address.Plo
$(AM_V_CC) \
# source='mdm-address.c' object='libmdmcommon_la-mdm-address.lo' libtool=yes
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -c -o libmdmcommon_la-mdm-address.lo `test -f 'mdm-address.c' || echo '$(srcdir)/'`mdm-address.c
libmdmcommon_la-mdm-common.lo: mdm-common.c
# $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -MT libmdmcommon_la-mdm-common.lo -MD -MP -MF $(DEPDIR)/libmdmcommon_la-mdm-common.Tpo -c -o libmdmcommon_la-mdm-common.lo `test -f 'mdm-common.c' || echo '$(srcdir)/'`mdm-common.c
# $(AM_V_at)$(am__mv) $(DEPDIR)/libmdmcommon_la-mdm-common.Tpo $(DEPDIR)/libmdmcommon_la-mdm-common.Plo
$(AM_V_CC) \
# source='mdm-common.c' object='libmdmcommon_la-mdm-common.lo' libtool=yes
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -c -o libmdmcommon_la-mdm-common.lo `test -f 'mdm-common.c' || echo '$(srcdir)/'`mdm-common.c
libmdmcommon_la-mdm-common-unknown-origin.lo: mdm-common-unknown-origin.c
# $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -MT libmdmcommon_la-mdm-common-unknown-origin.lo -MD -MP -MF $(DEPDIR)/libmdmcommon_la-mdm-common-unknown-origin.Tpo -c -o libmdmcommon_la-mdm-common-unknown-origin.lo `test -f 'mdm-common-unknown-origin.c' || echo '$(srcdir)/'`mdm-common-unknown-origin.c
# $(AM_V_at)$(am__mv) $(DEPDIR)/libmdmcommon_la-mdm-common-unknown-origin.Tpo $(DEPDIR)/libmdmcommon_la-mdm-common-unknown-origin.Plo
$(AM_V_CC) \
# source='mdm-common-unknown-origin.c' object='libmdmcommon_la-mdm-common-unknown-origin.lo' libtool=yes
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -c -o libmdmcommon_la-mdm-common-unknown-origin.lo `test -f 'mdm-common-unknown-origin.c' || echo '$(srcdir)/'`mdm-common-unknown-origin.c
libmdmcommon_la-mdm-profile.lo: mdm-profile.c
# $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -MT libmdmcommon_la-mdm-profile.lo -MD -MP -MF $(DEPDIR)/libmdmcommon_la-mdm-profile.Tpo -c -o libmdmcommon_la-mdm-profile.lo `test -f 'mdm-profile.c' || echo '$(srcdir)/'`mdm-profile.c
# $(AM_V_at)$(am__mv) $(DEPDIR)/libmdmcommon_la-mdm-profile.Tpo $(DEPDIR)/libmdmcommon_la-mdm-profile.Plo
$(AM_V_CC) \
# source='mdm-profile.c' object='libmdmcommon_la-mdm-profile.lo' libtool=yes
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -c -o libmdmcommon_la-mdm-profile.lo `test -f 'mdm-profile.c' || echo '$(srcdir)/'`mdm-profile.c
libmdmcommon_la-mdm-settings.lo: mdm-settings.c
# $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -MT libmdmcommon_la-mdm-settings.lo -MD -MP -MF $(DEPDIR)/libmdmcommon_la-mdm-settings.Tpo -c -o libmdmcommon_la-mdm-settings.lo `test -f 'mdm-settings.c' || echo '$(srcdir)/'`mdm-settings.c
# $(AM_V_at)$(am__mv) $(DEPDIR)/libmdmcommon_la-mdm-settings.Tpo $(DEPDIR)/libmdmcommon_la-mdm-settings.Plo
$(AM_V_CC) \
# source='mdm-settings.c' object='libmdmcommon_la-mdm-settings.lo' libtool=yes
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -c -o libmdmcommon_la-mdm-settings.lo `test -f 'mdm-settings.c' || echo '$(srcdir)/'`mdm-settings.c
libmdmcommon_la-mdm-settings-backend.lo: mdm-settings-backend.c
# $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -MT libmdmcommon_la-mdm-settings-backend.lo -MD -MP -MF $(DEPDIR)/libmdmcommon_la-mdm-settings-backend.Tpo -c -o libmdmcommon_la-mdm-settings-backend.lo `test -f 'mdm-settings-backend.c' || echo '$(srcdir)/'`mdm-settings-backend.c
# $(AM_V_at)$(am__mv) $(DEPDIR)/libmdmcommon_la-mdm-settings-backend.Tpo $(DEPDIR)/libmdmcommon_la-mdm-settings-backend.Plo
$(AM_V_CC) \
# source='mdm-settings-backend.c' object='libmdmcommon_la-mdm-settings-backend.lo' libtool=yes
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -c -o libmdmcommon_la-mdm-settings-backend.lo `test -f 'mdm-settings-backend.c' || echo '$(srcdir)/'`mdm-settings-backend.c
libmdmcommon_la-mdm-settings-desktop-backend.lo: mdm-settings-desktop-backend.c
# $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -MT libmdmcommon_la-mdm-settings-desktop-backend.lo -MD -MP -MF $(DEPDIR)/libmdmcommon_la-mdm-settings-desktop-backend.Tpo -c -o libmdmcommon_la-mdm-settings-desktop-backend.lo `test -f 'mdm-settings-desktop-backend.c' || echo '$(srcdir)/'`mdm-settings-desktop-backend.c
# $(AM_V_at)$(am__mv) $(DEPDIR)/libmdmcommon_la-mdm-settings-desktop-backend.Tpo $(DEPDIR)/libmdmcommon_la-mdm-settings-desktop-backend.Plo
$(AM_V_CC) \
# source='mdm-settings-desktop-backend.c' object='libmdmcommon_la-mdm-settings-desktop-backend.lo' libtool=yes
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -c -o libmdmcommon_la-mdm-settings-desktop-backend.lo `test -f 'mdm-settings-desktop-backend.c' || echo '$(srcdir)/'`mdm-settings-desktop-backend.c
libmdmcommon_la-mdm-settings-utils.lo: mdm-settings-utils.c
# $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -MT libmdmcommon_la-mdm-settings-utils.lo -MD -MP -MF $(DEPDIR)/libmdmcommon_la-mdm-settings-utils.Tpo -c -o libmdmcommon_la-mdm-settings-utils.lo `test -f 'mdm-settings-utils.c' || echo '$(srcdir)/'`mdm-settings-utils.c
# $(AM_V_at)$(am__mv) $(DEPDIR)/libmdmcommon_la-mdm-settings-utils.Tpo $(DEPDIR)/libmdmcommon_la-mdm-settings-utils.Plo
$(AM_V_CC) \
# source='mdm-settings-utils.c' object='libmdmcommon_la-mdm-settings-utils.lo' libtool=yes
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -c -o libmdmcommon_la-mdm-settings-utils.lo `test -f 'mdm-settings-utils.c' || echo '$(srcdir)/'`mdm-settings-utils.c
libmdmcommon_la-mdm-settings-direct.lo: mdm-settings-direct.c
# $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -MT libmdmcommon_la-mdm-settings-direct.lo -MD -MP -MF $(DEPDIR)/libmdmcommon_la-mdm-settings-direct.Tpo -c -o libmdmcommon_la-mdm-settings-direct.lo `test -f 'mdm-settings-direct.c' || echo '$(srcdir)/'`mdm-settings-direct.c
# $(AM_V_at)$(am__mv) $(DEPDIR)/libmdmcommon_la-mdm-settings-direct.Tpo $(DEPDIR)/libmdmcommon_la-mdm-settings-direct.Plo
$(AM_V_CC) \
# source='mdm-settings-direct.c' object='libmdmcommon_la-mdm-settings-direct.lo' libtool=yes
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -c -o libmdmcommon_la-mdm-settings-direct.lo `test -f 'mdm-settings-direct.c' || echo '$(srcdir)/'`mdm-settings-direct.c
libmdmcommon_la-mdm-settings-client.lo: mdm-settings-client.c
# $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -MT libmdmcommon_la-mdm-settings-client.lo -MD -MP -MF $(DEPDIR)/libmdmcommon_la-mdm-settings-client.Tpo -c -o libmdmcommon_la-mdm-settings-client.lo `test -f 'mdm-settings-client.c' || echo '$(srcdir)/'`mdm-settings-client.c
# $(AM_V_at)$(am__mv) $(DEPDIR)/libmdmcommon_la-mdm-settings-client.Tpo $(DEPDIR)/libmdmcommon_la-mdm-settings-client.Plo
$(AM_V_CC) \
# source='mdm-settings-client.c' object='libmdmcommon_la-mdm-settings-client.lo' libtool=yes
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -c -o libmdmcommon_la-mdm-settings-client.lo `test -f 'mdm-settings-client.c' || echo '$(srcdir)/'`mdm-settings-client.c
libmdmcommon_la-mdm-log.lo: mdm-log.c
# $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -MT libmdmcommon_la-mdm-log.lo -MD -MP -MF $(DEPDIR)/libmdmcommon_la-mdm-log.Tpo -c -o libmdmcommon_la-mdm-log.lo `test -f 'mdm-log.c' || echo '$(srcdir)/'`mdm-log.c
# $(AM_V_at)$(am__mv) $(DEPDIR)/libmdmcommon_la-mdm-log.Tpo $(DEPDIR)/libmdmcommon_la-mdm-log.Plo
$(AM_V_CC) \
# source='mdm-log.c' object='libmdmcommon_la-mdm-log.lo' libtool=yes
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -c -o libmdmcommon_la-mdm-log.lo `test -f 'mdm-log.c' || echo '$(srcdir)/'`mdm-log.c
libmdmcommon_la-mdm-md5.lo: mdm-md5.c
# $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -MT libmdmcommon_la-mdm-md5.lo -MD -MP -MF $(DEPDIR)/libmdmcommon_la-mdm-md5.Tpo -c -o libmdmcommon_la-mdm-md5.lo `test -f 'mdm-md5.c' || echo '$(srcdir)/'`mdm-md5.c
# $(AM_V_at)$(am__mv) $(DEPDIR)/libmdmcommon_la-mdm-md5.Tpo $(DEPDIR)/libmdmcommon_la-mdm-md5.Plo
$(AM_V_CC) \
# source='mdm-md5.c' object='libmdmcommon_la-mdm-md5.lo' libtool=yes
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -c -o libmdmcommon_la-mdm-md5.lo `test -f 'mdm-md5.c' || echo '$(srcdir)/'`mdm-md5.c
libmdmcommon_la-mdm-signal-handler.lo: mdm-signal-handler.c
# $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -MT libmdmcommon_la-mdm-signal-handler.lo -MD -MP -MF $(DEPDIR)/libmdmcommon_la-mdm-signal-handler.Tpo -c -o libmdmcommon_la-mdm-signal-handler.lo `test -f 'mdm-signal-handler.c' || echo '$(srcdir)/'`mdm-signal-handler.c
# $(AM_V_at)$(am__mv) $(DEPDIR)/libmdmcommon_la-mdm-signal-handler.Tpo $(DEPDIR)/libmdmcommon_la-mdm-signal-handler.Plo
$(AM_V_CC) \
# source='mdm-signal-handler.c' object='libmdmcommon_la-mdm-signal-handler.lo' libtool=yes
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -c -o libmdmcommon_la-mdm-signal-handler.lo `test -f 'mdm-signal-handler.c' || echo '$(srcdir)/'`mdm-signal-handler.c
libmdmcommon_la-mkdtemp.lo: mkdtemp.c
# $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -MT libmdmcommon_la-mkdtemp.lo -MD -MP -MF $(DEPDIR)/libmdmcommon_la-mkdtemp.Tpo -c -o libmdmcommon_la-mkdtemp.lo `test -f 'mkdtemp.c' || echo '$(srcdir)/'`mkdtemp.c
# $(AM_V_at)$(am__mv) $(DEPDIR)/libmdmcommon_la-mkdtemp.Tpo $(DEPDIR)/libmdmcommon_la-mkdtemp.Plo
$(AM_V_CC) \
# source='mkdtemp.c' object='libmdmcommon_la-mkdtemp.lo' libtool=yes
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -c -o libmdmcommon_la-mkdtemp.lo `test -f 'mkdtemp.c' || echo '$(srcdir)/'`mkdtemp.c
libmdmcommon_la-mdm-marshal.lo: mdm-marshal.c
# $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -MT libmdmcommon_la-mdm-marshal.lo -MD -MP -MF $(DEPDIR)/libmdmcommon_la-mdm-marshal.Tpo -c -o libmdmcommon_la-mdm-marshal.lo `test -f 'mdm-marshal.c' || echo '$(srcdir)/'`mdm-marshal.c
# $(AM_V_at)$(am__mv) $(DEPDIR)/libmdmcommon_la-mdm-marshal.Tpo $(DEPDIR)/libmdmcommon_la-mdm-marshal.Plo
$(AM_V_CC) \
# source='mdm-marshal.c' object='libmdmcommon_la-mdm-marshal.lo' libtool=yes
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmdmcommon_la_CPPFLAGS) $(CPPFLAGS) $(libmdmcommon_la_CFLAGS) $(CFLAGS) -c -o libmdmcommon_la-mdm-marshal.lo `test -f 'mdm-marshal.c' || echo '$(srcdir)/'`mdm-marshal.c
mdm_crash_logger-mdm-crash-logger.o: mdm-crash-logger.c
# $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(mdm_crash_logger_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT mdm_crash_logger-mdm-crash-logger.o -MD -MP -MF $(DEPDIR)/mdm_crash_logger-mdm-crash-logger.Tpo -c -o mdm_crash_logger-mdm-crash-logger.o `test -f 'mdm-crash-logger.c' || echo '$(srcdir)/'`mdm-crash-logger.c
# $(AM_V_at)$(am__mv) $(DEPDIR)/mdm_crash_logger-mdm-crash-logger.Tpo $(DEPDIR)/mdm_crash_logger-mdm-crash-logger.Po
$(AM_V_CC) \
# source='mdm-crash-logger.c' object='mdm_crash_logger-mdm-crash-logger.o' libtool=no
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(mdm_crash_logger_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o mdm_crash_logger-mdm-crash-logger.o `test -f 'mdm-crash-logger.c' || echo '$(srcdir)/'`mdm-crash-logger.c
mdm_crash_logger-mdm-crash-logger.obj: mdm-crash-logger.c
# $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(mdm_crash_logger_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT mdm_crash_logger-mdm-crash-logger.obj -MD -MP -MF $(DEPDIR)/mdm_crash_logger-mdm-crash-logger.Tpo -c -o mdm_crash_logger-mdm-crash-logger.obj `if test -f 'mdm-crash-logger.c'; then $(CYGPATH_W) 'mdm-crash-logger.c'; else $(CYGPATH_W) '$(srcdir)/mdm-crash-logger.c'; fi`
# $(AM_V_at)$(am__mv) $(DEPDIR)/mdm_crash_logger-mdm-crash-logger.Tpo $(DEPDIR)/mdm_crash_logger-mdm-crash-logger.Po
$(AM_V_CC) \
# source='mdm-crash-logger.c' object='mdm_crash_logger-mdm-crash-logger.obj' libtool=no
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(mdm_crash_logger_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o mdm_crash_logger-mdm-crash-logger.obj `if test -f 'mdm-crash-logger.c'; then $(CYGPATH_W) 'mdm-crash-logger.c'; else $(CYGPATH_W) '$(srcdir)/mdm-crash-logger.c'; fi`
mostlyclean-libtool:
-rm -f *.lo
clean-libtool:
-rm -rf .libs _libs
install-mdmDATA: $(mdm_DATA)
@$(NORMAL_INSTALL)
test -z "$(mdmdir)" || $(MKDIR_P) "$(DESTDIR)$(mdmdir)"
@list='$(mdm_DATA)'; test -n "$(mdmdir)" || list=; \
for p in $$list; do \
if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
echo "$$d$$p"; \
done | $(am__base_list) | \
while read files; do \
echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(mdmdir)'"; \
$(INSTALL_DATA) $$files "$(DESTDIR)$(mdmdir)" || exit $$?; \
done
uninstall-mdmDATA:
@$(NORMAL_UNINSTALL)
@list='$(mdm_DATA)'; test -n "$(mdmdir)" || list=; \
files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
test -n "$$files" || exit 0; \
echo " ( cd '$(DESTDIR)$(mdmdir)' && rm -f" $$files ")"; \
cd "$(DESTDIR)$(mdmdir)" && rm -f $$files
ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) '{ files[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in files) print i; }; }'`; \
mkid -fID $$unique
tags: TAGS
TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
$(TAGS_FILES) $(LISP)
set x; \
here=`pwd`; \
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) '{ files[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in files) print i; }; }'`; \
shift; \
if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
test -n "$$unique" || unique=$$empty_fix; \
if test $$# -gt 0; then \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
"$$@" $$unique; \
else \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
$$unique; \
fi; \
fi
ctags: CTAGS
CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
$(TAGS_FILES) $(LISP)
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) '{ files[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in files) print i; }; }'`; \
test -z "$(CTAGS_ARGS)$$unique" \
|| $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
$$unique
GTAGS:
here=`$(am__cd) $(top_builddir) && pwd` \
&& $(am__cd) $(top_srcdir) \
&& gtags -i $(GTAGS_ARGS) "$$here"
distclean-tags:
-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
distdir: $(DISTFILES)
@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
list='$(DISTFILES)'; \
dist_files=`for file in $$list; do echo $$file; done | \
sed -e "s|^$$srcdirstrip/||;t" \
-e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
case $$dist_files in \
*/*) $(MKDIR_P) `echo "$$dist_files" | \
sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
sort -u` ;; \
esac; \
for file in $$dist_files; do \
if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
if test -d $$d/$$file; then \
dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
if test -d "$(distdir)/$$file"; then \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
else \
test -f "$(distdir)/$$file" \
|| cp -p $$d/$$file "$(distdir)/$$file" \
|| exit 1; \
fi; \
done
check-am: all-am
check: $(BUILT_SOURCES)
$(MAKE) $(AM_MAKEFLAGS) check-am
all-am: Makefile $(LTLIBRARIES) $(PROGRAMS) $(DATA)
installdirs:
for dir in "$(DESTDIR)$(libexecdir)" "$(DESTDIR)$(mdmdir)"; do \
test -z "$$dir" || $(MKDIR_P) "$$dir"; \
done
install: $(BUILT_SOURCES)
$(MAKE) $(AM_MAKEFLAGS) install-am
install-exec: install-exec-am
install-data: install-data-am
uninstall: uninstall-am
install-am: all-am
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
installcheck: installcheck-am
install-strip:
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
`test -z '$(STRIP)' || \
echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
mostlyclean-generic:
clean-generic:
-test -z "$(CLEANFILES)" || rm -f $(CLEANFILES)
distclean-generic:
-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
maintainer-clean-generic:
@echo "This command is intended for maintainers to use"
@echo "it deletes files that may require special tools to rebuild."
-test -z "$(BUILT_SOURCES)" || rm -f $(BUILT_SOURCES)
clean: clean-am
clean-am: clean-generic clean-libexecPROGRAMS clean-libtool \
clean-noinstLTLIBRARIES clean-noinstPROGRAMS mostlyclean-am
distclean: distclean-am
-rm -rf ./$(DEPDIR)
-rm -f Makefile
distclean-am: clean-am distclean-compile distclean-generic \
distclean-tags
dvi: dvi-am
dvi-am:
html: html-am
html-am:
info: info-am
info-am:
install-data-am: install-mdmDATA
install-dvi: install-dvi-am
install-dvi-am:
install-exec-am: install-libexecPROGRAMS
install-html: install-html-am
install-html-am:
install-info: install-info-am
install-info-am:
install-man:
install-pdf: install-pdf-am
install-pdf-am:
install-ps: install-ps-am
install-ps-am:
installcheck-am:
maintainer-clean: maintainer-clean-am
-rm -rf ./$(DEPDIR)
-rm -f Makefile
maintainer-clean-am: distclean-am maintainer-clean-generic
mostlyclean: mostlyclean-am
mostlyclean-am: mostlyclean-compile mostlyclean-generic \
mostlyclean-libtool
pdf: pdf-am
pdf-am:
ps: ps-am
ps-am:
uninstall-am: uninstall-libexecPROGRAMS uninstall-mdmDATA
.MAKE: all check install install-am install-strip
.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
clean-libexecPROGRAMS clean-libtool clean-noinstLTLIBRARIES \
clean-noinstPROGRAMS ctags distclean distclean-compile \
distclean-generic distclean-libtool distclean-tags distdir dvi \
dvi-am html html-am info info-am install install-am \
install-data install-data-am install-dvi install-dvi-am \
install-exec install-exec-am install-html install-html-am \
install-info install-info-am install-libexecPROGRAMS \
install-man install-mdmDATA install-pdf install-pdf-am \
install-ps install-ps-am install-strip installcheck \
installcheck-am installdirs maintainer-clean \
maintainer-clean-generic mostlyclean mostlyclean-compile \
mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
tags uninstall uninstall-am uninstall-libexecPROGRAMS \
uninstall-mdmDATA
mdm-settings-glue.h: mdm-settings.xml Makefile.am
dbus-binding-tool --prefix=mdm_settings --mode=glib-server --output=mdm-settings-glue.h $(srcdir)/mdm-settings.xml
mdm-marshal.c: mdm-marshal.list
echo "#include \"mdm-marshal.h\"" > $@ && \
/usr/bin/glib-genmarshal $< --prefix=mdm_marshal --body >> $@
mdm-marshal.h: mdm-marshal.list
/usr/bin/glib-genmarshal $< --prefix=mdm_marshal --header > $@
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:
|
gfunkmonk2/mate-display-manager
|
common/Makefile
|
Makefile
|
gpl-2.0
| 54,767
|
/*
* File : usb_common.h
* This file is part of RT-Thread RTOS
* COPYRIGHT (C) 2012, RT-Thread Development Team
*
* The license and distribution terms for this file may be
* found in the file LICENSE in this distribution or at
* http://www.rt-thread.org/license/LICENSE
*
* Change Logs:
* Date Author Notes
* 2012-10-01 Yi Qiu first version
*/
#ifndef __USB_COMMON_H__
#define __USB_COMMON_H__
#ifdef __cplusplus
extern "C" {
#endif
#include <rtthread.h>
#define RT_DEBUG_USB 0x00
#define USB_DYNAMIC 0x00
#define USB_CLASS_DEVICE 0x00
#define USB_CLASS_AUDIO 0x01
#define USB_CLASS_CDC 0x02
#define USB_CLASS_HID 0x03
#define USB_CLASS_PHYSICAL 0x05
#define USB_CLASS_IMAGE 0x06
#define USB_CLASS_PRINTER 0x07
#define USB_CLASS_MASS_STORAGE 0x08
#define USB_CLASS_HUB 0x09
#define USB_CLASS_CDC_DATA 0x0a
#define USB_CLASS_SMART_CARD 0x0b
#define USB_CLASS_SECURITY 0x0d
#define USB_CLASS_VIDEO 0x0e
#define USB_CLASS_HEALTHCARE 0x0f
#define USB_CLASS_DIAG_DEVICE 0xdc
#define USB_CLASS_WIRELESS 0xe0
#define USB_CLASS_MISC 0xef
#define USB_CLASS_APP_SPECIFIC 0xfe
#define USB_CLASS_VEND_SPECIFIC 0xff
#define USB_DESC_TYPE_DEVICE 0x01
#define USB_DESC_TYPE_CONFIGURATION 0x02
#define USB_DESC_TYPE_STRING 0x03
#define USB_DESC_TYPE_INTERFACE 0x04
#define USB_DESC_TYPE_ENDPOINT 0x05
#define USB_DESC_TYPE_DEVICEQUALIFIER 0x06
#define USB_DESC_TYPE_OTHERSPEED 0x07
#define USB_DESC_TYPE_IAD 0x0b
#define USB_DESC_TYPE_HID 0x21
#define USB_DESC_TYPE_REPORT 0x22
#define USB_DESC_TYPE_PHYSICAL 0x23
#define USB_DESC_TYPE_HUB 0x29
#define USB_DESC_LENGTH_DEVICE 0x12
#define USB_DESC_LENGTH_CONFIG 0x9
#define USB_DESC_LENGTH_IAD 0x8
#define USB_DESC_LENGTH_STRING 0x4
#define USB_DESC_LENGTH_INTERFACE 0x9
#define USB_DESC_LENGTH_ENDPOINT 0x7
#define USB_REQ_TYPE_STANDARD 0x00
#define USB_REQ_TYPE_CLASS 0x20
#define USB_REQ_TYPE_VENDOR 0x40
#define USB_REQ_TYPE_MASK 0x60
#define USB_REQ_TYPE_DIR_OUT 0x00
#define USB_REQ_TYPE_DIR_IN 0x80
#define USB_REQ_TYPE_DEVICE 0x00
#define USB_REQ_TYPE_INTERFACE 0x01
#define USB_REQ_TYPE_ENDPOINT 0x02
#define USB_REQ_TYPE_OTHER 0x03
#define USB_REQ_TYPE_RECIPIENT_MASK 0x1f
#define USB_FEATURE_ENDPOINT_HALT 0x00
#define USB_FEATURE_DEV_REMOTE_WAKEUP 0x01
#define USB_FEATURE_TEST_MODE 0x02
#define USB_REQ_GET_STATUS 0x00
#define USB_REQ_CLEAR_FEATURE 0x01
#define USB_REQ_SET_FEATURE 0x03
#define USB_REQ_SET_ADDRESS 0x05
#define USB_REQ_GET_DESCRIPTOR 0x06
#define USB_REQ_SET_DESCRIPTOR 0x07
#define USB_REQ_GET_CONFIGURATION 0x08
#define USB_REQ_SET_CONFIGURATION 0x09
#define USB_REQ_GET_INTERFACE 0x0A
#define USB_REQ_SET_INTERFACE 0x0B
#define USB_REQ_SYNCH_FRAME 0x0C
#define USB_REQ_SET_ENCRYPTION 0x0D
#define USB_REQ_GET_ENCRYPTION 0x0E
#define USB_REQ_RPIPE_ABORT 0x0E
#define USB_REQ_SET_HANDSHAKE 0x0F
#define USB_REQ_RPIPE_RESET 0x0F
#define USB_REQ_GET_HANDSHAKE 0x10
#define USB_REQ_SET_CONNECTION 0x11
#define USB_REQ_SET_SECURITY_DATA 0x12
#define USB_REQ_GET_SECURITY_DATA 0x13
#define USB_REQ_SET_WUSB_DATA 0x14
#define USB_REQ_LOOPBACK_DATA_WRITE 0x15
#define USB_REQ_LOOPBACK_DATA_READ 0x16
#define USB_REQ_SET_INTERFACE_DS 0x17
#define USB_STRING_LANGID_INDEX 0x00
#define USB_STRING_MANU_INDEX 0x01
#define USB_STRING_PRODUCT_INDEX 0x02
#define USB_STRING_SERIAL_INDEX 0x03
#define USB_STRING_CONFIG_INDEX 0x04
#define USB_STRING_INTERFACE_INDEX 0x05
#define USB_PID_OUT 0x01
#define USB_PID_ACK 0x02
#define USB_PID_DATA0 0x03
#define USB_PID_SOF 0x05
#define USB_PID_IN 0x09
#define USB_PID_NACK 0x0A
#define USB_PID_DATA1 0x0B
#define USB_PID_PRE 0x0C
#define USB_PID_SETUP 0x0D
#define USB_PID_STALL 0x0E
#define USB_EP_DESC_OUT 0x00
#define USB_EP_DESC_IN 0x80
#define USB_EP_DESC_NUM_MASK 0x0f
#define USB_EP_ATTR_CONTROL 0x00
#define USB_EP_ATTR_ISOC 0x01
#define USB_EP_ATTR_BULK 0x02
#define USB_EP_ATTR_INT 0x03
#define USB_EP_ATTR_TYPE_MASK 0x03
#define USB_EPNO_MASK 0x7f
#define USB_DIR_OUT 0x00
#define USB_DIR_IN 0x80
#define USB_DIR_MASK 0x80
#define RH_GET_PORT_STATUS 0
#define RH_SET_PORT_STATUS 1
#define RH_CLEAR_PORT_FEATURE 2
#define RH_SET_PORT_FEATURE 3
/*
* Port feature numbers
*/
#define PORT_FEAT_CONNECTION 0
#define PORT_FEAT_ENABLE 1
#define PORT_FEAT_SUSPEND 2
#define PORT_FEAT_OVER_CURRENT 3
#define PORT_FEAT_RESET 4
#define PORT_FEAT_POWER 8
#define PORT_FEAT_LOWSPEED 9
#define PORT_FEAT_HIGHSPEED 10
#define PORT_FEAT_C_CONNECTION 16
#define PORT_FEAT_C_ENABLE 17
#define PORT_FEAT_C_SUSPEND 18
#define PORT_FEAT_C_OVER_CURRENT 19
#define PORT_FEAT_C_RESET 20
/*
The HcRhPortStatus[1:NDP] register is used to control and report port events on a per-port
basis. NumberDownstreamPorts represents the number of HcRhPortStatus registers that are
implemented in hardware. The lower word is used to reflect the port status, whereas the upper
word reflects the status change bits. Some status bits are implemented with special write behavior
(see below). If a transaction (token through handshake) is in progress when a write to change
port status occurs, the resulting port status change must be postponed until the transaction
completes. Reserved bits should always be written '0'.
*/
#define PORT_CCS 0x00000001UL /* R:CurrentConnectStatus - W:ClearPortEnable */
#define PORT_PES 0x00000002UL /* R:PortEnableStatus - W:SetPortEnable */
#define PORT_PSS 0x00000004UL /* R:PortSuspendStatus - W:SetPortSuspend */
#define PORT_POCI 0x00000008UL /* R:PortOverCurrentIndicator - W:ClearSuspendStatus */
#define PORT_PRS 0x00000010UL /* R:PortResetStatus - W: SetPortReset */
#define PORT_PPS 0x00000100UL /* R:PortPowerStatus - W: SetPortPower */
#define PORT_LSDA 0x00000200UL /* R:LowSpeedDeviceAttached - W:ClearPortPower */
#define PORT_CCSC 0x00010000UL
#define PORT_PESC 0x00020000UL
#define PORT_PSSC 0x00040000UL
#define PORT_POCIC 0x00080000UL
#define PORT_PRSC 0x00100000UL
/*
*Hub Status & Hub Change bit masks
*/
#define HUB_STATUS_LOCAL_POWER 0x0001
#define HUB_STATUS_OVERCURRENT 0x0002
#define HUB_CHANGE_LOCAL_POWER 0x0001
#define HUB_CHANGE_OVERCURRENT 0x0002
#define USB_EP_ATTR(attr) (attr & USB_EP_ATTR_TYPE_MASK)
#define USB_EP_DESC_NUM(addr) (addr & USB_EP_DESC_NUM_MASK)
#define uswap_32(x) \
((((x) & 0xff000000) >> 24) | \
(((x) & 0x00ff0000) >> 8) | \
(((x) & 0x0000ff00) << 8) | \
(((x) & 0x000000ff) << 24))
#define uswap_8(x) \
(((rt_uint16_t)(*((rt_uint8_t *)(x)))) + \
(((rt_uint16_t)(*(((rt_uint8_t *)(x)) + 1))) << 8))
typedef void (*func_callback)(void *context);
typedef enum
{
USB_STATE_NOTATTACHED = 0,
USB_STATE_ATTACHED,
USB_STATE_POWERED,
USB_STATE_RECONNECTING,
USB_STATE_UNAUTHENTICATED,
USB_STATE_DEFAULT,
USB_STATE_ADDRESS,
USB_STATE_CONFIGURED,
USB_STATE_SUSPENDED
}udevice_state_t;
#pragma pack(1)
struct usb_descriptor
{
rt_uint8_t bLength;
rt_uint8_t type;
};
typedef struct usb_descriptor* udesc_t;
struct udevice_descriptor
{
rt_uint8_t bLength;
rt_uint8_t type;
rt_uint16_t bcdUSB;
rt_uint8_t bDeviceClass;
rt_uint8_t bDeviceSubClass;
rt_uint8_t bDeviceProtocol;
rt_uint8_t bMaxPacketSize0;
rt_uint16_t idVendor;
rt_uint16_t idProduct;
rt_uint16_t bcdDevice;
rt_uint8_t iManufacturer;
rt_uint8_t iProduct;
rt_uint8_t iSerialNumber;
rt_uint8_t bNumConfigurations;
};
typedef struct udevice_descriptor* udev_desc_t;
struct uconfig_descriptor
{
rt_uint8_t bLength;
rt_uint8_t type;
rt_uint16_t wTotalLength;
rt_uint8_t bNumInterfaces;
rt_uint8_t bConfigurationValue;
rt_uint8_t iConfiguration;
rt_uint8_t bmAttributes;
rt_uint8_t MaxPower;
rt_uint8_t data[256];
};
typedef struct uconfig_descriptor* ucfg_desc_t;
struct uinterface_descriptor
{
rt_uint8_t bLength;
rt_uint8_t type;
rt_uint8_t bInterfaceNumber;
rt_uint8_t bAlternateSetting;
rt_uint8_t bNumEndpoints;
rt_uint8_t bInterfaceClass;
rt_uint8_t bInterfaceSubClass;
rt_uint8_t bInterfaceProtocol;
rt_uint8_t iInterface;
};
typedef struct uinterface_descriptor* uintf_desc_t;
/* Interface Association Descriptor (IAD) */
struct uiad_descriptor
{
rt_uint8_t bLength;
rt_uint8_t bDescriptorType;
rt_uint8_t bFirstInterface;
rt_uint8_t bInterfaceCount;
rt_uint8_t bFunctionClass;
rt_uint8_t bFunctionSubClass;
rt_uint8_t bFunctionProtocol;
rt_uint8_t iFunction;
};
typedef struct uiad_descriptor* uiad_desc_t;
struct uendpoint_descriptor
{
rt_uint8_t bLength;
rt_uint8_t type;
rt_uint8_t bEndpointAddress;
rt_uint8_t bmAttributes;
rt_uint16_t wMaxPacketSize;
rt_uint8_t bInterval;
};
typedef struct uendpoint_descriptor* uep_desc_t;
struct ustring_descriptor
{
rt_uint8_t bLength;
rt_uint8_t type;
rt_uint8_t String[64];
};
typedef struct ustring_descriptor* ustr_desc_t;
struct uhub_descriptor
{
rt_uint8_t length;
rt_uint8_t type;
rt_uint8_t num_ports;
rt_uint16_t characteristics;
rt_uint8_t pwron_to_good; /* power on to power good */
rt_uint8_t current;
rt_uint8_t removable[8];
rt_uint8_t pwr_ctl[8];
};
typedef struct uhub_descriptor* uhub_desc_t;
struct uhid_descriptor
{
rt_uint8_t bLength;
rt_uint8_t type;
rt_uint16_t bcdHID;
rt_uint8_t bCountryCode;
rt_uint8_t bNumDescriptors;
struct hid_descriptor_list
{
rt_uint8_t type;
rt_uint16_t wLength;
}Descriptor[1];
};
typedef struct uhid_descriptor* uhid_desc_t;
struct ureqest
{
rt_uint8_t request_type;
rt_uint8_t request;
rt_uint16_t value;
rt_uint16_t index;
rt_uint16_t length;
};
typedef struct ureqest* ureq_t;
#define MIN(a, b) (a < b ? a : b)
#define MAX(a, b) (a > b ? a : b)
/*
* the define related to mass storage
*/
#define USBREQ_GET_MAX_LUN 0xfe
#define USBREQ_MASS_STORAGE_RESET 0xff
#define SIZEOF_CSW 0x0d
#define SIZEOF_CBW 0x1f
#define CBWFLAGS_DIR_M 0x80
#define CBWFLAGS_DIR_IN 0x80
#define CBWFLAGS_DIR_OUT 0x00
#define SCSI_TEST_UNIT_READY 0x00
#define SCSI_REQUEST_SENSE 0x03
#define SCSI_INQUIRY_CMD 0x12
#define SCSI_ALLOW_MEDIUM_REMOVAL 0x1e
#define SCSI_MODE_SENSE_6 0x1a
#define SCSI_START_STOP 0x1b
#define SCSI_READ_CAPACITIES 0x23
#define SCSI_READ_CAPACITY 0x25
#define SCSI_READ_10 0x28
#define SCSI_WRITE_10 0x2a
#define SCSI_VERIFY_10 0x2f
#define CBW_SIGNATURE 0x43425355
#define CSW_SIGNATURE 0x53425355
#define CBW_TAG_VALUE 0x12345678
struct ustorage_cbw
{
rt_uint32_t signature;
rt_uint32_t tag;
rt_uint32_t xfer_len;
rt_uint8_t dflags;
rt_uint8_t lun;
rt_uint8_t cb_len;
rt_uint8_t cb[16];
};
typedef struct ustorage_cbw* ustorage_cbw_t;
struct ustorage_csw
{
rt_uint32_t signature;
rt_uint32_t tag;
rt_uint32_t data_reside;
rt_uint8_t status;
};
typedef struct ustorage_csw* ustorage_csw_t;
#pragma pack()
/*
* USB device event loop thread configurations
*/
/* the stack size of USB thread */
#ifndef RT_USBD_THREAD_STACK_SZ
#define RT_USBD_THREAD_STACK_SZ 2048
#endif
/* the priority of USB thread */
#ifndef RT_USBD_THREAD_PRIO
#define RT_USBD_THREAD_PRIO 8
#endif
#ifdef __cplusplus
}
#endif
#endif
|
levenlai/rt-stm32
|
components/drivers/include/drivers/usb_common.h
|
C
|
gpl-2.0
| 13,355
|
/*
Copyright (C) 2011 ABRT Team
Copyright (C) 2011 RedHat inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "event_config.h"
#include "internal_libreport.h"
#define EVENT_ELEMENT "event"
#define LABEL_ELEMENT "label"
#define DESCRIPTION_ELEMENT "description"
#define LONG_DESCR_ELEMENT "long-description"
#define ALLOW_EMPTY_ELEMENT "allow-empty"
#define NOTE_HTML_ELEMENT "note-html"
#define OPTION_ELEMENT "option"
//#define ACTION_ELEMENT "action"
#define NAME_ELEMENT "name"
#define DEFAULT_VALUE_ELEMENT "default-value"
#define MINIMAL_RATING_ELEMENT "minimal-rating"
#define GUI_REVIEW_ELEMENTS "gui-review-elements"
#define SENDING_SENSITIVE_DATA_ELEMENT "sending-sensitive-data"
#define SUPPORTS_RESTRICTED_ACCESS_ELEMENT "support-restricted-access"
#define RESTRICTED_ACCESS_OPTION_ATTR "optionname"
#define REQUIRES_DETAILS "requires-details"
#define REQUIRES_ELEMENT "requires-items"
#define EXCL_BY_DEFAULT_ELEMENT "exclude-items-by-default"
#define INCL_BY_DEFAULT_ELEMENT "include-items-by-default"
#define EXCL_ALWAYS_ELEMENT "exclude-items-always"
#define EXCL_BINARY_ELEMENT "exclude-binary-items"
#define ADV_OPTIONS_ELEMENT "advanced-options"
#define IMPORT_OPTIONS_ELEMENT "import-event-options"
typedef struct
{
event_config_t *values;
bool exact_name;
bool exact_description;
bool exact_long_description;
} parsed_event_config_t;
typedef struct
{
event_option_t *values;
bool exact_label;
bool exact_note_html;
} parsed_event_option_t;
struct my_parse_data
{
parsed_event_config_t event_config;
parsed_event_option_t cur_option;
char *cur_locale;
char *attribute_lang;
bool in_adv_option;
};
static const char *const option_types[] =
{
[OPTION_TYPE_TEXT ] = "text",
[OPTION_TYPE_BOOL ] = "bool",
[OPTION_TYPE_PASSWORD ] = "password",
[OPTION_TYPE_NUMBER ] = "number",
[OPTION_TYPE_HINT_HTML] = "hint-html",
[OPTION_TYPE_INVALID ] = NULL
};
// Return xml:lang value for <foo xml:lang="value"> if value matches current locale,
// "" if foo has no xml:lang attribute at all,
// else (if xml:lang is for some other locale) return NULL
//
static char *get_element_lang(struct my_parse_data *parse_data, const gchar **att_names, const gchar **att_values)
{
char *short_locale_end = strchr(parse_data->cur_locale, '_');
//log_debug("locale: %s", parse_data->cur_locale);
int i;
for (i = 0; att_names[i] != NULL; ++i)
{
//log_debug("attr: %s:%s", att_names[i], att_values[i]);
if (strcmp(att_names[i], "xml:lang") == 0)
{
if (strcmp(att_values[i], parse_data->cur_locale) == 0)
{
log_debug("found translation for: %s", parse_data->cur_locale);
return g_strdup(att_values[i]);
}
/* try to match shorter locale
* e.g: "cs" with cs_CZ
*/
if (short_locale_end
&& strncmp(att_values[i], parse_data->cur_locale, short_locale_end - parse_data->cur_locale) == 0
) {
log_debug("found translation for shortlocale: %s", parse_data->cur_locale);
return g_strndup(att_values[i], short_locale_end - parse_data->cur_locale);
}
}
}
/* if the element has no attribute then it's a default non-localized value */
if (i == 0)
return g_strdup("");
/* if the element is in different language than the current locale */
return NULL;
}
static int cmp_event_option_name_with_string(gconstpointer a, gconstpointer b)
{
const event_option_t *evopt = a;
/* "When it is not a match?" */
return !evopt->eo_name || strcmp(evopt->eo_name, (char *)b) != 0;
}
static void consume_cur_option(struct my_parse_data *parse_data)
{
event_option_t *opt = parse_data->cur_option.values;
if (!opt)
return;
memset(&parse_data->cur_option, 0, sizeof(parse_data->cur_option));
parsed_event_config_t *event_config = &parse_data->event_config;
/* Example of "nameless" option: <option type="hint-html">
* The remaining code does not like "nameless" options
* (strcmp would segfault, etc), so provide invented name:
*/
if (!opt->eo_name)
opt->eo_name = g_strdup_printf("%u", (unsigned)g_list_length(event_config->values->options));
GList *elem = g_list_find_custom(event_config->values->options, opt->eo_name, cmp_event_option_name_with_string);
if (elem)
{
/* we already have option with such name */
event_option_t *old_opt = elem->data;
if (old_opt->eo_value)
{
/* ...and it already has a value, which
* overrides xml-defined default one:
*/
g_free(opt->eo_value);
opt->eo_value = old_opt->eo_value;
old_opt->eo_value = NULL;
}
free_event_option(old_opt);
elem->data = opt;
}
else
{
event_config->values->options = g_list_append(event_config->values->options, opt);
}
}
// Called for opening tags <foo bar="baz">
static void start_element(GMarkupParseContext *context,
const gchar *element_name,
const gchar **attribute_names,
const gchar **attribute_values,
gpointer user_data,
GError **error)
{
struct my_parse_data *parse_data = user_data;
if (strcmp(element_name, ADV_OPTIONS_ELEMENT) == 0)
{
parse_data->in_adv_option = true;
return;
}
if (strcmp(element_name, OPTION_ELEMENT) == 0)
{
if (parse_data->cur_option.values)
{
error_msg("error, option nested in option");
return;
}
memset(&parse_data->cur_option, 0, sizeof(parse_data->cur_option));
event_option_t *opt = parse_data->cur_option.values = new_event_option();
opt->is_advanced = (parse_data->in_adv_option == true);
int i;
for (i = 0; attribute_names[i] != NULL; ++i)
{
log_info("attr: %s:%s", attribute_names[i], attribute_values[i]);
if (strcmp(attribute_names[i], "name") == 0)
{
g_free(opt->eo_name);
opt->eo_name = g_strdup(attribute_values[i]);
}
else if (strcmp(attribute_names[i], "type") == 0)
{
option_type_t type;
for (type = OPTION_TYPE_TEXT; type < OPTION_TYPE_INVALID; ++type)
{
if (strcmp(option_types[type], attribute_values[i]) == 0)
opt->eo_type = type;
}
}
}
}
else
if (strcmp(element_name, IMPORT_OPTIONS_ELEMENT) == 0)
{
if (attribute_names[0] == NULL
|| attribute_names[1] != NULL
|| strcmp(attribute_names[0], "event") != 0)
{
error_msg("XML event configuration error: import-event-options element misses attribute 'event'");
return;
}
GList *head = parse_data->event_config.values->ec_imported_event_names;
parse_data->event_config.values->ec_imported_event_names = g_list_append(head, g_strdup(attribute_values[0]));
}
else
if (strcmp(element_name, LABEL_ELEMENT) == 0
|| strcmp(element_name, DESCRIPTION_ELEMENT) == 0
|| strcmp(element_name, LONG_DESCR_ELEMENT) == 0
|| strcmp(element_name, NAME_ELEMENT) == 0
|| strcmp(element_name, NOTE_HTML_ELEMENT) == 0
) {
g_free(parse_data->attribute_lang);
parse_data->attribute_lang = get_element_lang(parse_data, attribute_names, attribute_values);
}
else
if (strcmp(element_name, SUPPORTS_RESTRICTED_ACCESS_ELEMENT) == 0)
{
if (attribute_names[0] == NULL
|| attribute_names[1] != NULL
|| strcmp(attribute_names[0], RESTRICTED_ACCESS_OPTION_ATTR) != 0)
{
error_msg("XML event configuration error: '%s' element misses attribute '%s'",
SUPPORTS_RESTRICTED_ACCESS_ELEMENT, RESTRICTED_ACCESS_OPTION_ATTR);
return;
}
parse_data->event_config.values->ec_restricted_access_option = g_strdup(attribute_values[0]);
}
}
// Called for close tags </foo>
static void end_element(GMarkupParseContext *context,
const gchar *element_name,
gpointer user_data,
GError **error)
{
struct my_parse_data *parse_data = user_data;
g_free(parse_data->attribute_lang);
parse_data->attribute_lang = NULL;
if (strcmp(element_name, ADV_OPTIONS_ELEMENT) == 0)
{
parse_data->in_adv_option = false;
}
if (strcmp(element_name, OPTION_ELEMENT) == 0)
{
consume_cur_option(parse_data);
}
if (strcmp(element_name, EVENT_ELEMENT) == 0)
{
consume_cur_option(parse_data);
}
}
// Called for character data
// text is not nul-terminated
static void text(GMarkupParseContext *context,
const gchar *text,
gsize text_len,
gpointer user_data,
GError **error)
{
struct my_parse_data *parse_data = user_data;
event_config_t *ui = parse_data->event_config.values;
const gchar *inner_element = g_markup_parse_context_get_element(context);
char *text_copy = g_strndup(text, text_len);
event_option_t *opt = parse_data->cur_option.values;
if (opt)
{
if (strcmp(inner_element, LABEL_ELEMENT) == 0)
{
if (parse_data->attribute_lang != NULL) /* if it isn't for other locale */
{
/* set the value only if we found a value for the current locale
* OR the label is still not set and we found the default value
*/
if (parse_data->attribute_lang[0] != '\0'
|| !opt->eo_label /* && parse_data->attribute_lang is "" - always true */
) {
if (!parse_data->cur_option.exact_label)
{
parse_data->cur_option.exact_label =
(strcmp(parse_data->attribute_lang, parse_data->cur_locale) == 0);
log_info("new label:'%s'", text_copy);
g_free(opt->eo_label);
opt->eo_label = g_steal_pointer(&text_copy);
}
}
}
}
/*
* we can add a separate field for the default value
* in that case we can implement features like "reset to default value"
* but for now using "value" should be enough and clients doesn't
* have to know about the "defaul-value"
*/
else if (strcmp(inner_element, DEFAULT_VALUE_ELEMENT) == 0)
{
log_info("default value:'%s'", text_copy);
g_free(opt->eo_value);
opt->eo_value = g_steal_pointer(&text_copy);
}
else if (strcmp(inner_element, NOTE_HTML_ELEMENT) == 0)
{
if (parse_data->attribute_lang != NULL) /* if it isn't for other locale */
{
/* set the value only if we found a value for the current locale
* OR the label is still not set and we found the default value
*/
if (parse_data->attribute_lang[0] != '\0'
|| !opt->eo_note_html /* && parse_data->attribute_lang is "" - always true */
) {
if (!parse_data->cur_option.exact_note_html)
{
parse_data->cur_option.exact_note_html =
(strcmp(parse_data->attribute_lang, parse_data->cur_locale) == 0);
log_info("html note:'%s'", text_copy);
g_free(opt->eo_note_html);
opt->eo_note_html = g_steal_pointer(&text_copy);
}
}
}
}
else if (strcmp(inner_element, ALLOW_EMPTY_ELEMENT) == 0)
{
log_info("allow-empty:'%s'", text_copy);
opt->eo_allow_empty = libreport_string_to_bool(text_copy);
}
}
else
{
if (strcmp(inner_element, NAME_ELEMENT) == 0)
{
if (parse_data->attribute_lang != NULL) /* if it isn't for other locale */
{
/* set the value only if we found a value for the current locale
* OR the label is still not set and we found the default value
*/
if (parse_data->attribute_lang[0] != '\0'
|| !ec_get_screen_name(ui) /* && parse_data->attribute_lang is "" - always true */
) {
if (!parse_data->event_config.exact_name)
{
parse_data->event_config.exact_name =
(strcmp(parse_data->attribute_lang, parse_data->cur_locale) == 0);
log_info("event name:'%s'", text_copy);
ec_set_screen_name(ui, text_copy);
g_clear_pointer(&text_copy, g_free);
}
}
}
}
else if (strcmp(inner_element, DESCRIPTION_ELEMENT) == 0)
{
log_debug("event description:'%s'", text_copy);
if (parse_data->attribute_lang != NULL) /* if it isn't for other locale */
{
/* set the value only if we found a value for the current locale
* OR the description is still not set and we found the default value
*/
if (parse_data->attribute_lang[0] != '\0'
|| !ec_get_description(ui) /* && parse_data->attribute_lang is "" - always true */
) {
if (!parse_data->event_config.exact_description)
{
parse_data->event_config.exact_description =
(strcmp(parse_data->attribute_lang, parse_data->cur_locale) == 0);
ec_set_description(ui, text_copy);
g_clear_pointer(&text_copy, g_free);
}
}
}
}
else if (strcmp(inner_element, LONG_DESCR_ELEMENT) == 0)
{
log_debug("event long description:'%s'", text_copy);
if (parse_data->attribute_lang != NULL) /* if it isn't for other locale */
{
/* set the value only if we found a value for the current locale
* OR the description is still not set and we found the default value
*/
if (parse_data->attribute_lang[0] != '\0'
|| !ec_get_long_desc(ui) /* && parse_data->attribute_lang is "" - always true */
) {
if (!parse_data->event_config.exact_long_description)
{
parse_data->event_config.exact_long_description =
(strcmp(parse_data->attribute_lang, parse_data->cur_locale) == 0);
ec_set_long_desc(ui, text_copy);
g_clear_pointer(&text_copy, g_free);
}
}
}
}
else if (strcmp(inner_element, REQUIRES_ELEMENT) == 0)
{
g_free(ui->ec_requires_items);
ui->ec_requires_items = g_steal_pointer(&text_copy);
}
else if (strcmp(inner_element, EXCL_BY_DEFAULT_ELEMENT) == 0)
{
g_free(ui->ec_exclude_items_by_default);
ui->ec_exclude_items_by_default = g_steal_pointer(&text_copy);
}
else if (strcmp(inner_element, INCL_BY_DEFAULT_ELEMENT) == 0)
{
g_free(ui->ec_include_items_by_default);
ui->ec_include_items_by_default = g_steal_pointer(&text_copy);
}
else if (strcmp(inner_element, EXCL_ALWAYS_ELEMENT) == 0)
{
g_free(ui->ec_exclude_items_always);
ui->ec_exclude_items_always = g_steal_pointer(&text_copy);
}
else if (strcmp(inner_element, EXCL_BINARY_ELEMENT) == 0)
{
ui->ec_exclude_binary_items = libreport_string_to_bool(text_copy);
}
else if (strcmp(inner_element, MINIMAL_RATING_ELEMENT) == 0)
{
char *endptr;
errno = 0;
ui->ec_minimal_rating = strtol(text_copy, &endptr, 10);
if (errno != 0 || endptr == text_copy || *endptr != '\0')
{
log_warning("invalid minimal-rating number '%s', set to default 4", text_copy);
ui->ec_minimal_rating = 4;
}
}
else if (strcmp(inner_element, GUI_REVIEW_ELEMENTS) == 0)
{
ui->ec_skip_review = !libreport_string_to_bool(text_copy);
}
else if (strcmp(inner_element, SENDING_SENSITIVE_DATA_ELEMENT) == 0)
{
ui->ec_sending_sensitive_data = libreport_string_to_bool(text_copy);
}
else if (strcmp(inner_element, SUPPORTS_RESTRICTED_ACCESS_ELEMENT) == 0)
{
ui->ec_supports_restricted_access = libreport_string_to_bool(text_copy);
}
else if (strcmp(inner_element, REQUIRES_DETAILS) == 0)
{
ui->ec_requires_details = libreport_string_to_bool(text_copy);
}
}
g_free(text_copy);
}
// Called for strings that should be re-saved verbatim in this same
// position, but are not otherwise interpretable. At the moment
// this includes comments and processing instructions.
// text is not nul-terminated
static void passthrough(GMarkupParseContext *context,
const gchar *passthrough_text,
gsize text_len,
gpointer user_data,
GError **error)
{
log_debug("passthrough");
}
// Called on error, including one set by other
// methods in the vtable. The GError should not be freed.
static void error(GMarkupParseContext *context,
GError *error,
gpointer user_data)
{
error_msg("error in XML parsing");
}
/* this function takes 2 parameters
* ui -> pointer to event_config_t
* filename -> filename to read
* event_config_t contains list of options, which is malloced by this function
* and must be freed by the caller
*/
void load_event_description_from_file(event_config_t *event_config, const char* filename)
{
log_info("loading event: '%s'", filename);
struct my_parse_data parse_data = {
{ event_config, false, false, false },
{ NULL, false, false },
NULL,
NULL,
false
};
parse_data.cur_locale = g_strdup(setlocale(LC_ALL, NULL));
strchrnul(parse_data.cur_locale, '.')[0] = '\0';
GMarkupParser parser;
memset(&parser, 0, sizeof(parser)); /* just in case */
parser.start_element = &start_element;
parser.end_element = &end_element;
parser.text = &text;
parser.passthrough = &passthrough;
parser.error = &error;
GMarkupParseContext *context = g_markup_parse_context_new(
&parser, G_MARKUP_TREAT_CDATA_AS_TEXT,
&parse_data, /*GDestroyNotify:*/ NULL);
FILE* fin = fopen(filename, "r");
if (fin != NULL)
{
size_t read_bytes;
char buff[1024];
while ((read_bytes = fread(buff, 1, 1024, fin)) != 0)
{
g_markup_parse_context_parse(context, buff, read_bytes, NULL);
}
fclose(fin);
}
else
perror_msg("cannot load event description from file: '%s'", filename);
g_markup_parse_context_free(context);
consume_cur_option(&parse_data); /* just in case */
g_free(parse_data.attribute_lang); /* just in case */
g_free(parse_data.cur_locale);
}
|
abrt/libreport
|
src/lib/event_xml_parser.c
|
C
|
gpl-2.0
| 20,765
|
/**
* Created by herve on 10/11/15.
*/
function ajax_exercises_by_muscles(muscle) {
$("#loader").show();
$("#loader-message").show();
$.ajax({
url : "/exercises/muscles/ajax-exercises-by-muscles/", // the endpoint
type : "POST", // http method
data : { muscle : muscle }, // data sent with the post request
// handle a successful response
success : function(json) {
json = JSON.stringify(json);
json = JSON.parse(json);
$("#loader").hide();
$("#loader-message").hide();
$("#exercises-count").text(json.count);
$("#exercises-count").attr('href', json.link);
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
};
|
4383/street-workout-database
|
sport/web/static/js/ajax.js
|
JavaScript
|
gpl-2.0
| 926
|
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/*
* Copyright (C) 2007 Philip Withnall <philip@tecnocode.co.uk>
*
* 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.
*
* The Idol project hereby grant permission for non-gpl compatible GStreamer
* plugins to be used and distributed together with GStreamer and Idol. This
* permission are above and beyond the permissions granted by the GPL license
* Idol is covered by.
*
* Monday 7th February 2005: Christian Schaller: Add excemption clause.
* See license_change file for details.
*
* Author: Bastien Nocera <hadess@hadess.net>, Philip Withnall <philip@tecnocode.co.uk>
*/
#include "config.h"
#include <glib/gi18n-lib.h>
#include <gmodule.h>
#include <string.h>
#include <gdk/gdkkeysyms.h>
#include "idol-skipto-plugin.h"
#include "idol-skipto.h"
struct IdolSkiptoPluginPrivate
{
IdolSkipto *st;
guint handler_id_stream_length;
guint handler_id_seekable;
guint handler_id_key_press;
guint ui_merge_id;
GtkActionGroup *action_group;
};
G_MODULE_EXPORT GType register_idol_plugin (GTypeModule *module);
static void idol_skipto_plugin_finalize (GObject *object);
static gboolean impl_activate (IdolPlugin *plugin, IdolObject *idol, GError **error);
static void impl_deactivate (IdolPlugin *plugin, IdolObject *idol);
IDOL_PLUGIN_REGISTER_EXTENDED(IdolSkiptoPlugin, idol_skipto_plugin, IDOL_PLUGIN_REGISTER_TYPE(idol_skipto))
static void
idol_skipto_plugin_class_init (IdolSkiptoPluginClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
IdolPluginClass *plugin_class = IDOL_PLUGIN_CLASS (klass);
g_type_class_add_private (klass, sizeof (IdolSkiptoPluginPrivate));
object_class->finalize = idol_skipto_plugin_finalize;
plugin_class->activate = impl_activate;
plugin_class->deactivate = impl_deactivate;
}
static void
idol_skipto_plugin_init (IdolSkiptoPlugin *plugin)
{
plugin->priv = G_TYPE_INSTANCE_GET_PRIVATE (plugin,
IDOL_TYPE_SKIPTO_PLUGIN,
IdolSkiptoPluginPrivate);
plugin->priv->st = NULL;
}
static void
destroy_dialog (IdolSkiptoPlugin *plugin)
{
IdolSkiptoPluginPrivate *priv = plugin->priv;
if (priv->st != NULL) {
g_object_remove_weak_pointer (G_OBJECT (priv->st),
(gpointer *)&(priv->st));
gtk_widget_destroy (GTK_WIDGET (priv->st));
priv->st = NULL;
}
}
static void
idol_skipto_plugin_finalize (GObject *object)
{
IdolSkiptoPlugin *plugin = IDOL_SKIPTO_PLUGIN (object);
destroy_dialog (plugin);
G_OBJECT_CLASS (idol_skipto_plugin_parent_class)->finalize (object);
}
static void
idol_skipto_update_from_state (IdolObject *idol,
IdolSkiptoPlugin *plugin)
{
gint64 _time;
gboolean seekable;
GtkAction *action;
IdolSkiptoPluginPrivate *priv = plugin->priv;
g_object_get (G_OBJECT (idol),
"stream-length", &_time,
"seekable", &seekable,
NULL);
if (priv->st != NULL) {
idol_skipto_update_range (priv->st, _time);
idol_skipto_set_seekable (priv->st, seekable);
}
/* Update the action's sensitivity */
action = gtk_action_group_get_action (priv->action_group, "skip-to");
gtk_action_set_sensitive (action, seekable);
}
static void
property_notify_cb (IdolObject *idol,
GParamSpec *spec,
IdolSkiptoPlugin *plugin)
{
idol_skipto_update_from_state (idol, plugin);
}
static void
skip_to_response_callback (GtkDialog *dialog, gint response, IdolSkiptoPlugin *plugin)
{
if (response != GTK_RESPONSE_OK) {
destroy_dialog (plugin);
return;
}
gtk_widget_hide (GTK_WIDGET (dialog));
idol_action_seek_time (plugin->idol,
idol_skipto_get_range (plugin->priv->st),
TRUE);
destroy_dialog (plugin);
}
static void
run_skip_to_dialog (IdolSkiptoPlugin *plugin)
{
IdolSkiptoPluginPrivate *priv = plugin->priv;
if (idol_is_seekable (plugin->idol) == FALSE)
return;
if (priv->st != NULL) {
gtk_window_present (GTK_WINDOW (priv->st));
idol_skipto_set_current (priv->st, idol_get_current_time
(plugin->idol));
return;
}
priv->st = IDOL_SKIPTO (idol_skipto_new (plugin));
g_signal_connect (G_OBJECT (priv->st), "delete-event",
G_CALLBACK (gtk_widget_destroy), NULL);
g_signal_connect (G_OBJECT (priv->st), "response",
G_CALLBACK (skip_to_response_callback), plugin);
g_object_add_weak_pointer (G_OBJECT (priv->st),
(gpointer *)&(priv->st));
idol_skipto_update_from_state (plugin->idol, plugin);
idol_skipto_set_current (priv->st,
idol_get_current_time (plugin->idol));
}
static void
skip_to_action_callback (GtkAction *action, IdolSkiptoPlugin *plugin)
{
run_skip_to_dialog (plugin);
}
static gboolean
on_window_key_press_event (GtkWidget *window, GdkEventKey *event, IdolSkiptoPlugin *plugin)
{
if (event->state == 0 || !(event->state & GDK_CONTROL_MASK))
return FALSE;
switch (event->keyval) {
case GDK_k:
case GDK_K:
run_skip_to_dialog (plugin);
break;
default:
return FALSE;
}
return TRUE;
}
static gboolean
impl_activate (IdolPlugin *plugin,
IdolObject *idol,
GError **error)
{
GtkWindow *window;
GtkUIManager *manager;
IdolSkiptoPlugin *pi = IDOL_SKIPTO_PLUGIN (plugin);
IdolSkiptoPluginPrivate *priv = pi->priv;
char *builder_path;
const GtkActionEntry menu_entries[] = {
{ "skip-to", GTK_STOCK_JUMP_TO, N_("_Skip to..."), "<Control>K", N_("Skip to a specific time"), G_CALLBACK (skip_to_action_callback) }
};
builder_path = idol_plugin_find_file (IDOL_PLUGIN (plugin), "skipto.ui");
if (builder_path == NULL) {
g_set_error_literal (error, IDOL_PLUGIN_ERROR, IDOL_PLUGIN_ERROR_ACTIVATION,
_("Could not load the \"Skip to\" dialog interface."));
return FALSE;
}
g_free (builder_path);
pi->idol = idol;
priv->handler_id_stream_length = g_signal_connect (G_OBJECT (idol),
"notify::stream-length",
G_CALLBACK (property_notify_cb),
pi);
priv->handler_id_seekable = g_signal_connect (G_OBJECT (idol),
"notify::seekable",
G_CALLBACK (property_notify_cb),
pi);
/* Key press handler */
window = idol_get_main_window (idol);
priv->handler_id_key_press = g_signal_connect (G_OBJECT(window),
"key-press-event",
G_CALLBACK (on_window_key_press_event),
pi);
g_object_unref (window);
/* Install the menu */
priv->action_group = gtk_action_group_new ("skip-to_group");
gtk_action_group_set_translation_domain (priv->action_group, GETTEXT_PACKAGE);
gtk_action_group_add_actions (priv->action_group, menu_entries,
G_N_ELEMENTS (menu_entries), pi);
manager = idol_get_ui_manager (idol);
gtk_ui_manager_insert_action_group (manager, priv->action_group, -1);
g_object_unref (priv->action_group);
priv->ui_merge_id = gtk_ui_manager_new_merge_id (manager);
gtk_ui_manager_add_ui (manager, priv->ui_merge_id,
"/ui/tmw-menubar/go/skip-forward", "skip-to",
"skip-to", GTK_UI_MANAGER_AUTO, TRUE);
idol_skipto_update_from_state (idol, pi);
return TRUE;
}
static void
impl_deactivate (IdolPlugin *plugin,
IdolObject *idol)
{
GtkWindow *window;
GtkUIManager *manager;
IdolSkiptoPluginPrivate *priv = IDOL_SKIPTO_PLUGIN (plugin)->priv;
g_signal_handler_disconnect (G_OBJECT (idol),
priv->handler_id_stream_length);
g_signal_handler_disconnect (G_OBJECT (idol),
priv->handler_id_seekable);
if (priv->handler_id_key_press != 0) {
window = idol_get_main_window (idol);
g_signal_handler_disconnect (G_OBJECT(window),
priv->handler_id_key_press);
priv->handler_id_key_press = 0;
g_object_unref (window);
}
/* Remove the menu */
manager = idol_get_ui_manager (idol);
gtk_ui_manager_remove_ui (manager, priv->ui_merge_id);
gtk_ui_manager_remove_action_group (manager, priv->action_group);
}
|
gfunkmonk2/mate-movie-player
|
src/plugins/skipto/idol-skipto-plugin.c
|
C
|
gpl-2.0
| 8,361
|
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : Variable Reference: $adsense_blocks_counter</title>
<link rel="stylesheet" href="../sample.css" type="text/css">
<link rel="stylesheet" href="../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Sat Nov 21 22:13:19 2015 -->
<!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net -->
<!-- http://phpxref.sourceforge.net/ -->
<script src="../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
ext='.html';
relbase='../';
subdir='_variables';
filename='index.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
logVariable('adsense_blocks_counter');
// -->
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
[<a href="../index.html">Top level directory</a>]<br>
<script language="JavaScript" type="text/javascript">
<!--
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
// -->
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h3>Variable Cross Reference</h3>
<h2><a href="index.html#adsense_blocks_counter">$adsense_blocks_counter</a></h2>
<b>Defined at:</b><ul>
<li><a href="../plugins/adsense_plugin/_adsense.plugin.php.html">/plugins/adsense_plugin/_adsense.plugin.php</A> -> <a href="../plugins/adsense_plugin/_adsense.plugin.php.source.html#l195"> line 195</A></li>
</ul>
<br><b>Referenced 4 times:</b><ul>
<li><a href="../plugins/adsense_plugin/_adsense.plugin.php.html">/plugins/adsense_plugin/_adsense.plugin.php</a> -> <a href="../plugins/adsense_plugin/_adsense.plugin.php.source.html#l195"> line 195</a></li>
<li><a href="../plugins/adsense_plugin/_adsense.plugin.php.html">/plugins/adsense_plugin/_adsense.plugin.php</a> -> <a href="../plugins/adsense_plugin/_adsense.plugin.php.source.html#l197"> line 197</a></li>
<li><a href="../plugins/adsense_plugin/_adsense.plugin.php.html">/plugins/adsense_plugin/_adsense.plugin.php</a> -> <a href="../plugins/adsense_plugin/_adsense.plugin.php.source.html#l199"> line 199</a></li>
<li><a href="../plugins/adsense_plugin/_adsense.plugin.php.html">/plugins/adsense_plugin/_adsense.plugin.php</a> -> <a href="../plugins/adsense_plugin/_adsense.plugin.php.source.html#l201"> line 201</a></li>
</ul>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Sat Nov 21 22:13:19 2015</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
|
mgsolipa/b2evolution_phpxref
|
_variables/adsense_blocks_counter.html
|
HTML
|
gpl-2.0
| 5,490
|
/*
* 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.
*
* RAW - implementation of IP "raw" sockets.
*
* Authors: Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
*
* Fixes:
* Alan Cox : verify_area() fixed up
* Alan Cox : ICMP error handling
* Alan Cox : EMSGSIZE if you send too big a packet
* Alan Cox : Now uses generic datagrams and shared
* skbuff library. No more peek crashes,
* no more backlogs
* Alan Cox : Checks sk->broadcast.
* Alan Cox : Uses skb_free_datagram/skb_copy_datagram
* Alan Cox : Raw passes ip options too
* Alan Cox : Setsocketopt added
* Alan Cox : Fixed error return for broadcasts
* Alan Cox : Removed wake_up calls
* Alan Cox : Use ttl/tos
* Alan Cox : Cleaned up old debugging
* Alan Cox : Use new kernel side addresses
* Arnt Gulbrandsen : Fixed MSG_DONTROUTE in raw sockets.
* Alan Cox : BSD style RAW socket demultiplexing.
* Alan Cox : Beginnings of mrouted support.
* Alan Cox : Added IP_HDRINCL option.
* Alan Cox : Skip broadcast check if BSDism set.
* David S. Miller : New socket lookup architecture.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/types.h>
#include <linux/atomic.h>
#include <asm/byteorder.h>
#include <asm/current.h>
#include <asm/uaccess.h>
#include <asm/ioctls.h>
#include <linux/stddef.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/aio.h>
#include <linux/kernel.h>
#include <linux/export.h>
#include <linux/spinlock.h>
#include <linux/sockios.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/mroute.h>
#include <linux/netdevice.h>
#include <linux/in_route.h>
#include <linux/route.h>
#include <linux/skbuff.h>
#include <net/net_namespace.h>
#include <net/dst.h>
#include <net/sock.h>
#include <linux/ip.h>
#include <linux/net.h>
#include <net/ip.h>
#include <net/icmp.h>
#include <net/udp.h>
#include <net/raw.h>
#include <net/snmp.h>
#include <net/tcp_states.h>
#include <net/inet_common.h>
#include <net/checksum.h>
#include <net/xfrm.h>
#include <linux/rtnetlink.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/compat.h>
static struct raw_hashinfo raw_v4_hashinfo = {
.lock = __RW_LOCK_UNLOCKED(raw_v4_hashinfo.lock),
};
void raw_hash_sk(struct sock *sk)
{
struct raw_hashinfo *h = sk->sk_prot->h.raw_hash;
struct hlist_head *head;
head = &h->ht[inet_sk(sk)->inet_num & (RAW_HTABLE_SIZE - 1)];
write_lock_bh(&h->lock);
sk_add_node(sk, head);
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
write_unlock_bh(&h->lock);
}
EXPORT_SYMBOL_GPL(raw_hash_sk);
void raw_unhash_sk(struct sock *sk)
{
struct raw_hashinfo *h = sk->sk_prot->h.raw_hash;
write_lock_bh(&h->lock);
if (sk_del_node_init(sk))
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
write_unlock_bh(&h->lock);
}
EXPORT_SYMBOL_GPL(raw_unhash_sk);
static struct sock *__raw_v4_lookup(struct net *net, struct sock *sk,
unsigned short num, __be32 raddr, __be32 laddr, int dif)
{
sk_for_each_from(sk) {
struct inet_sock *inet = inet_sk(sk);
if (net_eq(sock_net(sk), net) && inet->inet_num == num &&
!(inet->inet_daddr && inet->inet_daddr != raddr) &&
!(inet->inet_rcv_saddr && inet->inet_rcv_saddr != laddr) &&
!(sk->sk_bound_dev_if && sk->sk_bound_dev_if != dif))
goto found; /* gotcha */
}
sk = NULL;
found:
return sk;
}
/*
* 0 - deliver
* 1 - block
*/
static int icmp_filter(const struct sock *sk, const struct sk_buff *skb)
{
struct icmphdr _hdr;
const struct icmphdr *hdr;
hdr = skb_header_pointer(skb, skb_transport_offset(skb),
sizeof(_hdr), &_hdr);
if (!hdr)
return 1;
if (hdr->type < 32) {
__u32 data = raw_sk(sk)->filter.data;
return ((1U << hdr->type) & data) != 0;
}
/* Do not block unknown ICMP types */
return 0;
}
/* IP input processing comes here for RAW socket delivery.
* Caller owns SKB, so we must make clones.
*
* RFC 1122: SHOULD pass TOS value up to the transport layer.
* -> It does. And not only TOS, but all IP header.
*/
static int raw_v4_input(struct sk_buff *skb, const struct iphdr *iph, int hash)
{
struct sock *sk;
struct hlist_head *head;
int delivered = 0;
struct net *net;
read_lock(&raw_v4_hashinfo.lock);
head = &raw_v4_hashinfo.ht[hash];
if (hlist_empty(head))
goto out;
net = dev_net(skb->dev);
sk = __raw_v4_lookup(net, __sk_head(head), iph->protocol,
iph->saddr, iph->daddr,
skb->dev->ifindex);
while (sk) {
delivered = 1;
if (iph->protocol != IPPROTO_ICMP || !icmp_filter(sk, skb)) {
struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC);
/* Not releasing hash table! */
if (clone)
raw_rcv(sk, clone);
}
sk = __raw_v4_lookup(net, sk_next(sk), iph->protocol,
iph->saddr, iph->daddr,
skb->dev->ifindex);
}
out:
read_unlock(&raw_v4_hashinfo.lock);
return delivered;
}
int raw_local_deliver(struct sk_buff *skb, int protocol)
{
int hash;
struct sock *raw_sk;
hash = protocol & (RAW_HTABLE_SIZE - 1);
raw_sk = sk_head(&raw_v4_hashinfo.ht[hash]);
/* If there maybe a raw socket we must check - if not we
* don't care less
*/
if (raw_sk && !raw_v4_input(skb, ip_hdr(skb), hash))
raw_sk = NULL;
return raw_sk != NULL;
}
static void raw_err(struct sock *sk, struct sk_buff *skb, u32 info)
{
struct inet_sock *inet = inet_sk(sk);
const int type = icmp_hdr(skb)->type;
const int code = icmp_hdr(skb)->code;
int err = 0;
int harderr = 0;
if (type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED)
ipv4_sk_update_pmtu(skb, sk, info);
else if (type == ICMP_REDIRECT) {
ipv4_sk_redirect(skb, sk);
return;
}
/* Report error on raw socket, if:
1. User requested ip_recverr.
2. Socket is connected (otherwise the error indication
is useless without ip_recverr and error is hard.
*/
if (!inet->recverr && sk->sk_state != TCP_ESTABLISHED)
return;
switch (type) {
default:
case ICMP_TIME_EXCEEDED:
err = EHOSTUNREACH;
break;
case ICMP_SOURCE_QUENCH:
return;
case ICMP_PARAMETERPROB:
err = EPROTO;
harderr = 1;
break;
case ICMP_DEST_UNREACH:
err = EHOSTUNREACH;
if (code > NR_ICMP_UNREACH)
break;
err = icmp_err_convert[code].errno;
harderr = icmp_err_convert[code].fatal;
if (code == ICMP_FRAG_NEEDED) {
harderr = inet->pmtudisc != IP_PMTUDISC_DONT;
err = EMSGSIZE;
}
}
if (inet->recverr) {
const struct iphdr *iph = (const struct iphdr *)skb->data;
u8 *payload = skb->data + (iph->ihl << 2);
if (inet->hdrincl)
payload = skb->data;
ip_icmp_error(sk, skb, err, 0, info, payload);
}
if (inet->recverr || harderr) {
sk->sk_err = err;
sk->sk_error_report(sk);
}
}
void raw_icmp_error(struct sk_buff *skb, int protocol, u32 info)
{
int hash;
struct sock *raw_sk;
const struct iphdr *iph;
struct net *net;
hash = protocol & (RAW_HTABLE_SIZE - 1);
read_lock(&raw_v4_hashinfo.lock);
raw_sk = sk_head(&raw_v4_hashinfo.ht[hash]);
if (raw_sk != NULL) {
iph = (const struct iphdr *)skb->data;
net = dev_net(skb->dev);
while ((raw_sk = __raw_v4_lookup(net, raw_sk, protocol,
iph->daddr, iph->saddr,
skb->dev->ifindex)) != NULL) {
raw_err(raw_sk, skb, info);
raw_sk = sk_next(raw_sk);
iph = (const struct iphdr *)skb->data;
}
}
read_unlock(&raw_v4_hashinfo.lock);
}
static int raw_rcv_skb(struct sock *sk, struct sk_buff *skb)
{
/* Charge it to the socket. */
ipv4_pktinfo_prepare(sk, skb);
if (sock_queue_rcv_skb(sk, skb) < 0) {
kfree_skb(skb);
return NET_RX_DROP;
}
return NET_RX_SUCCESS;
}
int raw_rcv(struct sock *sk, struct sk_buff *skb)
{
if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
atomic_inc(&sk->sk_drops);
kfree_skb(skb);
return NET_RX_DROP;
}
nf_reset(skb);
skb_push(skb, skb->data - skb_network_header(skb));
raw_rcv_skb(sk, skb);
return 0;
}
static int raw_send_hdrinc(struct sock *sk, struct flowi4 *fl4,
void *from, size_t length,
struct rtable **rtp,
unsigned int flags)
{
struct inet_sock *inet = inet_sk(sk);
struct net *net = sock_net(sk);
struct iphdr *iph;
struct sk_buff *skb;
unsigned int iphlen;
int err;
struct rtable *rt = *rtp;
int hlen, tlen;
if (length > rt->dst.dev->mtu) {
ip_local_error(sk, EMSGSIZE, fl4->daddr, inet->inet_dport,
rt->dst.dev->mtu);
return -EMSGSIZE;
}
if (flags&MSG_PROBE)
goto out;
hlen = LL_RESERVED_SPACE(rt->dst.dev);
tlen = rt->dst.dev->needed_tailroom;
skb = sock_alloc_send_skb(sk,
length + hlen + tlen + 15,
flags & MSG_DONTWAIT, &err);
if (skb == NULL)
goto error;
skb_reserve(skb, hlen);
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
skb_dst_set(skb, &rt->dst);
*rtp = NULL;
skb_reset_network_header(skb);
iph = ip_hdr(skb);
skb_put(skb, length);
skb->ip_summed = CHECKSUM_NONE;
skb->transport_header = skb->network_header;
err = -EFAULT;
if (memcpy_fromiovecend((void *)iph, from, 0, length))
goto error_free;
iphlen = iph->ihl * 4;
/*
* We don't want to modify the ip header, but we do need to
* be sure that it won't cause problems later along the network
* stack. Specifically we want to make sure that iph->ihl is a
* sane value. If ihl points beyond the length of the buffer passed
* in, reject the frame as invalid
*/
err = -EINVAL;
if (iphlen > length)
goto error_free;
if (iphlen >= sizeof(*iph)) {
if (!iph->saddr)
iph->saddr = fl4->saddr;
iph->check = 0;
iph->tot_len = htons(length);
if (!iph->id)
ip_select_ident(skb, NULL);
iph->check = ip_fast_csum((unsigned char *)iph, iph->ihl);
}
if (iph->protocol == IPPROTO_ICMP)
icmp_out_count(net, ((struct icmphdr *)
skb_transport_header(skb))->type);
err = NF_HOOK(NFPROTO_IPV4, NF_INET_LOCAL_OUT, skb, NULL,
rt->dst.dev, dst_output);
if (err > 0)
err = net_xmit_errno(err);
if (err)
goto error;
out:
return 0;
error_free:
kfree_skb(skb);
error:
IP_INC_STATS(net, IPSTATS_MIB_OUTDISCARDS);
if (err == -ENOBUFS && !inet->recverr)
err = 0;
return err;
}
static int raw_probe_proto_opt(struct flowi4 *fl4, struct msghdr *msg)
{
struct iovec *iov;
u8 __user *type = NULL;
u8 __user *code = NULL;
int probed = 0;
unsigned int i;
if (!msg->msg_iov)
return 0;
for (i = 0; i < msg->msg_iovlen; i++) {
iov = &msg->msg_iov[i];
if (!iov)
continue;
switch (fl4->flowi4_proto) {
case IPPROTO_ICMP:
/* check if one-byte field is readable or not. */
if (iov->iov_base && iov->iov_len < 1)
break;
if (!type) {
type = iov->iov_base;
/* check if code field is readable or not. */
if (iov->iov_len > 1)
code = type + 1;
} else if (!code)
code = iov->iov_base;
if (type && code) {
if (get_user(fl4->fl4_icmp_type, type) ||
get_user(fl4->fl4_icmp_code, code))
return -EFAULT;
probed = 1;
}
break;
default:
probed = 1;
break;
}
if (probed)
break;
}
return 0;
}
static int raw_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
size_t len)
{
struct inet_sock *inet = inet_sk(sk);
struct ipcm_cookie ipc;
struct rtable *rt = NULL;
struct flowi4 fl4;
int free = 0;
__be32 daddr;
__be32 saddr;
u8 tos;
int err;
struct ip_options_data opt_copy;
err = -EMSGSIZE;
if (len > 0xFFFF)
goto out;
/*
* Check the flags.
*/
err = -EOPNOTSUPP;
if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message */
goto out; /* compatibility */
/*
* Get and verify the address.
*/
if (msg->msg_namelen) {
DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
err = -EINVAL;
if (msg->msg_namelen < sizeof(*usin))
goto out;
if (usin->sin_family != AF_INET) {
pr_info_once("%s: %s forgot to set AF_INET. Fix it!\n",
__func__, current->comm);
err = -EAFNOSUPPORT;
if (usin->sin_family)
goto out;
}
daddr = usin->sin_addr.s_addr;
/* ANK: I did not forget to get protocol from port field.
* I just do not know, who uses this weirdness.
* IP_HDRINCL is much more convenient.
*/
} else {
err = -EDESTADDRREQ;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
daddr = inet->inet_daddr;
}
ipc.addr = inet->inet_saddr;
ipc.opt = NULL;
ipc.tx_flags = 0;
ipc.ttl = 0;
ipc.tos = -1;
ipc.oif = sk->sk_bound_dev_if;
if (msg->msg_controllen) {
err = ip_cmsg_send(sock_net(sk), msg, &ipc, false);
if (unlikely(err)) {
kfree(ipc.opt);
goto out;
}
if (ipc.opt)
free = 1;
}
saddr = ipc.addr;
ipc.addr = daddr;
if (!ipc.opt) {
struct ip_options_rcu *inet_opt;
rcu_read_lock();
inet_opt = rcu_dereference(inet->inet_opt);
if (inet_opt) {
memcpy(&opt_copy, inet_opt,
sizeof(*inet_opt) + inet_opt->opt.optlen);
ipc.opt = &opt_copy.opt;
}
rcu_read_unlock();
}
if (ipc.opt) {
err = -EINVAL;
/* Linux does not mangle headers on raw sockets,
* so that IP options + IP_HDRINCL is non-sense.
*/
if (inet->hdrincl)
goto done;
if (ipc.opt->opt.srr) {
if (!daddr)
goto done;
daddr = ipc.opt->opt.faddr;
}
}
tos = get_rtconn_flags(&ipc, sk);
if (msg->msg_flags & MSG_DONTROUTE)
tos |= RTO_ONLINK;
if (ipv4_is_multicast(daddr)) {
if (!ipc.oif)
ipc.oif = inet->mc_index;
if (!saddr)
saddr = inet->mc_addr;
} else if (!ipc.oif)
ipc.oif = inet->uc_index;
flowi4_init_output(&fl4, ipc.oif, sk->sk_mark, tos,
RT_SCOPE_UNIVERSE,
inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol,
inet_sk_flowi_flags(sk) |
(inet->hdrincl ? FLOWI_FLAG_KNOWN_NH : 0),
daddr, saddr, 0, 0);
if (!inet->hdrincl) {
err = raw_probe_proto_opt(&fl4, msg);
if (err)
goto done;
}
security_sk_classify_flow(sk, flowi4_to_flowi(&fl4));
rt = ip_route_output_flow(sock_net(sk), &fl4, sk);
if (IS_ERR(rt)) {
err = PTR_ERR(rt);
rt = NULL;
goto done;
}
err = -EACCES;
if (rt->rt_flags & RTCF_BROADCAST && !sock_flag(sk, SOCK_BROADCAST))
goto done;
if (msg->msg_flags & MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
if (inet->hdrincl)
err = raw_send_hdrinc(sk, &fl4, msg->msg_iov, len,
&rt, msg->msg_flags);
else {
if (!ipc.addr)
ipc.addr = fl4.daddr;
lock_sock(sk);
err = ip_append_data(sk, &fl4, ip_generic_getfrag,
msg->msg_iov, len, 0,
&ipc, &rt, msg->msg_flags);
if (err)
ip_flush_pending_frames(sk);
else if (!(msg->msg_flags & MSG_MORE)) {
err = ip_push_pending_frames(sk, &fl4);
if (err == -ENOBUFS && !inet->recverr)
err = 0;
}
release_sock(sk);
}
done:
if (free)
kfree(ipc.opt);
ip_rt_put(rt);
out:
if (err < 0)
return err;
return len;
do_confirm:
dst_confirm(&rt->dst);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto done;
}
static void raw_close(struct sock *sk, long timeout)
{
/*
* Raw sockets may have direct kernel references. Kill them.
*/
ip_ra_control(sk, 0, NULL);
sk_common_release(sk);
}
static void raw_destroy(struct sock *sk)
{
lock_sock(sk);
ip_flush_pending_frames(sk);
release_sock(sk);
}
/* This gets rid of all the nasties in af_inet. -DaveM */
static int raw_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct inet_sock *inet = inet_sk(sk);
struct sockaddr_in *addr = (struct sockaddr_in *) uaddr;
int ret = -EINVAL;
int chk_addr_ret;
if (sk->sk_state != TCP_CLOSE || addr_len < sizeof(struct sockaddr_in))
goto out;
chk_addr_ret = inet_addr_type(sock_net(sk), addr->sin_addr.s_addr);
ret = -EADDRNOTAVAIL;
if (addr->sin_addr.s_addr && chk_addr_ret != RTN_LOCAL &&
chk_addr_ret != RTN_MULTICAST && chk_addr_ret != RTN_BROADCAST)
goto out;
inet->inet_rcv_saddr = inet->inet_saddr = addr->sin_addr.s_addr;
if (chk_addr_ret == RTN_MULTICAST || chk_addr_ret == RTN_BROADCAST)
inet->inet_saddr = 0; /* Use device */
sk_dst_reset(sk);
ret = 0;
out: return ret;
}
/*
* This should be easy, if there is something there
* we return it, otherwise we block.
*/
static int raw_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
size_t len, int noblock, int flags, int *addr_len)
{
struct inet_sock *inet = inet_sk(sk);
size_t copied = 0;
int err = -EOPNOTSUPP;
DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
struct sk_buff *skb;
if (flags & MSG_OOB)
goto out;
if (flags & MSG_ERRQUEUE) {
err = ip_recv_error(sk, msg, len, addr_len);
goto out;
}
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
goto out;
copied = skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (err)
goto done;
sock_recv_ts_and_drops(msg, sk, skb);
/* Copy the address. */
if (sin) {
sin->sin_family = AF_INET;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
sin->sin_port = 0;
memset(&sin->sin_zero, 0, sizeof(sin->sin_zero));
*addr_len = sizeof(*sin);
}
if (inet->cmsg_flags)
ip_cmsg_recv(msg, skb);
if (flags & MSG_TRUNC)
copied = skb->len;
done:
skb_free_datagram(sk, skb);
out:
if (err)
return err;
return copied;
}
static int raw_init(struct sock *sk)
{
struct raw_sock *rp = raw_sk(sk);
if (inet_sk(sk)->inet_num == IPPROTO_ICMP)
memset(&rp->filter, 0, sizeof(rp->filter));
return 0;
}
static int raw_seticmpfilter(struct sock *sk, char __user *optval, int optlen)
{
if (optlen > sizeof(struct icmp_filter))
optlen = sizeof(struct icmp_filter);
if (copy_from_user(&raw_sk(sk)->filter, optval, optlen))
return -EFAULT;
return 0;
}
static int raw_geticmpfilter(struct sock *sk, char __user *optval, int __user *optlen)
{
int len, ret = -EFAULT;
if (get_user(len, optlen))
goto out;
ret = -EINVAL;
if (len < 0)
goto out;
if (len > sizeof(struct icmp_filter))
len = sizeof(struct icmp_filter);
ret = -EFAULT;
if (put_user(len, optlen) ||
copy_to_user(optval, &raw_sk(sk)->filter, len))
goto out;
ret = 0;
out: return ret;
}
static int do_raw_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen)
{
if (optname == ICMP_FILTER) {
if (inet_sk(sk)->inet_num != IPPROTO_ICMP)
return -EOPNOTSUPP;
else
return raw_seticmpfilter(sk, optval, optlen);
}
return -ENOPROTOOPT;
}
static int raw_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen)
{
if (level != SOL_RAW)
return ip_setsockopt(sk, level, optname, optval, optlen);
return do_raw_setsockopt(sk, level, optname, optval, optlen);
}
#ifdef CONFIG_COMPAT
static int compat_raw_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen)
{
if (level != SOL_RAW)
return compat_ip_setsockopt(sk, level, optname, optval, optlen);
return do_raw_setsockopt(sk, level, optname, optval, optlen);
}
#endif
static int do_raw_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
if (optname == ICMP_FILTER) {
if (inet_sk(sk)->inet_num != IPPROTO_ICMP)
return -EOPNOTSUPP;
else
return raw_geticmpfilter(sk, optval, optlen);
}
return -ENOPROTOOPT;
}
static int raw_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
if (level != SOL_RAW)
return ip_getsockopt(sk, level, optname, optval, optlen);
return do_raw_getsockopt(sk, level, optname, optval, optlen);
}
#ifdef CONFIG_COMPAT
static int compat_raw_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
if (level != SOL_RAW)
return compat_ip_getsockopt(sk, level, optname, optval, optlen);
return do_raw_getsockopt(sk, level, optname, optval, optlen);
}
#endif
static int raw_ioctl(struct sock *sk, int cmd, unsigned long arg)
{
switch (cmd) {
case SIOCOUTQ: {
int amount = sk_wmem_alloc_get(sk);
return put_user(amount, (int __user *)arg);
}
case SIOCINQ: {
struct sk_buff *skb;
int amount = 0;
spin_lock_bh(&sk->sk_receive_queue.lock);
skb = skb_peek(&sk->sk_receive_queue);
if (skb != NULL)
amount = skb->len;
spin_unlock_bh(&sk->sk_receive_queue.lock);
return put_user(amount, (int __user *)arg);
}
default:
#ifdef CONFIG_IP_MROUTE
return ipmr_ioctl(sk, cmd, (void __user *)arg);
#else
return -ENOIOCTLCMD;
#endif
}
}
#ifdef CONFIG_COMPAT
static int compat_raw_ioctl(struct sock *sk, unsigned int cmd, unsigned long arg)
{
switch (cmd) {
case SIOCOUTQ:
case SIOCINQ:
return -ENOIOCTLCMD;
default:
#ifdef CONFIG_IP_MROUTE
return ipmr_compat_ioctl(sk, cmd, compat_ptr(arg));
#else
return -ENOIOCTLCMD;
#endif
}
}
#endif
struct proto raw_prot = {
.name = "RAW",
.owner = THIS_MODULE,
.close = raw_close,
.destroy = raw_destroy,
.connect = ip4_datagram_connect,
.disconnect = udp_disconnect,
.ioctl = raw_ioctl,
.init = raw_init,
.setsockopt = raw_setsockopt,
.getsockopt = raw_getsockopt,
.sendmsg = raw_sendmsg,
.recvmsg = raw_recvmsg,
.bind = raw_bind,
.backlog_rcv = raw_rcv_skb,
.release_cb = ip4_datagram_release_cb,
.hash = raw_hash_sk,
.unhash = raw_unhash_sk,
.obj_size = sizeof(struct raw_sock),
.h.raw_hash = &raw_v4_hashinfo,
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_raw_setsockopt,
.compat_getsockopt = compat_raw_getsockopt,
.compat_ioctl = compat_raw_ioctl,
#endif
};
#ifdef CONFIG_PROC_FS
static struct sock *raw_get_first(struct seq_file *seq)
{
struct sock *sk;
struct raw_iter_state *state = raw_seq_private(seq);
for (state->bucket = 0; state->bucket < RAW_HTABLE_SIZE;
++state->bucket) {
sk_for_each(sk, &state->h->ht[state->bucket])
if (sock_net(sk) == seq_file_net(seq))
goto found;
}
sk = NULL;
found:
return sk;
}
static struct sock *raw_get_next(struct seq_file *seq, struct sock *sk)
{
struct raw_iter_state *state = raw_seq_private(seq);
do {
sk = sk_next(sk);
try_again:
;
} while (sk && sock_net(sk) != seq_file_net(seq));
if (!sk && ++state->bucket < RAW_HTABLE_SIZE) {
sk = sk_head(&state->h->ht[state->bucket]);
goto try_again;
}
return sk;
}
static struct sock *raw_get_idx(struct seq_file *seq, loff_t pos)
{
struct sock *sk = raw_get_first(seq);
if (sk)
while (pos && (sk = raw_get_next(seq, sk)) != NULL)
--pos;
return pos ? NULL : sk;
}
void *raw_seq_start(struct seq_file *seq, loff_t *pos)
{
struct raw_iter_state *state = raw_seq_private(seq);
read_lock(&state->h->lock);
return *pos ? raw_get_idx(seq, *pos - 1) : SEQ_START_TOKEN;
}
EXPORT_SYMBOL_GPL(raw_seq_start);
void *raw_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct sock *sk;
if (v == SEQ_START_TOKEN)
sk = raw_get_first(seq);
else
sk = raw_get_next(seq, v);
++*pos;
return sk;
}
EXPORT_SYMBOL_GPL(raw_seq_next);
void raw_seq_stop(struct seq_file *seq, void *v)
{
struct raw_iter_state *state = raw_seq_private(seq);
read_unlock(&state->h->lock);
}
EXPORT_SYMBOL_GPL(raw_seq_stop);
static void raw_sock_seq_show(struct seq_file *seq, struct sock *sp, int i)
{
struct inet_sock *inet = inet_sk(sp);
__be32 dest = inet->inet_daddr,
src = inet->inet_rcv_saddr;
__u16 destp = 0,
srcp = inet->inet_num;
seq_printf(seq, "%4d: %08X:%04X %08X:%04X"
" %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %d\n",
i, src, srcp, dest, destp, sp->sk_state,
sk_wmem_alloc_get(sp),
sk_rmem_alloc_get(sp),
0, 0L, 0,
from_kuid_munged(seq_user_ns(seq), sock_i_uid(sp)),
0, sock_i_ino(sp),
atomic_read(&sp->sk_refcnt), sp, atomic_read(&sp->sk_drops));
}
static int raw_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_printf(seq, " sl local_address rem_address st tx_queue "
"rx_queue tr tm->when retrnsmt uid timeout "
"inode ref pointer drops\n");
else
raw_sock_seq_show(seq, v, raw_seq_private(seq)->bucket);
return 0;
}
static const struct seq_operations raw_seq_ops = {
.start = raw_seq_start,
.next = raw_seq_next,
.stop = raw_seq_stop,
.show = raw_seq_show,
};
int raw_seq_open(struct inode *ino, struct file *file,
struct raw_hashinfo *h, const struct seq_operations *ops)
{
int err;
struct raw_iter_state *i;
err = seq_open_net(ino, file, ops, sizeof(struct raw_iter_state));
if (err < 0)
return err;
i = raw_seq_private((struct seq_file *)file->private_data);
i->h = h;
return 0;
}
EXPORT_SYMBOL_GPL(raw_seq_open);
static int raw_v4_seq_open(struct inode *inode, struct file *file)
{
return raw_seq_open(inode, file, &raw_v4_hashinfo, &raw_seq_ops);
}
static const struct file_operations raw_seq_fops = {
.owner = THIS_MODULE,
.open = raw_v4_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
static __net_init int raw_init_net(struct net *net)
{
if (!proc_create("raw", S_IRUGO, net->proc_net, &raw_seq_fops))
return -ENOMEM;
return 0;
}
static __net_exit void raw_exit_net(struct net *net)
{
remove_proc_entry("raw", net->proc_net);
}
static __net_initdata struct pernet_operations raw_net_ops = {
.init = raw_init_net,
.exit = raw_exit_net,
};
int __init raw_proc_init(void)
{
return register_pernet_subsys(&raw_net_ops);
}
void __init raw_proc_exit(void)
{
unregister_pernet_subsys(&raw_net_ops);
}
#endif /* CONFIG_PROC_FS */
|
heptalium/rpi-sources-3.16
|
net/ipv4/raw.c
|
C
|
gpl-2.0
| 25,566
|
require 'rails_helper'
RSpec.describe Category, type: :model do
let(:category) { create(:category) }
it 'is valid factory for :category' do
expect(category).to be_valid
end
it 'is check empty category name' do
category = build(:category, name: nil)
category.valid?
expect(category.errors[:name]).to include("can't be blank")
end
it 'is check category name limit with 255 chars' do
category = build(:category, name: 's' * 256)
category.valid?
expect(category.errors[:name]).to include('is too long (maximum is 255 characters)')
end
it 'is check empty category uri' do
category = build(:category, uri: nil)
category.valid?
expect(category.errors[:uri]).to include("can't be blank")
end
it 'is check category uri limit with 64 chars' do
category = build(:category, uri: 's' * 65)
category.valid?
expect(category.errors[:uri]).to include('is too long (maximum is 64 characters)')
end
it 'is check uniq values of category uri' do
create(:category, uri: 'cars')
category = build(:category, uri: 'cars')
category.valid?
expect(category.errors[:uri]).to include('has already been taken')
end
it 'is check subcategory should be destroyed when category deleted' do
parent_category = create(:category)
create(:subcategory, category: parent_category)
expect { parent_category.destroy }.to change(Subcategory, :count).by(-1)
end
end
|
ufacode/wenternet
|
spec/models/category_spec.rb
|
Ruby
|
gpl-2.0
| 1,438
|
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : /rsc/js/helper.js source</title>
<link rel="stylesheet" href="../../sample.css" type="text/css">
<link rel="stylesheet" href="../../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Sat Nov 21 22:13:19 2015 -->
<!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net -->
<!-- http://phpxref.sourceforge.net/ -->
<script src="../../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
ext='.html';
relbase='../../';
subdir='rsc/js';
filename='helper.js.source.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
// -->
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
<script language="JavaScript" type="text/javascript">
<!--
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
// -->
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h2 class="listing-heading"><a href="./index.html">/rsc/js/</a> -> <a href="helper.js.html">helper.js</a> (source)</h2>
<div class="listing">
<p class="viewlinks">[<a href="helper.js.html">Summary view</a>]
[<a href="javascript:window.print();">Print</a>]
[<a href="helper.js.source.txt" target="_new">Text view</a>]
</p>
<pre>
<a name="l1"><span class="linenum"> 1</span></a> <span class="comment">/**</span>
<a name="l2"><span class="linenum"> 2</span></a> <span class="comment"> * This file implements the b2evoHelper object</span>
<a name="l3"><span class="linenum"> 3</span></a> <span class="comment"> * This file is part of the evoCore framework - {@link http://evocore.net/}</span>
<a name="l4"><span class="linenum"> 4</span></a> <span class="comment"> * See also {@link https://github.com/b2evolution/b2evolution}.</span>
<a name="l5"><span class="linenum"> 5</span></a> <span class="comment"> * @author yabs {@link http://innervisions.org.uk/ }</span>
<a name="l6"><span class="linenum"> 6</span></a> <span class="comment"> * @version $Id: helper.js 8373 2015-02-28 21:44:37Z fplanque $</span>
<a name="l7"><span class="linenum"> 7</span></a> <span class="comment"> */</span>
<a name="l8"><span class="linenum"> 8</span></a>
<a name="l9"><span class="linenum"> 9</span></a>
<a name="l10"><span class="linenum"> 10</span></a> var _b2evoHelper = function()
<a name="l11"><span class="linenum"> 11</span></a> {
<a name="l12"><span class="linenum"> 12</span></a> var me; <span class="comment">// reference to self</span>
<a name="l13"><span class="linenum"> 13</span></a>
<a name="l14"><span class="linenum"> 14</span></a> var _debug = false;
<a name="l15"><span class="linenum"> 15</span></a>
<a name="l16"><span class="linenum"> 16</span></a> var _t = Array(); <span class="comment">// translation strings</span>
<a name="l17"><span class="linenum"> 17</span></a>
<a name="l18"><span class="linenum"> 18</span></a> return {
<a name="l19"><span class="linenum"> 19</span></a> <span class="comment">/**</span>
<a name="l20"><span class="linenum"> 20</span></a> <span class="comment"> * Initialise the helper object</span>
<a name="l21"><span class="linenum"> 21</span></a> <span class="comment"> * Adds any translation strings found in html</span>
<a name="l22"><span class="linenum"> 22</span></a> <span class="comment"> *</span>
<a name="l23"><span class="linenum"> 23</span></a> <span class="comment"> * @param debug (boolean) enable debug mode</span>
<a name="l24"><span class="linenum"> 24</span></a> <span class="comment"> */</span>
<a name="l25"><span class="linenum"> 25</span></a> Init:function()
<a name="l26"><span class="linenum"> 26</span></a> {
<a name="l27"><span class="linenum"> 27</span></a> <span class="comment"> // set available params to defaults</span>
<a name="l28"><span class="linenum"> 28</span></a> var params = jQuery.fn.<a class="function" onClick="logFunction('extend')" href="../../_functions/extend.html" onMouseOver="funcPopup(event,'extend')">extend</a>({
<a name="l29"><span class="linenum"> 29</span></a> <span class="comment"> // no comma after final entry or IE barfs</span>
<a name="l30"><span class="linenum"> 30</span></a> debug:false, // are we in debug mode?
<a name="l31"><span class="linenum"> 31</span></a> }, ( arguments.length ? arguments[0] : '' ) );
<a name="l32"><span class="linenum"> 32</span></a>
<a name="l33"><span class="linenum"> 33</span></a> _debug = params.debug; <span class="comment">// set debug mode</span>
<a name="l34"><span class="linenum"> 34</span></a>
<a name="l35"><span class="linenum"> 35</span></a> me = this; <span class="comment">// set reference to self</span>
<a name="l36"><span class="linenum"> 36</span></a>
<a name="l37"><span class="linenum"> 37</span></a> jQuery( '<div id="b2evoMessages"></div>' ).prependTo( '.pblock' );<span class="comment">// placeholder for error/success messages</span>
<a name="l38"><span class="linenum"> 38</span></a>
<a name="l39"><span class="linenum"> 39</span></a> jQuery( '#b2evo_translations div' ).<a class="phpfunction" onClick="logFunction('each')" href="../../_functions/each.html" onMouseOver="phpfuncPopup(event,'each')">each</a>( function(){ // grab all translation strings
<a name="l40"><span class="linenum"> 40</span></a> var untranslated = jQuery( this ).<a class="function" onClick="logFunction('find')" href="../../_functions/find.html" onMouseOver="funcPopup(event,'find')">find</a>( '.b2evo_t_string' ).html();
<a name="l41"><span class="linenum"> 41</span></a> var translated = jQuery( this ).<a class="function" onClick="logFunction('find')" href="../../_functions/find.html" onMouseOver="funcPopup(event,'find')">find</a>( '.b2evo_translation' ).html();
<a name="l42"><span class="linenum"> 42</span></a> _t[ untranslated ] = translated;
<a name="l43"><span class="linenum"> 43</span></a> });
<a name="l44"><span class="linenum"> 44</span></a>
<a name="l45"><span class="linenum"> 45</span></a> me.<a class="function" onClick="logFunction('info')" href="../../_functions/info.html" onMouseOver="funcPopup(event,'info')">info</a>( 'Helper object ready' );
<a name="l46"><span class="linenum"> 46</span></a> },
<a name="l47"><span class="linenum"> 47</span></a>
<a name="l48"><span class="linenum"> 48</span></a>
<a name="l49"><span class="linenum"> 49</span></a> <span class="comment">/**</span>
<a name="l50"><span class="linenum"> 50</span></a> <span class="comment"> * Displays messages</span>
<a name="l51"><span class="linenum"> 51</span></a> <span class="comment"> *</span>
<a name="l52"><span class="linenum"> 52</span></a> <span class="comment"> * @param message (string) message to display</span>
<a name="l53"><span class="linenum"> 53</span></a> <span class="comment"> */</span>
<a name="l54"><span class="linenum"> 54</span></a> DisplayMessage:function( message )
<a name="l55"><span class="linenum"> 55</span></a> {
<a name="l56"><span class="linenum"> 56</span></a> jQuery( '#b2evoMessages' ).addClass( "log_container" ).html( message );
<a name="l57"><span class="linenum"> 57</span></a> },
<a name="l58"><span class="linenum"> 58</span></a>
<a name="l59"><span class="linenum"> 59</span></a>
<a name="l60"><span class="linenum"> 60</span></a> <span class="comment">/**</span>
<a name="l61"><span class="linenum"> 61</span></a> <span class="comment"> * Displays Server messages</span>
<a name="l62"><span class="linenum"> 62</span></a> <span class="comment"> *</span>
<a name="l63"><span class="linenum"> 63</span></a> <span class="comment"> * @param message (string) message to display</span>
<a name="l64"><span class="linenum"> 64</span></a> <span class="comment"> */</span>
<a name="l65"><span class="linenum"> 65</span></a> DisplayServerMessage:function( message )
<a name="l66"><span class="linenum"> 66</span></a> {
<a name="l67"><span class="linenum"> 67</span></a> jQuery( '#b2evoMessages' ).removeClass( "log_container" ).html( message );
<a name="l68"><span class="linenum"> 68</span></a> },
<a name="l69"><span class="linenum"> 69</span></a>
<a name="l70"><span class="linenum"> 70</span></a>
<a name="l71"><span class="linenum"> 71</span></a> <span class="comment">/**</span>
<a name="l72"><span class="linenum"> 72</span></a> <span class="comment"> * Fades out the selected element(s)</span>
<a name="l73"><span class="linenum"> 73</span></a> <span class="comment"> * For available effects see @link http://http://docs.jquery.com/Effects/animate#paramsoptions</span>
<a name="l74"><span class="linenum"> 74</span></a> <span class="comment"> */</span>
<a name="l75"><span class="linenum"> 75</span></a> FadeOut:function()
<a name="l76"><span class="linenum"> 76</span></a> {
<a name="l77"><span class="linenum"> 77</span></a> <span class="comment"> // set available params to defaults</span>
<a name="l78"><span class="linenum"> 78</span></a> var params = jQuery.fn.<a class="function" onClick="logFunction('extend')" href="../../_functions/extend.html" onMouseOver="funcPopup(event,'extend')">extend</a>({
<a name="l79"><span class="linenum"> 79</span></a> <span class="comment"> // no comma after final entry or IE barfs</span>
<a name="l80"><span class="linenum"> 80</span></a> selector:'', // jQuery selector for objects to fade
<a name="l81"><span class="linenum"> 81</span></a> start:{}, // params for start see @link http://http://docs.jquery.com/Effects/animate#paramsoptions
<a name="l82"><span class="linenum"> 82</span></a> end:{}, // params for end see @link http://http://docs.jquery.com/Effects/animate#paramsoptions
<a name="l83"><span class="linenum"> 83</span></a> callback:function(obj){}, // callback function when finished, will be passed the faded object
<a name="l84"><span class="linenum"> 84</span></a> remove_style: true // remove style attribute when finished
<a name="l85"><span class="linenum"> 85</span></a> }, ( arguments.length ? arguments[0] : '' ) );
<a name="l86"><span class="linenum"> 86</span></a> jQuery( params.selector ).<a class="function" onClick="logFunction('animate')" href="../../_functions/animate.html" onMouseOver="funcPopup(event,'animate')">animate</a>( params.start, {
<a name="l87"><span class="linenum"> 87</span></a> duration:"fast",
<a name="l88"><span class="linenum"> 88</span></a> complete:function(){
<a name="l89"><span class="linenum"> 89</span></a> jQuery( this ).<a class="function" onClick="logFunction('animate')" href="../../_functions/animate.html" onMouseOver="funcPopup(event,'animate')">animate</a>( params.end,{
<a name="l90"><span class="linenum"> 90</span></a> duration:"fast",
<a name="l91"><span class="linenum"> 91</span></a> complete:function(){
<a name="l92"><span class="linenum"> 92</span></a> if( params.remove_style )
<a name="l93"><span class="linenum"> 93</span></a> {
<a name="l94"><span class="linenum"> 94</span></a> jQuery( this ).removeAttr( 'style' );
<a name="l95"><span class="linenum"> 95</span></a> }
<a name="l96"><span class="linenum"> 96</span></a> params.callback( this ); <span class="comment">// trigger callback</span>
<a name="l97"><span class="linenum"> 97</span></a> }
<a name="l98"><span class="linenum"> 98</span></a> });
<a name="l99"><span class="linenum"> 99</span></a> }
<a name="l100"><span class="linenum"> 100</span></a> });
<a name="l101"><span class="linenum"> 101</span></a> },
<a name="l102"><span class="linenum"> 102</span></a>
<a name="l103"><span class="linenum"> 103</span></a>
<a name="l104"><span class="linenum"> 104</span></a> <span class="comment">/**</span>
<a name="l105"><span class="linenum"> 105</span></a> <span class="comment"> * replicates PHP's str_repeat() function</span>
<a name="l106"><span class="linenum"> 106</span></a> <span class="comment"> *</span>
<a name="l107"><span class="linenum"> 107</span></a> <span class="comment"> * @param data (string) string to repeat</span>
<a name="l108"><span class="linenum"> 108</span></a> <span class="comment"> * @param multiplier (int) number of repeats required</span>
<a name="l109"><span class="linenum"> 109</span></a> <span class="comment"> *</span>
<a name="l110"><span class="linenum"> 110</span></a> <span class="comment"> * @return the multiplied string</span>
<a name="l111"><span class="linenum"> 111</span></a> <span class="comment"> */</span>
<a name="l112"><span class="linenum"> 112</span></a> str_repeat:function( data, multiplier )
<a name="l113"><span class="linenum"> 113</span></a> {
<a name="l114"><span class="linenum"> 114</span></a> if( multiplier = Math.<a class="phpfunction" onClick="logFunction('floor')" href="../../_functions/floor.html" onMouseOver="phpfuncPopup(event,'floor')">floor</a>( multiplier ) )
<a name="l115"><span class="linenum"> 115</span></a> {
<a name="l116"><span class="linenum"> 116</span></a> return new Array( multiplier + 1 ).join( data );
<a name="l117"><span class="linenum"> 117</span></a> }
<a name="l118"><span class="linenum"> 118</span></a> return false;
<a name="l119"><span class="linenum"> 119</span></a> },
<a name="l120"><span class="linenum"> 120</span></a>
<a name="l121"><span class="linenum"> 121</span></a>
<a name="l122"><span class="linenum"> 122</span></a> <span class="comment">/**</span>
<a name="l123"><span class="linenum"> 123</span></a> <span class="comment"> * Translates a string</span>
<a name="l124"><span class="linenum"> 124</span></a> <span class="comment"> *</span>
<a name="l125"><span class="linenum"> 125</span></a> <span class="comment"> * @param untranslated (string) the string to be translated</span>
<a name="l126"><span class="linenum"> 126</span></a> <span class="comment"> *</span>
<a name="l127"><span class="linenum"> 127</span></a> <span class="comment"> * @return string translated string if available or original string</span>
<a name="l128"><span class="linenum"> 128</span></a> <span class="comment"> */</span>
<a name="l129"><span class="linenum"> 129</span></a> T_:function( untranslated )
<a name="l130"><span class="linenum"> 130</span></a> {
<a name="l131"><span class="linenum"> 131</span></a> if( typeof( _t[ untranslated ] ) == 'string' )
<a name="l132"><span class="linenum"> 132</span></a> { // we have a translation
<a name="l133"><span class="linenum"> 133</span></a> return _t[ untranslated ];
<a name="l134"><span class="linenum"> 134</span></a> }
<a name="l135"><span class="linenum"> 135</span></a> return untranslated;
<a name="l136"><span class="linenum"> 136</span></a> },
<a name="l137"><span class="linenum"> 137</span></a>
<a name="l138"><span class="linenum"> 138</span></a>
<a name="l139"><span class="linenum"> 139</span></a> <span class="comment">/**</span>
<a name="l140"><span class="linenum"> 140</span></a> <span class="comment"> * Add Log message to console if enabled and in debug mode</span>
<a name="l141"><span class="linenum"> 141</span></a> <span class="comment"> *</span>
<a name="l142"><span class="linenum"> 142</span></a> <span class="comment"> * @param message (string) message to be added to the console</span>
<a name="l143"><span class="linenum"> 143</span></a> <span class="comment"> */</span>
<a name="l144"><span class="linenum"> 144</span></a> log:function(message)
<a name="l145"><span class="linenum"> 145</span></a> {
<a name="l146"><span class="linenum"> 146</span></a> if( _debug && typeof( console ) == 'object' )
<a name="l147"><span class="linenum"> 147</span></a> {
<a name="l148"><span class="linenum"> 148</span></a> console.<a class="phpfunction" onClick="logFunction('log')" href="../../_functions/log.html" onMouseOver="phpfuncPopup(event,'log')">log</a>( message );
<a name="l149"><span class="linenum"> 149</span></a> }
<a name="l150"><span class="linenum"> 150</span></a> },
<a name="l151"><span class="linenum"> 151</span></a>
<a name="l152"><span class="linenum"> 152</span></a>
<a name="l153"><span class="linenum"> 153</span></a> <span class="comment">/**</span>
<a name="l154"><span class="linenum"> 154</span></a> <span class="comment"> * Add Error message to console if enabled and in debug mode</span>
<a name="l155"><span class="linenum"> 155</span></a> <span class="comment"> *</span>
<a name="l156"><span class="linenum"> 156</span></a> <span class="comment"> * @param message (string) message to be added to the console</span>
<a name="l157"><span class="linenum"> 157</span></a> <span class="comment"> */</span>
<a name="l158"><span class="linenum"> 158</span></a> error:function(message)
<a name="l159"><span class="linenum"> 159</span></a> {
<a name="l160"><span class="linenum"> 160</span></a> if( _debug && typeof( console ) == 'object' )
<a name="l161"><span class="linenum"> 161</span></a> {
<a name="l162"><span class="linenum"> 162</span></a> console.error( message );
<a name="l163"><span class="linenum"> 163</span></a> }
<a name="l164"><span class="linenum"> 164</span></a> },
<a name="l165"><span class="linenum"> 165</span></a>
<a name="l166"><span class="linenum"> 166</span></a>
<a name="l167"><span class="linenum"> 167</span></a> <span class="comment">/**</span>
<a name="l168"><span class="linenum"> 168</span></a> <span class="comment"> * Add Info message to console if enabled and in debug mode</span>
<a name="l169"><span class="linenum"> 169</span></a> <span class="comment"> *</span>
<a name="l170"><span class="linenum"> 170</span></a> <span class="comment"> * @param message (string) message to be added to the console</span>
<a name="l171"><span class="linenum"> 171</span></a> <span class="comment"> */</span>
<a name="l172"><span class="linenum"> 172</span></a> info:function(message)
<a name="l173"><span class="linenum"> 173</span></a> {
<a name="l174"><span class="linenum"> 174</span></a> if( _debug && typeof( console ) == 'object' )
<a name="l175"><span class="linenum"> 175</span></a> {
<a name="l176"><span class="linenum"> 176</span></a> console.<a class="function" onClick="logFunction('info')" href="../../_functions/info.html" onMouseOver="funcPopup(event,'info')">info</a>( message );
<a name="l177"><span class="linenum"> 177</span></a> }
<a name="l178"><span class="linenum"> 178</span></a> }
<a name="l179"><span class="linenum"> 179</span></a> }
<a name="l180"><span class="linenum"> 180</span></a> } <span class="comment">// _b2evoHelper</span>
<a name="l181"><span class="linenum"> 181</span></a>
<a name="l182"><span class="linenum"> 182</span></a> <span class="comment">// create instance of the helper</span>
<a name="l183"><span class="linenum"> 183</span></a> var b2evoHelper = new _b2evoHelper();
</pre>
</div>
<script language="JavaScript" type="text/javascript">
FUNC_DATA={
'extend': ['extend', '', [['rsc/js/videojs','video.js',9920]], 740],
'find': ['find', '', [['rsc/js/flowplayer','flowplayer.js',1498]], 701],
'animate': ['animate', '', [['rsc/js/jquery','jquery.scrollto.js',154]], 119],
'info': ['info', 'Builds an info field. An info field is a fieldset containing a label div and an info div. ', [['inc/_core/ui/forms','_form.class.php',2822]], 237],
'log': ['log', '', [], 89],
'each': ['each', '', [], 826],
'floor': ['floor', '', [], 116]};
CLASS_DATA={
};
CONST_DATA={
};
</script>
<div id="func-popup" class="funcpopup"><p id="func-title" class="popup-title">title</p><p id="func-desc" class="popup-desc">Description</p><p id="func-body" class="popup-body">Body</p></div>
<div id="class-popup" class="funcpopup"><p id="class-title" class="popup-title">title</p><p id="class-desc" class="popup-desc">Description</p><p id="class-body" class="popup-body">Body</p></div>
<div id="const-popup" class="funcpopup"><p id="const-title" class="popup-title">title</p><p id="const-desc" class="popup-desc">Description</p><p id="const-body" class="popup-body">Body</p></div>
<div id="req-popup" class="funcpopup"><p id="req-title" class="popup-title">title</p><p id="req-body" class="popup-body">Body</p></div>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Sat Nov 21 22:13:19 2015</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
|
mgsolipa/b2evolution_phpxref
|
rsc/js/helper.js.source.html
|
HTML
|
gpl-2.0
| 24,947
|
<!--A Design by W3layouts
Author: W3layout
Author URL: http://w3layouts.com
License: Creative Commons Attribution 3.0 Unported
License URL: http://creativecommons.org/licenses/by/3.0/
-->
<!DOCTYPE HTML>
<head>
<title>Ui kits for Iphone, Android and Smartphone Website Templates | Home :: w3layouts</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<link href="{{ url_for('static', filename='css/style.css') }}" rel="stylesheet" type="text/css" media="all"/>
<script type="text/javascript" src="{{ url_for('static', filename='js/jquery.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/login.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/Chart.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/jquery.easing.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/jquery.ulslide.js') }}"></script>
<link type="text/css" href="{{ url_for('static', filename='css/mmenu.css') }}" rel="stylesheet" media="all" />
<script type="text/javascript" src="{{ url_for('static', filename='js/jquery.mmenu.min.js') }}"></script>
<script type="text/javascript">
$(function() {
$('nav#menu').mmenu();
});
</script>
</head>
<body>
<div class="wrap">
<div class="header">
<div class="header_top">
<div class="menu-ico"><a href="#menu"></a></div>
<div class="profile_details">
<div id="loginContainer">
<a id="loginButton" class=""><span>Me</span></a>
<div id="loginBox">
<form id="loginForm">
<fieldset id="body">
<div class="user-info">
<h4>Hello,<a href="#"> Username</a></h4>
<ul>
<li class="logout"><a href="#"> Logout</a></li>
<div class="clear"></div>
</ul>
</div>
</fieldset>
</form>
</div>
</div>
<div class="profile_img">
<a href=""><img src="{{ url_for('static', filename='images/profile_img40x40.jpg') }}" alt="" /> </a>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
</div>
</div>
<div class="main">
<div class="wrap">
<div class="column_left">
<!---
<div class="menu_box">
<h3>Menu Box</h3>
<div class="menu_box_list">
<ul>
<li><a href="#" class="messages"><span>Messages</span><label class="digits">24</label><div class="clear"></div></a></li>
<li class="active"><a href="#" class="invites"><span>Invites</span><label class="digits active">3</label><div class="clear"></div></a></li>
<li><a href="#" class="events"><span>Events</span><label class="digits">5</label><div class="clear"></div></a></li>
<li><a href="#" class="account_settings"><span>Account Settings</span></a></li>
<li><a href="#" class="statistics"><span>Statistics</span></a></li>
</ul>
</div>
</div>
----->
<div class="column_middle">
<div class="column_middle_grid1">
<div class="profile_picture">
<a href=""><img src="{{ url_for('static', filename='images/profile_img150x150.jpg') }}" alt="" /> </a>
<div class="profile_picture_name">
<h2>Anne Hathaway</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing </p>
</div>
<span><a href="#"> <img src="{{ url_for('static', filename='images/follow_user.png') }}" alt="" /> </a></span>
</div>
</div>
<div class="weather">
<h3><i><img src="{{ url_for('static', filename='images/location.png') }}" alt="" /> </i> Cluj-Napoca / Ro</h3>
<div class="today_temp">
<div class="temp">
<figure>Fri 29/06<span>24<em>o</em></span></figure>
</div>
<img src="{{ url_for('static', filename='images/sun.png') }}" alt="" />
</div>
<div class="temp_list">
<ul>
<li><a href="#"><span class="day_name">Sat</span> 29/06
<label class="digits">25<em>o</em> <i><img src="{{ url_for('static', filename='images/sun_icon1.png') }}" alt="" /></i></label><div class="clear"></div></a></li>
<li class="active"><a href="#"><span class="day_name">Sun</span> 30/06
<label class="digits">22<em>o</em> <i><img src="{{ url_for('static', filename='images/clouds.png') }}" alt="" /></i></label><div class="clear"></div></a></li>
</ul>
</div>
</div>
<div class="tweets">
<h3><i><img src="{{ url_for('static', filename='images/tweets.png') }}" alt="" /> </i> Latest Tweets</h3>
<div class="tweets_list">
<ul>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore <a href="#">@Neque</a>
<span>10 minutes ago</span></li>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore eiusmod <a href="#">#Creative Cloud</a>
<span>2 hours ago</span></li>
</ul>
</div>
</div>
</div>
<div class="column_right">
<div class="column_right_grid sign-in">
<div class="sign_in">
<h3>Sign in to your account</h3>
<form>
<span>
<i><img src="{{ url_for('static', filename='images/mail.png') }}" alt="" /></i><input type="text" value="Enter your email" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Enter your email';}">
</span>
<span>
<i><img src="{{ url_for('static', filename='images/lock.png') }}" alt="" /></i>
<input type="password" placeholder="password">
</span>
<input type="submit" class="my-button" value="Sign In">
</form>
<h4><a href="#">Forget Password?</a></h4>
</div>
<div class="signin_facebook">
<p><a href="#"> <i> <img src="{{ url_for('static', filename='images/facebook.png') }}" alt="" /></i>Sign in with facebook</a></p>
</div>
</div>
<div class="column_right_grid date_events">
<h3><a href="#" id="slide_prev"><img src="{{ url_for('static', filename='images/arrow-left.png') }}" alt="" /></a> Wednesday <a href="#" id="slide_next"><img src="{{ url_for('static', filename='images/arrow-right.png') }}" alt="" /></a></h3>
<ul id="slide" class="event_dates">
<li>26</li>
<li>25</li>
<li>24</li>
<li>23</li>
<li>22</li>
<li>21</li>
<li>20</li>
<li>19</li>
<li>18</li>
<li>17</li>
<li>16</li>
<li>15</li>
<li>14</li>
<li>13</li>
<li>12</li>
<li>11</li>
<li>10</li>
<li>9</li>
<li>8</li>
<li>7</li>
<li>6</li>
<li>5</li>
<li>4</li>
<li>3</li>
<li>2</li>
<li>1</li>
<li>31</li>
<li>30</li>
<li>29</li>
<li>28</li>
<li>27</li>
</ul>
<div class="button"><a href="#">Add Event</a></div>
<script type="text/javascript">
$(function() {
$('#slide').ulslide({
effect: {
type: 'carousel', // slide or fade
axis: 'x', // x, y
showCount:1
},
nextButton: '#slide_next',
prevButton: '#slide_prev',
duration: 800,
/*autoslide: 2000,*/
easing: 'easeOutBounce'
});
});
</script>
</div>
</div>
<div class="clear"></div>
</div>
</div>
<nav id="menu">
<ul>
<li><a href="#"><i><img src="{{ url_for('static', filename='images/user.png') }}"></i> Profile</a></li>
<li><a href="#"><span><i><img src="{{ url_for('static', filename='images/mail.png') }}"></i> Messages</span><label class="digits active">5</label><div class="clear"></div></a></li>
<li><a href="#"><span> <i><img src="{{ url_for('static', filename='images/events.png') }}"></i> Events</span><label class="digits">5</label><div class="clear"></div></a></li>
<li><a href="#"><i><img src="{{ url_for('static', filename='images/settings.png') }}" alt="" /></i>Settings</a></li>
</ul>
</nav>
<div class="copy-right">
<p>© 2013 Designed by <a href="http://graphicburger.com/flat-design-ui-components/" target="_blank">GraphicBurger</a> • Template by <a href="http://w3layouts.com" target="_blank">w3layouts</a> </p>
</div>
</body>
</html>
|
SweenEy1130/babel-server
|
app/templates/full.html
|
HTML
|
gpl-2.0
| 9,769
|
<form role="search" method="get" id="searchform" class="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<div>
<input type="submit" id="searchsubmit" value="<?php echo esc_attr_x( 'Search', 'submit button' ); ?>" />
<label class="screen-reader-text" for="s"><?php _x( 'Search for:', 'label' ); ?></label>
<input id="autocomplete" title="type "a"" type="text" value="<?php echo get_search_query(); ?>" name="s" id="s" placeholder=" Help you find anything?" />
</div>
</form>
|
Kitzo/door-fellowship
|
wp-content/themes/chris-base-theme/searchform.php
|
PHP
|
gpl-2.0
| 506
|
require 'vx/container_connector'
require 'vx/instrumentation'
require 'active_support/notifications'
$stdout.puts ' --> initializing Vx::ContainerConnector'
Vx::ContainerConnector.instrumenter = ActiveSupport::Notifications
|
pacoguzman/vx-worker
|
lib/vx/worker/initializers/containers.rb
|
Ruby
|
gpl-2.0
| 226
|
import React from "react";
import { connect } from "react-redux";
import { TimeMode, AppState, Dispatch } from "../../types";
import { getTimeObj } from "../../utils";
import * as Actions from "../../actionCreators";
import * as Selectors from "../../selectors";
import { TIME_MODE } from "../../constants";
interface StateProps {
timeElapsed: number;
duration: number;
timeMode: TimeMode;
}
interface DispatchProps {
toggleTimeMode(): void;
}
const Time = ({
timeElapsed,
duration,
timeMode,
toggleTimeMode,
}: StateProps & DispatchProps) => {
const seconds =
timeMode === TIME_MODE.ELAPSED ? timeElapsed : duration - timeElapsed;
const timeObj = getTimeObj(seconds);
return (
<div id="time" onClick={toggleTimeMode} className="countdown">
{timeMode === TIME_MODE.REMAINING && <div id="minus-sign" />}
<div
id="minute-first-digit"
className={`digit digit-${timeObj.minutesFirstDigit}`}
/>
<div
id="minute-second-digit"
className={`digit digit-${timeObj.minutesSecondDigit}`}
/>
<div
id="second-first-digit"
className={`digit digit-${timeObj.secondsFirstDigit}`}
/>
<div
id="second-second-digit"
className={`digit digit-${timeObj.secondsSecondDigit}`}
/>
</div>
);
};
const mapStateToProps = (state: AppState): StateProps => {
const timeElapsed = Selectors.getTimeElapsed(state);
const duration = Selectors.getDuration(state);
const { timeMode } = state.media;
return { timeElapsed, duration: duration || 0, timeMode };
};
const mapDispatchToProps = (dispatch: Dispatch): DispatchProps => ({
toggleTimeMode: () => dispatch(Actions.toggleTimeMode()),
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Time);
|
mazhar266/mazhar266.github.io
|
webamp/js/components/MainWindow/Time.tsx
|
TypeScript
|
gpl-2.0
| 1,798
|
--//=============================================================================
--//
function _DrawTextureAspect(x,y,w,h ,tw,th)
local twa = w/tw
local tha = h/th
local aspect = 1
if (twa < tha) then
aspect = twa
y = y + h*0.5 - th*aspect*0.5
h = th*aspect
else
aspect = tha
x = x + w*0.5 - tw*aspect*0.5
w = tw*aspect
end
local right = math.ceil(x+w)
local bottom = math.ceil(y+h)
x = math.ceil(x)
y = math.ceil(y)
gl.TexRect(x,y,right,bottom,false,true)
end
local _DrawTextureAspect = _DrawTextureAspect
function _DrawTiledTexture(x,y,w,h, skLeft,skTop,skRight,skBottom, texw,texh, texIndex)
texIndex = texIndex or 0
local txLeft = skLeft/texw
local txTop = skTop/texh
local txRight = skRight/texw
local txBottom = skBottom/texh
--//scale down the texture if we don't have enough space
local scaleY = h/(skTop+skBottom)
local scaleX = w/(skLeft+skRight)
local scale = (scaleX < scaleY) and scaleX or scaleY
if (scale<1) then
skTop = skTop * scale
skBottom = skBottom * scale
skLeft = skLeft * scale
skRight = skRight * scale
end
--//topleft
gl.MultiTexCoord(texIndex,0,0)
gl.Vertex(x, y)
gl.MultiTexCoord(texIndex,0,txTop)
gl.Vertex(x, y+skTop)
gl.MultiTexCoord(texIndex,txLeft,0)
gl.Vertex(x+skLeft, y)
gl.MultiTexCoord(texIndex,txLeft,txTop)
gl.Vertex(x+skLeft, y+skTop)
--//topcenter
gl.MultiTexCoord(texIndex,1-txRight,0)
gl.Vertex(x+w-skRight, y)
gl.MultiTexCoord(texIndex,1-txRight,txTop)
gl.Vertex(x+w-skRight, y+skTop)
--//topright
gl.MultiTexCoord(texIndex,1,0)
gl.Vertex(x+w, y)
gl.MultiTexCoord(texIndex,1,txTop)
gl.Vertex(x+w, y+skTop)
--//right center
gl.MultiTexCoord(texIndex,1,1-txBottom)
gl.Vertex(x+w, y+h-skBottom) --//degenerate
gl.MultiTexCoord(texIndex,1-txRight,txTop)
gl.Vertex(x+w-skRight, y+skTop)
gl.MultiTexCoord(texIndex,1-txRight,1-txBottom)
gl.Vertex(x+w-skRight, y+h-skBottom)
--//background
gl.MultiTexCoord(texIndex,txLeft,txTop)
gl.Vertex(x+skLeft, y+skTop)
gl.MultiTexCoord(texIndex,txLeft,1-txBottom)
gl.Vertex(x+skLeft, y+h-skBottom)
--//left center
gl.MultiTexCoord(texIndex,0,txTop)
gl.Vertex(x, y+skTop)
gl.MultiTexCoord(texIndex,0,1-txBottom)
gl.Vertex(x, y+h-skBottom)
--//bottom right
gl.MultiTexCoord(texIndex,0,1)
gl.Vertex(x, y+h) --//degenerate
gl.MultiTexCoord(texIndex,txLeft,1-txBottom)
gl.Vertex(x+skLeft, y+h-skBottom)
gl.MultiTexCoord(texIndex,txLeft,1)
gl.Vertex(x+skLeft, y+h)
--//bottom center
gl.MultiTexCoord(texIndex,1-txRight,1-txBottom)
gl.Vertex(x+w-skRight, y+h-skBottom)
gl.MultiTexCoord(texIndex,1-txRight,1)
gl.Vertex(x+w-skRight, y+h)
--//bottom right
gl.MultiTexCoord(texIndex,1,1-txBottom)
gl.Vertex(x+w, y+h-skBottom)
gl.MultiTexCoord(texIndex,1,1)
gl.Vertex(x+w, y+h)
end
local _DrawTiledTexture = _DrawTiledTexture
function _DrawTiledBorder(x,y,w,h, skLeft,skTop,skRight,skBottom, texw,texh, texIndex)
texIndex = texIndex or 0
local txLeft = skLeft/texw
local txTop = skTop/texh
local txRight = skRight/texw
local txBottom = skBottom/texh
--//scale down the texture if we don't have enough space
local scaleY = h/(skTop+skBottom)
local scaleX = w/(skLeft+skRight)
local scale = (scaleX < scaleY) and scaleX or scaleY
if (scale<1) then
skTop = skTop * scale
skBottom = skBottom * scale
skLeft = skLeft * scale
skRight = skRight * scale
end
--//topleft
gl.MultiTexCoord(texIndex,0,0)
gl.Vertex(x, y)
gl.MultiTexCoord(texIndex,0,txTop)
gl.Vertex(x, y+skTop)
gl.MultiTexCoord(texIndex,txLeft,0)
gl.Vertex(x+skLeft, y)
gl.MultiTexCoord(texIndex,txLeft,txTop)
gl.Vertex(x+skLeft, y+skTop)
--//topcenter
gl.MultiTexCoord(texIndex,1-txRight,0)
gl.Vertex(x+w-skRight, y)
gl.MultiTexCoord(texIndex,1-txRight,txTop)
gl.Vertex(x+w-skRight, y+skTop)
--//topright
gl.MultiTexCoord(texIndex,1,0)
gl.Vertex(x+w, y)
gl.MultiTexCoord(texIndex,1,txTop)
gl.Vertex(x+w, y+skTop)
--//right center
gl.Vertex(x+w, y+skTop) --//degenerate
gl.MultiTexCoord(texIndex,1-txRight,txTop)
gl.Vertex(x+w-skRight, y+skTop)
gl.MultiTexCoord(texIndex,1,1-txBottom)
gl.Vertex(x+w, y+h-skBottom)
gl.MultiTexCoord(texIndex,1-txRight,1-txBottom)
gl.Vertex(x+w-skRight, y+h-skBottom)
--//bottom right
gl.MultiTexCoord(texIndex,1,1)
gl.Vertex(x+w, y+h)
gl.MultiTexCoord(texIndex,1-txRight,1)
gl.Vertex(x+w-skRight, y+h)
--//bottom center
gl.Vertex(x+w-skRight, y+h) --//degenerate
gl.MultiTexCoord(texIndex,1-txRight,1-txBottom)
gl.Vertex(x+w-skRight, y+h-skBottom)
gl.MultiTexCoord(texIndex,txLeft,1)
gl.Vertex(x+skLeft, y+h)
gl.MultiTexCoord(texIndex,txLeft,1-txBottom)
gl.Vertex(x+skLeft, y+h-skBottom)
--//bottom left
gl.MultiTexCoord(texIndex,0,1)
gl.Vertex(x, y+h)
gl.MultiTexCoord(texIndex,0,1-txBottom)
gl.Vertex(x, y+h-skBottom)
--//left center
gl.Vertex(x, y+h-skBottom) --//degenerate
gl.MultiTexCoord(texIndex,0,txTop)
gl.Vertex(x, y+skTop)
gl.MultiTexCoord(texIndex,txLeft,1-txBottom)
gl.Vertex(x+skLeft, y+h-skBottom)
gl.MultiTexCoord(texIndex,txLeft,txTop)
gl.Vertex(x+skLeft, y+skTop)
end
local _DrawTiledBorder = _DrawTiledBorder
local function _DrawDragGrip(obj)
local x = 13
local y = 8
local w = obj.dragGripSize[1]
local h = obj.dragGripSize[2]
gl.Color(0.8,0.8,0.8,0.9)
gl.Vertex(x, y + h*0.5)
gl.Vertex(x + w*0.5, y)
gl.Vertex(x + w*0.5, y + h*0.5)
gl.Color(0.3,0.3,0.3,0.9)
gl.Vertex(x + w*0.5, y + h*0.5)
gl.Vertex(x + w*0.5, y)
gl.Vertex(x + w, y + h*0.5)
gl.Vertex(x + w*0.5, y + h)
gl.Vertex(x, y + h*0.5)
gl.Vertex(x + w*0.5, y + h*0.5)
gl.Color(0.1,0.1,0.1,0.9)
gl.Vertex(x + w*0.5, y + h)
gl.Vertex(x + w*0.5, y + h*0.5)
gl.Vertex(x + w, y + h*0.5)
end
local function _DrawResizeGrip(obj)
if (obj.resizable) then
local x = 0
local y = 0
local resizeBox = GetRelativeObjBox(obj,obj.boxes.resize)
x = x-1
y = y-1
gl.Color(1,1,1,0.2)
gl.Vertex(x + resizeBox[1], y + resizeBox[4])
gl.Vertex(x + resizeBox[3], y + resizeBox[2])
gl.Vertex(x + resizeBox[1] + math.ceil((resizeBox[3] - resizeBox[1])*0.33), y + resizeBox[4])
gl.Vertex(x + resizeBox[3], y + resizeBox[2] + math.ceil((resizeBox[4] - resizeBox[2])*0.33))
gl.Vertex(x + resizeBox[1] + math.ceil((resizeBox[3] - resizeBox[1])*0.66), y + resizeBox[4])
gl.Vertex(x + resizeBox[3], y + resizeBox[2] + math.ceil((resizeBox[4] - resizeBox[2])*0.66))
x = x+1
y = y+1
gl.Color(0.1, 0.1, 0.1, 0.9)
gl.Vertex(x + resizeBox[1], y + resizeBox[4])
gl.Vertex(x + resizeBox[3], y + resizeBox[2])
gl.Vertex(x + resizeBox[1] + math.ceil((resizeBox[3] - resizeBox[1])*0.33), y + resizeBox[4])
gl.Vertex(x + resizeBox[3], y + resizeBox[2] + math.ceil((resizeBox[4] - resizeBox[2])*0.33))
gl.Vertex(x + resizeBox[1] + math.ceil((resizeBox[3] - resizeBox[1])*0.66), y + resizeBox[4])
gl.Vertex(x + resizeBox[3], y + resizeBox[2] + math.ceil((resizeBox[4] - resizeBox[2])*0.66))
end
end
local function _DrawCursor(x, y, w, h)
gl.Vertex(x, y)
gl.Vertex(x, y + h)
gl.Vertex(x + w, y)
gl.Vertex(x + w, y + h)
end
--//=============================================================================
--//
function DrawWindow(obj)
local w = obj.width
local h = obj.height
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
local c = obj.color
if (c) then
gl.Color(c)
else
gl.Color(1,1,1,1)
end
TextureHandler.LoadTexture(0,obj.TileImage,obj)
local texInfo = gl.TextureInfo(obj.TileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th)
gl.Texture(0,false)
if (obj.caption) then
obj.font:Print(obj.caption, w*0.5, 9, "center")
end
end
--//=============================================================================
--//
function DrawButton(obj)
if obj.debug then Spring.Echo("DrawButton", obj.name, obj.state.pressed) end
local w = obj.width
local h = obj.height
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
local bgcolor = obj.backgroundColor
if (obj.state.pressed) then
bgcolor = mulColor(bgcolor, 0.4)
elseif (obj.state.hovered) --[[ or (obj.state.focused)]] then
bgcolor = obj.focusColor
--bgcolor = mixColors(bgcolor, obj.focusColor, 0.5)
end
gl.Color(bgcolor)
TextureHandler.LoadTexture(0,obj.TileImageBK,obj)
local texInfo = gl.TextureInfo(obj.TileImageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
local fgcolor = obj.borderColor
if (obj.state.pressed) then
fgcolor = mulColor(fgcolor, 0.4)
elseif (obj.state.hovered) --[[ or (obj.state.focused)]] then
fgcolor = obj.focusColor
end
gl.Color(fgcolor)
TextureHandler.LoadTexture(0,obj.TileImageFG,obj)
local texInfo = gl.TextureInfo(obj.TileImageFG) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
if (obj.caption) then
obj.font:Print(obj.caption, w*0.5, h*0.5, "center", "center")
end
end
function DrawComboBox(self)
DrawButton(self)
if (self.state.pressed) then
gl.Color(self.focusColor)
else
gl.Color(1,1,1,1)
end
TextureHandler.LoadTexture(0,self.TileImageArrow,self)
local texInfo = gl.TextureInfo(self.TileImageArrow) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
_DrawTextureAspect(self.width - self.padding[3], 0, self.padding[3], self.height, tw,th)
gl.Texture(0,false)
end
function DrawEditBox(obj)
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
gl.Color(obj.backgroundColor)
TextureHandler.LoadTexture(0,obj.TileImageBK,obj)
local texInfo = gl.TextureInfo(obj.TileImageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0, 0, obj.width, obj.height, skLeft,skTop,skRight,skBottom, tw,th)
--gl.Texture(0,false)
if obj.state.focused or obj.state.hovered then
gl.Color(obj.focusColor)
else
gl.Color(obj.borderColor)
end
TextureHandler.LoadTexture(0,obj.TileImageFG,obj)
local texInfo = gl.TextureInfo(obj.TileImageFG) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0, 0, obj.width, obj.height, skLeft,skTop,skRight,skBottom, tw,th)
gl.Texture(0,false)
if (obj.text) then
if (obj.offset > obj.cursor) then
obj.offset = obj.cursor
end
local clientX,clientY,clientWidth,clientHeight = unpack4(obj.clientArea)
--// make cursor pos always visible (when text is longer than editbox!)
repeat
local txt = obj.text:sub(obj.offset, obj.cursor)
local wt = obj.font:GetTextWidth(txt)
if (wt <= clientWidth) then
break
end
if (obj.offset >= obj.cursor) then
break
end
obj.offset = obj.offset + 1
until (false)
local txt = obj.text:sub(obj.offset)
--// strip part at the end that exceeds the editbox
local lsize = math.max(0, obj.font:WrapText(txt, clientWidth, clientHeight):len() - 3) -- find a good start (3 dots at end if stripped)
while (lsize <= txt:len()) do
local wt = obj.font:GetTextWidth(txt:sub(1, lsize))
if (wt > clientWidth) then
break
end
lsize = lsize + 1
end
txt = txt:sub(1, lsize - 1)
gl.Color(1,1,1,1)
obj.font:DrawInBox(txt, clientX, clientY, clientWidth, clientHeight, obj.align, obj.valign)
if obj.state.focused then
local cursorTxt = obj.text:sub(obj.offset, obj.cursor - 1)
local cursorX = obj.font:GetTextWidth(cursorTxt)
local dt = Spring.DiffTimers(Spring.GetTimer(), obj._interactedTime)
local as = math.sin(dt * 8);
local ac = math.cos(dt * 8);
if (as < 0) then as = 0 end
if (ac < 0) then ac = 0 end
local alpha = as + ac
if (alpha > 1) then alpha = 1 end
alpha = 0.8 * alpha
local cc = obj.cursorColor
gl.Color(cc[1], cc[2], cc[3], cc[4] * alpha)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawCursor, cursorX + clientX - 1, clientY, 3, clientHeight)
end
end
end
--//=============================================================================
--//
function DrawPanel(obj)
local w = obj.width
local h = obj.height
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
gl.Color(obj.backgroundColor)
TextureHandler.LoadTexture(0,obj.TileImageBK,obj)
local texInfo = gl.TextureInfo(obj.TileImageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
gl.Color(obj.borderColor)
TextureHandler.LoadTexture(0,obj.TileImageFG,obj)
local texInfo = gl.TextureInfo(obj.TileImageFG) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
end
--//=============================================================================
--//
function DrawItemBkGnd(obj,x,y,w,h,state)
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
if (state=="selected") then
gl.Color(obj.colorBK_selected)
else
gl.Color(obj.colorBK)
end
TextureHandler.LoadTexture(0,obj.imageBK,obj)
local texInfo = gl.TextureInfo(obj.imageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
if (state=="selected") then
gl.Color(obj.colorFG_selected)
else
gl.Color(obj.colorFG)
end
TextureHandler.LoadTexture(0,obj.imageFG,obj)
local texInfo = gl.TextureInfo(obj.imageFG) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
end
--//=============================================================================
--//
function DrawScrollPanelBorder(self)
local clientX,clientY,clientWidth,clientHeight = unpack4(self.clientArea)
local contX,contY,contWidth,contHeight = unpack4(self.contentArea)
do
TextureHandler.LoadTexture(0,self.BorderTileImage,self)
local texInfo = gl.TextureInfo(self.BorderTileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
local skLeft,skTop,skRight,skBottom = unpack4(self.bordertiles)
local width = self.width
local height = self.height
if (self._vscrollbar) then
width = width - self.scrollbarSize - 1
end
if (self._hscrollbar) then
height = height - self.scrollbarSize - 1
end
gl.Color(self.borderColor)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledBorder, 0,0,width,height, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
end
end
--//=============================================================================
--//
function DrawScrollPanel(obj)
local clientX,clientY,clientWidth,clientHeight = unpack4(obj.clientArea)
local contX,contY,contWidth,contHeight = unpack4(obj.contentArea)
if (obj.BackgroundTileImage) then
TextureHandler.LoadTexture(0,obj.BackgroundTileImage,obj)
local texInfo = gl.TextureInfo(obj.BackgroundTileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
local skLeft,skTop,skRight,skBottom = unpack4(obj.bkgndtiles)
local width = obj.width
local height = obj.height
if (obj._vscrollbar) then
width = width - obj.scrollbarSize - 1
end
if (obj._hscrollbar) then
height = height - obj.scrollbarSize - 1
end
gl.Color(obj.backgroundColor)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,width,height, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
end
if obj._vscrollbar then
local x = obj.width - obj.scrollbarSize
local y = 0
local w = obj.scrollbarSize
local h = obj.height --FIXME what if hscrollbar is visible
if (obj._hscrollbar) then
h = h - obj.scrollbarSize
end
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
TextureHandler.LoadTexture(0,obj.TileImage,obj)
local texInfo = gl.TextureInfo(obj.TileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
if obj._vscrolling or obj._vHovered then
gl.Color(obj.KnobColorSelected)
else
gl.Color(1,1,1,1)
end
TextureHandler.LoadTexture(0,obj.KnobTileImage,obj)
texInfo = gl.TextureInfo(obj.KnobTileImage) or {xsize=1, ysize=1}
tw,th = texInfo.xsize, texInfo.ysize
skLeft,skTop,skRight,skBottom = unpack4(obj.KnobTiles)
local pos = obj.scrollPosY / contHeight
local visible = clientHeight / contHeight
local gripy = math.floor(y + h * pos) + 0.5
local griph = math.floor(h * visible)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,gripy,obj.scrollbarSize,griph, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
gl.Color(1,1,1,1)
end
if obj._hscrollbar then
gl.Color(1,1,1,1)
local x = 0
local y = obj.height - obj.scrollbarSize
local w = obj.width
local h = obj.scrollbarSize
if (obj._vscrollbar) then
w = w - obj.scrollbarSize
end
local skLeft,skTop,skRight,skBottom = unpack4(obj.htiles)
TextureHandler.LoadTexture(0,obj.HTileImage,obj)
local texInfo = gl.TextureInfo(obj.HTileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
if obj._hscrolling or obj._hHovered then
gl.Color(obj.KnobColorSelected)
else
gl.Color(1,1,1,1)
end
TextureHandler.LoadTexture(0,obj.HKnobTileImage,obj)
texInfo = gl.TextureInfo(obj.HKnobTileImage) or {xsize=1, ysize=1}
tw,th = texInfo.xsize, texInfo.ysize
skLeft,skTop,skRight,skBottom = unpack4(obj.HKnobTiles)
local pos = obj.scrollPosX / contWidth
local visible = clientWidth / contWidth
local gripx = math.floor(x + w * pos) + 0.5
local gripw = math.floor(w * visible)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, gripx,y,gripw,obj.scrollbarSize, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
end
gl.Texture(0,false)
end
--//=============================================================================
--//
function DrawCheckbox(obj)
local boxSize = obj.boxsize
local x = obj.width - boxSize
local y = obj.height*0.5 - boxSize*0.5
local w = boxSize
local h = boxSize
local tx = 0
local ty = obj.height * 0.5 --// verticale center
if obj.boxalign == "left" then
x = 0
tx = boxSize + 2
end
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
if (obj.state.hovered) then
gl.Color(obj.focusColor)
else
gl.Color(1,1,1,1)
end
TextureHandler.LoadTexture(0,obj.TileImageBK,obj)
local texInfo = gl.TextureInfo(obj.TileImageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
if (obj.state.checked) then
TextureHandler.LoadTexture(0,obj.TileImageFG,obj)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
end
gl.Texture(0,false)
gl.Color(1,1,1,1)
if (obj.caption) then
obj.font:Print(obj.caption, tx, ty, nil, "center")
end
end
--//=============================================================================
--//
function DrawProgressbar(obj)
local w = obj.width
local h = obj.height
local percent = (obj.value-obj.min)/(obj.max-obj.min)
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
if not obj.noSkin then
gl.Color(obj.backgroundColor)
TextureHandler.LoadTexture(0,obj.TileImageBK,obj)
local texInfo = gl.TextureInfo(obj.TileImageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
end
gl.Color(obj.color)
TextureHandler.LoadTexture(0,obj.TileImageFG,obj)
local texInfo = gl.TextureInfo(obj.TileImageFG) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
-- workaround for catalyst >12.6 drivers: do the "clipping" by multiplying width by percentage in glBeginEnd instead of using glClipPlane
-- AMD :(
--gl.ClipPlane(1, -1,0,0, w*percent)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w*percent,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.ClipPlane(1, false)
gl.Texture(0,false)
if (obj.caption) then
(obj.font):Print(obj.caption, w*0.5, h*0.5, "center", "center")
end
end
--//=============================================================================
--//
function DrawTrackbar(self)
local percent = self:_GetPercent()
local w = self.width
local h = self.height
local skLeft,skTop,skRight,skBottom = unpack4(self.tiles)
local pdLeft,pdTop,pdRight,pdBottom = unpack4(self.hitpadding)
gl.Color(1,1,1,1)
if not self.noDrawBar then
TextureHandler.LoadTexture(0,self.TileImage,self)
local texInfo = gl.TextureInfo(self.TileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
end
if not self.noDrawStep then
TextureHandler.LoadTexture(0,self.StepImage,self)
local texInfo = gl.TextureInfo(self.StepImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
--// scale the thumb down if we don't have enough space
if (th>h) then
tw = math.ceil(tw*(h/th))
th = h
end
if (tw>w) then
th = math.ceil(th*(w/tw))
tw = w
end
local barWidth = w - (pdLeft + pdRight)
local stepWidth = barWidth / ((self.max - self.min)/self.step)
if ((self.max - self.min)/self.step)<20 then
local newStepWidth = stepWidth
if (newStepWidth<20) then
newStepWidth = stepWidth*2
end
if (newStepWidth<20) then
newStepWidth = stepWidth*5
end
if (newStepWidth<20) then
newStepWidth = stepWidth*10
end
stepWidth = newStepWidth
local my = h*0.5
local mx = pdLeft+stepWidth
while (mx<(pdLeft+barWidth)) do
gl.TexRect(math.ceil(mx-tw*0.5),math.ceil(my-th*0.5),math.ceil(mx+tw*0.5),math.ceil(my+th*0.5),false,true)
mx = mx+stepWidth
end
end
end
if (self.state.hovered) then
gl.Color(self.focusColor)
else
gl.Color(1,1,1,1)
end
if not self.noDrawThumb then
TextureHandler.LoadTexture(0,self.ThumbImage,self)
local texInfo = gl.TextureInfo(self.ThumbImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
--// scale the thumb down if we don't have enough space
tw = math.ceil(tw * (h / th))
th = h
local barWidth = w - (pdLeft + pdRight)
local mx = pdLeft + barWidth * percent
local my = h * 0.5
mx = math.floor(mx - tw * 0.5)
my = math.floor(my - th * 0.5)
gl.TexRect(mx, my, mx + tw, my + th, false, true)
end
gl.Texture(0,false)
end
--//=============================================================================
--//
function DrawTreeviewNode(self)
if CompareLinks(self.treeview.selected,self) then
local x = self.clientArea[1]
local y = 0
local w = self.children[1].width
local h = self.clientArea[2] + self.children[1].height
local skLeft,skTop,skRight,skBottom = unpack4(self.treeview.tiles)
gl.Color(1,1,1,1)
TextureHandler.LoadTexture(0,self.treeview.ImageNodeSelected,self)
local texInfo = gl.TextureInfo(self.treeview.ImageNodeSelected) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
end
end
local function _DrawLineV(x, y1, y2, width, next_func, ...)
gl.Vertex(x-width*0.5, y1)
gl.Vertex(x+width*0.5, y1)
gl.Vertex(x-width*0.5, y2)
gl.Vertex(x+width*0.5, y1)
gl.Vertex(x-width*0.5, y2)
gl.Vertex(x+width*0.5, y2)
if (next_func) then
next_func(...)
end
end
local function _DrawLineH(x1, x2, y, width, next_func, ...)
gl.Vertex(x1, y-width*0.5)
gl.Vertex(x1, y+width*0.5)
gl.Vertex(x2, y-width*0.5)
gl.Vertex(x1, y+width*0.5)
gl.Vertex(x2, y-width*0.5)
gl.Vertex(x2, y+width*0.5)
if (next_func) then
next_func(...)
end
end
function DrawTreeviewNodeTree(self)
local x1 = math.ceil(self.padding[1]*0.5)
local x2 = self.padding[1]
local y1 = 0
local y2 = self.height
local y3 = self.padding[2] + math.ceil(self.children[1].height*0.5)
if (self.parent)and(CompareLinks(self,self.parent.nodes[#self.parent.nodes])) then
y2 = y3
end
gl.Color(self.treeview.treeColor)
gl.BeginEnd(GL.TRIANGLES, _DrawLineV, x1-0.5, y1, y2, 1, _DrawLineH, x1, x2, y3-0.5, 1)
if (not self.nodes[1]) then
return
end
gl.Color(1,1,1,1)
local image = self.ImageExpanded or self.treeview.ImageExpanded
if (not self.expanded) then
image = self.ImageCollapsed or self.treeview.ImageCollapsed
end
TextureHandler.LoadTexture(0, image, self)
local texInfo = gl.TextureInfo(image) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
_DrawTextureAspect(0,0,math.ceil(self.padding[1]),math.ceil(self.children[1].height) ,tw,th)
gl.Texture(0,false)
end
--//=============================================================================
--//
function DrawLine(self)
gl.Color(self.borderColor)
if (self.style:find("^v")) then
local skLeft,skTop,skRight,skBottom = unpack4(self.tilesV)
TextureHandler.LoadTexture(0,self.TileImageV,self)
local texInfo = gl.TextureInfo(self.TileImageV) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, self.width * 0.5 - 2, 0, 4, self.height, skLeft,skTop,skRight,skBottom, tw,th, 0)
else
local skLeft,skTop,skRight,skBottom = unpack4(self.tiles)
TextureHandler.LoadTexture(0,self.TileImage,self)
local texInfo = gl.TextureInfo(self.TileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0, self.height * 0.5 - 2, self.width, 4, skLeft,skTop,skRight,skBottom, tw,th, 0)
end
gl.Texture(0,false)
if (self.debug) then
gl.Color(0,1,0,0.5)
gl.PolygonMode(GL.FRONT_AND_BACK,GL.LINE)
gl.LineWidth(2)
gl.Rect(0,0,self.width,self.height)
gl.LineWidth(1)
gl.PolygonMode(GL.FRONT_AND_BACK,GL.FILL)
end
end
--//=============================================================================
--//
function DrawTabBarItem(obj)
local w = obj.width
local h = obj.height
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
if (obj.state.pressed) then
gl.Color(mulColor(obj.backgroundColor,0.4))
elseif (obj.state.hovered) then
gl.Color(obj.focusColor)
elseif (obj.state.selected) then
gl.Color(obj.focusColor)
else
gl.Color(obj.backgroundColor)
end
TextureHandler.LoadTexture(0,obj.TileImageBK,obj)
local texInfo = gl.TextureInfo(obj.TileImageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
if (obj.state.pressed) then
gl.Color(0.6,0.6,0.6,1) --FIXME
elseif (obj.state.selected) then
gl.Color(obj.focusColor)
else
gl.Color(obj.borderColor)
end
TextureHandler.LoadTexture(0,obj.TileImageFG,obj)
local texInfo = gl.TextureInfo(obj.TileImageFG) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0,0,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
if (obj.caption) then
local cx,cy,cw,ch = unpack4(obj.clientArea)
obj.font:DrawInBox(obj.caption, cx, cy, cw, ch, "center", "center")
end
end
--//=============================================================================
--//
function DrawDragGrip(obj)
gl.BeginEnd(GL.TRIANGLES, _DrawDragGrip, obj)
end
function DrawResizeGrip(obj)
gl.BeginEnd(GL.LINES, _DrawResizeGrip, obj)
end
--//=============================================================================
--// HitTest helpers
function _ProcessRelative(code, total)
--// FIXME: duplicated in control.lua!
if (type(code) == "string") then
local percent = tonumber(code:sub(1,-2)) or 0
if (percent<0) then
percent = 0
elseif (percent>100) then
percent = 100
end
return math.floor(total * percent)
elseif (code<0) then
return math.floor(total + code)
else
return math.floor(code)
end
end
function GetRelativeObjBox(obj,boxrelative)
return {
_ProcessRelative(boxrelative[1], obj.width),
_ProcessRelative(boxrelative[2], obj.height),
_ProcessRelative(boxrelative[3], obj.width),
_ProcessRelative(boxrelative[4], obj.height)
}
end
--//=============================================================================
--//
function NCHitTestWithPadding(obj,mx,my)
local hp = obj.hitpadding
local x = hp[1]
local y = hp[2]
local w = obj.width - hp[1] - hp[3]
local h = obj.height - hp[2] - hp[4]
--// early out
if (not InRect({x,y,w,h},mx,my)) then
return false
end
local resizable = obj.resizable
local draggable = obj.draggable
local dragUseGrip = obj.dragUseGrip
if IsTweakMode() then
resizable = resizable or obj.tweakResizable
draggable = draggable or obj.tweakDraggable
dragUseGrip = draggable and obj.tweakDragUseGrip
end
if (resizable) then
local resizeBox = GetRelativeObjBox(obj,obj.boxes.resize)
if (InRect(resizeBox,mx,my)) then
return obj
end
end
if (dragUseGrip) then
local dragBox = GetRelativeObjBox(obj,obj.boxes.drag)
if (InRect(dragBox,mx,my)) then
return obj
end
elseif (draggable) then
return obj
end
end
function WindowNCMouseDown(obj,x,y)
local resizable = obj.resizable
local draggable = obj.draggable
local dragUseGrip = obj.dragUseGrip
if IsTweakMode() then
resizable = resizable or obj.tweakResizable
draggable = draggable or obj.tweakDraggable
dragUseGrip = draggable and obj.tweakDragUseGrip
end
if (resizable) then
local resizeBox = GetRelativeObjBox(obj,obj.boxes.resize)
if (InRect(resizeBox,x,y)) then
obj:StartResizing(x,y)
return obj
end
end
if (dragUseGrip) then
local dragBox = GetRelativeObjBox(obj,obj.boxes.drag)
if (InRect(dragBox,x,y)) then
obj:StartDragging()
return obj
end
end
end
function WindowNCMouseDownPostChildren(obj,x,y)
local draggable = obj.draggable
local dragUseGrip = obj.dragUseGrip
if IsTweakMode() then
draggable = draggable or obj.tweakDraggable
dragUseGrip = draggable and obj.tweakDragUseGrip
end
if (draggable and not dragUseGrip) then
obj:StartDragging()
return obj
end
end
--//=============================================================================
|
xponen/Zero-K
|
LuaUI/Widgets/chili_new/headers/skinutils.lua
|
Lua
|
gpl-2.0
| 32,373
|
<?php
/* This file is part of a copyrighted work; it is distributed with NO WARRANTY.
* See the file COPYRIGHT.html for more details.
*/
require_once("../shared/common.php");
$tab = "admin";
$nav = "materials";
$restrictInDemo = true;
require_once("../shared/logincheck.php");
require_once("../classes/DmQuery.php");
/*
require_once("../classes/CheckoutPrivsQuery.php"); //add jalg de la version openbiblio 7.1
require_once("../classes/MaterialFieldQuery.php"); //add jalg de la version openbiblio 7.1
*/
require_once("../functions/errorFuncs.php");
require_once("../classes/Localize.php");
$loc = new Localize(OBIB_LOCALE,$tab);
#****************************************************************************
#* Checking for query string. Go back to material type list if none found.
#****************************************************************************
if (!isset($_GET["code"])){
header("Location: ../admin/materials_list.php");
exit();
}
$code = $_GET["code"];
$description = $_GET["desc"];
#**************************************************************************
#* Delete row
#**************************************************************************
$dmQ = new DmQuery();
$dmQ->connect();
$dmQ->delete("material_type_dm",$code);
$dmQ->close();
/*
//add jalg de la version openbiblio 7.1
$checkoutPrivsQ = new CheckoutPrivsQuery();
$checkoutPrivsQ->connect();
$checkoutPrivsQ->delete_by_material_cd($code);
$checkoutPrivsQ->close();
$materialFieldQ = new MaterialFieldQuery();
$materialFieldQ->connect();
$materialFieldQ->deleteCustomField($code);
$materialFieldQ->close();
//add jalg de la version openbiblio 7.1
*/
#**************************************************************************
#* Show success page
#**************************************************************************
require_once("../shared/header.php");
?>
<?php echo $loc->getText("admin_materials_delMaterialType"); ?>
<?php echo H($description);?><?php echo $loc->getText("admin_materials_delMaterialdeleted"); ?>
<br><br>
<a href="../admin/materials_list.php"><?php echo $loc->getText("admin_materials_Return"); ?></a>
<?php require_once("../shared/footer.php");
|
uniedpa/biblioteca
|
admin/materials_del.php
|
PHP
|
gpl-2.0
| 2,251
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Random mutator based on C. Miller 'algorithm' for Nightmare Fuzzing Project.
Created on Sun May 12 10:57:06 2013
@author: joxean
"""
import sys
import math
import random
#-----------------------------------------------------------------------
class CCMillerMutator(object):
def __init__(self, buf, skip=5):
self.buf = buf
self.skip = 5
def mutate(self):
buf = self.buf
fuzz_factor = len(buf)/500.
if fuzz_factor < 1:
fuzz_factor = 1
numwrites = random.randrange(math.ceil((float(len(buf)) / fuzz_factor)))+1
#print "Total of %d" % numwrites
diff = []
for j in range(numwrites):
rbyte = random.randrange(256)
rn = random.randrange(len(buf))
rtotal = random.randint(0, 16)
c = "%c" % rbyte
buf = buf[:rn-1] + c*rtotal + buf[rn+rtotal:]
diff.append("%d, %d" % (rn, rtotal))
return buf, diff
#-----------------------------------------------------------------------
def main(template, output):
mut = CCMillerMutator(open(template, "rb").read())
buf, diff = mut.mutate()
f = open(output, "wb")
f.write(buf)
f.close()
diff.sort()
f = open(output + ".diff", "wb")
f.write("# Original file created by 'CMiller Mutator Rep' was %s\n" % template)
f.write("\n".join(diff))
f.close()
#-----------------------------------------------------------------------
def usage():
print "Usage:", sys.argv[0], "<template> <output filename>"
if __name__ == "__main__":
if len(sys.argv) != 3:
usage()
else:
main(sys.argv[1], sys.argv[2])
|
joxeankoret/nightmare
|
mutators/cmiller_mutator_rep.py
|
Python
|
gpl-2.0
| 1,588
|
/*
* $XConsortium: extutil.h,v 1.15 94/10/07 15:36:33 kaleb Exp $
*
Copyright (c) 1989 X Consortium
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
X CONSORTIUM 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.
Except as contained in this notice, the name of the X Consortium shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from the X Consortium.
*
* Author: Jim Fulton, MIT X Consortium
*
* Xlib Extension-Writing Utilities
*
* This package contains utilities for writing the client API for various
* protocol extensions. THESE INTERFACES ARE NOT PART OF THE X STANDARD AND
* ARE SUBJECT TO CHANGE!
*/
#ifndef _EXTUTIL_H_
#define _EXTUTIL_H_
/*
* We need to keep a list of open displays since the Xlib display list isn't
* public. We also have to per-display info in a separate block since it isn't
* stored directly in the Display structure.
*/
typedef struct _XExtDisplayInfo {
struct _XExtDisplayInfo *next; /* keep a linked list */
Display *display; /* which display this is */
XExtCodes *codes; /* the extension protocol codes */
XPointer data; /* extra data for extension to use */
} XExtDisplayInfo;
typedef struct _XExtensionInfo {
XExtDisplayInfo *head; /* start of list */
XExtDisplayInfo *cur; /* most recently used */
int ndisplays; /* number of displays */
} XExtensionInfo;
typedef struct _XExtensionHooks {
int (*create_gc)(
#if NeedNestedPrototypes
Display* /* display */,
GC /* gc */,
XExtCodes* /* codes */
#endif
);
int (*copy_gc)(
#if NeedNestedPrototypes
Display* /* display */,
GC /* gc */,
XExtCodes* /* codes */
#endif
);
int (*flush_gc)(
#if NeedNestedPrototypes
Display* /* display */,
GC /* gc */,
XExtCodes* /* codes */
#endif
);
int (*free_gc)(
#if NeedNestedPrototypes
Display* /* display */,
GC /* gc */,
XExtCodes* /* codes */
#endif
);
int (*create_font)(
#if NeedNestedPrototypes
Display* /* display */,
XFontStruct* /* fs */,
XExtCodes* /* codes */
#endif
);
int (*free_font)(
#if NeedNestedPrototypes
Display* /* display */,
XFontStruct* /* fs */,
XExtCodes* /* codes */
#endif
);
int (*close_display)(
#if NeedNestedPrototypes
Display* /* display */,
XExtCodes* /* codes */
#endif
);
Bool (*wire_to_event)(
#if NeedNestedPrototypes
Display* /* display */,
XEvent* /* re */,
xEvent* /* event */
#endif
);
Status (*event_to_wire)(
#if NeedNestedPrototypes
Display* /* display */,
XEvent* /* re */,
xEvent* /* event */
#endif
);
int (*error)(
#if NeedNestedPrototypes
Display* /* display */,
xError* /* err */,
XExtCodes* /* codes */,
int* /* ret_code */
#endif
);
char *(*error_string)(
#if NeedNestedPrototypes
Display* /* display */,
int /* code */,
XExtCodes* /* codes */,
char* /* buffer */,
int /* nbytes */
#endif
);
} XExtensionHooks;
extern XExtensionInfo *XextCreateExtension(
#if NeedFunctionPrototypes
void
#endif
);
extern void XextDestroyExtension(
#if NeedFunctionPrototypes
XExtensionInfo* /* info */
#endif
);
extern XExtDisplayInfo *XextAddDisplay(
#if NeedFunctionPrototypes
XExtensionInfo* /* extinfo */,
Display* /* dpy */,
char* /* ext_name */,
XExtensionHooks* /* hooks */,
int /* nevents */,
XPointer /* data */
#endif
);
extern int XextRemoveDisplay(
#if NeedFunctionPrototypes
XExtensionInfo* /* extinfo */,
Display* /* dpy */
#endif
);
extern XExtDisplayInfo *XextFindDisplay(
#if NeedFunctionPrototypes
XExtensionInfo* /* extinfo */,
Display* /* dpy */
#endif
);
#define XextHasExtension(i) ((i) && ((i)->codes))
#define XextCheckExtension(dpy,i,name,val) \
if (!XextHasExtension(i)) { XMissingExtension (dpy, name); return val; }
#define XextSimpleCheckExtension(dpy,i,name) \
if (!XextHasExtension(i)) { XMissingExtension (dpy, name); return; }
/*
* helper macros to generate code that is common to all extensions; caller
* should prefix it with static if extension source is in one file; this
* could be a utility function, but have to stack 6 unused arguments for
* something that is called many, many times would be bad.
*/
#define XEXT_GENERATE_FIND_DISPLAY(proc,extinfo,extname,hooks,nev,data) \
XExtDisplayInfo *proc (dpy) \
register Display *dpy; \
{ \
XExtDisplayInfo *dpyinfo; \
if (!extinfo) { if (!(extinfo = XextCreateExtension())) return NULL; } \
if (!(dpyinfo = XextFindDisplay (extinfo, dpy))) \
dpyinfo = XextAddDisplay (extinfo,dpy,extname,hooks,nev,data); \
return dpyinfo; \
}
#define XEXT_GENERATE_CLOSE_DISPLAY(proc,extinfo) \
int proc (dpy, codes) \
Display *dpy; \
XExtCodes *codes; \
{ \
return XextRemoveDisplay (extinfo, dpy); \
}
#define XEXT_GENERATE_ERROR_STRING(proc,extname,nerr,errl) \
char *proc (dpy, code, codes, buf, n) \
Display *dpy; \
int code; \
XExtCodes *codes; \
char *buf; \
int n; \
{ \
code -= codes->first_error; \
if (code >= 0 && code < nerr) { \
char tmp[256]; \
sprintf (tmp, "%s.%d", extname, code); \
XGetErrorDatabaseText (dpy, "XProtoError", tmp, errl[code], buf, n); \
return buf; \
} \
return (char *)0; \
}
#endif
|
AudriusButkevicius/TurboVNC
|
unix/Xvnc/include/extensions/extutil.h
|
C
|
gpl-2.0
| 6,580
|
## Posts
__php/postworld_posts.php__
------
### pw_get_posts ( *$post_ids, $fields* )
- Run `pw_get_post()` on each of the __$post_ids__ , and return the given fields in an __Array__
#### Parameters:
__$post_ids__ : *Array*
- An array of post IDs
__$fields__ : *Array*
- Corresponds to `pw_get_post()` fields parameter
#### Process:
- Get the feed outline
- Select which posts to preload
- Preload selected posts
__return__ : *Array*
``` php
array(
array(
'ID' => 24,
'post_title' => 'Post Title',
'post_content' => 'Content of the post.'
'post_type' => 'post',
'link_format' => 'standard',
...
),
array(
...
)
)
```
#### Requirements:
- `pw_get_post()` PHP Method
- `pw_query()` PHP Method
- `pw_feed_outline()` PHP Method
------
### pw_get_post ( *$post_id, $fields, [$user_id]* )
- Gets data fields for the specified post, including post world meta data and custom sized thumbnails
#### Parameters:
__$post_id__ : *integer*
__$user_id__ : *integer* (optional)
- ID of the currently logged in user, for user-view specific data (points voted, etc)
__$fields__ : *string / Array*
- Options :
- __'all'__ (default)
- __'preview'__ - Returns a basic set of commonly usable fields
- __'micro'__ - Returns a basic set of commonly usable fields
- __'edit'__ - Returns a basic set of standard fields for editing a post
- __Array__ - Use any of the following values in an Array :
__WP GET_POST METHOD__ : http://codex.wordpress.org/Function_Reference/get_post
- __ID__ (default always)
- __post_author__
- __post_date__
- __post_date_gmt__
- __post_title__
- __post_content__
- __post_permalink__
- __post_excerpt__
- __post_path__
- __post_name__
- __post_type__
- __post_status__
- (all __get_post__ return values )
__WORDPRESS__
- __post_permalink__
- Uses WP `get_post_permalink()` Method
__POSTWORLD__
- __post_points__
- __rank_score__
- __post_class__
- __geo_latitude__
- __geo_longitude__
- __event_start__
- __event_end__
- __related_post__
- __post_timestamp__ - UNIX Timestamp from GMT Date
__TAXONOMIES__
- __taxonomy(tax_slug)[fields]__ - Returns taxonomy terms array for the post
- Usage :
`taxonomy(all)`
`taxonomy(category)`
`taxonomy(category, post_tag)`
`taxonomy(category)[slug]`
`taxonomy(category,post_tag)[slug,name]`
- __return__ : *Array* - returns an Associative Array with each term in the given taxonomy
- __[fields]__ : (optional)(Default : *all*) - The fields to return. If only one, will return flat array.
Options : *term_id, name, slug, description, parent, count, taxonomy, url*
__VIEWER SPECIFIC__
- __has_voted__ - number of points the user has voted for this post
__IMAGE__
- Registered Image Sizes
- __image( registered_image_size_name[ thumbnail / medium / large / full ] )__
example : __image(medium)__ - returns the registered 'medium' image size
- Custom Image Sizes
- __image( handle, width, height, hard_crop )__
example : __image(banner,700,100,1)__
__AVATAR__
- Avatar Images -(Supports both Buddypress and Regular Wordpress Avatars)
- __avatar( handle, size )__
example : __avatar(small,48)__
__AUTHOR__
- author(ID,display_name,user_nicename,posts_url,user_profile_url)
- __edit_post_link__ // ??
- __user_profile_url__ - *Requires Buddypress*
- __post_author_social__ <<< PHONG
__DATE & TIME__
- __time_ago__ - "(2 minutes ago)" : http://www.devnetwork.net/viewtopic.php?f=50&t=113253
#### Process:
- Mixed Methods for retrieving data
__return__ : *Array* (requested fields)
``` php
array(
'ID' => 24,
'post_title' => 'Post Title',
'post_content' => 'The post content.',
'taxonomy' => array(
'taxonomy_slug' => array( // taxonomy name
array(
'term' => 'blue'
'url' => 'http://.../tags/blue/'
),
array(
'term' => 'red'
'url' => 'http://.../tags/red/'
),
),
'image' => array(
'thumbnail' => array( // registered image 'thumbnail'
'width' => 150,
'height' => 150,
'url' => 'http://../image-150.jpg'
),
'custom_handle' => array( // custom image
'width' => 320,
'height' => 240,
'url' => 'http://../image-320.jpg'
),
'full' => array( // full original image
'width' => 1280,
'height' => 1024,
'url' => 'http://../image.jpg'
),
),
'avatar' => array(
'small' => array( // handle
'width' => 24,
'height' => 24,
'url' => 'http://../avatar-24.jpg'
),
'medium' => array( // handle
'width' => 48,
'height' => 48,
'url' => 'http://../avatar-48.jpg'
),
),
...
)
```
------
### pw_print_post( $vars )
- Injects a post into an HTML template
- Template takes django style markup, using **h2o-php** *by speedmax*
#### Parameters : __$vars__
__post_id__ : *integer* (required)
- The ID of the post
__template__ : *string* (optional)
- The absolute system directory path of the template to inject the post into
__view__ : *string* (optional)
- The name of the registered view template to display the post in
- This field over-rides `template` variables if provided
- Uses `pw_get_post_template` to get the template path
__fields__ : *string/Array* (optional)
- Passed to `pw_get_post()` `fields` parameter
- Define all the fields here which will be accessable in the template
__vars__ : *A_Array* (optional)
- Can contain a series of `key/value` pairs which will be injected into the data object and accessible in the template.
- Accessible by `{{ key.value }}` markup in the template
__js_vars__ : *Array* (optional)
- List the variables to be injected into the Javascript `$window` object for accessibility
- The required value in most cases is : `array('post')`
#### Example Usage
- In the context of a single post template, ie. `single.php`
```php
// Globalize Post
global $post;
// Social Media Widgets
global $social_settings;
$social_settings['meta']['url'] = get_permalink();
// Post Settings
$post_settings = array(
'post_id' => $post->ID,
'template' => pw_get_post_template ( $post->ID, 'full-h2o', 'dir', true ),
'fields' => 'all',
'vars' => array(
'language' => $pwSiteLanguage,
'social_widgets' => pw_social_widgets()
),
'js_vars' => array('post'),
);
$post_html = pw_print_post( $post_settings );
echo $post_html;
```
------
### pw_insert_post ( $post )
- Extends `wp_insert_post` : http://codex.wordpress.org/Function_Reference/wp_insert_post
- Include additional Postworld __Post Meta__ fields as inputs
#### Parameters : $post *Array*
- All fields in `wp_insert_post()` Method
- Postworld __Post Meta__ Fields:
- __post_class__
- __author_id__
__return__ :
- *post_id* - If added to the database, otherwise return *WP_Error Object*
------
### pw_update_post ( *$post* )
- Extends `wp_update_post()` : http://codex.wordpress.org/Function_Reference/wp_update_post
- Include additional Postworld fields as inputs (see `pw_insert_post()` )
__return__ : *integer*
- The ID of the post if the post is successfully updated in the database. Otherwise returns 0.
------
### pw_save_post ( *$post* )
Status : In development... (phongmedia)
#### Description
- Uses both `pw_update_post()` and `pw_insert_post()` as needed
- When post ID is *not* supplied, use __Insert Post__ : `pw_insert_post()`
- When post ID is supplied, use __Update Post__ : `pw_update_post()`
- __Images__ - Takes Media Library ID or raw URL to set a thumbnail image
- When only a URL is supplied, use the URL
- When only an ID is supplied, use the ID
- When both are supplied, use the ID
#### Process
__WP & PW Fields__
1. Check if there is a Post ID.
2. Check if that Post ID exists
3. Check if the user owns that Post ID, or if they have permissions to edit other's posts
4. Pass the values to the cooroponding function: `pw_update_post()` and `pw_insert_post()`
__Image Meta__
- Use `$thumbnail_id` in priority over `$thumbnail_url` if both are provided
#### Usage
``` php
$post_data = array(
///// STANDARD WORDPRESS INPUTS /////
'ID' => [ <post id> ] //Are you updating an existing post?
'menu_order' => [ <order> ] //If new post is a page, it sets the order in which it should appear in the tabs.
'comment_status' => [ 'closed' | 'open' ] // 'closed' means no comments.
'ping_status' => [ 'closed' | 'open' ] // 'closed' means pingbacks or trackbacks turned off
'post_author' => [ <user ID> ] //The user ID number of the author.
'post_content' => [ <the text of the post> ] //The full text of the post.
'post_date' => [ Y-m-d H:i:s ] //The time post was made.
'post_date_gmt' => [ Y-m-d H:i:s ] //The time post was made, in GMT.
'post_excerpt' => [ <an excerpt> ] //For all your post excerpt needs.
'post_name' => [ <the name> ] // The name (slug) for your post
'post_parent' => [ <post ID> ] //Sets the parent of the new post.
'post_password' => [ ? ] //password for post?
'post_status' => [ 'draft' | 'publish' | 'pending'| 'future' | 'private' | 'custom_registered_status' ]
'post_title' => [ <the title> ]
'post_type' => [ 'post' ] // The name/slug of the post type
'tags_input' => [ '<tag>, <tag>, <...>' ] //For tags.
'to_ping' => [ ? ] //?
'tax_input' => [ array( 'taxonomy_name' => array( 'term', 'term2', 'term3' ) ) ] // support for custom taxonomies.
///// POSTWORLD INPUTS /////
'post_class' => [ 'author' | 'contributor' ],
'event_start' => [ integer | UNIX timestamp ]
'event_end' => [ integer | UNIX timestamp ]
'geo_latitude' => [ number ]
'geo_longitude' => [ number ]
'related_post' => [ number ]
///// IMAGE INPUTS /////
'thumbnail_url' => [ <URL> ], // The URL of an image to be imported into the library
'thumbnail_id' => [ <ID> ], // The ID of the item in the media library
);
pw_save_post($post_data);
```
__return__ : *integer* (the ID of the post which was added / updated)
------
### pw_set_post_thumbnail( *$post_id, $image, [$image_meta]* )
#### Description
- Takes URL or integer / ID and sets as post thumbnail
- Optionally insert image title, excerpt, body, etc.
#### Parameters
__$post_id__ : *integer*
- The ID of the post which is having the thumbnail set
__$image__ : *integer / string*
- Options :
- *integer* - The ID of the media library item to
- *string* - The URL of the image which to import into the Media Library and then set
#### Process
- Check if `$image` is an integer or a string
- If it's an image, use `set_post_thumbnail()`
- If it's a URL, import it into the Media Library and then set it with `set_post_thumbnail()`
__return__ : *integer* (The ID of the item in the Media Library)
------
|
phongmedia/postworld
|
php/core/posts.md
|
Markdown
|
gpl-2.0
| 10,651
|