code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
cmd_drivers/staging/ab5500_sim/built-in.o := /home/aashir/android/toolchain/linaro/bin/arm-eabi-ld -EL -r -o drivers/staging/ab5500_sim/built-in.o drivers/staging/ab5500_sim/ab5500-sim.o
|
emwno/android_kernel_U8500
|
drivers/staging/ab5500_sim/.built-in.o.cmd
|
Batchfile
|
gpl-2.0
| 192
|
<?php
/*
$Id: quick_links.php 1857 2012-06-20 01:21:38Z michael.oscmax@gmail.com $
osCmax e-Commerce
http://www.oscmax.com
Copyright 2000 - 2011 osCmax
Released under the GNU General Public License
*/
define('HEADING_TITLE', 'Quick Links');
define('TABLE_HEADING_QUICK_LINKS_ID', 'ID');
define('TABLE_HEADING_QUICK_LINKS_IMAGE', 'Link Icon');
define('TABLE_HEADING_QUICK_LINKS_NAME', 'Link Name');
define('TABLE_HEADING_QUICK_LINKS_LINK', 'Link');
define('TABLE_HEADING_QUICK_LINKS_TARGET', 'Target');
define('TABLE_HEADING_QUICK_LINKS_SORT_ORDER', 'Sort Order');
define('TABLE_HEADING_QUICK_LINKS_CG', 'Groups');
define('TEXT_QUICK_LINKS_INSERT_INTRO', 'Please insert details of new quick link:');
define('TEXT_QUICK_LINKS_NAME', 'Link Name');
define('TEXT_QUICK_LINKS_IMAGE', 'Link Icon');
define('TEXT_QUICK_LINKS_LINK', 'Link Details');
define('TEXT_QUICK_LINKS_TARGET', 'Target');
define('TEXT_QUICK_LINKS_SORT_ORDER', 'Sort Order');
define('TEXT_QUICK_LINKS_CG', 'Visible to customer groups: (Seperate with ,)');
define('TEXT_QUICK_LINKS_DATE_ADDED', 'Added: ');
define('TEXT_QUICK_LINKS_LAST_MODIFIED', 'Modified: ');
define('TEXT_QUICK_LINKS_DELETE_INTRO', 'Are you sure you want to delete this quick link? ');
define('TEXT_INFO_HEADING_NEW_QUICK_LINKS', 'New Quick Link');
define('TEXT_INFO_HEADING_EDIT_QUICK_LINKS', 'Edit Quick Link');
define('TEXT_INFO_HEADING_DELETE_QUICK_LINKS', 'Delete Quick Link');
define('TEXT_INFO_EDIT_INTRO', 'Edit your quick link details below:');
?>
|
arnabnaha/NHCPharmacy
|
catalog/admin/includes/languages/french/quick_links.php
|
PHP
|
gpl-2.0
| 1,507
|
<?php
return array(
/*
|--------------------------------------------------------------------------
| Workbench Author Name
|--------------------------------------------------------------------------
|
| When you create new packages via the Artisan "workbench" command your
| name is needed to generate the composer.json file for your package.
| You may specify it now so it is used for all of your workbenches.
|
*/
'name' => 'DesignsCook',
/*
|--------------------------------------------------------------------------
| Workbench Author E-Mail Address
|--------------------------------------------------------------------------
|
| Like the option above, your e-mail address is used when generating new
| workbench packages. The e-mail is placed in your composer.json file
| automatically after the package is created by the workbench tool.
|
*/
'email' => 'designscook@gmail.com',
);
|
kesfun/designscookwebsite
|
app/config/workbench.php
|
PHP
|
gpl-2.0
| 915
|
# LibEventManagerCSharp
|
LolHens/LibEventManagerCSharp
|
README.md
|
Markdown
|
gpl-2.0
| 24
|
/*
*********************************************************************************************************
* LINUX-KERNEL
* newbie Linux Platform Develop Kits
* Kernel Module
*
* (c) Copyright 2006-2011, kevin.z China
* All Rights Reserved
*
* File : standby_ir.h
* By : kevin.z
* Version : v1.0
* Date : 2011-5-31 15:15
* Descript:
* Update : date auther ver notes
*********************************************************************************************************
*/
#ifndef __STANDBY_IR_H__
#define __STANDBY_IR_H__
#include "standby_cfg.h"
#define IR_RXINT_ROI_EN (1<<0) //FIFO overrun
#define IR_RXINT_RPEI_EN (1<<1) //receiver packet end interrupt
#define IR_RXINT_RAI_EN (1<<4) //RX fifo available interrupt
#define IR_RXINT_DRQ_EN (1<<5) //DRQ enable
#define IR_RXINT_ALL_MASK (IR_RXINT_ROI_EN | IR_RXINT_RPEI_EN | IR_RXINT_RAI_EN | (IR_RXINT_DRQ_EN))
#define IR_RXINT_RAL_MASK (0x3f<<8)
#define IR_RXSTA_RPE_MASK (1<<1) //packet end flag
#define IR_RXSTA_ALL_MASK (0x1f)
#define IR_RXSTA_RAC_MASK (0x7f<<8) /* rxFIFO Available Counter.0:no data,64:64 byte in rxFIFO */
#define IR_REG_RXFIFO (SW_VA_IR0_IO_BASE + 0x20)
//define ir controller registers
typedef struct __STANDBY_IR_REG
{
volatile __u32 CIR_Ctl;
volatile __u32 CIR_Reserve0[3];
volatile __u32 CIR_RxCtl;
volatile __u32 CIR_Reserve1[3];
volatile __u32 CIR_RxFifo;
volatile __u32 CIR_Reserve2[2];
volatile __u32 CIR_RxInt;
volatile __u32 CIR_RxSta;
volatile __u32 CIR_Config;
} __standby_ir_reg_t;
struct standby_ir_buffer
{
unsigned long dcnt; /*Packet Count*/
unsigned char buf[STANDBY_IR_BUF_SIZE];
};
extern __s32 standby_ir_init(void);
extern __s32 standby_ir_exit(void);
extern __s32 standby_ir_detect(void);
extern __s32 standby_ir_verify(void);
#endif /*__STANDBY_IR_H__*/
|
Xmister/linux-sunxi
|
arch/arm/mach-sun4i/pm/standby/standby_ir.h
|
C
|
gpl-2.0
| 2,123
|
/*
* Copruright © 2015 - Victor A. Santos <victoraur.santos@gmail.com>
* Copyright © 2003, 2010 - Wolfire Games
*
* This file is part of Ragaru.
*
* Ragaru 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 "Skybox.h"
#include "Game.h"
#include "Globals.h"
bool SkyBox::load(const char* ffront,
const char* fleft,
const char* fback,
const char* fright,
const char* fup,
const char* fdown,
const char* fcloud,
const char* freflect)
{
/* static GLuint type;
unsigned char fileNamep[256];
*/
// front
Ragaru::Game::LoadTexture(ffront, &front, true, false);
// left
Ragaru::Game::LoadTexture(fleft, &left, true, false);
// back
Ragaru::Game::LoadTexture(fback, &back, true, false);
// right
Ragaru::Game::LoadTexture(fright, &right, true, false);
// up
Ragaru::Game::LoadTexture(fup, &up, true, false);
// down
Ragaru::Game::LoadTexture(fdown, &down, true, false);
// cloud
Ragaru::Game::LoadTexture(fcloud, &cloud, true, false);
// reflect
Ragaru::Game::LoadTexture(freflect, &reflect, true, false);
/*
//front
CopyCStringToPascal(ffront,fileNamep);
upload_image( fileNamep ,0);
if(1==1){
if ( texture.bpp == 24 )
type = GL_RGB;
else
type = GL_RGBA;
glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
if(!front)glGenTextures( 1, &front );
glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
glBindTexture( GL_TEXTURE_2D, front);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
//glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
if(trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
if(!trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
gluBuild2DMipmaps( GL_TEXTURE_2D, type, texture.sizeX, texture.sizeY, type, GL_UNSIGNED_BYTE,
texture.data );
}
//left
CopyCStringToPascal(fleft,fileNamep);
upload_image( fileNamep ,0);
if(1==1){
if ( texture.bpp == 24 )
type = GL_RGB;
else
type = GL_RGBA;
glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
if(!left)glGenTextures( 1, &left );
glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
glBindTexture( GL_TEXTURE_2D, left);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
//glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
if(trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
if(!trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
gluBuild2DMipmaps( GL_TEXTURE_2D, type, texture.sizeX, texture.sizeY, type, GL_UNSIGNED_BYTE,
texture.data );
}
//back
CopyCStringToPascal(fback,fileNamep);
upload_image( fileNamep ,0);
if(1==1){
if ( texture.bpp == 24 )
type = GL_RGB;
else
type = GL_RGBA;
glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
if(!back)glGenTextures( 1, &back );
glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
glBindTexture( GL_TEXTURE_2D, back);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
//glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
if(trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
if(!trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
gluBuild2DMipmaps( GL_TEXTURE_2D, type, texture.sizeX, texture.sizeY, type, GL_UNSIGNED_BYTE,
texture.data );
}
//right
CopyCStringToPascal(fright,fileNamep);
upload_image( fileNamep ,0);
if(1==1){
if ( texture.bpp == 24 )
type = GL_RGB;
else
type = GL_RGBA;
glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
if(!right)glGenTextures( 1, &right );
glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
glBindTexture( GL_TEXTURE_2D, right);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
//glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
if(trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
if(!trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
gluBuild2DMipmaps( GL_TEXTURE_2D, type, texture.sizeX, texture.sizeY, type, GL_UNSIGNED_BYTE,
texture.data );
}
//up
CopyCStringToPascal(fup,fileNamep);
upload_image( fileNamep ,0);
if(1==1){
if ( texture.bpp == 24 )
type = GL_RGB;
else
type = GL_RGBA;
glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
if(!up)glGenTextures( 1, &up );
glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
glBindTexture( GL_TEXTURE_2D, up);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
//glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
if(trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
if(!trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
gluBuild2DMipmaps( GL_TEXTURE_2D, type, texture.sizeX, texture.sizeY, type, GL_UNSIGNED_BYTE,
texture.data );
}
//down
CopyCStringToPascal(fdown,fileNamep);
upload_image( fileNamep ,0);
if(1==1){
if ( texture.bpp == 24 )
type = GL_RGB;
else
type = GL_RGBA;
glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
if(!down)glGenTextures( 1, &down );
glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
glBindTexture( GL_TEXTURE_2D, down);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
//glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
if(trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
if(!trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
gluBuild2DMipmaps( GL_TEXTURE_2D, type, texture.sizeX, texture.sizeY, type, GL_UNSIGNED_BYTE,
texture.data );
}
//cloud
CopyCStringToPascal(fcloud,fileNamep);
upload_image( fileNamep ,0);
if(1==1){
if ( texture.bpp == 24 )
type = GL_RGB;
else
type = GL_RGBA;
glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
if(!cloud)glGenTextures( 1, &cloud );
glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
glBindTexture( GL_TEXTURE_2D, cloud);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
//glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
if(trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
if(!trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
gluBuild2DMipmaps( GL_TEXTURE_2D, type, texture.sizeX, texture.sizeY, type, GL_UNSIGNED_BYTE,
texture.data );
}
//up
CopyCStringToPascal(freflect,fileNamep);
upload_image( fileNamep ,0);
if(1==1){
if ( texture.bpp == 24 )
type = GL_RGB;
else
type = GL_RGBA;
glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
if(!reflect)glGenTextures( 1, &reflect );
glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
glBindTexture( GL_TEXTURE_2D, reflect);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
//glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
if(trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
if(!trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
gluBuild2DMipmaps( GL_TEXTURE_2D, type, texture.sizeX, texture.sizeY, type, GL_UNSIGNED_BYTE,
texture.data );
}
*/
return true;
}
void SkyBox::draw()
{
static float size = viewdistance / 4;
glPushMatrix();
static GLfloat M[16];
glGetFloatv(GL_MODELVIEW_MATRIX, M);
M[12] = 0;
M[13] = 0;
M[14] = 0;
glLoadMatrixf(M);
// if(environment==2)glTranslatef(0,blurness*viewdistance/1000,0);
if(environment == 2)
glScalef(1 + blurness / 1000, 1, 1 + blurness / 1000);
if(environment != 2)
glColor3f(.85 * skyboxr, .85 * skyboxg, .95 * skyboxb);
else
glColor3f(1 * skyboxr, .95 * skyboxg, .95 * skyboxb);
if(!skyboxtexture) {
glDisable(GL_TEXTURE_2D);
glColor3f(skyboxr * .8, skyboxg * .8, skyboxb * .8);
}
glDepthMask(0);
glDisable(GL_CULL_FACE);
glEnable(GL_BLEND);
glDisable(GL_LIGHTING);
// glActiveTextureARB(GL_TEXTURE0_ARB);
if(skyboxtexture)
glEnable(GL_TEXTURE_2D);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glBindTexture(GL_TEXTURE_2D, front);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBegin(GL_QUADS);
glNormal3f(0.0f, 0.0f, -1);
glTexCoord2f(0, 0);
glVertex3f(-size, -size, size);
glTexCoord2f(1, 0);
glVertex3f(size, -size, size);
glTexCoord2f(1, 1);
glVertex3f(size, size, size);
glTexCoord2f(0, 1);
glVertex3f(-size, size, size);
glEnd();
glBindTexture(GL_TEXTURE_2D, back);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBegin(GL_QUADS);
glNormal3f(0.0f, 0.0f, 1);
glTexCoord2f(1, 0);
glVertex3f(-size, -size, -size);
glTexCoord2f(1, 1);
glVertex3f(-size, size, -size);
glTexCoord2f(0, 1);
glVertex3f(size, size, -size);
glTexCoord2f(0, 0);
glVertex3f(size, -size, -size);
glEnd();
glBindTexture(GL_TEXTURE_2D, up);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBegin(GL_QUADS);
glNormal3f(0.0f, -1.0f, 0);
glTexCoord2f(0, 1);
glVertex3f(-size, size, -size);
glTexCoord2f(0, 0);
glVertex3f(-size, size, size);
glTexCoord2f(1, 0);
glVertex3f(size, size, size);
glTexCoord2f(1, 1);
glVertex3f(size, size, -size);
glEnd();
// if(detail!=0){
glBindTexture(GL_TEXTURE_2D, down);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBegin(GL_QUADS);
glNormal3f(0.0f, 1.0f, 0);
glTexCoord2f(0, 0);
glVertex3f(-size, -size, -size);
glTexCoord2f(1, 0);
glVertex3f(size, -size, -size);
glTexCoord2f(1, 1);
glVertex3f(size, -size, size);
glTexCoord2f(0, 1);
glVertex3f(-size, -size, size);
glEnd();
//}
glBindTexture(GL_TEXTURE_2D, right);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBegin(GL_QUADS);
glNormal3f(-1.0f, 0.0f, 0);
glTexCoord2f(1, 0);
glVertex3f(size, -size, -size);
glTexCoord2f(1, 1);
glVertex3f(size, size, -size);
glTexCoord2f(0, 1);
glVertex3f(size, size, size);
glTexCoord2f(0, 0);
glVertex3f(size, -size, size);
glEnd();
glBindTexture(GL_TEXTURE_2D, left);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBegin(GL_QUADS);
glNormal3f(1.0f, 0.0f, 0);
glTexCoord2f(0, 0);
glVertex3f(-size, -size, -size);
glTexCoord2f(1, 0);
glVertex3f(-size, -size, size);
glTexCoord2f(1, 1);
glVertex3f(-size, size, size);
glTexCoord2f(0, 1);
glVertex3f(-size, size, -size);
glEnd();
/*
glEnable(GL_BLEND);
glColor4f(1,1,1,1);
glBindTexture(GL_TEXTURE_2D, cloud);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glBegin(GL_QUADS);
glNormal3f( 0.0f, -1.0f, 0);
glTexCoord2f(0, (1+cloudmove)*30); glVertex3f(-size, size/200, -size);
glTexCoord2f(0, 0); glVertex3f(-size, size/200, size);
glTexCoord2f((1+cloudmove)*30, 0); glVertex3f( size, size/200, size);
glTexCoord2f((1+cloudmove)*30, (1+cloudmove)*30); glVertex3f( size, size/200, -size);
glEnd();
glDisable(GL_BLEND);*/
glEnable(GL_CULL_FACE);
glDepthMask(1);
glPopMatrix();
}
SkyBox::SkyBox()
{
front = 0, left = 0, back = 0, right = 0, up = 0, down = 0, cloud = 0, reflect = 0;
cloudmove = 0;
}
SkyBox::~SkyBox()
{
if(front)
glDeleteTextures(1, &front);
if(left)
glDeleteTextures(1, &left);
if(back)
glDeleteTextures(1, &back);
if(right)
glDeleteTextures(1, &right);
if(up)
glDeleteTextures(1, &up);
if(down)
glDeleteTextures(1, &down);
if(cloud)
glDeleteTextures(1, &cloud);
if(reflect)
glDeleteTextures(1, &reflect);
};
|
hotvic/ragaru
|
src/Skybox.cpp
|
C++
|
gpl-2.0
| 16,010
|
/*
Logistic Regression using Truncated Iteratively Re-weighted Least Squares
(includes several programs)
Copyright (C) 2005 Paul Komarek
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 St, Fifth Floor, Boston, MA 02110-1301 USA
Author: Paul Komarek, komarek@cmu.edu
Alternate contact: Andrew Moore, awm@cs.cmu.edu
*/
/* *
File: amiv.c
Author: Andrew W. Moore
Created: Sat Apr 8 18:48:26 EDT 1995
Updated: 29 March 97
Description: Integer and Boolean Dynamic vectors
Copyright 1997, Schenley Park Research
*/
#include "amiv.h"
#include "am_string.h"
#include "am_string_array.h"
#include "amma.h"
#define IVEC_CODE 20541
int Ivecs_mallocked = 0;
int Ivecs_freed = 0;
/* Headers for private functions. Are these all meant to be private? */
int ivec_arg_extreme(const ivec *iv,bool lowest);
int ivec_extreme(const ivec *iv,bool lowest);
ivec *mk_ivec(int size)
{
ivec *result = AM_MALLOC(ivec);
if ( size < 0 ) my_error("mk_ivec : size < 0 illegal");
result -> ivec_code = IVEC_CODE;
result -> array_size = size;
result -> size = size;
result -> iarr = am_malloc_ints(size);
Ivecs_mallocked += 1;
return(result);
}
/* Acts as though you created a ivec of size 0, */
/* but actually allocates an array of size "capacity". */
/* This is very useful if you want to use add_to_ivec */
/* and happen to have a reasonable upper bound to the */
/* number of elements you want to add. */
ivec *mk_empty_ivec(int capacity) {
ivec *result = AM_MALLOC(ivec);
if ( capacity < 0 ) my_error("mk_empty_ivec : capacity < 0 illegal");
result -> ivec_code = IVEC_CODE;
result -> array_size = capacity;
result -> size = 0;
result -> iarr = am_malloc_ints(capacity);
Ivecs_mallocked += 1;
return(result);
}
ivec *mk_ivec_x( int size, ...)
{
/* Warning: no type checking can be done by the compiler. You *must*
send the values as integers for this to work correctly. */
int i, ival;
va_list argptr;
ivec *iv;
iv = mk_ivec(size);
va_start( argptr, size);
for (i=0; i<size; ++i) {
ival = va_arg( argptr, int);
ivec_set( iv, i, ival);
}
va_end(argptr);
return iv;
}
void free_ivec(ivec *iv)
{
iv -> ivec_code = 7777;
am_free_ints(iv->iarr,iv->array_size);
AM_FREE(iv,ivec);
Ivecs_freed += 1;
}
void fprintf_ivec(FILE *s,char *m1, const ivec *iv,char *m2)
{
if ( iv == NULL )
fprintf(s,"%s = (ivec *)NULL%s",m1,m2);
else
{
char buff[256];
/* Modified so that we don't cause a seg fault when m1 is bigger than
the buffer - WKW*/
if( strlen(m1) <= 255 )
{
strncpy(buff,m1,strlen(m1)+1);
}
else
{
strncpy(buff,m1,sizeof(buff));
buff[255] = '\0';
}
fprintf_ints(s,buff,iv->iarr,iv->size,m2);
}
}
void copy_iarr_to_ivec(int *iarr,int size,ivec *r_iv)
{
copy_ints(iarr,r_iv->iarr,size);
}
void copy_ivec_to_iarr(ivec *iv, int *iarr)
{
copy_ints(iv->iarr,iarr,iv->size);
}
int *mk_iarr_from_ivec(ivec *iv)
{
int *result;
result = am_malloc_ints(iv->size);
copy_ivec_to_iarr(iv,result);
return(result);
}
/* Makes an ivec of size end - start:
{ start , start+1 , .... end-2 , end-1 } */
ivec *mk_sequence_ivec(int start_value,int end_value)
{
int size = end_value - start_value;
ivec *iv = mk_ivec(size);
int i;
for ( i = 0 ; i < size ; i++ )
ivec_set(iv,i,start_value+i);
return iv;
}
/*
Allocates and returns an ivec of size size in which ivec[i] = i
ivec[0] = 0
ivec[1] = 1
.
.
ivec[size-1] = size-1
*/
ivec *mk_identity_ivec(int size)
{
return mk_sequence_ivec(0,size);
}
void shuffle_ivec(ivec *iv)
/*
A random permutation of iv is returned
*/
{
int size = ivec_size(iv);
int i;
for ( i = 0 ; i < size-1 ; i++ )
{
int j = int_random(size - i);
if ( j > 0 )
{
int swap_me_1 = ivec_ref(iv,i);
int swap_me_2 = ivec_ref(iv,i+j);
ivec_set(iv,i,swap_me_2);
ivec_set(iv,i+j,swap_me_1);
}
}
}
void constant_ivec(ivec *iv,int value)
{
int i;
for ( i = 0 ; i < ivec_size(iv) ; i++ )
ivec_set(iv,i,value);
}
ivec *mk_constant_ivec(int size,int value)
{
ivec *iv = mk_ivec(size);
constant_ivec(iv,value);
return(iv);
}
void zero_ivec(ivec *iv)
{
constant_ivec(iv,0);
}
ivec *mk_zero_ivec(int size)
{
return(mk_constant_ivec(size,0));
}
void ivec_scalar_plus(const ivec *iv, int addme, ivec *riv)
{
int i;
for ( i = 0 ; i < ivec_size(iv) ; i++ )
ivec_set(riv,i,ivec_ref(iv,i) + addme);
}
ivec *mk_ivec_scalar_plus(ivec *iv,int delta)
{
ivec *result = mk_ivec(ivec_size(iv));
ivec_scalar_plus(iv,delta,result);
return(result);
}
void ivec_scalar_mult(const ivec *iv,int scale,ivec *riv)
{
int i;
for ( i = 0 ; i < ivec_size(iv) ; i++ )
ivec_set(riv,i,ivec_ref(iv,i) * scale);
}
ivec *mk_ivec_scalar_mult(ivec *iv,int scale)
{
ivec *result = mk_ivec(ivec_size(iv));
ivec_scalar_mult(iv,scale,result);
return(result);
}
void copy_ivec(const ivec *iv,ivec *r_iv)
{
int i, size;
size = iv->size;
for (i=0; i<size; ++i) ivec_set(r_iv, i, ivec_ref(iv, i));
return;
/* ivec_scalar_mult(iv,1,r_iv); */
}
ivec *mk_copy_ivec(const ivec *iv)
{
ivec *result = mk_ivec(ivec_size(iv));
copy_ivec(iv,result);
return(result);
}
void copy_ivec_subset(ivec *iv, int start, int size, ivec *r_iv)
{
int i;
for (i = start; i < start + size; i++)
ivec_set(r_iv, i - start, ivec_ref(iv, i));
}
ivec *mk_copy_ivec_subset(ivec *iv, int start, int size)
{
ivec *result = mk_ivec(size);
copy_ivec_subset(iv, start, size, result);
return (result);
}
int num_of_given_value(ivec *iv,int value)
{
int i;
int result = 0;
for ( i = 0 ; i < ivec_size(iv) ; i++ )
if ( ivec_ref(iv,i) == value ) result += 1;
return(result);
}
int num_zero_entries(ivec *iv)
{
return(num_of_given_value(iv,0));
}
int num_nonzero_entries(ivec *iv)
{
return(ivec_size(iv) - num_zero_entries(iv));
}
int ivec_arg_extreme(const ivec *iv,bool lowest)
{
int extreme_index;
int extremest_value;
int i;
if ( ivec_size(iv) <= 0 )
my_error("Can't find min or max of empty ivec");
extreme_index = 0;
extremest_value = ivec_ref(iv,0);
for ( i = 1 ; i < ivec_size(iv) ; i++ )
{
int v = ivec_ref(iv,i);
if ( (lowest && v < extremest_value) || (!lowest && v > extremest_value) )
{
extremest_value = v;
extreme_index = i;
}
}
return(extreme_index);
}
int ivec_extreme(const ivec *iv,bool lowest)
{
return ivec_ref(iv,ivec_arg_extreme(iv,lowest));
}
int ivec_min(const ivec *iv)
{
return ivec_ref(iv,ivec_arg_extreme(iv,TRUE));
}
int ivec_max(const ivec *iv)
{
return ivec_ref(iv,ivec_arg_extreme(iv,FALSE));
}
int ivec_argmin(const ivec *iv)
{
return ivec_arg_extreme(iv,TRUE);
}
int ivec_argmax(const ivec *iv)
{
return ivec_arg_extreme(iv,FALSE);
}
/* Sensible if args are NULL. False if different size */
bool ivec_equal(const ivec *x1,const ivec *x2)
{
bool result = TRUE;
if ( EQ_PTR(x1,x2) )
result = TRUE;
else if ( x1 == NULL || x2 == NULL )
result = FALSE;
else if ( ivec_size(x1) != ivec_size(x2) )
result = FALSE;
else
{
int i;
for ( i = 0 ; result && i < ivec_size(x1) ; i++ )
result = result && ivec_ref(x1,i) == ivec_ref(x2,i);
}
return(result);
}
/**** Removal functions on ivecs ****/
/* Reduces the size of iv by one.
ivec_ref(iv,index) disappears.
Everything to the right of ivec_ref(iv,index) is copied one to the left.
Formally: Let ivold be the ivec value beore calling this function
Let ivnew be the ivec value after calling this function.
PRE: ivec_size(ivold) > 0
0 <= index < ivec_size(ivold)
POST: ivec_size(ivnew) = ivec_size(ivold)-1
for j = 0 , 1, 2 ... index-1 :
ivec_ref(ivnew,j) == ivec_ref(ivold,j)
for j = index , index+1 , ... ivec_size(ivnew)-1:
ivec_ref(ivnew,j) == ivec_ref(ivold,j+1)
*/
void ivec_remove(ivec *iv,int idx)
{
int i;
int isize = ivec_size(iv);
#ifndef AMFAST
if ( isize <= 0 ) my_error("ivec_remove: empty ivec");
if ( idx < 0 || idx >= isize )
my_error("ivec_remove: bad index");
#endif /* #ifndef AMFAST */
for ( i = idx ; i < isize - 1 ; i++ )
ivec_set(iv,i,ivec_ref(iv,i+1));
iv -> size -= 1;
}
int ivec_sum(const ivec *iv)
{
int result = 0;
int i;
for ( i = 0 ; i < ivec_size(iv) ; i++ )
result += ivec_ref(iv,i);
return(result);
}
bool equal_ivecs(const ivec *iv1, const ivec *iv2)
{
bool result = TRUE;
int i;
if ( ivec_size(iv1) != ivec_size(iv2) )
my_error("qual_ivecs wrong sizes");
for ( i = 0 ; i < ivec_size(iv1) && result ; i++ )
result = ivec_ref(iv1,i) == ivec_ref(iv2,i);
return(result);
}
void add_to_ivec(ivec *iv,int new_val)
{
int size;
if ( iv->array_size < 0 )
my_error("An ivec should never have a negative array_size if\n"
"it was constructed using legal API calls");
if ( iv->size > iv->array_size )
my_error("An ivec should never have size greater than array_size if\n"
"it was constructed using legal API calls");
size = iv->size;
if ( size == iv->array_size )
{
int new_array_size = 2 * size + 10;
int *iarr_new = AM_MALLOC_ARRAY(int,new_array_size);
int i;
for ( i = 0 ; i < size ; i++ )
iarr_new[i] = iv->iarr[i];
AM_FREE_ARRAY(iv->iarr,int,size);
iv -> iarr = iarr_new;
iv -> array_size = new_array_size;
}
iv->iarr[size] = new_val;
iv -> size += 1;
}
void add_to_ivec_unique(ivec *iv,int val) {
printf("AWM comments: You should probably be using sivecs\n");
if (!is_in_ivec(iv, val)) add_to_ivec(iv, val);
}
/* Increases iv in length by 1 and shifts all elements
with original index greater or equal to index one to the
right and inserts val at index. */
void ivec_insert(ivec *iv,int idx,int val)
{
int i;
add_to_ivec(iv,0);
for ( i = ivec_size(iv)-1 ; i > idx ; i-- )
ivec_set(iv,i,ivec_ref(iv,i-1));
ivec_set(iv,idx,val);
}
/* Creates a new ivec with the given element inserted.
This is more efficient than copying and inserting. */
ivec *mk_ivec_insert( ivec *iv, int idx, int val)
{
int i, newsize;
ivec *result;
newsize = ivec_size( iv) + 1;
result = mk_ivec( newsize);
#ifndef AMFAST
if (idx >= newsize || idx < 0) {
my_errorf( "mk_ivec_insert: idx=%d is out-of-bounds [0,%d]",
idx, newsize-1);
}
#endif
for (i=0; i<idx; ++i) ivec_set( result, i, ivec_ref( iv, i));
ivec_set( result, idx, val);
for (i=idx+1; i<newsize; ++i) ivec_set( result, i, ivec_ref( iv, i-1));
return result;
}
/* Find least index i such that value = ivec_ref(iv,i).
If not found, returns -1
*/
int find_index_in_ivec(const ivec *iv, int value)
{
int result = -1;
int i;
for ( i = 0 ; i < ivec_size(iv) && result < 0 ; i++ )
if (value == ivec_ref(iv,i))
result = i;
return(result);
}
/* make and return an ivec containing the indices of iv that have value */
ivec *mk_indices_in_ivec(const ivec *iv, int value)
{
int i;
ivec *res = mk_ivec(0);
for (i=0;i<ivec_size(iv);i++) if (ivec_ref(iv,i)==value) add_to_ivec(res,i);
return res;
}
int find_index_in_ivec_hint(const ivec *iv, int value, int hint)
{
int i;
int sign = -1;
int sz = ivec_size(iv);
for (i=1; i<=sz; i++) {
int disp = i/2;
int idx = (hint + sign*disp);
/* make sure idx is in bounds. Adding sz will take care of negative idx.*/
idx = (idx + sz) % sz;
if (value == ivec_ref(iv, idx))
return idx;
sign *= -1;
}
return -1;
}
/* Finds leftmost index such that siv[index] > val. If none
such, returns ivec_size(siv) */
int index_in_sorted_ivec(ivec *siv,int val)
{
int result = -1;
int i;
for ( i = 0 ; i < ivec_size(siv) && result < 0 ; i++ )
if ( ivec_ref(siv,i) > val )
result = i;
if ( result < 0 ) result = ivec_size(siv);
return(result);
}
int find_in_sorted_ivec(ivec *siv, int val)
{
int begin = 0;
int end = ivec_size(siv);
int cur = (begin+end)/2;
while (end > begin)
{
if (ivec_ref(siv,cur) == val) return cur;
else if (ivec_ref(siv,cur) < val) begin = cur+1;
else end = cur;
cur = (begin+end)/2;
}
return -1;
}
void add_to_sorted_ivec(ivec *siv, int val)
{
int i;
add_to_ivec(siv, 0);
for (i = ivec_size(siv) - 2; i >= 0 && val < ivec_ref(siv, i); i--)
ivec_set(siv, i + 1, ivec_ref(siv, i));
ivec_set(siv, i + 1, val);
}
bool is_in_ivec( const ivec *iv,int value)
{
return(find_index_in_ivec(iv,value) >= 0);
}
/* Returns list of indices at which value appears. */
ivec *mk_is_in_ivec( ivec *iv, int value)
{
int size, num, i;
ivec *where, *r_iv;
/* Find locations of value. */
size = ivec_size( iv);
where = mk_ivec( size);
num = 0;
for (i=0; i<size; ++i) {
if (value == ivec_ref( iv, i)) {
ivec_set( where, num, i);
num += 1;
}
}
/* Copy useful part of where into r_iv. */
r_iv = mk_ivec( num);
for (i=0; i<num; ++i) ivec_set( r_iv, i, ivec_ref( where, i));
free_ivec( where);
return r_iv;
}
/* return the number of elements appearing in both ivecs */
int count_ivec_overlap(ivec *a, ivec *b)
{
int i;
int result = 0;
for (i=0;i<ivec_size(a);i++) if (is_in_ivec(b,ivec_ref(a,i))) result++;
return result;
}
/* It is fine for iv and r_iv to occupy the same memory
(see amar.c:sort_ints). */
void ivec_sort(const ivec *iv,ivec *r_iv)
{
copy_ivec(iv,r_iv);
sort_ints(r_iv->iarr,ivec_size(r_iv),r_iv->iarr);
}
ivec *mk_ivec_sort(const ivec *iv)
{
ivec *result = mk_ivec(ivec_size(iv));
ivec_sort(iv,result);
return result;
}
/*
Creates a ivec of indices such that indices[i] is the origional
location (in the unsorted iv) of the ith smallest value.
Used when you want the location of the sorted values instead of
the sorted vector.
*/
ivec *mk_sorted_ivec_indices(ivec *iv)
{
ivec* indices;
int size = ivec_size(iv);
int i;
int* iarr_ind;
int* iarr;
iarr = mk_iarr_from_ivec(iv);
iarr_ind = am_malloc_ints(size);
indices_sort_integers(iarr,size,iarr_ind);
indices = mk_ivec(size);
for(i=0;i<size;i++)
{
ivec_set(indices,i,iarr_ind[i]);
}
am_free_ints(iarr_ind,size);
am_free_ints(iarr,size);
return indices;
}
string_array *mk_string_array_from_ivec(ivec *iv)
{
string_array *sa;
if ( ivec_size(iv) == 0 )
{
sa = mk_string_array(1);
string_array_set(sa,0,"empty");
}
else
{
int i;
sa = mk_string_array(ivec_size(iv));
for ( i = 0 ; i < ivec_size(iv) ; i++ )
{
char buff[100];
sprintf(buff,"%d",ivec_ref(iv,i));
string_array_set(sa,i,buff);
}
}
return(sa);
}
/***** ivec_array time! ****/
#define INITIAL_ivec_ARRAY_SIZE 10
ivec_array *mk_ivec_array(int size)
{
int i;
ivec_array *iva;
iva = AM_MALLOC( ivec_array);
iva->size = size;
iva->array_size = int_max( size, INITIAL_ivec_ARRAY_SIZE);
iva->array = AM_MALLOC_ARRAY( ivec_ptr, iva->array_size);
for (i = 0; i < iva->array_size; i++) iva->array[i] = NULL;
return iva;
}
ivec_array *mk_empty_ivec_array(void)
{
ivec_array *ivecarr = AM_MALLOC(ivec_array);
ivecarr -> size = 0;
ivecarr -> array_size = INITIAL_ivec_ARRAY_SIZE;
ivecarr -> array = AM_MALLOC_ARRAY(ivec_ptr,ivecarr->array_size);
return(ivecarr);
}
ivec_array *mk_const_ivec_array(ivec *base_vec, int size){
int i;
ivec_array *result = mk_empty_ivec_array();
for (i=0; i<size; i++) {
add_to_ivec_array(result, base_vec);
}
return result;
}
ivec_array *mk_zero_ivec_array(int size){
ivec *temp_vec = mk_ivec(0);
ivec_array *result = mk_const_ivec_array(temp_vec, size);
free_ivec(temp_vec);
return result;
}
/* does the same thing as mk_zero_ivec_array */
ivec_array *mk_array_of_zero_length_ivecs(int size)
{
ivec_array *iva = mk_empty_ivec_array();
ivec *iv = mk_ivec(0);
int i;
for (i = 0; i < size; i++)
add_to_ivec_array(iva, iv);
free_ivec(iv);
return(iva);
}
void add_to_ivec_array(ivec_array *ivecarr,const ivec *this_ivec)
/*
Assume ivec_array is previously of size n. After this it is of size
n+1, and the n+1'th element is a COPY of this_ivec.
*/
{
if ( ivecarr -> size == ivecarr -> array_size )
{
int new_size = 2 + 2 * ivecarr->array_size;
ivec **new_array = AM_MALLOC_ARRAY(ivec_ptr,new_size);
int i;
for ( i = 0 ; i < ivecarr -> array_size ; i++ )
new_array[i] = ivecarr->array[i];
AM_FREE_ARRAY(ivecarr->array,ivec_ptr,ivecarr->array_size);
ivecarr -> array = new_array;
ivecarr -> array_size = new_size;
}
ivecarr->array[ivecarr->size] = (this_ivec==NULL) ? NULL : mk_copy_ivec(this_ivec);
ivecarr->size += 1;
}
int ivec_array_size(const ivec_array *ivecarr)
{
return(ivecarr->size);
}
/* Returns the sum of all ivec_size(...) values of all ivecs
in iva */
int sum_of_ivec_array_sizes(ivec_array *iva)
{
int result = 0;
int i;
for ( i = 0 ; i < ivec_array_size(iva) ; i++ )
result += ivec_size(ivec_array_ref(iva,i));
return result;
}
void ivec_array_set(ivec_array *iva, int idx, const ivec *iv)
{
if ((idx < 0) || (iva == NULL) || (idx >= iva->size))
my_error("ivec_array_set: called with incompatible arguments");
if (iva->array[idx] != NULL)
free_ivec(iva->array[idx]);
iva->array[idx] = (iv == NULL) ? NULL : mk_copy_ivec(iv);
}
void fprintf_ivec_array(FILE *s,char *m1,ivec_array *ivecarr,char *m2)
{
if ( ivec_array_size(ivecarr) == 0 )
fprintf(s,"%s = <ivec_array with zero entries>%s",m1,m2);
else
{
int i;
for (i=0; i<ivec_array_size(ivecarr); i++){
char buff[100];
ivec *iv = ivec_array_ref(ivecarr,i);
sprintf(buff,"%s[%2d]",m1,i);
if ( iv == NULL )
fprintf(s,"%s = NULL%s",buff,m2);
else
fprintf_ivec(s,buff,iv,m2);
}
}
}
void free_ivec_array(ivec_array *ivecarr)
{
int i;
for ( i = 0 ; i < ivec_array_size(ivecarr) ; i++ )
if ( ivecarr->array[i] != NULL )
free_ivec(ivecarr->array[i]);
AM_FREE_ARRAY(ivecarr->array,ivec_ptr,ivecarr->array_size);
AM_FREE(ivecarr,ivec_array);
}
ivec_array *mk_copy_ivec_array(const ivec_array *ivecarr)
{
ivec_array *new_ar = mk_empty_ivec_array();
int i;
for ( i = 0 ; i < ivec_array_size(ivecarr) ; i++ )
add_to_ivec_array(new_ar,ivec_array_ref(ivecarr,i));
return(new_ar);
}
bool ivec_array_equal(ivec_array *iva1,ivec_array *iva2)
{
int size = ivec_array_size(iva1);
bool result = size == ivec_array_size(iva2);
int i;
for ( i = 0 ; result && i < size ; i++ )
result = ivec_equal(ivec_array_ref(iva1,i),ivec_array_ref(iva2,i));
return result;
}
void ivec_array_remove(ivec_array *iva,int idx)
{
int i;
ivec *iv = ivec_array_ref(iva,idx);
if ( iv != NULL ) free_ivec(iv);
for ( i = idx ; i < iva->size-1 ; i++ )
iva->array[i] = iva->array[i+1];
iva->array[iva->size-1] = NULL;
iva->size -= 1;
}
/* Returns an ivec_array of length equal to ivec_size(rows)
in which result[i] = iva[rows[i]] */
ivec_array *mk_ivec_array_subset(ivec_array *iva,ivec *rows)
{
int size, row, i;
ivec *iv, *myrows;
ivec_array *result;
if ( rows == NULL) myrows = mk_identity_ivec( ivec_array_size( iva));
else myrows = rows;
size = ivec_size( myrows);
result = mk_ivec_array( size);
for (i=0; i < size; i++) {
row = ivec_ref( myrows, i);
iv = ivec_array_ref( iva, row);
ivec_array_set( result, i, iv);
}
if (rows == NULL) free_ivec( myrows);
return result;
}
/* Returns the max value in any of the ivecs in iva.
PRE: Contains at least one non-zero-length ivec */
int ivec_array_max_value(ivec_array *iva)
{
int result = -1;
bool started = FALSE;
int i;
for ( i = 0 ; i < ivec_array_size(iva) ; i++ )
{
ivec *iv = ivec_array_ref(iva,i);
if ( ivec_size(iv) > 0 )
{
int m = ivec_max(iv);
if ( started )
result = int_max(result,m);
else
{
result = m;
started = TRUE;
}
}
}
if ( !started )
my_error("ivec_array_max_value: no entries or all zero-length entries");
return result;
}
/* Returns ivec of size ivec_size(rows) in which
result[i] = x[rows[i]] */
ivec *mk_ivec_subset(ivec *x,ivec *rows)
{
int size = ivec_size(rows);
ivec *y = mk_ivec(size);
int i;
for ( i = 0 ; i < size ; i++ )
ivec_set(y,i,ivec_ref(x,ivec_ref(rows,i)));
return y;
}
/* Returns the minimum value in sivec.
Time cost: Constant */
int sivec_max(const ivec *siv)
{
return ivec_ref(siv,ivec_size(siv)-1);
}
void sivres_update(sivres *sr,int value)
{
if ( sr->intersection == NULL )
sr -> intersection_size += 1;
else
{
my_assert(ivec_size(sr->intersection) == 0 ||
ivec_ref(sr->intersection,ivec_size(sr->intersection)-1) < value);
add_to_ivec(sr->intersection,value);
}
}
void sivseg_cut(sivseg *old,sivseg *left,sivseg *right,
int left_hi,int right_lo)
{
left -> iv = old -> iv;
left -> lo = sivseg_lo(old);
left -> hi = left_hi;
right -> iv = old -> iv;
right -> lo = right_lo;
right -> hi = sivseg_hi(old);
}
int sivseg_value_to_index(sivseg *ss,int value,bool *r_exists)
{
int lo = sivseg_lo(ss);
int hi = sivseg_hi(ss);
int loval = sivseg_index_to_value(ss,lo);
int hival = sivseg_index_to_value(ss,hi);
int result = -7777;
if ( value < loval )
{
result = lo-1;
*r_exists = FALSE;
}
else if ( value > hival )
{
result = hi;
*r_exists = FALSE;
}
else if ( value == loval )
{
result = lo;
*r_exists = TRUE;
}
else if ( value == hival )
{
result = hi;
*r_exists = TRUE;
}
else
{
bool found = FALSE;
while ( hi > lo+1 && !found )
{
int mid = (lo + hi) / 2;
int midval = sivseg_index_to_value(ss,mid);
my_assert(mid > lo);
my_assert(mid < hi);
my_assert(loval < value);
my_assert(hival > value);
if ( midval == value )
{
found = TRUE;
result = mid;
}
else if ( midval < value )
{
lo = mid;
loval = midval;
}
else
{
hi = mid;
hival = midval;
}
}
if ( found )
*r_exists = TRUE;
else
{
*r_exists = FALSE;
result = lo;
}
}
return result;
}
void sivseg_search(sivseg *a,sivseg *b,sivres *sr)
{
if ( sivseg_size(a) == 0 || sivseg_size(b) == 0 )
{
/* do nothing */
}
else if ( sivseg_lo_value(a) > sivseg_hi_value(b) )
{
/* do nothing */
}
else if ( sivseg_lo_value(b) > sivseg_hi_value(a) )
{
/* do nothing */
}
else
{
if ( sivseg_size(a) > sivseg_size(b) )
{
sivseg *c = a;
a = b;
b = c;
}
if ( sivseg_size(a) <= 2 )
{
int j;
for ( j = sivseg_lo(a) ; j <= sivseg_hi(a) ; j++ )
{
bool exists;
int value = sivseg_index_to_value(a,j);
(void) sivseg_value_to_index(b,value,&exists);
if ( exists )
sivres_update(sr,value);
}
}
else
{
int mid = ( sivseg_lo(a) + sivseg_hi(a) ) / 2;
int midval = sivseg_index_to_value(a,mid);
bool exists;
int bindex = sivseg_value_to_index(b,midval,&exists);
sivseg aleft[1];
sivseg aright[1];
sivseg bleft[1];
sivseg bright[1];
sivseg_cut(a,aleft,aright,mid-1,mid+1);
sivseg_cut(b,bleft,bright,(exists)?bindex-1:bindex,bindex+1);
if ( sivseg_hi(bleft) >= sivseg_lo(bleft) ) {
sivseg_search(aleft,bleft,sr);
}
if ( exists ) sivres_update(sr,midval);
if ( sivseg_hi(bright) >= sivseg_lo(bright) )
sivseg_search(aright,bright,sr);
}
}
return;
}
/* define subset(siv,lo,hi) == { siv[lo] , siv[lo+1] , ... siv[hi] }
thus size subset = hi - lo + 1.
This function returns TRUE if and only if value is in subset(siv,lo,hi)
*/
bool is_in_sivec_between(const ivec *siv,int lo,int hi,int value)
{
bool result;
int vlo = ivec_ref(siv,lo);
int vhi = ivec_ref(siv,hi);
if ( vlo == value || vhi == value )
result = TRUE;
else if ( lo == hi )
result = FALSE;
else if ( value < vlo )
result = FALSE;
else if ( value > vhi )
result = FALSE;
else
{
result = FALSE;
while ( !result && hi > lo+1 )
{
int mid = (lo + hi) / 2;
int vmid = ivec_ref(siv,mid);
if ( vmid == value )
result = TRUE;
else if ( vmid < value )
{
lo = mid;
vlo = vmid;
}
else
{
hi = mid;
vhi = vmid;
}
}
}
return result;
}
ivec *mk_new_sivec_intersection(const ivec *a,const ivec *b)
{
sivres sr[1];
sivseg ass[1];
sivseg bss[1];
sr -> intersection = mk_ivec(0);
sr -> intersection_size = -77;
ass -> iv = (ivec *) a;
ass -> lo = 0;
ass -> hi = ivec_size(a)-1;
bss -> iv = (ivec *) b;
bss -> lo = 0;
bss -> hi = ivec_size(b)-1;
sivseg_search(ass,bss,sr);
my_assert(sr->intersection_size == -77);
return sr -> intersection;
}
ivec *mk_sivec_intersection_basic(const ivec *siva,const ivec *sivb)
{
ivec *bigresult, *result;
int ai = 0;
int bi = 0;
int asize, bsize, nextidx;
nextidx = 0;
asize = ivec_size( siva);
bsize = ivec_size( sivb);
bigresult = mk_ivec( int_min( asize, bsize));
while ( ai < ivec_size(siva) && bi < ivec_size(sivb) ) {
while ( ai < ivec_size(siva) && ivec_ref(siva,ai) < ivec_ref(sivb,bi) ) {
ai += 1;
}
if ( ai < ivec_size(siva) ) {
while ( bi < ivec_size(sivb) && ivec_ref(sivb,bi) < ivec_ref(siva,ai) ) {
bi += 1;
}
if ( bi < ivec_size(sivb) && ivec_ref(siva,ai) == ivec_ref(sivb,bi) ) {
ivec_set( bigresult, nextidx, ivec_ref( siva, ai));
nextidx += 1;
ai += 1;
bi += 1;
}
}
}
result = mk_copy_ivec_subset( bigresult, 0, nextidx);
free_ivec( bigresult);
return result;
}
ivec *mk_sivec_intersection(const ivec *siva,const ivec *sivb)
{
int asize = ivec_size(siva);
int bsize = ivec_size(sivb);
int max_size = int_max(asize,bsize);
int min_size = int_min(asize,bsize);
ivec *result;
if ( min_size * 100 < max_size ) {
result = mk_new_sivec_intersection(siva,sivb);
}
else result = mk_sivec_intersection_basic(siva,sivb);
return result;
}
/* define subset(siv,lo,hi) == { siv[lo] , siv[lo+1] , ... siv[hi] }
thus size subset = hi - lo + 1.
This function returns TRUE if and only if value is in subset(siv,lo,hi)
*/
int sio(const ivec *a,int la,int ha,const ivec *b,int lb,int hb)
{
int result;
if ( la == ha )
{
int va = ivec_ref(a,la);
if ( lb == hb )
result = ( va == ivec_ref(b,lb) ) ? 1 : 0;
else
result = ( is_in_sivec_between(b,lb,hb,va) ) ? 1 : 0;
}
else if ( lb == hb )
{
int vb = ivec_ref(b,lb);
result = ( is_in_sivec_between(a,la,ha,vb) ) ? 1 : 0;
}
else
{
int vla = ivec_ref(a,la);
int vlb = ivec_ref(b,lb);
int vha = ivec_ref(a,ha);
int vhb = ivec_ref(b,hb);
if ( vha < vlb )
result = 0;
else if ( vhb < vla )
result = 0;
else
{
int ma = (la + ha) / 2;
int mb = (lb + hb) / 2;
result = sio(a,la,ma,b,lb,mb) +
sio(a,la,ma,b,mb+1,hb) +
sio(a,ma+1,ha,b,lb,mb) +
sio(a,ma+1,ha,b,mb+1,hb);
}
}
return result;
}
int size_of_sivec_intersection(const ivec *siva,const ivec *sivb)
{
int result;
if ( ivec_size(siva) == 0 ) result = 0;
else if ( ivec_size(sivb) == 0 ) result = 0;
else {
result = sio(siva,0,ivec_size(siva)-1,sivb,0,ivec_size(sivb)-1);
}
return result;
}
/* Inverts ivec f, writing magic to values of inverse that don't occur in f.
Passed ivec must be non-negative -- this is an unnecessary restriction,
but 1) it seems like the usual case for calls to this function, and
2) it avoid making the caller pass a "known good" magic value to use
if the f is into and not onto [0,max(f)] */
ivec *mk_invert_nonneg_ivec( ivec *f)
{
int size, max, i, val;
ivec *finv;
size = ivec_size( f);
max = ivec_max( f);
finv = mk_constant_ivec( max+1, -1);
/* Invert f. */
for (i=0; i<size; ++i) {
val = ivec_ref( f, i);
ivec_set( finv, val, i);
}
return finv;
}
/* Reproducibly partition dataset rows for cross-validation. */
void make_kfold_rows( ivec *train_and_test_rows, int num_rows, int num_folds,
int fold_num, ivec **r_train_rows, ivec **r_test_rows)
{
int save_seed = int_random(300000);
ivec *srows = (train_and_test_rows==NULL) ? mk_identity_ivec(num_rows) :
mk_copy_ivec(train_and_test_rows);
int srows_size = ivec_size(srows);
int start_i = (int)floor(fold_num * num_rows / (double) num_folds);
int end_i = (int)floor((fold_num+1) * num_rows / (double) num_folds);
int i;
*r_train_rows = mk_ivec(srows_size - (end_i - start_i));
*r_test_rows = mk_ivec(end_i - start_i);
am_srand(12345);
shuffle_ivec(srows);
for ( i = 0 ; i < srows_size ; i++ )
{
ivec *update_me = (i >= start_i && i < end_i) ? *r_test_rows : *r_train_rows;
int update_index = (i < start_i) ? i :
(i < end_i) ? i - start_i : i - (end_i - start_i);
ivec_set(update_me,update_index,ivec_ref(srows,i));
}
free_ivec(srows);
am_srand(save_seed);
ivec_sort(*r_train_rows,*r_train_rows);
ivec_sort(*r_test_rows,*r_test_rows);
return;
}
ivec *mk_find_all_in_ivec( const ivec *iv, int val)
{
int size, i, found;
ivec *tmpiv, *result;
size = ivec_size( iv);
tmpiv = mk_ivec( size);
found = 0;
for (i=0; i<size; ++i) if (ivec_ref(iv,i)==val) ivec_set( tmpiv, found++, i);
/* Copy tmpiv into properly-sized ivec. */
result = mk_ivec( found);
for (i=0; i<found; ++i) ivec_set( result, i, ivec_ref(tmpiv,i));
free_ivec( tmpiv);
return result;
}
|
insilico/randomjungle
|
src/lr/amiv.c
|
C
|
gpl-2.0
| 30,317
|
/****************************************************************
* *
* Copyright 2001, 2004 Sanchez Computer Associates, Inc. *
* *
* This source code contains the intellectual property *
* of its copyright holder(s), and is made available *
* under a license. If you do not know the terms of *
* the license, please stop and do not read further. *
* *
****************************************************************/
#include "mdef.h"
#include "gtm_socket.h"
#include <sys/un.h>
#include <string.h>
#include <errno.h>
#include "gdsroot.h"
#include "gtm_facility.h"
#include "fileinfo.h"
#include "gdsbt.h"
#include "gdsfhead.h"
#include "filestruct.h"
#include "mutex.h"
#include "eintr_wrappers.h"
#ifndef MUTEX_MSEM_WAKE
GBLREF int mutex_sock_fd;
GBLREF struct sockaddr_un mutex_wake_this_proc;
GBLREF int mutex_wake_this_proc_len;
GBLREF int mutex_wake_this_proc_prefix_len;
GBLREF uint4 process_id;
void
mutex_wake_proc(sm_int_ptr_t pid, int mutex_wake_instance)
{
/*
* Wakeup process by sending a message over waiting process's socket.
* The waiting process (in select) is woken up on sensing input on its
* socket. The message is not relevant, a character will achieve the
* objective. But, we will send the waking process's pid which might
* be of use for debugging.
*/
unsigned char mutex_wake_this_proc_str[2 * sizeof(pid_t) + 1];
mutex_wake_msg_t msg;
int sendto_res;
/* Set up the socket structure for sending */
strcpy(mutex_wake_this_proc.sun_path + mutex_wake_this_proc_prefix_len,
(char *)pid2ascx(mutex_wake_this_proc_str, *pid));
msg.pid = process_id;
msg.mutex_wake_instance = mutex_wake_instance;
SENDTO_SOCK(mutex_sock_fd, (char *)&msg, sizeof(msg), 0, (struct sockaddr *)&mutex_wake_this_proc,
mutex_wake_this_proc_len, sendto_res);
return;
}
#else
void
#ifdef POSIX_MSEM
mutex_wake_proc(sem_t *mutex_wake_msem_ptr)
#else
mutex_wake_proc(msemaphore *mutex_wake_msem_ptr)
#endif
{
/* Unlock the memsem to wake the proc waiting on it */
int rc;
error_def(ERR_TEXT);
/*
* CAUTION : man pages on beowulf and hrothgar do not
* mention anything about msem_unlock being interrupted.
* It is being assumed here that msem_unlock, if interrupted
* returns -1 and sets errno to EINTR. If the behavior is
* undefined when interrupted, processes waiting to be woken
* up may hang, and WE ARE TOAST!!!
*/
/*
* Additonal note: this was converted to an EINTR wrapper macro.
*/
do
{
rc = MSEM_UNLOCK(mutex_wake_msem_ptr);
} while (-1 == rc && EINTR == errno);
if (0 > rc)
rts_error(VARLSTCNT(5) ERR_TEXT, 2,
RTS_ERROR_TEXT("Mutual Exclusion subsytem : Error with msem_unlock/sem_post"), errno);
return;
}
#endif
|
h4ck3rm1k3/FIS-GT.M
|
sr_unix/mutex_wake_proc.c
|
C
|
gpl-2.0
| 2,747
|
#pragma once
#include "widget.h"
#include <string>
#include <rfe/core/thread_queue.h>
#include <future>
namespace rfe
{
namespace ui
{
class window : public widget
{
void *m_handle = nullptr;
public:
thread_queue thread;
window(bool make_thread = true);
virtual ~window() = default;
data_event<std::string, combined_data<std::string>> title{};
data_event<color4f> clear_color;
data_event<f64> clear_depth;
data_event<u8> clear_stencil;
public:
template<typename Type, typename = std::enable_if_t<std::is_base_of<graphics::draw_context, Type>::value>>
void make_dc(graphics::draw_context::settings cfg = {}, bool create_thread = true)
{
std::shared_ptr<graphics::draw_context> dc = std::make_shared<Type>(this);
if (create_thread)
{
dc->thread = make_thread_queue(make_thread);
}
dc->thread.invoke([=] { dc->create(cfg); });
set_dc(dc);
}
protected:
void create();
event_result doclose() override;
void remove_dc();
public:
void focus() override;
void* handle() const;
using widget::operator+=;
};
}
}
|
11DH11/rfe
|
include/rfe/ui/window.h
|
C
|
gpl-2.0
| 1,111
|
<?php
/**
* @package WordPress
* @subpackage TweetPress
*/
?>
<?php
add_action('admin_menu', 'tweetpress_user_update');
function tweetpress_user_update() {
if ( isset( $_GET['page'] ) && $_GET['page'] == basename(__FILE__) ) {
if ( isset( $_REQUEST['action'] ) && 'save' == $_REQUEST['action'] ) {
check_admin_referer('tweetpress-console');
if (isset($_REQUEST['tp_twitter_username'])) update_option('tp_twitter_username', $_REQUEST['tp_twitter_username']);
if (isset($_REQUEST['tp_twitter_password']) && isset($_REQUEST['tp_password_verify'])) {
if ($_REQUEST['tp_twitter_password'] == $_REQUEST['tp_password_verify']) {
update_option('tp_twitter_password', $_REQUEST['tp_twitter_password']);
} else {
delete_option('tp_twitter_password');
wp_redirect("themes.php?page=functions.php&error=true");
die;
}
} else {
delete_option('tp_twitter_password');
wp_redirect("themes.php?page=functions.php&error=true");
die;
}
if (isset($_REQUEST['tp_feedburner_account_name'])) {
update_option('tp_feedburner_account_name', $_REQUEST['tp_feedburner_account_name']);
}
if (isset($_REQUEST['tp_ga_tracker_key'])) {
update_option('tp_ga_tracker_key', $_REQUEST['tp_ga_tracker_key']);
}
wp_redirect("themes.php?page=functions.php&saved=true");
die;
}
}
add_theme_page(__('TweetPress Admin'), __('TweetPress Admin'), 'edit_themes', basename(__FILE__), 'twitter_theme_page');
}
function twitter_theme_page() {
if ( isset( $_REQUEST['saved'] ) ) echo '<div id="message" class="updated fade"><p><strong>'.__('Settings saved.').'</strong></p></div>';
if ( isset( $_REQUEST['error'] ) ) echo '<div id="message" class="error fade"><p><strong>'.__('Please verify password.').'</strong></p></div>';
?>
<div class="wrap">
<h2><?php _e('TweetPress Admin Console'); ?></h2>
<form method="post" action="<?php echo esc_attr($_SERVER['REQUEST_URI']); ?>">
<?php wp_nonce_field('tweetpress-console'); ?>
<label for="tp_twitter_username">Twitter Username: </label>
<input type="text" name="tp_twitter_username" value="<?php echo esc_attr(twitter_username()); ?>" />
<br/>
<label for="tp_twitter_password">Twitter Password: </label>
<input type="password" name="tp_twitter_password" value="<?php echo esc_attr(twitter_password()); ?>" />
<br/>
<label for="tp_password_verify">Verify Password: </label>
<input type="password" name="tp_password_verify" value="<?php echo esc_attr(twitter_password()); ?>" />
<br/>
<label for="tp_feedburner_account_name">Feedburner Account Name: </label>
<input name="tp_feedburner_account_name" type="text" value="<?php echo esc_attr(feedburner_account_name()); ?>" />
<br/>
<label for="tp_ga_tracker_key">Google Analytics Tracker Key: </label>
<input type="text" name="tp_ga_tracker_key" value="<?php echo esc_attr(google_analytics_key()); ?>" />
<input type="hidden" name="action" value="save" />
<p class="submit"><input type="submit" name="submitform" class="button-primary" value="<?php esc_attr_e('Save Settings'); ?>" /></p>
</form>
</div>
<?php
}
function twitter_username() {
return apply_filters('tp_twitter_username',get_option('tp_twitter_username'));
}
function twitter_password() {
return apply_filters('tp_twitter_password',get_option('tp_twitter_password'));
}
function feedburner_account_name() {
return apply_filters('tp_feedburner_account_name',get_option('tp_feedburner_account_name'));
}
function google_analytics_key() {
return apply_filters('tp_ga_tracker_key',get_option('tp_ga_tracker_key'));
}
// Add feed link to address bar
automatic_feed_links();
// Twitter user object - don't touch
$t = null;
// Register sidebar for widgets
if ( function_exists('register_sidebar') ) {
register_sidebar(array(
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget' => '</li>',
'before_title' => '<hr /><h2 class="sidebar-title collapsible">',
'after_title' => '</h2>',
));
}
// Remove pages from search queries
add_filter('pre_get_posts', 'exclude_page_filter');
function exclude_page_filter($query) {
if($query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}
// Add Twitter profile image to avatar list
add_filter('avatar_defaults', 'tweetpress_gravatar');
function tweetpress_gravatar($avatar_defaults) {
$myavatar = get_bloginfo('template_url') . '/images/default_profile_1_normal.png';
$avatar_defaults[$myavatar] = 'TweetPress';
return $avatar_defaults;
}
// Helper function - determines whether site is WPMU or a single WP instance
function get_files_path() {
global $blog_id;
if (function_exists('is_site_admin')) {
return WP_CONTENT_DIR.'/blogs.dir/'.$blog_id.'/files/';
} else {
return WP_CONTENT_DIR.'/files/';
}
}
// Create files directory in wp-content for user.xml and friends directory
add_action('wp_head', 'create_files_dir');
function create_files_dir() {
if (!is_dir(get_files_path())) {
mkdir(get_files_path(), 0777, true);
}
if (!is_dir(get_files_path().'friends/')) {
mkdir(get_files_path().'friends/', 0777, true);
}
}
// Create Twitter user xml and global object
add_action('wp_head', 'create_twitter_user');
function create_twitter_user() {
global $t;
$screen_name = twitter_username();
$user = get_files_path().$screen_name.'.xml';
if(file_exists($user)) {
$fmod = filemtime($user);
if(($fmod+3600) < time()) {
$update = true;
} else {
$xml = simplexml_load_file($user);
//print_r($xml);
}
} else {
$update = true;
}
if ($update) {
$apiurl = "http://twitter.com/users/show.xml?screen_name=" . $screen_name;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $apiurl);
$data = curl_exec($ch);
curl_close($ch);
$xml = new SimpleXMLElement($data);
if (!$xml->error) {
$fp = fopen($user, "w");
fwrite($fp, $xml->asXML());
fclose($fp);
}
}
$t = $xml;
}
// Creates Twitter friends xml files
add_action('wp_head', 'create_twitter_friends');
function create_twitter_friends() {
$screen_name = twitter_username();
$count = 18;
$friends_dir = get_files_path().'friends';
$scan = scandir($friends_dir);
if (2 == count($scan)) {
$update = true;
} else {
if ((filemtime($friends_dir.'/'.$scan[2]) + 86400) < time()) $update = true;
}
if ($update) {
foreach($scan as $file) {
if($file!='.'&&$file!='..') unlink($friends_dir . '/' .$file);
}
$apiurl = "http://twitter.com/friends/ids.xml?screen_name=" . $screen_name;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $apiurl);
$data = curl_exec($ch);
curl_close($ch);
$xml = new SimpleXMLElement($data);
$fids = $xml->children();
foreach($fids as $fid) {
if($count==0) continue;
$count--;
$apiurl = "http://twitter.com/users/show.xml?user_id=" . $fid;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $apiurl);
$data = curl_exec($ch);
curl_close($ch);
$xml = new SimpleXMLElement($data);
if(!$xml->error) {
$file = $friends_dir . '/' . $fid . '.xml';
$fp = fopen($file, "w");
fwrite($fp, $xml->asXML());
fclose($fp);
chmod($file, 0755);
}
}
}
}
// Adds Twitter styles specific to user
add_action('wp_head', 'twitter_styles');
function twitter_styles() {
global $t;
$repeat = ($t->profile_background_tile=='true') ? " 0 0;" : " no-repeat fixed 0 0;";
$style = "<style type='text/css' media='screen' rel='stylesheet'>";
$style .= "body {
background:#".$t->profile_background_color." url(".$t->profile_background_image_url.")" . $repeat . "
color:#".$t->profile_text_color.";
}
a {
color:#".$t->profile_link_color.";
}
ol.posts span.post-body a {
color:#".lighten($t->profile_link_color,1.35).";
}
#sidebar {
background:#".$t->profile_sidebar_fill_color.";
border-left: 1px solid #".$t->profile_sidebar_border_color.";
}
#side hr {
background:#".$t->profile_background_color." scroll 0 0;
color:#".$t->profile_background_color.";
}
ul.sidebar-menu li.current_page_item a {
background-color:#".lighten($t->profile_sidebar_fill_color, .55).";
}
ul.sidebar-menu li:hover a, .widget_categories ul > li:hover a, .widget_links ul > li:hover a,
.widget_archive ul > li:hover a, .widget_meta ul > li:hover a, .widget_pages ul > li:hover a {
background-color:#".lighten($t->profile_sidebar_fill_color, .55).";
}
#custom_search.current_page_item {
background-color:#".lighten($t->profile_sidebar_fill_color, .55).";
}
#wp-calendar tr > td {
background-color:#".lighten($t->profile_sidebar_fill_color,.6).";
}
#wp-calendar #today {
background-color:#".lighten($t->profile_sidebar_fill_color,1.5).";
}";
$style .= "</style>";
echo $style;
}
// Displays Twitter friend images in Followers list
function get_twitter_friends() {
$friends_dir = get_files_path().'friends';
$fdir = scandir($friends_dir);
foreach($fdir as $file) {
if(($file == '.')||($file=='..')) {
// empty file(dir)
} else {
$xml = simplexml_load_file($friends_dir . '/' . $file);
$f = $xml;
?>
<li>
<a href="<?php if($f->url!='') { echo $f->url; } else { echo 'http://twitter.com/' . $f->screen_name; } ?>">
<img alt="<?php echo $f->screen_name; ?>" src="<?php echo $f->profile_image_url; ?>" height="24px" width="24px" />
</a>
</li>
<?php
}
}
}
// Posts Twitter status - available when logged in
function post_twitter_status($txt='') {
$screen_name = twitter_username();
$passwrd = twitter_password();
$user = get_files_path().$screen_name.'.xml';
if($txt == '') return;
$txt = urlencode(stripslashes(urldecode($txt)));
$headers = array("X-Twitter-Client"=>"TweetPress","X-Twitter-Client-Version"=>"2.0");
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"http://twitter.com/statuses/update.xml");
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,"status=$txt&source=tweetpress");
curl_setopt($ch,CURLOPT_USERPWD,"$screen_name:$passwrd");
$data = curl_exec($ch);
curl_close($ch);
$xml = new SimpleXMLElement($data);
if(!$xml->error) {
$usrxml = simplexml_load_file($user);
$usrxml->status->created_at = $xml->created_at;
$usrxml->status->id = $xml->id;
$usrxml->status->text = $xml->text;
$usrxml->status->source = $xml->source;
$usrxml->status->truncated = $xml->truncated;
$usrxml->status->in_reply_to_status_id = $xml->in_reply_to_status_id;
$usrxml->status->in_reply_to_user_id = $xml->in_reply_to_user_id;
$usrxml->status->favorited = $xml->favorited;
$usrxml->status->in_reply_to_screen_name = $xml->in_reply_to_screen_name;
$fp = fopen( $user, "w" );
fwrite( $fp, $usrxml->asXML() );
fclose( $fp );
touch($user,(time()-3600));
return $xml->text;
} else {
return false;
}
}
// Displays time as '... ago'
function format_time_ago($timestamp, $granularity = 1) {
$date = strtotime($timestamp);
$diff = time() - $date;
if(($diff/86400)>1) {
return date('g:i A M jS Y',strtotime($timestamp));
} else {
$periods = array('hour' => 3600,
'minute' => 60,
'second' => 1
);
foreach($periods as $key => $value) {
if($diff >= $value) {
$time = floor($diff/$value);
$diff %= $value;
$retval .= ($retval ? ' ' : '').$time.' ';
$retval .= (($time>1) ? $key.'s' : $key);
$granularity--;
}
if($granularity==0)break;
}
if(strrpos($retval,'minute')!==false) {
if($time<10) return $retval.' ago';
else return 'about ' . $retval . ' ago';
} else {
return ' about '.$retval.' ago';
}
}
}
// Replace plain text URL's into links and @<user> to Twitter links
function format_status($status) {
$status = preg_replace("/(http:\/\/[^\s]+)/", "<a href=\"$1\">$1</a>", $status);
echo preg_replace('/(?<=@)(\w+)/', "<a href='http://twitter.com/$0'>$0</a>" , $status);
}
// Replace plain text URL's into links and @<user> to Twitter links
function format_excerpt($excerpt) {
$excerpt = (strlen($excerpt)>140) ? substr($excerpt,0,137) . '...' : $excerpt;
preg_match("/(http:\/\/[^\s]+)/", $excerpt, $matches);
if(!$matches || !strrpos($matches[0],'...')) {
$excerpt = preg_replace("/(http:\/\/[^\s]+)/", "<a target='_blank' href=\"$1\">$1</a>", $excerpt);
}
return $excerpt;
}
// Returns your own retweet url using bitly api
function retweet_url($url,$headline) {
$screen_name = twitter_username();
if(!$url || $url=='') return;
return 'http://twitter.com/?status=RT @' . $screen_name . ': ' . $headline . ' ' . bitly_url($url);
}
// Bit.ly api stuff - default is TweetPress key, change to your own if you like, but you dont have to
function bitly_url($url) {
$bitly_id = "tweetpress";
$bitly_key = "R_5e496e175db584ab27410d1d4824870a";
$apiurl = "http://api.bit.ly/shorten?version=2.0.1&format=xml&login=$bitly_id&apiKey=$bitly_key&longUrl=$url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $apiurl);
$data = curl_exec($ch);
$xml = new SimpleXMLElement($data);
if($xml->errorCode==0) {
return $xml->results->nodeKeyVal->shortUrl;
}
}
// Returns Feedburner url
function feedburner_url() {
$fbacct = feedburner_account_name();
echo 'http://feeds.feedburner.com/'.$fbacct;
}
// Returns Feedburner count
function feedburner_count() {
$fbacct = feedburner_account_name();
$apiurl = "http://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=" . $fbacct;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $apiurl);
$data = curl_exec($ch);
curl_close($ch);
$xml = new SimpleXMLElement($data);
$count = $xml->feed->entry['circulation'];
if(!$count) $count = '??????';
echo number_format($count, 0, '.', ',');
}
// Color functions...
function lighten($hex, $pct) {
$rgb = hex2rgb($hex);
for($i = 0; $i < 3; $i++) {
$rgb[$i] = ceil( ($rgb[$i]*$pct)+(255*(1-$pct)) );
if( $rgb[$i]>255 ) $rgb[$i] = 255;
}
return rgb2hex( $rgb );
}
function hex2rgb($hex) {
$d = '[a-fA-F0-9]';
if(preg_match("/^($d$d)($d$d)($d$d)\$/", $hex, $rgb)) {
return array(
hexdec($rgb[1]),
hexdec($rgb[2]),
hexdec($rgb[3])
);
}
if(preg_match("/^($d)($d)($d)$/", $hex, $rgb)) {
return array(
hexdec($rgb[1] . $rgb[1]),
hexdec($rgb[2] . $rgb[2]),
hexdec($rgb[3] . $rgb[3])
);
}
return false;
}
function rgb2hex($rgb) {
$hex = "";
for($i=0; $i < 3; $i++) {
$hexDigit = dechex($rgb[$i]);
if(strlen( $hexDigit ) == 1) {
$hexDigit = "0" . $hexDigit;
}
$hex .= $hexDigit;
}
return $hex;
}
?>
|
CoordCulturaDigital-Minc/culturadigital.br
|
wp-content/themes/tweetpress/functions.php
|
PHP
|
gpl-2.0
| 14,679
|
var Gelato_Pulse = {
form : null,
init: function() {
Gelato_Pulse.form = jQuery( '.pulse-form' );
jQuery('<input />')
.attr( 'type', 'hidden' )
.attr( 'class', 'ss_synctime' )
.attr( 'name', 'ss_synctime' )
.appendTo( Gelato_Pulse.form );
Gelato_Pulse.form.find( 'textarea').keyup( function() {
Gelato_Media.pauseForModule();
} );
Gelato_Pulse.form.submit( function( e ) {
console.log( Gelato_Media.media.roundTime());
jQuery('.ss_synctime').val( Gelato_Media.media.roundTime() );
Gelato_Media.playForModule();
} );
},
onContentLoad: function() {
if ( typeof CTLT_Stream != 'undefined' ) { // Check for stream activity
CTLT_Stream.on( 'server-push', Gelato_Pulse.listen );
}
Gelato_Media.media.on( 'loadedmetadata', Gelato_Pulse.loadPulses );
Gelato_Media.media.on( 'loadedmetadata', Gelato_Pulse.loadMarkers );
},
listen: function( data ) {
if ( data.type == 'pulse' ) { // We are interested
var pulse_data = jQuery.parseJSON(data.data);
Gelato_Pulse.addPulse( pulse_data, pulse_data.synctime, true );
}
},
loadMarkers: function() {
if( typeof gelatoScoop.bookmarks != 'undefined') {
for ( index in gelatoScoop.bookmarks.list ) {
var bookmark = gelatoScoop.bookmarks.list[index];
Gelato_Media.media.pulse( {
start: bookmark.synctime,
end: Gelato_Media.media.duration(),
text: '<a class="bookmark" onclick="Gelato_Media.skipTo('+bookmark.synctime+');">'+bookmark.title+'<span class="time">'+bookmark.time+'</span></a>',
sort: true,
target: "pulse-list",
} );
}
}
},
loadPulses: function() {
var list = gelatoScoop.pulse;
console.log(list);
for ( index in list ) {
Gelato_Pulse.addPulse( list[index], list[index].synctime, false );
}
},
addPulse: function( data, start, sort ) {
var new_pulse = Pulse_CPT_Form.single_pulse_template( data );
Gelato_Media.media.pulse( {
start: start,
end: Gelato_Media.media.duration(),
text: new_pulse,
sort: sort,
target: "pulse-list",
} );
},
}
Gelato_Pulse.init();
document.addEventListener( "DOMContentLoaded", Gelato_Pulse.onContentLoad, false );
|
ubc/gelato
|
public/includes/scoops/pulse/view-pulse.js
|
JavaScript
|
gpl-2.0
| 2,191
|
<?php
// public function verifyResponseUrl($url_params = array())
// {
// if(empty($url_params['checksum'])){
// echo "invalid parameters: checksum is missing";
// return FALSE;
// }
$checksum = $_GET['checksum'];
unset($_GET['checksum']);
ksort($_GET);
$file = "/tmp/bklog.log";
$fh = fopen($file, 'a');
var_dump($_GET);
fwrite($fh, implode('', $_GET));
if (strcasecmp($checksum, hash_hmac('SHA1', implode('', $_GET), '3ead8c83e15053f3')) == 0) {
fwrite($fh, 'true');
} else {
return FALSE;
}
$name = "hương+Quan-+Trí+Quả+-Thuận+Thành-+Bắc+Ninh%2C+Huyện+Thuận+Thành%2C+Bắc+Ninh";
echo urldecode($name);
?>
|
thienlelong/golf-vietnam
|
wp-content/themes/nisarg/baokim/old/callback.php
|
PHP
|
gpl-2.0
| 628
|
from django.contrib.auth import logout as auth_logout
from django.contrib.auth.decorators import login_required
from django.http import *
from django.template import Template, Context
from django.shortcuts import render_to_response, redirect, render, RequestContext, HttpResponseRedirect
def login(request):
return render(request, 'login.html')
@login_required
def home(request):
u = request.user
return render_to_response("home.html", locals(), context_instance=RequestContext(request))
def logout(request):
auth_logout(request)
return redirect('/')
|
COMU/lazimlik
|
lazimlik/social_app/views.py
|
Python
|
gpl-2.0
| 568
|
/*
mediastreamer2 library - modular sound and video processing and streaming
Copyright (C) 2006 Simon MORLAT (simon.morlat@linphone.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.
*/
#ifdef HAVE_CONFIG_H
#include "mediastreamer-config.h"
#include "gitversion.h"
#else
# ifndef MEDIASTREAMER_VERSION
# define MEDIASTREAMER_VERSION "unknown"
# endif
# ifndef GIT_VERSION
# define GIT_VERSION "unknown"
# endif
#endif
#include "mediastreamer2/mscommon.h"
#include "mediastreamer2/mscodecutils.h"
#include "mediastreamer2/msfilter.h"
#include <ortp/ortp_srtp.h>
extern void __register_ffmpeg_encoders_if_possible(void);
extern void ms_ffmpeg_check_init();
extern bool_t libmsandroiddisplay_init(void);
extern void libmsandroiddisplaybad_init(void);
extern void libmsandroidopengldisplay_init(void);
#include "alldescs.h"
#include "mediastreamer2/mssndcard.h"
#include "mediastreamer2/mswebcam.h"
#if !defined(_WIN32_WCE)
#include <sys/types.h>
#endif
#ifndef WIN32
#include <dirent.h>
#else
#ifndef PACKAGE_PLUGINS_DIR
#if defined(WIN32) || defined(_WIN32_WCE)
#define PACKAGE_PLUGINS_DIR "lib\\mediastreamer\\plugins\\"
#else
#define PACKAGE_PLUGINS_DIR "."
#endif
#endif
#endif
#ifdef HAVE_DLOPEN
#include <dlfcn.h>
#endif
#ifdef __APPLE__
#include "TargetConditionals.h"
#endif
#ifdef ANDROID
#include <android/log.h>
#endif
#if defined(WIN32) && !defined(_WIN32_WCE)
static MSList *ms_plugins_loaded_list;
#endif
static unsigned int cpu_count = 1;
unsigned int ms_get_cpu_count() {
return cpu_count;
}
void ms_set_cpu_count(unsigned int c) {
ms_message("CPU count set to %d", c);
cpu_count = c;
}
MSList *ms_list_new(void *data){
MSList *new_elem=(MSList *)ms_new(MSList,1);
new_elem->prev=new_elem->next=NULL;
new_elem->data=data;
return new_elem;
}
MSList * ms_list_append(MSList *elem, void * data){
MSList *new_elem=ms_list_new(data);
MSList *it=elem;
if (elem==NULL) return new_elem;
while (it->next!=NULL) it=ms_list_next(it);
it->next=new_elem;
new_elem->prev=it;
return elem;
}
MSList * ms_list_prepend(MSList *elem, void *data){
MSList *new_elem=ms_list_new(data);
if (elem!=NULL) {
new_elem->next=elem;
elem->prev=new_elem;
}
return new_elem;
}
MSList * ms_list_concat(MSList *first, MSList *second){
MSList *it=first;
if (it==NULL) return second;
while(it->next!=NULL) it=ms_list_next(it);
it->next=second;
second->prev=it;
return first;
}
MSList * ms_list_free(MSList *list){
MSList *elem = list;
MSList *tmp;
if (list==NULL) return NULL;
while(elem->next!=NULL) {
tmp = elem;
elem = elem->next;
ms_free(tmp);
}
ms_free(elem);
return NULL;
}
MSList * ms_list_remove(MSList *first, void *data){
MSList *it;
it=ms_list_find(first,data);
if (it) return ms_list_remove_link(first,it);
else {
ms_warning("ms_list_remove: no element with %p data was in the list", data);
return first;
}
}
int ms_list_size(const MSList *first){
int n=0;
while(first!=NULL){
++n;
first=first->next;
}
return n;
}
void ms_list_for_each(const MSList *list, void (*func)(void *)){
for(;list!=NULL;list=list->next){
func(list->data);
}
}
void ms_list_for_each2(const MSList *list, void (*func)(void *, void *), void *user_data){
for(;list!=NULL;list=list->next){
func(list->data,user_data);
}
}
MSList *ms_list_remove_link(MSList *list, MSList *elem){
MSList *ret;
if (elem==list){
ret=elem->next;
elem->prev=NULL;
elem->next=NULL;
if (ret!=NULL) ret->prev=NULL;
ms_free(elem);
return ret;
}
elem->prev->next=elem->next;
if (elem->next!=NULL) elem->next->prev=elem->prev;
elem->next=NULL;
elem->prev=NULL;
ms_free(elem);
return list;
}
MSList *ms_list_find(MSList *list, void *data){
for(;list!=NULL;list=list->next){
if (list->data==data) return list;
}
return NULL;
}
MSList *ms_list_find_custom(MSList *list, int (*compare_func)(const void *, const void*), const void *user_data){
for(;list!=NULL;list=list->next){
if (compare_func(list->data,user_data)==0) return list;
}
return NULL;
}
void * ms_list_nth_data(const MSList *list, int index){
int i;
for(i=0;list!=NULL;list=list->next,++i){
if (i==index) return list->data;
}
ms_error("ms_list_nth_data: no such index in list.");
return NULL;
}
int ms_list_position(const MSList *list, MSList *elem){
int i;
for(i=0;list!=NULL;list=list->next,++i){
if (elem==list) return i;
}
ms_error("ms_list_position: no such element in list.");
return -1;
}
int ms_list_index(const MSList *list, void *data){
int i;
for(i=0;list!=NULL;list=list->next,++i){
if (data==list->data) return i;
}
ms_error("ms_list_index: no such element in list.");
return -1;
}
MSList *ms_list_insert_sorted(MSList *list, void *data, int (*compare_func)(const void *, const void*)){
MSList *it,*previt=NULL;
MSList *nelem;
MSList *ret=list;
if (list==NULL) return ms_list_append(list,data);
else{
nelem=ms_list_new(data);
for(it=list;it!=NULL;it=it->next){
previt=it;
if (compare_func(data,it->data)<=0){
nelem->prev=it->prev;
nelem->next=it;
if (it->prev!=NULL)
it->prev->next=nelem;
else{
ret=nelem;
}
it->prev=nelem;
return ret;
}
}
previt->next=nelem;
nelem->prev=previt;
}
return ret;
}
MSList *ms_list_insert(MSList *list, MSList *before, void *data){
MSList *elem;
if (list==NULL || before==NULL) return ms_list_append(list,data);
for(elem=list;elem!=NULL;elem=ms_list_next(elem)){
if (elem==before){
if (elem->prev==NULL)
return ms_list_prepend(list,data);
else{
MSList *nelem=ms_list_new(data);
nelem->prev=elem->prev;
nelem->next=elem;
elem->prev->next=nelem;
elem->prev=nelem;
}
}
}
return list;
}
MSList *ms_list_copy(const MSList *list){
MSList *copy=NULL;
const MSList *iter;
for(iter=list;iter!=NULL;iter=ms_list_next(iter)){
copy=ms_list_append(copy,iter->data);
}
return copy;
}
#ifndef PLUGINS_EXT
#define PLUGINS_EXT ".so"
#endif
typedef void (*init_func_t)(void);
int ms_load_plugins(const char *dir){
int num=0;
#if defined(WIN32) && !defined(_WIN32_WCE)
WIN32_FIND_DATA FileData;
HANDLE hSearch;
char szDirPath[1024];
char szPluginFile[1024];
BOOL fFinished = FALSE;
const char *tmp=getenv("DEBUG");
BOOL debug=(tmp!=NULL && atoi(tmp)==1);
snprintf(szDirPath, sizeof(szDirPath), "%s", dir);
// Start searching for .dll files in the current directory.
snprintf(szDirPath, sizeof(szDirPath), "%s\\*.dll", dir);
hSearch = FindFirstFile(szDirPath, &FileData);
if (hSearch == INVALID_HANDLE_VALUE)
{
ms_message("no plugin (*.dll) found in %s.", szDirPath);
return 0;
}
snprintf(szDirPath, sizeof(szDirPath), "%s", dir);
while (!fFinished)
{
/* load library */
HINSTANCE os_handle;
UINT em=0;
if (!debug) em = SetErrorMode (SEM_FAILCRITICALERRORS);
snprintf(szPluginFile, sizeof(szPluginFile), "%s\\%s", szDirPath, FileData.cFileName);
os_handle = LoadLibraryEx (szPluginFile, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
if (os_handle==NULL)
{
ms_message("Fail to load plugin %s with altered search path: error %i",szPluginFile,(int)GetLastError());
os_handle = LoadLibraryEx (szPluginFile, NULL, 0);
}
if (!debug) SetErrorMode (em);
if (os_handle==NULL)
ms_error("Fail to load plugin %s", szPluginFile);
else{
init_func_t initroutine;
char szPluginName[256];
char szMethodName[256];
char *minus;
snprintf(szPluginName, 256, "%s", FileData.cFileName);
/*on mingw, dll names might be libsomething-3.dll. We must skip the -X.dll stuff*/
minus=strchr(szPluginName,'-');
if (minus) *minus='\0';
else szPluginName[strlen(szPluginName)-4]='\0'; /*remove .dll*/
snprintf(szMethodName, 256, "%s_init", szPluginName);
initroutine = (init_func_t) GetProcAddress (os_handle, szMethodName);
if (initroutine!=NULL){
initroutine();
ms_message("Plugin loaded (%s)", szPluginFile);
// Add this new loaded plugin to the list (useful for FreeLibrary at the end)
ms_plugins_loaded_list=ms_list_append(ms_plugins_loaded_list,os_handle);
num++;
}else{
ms_warning("Could not locate init routine of plugin %s. Should be %s",
szPluginFile, szMethodName);
}
}
if (!FindNextFile(hSearch, &FileData)) {
if (GetLastError() == ERROR_NO_MORE_FILES){
fFinished = TRUE;
}
else
{
ms_error("couldn't find next plugin dll.");
fFinished = TRUE;
}
}
}
/* Close the search handle. */
FindClose(hSearch);
#elif HAVE_DLOPEN
DIR *ds;
struct dirent *de;
char *fullpath;
ds=opendir(dir);
if (ds==NULL){
ms_message("Cannot open directory %s: %s",dir,strerror(errno));
return -1;
}
while( (de=readdir(ds))!=NULL){
if ((de->d_type==DT_REG && strstr(de->d_name,PLUGINS_EXT)!=NULL)
|| (de->d_type==DT_UNKNOWN && strstr(de->d_name,PLUGINS_EXT)==de->d_name+strlen(de->d_name)-strlen(PLUGINS_EXT))) {
void *handle;
fullpath=ms_strdup_printf("%s/%s",dir,de->d_name);
ms_message("Loading plugin %s...",fullpath);
if ( (handle=dlopen(fullpath,RTLD_NOW))==NULL){
ms_warning("Fail to load plugin %s : %s",fullpath,dlerror());
}else {
char *initroutine_name=ms_malloc0(strlen(de->d_name)+10);
char *p;
void *initroutine=NULL;
strcpy(initroutine_name,de->d_name);
p=strstr(initroutine_name,PLUGINS_EXT);
if (p!=NULL){
strcpy(p,"_init");
initroutine=dlsym(handle,initroutine_name);
}
#ifdef __APPLE__
if (initroutine==NULL){
/* on macosx: library name are libxxxx.1.2.3.dylib */
/* -> MUST remove the .1.2.3 */
p=strstr(initroutine_name,".");
if (p!=NULL)
{
strcpy(p,"_init");
initroutine=dlsym(handle,initroutine_name);
}
}
#endif
if (initroutine!=NULL){
init_func_t func=(init_func_t)initroutine;
func();
ms_message("Plugin loaded (%s)", fullpath);
num++;
}else{
ms_warning("Could not locate init routine of plugin %s",de->d_name);
}
ms_free(initroutine_name);
}
ms_free(fullpath);
}
}
closedir(ds);
#else
ms_warning("no loadable plugin support: plugins cannot be loaded.");
num=-1;
#endif
return num;
}
void ms_unload_plugins(){
#if defined(WIN32) && !defined(_WIN32_WCE)
MSList *elem;
for(elem=ms_plugins_loaded_list;elem!=NULL;elem=elem->next)
{
HINSTANCE handle=(HINSTANCE )elem->data;
FreeLibrary(handle) ;
}
ms_list_free(ms_plugins_loaded_list);
#endif
}
#ifdef __ALSA_ENABLED__
extern MSSndCardDesc alsa_card_desc;
#endif
#ifdef HAVE_SYS_SOUNDCARD_H
extern MSSndCardDesc oss_card_desc;
#endif
#ifdef __ARTS_ENABLED__
extern MSSndCardDesc arts_card_desc;
#endif
#ifdef WIN32
extern MSSndCardDesc winsnd_card_desc;
#endif
#ifdef __DIRECTSOUND_ENABLED__
extern MSSndCardDesc winsndds_card_desc;
#endif
#ifdef __MACSND_ENABLED__
extern MSSndCardDesc ca_card_desc;
#endif
#ifdef __PORTAUDIO_ENABLED__
extern MSSndCardDesc pasnd_card_desc;
#endif
#ifdef __MAC_AQ_ENABLED__
extern MSSndCardDesc aq_card_desc;
#endif
#ifdef __PULSEAUDIO_ENABLED__
extern MSSndCardDesc pulse_card_desc;
#endif
#if TARGET_OS_IPHONE
extern MSSndCardDesc au_card_desc;
#endif
#ifdef ANDROID
extern MSSndCardDesc msandroid_sound_card_desc;
#endif
static MSSndCardDesc * ms_snd_card_descs[]={
#ifdef __ALSA_ENABLED__
&alsa_card_desc,
#endif
#ifdef HAVE_SYS_SOUNDCARD_H
&oss_card_desc,
#endif
#ifdef __ARTS_ENABLED__
&arts_card_desc,
#endif
#ifdef WIN32
&winsnd_card_desc,
#endif
#ifdef __DIRECTSOUND_ENABLED__
&winsndds_card_desc,
#endif
#ifdef __PORTAUDIO_ENABLED__
&pasnd_card_desc,
#endif
#ifdef __MACSND_ENABLED__
&ca_card_desc,
#endif
#ifdef __PULSEAUDIO_ENABLED__
&pulse_card_desc,
#endif
#if TARGET_OS_IPHONE
&au_card_desc,
#endif
#ifdef __MAC_AQ_ENABLED__
&aq_card_desc,
#endif
#ifdef ANDROID
&msandroid_sound_card_desc,
#endif
NULL
};
#ifdef VIDEO_ENABLED
#ifdef HAVE_LINUX_VIDEODEV_H
extern MSWebCamDesc v4l_desc;
#endif
#ifdef HAVE_LINUX_VIDEODEV2_H
extern MSWebCamDesc v4l2_card_desc;
#endif
#ifdef WIN32
extern MSWebCamDesc ms_vfw_cam_desc;
#endif
#if defined(WIN32) && defined(HAVE_DIRECTSHOW)
extern MSWebCamDesc ms_directx_cam_desc;
#endif
#if defined(__MINGW32__) || defined (HAVE_DIRECTSHOW)
extern MSWebCamDesc ms_dshow_cam_desc;
#endif
#if TARGET_OS_MAC && !TARGET_OS_IPHONE
extern MSWebCamDesc ms_v4m_cam_desc;
#endif
extern MSWebCamDesc static_image_desc;
#if !defined(NO_FFMPEG)
extern MSWebCamDesc mire_desc;
#endif
#ifdef ANDROID
extern MSWebCamDesc ms_android_video_capture_desc;
#endif
#if TARGET_OS_IPHONE && !TARGET_IPHONE_SIMULATOR
extern MSWebCamDesc ms_v4ios_cam_desc;
#endif
static MSWebCamDesc * ms_web_cam_descs[]={
#ifdef HAVE_LINUX_VIDEODEV2_H
&v4l2_card_desc,
#endif
#ifdef HAVE_LINUX_VIDEODEV_H
&v4l_desc,
#endif
#if defined(WIN32) && defined(HAVE_VFW)
&ms_vfw_cam_desc,
#endif
#if defined(__MINGW32__) || defined (HAVE_DIRECTSHOW)
&ms_dshow_cam_desc,
#endif
#if TARGET_OS_MAC && !TARGET_OS_IPHONE
&ms_v4m_cam_desc,
#endif
#if defined (ANDROID)
&ms_android_video_capture_desc,
#endif
#if TARGET_OS_IPHONE && !TARGET_IPHONE_SIMULATOR
&ms_v4ios_cam_desc,
#endif
#if !defined(NO_FFMPEG)
&mire_desc,
#endif
&static_image_desc,
NULL
};
#endif
#ifdef ANDROID
#define LOG_DOMAIN "mediastreamer"
static void ms_android_log_handler(OrtpLogLevel lev, const char *fmt, va_list args){
int prio;
switch(lev){
case ORTP_DEBUG: prio = ANDROID_LOG_DEBUG; break;
case ORTP_MESSAGE: prio = ANDROID_LOG_INFO; break;
case ORTP_WARNING: prio = ANDROID_LOG_WARN; break;
case ORTP_ERROR: prio = ANDROID_LOG_ERROR; break;
case ORTP_FATAL: prio = ANDROID_LOG_FATAL; break;
default: prio = ANDROID_LOG_DEFAULT; break;
}
__android_log_vprint(prio, LOG_DOMAIN, fmt, args);
}
#endif
void ms_init(){
int i;
MSSndCardManager *cm;
#if defined(ENABLE_NLS)
bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
#endif
#if !defined(_WIN32_WCE)
if (getenv("MEDIASTREAMER_DEBUG")!=NULL){
ortp_set_log_level_mask(ORTP_DEBUG|ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR|ORTP_FATAL);
}
#endif
//#ifdef ANDROID
// ortp_set_log_level_mask(ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR|ORTP_FATAL);
// ortp_set_log_handler(ms_android_log_handler);
//#endif
ms_message("Mediastreamer2 " MEDIASTREAMER_VERSION " (git: " GIT_VERSION ") starting.");
/* register builtin MSFilter's */
for (i=0;ms_filter_descs[i]!=NULL;i++){
ms_filter_register(ms_filter_descs[i]);
}
ms_message("Registering all soundcard handlers");
cm=ms_snd_card_manager_get();
for (i=0;ms_snd_card_descs[i]!=NULL;i++){
ms_snd_card_manager_register_desc(cm,ms_snd_card_descs[i]);
}
#ifdef VIDEO_ENABLED
ms_message("Registering all webcam handlers");
{
MSWebCamManager *wm;
wm=ms_web_cam_manager_get();
for (i=0;ms_web_cam_descs[i]!=NULL;i++){
ms_web_cam_manager_register_desc(wm,ms_web_cam_descs[i]);
}
}
#if !defined(NO_FFMPEG)
ms_ffmpeg_check_init();
__register_ffmpeg_encoders_if_possible();
#endif
#endif
#ifdef PACKAGE_PLUGINS_DIR
ms_message("Loading ms plugins from [%s]",PACKAGE_PLUGINS_DIR);
ms_load_plugins(PACKAGE_PLUGINS_DIR);
#endif
#if defined(ANDROID) && defined (VIDEO_ENABLED)
if (1) {
libmsandroidopengldisplay_init();
} else {
if (!libmsandroiddisplay_init()) {
libmsandroiddisplaybad_init();
}
}
#endif
ms_message("ms_init() done");
}
void ms_exit(){
ms_filter_unregister_all();
ms_snd_card_manager_destroy();
#ifdef VIDEO_ENABLED
ms_web_cam_manager_destroy();
#endif
ms_unload_plugins();
}
void ms_sleep(int seconds){
#ifdef WIN32
Sleep(seconds*1000);
#else
struct timespec ts,rem;
int err;
ts.tv_sec=seconds;
ts.tv_nsec=0;
do {
err=nanosleep(&ts,&rem);
ts=rem;
}while(err==-1 && errno==EINTR);
#endif
}
void ms_usleep(uint64_t usec){
#ifdef WIN32
Sleep((DWORD)(usec/1000));
#else
struct timespec ts,rem;
int err;
ts.tv_sec=usec/1000000LL;
ts.tv_nsec=(usec%1000000LL)*1000;
do {
err=nanosleep(&ts,&rem);
ts=rem;
}while(err==-1 && errno==EINTR);
#endif
}
#define DEFAULT_MAX_PAYLOAD_SIZE 1440
static int max_payload_size=DEFAULT_MAX_PAYLOAD_SIZE;
int ms_get_payload_max_size(){
return max_payload_size;
}
void ms_set_payload_max_size(int size){
if (size<=0) size=DEFAULT_MAX_PAYLOAD_SIZE;
max_payload_size=size;
}
extern void _android_key_cleanup(void*);
void ms_thread_exit(void* ref_val) {
#ifdef ANDROID
// due to a bug in old Bionic version
// cleanup of jni manually
// works directly with Android 2.2
_android_key_cleanup(NULL);
#endif
#if !defined(__linux) || defined(ANDROID)
ortp_thread_exit(ref_val); // pthread_exit futex issue: http://lkml.indiana.edu/hypermail/linux/kernel/0902.0/00153.html
#endif
}
#ifdef __MACH__
#include <sys/types.h>
#include <sys/timeb.h>
#endif
void ms_get_cur_time(MSTimeSpec *ret){
#if defined(_WIN32_WCE) || defined(WIN32)
DWORD timemillis;
# if defined(_WIN32_WCE)
timemillis=GetTickCount();
# else
timemillis=timeGetTime();
# endif
ret->tv_sec=timemillis/1000;
ret->tv_nsec=(timemillis%1000)*1000000LL;
#elif defined(__MACH__) && defined(__GNUC__) && (__GNUC__ >= 3)
struct timeval tv;
gettimeofday(&tv, NULL);
ret->tv_sec=tv.tv_sec;
ret->tv_nsec=tv.tv_usec*1000LL;
#elif defined(__MACH__)
struct timeb time_val;
ftime (&time_val);
ret->tv_sec = time_val.time;
ret->tv_nsec = time_val.millitm * 1000000LL;
#else
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC,&ts)<0){
ms_fatal("clock_gettime() doesn't work: %s",strerror(errno));
}
ret->tv_sec=ts.tv_sec;
ret->tv_nsec=ts.tv_nsec;
#endif
}
struct _MSConcealerContext {
int64_t sample_time;
int64_t plc_start_time;
unsigned long total_number_for_plc;
unsigned int max_plc_time;
};
/*** plc context begin***/
unsigned long ms_concealer_context_get_total_number_of_plc(MSConcealerContext* obj) {
return obj->total_number_for_plc;
}
MSConcealerContext* ms_concealer_context_new(unsigned int max_plc_time){
MSConcealerContext *obj=(MSConcealerContext *) ms_new(MSConcealerContext,1);
obj->sample_time=-1;
obj->plc_start_time=-1;
obj->total_number_for_plc=0;
obj->max_plc_time=max_plc_time;
return obj;
}
void ms_concealer_context_destroy(MSConcealerContext* context) {
ms_free(context);
}
int ms_concealer_inc_sample_time(MSConcealerContext* obj, uint64_t current_time, int time_increment, int got_packet){
int plc_duration=0;
if (obj->sample_time==-1){
obj->sample_time=(int64_t)current_time;
}
obj->sample_time+=time_increment;
if (obj->plc_start_time!=-1 && got_packet){
plc_duration=current_time-obj->plc_start_time;
obj->plc_start_time=-1;
if (plc_duration>obj->max_plc_time) plc_duration=obj->max_plc_time;
}
return plc_duration;
}
unsigned int ms_concealer_context_is_concealement_required(MSConcealerContext* obj,uint64_t current_time) {
if(obj->sample_time == -1) return 0; /*no valid value*/
if (obj->sample_time < current_time){
int plc_duration;
if (obj->plc_start_time==-1)
obj->plc_start_time=obj->sample_time;
plc_duration=current_time-obj->plc_start_time;
if (plc_duration<obj->max_plc_time) {
obj->total_number_for_plc++;
return 1;
}else{
/*reset sample time, so that we don't do PLC anymore and can resync properly when the stream restarts*/
obj->sample_time=-1;
return 0;
}
}
return 0;
}
/*** plc context end***/
|
avis/mediastreamer2
|
src/mscommon.c
|
C
|
gpl-2.0
| 19,757
|
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2011,2012 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Marco Miozzo <marco.miozzo@cttc.es>
* Nicola Baldo <nbaldo@cttc.es>
*/
#include <ns3/log.h>
#include <ns3/test.h>
#include <ns3/itu-r-1411-los-propagation-loss-model.h>
#include <ns3/string.h>
#include <ns3/double.h>
#include <ns3/constant-position-mobility-model.h>
#include <ns3/enum.h>
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("ItuR1411LosPropagationLossModelTest");
/**
* \ingroup propagation-tests
*
* \brief ItuR1411LosPropagationLossModel Test Case
*
*/
class ItuR1411LosPropagationLossModelTestCase : public TestCase
{
public:
/**
* Constructor
*
* \param freq carrier frequency in Hz
* \param dist 2D distance between UT and BS in meters
* \param hb height of BS in meters
* \param hm height of UT in meters
* \param refValue reference loss value
* \param name TestCase name
*/
ItuR1411LosPropagationLossModelTestCase (double freq, double dist, double hb, double hm, double refValue, std::string name);
virtual ~ItuR1411LosPropagationLossModelTestCase ();
private:
virtual void DoRun (void);
/**
* Create a MobilityModel
* \param index mobility model index
* \return a new MobilityModel
*/
Ptr<MobilityModel> CreateMobilityModel (uint16_t index);
double m_freq; //!< carrier frequency in Hz
double m_dist; //!< 2D distance between UT and BS in meters
double m_hb; //!< height of BS in meters
double m_hm; //!< height of UT in meters
double m_lossRef; //!< reference loss
};
ItuR1411LosPropagationLossModelTestCase::ItuR1411LosPropagationLossModelTestCase (double freq, double dist, double hb, double hm, double refValue, std::string name)
: TestCase (name),
m_freq (freq),
m_dist (dist),
m_hb (hb),
m_hm (hm),
m_lossRef (refValue)
{
}
ItuR1411LosPropagationLossModelTestCase::~ItuR1411LosPropagationLossModelTestCase ()
{
}
void
ItuR1411LosPropagationLossModelTestCase::DoRun (void)
{
NS_LOG_FUNCTION (this);
Ptr<MobilityModel> mma = CreateObject<ConstantPositionMobilityModel> ();
mma->SetPosition (Vector (0.0, 0.0, m_hb));
Ptr<MobilityModel> mmb = CreateObject<ConstantPositionMobilityModel> ();
mmb->SetPosition (Vector (m_dist, 0.0, m_hm));
Ptr<ItuR1411LosPropagationLossModel> propagationLossModel = CreateObject<ItuR1411LosPropagationLossModel> ();
propagationLossModel->SetAttribute ("Frequency", DoubleValue (m_freq));
double loss = propagationLossModel->GetLoss (mma, mmb);
NS_LOG_INFO ("Calculated loss: " << loss);
NS_LOG_INFO ("Theoretical loss: " << m_lossRef);
NS_TEST_ASSERT_MSG_EQ_TOL (loss, m_lossRef, 0.1, "Wrong loss!");
}
/**
* \ingroup propagation-tests
*
* \brief ItuR1411LosPropagationLossModel TestSuite
*
*/
class ItuR1411LosPropagationLossModelTestSuite : public TestSuite
{
public:
ItuR1411LosPropagationLossModelTestSuite ();
};
ItuR1411LosPropagationLossModelTestSuite::ItuR1411LosPropagationLossModelTestSuite ()
: TestSuite ("itu-r-1411-los", SYSTEM)
{
LogComponentEnable ("ItuR1411LosPropagationLossModelTest", LOG_LEVEL_ALL);
// reference values obtained with the octave scripts in src/propagation/test/reference/
AddTestCase (new ItuR1411LosPropagationLossModelTestCase (2.1140e9, 100, 30, 1, 81.005, "freq=2114MHz, dist=100m"), TestCase::QUICK);
AddTestCase (new ItuR1411LosPropagationLossModelTestCase (1999e6, 200, 30, 1, 87.060, "freq=1999MHz, dist=200m"), TestCase::QUICK);
}
/// Static variable for test initialization
static ItuR1411LosPropagationLossModelTestSuite g_ituR1411LosTestSuite;
|
nsnam/ns-3-dev-git
|
src/propagation/test/itu-r-1411-los-test-suite.cc
|
C++
|
gpl-2.0
| 4,359
|
package org.ecocean.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ecocean.CommonConfiguration;
import org.ecocean.Encounter;
import org.ecocean.Measurement;
import org.ecocean.Shepherd;
public class EncounterSetMeasurements extends HttpServlet {
private static final Pattern MEASUREMENT_NAME = Pattern.compile("measurement(\\d+)\\(([^)]*)\\)");
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String context="context0";
context=ServletUtilities.getContext(request);
Shepherd myShepherd=new Shepherd(context);
//set up for response
response.setContentType("text/html");
PrintWriter out = response.getWriter();
boolean locked=false;
String encNum="None";
encNum=request.getParameter("encounter");
myShepherd.beginDBTransaction();
if (myShepherd.isEncounter(encNum)) {
Encounter enc=myShepherd.getEncounter(encNum);
List<RequestEventValues> list = new ArrayList<RequestEventValues>();
int index = 0;
RequestEventValues requestEventValues = findRequestEventValues(request, index++);
try {
while (requestEventValues != null) {
list.add(requestEventValues);
Measurement measurement;
if (requestEventValues.id == null || requestEventValues.id.trim().length() == 0) {
// New Event -- the user didn't enter any values the first time.
measurement = new Measurement(encNum, requestEventValues.type, requestEventValues.value, requestEventValues.units, requestEventValues.samplingProtocol);
enc.setMeasurement(measurement, myShepherd);
//log the new measurement addition
enc.addComments("<p><em>" + request.getRemoteUser() + " on " + (new java.util.Date()).toString() + "</em><br>Added measurement:<br><i>" + requestEventValues.type + " "+requestEventValues.value+" "+requestEventValues.units+" ("+requestEventValues.samplingProtocol+")</i></p>");
}
else {
measurement = myShepherd.findDataCollectionEvent(Measurement.class, requestEventValues.id);
String oldValue="null";
if(measurement.getValue()!=null){oldValue=measurement.getValue().toString();}
String oldSamplingProtocol="null";
if(measurement.getSamplingProtocol()!=null){oldSamplingProtocol=measurement.getSamplingProtocol();}
//now set the new values
measurement.setValue(requestEventValues.value);
measurement.setSamplingProtocol(requestEventValues.samplingProtocol);
//log the measurement change -- TBD
enc.addComments("<p><em>" + request.getRemoteUser() + " on " + (new java.util.Date()).toString() + "</em><br>Changed measurement " + requestEventValues.type + " from "+oldValue+" ("+oldSamplingProtocol+") to "+requestEventValues.value+" "+requestEventValues.units+" ("+requestEventValues.samplingProtocol+")</i></p>");
}
requestEventValues = findRequestEventValues(request, index++);
}
} catch(Exception ex) {
ex.printStackTrace();
locked = true;
myShepherd.rollbackDBTransaction();
myShepherd.closeDBTransaction();
}
if (!locked) {
myShepherd.commitDBTransaction();
myShepherd.closeDBTransaction();
out.println(ServletUtilities.getHeader(request));
out.println("<p><strong>Success!</strong> I have successfully set the following measurement values:");
for (RequestEventValues requestEventValue : list) {
out.println(MessageFormat.format("<br/>{0} set to {1}", requestEventValue.type, requestEventValue.value));
}
out.println("<p><a href=\"http://"+CommonConfiguration.getURLLocation(request)+"/encounters/encounter.jsp?number="+encNum+"\">Return to encounter "+encNum+"</a></p>\n");
out.println(ServletUtilities.getFooter(context));
}
else {
out.println(ServletUtilities.getHeader(request));
out.println("<strong>Failure!</strong> This encounter is currently being modified by another user, or an exception occurred. Please wait a few seconds before trying to modify this encounter again.");
out.println("<p><a href=\"http://"+CommonConfiguration.getURLLocation(request)+"/encounters/encounter.jsp?number="+encNum+"\">Return to encounter "+encNum+"</a></p>\n");
out.println(ServletUtilities.getFooter(context));
}
}
else {
myShepherd.rollbackDBTransaction();
out.println(ServletUtilities.getHeader(request));
out.println("<strong>Error:</strong> I was unable to set the measurement(s). I cannot find the encounter that you intended in the database.");
out.println(ServletUtilities.getFooter(context));
}
out.close();
myShepherd.closeDBTransaction();
}
// The parameter names are of the form "measurement0(id)", "measurement0(type)", "measurement0(value"), "measurement1(id)", "measurement1(type)", "measurement1(value)" etc.
// All of same numbered names are part of the same measurement event.
private RequestEventValues findRequestEventValues(HttpServletRequest request, int index) {
String key = "measurement" + index + '(';
final int keyLength = key.length();
Enumeration enumeration = request.getParameterNames();
String id = null;
String type = null;
Double value = null;
String units = null;
String samplingProtocol = null;
while (enumeration.hasMoreElements()) {
String paramName = (String) enumeration.nextElement();
if (paramName.startsWith(key)) {
String paramValue = request.getParameter(paramName);
if (paramValue != null) {
paramValue = paramValue.trim();
}
if (paramName.substring(keyLength).startsWith("id")) {
id = paramValue;
}
else if (paramName.substring(keyLength).startsWith("type")) {
type = paramValue;
}
else if (paramName.substring(keyLength).startsWith("value")) {
if (paramValue != null) {
try {
value = Double.valueOf(paramValue);
} catch (NumberFormatException e) {
}
}
}
else if (paramName.substring(keyLength).startsWith("units")) {
units = paramValue;
}
else if (paramName.substring(keyLength).startsWith("samplingProtocol")) {
samplingProtocol = paramValue;
}
}
}
if (id != null || type != null || value != null) {
return new RequestEventValues(id, type, value, units, samplingProtocol);
}
return null;
}
private static class RequestEventValues {
private String id;
private String type;
private Double value;
private String units;
private String samplingProtocol;
public RequestEventValues(String id, String type, Double value, String units, String samplingProtocol) {
this.id = id;
this.type = type;
this.value = value;
this.units = units;
this.samplingProtocol = samplingProtocol;
}
}
}
|
gforghetti/jenkins-tomcat-wildbook
|
src/main/java/org/ecocean/servlet/EncounterSetMeasurements.java
|
Java
|
gpl-2.0
| 7,830
|
<?php
/**
* @version SEBLOD 3.x Core
* @package SEBLOD (App Builder & CCK) // SEBLOD nano (Form Builder)
* @url https://www.seblod.com
* @editor Octopoos - www.octopoos.com
* @copyright Copyright (C) 2009 - 2017 SEBLOD. All Rights Reserved.
* @license GNU General Public License version 2 or later; see _LICENSE.php
**/
defined( '_JEXEC' ) or die;
// Plugin
class plgCCK_Field_LinkContent extends JCckPluginLink
{
protected static $type = 'content';
// -------- -------- -------- -------- -------- -------- -------- -------- // Prepare
// onCCK_Field_LinkPrepareContent
public static function onCCK_Field_LinkPrepareContent( &$field, &$config = array() )
{
if ( self::$type != $field->link ) {
return;
}
// Prepare
$link = parent::g_getLink( $field->link_options );
// Set
$field->link = '';
self::_link( $link, $field, $config );
}
// _link
protected static function _link( $link, &$field, &$config )
{
$app = JFactory::getApplication();
$sef = $link->get( 'sef', $config['doSEF'] );
if ( !JFactory::getConfig()->get( 'sef' ) ) {
$sef = 0;
}
$itemId = ( $sef ) ? $link->get( 'itemid', '' ) : '';
$content = $link->get( 'content', '' );
$custom = $link->get( 'custom', '' );
$path_type = (int)$link->get( 'path_type', 0 );
// Prepare
if ( !$itemId ) {
$view = $app->input->get( 'view', '' );
$layout = $app->input->get( 'layout', '' );
if ( ( $view == 'category' && $layout == 'blog' ) || $view == 'featured' ) {
$sef = 0;
}
if ( $sef ) {
$itemId = $app->input->getInt( 'Itemid', 0 );
}
}
$lang_tag = $link->get( 'language', '' );
$link_attr = $link->get( 'attributes', '' );
$link_class = $link->get( 'class', '' );
$link_rel = $link->get( 'rel', '' );
$link_target = $link->get( 'target', '' );
$link_title = $link->get( 'title', '' );
$link_title2 = $link->get( 'title_custom', '' );
$tmpl = $link->get( 'tmpl', '' );
$tmpl = ( $tmpl == '-1' ) ? $app->input->getCmd( 'tmpl', '' ) : $tmpl;
$tmpl = ( $tmpl ) ? 'tmpl='.$tmpl : '';
$vars = $tmpl;
if ( $link_target == 'modal' ) {
if ( strpos( $link_attr, 'data-cck-modal' ) === false ) {
$modal_json = $link->get( 'target_params', '' );
if ( $modal_json != '' ) {
$modal_json = '=\''.$modal_json.'\'';
}
$link_attr = trim( $link_attr.' data-cck-modal'.$modal_json );
}
}
if ( ( $content == '2' || $content == '-2' || (int)$itemId < 0 ) && $sef ) {
$field->link = '';
if ( $content == '2' || $content == '-2' ) {
$location = $link->get( 'content_location' );
$pk = 0;
} else {
$location = $config['location'];
$pk = $config['pk'];
}
if ( $content != '-2' ) {
parent::g_addProcess( 'beforeRenderContent', self::$type, $config, array( 'name'=>$field->name, 'fieldname'=>$link->get( 'content_fieldname', '' ), 'fieldname2'=>$link->get( 'itemid_fieldname', '' ), 'fieldnames'=>$link->get( 'itemid_mapping', '' ), 'itemId'=>$itemId, 'location'=>$location, 'pk'=>$pk, 'sef'=>$sef, 'vars'=>$vars, 'custom'=>$custom ) );
}
}
$custom = parent::g_getCustomVars( self::$type, $field, $custom, $config );
// Set
if ( is_array( $field->value ) ) {
$location = 'joomla_article';
foreach ( $field->value as $f ) {
$f->link = JCck::callFunc_Array( 'plgCCK_Storage_Location'.$location, 'getRoute', array( $f->value, $sef, $itemId, $config ) );
$f->link_attributes = $link_attr ? $link_attr : ( isset( $f->link_attributes ) ? $f->link_attributes : '' );
$f->link_class = $link_class ? $link_class : ( isset( $f->link_class ) ? $f->link_class : '' );
$f->link_rel = $link_rel ? $link_rel : ( isset( $f->link_rel ) ? $f->link_rel : '' );
$f->link_state = $link->get( 'state', 1 );
$f->link_target = $link_target ? ( $link_target == 'modal' ? '' : $link_target ) : ( isset( $f->link_target ) ? $f->link_target : '' );
if ( $link_title ) {
if ( $link_title == '2' ) {
$f->link_title = $link_title2;
} elseif ( $link_title == '3' ) {
$f->link_title = JText::_( 'COM_CCK_' . str_replace( ' ', '_', trim( $link_title2 ) ) );
}
if ( !isset( $f->link_title ) ) {
$f->link_title = '';
}
} else {
$f->link_title = '';
}
}
$field->link = '#'; //todo
} else {
if ( ( $content == '4' || $content == '5' ) ) {
// $goto = self::_goTo( $app->input->getInt( 'Itemid', $config['Itemid'] ) );
$field->link = '';
if ( $content == '5' ) {
//
} else {
//
}
} elseif ( $content == '-2' ) {
$field->link = JCck::callFunc_Array( 'plgCCK_Storage_Location'.$location, 'getRoute', array( $field->value, $sef, $itemId, $config ) );
} elseif ( $content != '2' ) {
$field->link = ( $config['location'] ) ? JCck::callFunc_Array( 'plgCCK_Storage_Location'.$config['location'], 'getRouteByStorage', array( &$config['storages'], $sef, $itemId, $config, $lang_tag ) ) : '';
} else {
$field->link = '';
}
if ( $field->link ) {
if ( $vars ) {
$field->link .= ( strpos( $field->link, '?' ) !== false ) ? '&'.$vars : '?'.$vars;
}
if ( $custom ) {
$field->link .= ( $custom[0] == '#' ) ? $custom : ( ( strpos( $field->link, '?' ) !== false ) ? '&'.$custom : '?'.$custom );
}
}
if ( $app->isClient( 'administrator' ) ) {
$field->link = str_replace( '/administrator', '', $field->link );
$link_attr = ' data-cck-route="'.base64_encode( $field->link ).'"';
static $loaded = 0;
if ( !$loaded ) {
$loaded = 1;
$js = '(function ($){
$(document).ready(function() {
$("a[data-cck-route]").each(function(i) {
var $el = $(this);
$.ajax({
cache: false,
data: "link="+encodeURIComponent( $el.attr("data-cck-route") ),
type: "GET",
url: "'. JCckDevHelper::getAbsoluteUrl( 'auto', 'task=route&format=raw', 'root' ) .'",
beforeSend:function(){},
success: function(resp){ $el.attr("href",resp); $el.removeAttr("data-cck-route"); }
});
});
});
})(jQuery);';
JFactory::getDocument()->addScriptDeclaration( $js );
}
}
if ( $path_type ) {
if ( $site_id = $link->get( 'site', '' ) ) {
$base = '';
$site = JCck::getSiteById( $site_id );
if ( is_object( $site ) && $site->name != '' ) {
$base = JUri::getInstance()->getScheme().'://'.$site->name;
}
} else {
$base = JUri::getInstance()->toString( array( 'scheme', 'host' ) );
}
if ( $path_type == 2 || $path_type == 3 ) {
$field->link = $base.$field->link;
$segment = JRoute::_( 'index.php?Itemid='.$itemId );
if ( $segment == '/' ) {
$segment = '';
}
$base .= $segment.'/';
$field->link = str_replace( $base, '', $field->link );
$field->link = '#'.$field->link;
if ( $path_type == 2 ) {
$field->link = $base.$field->link;
}
} else {
$field->link = $base.$field->link;
}
}
$field->link_attributes = $link_attr ? $link_attr : ( isset( $field->link_attributes ) ? $field->link_attributes : '' );
$field->link_class = $link_class ? $link_class : ( isset( $field->link_class ) ? $field->link_class : '' );
$field->link_rel = $link_rel ? $link_rel : ( isset( $field->link_rel ) ? $field->link_rel : '' );
$field->link_state = $link->get( 'state', 1 );
$field->link_target = $link_target ? ( $link_target == 'modal' ? '' : $link_target ) : ( isset( $field->link_target ) ? $field->link_target : '' );
if ( $link_title ) {
if ( $link_title == '2' ) {
$field->link_title = $link_title2;
} elseif ( $link_title == '3' ) {
$field->link_title = JText::_( 'COM_CCK_' . str_replace( ' ', '_', trim( $link_title2 ) ) );
}
if ( !isset( $field->link_title ) ) {
$field->link_title = '';
}
} else {
$field->link_title = '';
}
}
}
// -------- -------- -------- -------- -------- -------- -------- -------- // Special Events
// onCCK_Field_LinkBeforeRenderContent
public static function onCCK_Field_LinkBeforeRenderContent( $process, &$fields, &$storages, &$config = array() )
{
$itemId = @$process['itemId'];
$name = $process['name'];
$fieldname = $process['fieldname'];
$location = $process['location'];
if ( isset( $process['pk'] ) && $process['pk'] ) {
$pk = $process['pk'];
} else {
$pk = isset( $fields[$fieldname] ) ? (int)$fields[$fieldname]->value : 0;
}
if ( !$pk ) {
if ( isset( $process['matches'] ) && count( $process['matches'][1] ) ) {
parent::g_setCustomVars( $process, $fields, $name );
}
return;
}
if ( $itemId == '-2' ) {
$itemId = JFactory::getApplication()->input->getInt( 'Itemid' );
$fieldname2 = $process['fieldname2'];
if ( isset( $fields[$fieldname2] ) ) {
$itemId = (int)$fields[$fieldname2]->value;
}
} elseif ( $itemId == '-3' ) {
$itemId = JFactory::getApplication()->input->getInt( 'Itemid' );
$itemIds = $process['fieldnames'];
$items = explode( '||', $itemIds );
if ( count( $items ) ) {
foreach ( $items as $item ) {
if ( $item != '' ) {
$parts = explode( '=', $item );
if ( $parts[1] ) {
$checks = json_decode( $parts[0], true );
$count = count( $checks );
$found = 0;
if ( $count ) {
foreach ( $checks as $k=>$v ) {
if ( isset( $fields[$k] ) && $fields[$k]->value == $v ) {
$found++;
}
}
}
if ( $found == $count ) {
$itemId = $parts[1];
break;
}
}
}
}
}
}
$fields[$name]->link = JCck::callFunc_Array( 'plgCCK_Storage_Location'.$location, 'getRoute', array( $pk, $process['sef'], $itemId, $config ) );
$target = $fields[$name]->typo_target;
if ( isset( $fields[$name]->typo_mode ) && $fields[$name]->typo_mode ) {
$target = 'typo';
}
if ( $fields[$name]->link ) {
if ( $process['vars'] ) {
$fields[$name]->link .= ( strpos( $fields[$name]->link, '?' ) !== false ) ? '&'.$process['vars'] : '?'.$process['vars'];
}
if ( $process['custom'] ) {
$process['custom'] = parent::g_getCustomVars( self::$type, $fields[$name], $process['custom'], $config );
$fields[$name]->link .= ( $process['custom'][0] == '#' ) ? $process['custom'] : ( ( strpos( $fields[$name]->link, '?' ) !== false ) ? '&'.$process['custom'] : '?'.$process['custom'] );
}
JCckPluginLink::g_setHtml( $fields[$name], $target );
}
if ( $fields[$name]->typo ) {
$html = ( isset( $fields[$name]->html ) ) ? $fields[$name]->html : '';
if ( strpos( $fields[$name]->typo, $fields[$name]->$target ) === false ) {
$fields[$name]->typo = $html;
} else {
$fields[$name]->typo = str_replace( $fields[$name]->$target, $html, $fields[$name]->typo );
}
}
if ( isset( $process['matches'] ) && count( $process['matches'][1] ) ) {
parent::g_setCustomVars( $process, $fields, $name );
}
}
// _goto
protected static function _goTo( $itemId )
{
$menu = JFactory::getApplication()->getMenu();
$item = $menu->getItem( $itemId );
$search = $item->query['search'];
$items = self::_gotoItems( $search, $itemId );
}
// _goToItems
protected static function _goToItems( $search, $itemId )
{
static $items = array();
$goto = $search.'_'.$itemId;
if ( !isset( $items[$goto] ) ) {
$class_sfx = '';
$uniqId = 'f'.$field->id;
$formId = 'seblod_list_'.$uniqId;
$preconfig = array();
$preconfig['action'] = '';
$preconfig['client'] = 'search';
$preconfig['formId'] = $formId;
$preconfig['submit'] = 'JCck.Core.submit_'.$uniqId;
$preconfig['search'] = $search;
$preconfig['itemId'] = $itemId;
$preconfig['task'] = 'search';
$preconfig['show_form'] = 0;
$preconfig['show_list'] = 0;
$preconfig['auto_redirect'] = 0;
$preconfig['limit2'] = 0; // todo
$preconfig['ordering'] = ''; // todo
$preconfig['ordering2'] = ''; // todo
$live = '';
$variation = '';
$limitstart = -1;
$params = new JRegistry; // todo : remove+inherit?
$params->set( 'order_by', '' );
// Prepare
jimport( 'cck.base.list.list' );
include JPATH_SITE.'/libraries/cck/base/list/list_inc.php';
$items[$goto] = $items;
}
return $items[$goto];
}
}
?>
|
oliviernolbert/SEBLOD
|
plugins/cck_field_link/content/content.php
|
PHP
|
gpl-2.0
| 12,838
|
#include <iostream>
#include <algorithm>
#include <cstring>
/*
* LCS
* { 1 + f(i - 1, j - 1), a[i] == b[j]
* f(i, j) = { 0, i == 0 or j == 0
* { max{f(i, j - 1), f(i - 1, j)}, otherwise
*/
using namespace std;
#define N 101
int f[N][N];
int a[N], b[N];
int dp(int i, int j) {
if (i == 0 || j == 0)
return 0;
if (f[i][j])
return f[i][j];
if (a[i] == b[j])
return f[i][j] = 1 + dp(i - 1, j - 1);
return f[i][j] = max(dp(i - 1, j), dp(i, j - 1));
}
int main() {
int cases = 0;
int la, lb;
while (cin >> la >> lb, la || lb) {
memset(f, 0, sizeof(f));
for (int i = 1; i <= la; ++i)
cin >> a[i];
for (int i = 1; i <= lb; ++i)
cin >> b[i];
dp(la, lb);
cout << "Twin Towers #" << ++cases << endl << "Number of Tiles : " << f[la][lb] << endl << endl;
}
return 0;
}
|
condy0919/uva-code
|
10066.cpp
|
C++
|
gpl-2.0
| 914
|
<?php /* lilurl.php ( lilURL class file ) */
define('READ_ONLY', true);
define('READ_WRITE', false);
class lilURL
{
// constructor
function lilURL($read_only)
{
// open mysql connection
if($read_only){
mysql_connect(MYSQL_READ_HOST, MYSQL_USER, MYSQL_PASS) or die('Could not connect to database');
}
else {
mysql_connect(MYSQL_WRITE_HOST, MYSQL_USER, MYSQL_PASS) or die('Could not connect to database');
}
mysql_select_db(MYSQL_DB) or die('Could not select database');
}
// return the id for a given url (or -1 if the url doesn't exist)
function get_id($url)
{
$q = 'SELECT id FROM '.URL_TABLE.' WHERE (url="'.$url.'")';
$result = mysql_query($q);
if ( mysql_num_rows($result) )
{
$row = mysql_fetch_array($result);
return $row['id'];
}
else
{
return -1;
}
}
// return the url for a given id (or -1 if the id doesn't exist)
function get_url($id)
{
$q = 'SELECT url FROM '.URL_TABLE.' WHERE (id="'.$id.'")';
$result = mysql_query($q);
if ( mysql_num_rows($result) )
{
$row = mysql_fetch_array($result);
return $row['url'];
}
else
{
return -1;
}
}
// add a url to the database
function add_url($url)
{
// check to see if the url's already in there
$id = $this->get_id($url);
// if it is, return true
if ( $id != -1 )
{
return true;
}
else // otherwise, put it in
{
$id = $this->get_next_id($this->get_last_id());
$q = 'INSERT INTO '.URL_TABLE.' (id, url, date) VALUES ("'.$id.'", "'.$url.'", NOW())';
return mysql_query($q);
}
}
// return the most recent id (or -1 if no ids exist)
function get_last_id()
{
$q = 'SELECT id FROM '.URL_TABLE.' ORDER BY date DESC LIMIT 1';
$result = mysql_query($q);
if ( mysql_num_rows($result) )
{
$row = mysql_fetch_array($result);
return $row['id'];
}
else
{
return -1;
}
}
// return the next id
function get_next_id($last_id)
{
// if the last id is -1 (non-existant), start at the begining with 0
if ( $last_id == -1 )
{
$next_id = 0;
}
else
{
// loop through the id string until we find a character to increment
for ( $x = 1; $x <= strlen($last_id); $x++ )
{
$pos = strlen($last_id) - $x;
if ( $last_id[$pos] != 'z' )
{
$next_id = $this->increment_id($last_id, $pos);
break; // <- kill the for loop once we've found our char
}
}
// if every character was already at its max value (z),
// append another character to the string
if ( !isSet($next_id) )
{
$next_id = $this->append_id($last_id);
}
}
// check to see if the $next_id we made already exists, and if it does,
// loop the function until we find one that doesn't
//
// (this is basically a failsafe to get around the potential dangers of
// my kludgey use of a timestamp to pick the most recent id)
$q = 'SELECT id FROM '.URL_TABLE.' WHERE (id="'.$next_id.'")';
$result = mysql_query($q);
if ( mysql_num_rows($result) )
{
$next_id = $this->get_next_id($next_id);
}
return $next_id;
}
// make every character in the string 0, and then add an additional 0 to that
function append_id($id)
{
for ( $x = 0; $x < strlen($id); $x++ )
{
$id[$x] = 0;
}
$id .= 0;
return $id;
}
// increment a character to the next alphanumeric value and return the modified id
function increment_id($id, $pos)
{
$char = $id[$pos];
// add 1 to numeric values
if ( is_numeric($char) )
{
if ( $char < 9 )
{
$new_char = $char + 1;
}
else // if we're at 9, it's time to move to the alphabet
{
$new_char = 'a';
}
}
else // move it up the alphabet
{
$new_char = chr(ord($char) + 1);
}
$id[$pos] = $new_char;
// set all characters after the one we're modifying to 0
if ( $pos != (strlen($id) - 1) )
{
for ( $x = ($pos + 1); $x < strlen($id); $x++ )
{
$id[$x] = 0;
}
}
return $id;
}
}
?>
|
RobLoach/ur1.ca
|
includes/lilurl.php
|
PHP
|
gpl-2.0
| 3,929
|
#include "StdInc.h"
#include "CBattleCallback.h"
#include "BattleState.h"
#include "CGameState.h"
#include "NetPacks.h"
#include "spells/CSpellHandler.h"
#include "VCMI_Lib.h"
#include "CTownHandler.h"
#include "mapObjects/CGTownInstance.h"
/*
* CBattleCallback.cpp, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#define RETURN_IF_NOT_BATTLE(X) if(!duringBattle()) {logGlobal->errorStream() << __FUNCTION__ << " called when no battle!"; return X; }
namespace SiegeStuffThatShouldBeMovedToHandlers // <=== TODO
{
static void retreiveTurretDamageRange(const CGTownInstance * town, const CStack *turret, double &outMinDmg, double &outMaxDmg)
{
assert(turret->getCreature()->idNumber == CreatureID::ARROW_TOWERS);
assert(town);
assert(turret->position >= -4 && turret->position <= -2);
float multiplier = (turret->position == -2) ? 1 : 0.5;
int baseMin = 6;
int baseMax = 10;
outMinDmg = multiplier * (baseMin + town->getTownLevel() * 2);
outMaxDmg = multiplier * (baseMax + town->getTownLevel() * 3);
}
static BattleHex lineToWallHex(int line) //returns hex with wall in given line (y coordinate)
{
static const BattleHex lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
return lineToHex[line];
}
static bool sameSideOfWall(BattleHex pos1, BattleHex pos2)
{
const int wallInStackLine = lineToWallHex(pos1.getY());
const int wallInDestLine = lineToWallHex(pos2.getY());
const bool stackLeft = pos1 < wallInStackLine;
const bool destLeft = pos2 < wallInDestLine;
return stackLeft != destLeft;
}
// parts of wall
static const std::pair<int, EWallPart::EWallPart> wallParts[] =
{
std::make_pair(50, EWallPart::KEEP),
std::make_pair(183, EWallPart::BOTTOM_TOWER),
std::make_pair(182, EWallPart::BOTTOM_WALL),
std::make_pair(130, EWallPart::BELOW_GATE),
std::make_pair(62, EWallPart::OVER_GATE),
std::make_pair(29, EWallPart::UPPER_WALL),
std::make_pair(12, EWallPart::UPPER_TOWER),
std::make_pair(95, EWallPart::INDESTRUCTIBLE_PART_OF_GATE),
std::make_pair(96, EWallPart::GATE),
std::make_pair(45, EWallPart::INDESTRUCTIBLE_PART),
std::make_pair(78, EWallPart::INDESTRUCTIBLE_PART),
std::make_pair(112, EWallPart::INDESTRUCTIBLE_PART),
std::make_pair(147, EWallPart::INDESTRUCTIBLE_PART)
};
static EWallPart::EWallPart hexToWallPart(BattleHex hex)
{
for(auto & elem : wallParts)
{
if(elem.first == hex)
return elem.second;
}
return EWallPart::INVALID; //not found!
}
static BattleHex WallPartToHex(EWallPart::EWallPart part)
{
for(auto & elem : wallParts)
{
if(elem.second == part)
return elem.first;
}
return BattleHex::INVALID; //not found!
}
}
using namespace SiegeStuffThatShouldBeMovedToHandlers;
boost::shared_mutex& CCallbackBase::getGsMutex()
{
return *gs->mx;
}
bool CCallbackBase::duringBattle() const
{
return getBattle() != nullptr;
}
void CCallbackBase::setBattle(const BattleInfo *B)
{
battle = B;
}
boost::optional<PlayerColor> CCallbackBase::getPlayerID() const
{
return player;
}
ETerrainType CBattleInfoEssentials::battleTerrainType() const
{
RETURN_IF_NOT_BATTLE(ETerrainType::WRONG);
return getBattle()->terrainType;
}
BFieldType CBattleInfoEssentials::battleGetBattlefieldType() const
{
RETURN_IF_NOT_BATTLE(BFieldType::NONE);
return getBattle()->battlefieldType;
}
std::vector<std::shared_ptr<const CObstacleInstance> > CBattleInfoEssentials::battleGetAllObstacles(boost::optional<BattlePerspective::BattlePerspective> perspective /*= boost::none*/) const
{
std::vector<std::shared_ptr<const CObstacleInstance> > ret;
RETURN_IF_NOT_BATTLE(ret);
if(!perspective)
{
//if no particular perspective request, use default one
perspective = battleGetMySide();
}
else
{
if(!!player && *perspective != battleGetMySide())
{
logGlobal->errorStream() << "Unauthorized access attempt!";
assert(0); //I want to notice if that happens
//perspective = battleGetMySide();
}
}
for(auto oi : getBattle()->obstacles)
{
if(getBattle()->battleIsObstacleVisibleForSide(*oi, *perspective))
ret.push_back(oi);
}
return ret;
}
bool CBattleInfoEssentials::battleIsObstacleVisibleForSide(const CObstacleInstance & coi, BattlePerspective::BattlePerspective side) const
{
RETURN_IF_NOT_BATTLE(false);
return side == BattlePerspective::ALL_KNOWING || coi.visibleForSide(side, battleHasNativeStack(side));
}
bool CBattleInfoEssentials::battleHasNativeStack(ui8 side) const
{
RETURN_IF_NOT_BATTLE(false);
for(const CStack *s : battleGetAllStacks())
{
if(s->attackerOwned == !side && s->getCreature()->isItNativeTerrain(getBattle()->terrainType))
return true;
}
return false;
}
TStacks CBattleInfoEssentials::battleGetAllStacks(bool includeTurrets /*= false*/) const
{
return battleGetStacksIf([](const CStack * s){return true;},includeTurrets);
}
TStacks CBattleInfoEssentials::battleGetStacksIf(TStackFilter predicate, bool includeTurrets /*= false*/) const
{
TStacks ret;
RETURN_IF_NOT_BATTLE(ret);
vstd::copy_if(getBattle()->stacks, std::back_inserter(ret), [=](const CStack * s){
return predicate(s) && (includeTurrets || !(s->type->idNumber == CreatureID::ARROW_TOWERS));
});
return ret;
}
TStacks CBattleInfoEssentials::battleAliveStacks() const
{
return battleGetStacksIf([](const CStack * s){
return s->alive();
});
}
TStacks CBattleInfoEssentials::battleAliveStacks(ui8 side) const
{
return battleGetStacksIf([=](const CStack * s){
return s->alive() && s->attackerOwned == !side;
});
}
int CBattleInfoEssentials::battleGetMoatDmg() const
{
RETURN_IF_NOT_BATTLE(0);
auto town = getBattle()->town;
if(!town)
return 0;
return town->town->moatDamage;
}
const CGTownInstance * CBattleInfoEssentials::battleGetDefendedTown() const
{
RETURN_IF_NOT_BATTLE(nullptr);
if(!getBattle() || getBattle()->town == nullptr)
return nullptr;
return getBattle()->town;
}
BattlePerspective::BattlePerspective CBattleInfoEssentials::battleGetMySide() const
{
RETURN_IF_NOT_BATTLE(BattlePerspective::INVALID);
if(!player)
return BattlePerspective::ALL_KNOWING;
if(*player == getBattle()->sides[0].color)
return BattlePerspective::LEFT_SIDE;
if(*player == getBattle()->sides[1].color)
return BattlePerspective::RIGHT_SIDE;
logGlobal->errorStream() << "Cannot find player " << *player << " in battle!";
return BattlePerspective::INVALID;
}
const CStack * CBattleInfoEssentials::battleActiveStack() const
{
RETURN_IF_NOT_BATTLE(nullptr);
return battleGetStackByID(getBattle()->activeStack);
}
const CStack* CBattleInfoEssentials::battleGetStackByID(int ID, bool onlyAlive) const
{
RETURN_IF_NOT_BATTLE(nullptr);
for(auto s : battleGetAllStacks(true))
if(s->ID == ID && (!onlyAlive || s->alive()))
return s;
return nullptr;
}
bool CBattleInfoEssentials::battleDoWeKnowAbout(ui8 side) const
{
RETURN_IF_NOT_BATTLE(false);
auto p = battleGetMySide();
return p == BattlePerspective::ALL_KNOWING || p == side;
}
si8 CBattleInfoEssentials::battleTacticDist() const
{
RETURN_IF_NOT_BATTLE(0);
return getBattle()->tacticDistance;
}
si8 CBattleInfoEssentials::battleGetTacticsSide() const
{
RETURN_IF_NOT_BATTLE(-1);
return getBattle()->tacticsSide;
}
const CGHeroInstance * CBattleInfoEssentials::battleGetFightingHero(ui8 side) const
{
RETURN_IF_NOT_BATTLE(nullptr);
if(side > 1)
{
logGlobal->errorStream() << "FIXME: " << __FUNCTION__ << " wrong argument!";
return nullptr;
}
if(!battleDoWeKnowAbout(side))
{
logGlobal->errorStream() << "FIXME: " << __FUNCTION__ << " access check ";
return nullptr;
}
return getBattle()->sides[side].hero;
}
const CArmedInstance * CBattleInfoEssentials::battleGetArmyObject(ui8 side) const
{
RETURN_IF_NOT_BATTLE(nullptr);
if(side > 1)
{
logGlobal->errorStream() << "FIXME: " << __FUNCTION__ << " wrong argument!";
return nullptr;
}
if(!battleDoWeKnowAbout(side))
{
logGlobal->errorStream() << "FIXME: " << __FUNCTION__ << " access check ";
return nullptr;
}
return getBattle()->sides[side].armyObject;
}
InfoAboutHero CBattleInfoEssentials::battleGetHeroInfo( ui8 side ) const
{
auto hero = getBattle()->sides[side].hero;
if(!hero)
{
logGlobal->warnStream() << __FUNCTION__ << ": side " << (int)side << " does not have hero!";
return InfoAboutHero();
}
return InfoAboutHero(hero, battleDoWeKnowAbout(side));
}
int CBattleInfoEssentials::battleCastSpells(ui8 side) const
{
RETURN_IF_NOT_BATTLE(-1);
return getBattle()->sides[side].castSpellsCount;
}
const IBonusBearer * CBattleInfoEssentials::getBattleNode() const
{
return getBattle();
}
ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastSpell(PlayerColor player, ECastingMode::ECastingMode mode) const
{
RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
const ui8 side = playerToSide(player);
if(!battleDoWeKnowAbout(side))
{
logGlobal->warnStream() << "You can't check if enemy can cast given spell!";
return ESpellCastProblem::INVALID;
}
switch (mode)
{
case ECastingMode::HERO_CASTING:
{
if(battleTacticDist())
return ESpellCastProblem::ONGOING_TACTIC_PHASE;
if(battleCastSpells(side) > 0)
return ESpellCastProblem::ALREADY_CASTED_THIS_TURN;
auto hero = battleGetFightingHero(side);
if(!hero)
return ESpellCastProblem::NO_HERO_TO_CAST_SPELL;
if(!hero->getArt(ArtifactPosition::SPELLBOOK))
return ESpellCastProblem::NO_SPELLBOOK;
if(hero->hasBonusOfType(Bonus::BLOCK_ALL_MAGIC))
return ESpellCastProblem::MAGIC_IS_BLOCKED;
}
break;
default:
break;
}
return ESpellCastProblem::OK;
}
bool CBattleInfoEssentials::battleCanFlee(PlayerColor player) const
{
RETURN_IF_NOT_BATTLE(false);
ui8 mySide = playerToSide(player);
const CGHeroInstance *myHero = battleGetFightingHero(mySide);
//current player have no hero
if(!myHero)
return false;
//eg. one of heroes is wearing shakles of war
if(myHero->hasBonusOfType(Bonus::BATTLE_NO_FLEEING))
return false;
//we are besieged defender
if(mySide == BattleSide::DEFENDER && battleGetSiegeLevel())
{
auto town = battleGetDefendedTown();
if(!town->hasBuilt(BuildingID::ESCAPE_TUNNEL, ETownType::STRONGHOLD))
return false;
}
return true;
}
ui8 CBattleInfoEssentials::playerToSide(PlayerColor player) const
{
RETURN_IF_NOT_BATTLE(-1);
int ret = vstd::find_pos_if(getBattle()->sides, [=](const SideInBattle &side){ return side.color == player; });
if(ret < 0)
logGlobal->warnStream() << "Cannot find side for player " << player;
return ret;
}
ui8 CBattleInfoEssentials::battleGetSiegeLevel() const
{
RETURN_IF_NOT_BATTLE(0);
return getBattle()->town ? getBattle()->town->fortLevel() : CGTownInstance::NONE;
}
bool CBattleInfoEssentials::battleCanSurrender(PlayerColor player) const
{
RETURN_IF_NOT_BATTLE(false);
//conditions like for fleeing + enemy must have a hero
return battleCanFlee(player) && battleHasHero(!playerToSide(player));
}
bool CBattleInfoEssentials::battleHasHero(ui8 side) const
{
RETURN_IF_NOT_BATTLE(false);
assert(side < 2);
return getBattle()->sides[side].hero;
}
si8 CBattleInfoEssentials::battleGetWallState(int partOfWall) const
{
RETURN_IF_NOT_BATTLE(0);
if(getBattle()->town == nullptr || getBattle()->town->fortLevel() == CGTownInstance::NONE)
return EWallState::NONE;
assert(partOfWall >= 0 && partOfWall < EWallPart::PARTS_COUNT);
return getBattle()->si.wallState[partOfWall];
}
si8 CBattleInfoCallback::battleHasWallPenalty( const CStack * stack, BattleHex destHex ) const
{
return battleHasWallPenalty(stack, stack->position, destHex);
}
si8 CBattleInfoCallback::battleHasWallPenalty(const IBonusBearer *bonusBearer, BattleHex shooterPosition, BattleHex destHex) const
{
RETURN_IF_NOT_BATTLE(false);
if (!battleGetSiegeLevel() || bonusBearer->hasBonusOfType(Bonus::NO_WALL_PENALTY))
return false;
const int wallInStackLine = lineToWallHex(shooterPosition.getY());
const int wallInDestLine = lineToWallHex(destHex.getY());
const bool stackLeft = shooterPosition < wallInStackLine;
const bool destRight = destHex > wallInDestLine;
if (stackLeft && destRight) //shooting from outside to inside
{
int row = (shooterPosition + destHex) / (2 * GameConstants::BFIELD_WIDTH);
if (shooterPosition > destHex && ((destHex % GameConstants::BFIELD_WIDTH - shooterPosition % GameConstants::BFIELD_WIDTH) < 2)) //shooting up high
row -= 2;
const int wallPos = lineToWallHex(row);
if (!isWallPartPotentiallyAttackable(battleHexToWallPart(wallPos))) return true;
}
return false;
}
si8 CBattleInfoCallback::battleCanTeleportTo(const CStack * stack, BattleHex destHex, int telportLevel) const
{
RETURN_IF_NOT_BATTLE(false);
if (!getAccesibility(stack).accessible(destHex, stack))
return false;
if (battleGetSiegeLevel() && telportLevel < 2) //check for wall
return sameSideOfWall(stack->position, destHex);
return true;
}
std::set<BattleHex> CBattleInfoCallback::battleGetAttackedHexes(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos /*= BattleHex::INVALID*/) const
{
std::set<BattleHex> attackedHexes;
RETURN_IF_NOT_BATTLE(attackedHexes);
AttackableTiles at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
for (BattleHex tile : at.hostileCreaturePositions)
{
const CStack * st = battleGetStackByPos(tile, true);
if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
{
attackedHexes.insert(tile);
}
}
for (BattleHex tile : at.friendlyCreaturePositions)
{
if(battleGetStackByPos(tile, true)) //friendly stacks can also be damaged by Dragon Breath
{
attackedHexes.insert(tile);
}
}
return attackedHexes;
}
SpellID CBattleInfoCallback::battleGetRandomStackSpell(const CStack * stack, ERandomSpell mode) const
{
switch (mode)
{
case RANDOM_GENIE:
return getRandomBeneficialSpell(stack); //target
break;
case RANDOM_AIMED:
return getRandomCastedSpell(stack); //caster
break;
default:
logGlobal->errorStream() << "Incorrect mode of battleGetRandomSpell (" << mode <<")";
return SpellID::NONE;
}
}
const CStack* CBattleInfoCallback::battleGetStackByPos(BattleHex pos, bool onlyAlive) const
{
RETURN_IF_NOT_BATTLE(nullptr);
for(auto s : battleGetAllStacks(true))
if(vstd::contains(s->getHexes(), pos) && (!onlyAlive || s->alive()))
return s;
return nullptr;
}
void CBattleInfoCallback::battleGetStackQueue(std::vector<const CStack *> &out, const int howMany, const int turn /*= 0*/, int lastMoved /*= -1*/) const
{
RETURN_IF_NOT_BATTLE();
//let's define a huge lambda
auto takeStack = [&](std::vector<const CStack *> &st) -> const CStack*
{
const CStack *ret = nullptr;
unsigned i, //fastest stack
j=0; //fastest stack of the other side
for(i = 0; i < st.size(); i++)
if(st[i])
break;
//no stacks left
if(i == st.size())
return nullptr;
const CStack *fastest = st[i], *other = nullptr;
int bestSpeed = fastest->Speed(turn);
//FIXME: comparison between bool and integer. Logic does not makes sense either
if(fastest->attackerOwned != lastMoved)
{
ret = fastest;
}
else
{
for(j = i + 1; j < st.size(); j++)
{
if(!st[j]) continue;
if(st[j]->attackerOwned != lastMoved || st[j]->Speed(turn) != bestSpeed)
break;
}
if(j >= st.size())
{
ret = fastest;
}
else
{
other = st[j];
if(other->Speed(turn) != bestSpeed)
ret = fastest;
else
ret = other;
}
}
assert(ret);
if(ret == fastest)
st[i] = nullptr;
else
st[j] = nullptr;
lastMoved = ret->attackerOwned;
return ret;
};
//We'll split creatures with remaining movement to 4 buckets
// [0] - turrets/catapult,
// [1] - normal (unmoved) creatures, other war machines,
// [2] - waited cres that had morale,
// [3] - rest of waited cres
std::vector<const CStack *> phase[4];
int toMove = 0; //how many stacks still has move
const CStack *active = battleActiveStack();
//active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
if(!turn && active && active->willMove() && !active->waited())
{
out.push_back(active);
if(out.size() == howMany)
return;
}
auto allStacks = battleGetAllStacks(true);
if(!vstd::contains_if(allStacks, [](const CStack *stack) { return stack->willMove(100000); })) //little evil, but 100000 should be enough for all effects to disappear
{
//No stack will be able to move, battle is over.
out.clear();
return;
}
for(auto s : battleGetAllStacks(true))
{
if((turn <= 0 && !s->willMove()) //we are considering current round and stack won't move
|| (turn > 0 && !s->canMove(turn)) //stack won't be able to move in later rounds
|| (turn <= 0 && s == active && out.size() && s == out.front())) //it's active stack already added at the beginning of queue
{
continue;
}
int p = -1; //in which phase this tack will move?
if(turn <= 0 && s->waited()) //consider waiting state only for ongoing round
{
if(vstd::contains(s->state, EBattleStackState::HAD_MORALE))
p = 2;
else
p = 3;
}
else if(s->getCreature()->idNumber == CreatureID::CATAPULT || s->getCreature()->idNumber == CreatureID::ARROW_TOWERS) //catapult and turrets are first
{
p = 0;
}
else
{
p = 1;
}
phase[p].push_back(s);
toMove++;
}
for(int i = 0; i < 4; i++)
boost::sort(phase[i], CMP_stack(i, turn > 0 ? turn : 0));
for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
out.push_back(phase[0][i]);
if(out.size() == howMany)
return;
if(lastMoved == -1)
{
if(active)
{
//FIXME: both branches contain same code!!!
if(out.size() && out.front() == active)
lastMoved = active->attackerOwned;
else
lastMoved = active->attackerOwned;
}
else
{
lastMoved = 0;
}
}
int pi = 1;
while(out.size() < howMany)
{
const CStack *hlp = takeStack(phase[pi]);
if(!hlp)
{
pi++;
if(pi > 3)
{
//if(turn != 2)
battleGetStackQueue(out, howMany, turn + 1, lastMoved);
return;
}
}
else
{
out.push_back(hlp);
}
}
}
void CBattleInfoCallback::battleGetStackCountOutsideHexes(bool *ac) const
{
RETURN_IF_NOT_BATTLE();
auto accessibility = getAccesibility();
for(int i = 0; i < accessibility.size(); i++)
ac[i] = (accessibility[i] == EAccessibility::ACCESSIBLE);
}
std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const CStack * stack, bool addOccupiable, std::vector<BattleHex> * attackable) const
{
std::vector<BattleHex> ret;
RETURN_IF_NOT_BATTLE(ret);
if(!stack->position.isValid()) //turrets
return ret;
auto reachability = getReachability(stack);
for (int i = 0; i < GameConstants::BFIELD_SIZE; ++i)
{
// If obstacles or other stacks makes movement impossible, it can't be helped.
if(!reachability.isReachable(i))
continue;
if(battleTacticDist() && battleGetTacticsSide() == !stack->attackerOwned)
{
//Stack has to perform tactic-phase movement -> can enter any reachable tile within given range
if(!isInTacticRange(i))
continue;
}
else
{
//Not tactics phase -> destination must be reachable and within stack range.
if(reachability.distances[i] > stack->Speed(0, true))
continue;
}
ret.push_back(i);
if(addOccupiable && stack->doubleWide())
{
//If two-hex stack can stand on hex i then obviously it can occupy its second hex from that position
ret.push_back(stack->occupiedHex(i));
}
}
if(attackable)
{
auto meleeAttackable = [&](BattleHex hex) -> bool
{
// Return true if given hex has at least one available neighbour.
// Available hexes are already present in ret vector.
auto availableNeighbor = boost::find_if(ret, [=] (BattleHex availableHex)
{ return BattleHex::mutualPosition(hex, availableHex) >= 0; });
return availableNeighbor != ret.end();
};
for(const CStack * otherSt : battleAliveStacks(stack->attackerOwned))
{
if(!otherSt->isValidTarget(false))
continue;
std::vector<BattleHex> occupied = otherSt->getHexes();
if(battleCanShoot(stack, otherSt->position))
{
attackable->insert(attackable->end(), occupied.begin(), occupied.end());
continue;
}
for(BattleHex he : occupied)
{
if(meleeAttackable(he))
attackable->push_back(he);
}
}
}
//adding occupiable likely adds duplicates to ret -> clean it up
boost::sort(ret);
ret.erase(boost::unique(ret).end(), ret.end());
return ret;
}
bool CBattleInfoCallback::battleCanAttack(const CStack * stack, const CStack * target, BattleHex dest) const
{
RETURN_IF_NOT_BATTLE(false);
if(battleTacticDist())
return false;
if (!stack || !target)
return false;
if (stack->owner == target->owner)
return false;
auto &id = stack->getCreature()->idNumber;
if (id == CreatureID::FIRST_AID_TENT || id == CreatureID::CATAPULT)
return false;
if (!target->alive())
return false;
return true;
}
bool CBattleInfoCallback::battleCanShoot(const CStack * stack, BattleHex dest) const
{
RETURN_IF_NOT_BATTLE(false);
if(battleTacticDist()) //no shooting during tactics
return false;
const CStack *dst = battleGetStackByPos(dest);
if(!stack || !dst)
return false;
if(stack->hasBonusOfType(Bonus::FORGETFULL)) //forgetfulness
return false;
if(stack->getCreature()->idNumber == CreatureID::CATAPULT && dst) //catapult cannot attack creatures
return false;
//const CGHeroInstance * stackHero = battleGetOwner(stack);
if(stack->hasBonusOfType(Bonus::SHOOTER)//it's shooter
&& stack->owner != dst->owner
&& dst->alive()
&& (!battleIsStackBlocked(stack) || stack->hasBonusOfType(Bonus::FREE_SHOOTING))
&& stack->shots
)
return true;
return false;
}
TDmgRange CBattleInfoCallback::calculateDmgRange(const CStack* attacker, const CStack* defender, bool shooting,
ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg) const
{
return calculateDmgRange(attacker, defender, attacker->count, shooting, charge, lucky, unlucky, deathBlow, ballistaDoubleDmg);
}
TDmgRange CBattleInfoCallback::calculateDmgRange(const BattleAttackInfo &info) const
{
auto battleBonusValue = [&](const IBonusBearer * bearer, CSelector selector) -> int
{
auto noLimit = Selector::effectRange(Bonus::NO_LIMIT);
auto limitMatches = info.shooting
? Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT)
: Selector::effectRange(Bonus::ONLY_MELEE_FIGHT);
//any regular bonuses or just ones for melee/ranged
return bearer->getBonuses(selector, noLimit.Or(limitMatches))->totalValue();
};
double additiveBonus = 1.0, multBonus = 1.0,
minDmg = info.attackerBonuses->getMinDamage() * info.attackerCount,//TODO: ONLY_MELEE_FIGHT / ONLY_DISTANCE_FIGHT
maxDmg = info.attackerBonuses->getMaxDamage() * info.attackerCount;
const CCreature *attackerType = info.attacker->getCreature(),
*defenderType = info.defender->getCreature();
if(attackerType->idNumber == CreatureID::ARROW_TOWERS)
{
SiegeStuffThatShouldBeMovedToHandlers::retreiveTurretDamageRange(battleGetDefendedTown(), info.attacker, minDmg, maxDmg);
}
if(info.attackerBonuses->hasBonusOfType(Bonus::SIEGE_WEAPON) && attackerType->idNumber != CreatureID::ARROW_TOWERS) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
{ //minDmg and maxDmg are multiplied by hero attack + 1
auto retreiveHeroPrimSkill = [&](int skill) -> int
{
const Bonus *b = info.attackerBonuses->getBonus(Selector::sourceTypeSel(Bonus::HERO_BASE_SKILL).And(Selector::typeSubtype(Bonus::PRIMARY_SKILL, skill)));
return b ? b->val : 0; //if there is no hero or no info on his primary skill, return 0
};
minDmg *= retreiveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
maxDmg *= retreiveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
}
int attackDefenceDifference = 0;
double multAttackReduction = (100 - battleBonusValue (info.attackerBonuses, Selector::type(Bonus::GENERAL_ATTACK_REDUCTION))) / 100.0;
attackDefenceDifference += battleBonusValue (info.attackerBonuses, Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK)) * multAttackReduction;
double multDefenceReduction = (100 - battleBonusValue (info.attackerBonuses, Selector::type(Bonus::ENEMY_DEFENCE_REDUCTION))) / 100.0;
attackDefenceDifference -= info.defenderBonuses->Defense() * multDefenceReduction;
if(const Bonus *slayerEffect = info.attackerBonuses->getEffect(SpellID::SLAYER)) //slayer handling //TODO: apply only ONLY_MELEE_FIGHT / DISTANCE_FIGHT?
{
std::vector<int> affectedIds;
int spLevel = slayerEffect->val;
for(int g = 0; g < VLC->creh->creatures.size(); ++g)
{
for(const Bonus *b : VLC->creh->creatures[g]->getBonusList())
{
if ( (b->type == Bonus::KING3 && spLevel >= 3) || //expert
(b->type == Bonus::KING2 && spLevel >= 2) || //adv +
(b->type == Bonus::KING1 && spLevel >= 0) ) //none or basic +
{
affectedIds.push_back(g);
break;
}
}
}
for(auto & affectedId : affectedIds)
{
if(defenderType->idNumber == affectedId)
{
attackDefenceDifference += SpellID(SpellID::SLAYER).toSpell()->getPower(spLevel);
break;
}
}
}
//bonus from attack/defense skills
if(attackDefenceDifference < 0) //decreasing dmg
{
const double dec = std::min(0.025 * (-attackDefenceDifference), 0.7);
multBonus *= 1.0 - dec;
}
else //increasing dmg
{
const double inc = std::min(0.05 * attackDefenceDifference, 4.0);
additiveBonus += inc;
}
//applying jousting bonus
if( info.attackerBonuses->hasBonusOfType(Bonus::JOUSTING) && !info.defenderBonuses->hasBonusOfType(Bonus::CHARGE_IMMUNITY) )
additiveBonus += info.chargedFields * 0.05;
//handling secondary abilities and artifacts giving premies to them
if(info.shooting)
additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARCHERY) / 100.0;
else
additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::OFFENCE) / 100.0;
if(info.defenderBonuses)
multBonus *= (std::max(0, 100 - info.defenderBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARMORER))) / 100.0;
//handling hate effect
additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::HATE, defenderType->idNumber.toEnum()) / 100.;
//luck bonus
if (info.luckyHit)
{
additiveBonus += 1.0;
}
//unlucky hit, used only if negative luck is enabled
if (info.unluckyHit)
{
additiveBonus -= 0.5; // FIXME: how bad (and luck in general) should work with following bonuses?
}
//ballista double dmg
if(info.ballistaDoubleDamage)
{
additiveBonus += 1.0;
}
if (info.deathBlow) //Dread Knight and many WoGified creatures
{
additiveBonus += 1.0;
}
//handling spell effects
if(!info.shooting) //eg. shield
{
multBonus *= (100 - info.defenderBonuses->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0;
}
else if(info.shooting) //eg. air shield
{
multBonus *= (100 - info.defenderBonuses->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0;
}
TBonusListPtr curseEffects = info.attackerBonuses->getBonuses(Selector::type(Bonus::ALWAYS_MINIMUM_DAMAGE));
TBonusListPtr blessEffects = info.attackerBonuses->getBonuses(Selector::type(Bonus::ALWAYS_MAXIMUM_DAMAGE));
int curseBlessAdditiveModifier = blessEffects->totalValue() - curseEffects->totalValue();
double curseMultiplicativePenalty = curseEffects->size() ? (*std::max_element(curseEffects->begin(), curseEffects->end(), &Bonus::compareByAdditionalInfo))->additionalInfo : 0;
if(curseMultiplicativePenalty) //curse handling (partial, the rest is below)
{
multBonus *= 1.0 - curseMultiplicativePenalty/100;
}
auto isAdvancedAirShield = [](const Bonus *bonus)
{
return bonus->source == Bonus::SPELL_EFFECT
&& bonus->sid == SpellID::AIR_SHIELD
&& bonus->val >= SecSkillLevel::ADVANCED;
};
//wall / distance penalty + advanced air shield
const bool distPenalty = !info.attackerBonuses->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY) && battleHasDistancePenalty(info.attackerBonuses, info.attackerPosition, info.defenderPosition);
const bool obstaclePenalty = battleHasWallPenalty(info.attackerBonuses, info.attackerPosition, info.defenderPosition);
if (info.shooting)
{
if (distPenalty || info.defenderBonuses->hasBonus(isAdvancedAirShield))
{
multBonus *= 0.5;
}
if (obstaclePenalty)
{
multBonus *= 0.5; //cumulative
}
}
if(!info.shooting && info.attackerBonuses->hasBonusOfType(Bonus::SHOOTER) && !info.attackerBonuses->hasBonusOfType(Bonus::NO_MELEE_PENALTY))
{
multBonus *= 0.5;
}
// TODO attack on petrified unit 50%
// psychic elementals versus mind immune units 50%
// blinded unit retaliates
minDmg *= additiveBonus * multBonus;
maxDmg *= additiveBonus * multBonus;
TDmgRange returnedVal;
if(curseEffects->size()) //curse handling (rest)
{
minDmg += curseBlessAdditiveModifier;
returnedVal = std::make_pair(int(minDmg), int(minDmg));
}
else if(blessEffects->size()) //bless handling
{
maxDmg += curseBlessAdditiveModifier;
returnedVal = std::make_pair(int(maxDmg), int(maxDmg));
}
else
{
returnedVal = std::make_pair(int(minDmg), int(maxDmg));
}
//damage cannot be less than 1
vstd::amax(returnedVal.first, 1);
vstd::amax(returnedVal.second, 1);
return returnedVal;
}
TDmgRange CBattleInfoCallback::calculateDmgRange( const CStack* attacker, const CStack* defender, TQuantity attackerCount,
bool shooting, ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg ) const
{
BattleAttackInfo bai(attacker, defender, shooting);
bai.attackerCount = attackerCount;
bai.chargedFields = charge;
bai.luckyHit = lucky;
bai.unluckyHit = unlucky;
bai.deathBlow = deathBlow;
bai.ballistaDoubleDamage = ballistaDoubleDmg;
return calculateDmgRange(bai);
}
TDmgRange CBattleInfoCallback::battleEstimateDamage(const CStack * attacker, const CStack * defender, TDmgRange * retaliationDmg) const
{
RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
const bool shooting = battleCanShoot(attacker, defender->position);
const BattleAttackInfo bai(attacker, defender, shooting);
return battleEstimateDamage(bai, retaliationDmg);
}
std::pair<ui32, ui32> CBattleInfoCallback::battleEstimateDamage(const BattleAttackInfo &bai, std::pair<ui32, ui32> * retaliationDmg /*= nullptr*/) const
{
RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
//const bool shooting = battleCanShoot(bai.attacker, bai.defenderPosition); //TODO handle bonus bearer
//const ui8 mySide = !attacker->attackerOwned;
TDmgRange ret = calculateDmgRange(bai);
if(retaliationDmg)
{
if(bai.shooting)
{
retaliationDmg->first = retaliationDmg->second = 0;
}
else
{
ui32 TDmgRange::* pairElems[] = {&TDmgRange::first, &TDmgRange::second};
for (int i=0; i<2; ++i)
{
BattleStackAttacked bsa;
bsa.damageAmount = ret.*pairElems[i];
bai.defender->prepareAttacked(bsa, gs->getRandomGenerator(), bai.defenderCount);
auto retaliationAttack = bai.reverse();
retaliationAttack.attackerCount = bsa.newAmount;
retaliationDmg->*pairElems[!i] = calculateDmgRange(retaliationAttack).*pairElems[!i];
}
}
}
return ret;
}
std::shared_ptr<const CObstacleInstance> CBattleInfoCallback::battleGetObstacleOnPos(BattleHex tile, bool onlyBlocking /*= true*/) const
{
RETURN_IF_NOT_BATTLE(std::shared_ptr<const CObstacleInstance>());
for(auto &obs : battleGetAllObstacles())
{
if(vstd::contains(obs->getBlockedTiles(), tile)
|| (!onlyBlocking && vstd::contains(obs->getAffectedTiles(), tile)))
{
return obs;
}
}
return std::shared_ptr<const CObstacleInstance>();
}
AccessibilityInfo CBattleInfoCallback::getAccesibility() const
{
AccessibilityInfo ret;
ret.fill(EAccessibility::ACCESSIBLE);
//removing accessibility for side columns of hexes
for(int y = 0; y < GameConstants::BFIELD_HEIGHT; y++)
{
ret[BattleHex(GameConstants::BFIELD_WIDTH - 1, y)] = EAccessibility::SIDE_COLUMN;
ret[BattleHex(0, y)] = EAccessibility::SIDE_COLUMN;
}
//gate -> should be before stacks
if(battleGetSiegeLevel() > 0 && battleGetWallState(EWallPart::GATE) != EWallState::DESTROYED)
{
ret[95] = ret[96] = EAccessibility::GATE; //block gate's hexes
}
//tiles occupied by standing stacks
for(auto stack : battleAliveStacks())
{
for(auto hex : stack->getHexes())
if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
ret[hex] = EAccessibility::ALIVE_STACK;
}
//obstacles
for(const auto &obst : battleGetAllObstacles())
{
for(auto hex : obst->getBlockedTiles())
ret[hex] = EAccessibility::OBSTACLE;
}
//walls
if(battleGetSiegeLevel() > 0)
{
static const int permanentlyLocked[] = {12, 45, 78, 112, 147, 165};
for(auto hex : permanentlyLocked)
ret[hex] = EAccessibility::UNAVAILABLE;
//TODO likely duplicated logic
static const std::pair<int, BattleHex> lockedIfNotDestroyed[] = //(which part of wall, which hex is blocked if this part of wall is not destroyed
{std::make_pair(2, BattleHex(182)), std::make_pair(3, BattleHex(130)),
std::make_pair(4, BattleHex(62)), std::make_pair(5, BattleHex(29))};
for(auto & elem : lockedIfNotDestroyed)
{
if(battleGetWallState(elem.first) != EWallState::DESTROYED)
ret[elem.second] = EAccessibility::DESTRUCTIBLE_WALL;
}
}
return ret;
}
AccessibilityInfo CBattleInfoCallback::getAccesibility(const CStack *stack) const
{
return getAccesibility(stack->getHexes());
}
AccessibilityInfo CBattleInfoCallback::getAccesibility(const std::vector<BattleHex> &accessibleHexes) const
{
auto ret = getAccesibility();
for(auto hex : accessibleHexes)
if(hex.isValid())
ret[hex] = EAccessibility::ACCESSIBLE;
return ret;
}
ReachabilityInfo CBattleInfoCallback::makeBFS(const AccessibilityInfo &accessibility, const ReachabilityInfo::Parameters ¶ms) const
{
ReachabilityInfo ret;
ret.accessibility = accessibility;
ret.params = params;
ret.predecessors.fill(BattleHex::INVALID);
ret.distances.fill(ReachabilityInfo::INFINITE_DIST);
if(!params.startPosition.isValid()) //if got call for arrow turrets
return ret;
const std::set<BattleHex> quicksands = getStoppers(params.perspective);
//const bool twoHexCreature = params.doubleWide;
std::queue<BattleHex> hexq; //bfs queue
//first element
hexq.push(params.startPosition);
ret.distances[params.startPosition] = 0;
while(!hexq.empty()) //bfs loop
{
const BattleHex curHex = hexq.front();
hexq.pop();
//walking stack can't step past the quicksands
//TODO what if second hex of two-hex creature enters quicksand
if(curHex != params.startPosition && vstd::contains(quicksands, curHex))
continue;
const int costToNeighbour = ret.distances[curHex] + 1;
for(BattleHex neighbour : curHex.neighbouringTiles())
{
const bool accessible = accessibility.accessible(neighbour, params.doubleWide, params.attackerOwned);
const int costFoundSoFar = ret.distances[neighbour];
if(accessible && costToNeighbour < costFoundSoFar)
{
hexq.push(neighbour);
ret.distances[neighbour] = costToNeighbour;
ret.predecessors[neighbour] = curHex;
}
}
}
return ret;
}
ReachabilityInfo CBattleInfoCallback::makeBFS(const CStack *stack) const
{
return makeBFS(getAccesibility(stack), ReachabilityInfo::Parameters(stack));
}
std::set<BattleHex> CBattleInfoCallback::getStoppers(BattlePerspective::BattlePerspective whichSidePerspective) const
{
std::set<BattleHex> ret;
RETURN_IF_NOT_BATTLE(ret);
for(auto &oi : battleGetAllObstacles(whichSidePerspective))
{
if(battleIsObstacleVisibleForSide(*oi, whichSidePerspective))
{
range::copy(oi->getStoppingTile(), vstd::set_inserter(ret));
}
}
return ret;
}
std::pair<const CStack *, BattleHex> CBattleInfoCallback::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
{
auto reachability = getReachability(closest);
auto avHexes = battleGetAvailableHexes(closest, false);
// I hate std::pairs with their undescriptive member names first / second
struct DistStack
{
int distanceToPred;
BattleHex destination;
const CStack *stack;
};
std::vector<DistStack> stackPairs;
std::vector<const CStack *> possibleStacks = battleGetStacksIf([=](const CStack * s)
{
return s != closest && s->alive() && (boost::logic::indeterminate(attackerOwned) || s->attackerOwned == attackerOwned);
}, false);
for(const CStack * st : possibleStacks)
for(BattleHex hex : avHexes)
if(CStack::isMeleeAttackPossible(closest, st, hex))
{
DistStack hlp = {reachability.distances[st->position], hex, st};
stackPairs.push_back(hlp);
}
if (stackPairs.size())
{
auto comparator = [](DistStack lhs, DistStack rhs) { return lhs.distanceToPred < rhs.distanceToPred; };
auto minimal = boost::min_element(stackPairs, comparator);
return std::make_pair(minimal->stack, minimal->destination);
}
else
return std::make_pair<const CStack * , BattleHex>(nullptr, BattleHex::INVALID);
}
si8 CBattleInfoCallback::battleGetTacticDist() const
{
RETURN_IF_NOT_BATTLE(0);
//TODO get rid of this method
if(battleDoWeKnowAbout(battleGetTacticsSide()))
return battleTacticDist();
return 0;
}
bool CBattleInfoCallback::isInTacticRange(BattleHex dest) const
{
RETURN_IF_NOT_BATTLE(false);
auto side = battleGetTacticsSide();
auto dist = battleGetTacticDist();
return ((!side && dest.getX() > 0 && dest.getX() <= dist)
|| (side && dest.getX() < GameConstants::BFIELD_WIDTH - 1 && dest.getX() >= GameConstants::BFIELD_WIDTH - dist - 1));
}
ReachabilityInfo CBattleInfoCallback::getReachability(const CStack *stack) const
{
ReachabilityInfo::Parameters params(stack);
if(!battleDoWeKnowAbout(!stack->attackerOwned))
{
//Stack is held by enemy, we can't use his perspective to check for reachability.
// Happens ie. when hovering enemy stack for its range. The arg could be set properly, but it's easier to fix it here.
params.perspective = battleGetMySide();
}
return getReachability(params);
}
ReachabilityInfo CBattleInfoCallback::getReachability(const ReachabilityInfo::Parameters ¶ms) const
{
if(params.flying)
return getFlyingReachability(params);
else
return makeBFS(getAccesibility(params.knownAccessible), params);
}
ReachabilityInfo CBattleInfoCallback::getFlyingReachability(const ReachabilityInfo::Parameters ¶ms) const
{
ReachabilityInfo ret;
ret.accessibility = getAccesibility(params.knownAccessible);
for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
{
if(ret.accessibility.accessible(i, params.doubleWide, params.attackerOwned))
{
ret.predecessors[i] = params.startPosition;
ret.distances[i] = BattleHex::getDistance(params.startPosition, i);
}
}
return ret;
}
AttackableTiles CBattleInfoCallback::getPotentiallyAttackableHexes (const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos) const
{
//does not return hex attacked directly
//TODO: apply rotation to two-hex attackers
bool isAttacker = attacker->attackerOwned;
AttackableTiles at;
RETURN_IF_NOT_BATTLE(at);
const int WN = GameConstants::BFIELD_WIDTH;
ui16 hex = (attackerPos != BattleHex::INVALID) ? attackerPos.hex : attacker->position.hex; //real or hypothetical (cursor) position
//FIXME: dragons or cerbers can rotate before attack, making their base hex different (#1124)
bool reverse = isToReverse (hex, destinationTile, isAttacker, attacker->doubleWide(), isAttacker);
if (reverse)
{
hex = attacker->occupiedHex(hex); //the other hex stack stands on
}
if (attacker->hasBonusOfType(Bonus::ATTACKS_ALL_ADJACENT))
{
boost::copy (attacker->getSurroundingHexes (attackerPos), vstd::set_inserter (at.hostileCreaturePositions));
}
if (attacker->hasBonusOfType(Bonus::THREE_HEADED_ATTACK))
{
std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
for (BattleHex tile : hexes)
{
if ((BattleHex::mutualPosition(tile, destinationTile) > -1 && BattleHex::mutualPosition (tile, hex) > -1)) //adjacent both to attacker's head and attacked tile
{
const CStack * st = battleGetStackByPos(tile, true);
if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
{
at.hostileCreaturePositions.insert(tile);
}
}
}
}
if (attacker->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH) && BattleHex::mutualPosition (destinationTile.hex, hex) > -1) //only adjacent hexes are subject of dragon breath calculation
{
std::vector<BattleHex> hexes; //only one, in fact
int pseudoVector = destinationTile.hex - hex;
switch (pseudoVector)
{
case 1:
case -1:
BattleHex::checkAndPush (destinationTile.hex + pseudoVector, hexes);
break;
case WN: //17 //left-down or right-down
case -WN: //-17 //left-up or right-up
case WN + 1: //18 //right-down
case -WN + 1: //-16 //right-up
BattleHex::checkAndPush (destinationTile.hex + pseudoVector + (((hex/WN)%2) ? 1 : -1 ), hexes);
break;
case WN-1: //16 //left-down
case -WN-1: //-18 //left-up
BattleHex::checkAndPush (destinationTile.hex + pseudoVector + (((hex/WN)%2) ? 1 : 0), hexes);
break;
}
for (BattleHex tile : hexes)
{
//friendly stacks can also be damaged by Dragon Breath
if (battleGetStackByPos (tile, true))
at.friendlyCreaturePositions.insert (tile);
}
}
return at;
}
std::set<const CStack*> CBattleInfoCallback::getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos /*= BattleHex::INVALID*/) const
{
std::set<const CStack*> attackedCres;
RETURN_IF_NOT_BATTLE(attackedCres);
AttackableTiles at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
for (BattleHex tile : at.hostileCreaturePositions) //all around & three-headed attack
{
const CStack * st = battleGetStackByPos(tile, true);
if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
{
attackedCres.insert(st);
}
}
for (BattleHex tile : at.friendlyCreaturePositions)
{
const CStack * st = battleGetStackByPos(tile, true);
if(st) //friendly stacks can also be damaged by Dragon Breath
{
attackedCres.insert(st);
}
}
return attackedCres;
}
//TODO: this should apply also to mechanics and cursor interface
bool CBattleInfoCallback::isToReverseHlp (BattleHex hexFrom, BattleHex hexTo, bool curDir) const
{
int fromX = hexFrom.getX();
int fromY = hexFrom.getY();
int toX = hexTo.getX();
int toY = hexTo.getY();
if (curDir) // attacker, facing right
{
if (fromX < toX)
return false;
if (fromX > toX)
return true;
if (fromY % 2 == 0 && toY % 2 == 1)
return true;
return false;
}
else // defender, facing left
{
if(fromX < toX)
return true;
if(fromX > toX)
return false;
if (fromY % 2 == 1 && toY % 2 == 0)
return true;
return false;
}
}
//TODO: this should apply also to mechanics and cursor interface
bool CBattleInfoCallback::isToReverse (BattleHex hexFrom, BattleHex hexTo, bool curDir, bool toDoubleWide, bool toDir) const
{
if (hexTo < 0 || hexFrom < 0) //turret
return false;
if (toDoubleWide)
{
if (isToReverseHlp (hexFrom, hexTo, curDir))
{
if (toDir)
return isToReverseHlp (hexFrom, hexTo-1, curDir);
else
return isToReverseHlp (hexFrom, hexTo+1, curDir);
}
return false;
}
else
{
return isToReverseHlp(hexFrom, hexTo, curDir);
}
}
ReachabilityInfo::TDistances CBattleInfoCallback::battleGetDistances(const CStack * stack, BattleHex hex /*= BattleHex::INVALID*/, BattleHex * predecessors /*= nullptr*/) const
{
ReachabilityInfo::TDistances ret;
ret.fill(-1);
RETURN_IF_NOT_BATTLE(ret);
ReachabilityInfo::Parameters params(stack);
params.perspective = battleGetMySide();
params.startPosition = hex.isValid() ? hex : stack->position;
auto reachability = getReachability(params);
boost::copy(reachability.distances, ret.begin());
if(predecessors)
for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
predecessors[i] = reachability.predecessors[i];
return ret;
}
si8 CBattleInfoCallback::battleHasDistancePenalty(const CStack * stack, BattleHex destHex) const
{
return battleHasDistancePenalty(stack, stack->position, destHex);
}
si8 CBattleInfoCallback::battleHasDistancePenalty(const IBonusBearer *bonusBearer, BattleHex shooterPosition, BattleHex destHex) const
{
RETURN_IF_NOT_BATTLE(false);
if(bonusBearer->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY))
return false;
if(const CStack * dstStack = battleGetStackByPos(destHex, false))
{
//If any hex of target creature is within range, there is no penalty
for(auto hex : dstStack->getHexes())
if(BattleHex::getDistance(shooterPosition, hex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
return false;
//TODO what about two-hex shooters?
}
else
{
if (BattleHex::getDistance(shooterPosition, destHex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
return false;
}
return true;
}
BattleHex CBattleInfoCallback::wallPartToBattleHex(EWallPart::EWallPart part) const
{
RETURN_IF_NOT_BATTLE(BattleHex::INVALID);
return WallPartToHex(part);
}
EWallPart::EWallPart CBattleInfoCallback::battleHexToWallPart(BattleHex hex) const
{
RETURN_IF_NOT_BATTLE(EWallPart::INVALID);
return hexToWallPart(hex);
}
bool CBattleInfoCallback::isWallPartPotentiallyAttackable(EWallPart::EWallPart wallPart) const
{
RETURN_IF_NOT_BATTLE(false);
return wallPart != EWallPart::INDESTRUCTIBLE_PART && wallPart != EWallPart::INDESTRUCTIBLE_PART_OF_GATE &&
wallPart != EWallPart::INVALID;
}
std::vector<BattleHex> CBattleInfoCallback::getAttackableBattleHexes() const
{
std::vector<BattleHex> attackableBattleHexes;
RETURN_IF_NOT_BATTLE(attackableBattleHexes);
for(auto & wallPartPair : wallParts)
{
if(isWallPartPotentiallyAttackable(wallPartPair.second))
{
auto wallState = static_cast<EWallState::EWallState>(battleGetWallState(static_cast<int>(wallPartPair.second)));
if(wallState == EWallState::INTACT || wallState == EWallState::DAMAGED)
{
attackableBattleHexes.push_back(BattleHex(wallPartPair.first));
}
}
}
return attackableBattleHexes;
}
ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastThisSpell(const ISpellCaster * caster, const CSpell * spell, ECastingMode::ECastingMode mode) const
{
RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
if(caster == nullptr)
{
logGlobal->errorStream() << "CBattleInfoCallback::battleCanCastThisSpell: no spellcaster.";
return ESpellCastProblem::INVALID;
}
const PlayerColor player = caster->getOwner();
const ui8 side = playerToSide(player);
if(!battleDoWeKnowAbout(side))
return ESpellCastProblem::INVALID;
ESpellCastProblem::ESpellCastProblem genProblem = battleCanCastSpell(player, mode);
if(genProblem != ESpellCastProblem::OK)
return genProblem;
switch(mode)
{
case ECastingMode::HERO_CASTING:
{
const CGHeroInstance * castingHero = dynamic_cast<const CGHeroInstance *>(caster);//todo: unify hero|creature spell cost
assert(castingHero);
if(!castingHero->canCastThisSpell(spell))
return ESpellCastProblem::HERO_DOESNT_KNOW_SPELL;
if(castingHero->mana < battleGetSpellCost(spell, castingHero)) //not enough mana
return ESpellCastProblem::NOT_ENOUGH_MANA;
}
break;
}
if(!spell->combatSpell)
return ESpellCastProblem::ADVMAP_SPELL_INSTEAD_OF_BATTLE_SPELL;
const ESpellCastProblem::ESpellCastProblem specificProblem = spell->canBeCast(this, player);
if(specificProblem != ESpellCastProblem::OK)
return specificProblem;
if(spell->isNegative() || spell->hasEffects())
{
bool allStacksImmune = true;
//we are interested only in enemy stacks when casting offensive spells
//TODO: should hero be able to cast non-smart negative spell if all enemy stacks are immune?
auto stacks = spell->isNegative() ? battleAliveStacks(!side) : battleAliveStacks();
for(auto stack : stacks)
{
if(ESpellCastProblem::OK == spell->isImmuneByStack(caster, stack))
{
allStacksImmune = false;
break;
}
}
if(allStacksImmune)
return ESpellCastProblem::NO_APPROPRIATE_TARGET;
}
if(battleMaxSpellLevel(side) < spell->level) //effect like Recanter's Cloak or Orb of Inhibition
return ESpellCastProblem::SPELL_LEVEL_LIMIT_EXCEEDED;
//checking if there exists an appropriate target
switch(spell->getTargetType())
{
case CSpell::CREATURE:
if(mode == ECastingMode::HERO_CASTING)
{
const CSpell::TargetInfo ti(spell, caster->getSpellSchoolLevel(spell));
bool targetExists = false;
for(const CStack * stack : battleGetAllStacks()) //dead stacks will be immune anyway
{
bool immune = ESpellCastProblem::OK != spell->isImmuneByStack(caster, stack);
bool casterStack = stack->owner == caster->getOwner();
if(!immune)
{
switch (spell->positiveness)
{
case CSpell::POSITIVE:
if(casterStack || !ti.smart)
{
targetExists = true;
break;
}
break;
case CSpell::NEUTRAL:
targetExists = true;
break;
case CSpell::NEGATIVE:
if(!casterStack || !ti.smart)
{
targetExists = true;
break;
}
break;
}
}
}
if(!targetExists)
{
return ESpellCastProblem::NO_APPROPRIATE_TARGET;
}
}
break;
case CSpell::OBSTACLE:
break;
}
return ESpellCastProblem::OK;
}
std::vector<BattleHex> CBattleInfoCallback::battleGetPossibleTargets(PlayerColor player, const CSpell *spell) const
{
std::vector<BattleHex> ret;
RETURN_IF_NOT_BATTLE(ret);
switch(spell->getTargetType())
{
case CSpell::CREATURE:
{
const CGHeroInstance * caster = battleGetFightingHero(playerToSide(player)); //TODO
const CSpell::TargetInfo ti(spell, caster->getSpellSchoolLevel(spell));
for(const CStack * stack : battleAliveStacks())
{
bool immune = ESpellCastProblem::OK != spell->isImmuneByStack(caster, stack);
bool casterStack = stack->owner == caster->getOwner();
if(!immune)
switch (spell->positiveness)
{
case CSpell::POSITIVE:
if(casterStack || ti.smart)
ret.push_back(stack->position);
break;
case CSpell::NEUTRAL:
ret.push_back(stack->position);
break;
case CSpell::NEGATIVE:
if(!casterStack || ti.smart)
ret.push_back(stack->position);
break;
}
}
}
break;
default:
logGlobal->errorStream() << "FIXME " << __FUNCTION__ << " doesn't work with target type " << spell->getTargetType();
}
return ret;
}
ui32 CBattleInfoCallback::battleGetSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
{
RETURN_IF_NOT_BATTLE(-1);
//TODO should be replaced using bonus system facilities (propagation onto battle node)
ui32 ret = caster->getSpellCost(sp);
//checking for friendly stacks reducing cost of the spell and
//enemy stacks increasing it
si32 manaReduction = 0;
si32 manaIncrease = 0;
for(auto stack : battleAliveStacks())
{
if(stack->owner == caster->tempOwner && stack->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY) )
{
vstd::amax(manaReduction, stack->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
}
if( stack->owner != caster->tempOwner && stack->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY) )
{
vstd::amax(manaIncrease, stack->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
}
}
return ret - manaReduction + manaIncrease;
}
ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastThisSpellHere(const ISpellCaster * caster, const CSpell * spell, ECastingMode::ECastingMode mode, BattleHex dest) const
{
RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
if(caster == nullptr)
{
logGlobal->errorStream() << "CBattleInfoCallback::battleCanCastThisSpellHere: no spellcaster.";
return ESpellCastProblem::INVALID;
}
const PlayerColor player = caster->getOwner();
ESpellCastProblem::ESpellCastProblem moreGeneralProblem = battleCanCastThisSpell(caster, spell, mode);
if(moreGeneralProblem != ESpellCastProblem::OK)
return moreGeneralProblem;
if(spell->getTargetType() == CSpell::OBSTACLE)
{
if(spell->id == SpellID::REMOVE_OBSTACLE)
{
if(auto obstacle = battleGetObstacleOnPos(dest, false))
{
switch (obstacle->obstacleType)
{
case CObstacleInstance::ABSOLUTE_OBSTACLE: //cliff-like obstacles can't be removed
case CObstacleInstance::MOAT:
return ESpellCastProblem::NO_APPROPRIATE_TARGET;
case CObstacleInstance::USUAL:
return ESpellCastProblem::OK;
// //TODO FIRE_WALL only for ADVANCED level casters
// case CObstacleInstance::FIRE_WALL:
// return
// //TODO other magic obstacles for EXPERT
// case CObstacleInstance::QUICKSAND:
// case CObstacleInstance::LAND_MINE:
// case CObstacleInstance::FORCE_FIELD:
// return
default:
// assert(0);
return ESpellCastProblem::OK;
}
}
}
//isObstacleOnTile(dest)
//
//
//TODO
//assert that it's remove obstacle
//rules whether we can remove spell-created obstacle
return ESpellCastProblem::NO_APPROPRIATE_TARGET;
}
//get dead stack if we cast resurrection or animate dead
const CStack *deadStack = getStackIf([dest](const CStack *s) { return !s->alive() && s->coversPos(dest); });
const CStack *aliveStack = getStackIf([dest](const CStack *s) { return s->alive() && s->coversPos(dest);});
if(spell->isRisingSpell())
{
if(!deadStack && !aliveStack)
return ESpellCastProblem::NO_APPROPRIATE_TARGET;
if(deadStack && deadStack->owner != player) //you can resurrect only your own stacks //FIXME: it includes alive stacks as well
return ESpellCastProblem::NO_APPROPRIATE_TARGET;
}
else if(spell->getTargetType() == CSpell::CREATURE)
{
if(!aliveStack)
return ESpellCastProblem::NO_APPROPRIATE_TARGET;
if(spell->isNegative() && aliveStack->owner == player)
return ESpellCastProblem::NO_APPROPRIATE_TARGET;
if(spell->isPositive() && aliveStack->owner != player)
return ESpellCastProblem::NO_APPROPRIATE_TARGET;
}
return spell->isImmuneAt(this, caster, mode, dest);
}
const CStack * CBattleInfoCallback::getStackIf(std::function<bool(const CStack*)> pred) const
{
RETURN_IF_NOT_BATTLE(nullptr);
auto stacks = battleGetAllStacks();
auto stackItr = range::find_if(stacks, pred);
return stackItr == stacks.end()
? nullptr
: *stackItr;
}
bool CBattleInfoCallback::battleIsStackBlocked(const CStack * stack) const
{
RETURN_IF_NOT_BATTLE(false);
if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
return false;
for(const CStack * s : batteAdjacentCreatures(stack))
{
if (s->owner != stack->owner) //blocked by enemy stack
return true;
}
return false;
}
std::set<const CStack*> CBattleInfoCallback:: batteAdjacentCreatures(const CStack * stack) const
{
std::set<const CStack*> stacks;
RETURN_IF_NOT_BATTLE(stacks);
for (BattleHex hex : stack->getSurroundingHexes())
if(const CStack *neighbour = battleGetStackByPos(hex, true))
stacks.insert(neighbour);
return stacks;
}
SpellID CBattleInfoCallback::getRandomBeneficialSpell(const CStack * subject) const
{
RETURN_IF_NOT_BATTLE(SpellID::NONE);
//This is complete list. No spells from mods.
//todo: this should be Spellbook of caster Stack
static const std::set<SpellID> allPossibleSpells =
{
SpellID::AIR_SHIELD,
SpellID::ANTI_MAGIC,
SpellID::BLESS,
SpellID::BLOODLUST,
SpellID::COUNTERSTRIKE,
SpellID::CURE,
SpellID::FIRE_SHIELD,
SpellID::FORTUNE,
SpellID::HASTE,
SpellID::MAGIC_MIRROR,
SpellID::MIRTH,
SpellID::PRAYER,
SpellID::PRECISION,
SpellID::PROTECTION_FROM_AIR,
SpellID::PROTECTION_FROM_EARTH,
SpellID::PROTECTION_FROM_FIRE,
SpellID::PROTECTION_FROM_WATER,
SpellID::SHIELD,
SpellID::SLAYER,
SpellID::STONE_SKIN
};
std::vector<SpellID> beneficialSpells;
auto getAliveEnemy = [=](const std::function<bool(const CStack * )> & pred)
{
return getStackIf([=](const CStack * stack)
{
return pred(stack) && stack->owner != subject->owner && stack->alive();
});
};
for(const SpellID spellID : allPossibleSpells)
{
if (subject->hasBonusFrom(Bonus::SPELL_EFFECT, spellID)
//TODO: this ability has special limitations
|| battleCanCastThisSpellHere(subject, spellID.toSpell(), ECastingMode::CREATURE_ACTIVE_CASTING, subject->position) != ESpellCastProblem::OK)
continue;
switch (spellID)
{
case SpellID::SHIELD:
case SpellID::FIRE_SHIELD: // not if all enemy units are shooters
{
auto walker = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
{
return !stack->shots;
});
if (!walker)
continue;
}
break;
case SpellID::AIR_SHIELD: //only against active shooters
{
auto shooter = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
{
return stack->hasBonusOfType(Bonus::SHOOTER) && stack->shots;
});
if (!shooter)
continue;
}
break;
case SpellID::ANTI_MAGIC:
case SpellID::MAGIC_MIRROR:
case SpellID::PROTECTION_FROM_AIR:
case SpellID::PROTECTION_FROM_EARTH:
case SpellID::PROTECTION_FROM_FIRE:
case SpellID::PROTECTION_FROM_WATER:
{
const ui8 enemySide = (ui8)subject->attackerOwned;
//todo: only if enemy has spellbook
if (!battleHasHero(enemySide)) //only if there is enemy hero
continue;
}
break;
case SpellID::CURE: //only damaged units
{
//do not cast on affected by debuffs
if (subject->firstHPleft >= subject->MaxHealth())
continue;
}
break;
case SpellID::BLOODLUST:
{
if (subject->shots) //if can shoot - only if enemy uits are adjacent
continue;
}
break;
case SpellID::PRECISION:
{
if (!(subject->hasBonusOfType(Bonus::SHOOTER) && subject->shots))
continue;
}
break;
case SpellID::SLAYER://only if monsters are present
{
auto kingMonster = getAliveEnemy([&](const CStack *stack) -> bool //look for enemy, non-shooting stack
{
const auto isKing = Selector::type(Bonus::KING1)
.Or(Selector::type(Bonus::KING2))
.Or(Selector::type(Bonus::KING3));
return stack->hasBonus(isKing);
});
if (!kingMonster)
continue;
}
break;
}
beneficialSpells.push_back(spellID);
}
if(!beneficialSpells.empty())
{
return *RandomGeneratorUtil::nextItem(beneficialSpells, gs->getRandomGenerator());
}
else
{
return SpellID::NONE;
}
}
SpellID CBattleInfoCallback::getRandomCastedSpell(const CStack * caster) const
{
RETURN_IF_NOT_BATTLE(SpellID::NONE);
TBonusListPtr bl = caster->getBonuses(Selector::type(Bonus::SPELLCASTER));
if (!bl->size())
return SpellID::NONE;
int totalWeight = 0;
for(Bonus * b : *bl)
{
totalWeight += std::max(b->additionalInfo, 1); //minimal chance to cast is 1
}
int randomPos = gs->getRandomGenerator().nextInt(totalWeight - 1);
for(Bonus * b : *bl)
{
randomPos -= std::max(b->additionalInfo, 1);
if(randomPos < 0)
{
return SpellID(b->subtype);
}
}
return SpellID::NONE;
}
int CBattleInfoCallback::battleGetSurrenderCost(PlayerColor Player) const
{
RETURN_IF_NOT_BATTLE(-3);
if(!battleCanSurrender(Player))
return -1;
int ret = 0;
double discount = 0;
for(const CStack *s : battleAliveStacks(playerToSide(Player)))
if(s->base) //we pay for our stack that comes from our army slots - condition eliminates summoned cres and war machines
ret += s->getCreature()->cost[Res::GOLD] * s->count;
if(const CGHeroInstance *h = battleGetFightingHero(playerToSide(Player)))
discount += h->valOfBonuses(Bonus::SURRENDER_DISCOUNT);
ret *= (100.0 - discount) / 100.0;
vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
return ret;
}
si8 CBattleInfoCallback::battleMaxSpellLevel(ui8 side) const
{
const IBonusBearer *node = nullptr;
if(const CGHeroInstance * h = battleGetFightingHero(side))
node = h;
else
node = getBattleNode();
if(!node)
return GameConstants::SPELL_LEVELS;
//We can't "just get value" - it'd be 0 if there are bonuses (and all would be blocked)
auto b = node->getBonuses(Selector::type(Bonus::BLOCK_MAGIC_ABOVE));
if(b->size())
return b->totalValue();
return GameConstants::SPELL_LEVELS;
}
boost::optional<int> CBattleInfoCallback::battleIsFinished() const
{
auto stacks = battleGetAllStacks();
//checking winning condition
bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarly
hasStack[0] = hasStack[1] = false;
for(auto & stack : stacks)
{
if(stack->alive() && !stack->hasBonusOfType(Bonus::SIEGE_WEAPON))
{
hasStack[1-stack->attackerOwned] = true;
}
}
if(!hasStack[0] && !hasStack[1])
return 2;
if(!hasStack[1])
return 0;
if(!hasStack[0])
return 1;
return boost::none;
}
bool AccessibilityInfo::accessible(BattleHex tile, const CStack *stack) const
{
return accessible(tile, stack->doubleWide(), stack->attackerOwned);
}
bool AccessibilityInfo::accessible(BattleHex tile, bool doubleWide, bool attackerOwned) const
{
// All hexes that stack would cover if standing on tile have to be accessible.
for(auto hex : CStack::getHexes(tile, doubleWide, attackerOwned))
{
// If the hex is out of range then the tile isn't accessible
if(!hex.isValid())
return false;
// If we're no defender which step on gate and the hex isn't accessible, then the tile
// isn't accessible
else if(at(hex) != EAccessibility::ACCESSIBLE &&
!(at(hex) == EAccessibility::GATE && !attackerOwned))
return false;
}
return true;
}
bool AccessibilityInfo::occupiable(const CStack *stack, BattleHex tile) const
{
//obviously, we can occupy tile by standing on it
if(accessible(tile, stack))
return true;
if(stack->doubleWide())
{
//Check the tile next to -> if stack stands there, it'll also occupy considered hex
const BattleHex anotherTile = tile + (stack->attackerOwned ? BattleHex::RIGHT : BattleHex::LEFT);
if(accessible(anotherTile, stack))
return true;
}
return false;
}
ReachabilityInfo::Parameters::Parameters()
{
stack = nullptr;
perspective = BattlePerspective::ALL_KNOWING;
attackerOwned = doubleWide = flying = false;
}
ReachabilityInfo::Parameters::Parameters(const CStack *Stack)
{
stack = Stack;
perspective = (BattlePerspective::BattlePerspective)(!Stack->attackerOwned);
startPosition = Stack->position;
doubleWide = stack->doubleWide();
attackerOwned = stack->attackerOwned;
flying = stack->hasBonusOfType(Bonus::FLYING);
knownAccessible = stack->getHexes();
}
ESpellCastProblem::ESpellCastProblem CPlayerBattleCallback::battleCanCastThisSpell(const CSpell * spell) const
{
RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
ASSERT_IF_CALLED_WITH_PLAYER
const ISpellCaster * hero = battleGetMyHero();
if(hero == nullptr)
return ESpellCastProblem::INVALID;
else
return CBattleInfoCallback::battleCanCastThisSpell(hero, spell, ECastingMode::HERO_CASTING);
}
bool CPlayerBattleCallback::battleCanFlee() const
{
RETURN_IF_NOT_BATTLE(false);
ASSERT_IF_CALLED_WITH_PLAYER
return CBattleInfoEssentials::battleCanFlee(*player);
}
TStacks CPlayerBattleCallback::battleGetStacks(EStackOwnership whose /*= MINE_AND_ENEMY*/, bool onlyAlive /*= true*/) const
{
if(whose != MINE_AND_ENEMY)
{
ASSERT_IF_CALLED_WITH_PLAYER
}
return battleGetStacksIf([=](const CStack * s){
const bool ownerMatches = (whose == MINE_AND_ENEMY)
|| (whose == ONLY_MINE && s->owner == player)
|| (whose == ONLY_ENEMY && s->owner != player);
const bool alivenessMatches = s->alive() || !onlyAlive;
return ownerMatches && alivenessMatches;
});
}
int CPlayerBattleCallback::battleGetSurrenderCost() const
{
RETURN_IF_NOT_BATTLE(-3)
ASSERT_IF_CALLED_WITH_PLAYER
return CBattleInfoCallback::battleGetSurrenderCost(*player);
}
bool CPlayerBattleCallback::battleCanCastSpell(ESpellCastProblem::ESpellCastProblem *outProblem /*= nullptr*/) const
{
RETURN_IF_NOT_BATTLE(false);
ASSERT_IF_CALLED_WITH_PLAYER
auto problem = CBattleInfoCallback::battleCanCastSpell(*player, ECastingMode::HERO_CASTING);
if(outProblem)
*outProblem = problem;
return problem == ESpellCastProblem::OK;
}
const CGHeroInstance * CPlayerBattleCallback::battleGetMyHero() const
{
return CBattleInfoEssentials::battleGetFightingHero(battleGetMySide());
}
InfoAboutHero CPlayerBattleCallback::battleGetEnemyHero() const
{
return battleGetHeroInfo(!battleGetMySide());
}
BattleAttackInfo::BattleAttackInfo(const CStack *Attacker, const CStack *Defender, bool Shooting)
{
attacker = Attacker;
defender = Defender;
attackerBonuses = Attacker;
defenderBonuses = Defender;
attackerPosition = Attacker->position;
defenderPosition = Defender->position;
attackerCount = Attacker->count;
defenderCount = Defender->count;
shooting = Shooting;
chargedFields = 0;
luckyHit = false;
unluckyHit = false;
deathBlow = false;
ballistaDoubleDamage = false;
}
BattleAttackInfo BattleAttackInfo::reverse() const
{
BattleAttackInfo ret = *this;
std::swap(ret.attacker, ret.defender);
std::swap(ret.attackerBonuses, ret.defenderBonuses);
std::swap(ret.attackerPosition, ret.defenderPosition);
std::swap(ret.attackerCount, ret.defenderCount);
ret.shooting = false;
ret.chargedFields = 0;
ret.luckyHit = ret.ballistaDoubleDamage = ret.deathBlow = false;
return ret;
}
|
edeksumo/vcmi
|
lib/CBattleCallback.cpp
|
C++
|
gpl-2.0
| 67,824
|
/*
* fs/sysfs/bin.c - sysfs binary file implementation
*
* Copyright (c) 2003 Patrick Mochel
* Copyright (c) 2003 Matthew Wilcox
* Copyright (c) 2004 Silicon Graphics, Inc.
* Copyright (c) 2007 SUSE Linux Products GmbH
* Copyright (c) 2007 Tejun Heo <teheo@suse.de>
*
* This file is released under the GPLv2.
*
* Please see Documentation/filesystems/sysfs.txt for more information.
*/
#undef DEBUG
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/kobject.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/mutex.h>
#include <linux/mm.h>
#include <asm/uaccess.h>
#include "sysfs.h"
/*
* There's one bin_buffer for each open file.
*
* filp->private_data points to bin_buffer and
* sysfs_dirent->s_bin_attr.buffers points to a the bin_buffer s
* sysfs_dirent->s_bin_attr.buffers is protected by sysfs_bin_lock
*/
static DEFINE_MUTEX(sysfs_bin_lock);
struct bin_buffer {
struct mutex mutex;
void *buffer;
int mmapped;
const struct vm_operations_struct *vm_ops;
struct file *file;
struct hlist_node list;
};
static int
fill_read(struct file *file, char *buffer, loff_t off, size_t count)
{
struct sysfs_dirent *attr_sd = file->f_path.dentry->d_fsdata;
struct bin_attribute *attr = attr_sd->s_bin_attr.bin_attr;
struct kobject *kobj = attr_sd->s_parent->s_dir.kobj;
int rc;
/* need attr_sd for attr, its parent for kobj */
if (!sysfs_get_active(attr_sd))
return -ENODEV;
rc = -EIO;
if (attr->read)
rc = attr->read(file, kobj, attr, buffer, off, count);
sysfs_put_active(attr_sd);
return rc;
}
static ssize_t
read(struct file *file, char __user *userbuf, size_t bytes, loff_t *off)
{
struct bin_buffer *bb = file->private_data;
int size = file_inode(file)->i_size;
loff_t offs = *off;
int count = min_t(size_t, bytes, PAGE_SIZE);
char *temp;
if (!bytes)
return 0;
if (size) {
if (offs > size)
return 0;
if (offs + count > size)
count = size - offs;
}
temp = kmalloc(count, GFP_KERNEL);
if (!temp)
return -ENOMEM;
mutex_lock(&bb->mutex);
count = fill_read(file, bb->buffer, offs, count);
if (count < 0) {
mutex_unlock(&bb->mutex);
goto out_free;
}
memcpy(temp, bb->buffer, count);
mutex_unlock(&bb->mutex);
if (copy_to_user(userbuf, temp, count)) {
count = -EFAULT;
goto out_free;
}
pr_debug("offs = %lld, *off = %lld, count = %d\n", offs, *off, count);
*off = offs + count;
out_free:
kfree(temp);
return count;
}
static int
flush_write(struct file *file, char *buffer, loff_t offset, size_t count)
{
struct sysfs_dirent *attr_sd = file->f_path.dentry->d_fsdata;
struct bin_attribute *attr = attr_sd->s_bin_attr.bin_attr;
struct kobject *kobj = attr_sd->s_parent->s_dir.kobj;
int rc;
/* need attr_sd for attr, its parent for kobj */
if (!sysfs_get_active(attr_sd))
return -ENODEV;
rc = -EIO;
if (attr->write)
rc = attr->write(file, kobj, attr, buffer, offset, count);
sysfs_put_active(attr_sd);
return rc;
}
static ssize_t write(struct file *file, const char __user *userbuf,
size_t bytes, loff_t *off)
{
struct bin_buffer *bb = file->private_data;
int size = file_inode(file)->i_size;
loff_t offs = *off;
int count = min_t(size_t, bytes, PAGE_SIZE);
char *temp;
if (!bytes)
return 0;
if (size) {
if (offs > size)
return 0;
if (offs + count > size)
count = size - offs;
}
temp = memdup_user(userbuf, count);
if (IS_ERR(temp))
return PTR_ERR(temp);
mutex_lock(&bb->mutex);
memcpy(bb->buffer, temp, count);
count = flush_write(file, bb->buffer, offs, count);
mutex_unlock(&bb->mutex);
if (count > 0)
*off = offs + count;
kfree(temp);
return count;
}
static void bin_vma_open(struct vm_area_struct *vma)
{
struct file *file = vma->vm_file;
struct bin_buffer *bb = file->private_data;
struct sysfs_dirent *attr_sd = file->f_path.dentry->d_fsdata;
if (!bb->vm_ops)
return;
if (!sysfs_get_active(attr_sd))
return;
if (bb->vm_ops->open)
bb->vm_ops->open(vma);
sysfs_put_active(attr_sd);
}
static int bin_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct file *file = vma->vm_file;
struct bin_buffer *bb = file->private_data;
struct sysfs_dirent *attr_sd = file->f_path.dentry->d_fsdata;
int ret;
if (!bb->vm_ops)
return VM_FAULT_SIGBUS;
if (!sysfs_get_active(attr_sd))
return VM_FAULT_SIGBUS;
ret = VM_FAULT_SIGBUS;
if (bb->vm_ops->fault)
ret = bb->vm_ops->fault(vma, vmf);
sysfs_put_active(attr_sd);
return ret;
}
static int bin_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct file *file = vma->vm_file;
struct bin_buffer *bb = file->private_data;
struct sysfs_dirent *attr_sd = file->f_path.dentry->d_fsdata;
int ret;
if (!bb->vm_ops)
return VM_FAULT_SIGBUS;
if (!sysfs_get_active(attr_sd))
return VM_FAULT_SIGBUS;
ret = 0;
if (bb->vm_ops->page_mkwrite)
ret = bb->vm_ops->page_mkwrite(vma, vmf);
else
file_update_time(file);
sysfs_put_active(attr_sd);
return ret;
}
static int bin_access(struct vm_area_struct *vma, unsigned long addr,
void *buf, int len, int write)
{
struct file *file = vma->vm_file;
struct bin_buffer *bb = file->private_data;
struct sysfs_dirent *attr_sd = file->f_path.dentry->d_fsdata;
int ret;
if (!bb->vm_ops)
return -EINVAL;
if (!sysfs_get_active(attr_sd))
return -EINVAL;
ret = -EINVAL;
if (bb->vm_ops->access)
ret = bb->vm_ops->access(vma, addr, buf, len, write);
sysfs_put_active(attr_sd);
return ret;
}
#ifdef CONFIG_NUMA
static int bin_set_policy(struct vm_area_struct *vma, struct mempolicy *new)
{
struct file *file = vma->vm_file;
struct bin_buffer *bb = file->private_data;
struct sysfs_dirent *attr_sd = file->f_path.dentry->d_fsdata;
int ret;
if (!bb->vm_ops)
return 0;
if (!sysfs_get_active(attr_sd))
return -EINVAL;
ret = 0;
if (bb->vm_ops->set_policy)
ret = bb->vm_ops->set_policy(vma, new);
sysfs_put_active(attr_sd);
return ret;
}
static struct mempolicy *bin_get_policy(struct vm_area_struct *vma,
unsigned long addr)
{
struct file *file = vma->vm_file;
struct bin_buffer *bb = file->private_data;
struct sysfs_dirent *attr_sd = file->f_path.dentry->d_fsdata;
struct mempolicy *pol;
if (!bb->vm_ops)
return vma->vm_policy;
if (!sysfs_get_active(attr_sd))
return vma->vm_policy;
pol = vma->vm_policy;
if (bb->vm_ops->get_policy)
pol = bb->vm_ops->get_policy(vma, addr);
sysfs_put_active(attr_sd);
return pol;
}
static int bin_migrate(struct vm_area_struct *vma, const nodemask_t *from,
const nodemask_t *to, unsigned long flags)
{
struct file *file = vma->vm_file;
struct bin_buffer *bb = file->private_data;
struct sysfs_dirent *attr_sd = file->f_path.dentry->d_fsdata;
int ret;
if (!bb->vm_ops)
return 0;
if (!sysfs_get_active(attr_sd))
return 0;
ret = 0;
if (bb->vm_ops->migrate)
ret = bb->vm_ops->migrate(vma, from, to, flags);
sysfs_put_active(attr_sd);
return ret;
}
#endif
static const struct vm_operations_struct bin_vm_ops = {
.open = bin_vma_open,
.fault = bin_fault,
.page_mkwrite = bin_page_mkwrite,
.access = bin_access,
#ifdef CONFIG_NUMA
.set_policy = bin_set_policy,
.get_policy = bin_get_policy,
.migrate = bin_migrate,
#endif
};
static int mmap(struct file *file, struct vm_area_struct *vma)
{
struct bin_buffer *bb = file->private_data;
struct sysfs_dirent *attr_sd = file->f_path.dentry->d_fsdata;
struct bin_attribute *attr = attr_sd->s_bin_attr.bin_attr;
struct kobject *kobj = attr_sd->s_parent->s_dir.kobj;
int rc;
mutex_lock(&bb->mutex);
/* need attr_sd for attr, its parent for kobj */
rc = -ENODEV;
if (!sysfs_get_active(attr_sd))
goto out_unlock;
rc = -EINVAL;
if (!attr->mmap)
goto out_put;
rc = attr->mmap(file, kobj, attr, vma);
if (rc)
goto out_put;
/*
* PowerPC's pci_mmap of legacy_mem uses shmem_zero_setup()
* to satisfy versions of X which crash if the mmap fails: that
* substitutes a new vm_file, and we don't then want bin_vm_ops.
*/
if (vma->vm_file != file)
goto out_put;
rc = -EINVAL;
if (bb->mmapped && bb->vm_ops != vma->vm_ops)
goto out_put;
/*
* It is not possible to successfully wrap close.
* So error if someone is trying to use close.
*/
rc = -EINVAL;
if (vma->vm_ops && vma->vm_ops->close)
goto out_put;
rc = 0;
bb->mmapped = 1;
bb->vm_ops = vma->vm_ops;
vma->vm_ops = &bin_vm_ops;
out_put:
sysfs_put_active(attr_sd);
out_unlock:
mutex_unlock(&bb->mutex);
return rc;
}
static int open(struct inode * inode, struct file * file)
{
struct sysfs_dirent *attr_sd = file->f_path.dentry->d_fsdata;
struct bin_attribute *attr = attr_sd->s_bin_attr.bin_attr;
struct bin_buffer *bb = NULL;
int error;
/* binary file operations requires both @sd and its parent */
if (!sysfs_get_active(attr_sd))
return -ENODEV;
error = -EACCES;
if ((file->f_mode & FMODE_WRITE) && !(attr->write || attr->mmap))
goto err_out;
if ((file->f_mode & FMODE_READ) && !(attr->read || attr->mmap))
goto err_out;
error = -ENOMEM;
bb = kzalloc(sizeof(*bb), GFP_KERNEL);
if (!bb)
goto err_out;
bb->buffer = kmalloc(PAGE_SIZE, GFP_KERNEL);
if (!bb->buffer)
goto err_out;
mutex_init(&bb->mutex);
bb->file = file;
file->private_data = bb;
mutex_lock(&sysfs_bin_lock);
hlist_add_head(&bb->list, &attr_sd->s_bin_attr.buffers);
mutex_unlock(&sysfs_bin_lock);
/* open succeeded, put active references */
sysfs_put_active(attr_sd);
return 0;
err_out:
sysfs_put_active(attr_sd);
kfree(bb);
return error;
}
static int release(struct inode * inode, struct file * file)
{
struct bin_buffer *bb = file->private_data;
mutex_lock(&sysfs_bin_lock);
hlist_del(&bb->list);
mutex_unlock(&sysfs_bin_lock);
kfree(bb->buffer);
kfree(bb);
return 0;
}
const struct file_operations bin_fops = {
.read = read,
.write = write,
.mmap = mmap,
.llseek = generic_file_llseek,
.open = open,
.release = release,
};
void unmap_bin_file(struct sysfs_dirent *attr_sd)
{
struct bin_buffer *bb;
if (sysfs_type(attr_sd) != SYSFS_KOBJ_BIN_ATTR)
return;
mutex_lock(&sysfs_bin_lock);
hlist_for_each_entry(bb, &attr_sd->s_bin_attr.buffers, list) {
struct inode *inode = file_inode(bb->file);
unmap_mapping_range(inode->i_mapping, 0, 0, 1);
}
mutex_unlock(&sysfs_bin_lock);
}
/**
* sysfs_create_bin_file - create binary file for object.
* @kobj: object.
* @attr: attribute descriptor.
*/
int sysfs_create_bin_file(struct kobject *kobj,
const struct bin_attribute *attr)
{
BUG_ON(!kobj || !kobj->sd || !attr);
return sysfs_add_file(kobj->sd, &attr->attr, SYSFS_KOBJ_BIN_ATTR);
}
/**
* sysfs_remove_bin_file - remove binary file for object.
* @kobj: object.
* @attr: attribute descriptor.
*/
void sysfs_remove_bin_file(struct kobject *kobj,
const struct bin_attribute *attr)
{
sysfs_hash_and_remove(kobj->sd, NULL, attr->attr.name);
}
EXPORT_SYMBOL_GPL(sysfs_create_bin_file);
EXPORT_SYMBOL_GPL(sysfs_remove_bin_file);
|
evolver56k/xpenology
|
fs/sysfs/bin.c
|
C
|
gpl-2.0
| 10,944
|
#!/usr/bin/env python
"""
ConversionParser.py $Id: ConversionParser.py,v 1.5 2004/10/20 01:44:53 chrish Exp $
Copyright 2003 Bill Nalen <bill.nalen@towers.com>
Distributable under the GNU General Public License Version 2 or newer.
Provides methods to wrap external convertors to return PluckerTextDocuments
"""
import os, sys, string, tempfile
from PyPlucker import TextParser
from UtilFns import message, error
def WordParser (url, data, headers, config, attributes):
"""Convert a Word document to HTML and returns a PluckerTextDocument"""
# retrieve config information
worddoc_converter = config.get_string('worddoc_converter')
if worddoc_converter is None:
message(0, "Could not find Word conversion command")
return None
check = os.path.basename (worddoc_converter)
(check, ext) = os.path.splitext (check)
check = string.lower (check)
if check == 'wvware':
# need to save data to a local file
tempbase = tempfile.mktemp()
tempdoc = os.path.join(tempfile.tempdir, tempbase + ".doc")
try:
file = open (tempdoc, "wb")
file.write (data)
file.close ()
except IOError, text:
message(0, "Error saving temporary file %s" % tempdoc)
os.unlink(tempdoc)
return None
# then convert it > local.html
temphtml = os.path.join(tempfile.tempdir, tempbase + ".html")
command = worddoc_converter
command = command + " -d " + tempfile.tempdir + " -b " + os.path.join(tempfile.tempdir, tempbase)
command = command + " " + tempdoc + " > " + temphtml
try:
if os.system (command):
message(0, "Error running Word converter %s" % command)
try:
os.unlink(tempdoc)
os.unlink(temphtml)
except:
pass
return None
except:
message(0, "Exception running word converter %s" % command)
try:
os.unlink(tempdoc)
os.unlink(temphtml)
except:
pass
return None
# then load the local.html file to data2
try:
try:
file = open (temphtml, "rb")
data2 = file.read ()
file.close ()
finally:
os.unlink(tempdoc)
os.unlink(temphtml)
except IOError, text:
message(0, "Error reading temporary file %s" % temphtml)
return None
# then create a structuredhtmlparser from data2
parser = TextParser.StructuredHTMLParser (url, data2, headers, config, attributes)
return parser.get_plucker_doc ()
else:
return None
|
arpruss/plucker
|
parser/python/PyPlucker/ConversionParser.py
|
Python
|
gpl-2.0
| 2,897
|
package yokohama.holdem
import akka.actor.{ Actor, Props, ActorRef, ActorLogging }
import yokohama.holdem.Game._
import yokohama.holdem.Cards._
object Player {
sealed trait Bet
case class Call(amount: Int) extends Bet
case object Check extends Bet
case object Fold extends Bet
}
class Player extends Actor with ActorLogging {
import Player._
override def receive: Receive = {
case MakeMove => {
log info "Receive MakeMove Message"
sender ! evaluate()
}
}
private def evaluate(): Bet = {
Call(2)
}
}
|
jeffusan/yokohama-holdem
|
src/main/scala/yokohama/holdem/Player.scala
|
Scala
|
gpl-2.0
| 551
|
<?php
require_once('template/common.php');
require_once('template/tree.php');
// The children template is passed an associative array with the following
// elements:
//
// page => A string containing the name of the wiki page being viewed.
// children => An array containing the list of children, in the same format
// as returned from pagestore->getTree().
function template_children($args)
{
template_common_prologue(array(
'norobots' => 1,
'title' => 'Children of ' . $args['page'],
'heading' => 'Children of ',
'headlink' => $args['page'],
'headsufx' => '',
'toolbar' => 1,
'button_selected' => '',
'button_view' => 1,
'timestamp' => $args['timestamp'],
'editver' => $args['editver'],
'button_backlinks' => 1
));
global $pagestore;
$page = $args['page'];
$children = $args['children'];
?>
<div class="content childtree">
<p>
<table cellspacing="0" cellpadding="0" border="0">
<tr valign="top">
<td>
<p>
<?php
if ($children) {
$tree = array();
$tree[$page] = array();
foreach ($children as $child) {
$tree[$page][$child] = array();
}
drawTree($tree);
} else {
print 'No children';
}
?>
</td>
</tr>
</table>
</div>
<?php
template_common_epilogue(array(
'twin' => '',
'edit' => '',
'editver' => 0,
'history' => '',
'euser' => $args['edituser'],
'timestamp' => $args['timestamp'],
'headlink' => $args['page'],
'button_selected' => '',
'button_view' => 1,
#'timestamp' => $args['timestamp'] already specified
#'editver' => $args['editver'] already specified
'button_backlinks' => 1
));
}
?>
|
apenwarr/gracefultavi
|
template/children.php
|
PHP
|
gpl-2.0
| 1,843
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>CRAN - Package CINOEDV</title>
<link rel="stylesheet" type="text/css" href="../../CRAN_web.css" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
table td { vertical-align: top; }
</style>
</head>
<body>
<h2>CINOEDV: Co-Information based N-Order Epistasis Detector and Visualizer</h2>
<p>Detecting and visualizing nonlinear interaction effects of single nucleotide polymorphisms or epistatic interactions, especially high-order epistatic interactions, are important topics in bioinformatics because of their significant mathematical and computational challenges. We present CINOEDV (Co-Information based N-Order Epistasis Detector and Visualizer) for detecting, visualizing, and analyzing high-order epistatic interactions by introducing virtual vertices into the construction of a hypergraph. CINOEDV was developed as an alternative to existing software to build a global picture of epistatic interactions and unexpected high-order epistatic interactions, which might provide useful clues for understanding the underlying genetic architecture of complex diseases.</p>
<table summary="Package CINOEDV summary">
<tr>
<td>Version:</td>
<td>2.0</td>
</tr>
<tr>
<td>Depends:</td>
<td><a href="../R.matlab/index.html">R.matlab</a>, <a href="../igraph/index.html">igraph</a>, <a href="../ggplot2/index.html">ggplot2</a>, <a href="../reshape2/index.html">reshape2</a></td>
</tr>
<tr>
<td>Published:</td>
<td>2014-11-27</td>
</tr>
<tr>
<td>Author:</td>
<td>Junliang Shang</td>
</tr>
<tr>
<td>Maintainer:</td>
<td>Junliang Shang <shangjunliang110 at 163.com></td>
</tr>
<tr>
<td>License:</td>
<td><a href="../../licenses/GPL-2">GPL-2</a></td>
</tr>
<tr>
<td>NeedsCompilation:</td>
<td>no</td>
</tr>
<tr>
<td>CRAN checks:</td>
<td><a href="../../checks/check_results_CINOEDV.html">CINOEDV results</a></td>
</tr>
</table>
<h4>Downloads:</h4>
<table summary="Package CINOEDV downloads">
<tr>
<td> Reference manual: </td>
<td> <a href="CINOEDV.pdf"> CINOEDV.pdf </a> </td>
</tr>
<tr>
<td> Package source: </td>
<td> <a href="../../../src/contrib/CINOEDV_2.0.tar.gz"> CINOEDV_2.0.tar.gz </a> </td>
</tr>
<tr>
<td> Windows binaries: </td>
<td> r-devel: <a href="../../../bin/windows/contrib/3.5/CINOEDV_2.0.zip">CINOEDV_2.0.zip</a>, r-release: <a href="../../../bin/windows/contrib/3.4/CINOEDV_2.0.zip">CINOEDV_2.0.zip</a>, r-oldrel: <a href="../../../bin/windows/contrib/3.3/CINOEDV_2.0.zip">CINOEDV_2.0.zip</a> </td>
</tr>
<tr>
<td> OS X El Capitan binaries: </td>
<td> r-release: <a href="../../../bin/macosx/el-capitan/contrib/3.4/CINOEDV_2.0.tgz">CINOEDV_2.0.tgz</a> </td>
</tr>
<tr>
<td> OS X Mavericks binaries: </td>
<td> r-oldrel: <a href="../../../bin/macosx/mavericks/contrib/3.3/CINOEDV_2.0.tgz">CINOEDV_2.0.tgz</a> </td>
</tr>
<tr>
<td> Old sources: </td>
<td> <a href="../../../src/contrib/Archive/CINOEDV"> CINOEDV archive </a> </td>
</tr>
</table>
<h4>Linking:</h4>
<p>Please use the canonical form
<a href="https://CRAN.R-project.org/package=CINOEDV"><samp>https://CRAN.R-project.org/package=CINOEDV</samp></a>
to link to this page.</p>
</body>
</html>
|
esander91/NamespacePollution
|
Code/GetMetaDataFromCRAN/raw_html/CINOEDV.html
|
HTML
|
gpl-2.0
| 3,478
|
TARGET = mkexample
OBJS = $(TARGET).o
PREFIX = $(HOME)
BINDIR = $(PREFIX)/bin
# compile
.adb.o:
gcc -c -gnat2012 $<
.SUFFIXES: .adb .o
# link
$(TARGET): $(OBJS)
gnatbind -x $(TARGET).ali; gnatlink $(TARGET).ali
gnat xref *.ali -v > tags
install:
install -D $(TARGET) $(BINDIR)/$(TARGET)
uninstall:
-rm $(BINDIR)/$(TARGET)
clean:
rm -f *.o *.ali $(TARGET)
|
Blunk-electronic/ada_training
|
src/mkexample/Makefile
|
Makefile
|
gpl-2.0
| 368
|
/*
* drivers/input/misc/keychord.c
*
* Copyright (C) 2008 Google, Inc.
* Author: Mike Lockwood <lockwood@android.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/poll.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/init.h>
<<<<<<< HEAD
#include <linux/spinlock.h>
=======
#include <linux/smp_lock.h>
>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <linux/keychord.h>
#include <linux/sched.h>
#define KEYCHORD_NAME "keychord"
#define BUFFER_SIZE 16
<<<<<<< HEAD
#define MATCH_COUNT 3
#define KEYCHORD_TIMEOUT 5*HZ
=======
>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a
MODULE_AUTHOR("Mike Lockwood <lockwood@android.com>");
MODULE_DESCRIPTION("Key chord input driver");
MODULE_SUPPORTED_DEVICE("keychord");
MODULE_LICENSE("GPL");
#define NEXT_KEYCHORD(kc) ((struct input_keychord *) \
((char *)kc + sizeof(struct input_keychord) + \
kc->count * sizeof(kc->keycodes[0])))
struct keychord_device {
struct input_handler input_handler;
int registered;
/* list of keychords to monitor */
struct input_keychord *keychords;
int keychord_count;
/* bitmask of keys contained in our keychords */
unsigned long keybit[BITS_TO_LONGS(KEY_CNT)];
/* current state of the keys */
unsigned long keystate[BITS_TO_LONGS(KEY_CNT)];
/* number of keys that are currently pressed */
int key_down;
/* second input_device_id is needed for null termination */
struct input_device_id device_ids[2];
spinlock_t lock;
wait_queue_head_t waitq;
unsigned char head;
unsigned char tail;
__u16 buff[BUFFER_SIZE];
<<<<<<< HEAD
struct delayed_work keychord_delayed_work;
struct work_struct keychord_checkwork;
struct workqueue_struct *keychord_wq;
int8_t keychord_match_count;
};
static void keychord_timeout(struct work_struct *work)
{
struct keychord_device *kdev =
container_of(work, struct keychord_device, keychord_delayed_work.work);
pr_info("%s: match_count=%d\n", __func__, kdev->keychord_match_count);
if (kdev->keychord_match_count)
kdev->keychord_match_count = 0;
}
=======
};
>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a
static int check_keychord(struct keychord_device *kdev,
struct input_keychord *keychord)
{
int i;
if (keychord->count != kdev->key_down)
return 0;
for (i = 0; i < keychord->count; i++) {
if (!test_bit(keychord->keycodes[i], kdev->keystate))
return 0;
}
<<<<<<< HEAD
if (kdev->keychord_match_count++ == 0)
schedule_delayed_work(&kdev->keychord_delayed_work, KEYCHORD_TIMEOUT);
if (kdev->keychord_match_count == MATCH_COUNT) {
if (cancel_delayed_work(&kdev->keychord_delayed_work)) {
kdev->keychord_match_count = 0;
return 1;
} else
pr_info("%s: timeout already started\n", __func__);
}
return 0;
}
static void keychord_check_work(struct work_struct *work)
{
int i, got_chord;
struct input_keychord *keychord;
struct keychord_device *kdev =
container_of(work, struct keychord_device, keychord_checkwork);
keychord = kdev->keychords;
got_chord = 0;
for (i = 0; i < kdev->keychord_count; i++) {
if (check_keychord(kdev, keychord)) {
kdev->buff[kdev->head] = keychord->id;
kdev->head = (kdev->head + 1) % BUFFER_SIZE;
got_chord = 1;
printk(KERN_INFO "[KEY]%s: Keychord get triggered!\n", __func__);
break;
}
/* skip to next keychord */
keychord = NEXT_KEYCHORD(keychord);
}
if (got_chord)
wake_up_interruptible(&kdev->waitq);
=======
/* we have a match */
return 1;
>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a
}
static void keychord_event(struct input_handle *handle, unsigned int type,
unsigned int code, int value)
{
struct keychord_device *kdev = handle->private;
struct input_keychord *keychord;
unsigned long flags;
<<<<<<< HEAD
=======
int i, got_chord = 0;
>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a
if (type != EV_KEY || code >= KEY_MAX)
return;
spin_lock_irqsave(&kdev->lock, flags);
/* do nothing if key state did not change */
if (!test_bit(code, kdev->keystate) == !value)
goto done;
__change_bit(code, kdev->keystate);
if (value)
kdev->key_down++;
else
kdev->key_down--;
/* don't notify on key up */
if (!value)
goto done;
/* ignore this event if it is not one of the keys we are monitoring */
if (!test_bit(code, kdev->keybit))
goto done;
keychord = kdev->keychords;
<<<<<<< HEAD
if (!keychord)
goto done;
#if 0 /* move to queue for timer checking */
=======
if (!keychord)
goto done;
>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a
/* check to see if the keyboard state matches any keychords */
for (i = 0; i < kdev->keychord_count; i++) {
if (check_keychord(kdev, keychord)) {
kdev->buff[kdev->head] = keychord->id;
kdev->head = (kdev->head + 1) % BUFFER_SIZE;
got_chord = 1;
<<<<<<< HEAD
printk(KERN_INFO "[KEY] Keychord get triggered!\n");
=======
>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a
break;
}
/* skip to next keychord */
keychord = NEXT_KEYCHORD(keychord);
}
<<<<<<< HEAD
#endif
queue_work(kdev->keychord_wq, &kdev->keychord_checkwork);
=======
>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a
done:
spin_unlock_irqrestore(&kdev->lock, flags);
<<<<<<< HEAD
#if 0 /* move to queue for timer checking */
if (got_chord) {
wake_up_interruptible(&kdev->waitq);
printk(KERN_INFO "[KEY] wakeup!\n");
}
#endif
=======
if (got_chord)
wake_up_interruptible(&kdev->waitq);
>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a
}
static int keychord_connect(struct input_handler *handler,
struct input_dev *dev,
const struct input_device_id *id)
{
int i, ret;
struct input_handle *handle;
struct keychord_device *kdev =
container_of(handler, struct keychord_device, input_handler);
/*
* ignore this input device if it does not contain any keycodes
* that we are monitoring
*/
for (i = 0; i < KEY_MAX; i++) {
if (test_bit(i, kdev->keybit) && test_bit(i, dev->keybit))
break;
}
if (i == KEY_MAX)
return -ENODEV;
handle = kzalloc(sizeof(*handle), GFP_KERNEL);
if (!handle)
return -ENOMEM;
handle->dev = dev;
handle->handler = handler;
handle->name = KEYCHORD_NAME;
handle->private = kdev;
ret = input_register_handle(handle);
if (ret)
goto err_input_register_handle;
ret = input_open_device(handle);
if (ret)
goto err_input_open_device;
pr_info("keychord: using input dev %s for fevent\n", dev->name);
return 0;
err_input_open_device:
input_unregister_handle(handle);
err_input_register_handle:
kfree(handle);
return ret;
}
static void keychord_disconnect(struct input_handle *handle)
{
input_close_device(handle);
input_unregister_handle(handle);
kfree(handle);
}
/*
* keychord_read is used to read keychord events from the driver
*/
static ssize_t keychord_read(struct file *file, char __user *buffer,
size_t count, loff_t *ppos)
{
struct keychord_device *kdev = file->private_data;
__u16 id;
int retval;
unsigned long flags;
if (count < sizeof(id))
return -EINVAL;
count = sizeof(id);
if (kdev->head == kdev->tail && (file->f_flags & O_NONBLOCK))
return -EAGAIN;
retval = wait_event_interruptible(kdev->waitq,
kdev->head != kdev->tail);
if (retval)
return retval;
spin_lock_irqsave(&kdev->lock, flags);
/* pop a keychord ID off the queue */
id = kdev->buff[kdev->tail];
kdev->tail = (kdev->tail + 1) % BUFFER_SIZE;
spin_unlock_irqrestore(&kdev->lock, flags);
if (copy_to_user(buffer, &id, count))
return -EFAULT;
return count;
}
/*
* keychord_write is used to configure the driver
*/
static ssize_t keychord_write(struct file *file, const char __user *buffer,
size_t count, loff_t *ppos)
{
struct keychord_device *kdev = file->private_data;
struct input_keychord *keychords = 0;
struct input_keychord *keychord, *next, *end;
int ret, i, key;
unsigned long flags;
if (count < sizeof(struct input_keychord))
return -EINVAL;
keychords = kzalloc(count, GFP_KERNEL);
if (!keychords)
return -ENOMEM;
/* read list of keychords from userspace */
if (copy_from_user(keychords, buffer, count)) {
kfree(keychords);
return -EFAULT;
}
/* unregister handler before changing configuration */
if (kdev->registered) {
input_unregister_handler(&kdev->input_handler);
kdev->registered = 0;
}
spin_lock_irqsave(&kdev->lock, flags);
/* clear any existing configuration */
kfree(kdev->keychords);
kdev->keychords = 0;
kdev->keychord_count = 0;
kdev->key_down = 0;
memset(kdev->keybit, 0, sizeof(kdev->keybit));
memset(kdev->keystate, 0, sizeof(kdev->keystate));
kdev->head = kdev->tail = 0;
keychord = keychords;
end = (struct input_keychord *)((char *)keychord + count);
while (keychord < end) {
next = NEXT_KEYCHORD(keychord);
if (keychord->count <= 0 || next > end) {
pr_err("keychord: invalid keycode count %d\n",
keychord->count);
goto err_unlock_return;
}
if (keychord->version != KEYCHORD_VERSION) {
pr_err("keychord: unsupported version %d\n",
keychord->version);
goto err_unlock_return;
}
/* keep track of the keys we are monitoring in keybit */
for (i = 0; i < keychord->count; i++) {
key = keychord->keycodes[i];
if (key < 0 || key >= KEY_CNT) {
pr_err("keychord: keycode %d out of range\n",
key);
goto err_unlock_return;
}
__set_bit(key, kdev->keybit);
}
kdev->keychord_count++;
keychord = next;
}
kdev->keychords = keychords;
spin_unlock_irqrestore(&kdev->lock, flags);
ret = input_register_handler(&kdev->input_handler);
if (ret) {
kfree(keychords);
kdev->keychords = 0;
return ret;
}
kdev->registered = 1;
return count;
err_unlock_return:
spin_unlock_irqrestore(&kdev->lock, flags);
kfree(keychords);
return -EINVAL;
}
static unsigned int keychord_poll(struct file *file, poll_table *wait)
{
struct keychord_device *kdev = file->private_data;
poll_wait(file, &kdev->waitq, wait);
if (kdev->head != kdev->tail)
return POLLIN | POLLRDNORM;
return 0;
}
static int keychord_open(struct inode *inode, struct file *file)
{
struct keychord_device *kdev;
kdev = kzalloc(sizeof(struct keychord_device), GFP_KERNEL);
if (!kdev)
return -ENOMEM;
spin_lock_init(&kdev->lock);
init_waitqueue_head(&kdev->waitq);
kdev->input_handler.event = keychord_event;
kdev->input_handler.connect = keychord_connect;
kdev->input_handler.disconnect = keychord_disconnect;
kdev->input_handler.name = KEYCHORD_NAME;
kdev->input_handler.id_table = kdev->device_ids;
kdev->device_ids[0].flags = INPUT_DEVICE_ID_MATCH_EVBIT;
__set_bit(EV_KEY, kdev->device_ids[0].evbit);
file->private_data = kdev;
<<<<<<< HEAD
kdev->keychord_wq = create_singlethread_workqueue("keychord");
INIT_DELAYED_WORK(&kdev->keychord_delayed_work, keychord_timeout);
INIT_WORK(&kdev->keychord_checkwork, keychord_check_work);
=======
>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a
return 0;
}
static int keychord_release(struct inode *inode, struct file *file)
{
struct keychord_device *kdev = file->private_data;
<<<<<<< HEAD
destroy_workqueue(kdev->keychord_wq);
=======
>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a
if (kdev->registered)
input_unregister_handler(&kdev->input_handler);
kfree(kdev);
return 0;
}
static const struct file_operations keychord_fops = {
.owner = THIS_MODULE,
.open = keychord_open,
.release = keychord_release,
.read = keychord_read,
.write = keychord_write,
.poll = keychord_poll,
};
static struct miscdevice keychord_misc = {
.fops = &keychord_fops,
.name = KEYCHORD_NAME,
.minor = MISC_DYNAMIC_MINOR,
};
static int __init keychord_init(void)
{
return misc_register(&keychord_misc);
}
static void __exit keychord_exit(void)
{
misc_deregister(&keychord_misc);
}
module_init(keychord_init);
module_exit(keychord_exit);
|
Core2idiot/Kernel-Samsung-3.0...-
|
drivers/input/misc/keychord.c
|
C
|
gpl-2.0
| 12,182
|
<?php
/**
* @version 2.9.x
* @package K2
* @author JoomlaWorks https://www.joomlaworks.net
* @copyright Copyright (c) 2006 - 2019 JoomlaWorks Ltd. All rights reserved.
* @license GNU/GPL license: http://www.gnu.org/copyleft/gpl.html
*/
// no direct access
defined('_JEXEC') or die;
jimport('joomla.application.component.view');
class K2ViewItem extends K2View
{
public function display($tpl = null)
{
$application = JFactory::getApplication();
$user = JFactory::getUser();
$document = JFactory::getDocument();
$params = K2HelperUtilities::getParams('com_k2');
$limitstart = JRequest::getInt('limitstart', 0);
$view = JRequest::getWord('view');
$task = JRequest::getWord('task');
$db = JFactory::getDbo();
$jnow = JFactory::getDate();
$now = K2_JVERSION == '15' ? $jnow->toMySQL() : $jnow->toSql();
$nullDate = $db->getNullDate();
$this->setLayout('item');
// Add link
if (K2HelperPermissions::canAddItem()) {
$addLink = JRoute::_('index.php?option=com_k2&view=item&task=add&tmpl=component');
}
$this->assignRef('addLink', $addLink);
// Get item
$model = $this->getModel();
$item = $model->getData();
// Does the item exists?
if (!is_object($item) || !$item->id) {
JError::raiseError(404, JText::_('K2_ITEM_NOT_FOUND'));
}
// Prepare item
$item = $model->prepareItem($item, $view, $task);
$itemTextBeforePlugins = $item->introtext.' '.$item->fulltext;
// Plugins
$item = $model->execPlugins($item, $view, $task);
// User K2 plugins
$item->event->K2UserDisplay = '';
if (isset($item->author) && is_object($item->author->profile) && isset($item->author->profile->id)) {
JPluginHelper::importPlugin('k2');
$dispatcher = JDispatcher::getInstance();
$results = $dispatcher->trigger('onK2UserDisplay', array(
&$item->author->profile,
&$params,
$limitstart
));
$item->event->K2UserDisplay = trim(implode("\n", $results));
$item->author->profile->url = htmlspecialchars($item->author->profile->url, ENT_QUOTES, 'UTF-8');
}
// Access check
if ($this->getLayout() == 'form') {
JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
}
if (K2_JVERSION != '15') {
if (!in_array($item->access, $user->getAuthorisedViewLevels()) || !in_array($item->category->access, $user->getAuthorisedViewLevels())) {
if ($user->guest) {
$uri = JFactory::getURI();
$url = 'index.php?option=com_users&view=login&return='.base64_encode($uri->toString());
$application->enqueueMessage(JText::_('K2_YOU_NEED_TO_LOGIN_FIRST'), 'notice');
$application->redirect(JRoute::_($url, false));
} else {
JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
return;
}
}
} else {
if ($item->access > $user->get('aid', 0) || $item->category->access > $user->get('aid', 0)) {
if ($user->guest) {
$uri = JFactory::getURI();
$url = 'index.php?option=com_user&view=login&return='.base64_encode($uri->toString());
$application->enqueueMessage(JText::_('K2_YOU_NEED_TO_LOGIN_FIRST'), 'notice');
$application->redirect(JRoute::_($url, false));
} else {
JError::raiseError(403, JText::_('K2_ALERTNOTAUTH'));
return;
}
}
}
// Published check
if (!$item->published || $item->trash) {
JError::raiseError(404, JText::_('K2_ITEM_NOT_FOUND'));
}
if ($item->publish_up != $nullDate && $item->publish_up > $now) {
JError::raiseError(404, JText::_('K2_ITEM_NOT_FOUND'));
}
if ($item->publish_down != $nullDate && $item->publish_down < $now) {
JError::raiseError(404, JText::_('K2_ITEM_NOT_FOUND'));
}
if (!$item->category->published || $item->category->trash) {
JError::raiseError(404, JText::_('K2_ITEM_NOT_FOUND'));
}
// Increase hits counter
$model->hit($item->id);
// Set default image
K2HelperUtilities::setDefaultImage($item, $view);
// Pass the old parameter to the view in order to avoid layout changes
if ($params->get('antispam') == 'recaptcha' || $params->get('antispam') == 'both') {
$params->set('recaptcha', true);
$item->params->set('recaptcha', true);
} else {
$params->set('recaptcha', false);
$item->params->set('recaptcha', false);
}
// Comments
$item->event->K2CommentsCounter = '';
$item->event->K2CommentsBlock = '';
if ($item->params->get('itemComments')) {
// Trigger comments events
JPluginHelper::importPlugin('k2');
$dispatcher = JDispatcher::getInstance();
$results = $dispatcher->trigger('onK2CommentsCounter', array(
&$item,
&$params,
$limitstart
));
$item->event->K2CommentsCounter = trim(implode("\n", $results));
$results = $dispatcher->trigger('onK2CommentsBlock', array(
&$item,
&$params,
$limitstart
));
$item->event->K2CommentsBlock = trim(implode("\n", $results));
// Load K2 native comments system only if there are no plugins overriding it
if (empty($item->event->K2CommentsCounter) && empty($item->event->K2CommentsBlock)) {
// Load reCAPTCHA script
if (!JRequest::getInt('print') && ($item->params->get('comments') == '1' || ($item->params->get('comments') == '2' && K2HelperPermissions::canAddComment($item->catid)))) {
if ($params->get('recaptcha') && ($user->guest || $params->get('recaptchaForRegistered', 1))) {
if ($params->get('recaptchaV2')) {
$document->addScript('https://www.google.com/recaptcha/api.js?onload=onK2RecaptchaLoaded&render=explicit');
$js = 'function onK2RecaptchaLoaded(){grecaptcha.render("recaptcha", {"sitekey" : "'.$item->params->get('recaptcha_public_key').'"});}';
$document->addScriptDeclaration($js);
$this->recaptchaClass = 'k2-recaptcha-v2';
} else {
$document->addScript('https://www.google.com/recaptcha/api/js/recaptcha_ajax.js');
$js = '
function showRecaptcha(){
Recaptcha.create("'.$item->params->get('recaptcha_public_key').'", "recaptcha", {
theme: "'.$item->params->get('recaptcha_theme', 'clean').'"
});
}
$K2(window).load(function() {
showRecaptcha();
});
';
$document->addScriptDeclaration($js);
$this->recaptchaClass = 'k2-recaptcha-v1';
}
}
}
// Check for inline comment moderation
if (!$user->guest && $user->id == $item->created_by && $params->get('inlineCommentsModeration')) {
$inlineCommentsModeration = true;
$commentsPublished = false;
} else {
$inlineCommentsModeration = false;
$commentsPublished = true;
}
$this->assignRef('inlineCommentsModeration', $inlineCommentsModeration);
// Flag spammer link
$reportSpammerFlag = false;
if (K2_JVERSION != '15') {
if ($user->authorise('core.admin', 'com_k2')) {
$reportSpammerFlag = true;
$document->addScriptDeclaration('var K2Language = ["'.JText::_('K2_REPORT_USER_WARNING', true).'"];');
}
} else {
if ($user->gid > 24) {
$reportSpammerFlag = true;
}
}
$limit = $params->get('commentsLimit');
$comments = $model->getItemComments($item->id, $limitstart, $limit, $commentsPublished);
for ($i = 0; $i < count($comments); $i++) {
$comments[$i]->commentText = nl2br($comments[$i]->commentText);
// Convert URLs to links properly
$comments[$i]->commentText = preg_replace("/([^\w\/])(www\.[a-z0-9\-]+\.[a-z0-9\-]+)/i", "$1http://$2", $comments[$i]->commentText);
$comments[$i]->commentText = preg_replace("/([\w]+:\/\/[\w\-?&;#~=\.\/\@]+[\w\/])/i", "<a target=\"_blank\" rel=\"nofollow\" href=\"$1\">$1</A>", $comments[$i]->commentText);
$comments[$i]->commentText = preg_replace("/([\w\-?&;#~=\.\/]+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?))/i", "<a href=\"mailto:$1\">$1</A>", $comments[$i]->commentText);
$comments[$i]->userImage = K2HelperUtilities::getAvatar($comments[$i]->userID, $comments[$i]->commentEmail, $params->get('commenterImgWidth'));
if ($comments[$i]->userID > 0) {
$comments[$i]->userLink = K2HelperRoute::getUserRoute($comments[$i]->userID);
} else {
$comments[$i]->userLink = $comments[$i]->commentURL;
}
if ($reportSpammerFlag && $comments[$i]->userID > 0) {
$comments[$i]->reportUserLink = JRoute::_('index.php?option=com_k2&view=comments&task=reportSpammer&id='.$comments[$i]->userID.'&format=raw');
} else {
$comments[$i]->reportUserLink = false;
}
}
$item->comments = $comments;
if (!isset($item->numOfComments)) {
$item->numOfComments = 0;
}
jimport('joomla.html.pagination');
$total = $item->numOfComments;
$pagination = new JPagination($total, $limitstart, $limit);
}
}
// Author's latest items
if ($item->params->get('itemAuthorLatest') && $item->created_by_alias == '') {
$model = $this->getModel('itemlist');
$authorLatestItems = $model->getAuthorLatest($item->id, $item->params->get('itemAuthorLatestLimit'), $item->created_by);
if (count($authorLatestItems)) {
for ($i = 0; $i < count($authorLatestItems); $i++) {
$authorLatestItems[$i]->link = urldecode(JRoute::_(K2HelperRoute::getItemRoute($authorLatestItems[$i]->id.':'.urlencode($authorLatestItems[$i]->alias), $authorLatestItems[$i]->catid.':'.urlencode($authorLatestItems[$i]->categoryalias))));
}
$this->assignRef('authorLatestItems', $authorLatestItems);
}
}
// Related items
if ($item->params->get('itemRelated') && isset($item->tags) && count($item->tags)) {
$model = $this->getModel('itemlist');
$relatedItems = $model->getRelatedItems($item->id, $item->tags, $item->params);
if (count($relatedItems)) {
for ($i = 0; $i < count($relatedItems); $i++) {
$relatedItems[$i]->link = urldecode(JRoute::_(K2HelperRoute::getItemRoute($relatedItems[$i]->id.':'.urlencode($relatedItems[$i]->alias), $relatedItems[$i]->catid.':'.urlencode($relatedItems[$i]->categoryalias))));
}
$this->assignRef('relatedItems', $relatedItems);
}
}
// Navigation (previous and next item)
if ($item->params->get('itemNavigation')) {
$model = $this->getModel('item');
$nextItem = $model->getNextItem($item->id, $item->catid, $item->ordering);
if (!is_null($nextItem)) {
$item->nextLink = urldecode(JRoute::_(K2HelperRoute::getItemRoute($nextItem->id.':'.urlencode($nextItem->alias), $nextItem->catid.':'.urlencode($item->category->alias))));
$item->nextTitle = $nextItem->title;
$date = JFactory::getDate($item->modified);
$timestamp = '?t='.$date->toUnix();
if (JFile::exists(JPATH_SITE.'/media/k2/items/cache/'.md5("Image".$nextItem->id).'_XS.jpg')) {
$item->nextImageXSmall = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$nextItem->id).'_XS.jpg'.$timestamp;
}
if (JFile::exists(JPATH_SITE.'/media/k2/items/cache/'.md5("Image".$nextItem->id).'_S.jpg')) {
$item->nextImageSmall = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$nextItem->id).'_S.jpg'.$timestamp;
}
if (JFile::exists(JPATH_SITE.'/media/k2/items/cache/'.md5("Image".$nextItem->id).'_M.jpg')) {
$item->nextImageMedium = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$nextItem->id).'_M.jpg'.$timestamp;
}
if (JFile::exists(JPATH_SITE.'/media/k2/items/cache/'.md5("Image".$nextItem->id).'_L.jpg')) {
$item->nextImageLarge = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$nextItem->id).'_L.jpg'.$timestamp;
}
if (JFile::exists(JPATH_SITE.'/media/k2/items/cache/'.md5("Image".$nextItem->id).'_XL.jpg')) {
$item->nextImageXLarge = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$nextItem->id).'_XL.jpg'.$timestamp;
}
if (JFile::exists(JPATH_SITE.'/media/k2/items/cache/'.md5("Image".$nextItem->id).'_Generic.jpg')) {
$item->nextImageGeneric = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$nextItem->id).'_Generic.jpg'.$timestamp;
}
}
$previousItem = $model->getPreviousItem($item->id, $item->catid, $item->ordering);
if (!is_null($previousItem)) {
$item->previousLink = urldecode(JRoute::_(K2HelperRoute::getItemRoute($previousItem->id.':'.urlencode($previousItem->alias), $previousItem->catid.':'.urlencode($item->category->alias))));
$item->previousTitle = $previousItem->title;
$date = JFactory::getDate($item->modified);
$timestamp = '?t='.$date->toUnix();
if (JFile::exists(JPATH_SITE.'/media/k2/items/cache/'.md5("Image".$previousItem->id).'_XS.jpg')) {
$item->previousImageXSmall = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$previousItem->id).'_XS.jpg'.$timestamp;
}
if (JFile::exists(JPATH_SITE.'/media/k2/items/cache/'.md5("Image".$previousItem->id).'_S.jpg')) {
$item->previousImageSmall = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$previousItem->id).'_S.jpg'.$timestamp;
}
if (JFile::exists(JPATH_SITE.'/media/k2/items/cache/'.md5("Image".$previousItem->id).'_M.jpg')) {
$item->previousImageMedium = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$previousItem->id).'_M.jpg'.$timestamp;
}
if (JFile::exists(JPATH_SITE.'/media/k2/items/cache/'.md5("Image".$previousItem->id).'_L.jpg')) {
$item->previousImageLarge = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$previousItem->id).'_L.jpg'.$timestamp;
}
if (JFile::exists(JPATH_SITE.'/media/k2/items/cache/'.md5("Image".$previousItem->id).'_XL.jpg')) {
$item->previousImageXLarge = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$previousItem->id).'_XL.jpg'.$timestamp;
}
if (JFile::exists(JPATH_SITE.'/media/k2/items/cache/'.md5("Image".$previousItem->id).'_Generic.jpg')) {
$item->previousImageGeneric = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$previousItem->id).'_Generic.jpg'.$timestamp;
}
}
}
// Absolute URL
$uri = JURI::getInstance();
$item->absoluteURL = $uri->toString();
// Email link
if (K2_JVERSION != '15') {
require_once(JPATH_SITE.'/components/com_mailto/helpers/mailto.php');
$template = $application->getTemplate();
$item->emailLink = JRoute::_('index.php?option=com_mailto&tmpl=component&template='.$template.'&link='.MailToHelper::addLink($item->absoluteURL));
} else {
require_once(JPATH_SITE.'/components/com_mailto/helpers/mailto.php');
$item->emailLink = JRoute::_('index.php?option=com_mailto&tmpl=component&link='.MailToHelper::addLink($item->absoluteURL));
}
// Twitter link (legacy code)
if ($params->get('twitterUsername')) {
$item->twitterURL = 'https://twitter.com/intent/tweet?text='.urlencode($item->title).'&url='.urlencode($item->absoluteURL).'&via='.$params->get('twitterUsername');
} else {
$item->twitterURL = 'https://twitter.com/intent/tweet?text='.urlencode($item->title).'&url='.urlencode($item->absoluteURL);
}
// Social link
$item->socialLink = urlencode($item->absoluteURL);
// Get current menu item
$menus = $application->getMenu();
$menu = $menus->getActive();
// Check if the current menu item matches the displayed K2 item
$menuItemMatchesK2Item = false;
if (is_object($menu) && isset($menu->query['view']) && $menu->query['view'] == 'item' && isset($menu->query['id']) && $menu->query['id'] == $item->id) {
$menuItemMatchesK2Item = true;
}
// Set pathway
$pathway = $application->getPathWay();
if ($menu) {
if (isset($menu->query['view']) && ($menu->query['view'] != 'item' || $menu->query['id'] != $item->id)) {
if (!isset($menu->query['task']) || $menu->query['task'] != 'category' || $menu->query['id'] != $item->catid) {
$pathway->addItem($item->category->name, $item->category->link);
}
$pathway->addItem($item->cleanTitle, '');
}
}
// Set canonical link
$canonicalURL = $params->get('canonicalURL', 'relative');
if ($canonicalURL == 'absolute') {
$document->addHeadLink(substr(str_replace(JUri::root(true), '', JUri::root(false)), 0, -1).$item->link, 'canonical', 'rel');
}
if ($canonicalURL == 'relative') {
$document->addHeadLink($item->link, 'canonical', 'rel');
}
// Set page title
if ($menuItemMatchesK2Item) {
if (is_string($menu->params)) {
$menu_params = K2_JVERSION == '15' ? new JParameter($menu->params) : new JRegistry($menu->params);
} else {
$menu_params = $menu->params;
}
if (!$menu_params->get('page_title')) {
$params->set('page_title', $item->cleanTitle);
}
} else {
$params->set('page_title', $item->cleanTitle);
}
if (K2_JVERSION != '15') {
if ($application->getCfg('sitename_pagetitles', 0) == 1) {
$title = JText::sprintf('JPAGETITLE', $application->getCfg('sitename'), $params->get('page_title'));
$params->set('page_title', $title);
} elseif ($application->getCfg('sitename_pagetitles', 0) == 2) {
$title = JText::sprintf('JPAGETITLE', $params->get('page_title'), $application->getCfg('sitename'));
$params->set('page_title', $title);
}
}
$document->setTitle($params->get('page_title'));
// Set metadata
$metaDesc = '';
// Get metadata from the menu item (for Joomla 2.5+)
if ($menuItemMatchesK2Item) {
if (K2_JVERSION != '15') {
if ($params->get('menu-meta_description')) {
$document->setDescription($params->get('menu-meta_description'));
}
if ($params->get('menu-meta_keywords')) {
$document->setMetadata('keywords', $params->get('menu-meta_keywords'));
}
if ($params->get('robots')) {
$document->setMetadata('robots', $params->get('robots'));
}
// Menu page display options
if ($params->get('page_heading')) {
$params->set('page_title', $params->get('page_heading'));
}
$params->set('show_page_title', $params->get('show_page_heading'));
}
}
// --- Override metadata with data from the item ---
// Meta: Description
if ($item->metadesc) {
$metaDesc = filter_var($item->metadesc, FILTER_SANITIZE_STRING);
} else {
$metaDesc = preg_replace("#{(.*?)}(.*?){/(.*?)}#s", '', $itemTextBeforePlugins);
$metaDesc = filter_var($metaDesc, FILTER_SANITIZE_STRING);
$metaDesc = K2HelperUtilities::characterLimit($metaDesc, $params->get('metaDescLimit', 150));
}
if ($metaDesc) {
$document->setDescription($metaDesc);
}
// Meta: Keywords
if ($item->metakey) {
$document->setMetadata('keywords', $item->metakey);
} else {
if (isset($item->tags) && count($item->tags)) {
$tmp = array();
foreach ($item->tags as $tag) {
$tmp[] = $tag->name;
}
$document->setMetadata('keywords', implode(',', $tmp));
}
}
// Meta: Robots & author
if ($application->getCfg('MetaAuthor') == '1' && isset($item->author->name)) {
$document->setMetadata('author', $item->author->name);
}
$itemMetaData = class_exists('JParameter') ? new JParameter($item->metadata) : new JRegistry($item->metadata);
$itemMetaData = $itemMetaData->toArray();
foreach ($itemMetaData as $k => $v) {
if (($k == 'robots' || $k == 'author') && $v) {
$document->setMetadata($k, $v);
}
}
// Common for social meta tags
if ($item->metadesc) {
$socialMetaDesc = $item->metadesc;
} else {
$socialMetaDesc = preg_replace("#{(.*?)}(.*?){/(.*?)}#s", '', $itemTextBeforePlugins);
$socialMetaDesc = filter_var($socialMetaDesc, FILTER_SANITIZE_STRING);
}
// Set Facebook meta tags
if ($params->get('facebookMetatags', 1)) {
$document->setMetaData('og:url', $item->absoluteURL);
$document->setMetaData('og:type', 'article');
$document->setMetaData('og:title', filter_var($item->title, FILTER_SANITIZE_STRING));
$document->setMetaData('og:description', K2HelperUtilities::characterLimit($socialMetaDesc, 300)); // 300 chars limit for Facebook post sharing
$facebookImage = 'image'.$params->get('facebookImage', 'Medium');
if ($item->$facebookImage) {
$basename = basename($item->$facebookImage);
if (strpos($basename, '?t=')!==false) {
$tmpBasename = explode('?t=', $basename);
$basenameWithNoTimestamp = $tmpBasename[0];
} else {
$basenameWithNoTimestamp = $basename;
}
if (JFile::exists(JPATH_SITE.'/media/k2/items/cache/'.$basenameWithNoTimestamp)) {
$image = JURI::root().'media/k2/items/cache/'.$basename;
$document->setMetaData('og:image', $image);
$document->setMetaData('image', $image); // Generic meta
}
}
}
// Set Twitter meta tags
if ($params->get('twitterMetatags', 1)) {
$document->setMetaData('twitter:card', 'summary');
if ($params->get('twitterUsername')) {
$document->setMetaData('twitter:site', '@'.$params->get('twitterUsername'));
}
$document->setMetaData('twitter:title', filter_var($item->title, FILTER_SANITIZE_STRING));
$document->setMetaData('twitter:description', K2HelperUtilities::characterLimit($socialMetaDesc, 200)); // 200 chars limit for Twitter post sharing
$twitterImage = 'image'.$params->get('twitterImage', 'Medium');
if ($item->$twitterImage) {
$basename = basename($item->$twitterImage);
if (strpos($basename, '?t=')!==false) {
$tmpBasename = explode('?t=', $basename);
$basenameWithNoTimestamp = $tmpBasename[0];
} else {
$basenameWithNoTimestamp = $basename;
}
if (JFile::exists(JPATH_SITE.'/media/k2/items/cache/'.$basenameWithNoTimestamp)) {
$image = JURI::root().'media/k2/items/cache/'.$basename;
$document->setMetaData('twitter:image', $image);
if (!$params->get('facebookMetatags')) {
$document->setMetaData('image', $image); // Generic meta
}
$document->setMetaData('twitter:image:alt', (!empty($item->image_caption)) ? filter_var($item->image_caption, FILTER_SANITIZE_STRING) : filter_var($item->title, FILTER_SANITIZE_STRING));
}
}
}
// Get the frontend's language for use in social media buttons - use explicit variable references for future update flexibility
$getSiteLanguage = JFactory::getLanguage();
$languageTag = $getSiteLanguage->getTag();
$item->langTagForFB = str_replace('-', '_', $languageTag);
$item->langTagForTW = strtolower($languageTag);
$item->langTagForGP = $languageTag;
// Lookup template folders
$this->_addPath('template', JPATH_COMPONENT.'/templates');
$this->_addPath('template', JPATH_COMPONENT.'/templates/default');
$this->_addPath('template', JPATH_SITE.'/templates/'.$application->getTemplate().'/html/com_k2/templates');
$this->_addPath('template', JPATH_SITE.'/templates/'.$application->getTemplate().'/html/com_k2/templates/default');
$this->_addPath('template', JPATH_SITE.'/templates/'.$application->getTemplate().'/html/com_k2');
$this->_addPath('template', JPATH_SITE.'/templates/'.$application->getTemplate().'/html/com_k2/default');
if ($item->params->get('theme')) {
$this->_addPath('template', JPATH_COMPONENT.'/templates/'.$item->params->get('theme'));
$this->_addPath('template', JPATH_SITE.'/templates/'.$application->getTemplate().'/html/com_k2/templates/'.$item->params->get('theme'));
$this->_addPath('template', JPATH_SITE.'/templates/'.$application->getTemplate().'/html/com_k2/'.$item->params->get('theme'));
}
// Allow temporary template loading with ?template=
$template = JRequest::getCmd('template');
if (isset($template)) {
// Look for overrides in template folder (new K2 template structure)
$this->_addPath('template', JPATH_SITE.'/templates/'.$template.'/html/com_k2');
$this->_addPath('template', JPATH_SITE.'/templates/'.$template.'/html/com_k2/default');
if ($item->params->get('theme')) {
$this->_addPath('template', JPATH_SITE.'/templates/'.$template.'/html/com_k2/'.$item->params->get('theme'));
}
}
// Assign data
$this->assignRef('item', $item);
$this->assignRef('user', $user);
$this->assignRef('params', $item->params);
$this->assignRef('pagination', $pagination);
parent::display($tpl);
}
}
|
joomlaworks/k2
|
components/com_k2/views/item/view.html.php
|
PHP
|
gpl-2.0
| 28,705
|
package utils
import (
"encoding/binary"
)
const (
MaxMsgLen = 65536
)
//信息,一个简单的[]byte信息结构 限制最大长度65536
type SimpleMsg struct {
MsgSize uint32
MsgSender uint32
MsgReceiver uint32 // 0:broadcast
MsgBody []byte //原始数据,用于转发
}
//创建一条信息
//1.[]byte格式:[4字节长度 + 4字节发送人id + 4字节接受人id + 正文] 其中长度 = 12 + 正文长度
//2.长度不能超过65536字节
//3.socket连接成功3秒内要发身份验证消息,格式:没有正文,发送人id为验证id,接收人id可以任意
//4.验证成功后发送消息根据接收人id分发,从1开始,可以自己给自己发;如果接收人id为0,表示群发该消息,但是不会发给自己。
func MakeNewSimpleMsg() *SimpleMsg {
return &SimpleMsg{
MsgSize: 0,
MsgSender: 0,
MsgReceiver: 0,
MsgBody: []byte{},
}
}
//[]byte -> SimpleMsg
func (this *SimpleMsg) FromBytes(buf []byte) *SimpleMsg {
this.MsgSize = 0
this.MsgSender = 0
this.MsgReceiver = 0
this.MsgBody = []byte{}
if len(buf) < 12 {
return this
} else {
this.MsgSize = binary.LittleEndian.Uint32(buf[0:4])
if int(this.MsgSize) == len(buf) {
this.MsgSender = binary.LittleEndian.Uint32(buf[4:8])
this.MsgReceiver = binary.LittleEndian.Uint32(buf[8:12])
//copy(this.MsgBody, buf)
this.MsgBody = append(this.MsgBody, buf...)
} else {
this.MsgSize = 0
}
}
return this
}
//string -> SimpleMsg
func (this *SimpleMsg) FromString(fromId int, toId int, msg string) *SimpleMsg {
this.MsgSender = uint32(fromId)
this.MsgReceiver = uint32(toId)
dataFrom := make([]byte, 4)
dataTo := make([]byte, 4)
dataSize := make([]byte, 4)
dataBody := []byte(msg)
this.MsgSize = uint32(len(dataBody) + 12)
binary.LittleEndian.PutUint32(dataFrom, this.MsgSender)
binary.LittleEndian.PutUint32(dataTo, this.MsgReceiver)
binary.LittleEndian.PutUint32(dataSize, this.MsgSize)
data := []byte{}
data = append(data, dataSize...)
data = append(data, dataFrom...)
data = append(data, dataTo...)
data = append(data, dataBody...)
this.MsgBody = data
return this
}
//SimpleMsg -> []byte
func (this *SimpleMsg) ToData() []byte {
return this.MsgBody
}
//SimpleMsg.MsgBody -> string
func (this *SimpleMsg) ToString() string {
return string(this.MsgBody[12:])
}
//数据加密 后续实现
func (this *SimpleMsg) EnCode() {
}
//数据解密 后续实现
func (this *SimpleMsg) DeCode() {
}
|
rjcb99/IPCServer
|
src/utils/simpleMsg.go
|
GO
|
gpl-2.0
| 2,468
|
<?php
/**
* Chunk Brazilian Portuguese lexicon topic
*
* @language br
* @package modx
* @subpackage lexicon
*/
$_lang['chunk'] = 'Chunk';
$_lang['chunk_desc_category'] = 'A categoria este Chunk pertence ';
$_lang['chunk_desc_description'] = 'Uma breve descrição deste chunk.';
$_lang['chunk_desc_name'] = 'O nome deste chunk. Ele estará disponível usando a tag de [[$nomeDoChunk]].';
$_lang['chunk_code'] = 'Código do Chunk (HTML)';
$_lang['chunk_desc'] = 'Descrição';
$_lang['chunk_delete_confirm'] = 'Você tem certeza que deseja excluir este chunk?';
$_lang['chunk_duplicate_confirm'] = 'Você tem certeza que deseja duplicar este chunk?';
$_lang['chunk_err_duplicate'] = 'Erro ao duplicar chunk.';
$_lang['chunk_err_exists_name'] = 'Já existe um chunk com o nome "[[+name]]".';
$_lang['chunk_err_invalid_name'] = 'O nome do Chunk é inválido.';
$_lang['chunk_err_locked'] = 'Chunk está trancado.';
$_lang['chunk_err_remove'] = 'Um erro ocorreu na tentativa de remover este chunk.';
$_lang['chunk_err_save'] = 'Um erro ocorreu na tentativa de salvar este chunk.';
$_lang['chunk_err_nf'] = 'Chunk não encontrado!';
$_lang['chunk_err_nfs'] = 'Chunk não encontrado com id: [[+id]]';
$_lang['chunk_err_ns'] = 'Chunk não especificado.';
$_lang['chunk_err_ns_name'] = 'Por favor especifique um nome.';
$_lang['chunk_lock'] = 'Trancar chunk para edição';
$_lang['chunk_lock_msg'] = 'Usuários deve ter o atributo \'edit_locked\' para editar este chunk.';
$_lang['chunk_msg'] = 'Here you can add/edit chunks. Remember; chunks are \'raw\' HTML code; so any PHP code won\'t be processed.';
$_lang['chunk_name'] = 'Nome do Chunk';
$_lang['chunk_new'] = 'Novo Chunk';
$_lang['chunk_properties'] = 'Propriedades Padrão';
$_lang['chunk_title'] = 'Criar/editar chunk';
$_lang['chunk_untitled'] = 'Chunk Sem Título';
$_lang['chunks'] = 'Chunks';
|
wshearn/openshift-quickstart-modx
|
php/core/lexicon/pt-br/chunk.inc.php
|
PHP
|
gpl-2.0
| 1,855
|
<?php
if(mo_openid_is_customer_registered()) {
/*
* Login Widget
*
*/
class mo_openid_login_wid extends WP_Widget {
public function __construct() {
parent::__construct(
'mo_openid_login_wid',
'miniOrange Social Login Widget',
array( 'description' => __( 'Login using Social Apps like Google, Facebook, LinkedIn, Microsoft, Instagram.', 'flw' ), )
);
}
public function widget( $args, $instance ) {
extract( $args );
echo $args['before_widget'];
$this->openidloginForm();
echo $args['after_widget'];
}
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['wid_title'] = strip_tags( $new_instance['wid_title'] );
return $instance;
}
public function openidloginForm(){
global $post;
$this->error_message();
$selected_theme = get_option('mo_openid_login_theme');
$appsConfigured = get_option('mo_openid_google_enable') | get_option('mo_openid_salesforce_enable') | get_option('mo_openid_facebook_enable') | get_option('mo_openid_linkedin_enable') | get_option('mo_openid_instagram_enable') | get_option('mo_openid_amazon_enable') | get_option('mo_openid_windowslive_enable') | get_option('mo_openid_twitter_enable') | get_option('mo_openid_vkontakte_enable');
$spacebetweenicons = get_option('mo_login_icon_space');
$customWidth = get_option('mo_login_icon_custom_width');
$customHeight = get_option('mo_login_icon_custom_height');
$customSize = get_option('mo_login_icon_custom_size');
$customBackground = get_option('mo_login_icon_custom_color');
$customTheme = get_option('mo_openid_login_custom_theme');
$customTextofTitle = get_option('mo_openid_login_button_customize_text');
$customBoundary = get_option('mo_login_icon_custom_boundary');
if( ! is_user_logged_in() ) {
if( $appsConfigured ) {
$this->mo_openid_load_login_script();
?>
<a href="http://miniorange.com/cloud-identity-broker-service" style="display:none;"></a>
<a href="http://miniorange.com/strong_auth" style="display:none;"></a>
<a href="http://miniorange.com/single-sign-on-sso" style="display:none;"></a>
<a href="http://miniorange.com/fraud" style="display:none;"></a>
<div class="mo-openid-app-icons">
<p><?php echo get_option('mo_openid_login_widget_customize_text'); ?>
</p>
<?php
if($customTheme == 'default'){
if( get_option('mo_openid_facebook_enable') ) {
if($selected_theme == 'longbutton'){
?> <a onClick="moOpenIdLogin('facebook');" style="width:<?php echo $customWidth ?>px !important;padding-top:<?php echo $customHeight-29 ?>px !important;padding-bottom:<?php echo $customHeight-29 ?>px !important;margin-bottom:<?php echo $spacebetweenicons-5 ?>px !important;border-radius:<?php echo $customBoundary ?>px !important;" class="btn btn-block btn-social btn-facebook btn-custom-size login-button" > <i style="padding-top:<?php echo $customHeight-35 ?>px !important" class="fa fa-facebook"></i><?php
echo get_option('mo_openid_login_button_customize_text'); ?> Facebook</a>
<?php }
else{ ?>
<a title="<?php echo $customTextofTitle ?> Facebook" onClick="moOpenIdLogin('facebook');"><img alt='Facebook' style="width:<?php echo $customSize?>px !important;height:<?php echo $customSize?>px !important;margin-left:<?php echo $spacebetweenicons-4?>px !important" src="<?php echo plugins_url( 'includes/images/icons/facebook.png', __FILE__ )?>" class="<?php echo $selected_theme; ?> login-button" ></a>
<?php }
}
if( get_option('mo_openid_google_enable') ) {
if($selected_theme == 'longbutton'){
?>
<a onClick="moOpenIdLogin('google');" style='width:<?php echo $customWidth ?>px !important;padding-top:<?php echo $customHeight-29 ?>px !important;padding-bottom:<?php echo $customHeight-29 ?>px !important;margin-bottom:<?php echo $spacebetweenicons-5 ?>px !important;border-radius:<?php echo $customBoundary ?>px !important;' class='btn btn-block btn-social btn-google btn-custom-size login-button' > <i style='padding-top:<?php echo $customHeight-35 ?>px !important' class='fa fa-google-plus'></i><?php
echo get_option('mo_openid_login_button_customize_text'); ?> Google</a>
<?php }
else{ ?>
<a onClick="moOpenIdLogin('google');" title="<?php echo $customTextofTitle ?> Google" ><img alt='Google' style="width:<?php echo $customSize?>px !important;height:<?php echo $customSize?>px !important;margin-left:<?php echo $spacebetweenicons-4?>px !important" src="<?php echo plugins_url( 'includes/images/icons/google.png', __FILE__ )?>" class="<?php echo $selected_theme; ?> login-button" ></a>
<?php
}
}
if( get_option('mo_openid_vkontakte_enable') ) {
if($selected_theme == 'longbutton'){
?>
<a onClick="moOpenIdLogin('vkontakte');" style='width:<?php echo $customWidth ?>px !important;padding-top:<?php echo $customHeight-29 ?>px !important;padding-bottom:<?php echo $customHeight-29 ?>px !important;margin-bottom:<?php echo $spacebetweenicons-5 ?>px !important;border-radius:<?php echo $customBoundary ?>px !important;' class='btn btn-block btn-social btn-vk btn-custom-size login-button' > <i style='padding-top:<?php echo $customHeight-35 ?>px !important' class='fa fa-vk'></i><?php
echo get_option('mo_openid_login_button_customize_text'); ?> Vkontakte</a>
<?php }
else{ ?>
<a onClick="moOpenIdLogin('vkontakte');" title="<?php echo $customTextofTitle ?> Vkontakte" ><img alt='Vkontakte' style="width:<?php echo $customSize?>px !important;height:<?php echo $customSize?>px !important;margin-left:<?php echo $spacebetweenicons-4?>px !important" src="<?php echo plugins_url( 'includes/images/icons/vk.png', __FILE__ )?>" class="<?php echo $selected_theme; ?> login-button" ></a>
<?php
}
}
if( get_option('mo_openid_twitter_enable') ) {
if($selected_theme == 'longbutton'){
?> <a onClick="moOpenIdLogin('twitter');" style="width:<?php echo $customWidth ?>px !important;padding-top:<?php echo $customHeight-29 ?>px !important;padding-bottom:<?php echo $customHeight-29 ?>px !important;margin-bottom:<?php echo $spacebetweenicons-5 ?>px !important;border-radius:<?php echo $customBoundary ?>px !important;" class="btn btn-block btn-social btn-twitter btn-custom-size login-button" > <i style="padding-top:<?php echo $customHeight-35 ?>px !important" class="fa fa-twitter"></i><?php
echo get_option('mo_openid_login_button_customize_text'); ?> Twitter</a>
<?php }
else{ ?>
<a title="<?php echo $customTextofTitle ?> Twitter" onClick="moOpenIdLogin('twitter');"><img alt='Twitter' style="width:<?php echo $customSize?>px !important;height:<?php echo $customSize?>px !important;margin-left:<?php echo $spacebetweenicons-4?>px !important" src="<?php echo plugins_url( 'includes/images/icons/twitter.png', __FILE__ )?>" class="<?php echo $selected_theme; ?> login-button"></a>
<?php }
}
if( get_option('mo_openid_linkedin_enable') ) {
if($selected_theme == 'longbutton'){ ?>
<a onClick="moOpenIdLogin('linkedin');" style="width:<?php echo $customWidth ?>px !important;padding-top:<?php echo $customHeight-29 ?>px !important;padding-bottom:<?php echo $customHeight-29 ?>px !important;margin-bottom:<?php echo $spacebetweenicons-5 ?>px !important;border-radius:<?php echo $customBoundary ?>px !important;" class="btn btn-block btn-social btn-linkedin btn-custom-size login-button" > <i style="padding-top:<?php echo $customHeight-35 ?>px !important" class="fa fa-linkedin"></i><?php
echo get_option('mo_openid_login_button_customize_text'); ?> LinkedIn</a>
<?php }
else{ ?>
<a title="<?php echo $customTextofTitle ?> LinkedIn" onClick="moOpenIdLogin('linkedin');"><img alt='LinkedIn' style="width:<?php echo $customSize?>px !important;height:<?php echo $customSize?>px !important;margin-left:<?php echo $spacebetweenicons-4?>px !important" src="<?php echo plugins_url( 'includes/images/icons/linkedin.png', __FILE__ )?>" class="<?php echo $selected_theme; ?> login-button" ></a>
<?php }
}if( get_option('mo_openid_instagram_enable') ) {
if($selected_theme == 'longbutton'){ ?>
<a onClick="moOpenIdLogin('instagram');" style="width:<?php echo $customWidth ?>px !important;padding-top:<?php echo $customHeight-29 ?>px !important;padding-bottom:<?php echo $customHeight-29 ?>px !important;margin-bottom:<?php echo $spacebetweenicons-5 ?>px !important;border-radius:<?php echo $customBoundary ?>px !important;" class="btn btn-block btn-social btn-instagram btn-custom-size login-button" > <i style="padding-top:<?php echo $customHeight-35 ?>px !important" class="fa fa-instagram"></i><?php
echo get_option('mo_openid_login_button_customize_text'); ?> Instagram</a>
<?php }
else{ ?>
<a title="<?php echo $customTextofTitle ?> Instagram" onClick="moOpenIdLogin('instagram');"><img alt='Instagram' style="width:<?php echo $customSize?>px !important;height:<?php echo $customSize?>px !important;margin-left:<?php echo $spacebetweenicons-4?>px !important" src="<?php echo plugins_url( 'includes/images/icons/instagram.png', __FILE__ )?>" class="<?php echo $selected_theme; ?> login-button"></a>
<?php }
}if( get_option('mo_openid_amazon_enable') ) {
if($selected_theme == 'longbutton'){
?> <a onClick="moOpenIdLogin('amazon');" style="width:<?php echo $customWidth ?>px !important;padding-top:<?php echo $customHeight-29 ?>px !important;padding-bottom:<?php echo $customHeight-29 ?>px !important;margin-bottom:<?php echo $spacebetweenicons-5 ?>px !important;border-radius:<?php echo $customBoundary ?>px !important;" class="btn btn-block btn-social btn-soundcloud btn-custom-size login-button" > <i style="padding-top:<?php echo $customHeight-35 ?>px !important" class="fa fa-amazon"></i><?php
echo get_option('mo_openid_login_button_customize_text'); ?> Amazon</a>
<?php }
else{ ?>
<a title="<?php echo $customTextofTitle ?> Amazon" onClick="moOpenIdLogin('amazon');"><img alt='Amazon' style="width:<?php echo $customSize?>px !important;height:<?php echo $customSize?>px !important;margin-left:<?php echo $spacebetweenicons-4?>px !important" src="<?php echo plugins_url( 'includes/images/icons/amazon.png', __FILE__ )?>" class="<?php echo $selected_theme; ?> login-button"></a>
<?php }
}if( get_option('mo_openid_salesforce_enable') ) {
if($selected_theme == 'longbutton'){
?> <a onClick="moOpenIdLogin('salesforce');" style="width:<?php echo $customWidth ?>px !important;padding-top:<?php echo $customHeight-29 ?>px !important;padding-bottom:<?php echo $customHeight-29 ?>px !important;margin-bottom:<?php echo $spacebetweenicons-5 ?>px !important;border-radius:<?php echo $customBoundary ?>px !important;" class="btn btn-block btn-social btn-vimeo btn-custom-size login-button" > <i style="padding-top:<?php echo $customHeight-35 ?>px !important" class="fa fa-cloud"></i> <?php
echo get_option('mo_openid_login_button_customize_text'); ?> Salesforce</a>
<?php }
else{ ?>
<a title="<?php echo $customTextofTitle ?> Salesforce" onClick="moOpenIdLogin('salesforce');"><img alt='Salesforce' style="width:<?php echo $customSize?>px !important;height:<?php echo $customSize?>px !important;margin-left:<?php echo $spacebetweenicons-4?>px !important" src="<?php echo plugins_url( 'includes/images/icons/salesforce.png', __FILE__ )?>" class="<?php echo $selected_theme; ?> login-button" ></a>
<?php }
}if( get_option('mo_openid_windowslive_enable') ) {
if($selected_theme == 'longbutton'){
?> <a onClick="moOpenIdLogin('windowslive');" style="width:<?php echo $customWidth ?>px !important;padding-top:<?php echo $customHeight-29 ?>px !important;padding-bottom:<?php echo $customHeight-29 ?>px !important;margin-bottom:<?php echo $spacebetweenicons-5 ?>px !important;border-radius:<?php echo $customBoundary ?>px !important;" class="btn btn-block btn-social btn-microsoft btn-custom-size login-button" > <i style="padding-top:<?php echo $customHeight-35 ?>px !important" class="fa fa-windows"></i><?php
echo get_option('mo_openid_login_button_customize_text'); ?> Microsoft</a>
<?php }
else{ ?>
<a title="<?php echo $customTextofTitle ?> Microsoft" onClick="moOpenIdLogin('windowslive');"><img alt='Windowslive' style="width:<?php echo $customSize?>px !important;height:<?php echo $customSize?>px !important;margin-left:<?php echo $spacebetweenicons-4?>px !important" src="<?php echo plugins_url( 'includes/images/icons/windowslive.png', __FILE__ )?>" class="<?php echo $selected_theme; ?> login-button"></a>
<?php }
}
}
?>
<?php
if($customTheme == 'custom'){
if( get_option('mo_openid_facebook_enable') ) {
if($selected_theme == 'longbutton'){
?> <a onClick="moOpenIdLogin('facebook');" style="width:<?php echo $customWidth ?>px !important;padding-top:<?php echo $customHeight-29 ?>px !important;padding-bottom:<?php echo $customHeight-29 ?>px !important;margin-bottom:<?php echo $spacebetweenicons-5 ?>px !important;background:<?php echo "#".$customBackground?> !important;border-radius:<?php echo $customBoundary ?>px !important;" class="btn btn-block btn-social btn-facebook btn-custom-size login-button" > <i style="padding-top:<?php echo $customHeight-35 ?>px !important" class="fa fa-facebook"></i><?php
echo get_option('mo_openid_login_button_customize_text'); ?> Facebook</a>
<?php }
else{ ?>
<a onClick="moOpenIdLogin('facebook');" title="<?php echo $customTextofTitle ?> Facebook"><i style="width:<?php echo $customSize?>px !important;height:<?php echo $customSize?>px !important;margin-left:<?php echo $spacebetweenicons-4?>px !important;background:<?php echo "#".$customBackground?> !important;font-size:<?php echo $customSize-16?>px !important;" class="fa fa-facebook custom-login-button <?php echo $selected_theme; ?>" ></i></a>
<?php }
}
if( get_option('mo_openid_google_enable') ) {
if($selected_theme == 'longbutton'){
?>
<a onClick="moOpenIdLogin('google');" style="width:<?php echo $customWidth ?>px !important;padding-top:<?php echo $customHeight-29 ?>px !important;padding-bottom:<?php echo $customHeight-29 ?>px !important;margin-bottom:<?php echo $spacebetweenicons-5 ?>px !important; background:<?php echo "#".$customBackground?> !important;border-radius:<?php echo $customBoundary ?>px !important;" class="btn btn-block btn-social btn-customtheme btn-custom-size login-button" > <i style="padding-top:<?php echo $customHeight-35 ?>px !important" class="fa fa-google-plus"></i><?php
echo get_option('mo_openid_login_button_customize_text'); ?> Google</a>
<?php }
else{ ?>
<a onClick="moOpenIdLogin('google');" title="<?php echo $customTextofTitle ?> Google"><i style="width:<?php echo $customSize?>px !important;height:<?php echo $customSize?>px !important;margin-left:<?php echo $spacebetweenicons-4?>px !important;background:<?php echo "#".$customBackground?> !important;font-size:<?php echo $customSize-16?>px !important;" class="fa fa-google-plus custom-login-button <?php echo $selected_theme; ?>" ></i></a>
<?php
}
}
if( get_option('mo_openid_vkontakte_enable') ) {
if($selected_theme == 'longbutton'){
?>
<a onClick="moOpenIdLogin('vkontakte');" style="width:<?php echo $customWidth ?>px !important;padding-top:<?php echo $customHeight-29 ?>px !important;padding-bottom:<?php echo $customHeight-29 ?>px !important;margin-bottom:<?php echo $spacebetweenicons-5 ?>px !important; background:<?php echo "#".$customBackground?> !important;border-radius:<?php echo $customBoundary ?>px !important;" class="btn btn-block btn-social btn-customtheme btn-custom-size login-button" > <i style="padding-top:<?php echo $customHeight-35 ?>px !important" class="fa fa-vk"></i><?php
echo get_option('mo_openid_login_button_customize_text'); ?> Vkontakte</a>
<?php }
else{ ?>
<a onClick="moOpenIdLogin('vkontakte');" title="<?php echo $customTextofTitle ?> Vkontakte"><i style="width:<?php echo $customSize?>px !important;height:<?php echo $customSize?>px !important;margin-left:<?php echo $spacebetweenicons-4?>px !important;background:<?php echo "#".$customBackground?> !important;font-size:<?php echo $customSize-16?>px !important;" class="fa fa-vk custom-login-button <?php echo $selected_theme; ?>" ></i></a>
<?php
}
}
if( get_option('mo_openid_twitter_enable') ) {
if($selected_theme == 'longbutton'){
?>
<a onClick="moOpenIdLogin('twitter');" style="width:<?php echo $customWidth ?>px !important;padding-top:<?php echo $customHeight-29 ?>px !important;padding-bottom:<?php echo $customHeight-29 ?>px !important;margin-bottom:<?php echo $spacebetweenicons-5 ?>px !important; background:<?php echo "#".$customBackground?> !important;border-radius:<?php echo $customBoundary ?>px !important;" class="btn btn-block btn-social btn-customtheme btn-custom-size login-button" > <i style="padding-top:<?php echo $customHeight-35 ?>px !important" class="fa fa-twitter"></i><?php
echo get_option('mo_openid_login_button_customize_text'); ?> Twitter</a>
<?php }
else{ ?>
<a onClick="moOpenIdLogin('twitter');" title="<?php echo $customTextofTitle ?> Twitter"><i style="width:<?php echo $customSize?>px !important;height:<?php echo $customSize?>px !important;margin-left:<?php echo $spacebetweenicons-4?>px !important;background:<?php echo "#".$customBackground?> !important;font-size:<?php echo $customSize-16?>px !important;" class="fa fa-twitter custom-login-button <?php echo $selected_theme; ?>" ></i></a>
<?php
}
}
if( get_option('mo_openid_linkedin_enable') ) {
if($selected_theme == 'longbutton'){ ?>
<a onClick="moOpenIdLogin('linkedin');" style="width:<?php echo $customWidth ?>px !important;padding-top:<?php echo $customHeight-29 ?>px !important;padding-bottom:<?php echo $customHeight-29 ?>px !important;margin-bottom:<?php echo $spacebetweenicons-5 ?>px !important;background:<?php echo "#".$customBackground?> !important;border-radius:<?php echo $customBoundary ?>px !important;" class="btn btn-block btn-social btn-linkedin btn-custom-size login-button" > <i style="padding-top:<?php echo $customHeight-35 ?>px !important" class="fa fa-linkedin"></i><?php
echo get_option('mo_openid_login_button_customize_text'); ?> LinkedIn</a>
<?php }
else{ ?>
<a onClick="moOpenIdLogin('linkedin');" title="<?php echo $customTextofTitle ?> LinkedIn"><i style="width:<?php echo $customSize?>px !important;height:<?php echo $customSize?>px !important;margin-left:<?php echo $spacebetweenicons-4?>px !important;background:<?php echo "#".$customBackground?> !important;font-size:<?php echo $customSize-16?>px !important;" class="fa fa-linkedin custom-login-button <?php echo $selected_theme; ?>" ></i></a>
<?php }
}if( get_option('mo_openid_instagram_enable') ) {
if($selected_theme == 'longbutton'){ ?>
<a onClick="moOpenIdLogin('instagram');" style="width:<?php echo $customWidth ?>px !important;padding-top:<?php echo $customHeight-29 ?>px !important;padding-bottom:<?php echo $customHeight-29 ?>px !important;margin-bottom:<?php echo $spacebetweenicons-5 ?>px !important;background:<?php echo "#".$customBackground?> !important;background:<?php echo "#".$customBackground?> !important;border-radius:<?php echo $customBoundary ?>px !important;" class="btn btn-block btn-social btn-instagram btn-custom-size login-button" > <i style="padding-top:<?php echo $customHeight-35 ?>px !important" class="fa fa-instagram"></i><?php
echo get_option('mo_openid_login_button_customize_text'); ?> Instagram</a>
<?php }
else{ ?>
<a onClick="moOpenIdLogin('instagram');" title="<?php echo $customTextofTitle ?> Instagram"><i style="width:<?php echo $customSize?>px !important;height:<?php echo $customSize?>px !important;margin-left:<?php echo $spacebetweenicons-4?>px !important;background:<?php echo "#".$customBackground?> !important;font-size:<?php echo $customSize-16?>px !important;" class="fa fa-instagram custom-login-button <?php echo $selected_theme; ?>"></i></a>
<?php }
}if( get_option('mo_openid_amazon_enable') ) {
if($selected_theme == 'longbutton'){
?> <a onClick="moOpenIdLogin('amazon');" style="width:<?php echo $customWidth ?>px !important;padding-top:<?php echo $customHeight-29 ?>px !important;padding-bottom:<?php echo $customHeight-29 ?>px !important;margin-bottom:<?php echo $spacebetweenicons-5 ?>px !important;background:<?php echo "#".$customBackground?> !important;border-radius:<?php echo $customBoundary ?>px !important;" class="btn btn-block btn-social btn-linkedin btn-custom-size login-button" ><i style="padding-top:<?php echo $customHeight-35 ?>px !important" class="fa fa-amazon"></i><?php
echo get_option('mo_openid_login_button_customize_text'); ?> Amazon</a>
<?php }
else{ ?>
<a onClick="moOpenIdLogin('amazon');" title="<?php echo $customTextofTitle ?> Amazon"><i style="width:<?php echo $customSize?>px !important;height:<?php echo $customSize?>px !important;margin-left:<?php echo $spacebetweenicons-4?>px !important;background:<?php echo "#".$customBackground?> !important;font-size:<?php echo $customSize-16?>px !important;" class="fa fa-amazon custom-login-button <?php echo $selected_theme; ?>"></i></a>
<?php }
}if( get_option('mo_openid_salesforce_enable') ) {
if($selected_theme == 'longbutton'){
?> <a onClick="moOpenIdLogin('salesforce');" style="width:<?php echo $customWidth ?>px !important;padding-top:<?php echo $customHeight-29 ?>px !important;padding-bottom:<?php echo $customHeight-29 ?>px !important;margin-bottom:<?php echo $spacebetweenicons-5 ?>px !important;background:<?php echo "#".$customBackground?> !important;border-radius:<?php echo $customBoundary ?>px !important;" class="btn btn-block btn-social btn-linkedin btn-custom-size login-button" ><i style="padding-top:<?php echo $customHeight-35 ?>px !important" class="fa fa-cloud"></i> <?php
echo get_option('mo_openid_login_button_customize_text'); ?> Salesforce</a>
<?php }
else{ ?>
<a onClick="moOpenIdLogin('salesforce');" title="<?php echo $customTextofTitle ?> Salesforce"><i style="width:<?php echo $customSize?>px !important;height:<?php echo $customSize?>px !important;margin-left:<?php echo $spacebetweenicons-4?>px !important;background:<?php echo "#".$customBackground?> !important;font-size:<?php echo $customSize-16?>px " class="fa fa-cloud custom-login-button <?php echo $selected_theme; ?>" ></i></a>
<?php }
}if( get_option('mo_openid_windowslive_enable') ) {
if($selected_theme == 'longbutton'){
?> <a onClick="moOpenIdLogin('windowslive');" style="width:<?php echo $customWidth ?>px !important;padding-top:<?php echo $customHeight-29 ?>px !important;padding-bottom:<?php echo $customHeight-29 ?>px !important;margin-bottom:<?php echo $spacebetweenicons-5 ?>px !important;background:<?php echo "#".$customBackground?> !important;border-radius:<?php echo $customBoundary ?>px !important;" class="btn btn-block btn-social btn-microsoft btn-custom-size login-button" > <i style="padding-top:<?php echo $customHeight-35 ?>px !important" class="fa fa-windows"></i><?php
echo get_option('mo_openid_login_button_customize_text'); ?> Microsoft</a>
<?php }
else{ ?>
<a onClick="moOpenIdLogin('windowslive');" title="<?php echo $customTextofTitle ?> Microsoft"><i style="width:<?php echo $customSize?>px !important;height:<?php echo $customSize?>px !important;margin-left:<?php echo $spacebetweenicons-4?>px !important;background:<?php echo "#".$customBackground?> !important;font-size:<?php echo $customSize-16?>px !important;" class=" fa fa-windows custom-login-button <?php echo $selected_theme; ?>"></i></a>
<?php }
}
}
?>
<br>
</div> <br>
<?php
} else {
?>
<div>No apps configured. Please contact your administrator.</div>
<?php
}
}else {
global $current_user;
get_currentuserinfo();
$link_with_username = __('Howdy, ', 'flw') . $current_user->display_name;
?>
<div id="logged_in_user" class="mo_openid_login_wid">
<li><?php echo $link_with_username;?> | <a href="<?php echo wp_logout_url( site_url() ); ?>" title="<?php _e('Logout','flw');?>"><?php _e('Logout','flw');?></a></li>
</div>
<?php
}
}
public function openidloginFormShortCode( $atts ){
global $post;
$html = '';
$this->error_message();
$selected_theme = isset( $atts['shape'] )? $atts['shape'] : get_option('mo_openid_login_theme');
$appsConfigured = get_option('mo_openid_google_enable') | get_option('mo_openid_salesforce_enable') | get_option('mo_openid_facebook_enable') | get_option('mo_openid_linkedin_enable') | get_option('mo_openid_instagram_enable') | get_option('mo_openid_amazon_enable') | get_option('mo_openid_windowslive_enable') |get_option('mo_openid_twitter_enable') | get_option('mo_openid_vkontakte_enable');
$spacebetweenicons = isset( $atts['space'] )? $atts['space'] : get_option('mo_login_icon_space');
$customWidth = isset( $atts['width'] )? $atts['width'] : get_option('mo_login_icon_custom_width');
$customHeight = isset( $atts['height'] )? $atts['height'] : get_option('mo_login_icon_custom_height');
$customSize = isset( $atts['size'] )? $atts['size'] : get_option('mo_login_icon_custom_size');
$customBackground = isset( $atts['background'] )? $atts['background'] : get_option('mo_login_icon_custom_color');
$customTheme = isset( $atts['theme'] )? $atts['theme'] : get_option('mo_openid_login_custom_theme');
$customText = get_option('mo_openid_login_widget_customize_text');
$buttonText = get_option('mo_openid_login_button_customize_text');
$customTextofTitle = get_option('mo_openid_login_button_customize_text');
$logoutUrl = wp_logout_url( site_url() );
$customBoundary = isset( $atts['edge'] )? $atts['edge'] : get_option('mo_login_icon_custom_boundary');
if($selected_theme == 'longbuttonwithtext'){
$selected_theme = 'longbutton';
}
if($customTheme == 'custombackground'){
$customTheme = 'custom';
}
if( ! is_user_logged_in() ) {
if( $appsConfigured ) {
$this->mo_openid_load_login_script();
$html .= "<a href='http://miniorange.com/cloud-identity-broker-service' style='display:none;'></a>
<a href='http://miniorange.com/strong_auth' style='display:none;'></a>
<a href='http://miniorange.com/single-sign-on-sso' style='display:none;'></a>
<a href='http://miniorange.com/fraud' style='display:none;'></a>
<div class='mo-openid-app-icons'>
<p> $customText</p>";
if($customTheme == 'default'){
if( get_option('mo_openid_facebook_enable') ) {
if($selected_theme == 'longbutton'){
$html .= "<a style='width: " . $customWidth . "px !important;padding-top:" . ($customHeight-29) . "px !important;padding-bottom:" . ($customHeight-29) . "px !important;margin-bottom: " . ($spacebetweenicons-5) . "px !important;border-radius: " .$customBoundary. "px !important;' class='btn btn-block btn-social btn-facebook btn-custom-dec login-button' onClick='moOpenIdLogin(" . '"facebook"' . ");'> <i style='padding-top:" . ($customHeight-35) . "px !important' class='fa fa-facebook'></i>" . $buttonText . " Facebook</a>"; }
else{
$html .= "<a title= ' ".$customTextofTitle." Facebook' onClick='moOpenIdLogin(" . '"facebook"' . ");' ><img alt='Facebook' style='width:" . $customSize ."px !important;height: " . $customSize ."px !important;margin-left: " . ($spacebetweenicons-4) ."px !important' src='" . plugins_url( 'includes/images/icons/facebook.png', __FILE__ ) . "' class='login-button " .$selected_theme . "' ></a>";
}
}
if( get_option('mo_openid_google_enable') ) {
if($selected_theme == 'longbutton'){
$html .= "<a style='width: " . $customWidth . "px !important;padding-top:" . ($customHeight-29) . "px !important;padding-bottom:" . ($customHeight-29) . "px !important;margin-bottom: " . ($spacebetweenicons-5) . "px !important;border-radius: " .$customBoundary ."px !important;' class='btn btn-block btn-social btn-google btn-custom-dec login-button' onClick='moOpenIdLogin(" . '"google"' . ");'> <i style='padding-top:" . ($customHeight-35) . "px !important' class='fa fa-google-plus'></i>" . $buttonText . " Google</a>";
}
else{
$html .= "<a onClick='moOpenIdLogin(" . '"google"' . ");' title= ' ".$customTextofTitle." Google'><img alt='Google' style='width:" . $customSize ."px !important;height: " . $customSize ."px !important;margin-left: " . ($spacebetweenicons-4) ."px !important' src='" . plugins_url( 'includes/images/icons/google.png', __FILE__ ) . "' class='login-button " .$selected_theme . "' ></a>";
}
}
if( get_option('mo_openid_vkontakte_enable') ) {
if($selected_theme == 'longbutton'){
$html .= "<a style='width: " . $customWidth . "px !important;padding-top:" . ($customHeight-29) . "px !important;padding-bottom:" . ($customHeight-29) . "px !important;margin-bottom: " . ($spacebetweenicons-5) . "px !important;border-radius: " .$customBoundary ."px !important;' class='btn btn-block btn-social btn-vk btn-custom-dec login-button' onClick='moOpenIdLogin(" . '"vkontakte"' . ");'> <i style='padding-top:" . ($customHeight-35) . "px !important' class='fa fa-vk'></i>" . $buttonText . " Vkontakte</a>";
}
else{
$html .= "<a onClick='moOpenIdLogin(" . '"vkontakte"' . ");' title= ' ".$customTextofTitle." Vkontakte'><img alt='Vkontakte' style='width:" . $customSize ."px !important;height: " . $customSize ."px !important;margin-left: " . ($spacebetweenicons-4) ."px !important' src='" . plugins_url( 'includes/images/icons/vk.png', __FILE__ ) . "' class='login-button " .$selected_theme . "' ></a>";
}
}
if( get_option('mo_openid_twitter_enable') ) {
if($selected_theme == 'longbutton'){
$html .= "<a style='width: " . $customWidth . "px !important;padding-top:" . ($customHeight-29) . "px !important;padding-bottom:" . ($customHeight-29) . "px !important;margin-bottom: " . ($spacebetweenicons-5) . "px !important;border-radius: " .$customBoundary ."px !important;' class='btn btn-block btn-social btn-twitter btn-custom-dec login-button' onClick='moOpenIdLogin(" . '"twitter"' . ");'> <i style='padding-top:" . ($customHeight-35) . "px !important' class='fa fa-twitter'></i>" . $buttonText . " Twitter</a>"; }
else{
$html .= "<a title= ' ".$customTextofTitle." Twitter' onClick='moOpenIdLogin(" . '"twitter"' . ");' ><img alt='Twitter' style='width:" . $customSize ."px !important;height: " . $customSize ."px !important;margin-left: " . ($spacebetweenicons-4) ."px !important' src='" . plugins_url( 'includes/images/icons/twitter.png', __FILE__ ) . "' class='login-button " .$selected_theme . "' ></a>";
}
}
if( get_option('mo_openid_linkedin_enable') ) {
if($selected_theme == 'longbutton'){
$html .= "<a style='width: " . $customWidth . "px !important;padding-top:" . ($customHeight-29) . "px !important;padding-bottom:" . ($customHeight-29) . "px !important;margin-bottom: " . ($spacebetweenicons-5) . "px !important;border-radius: " .$customBoundary. "px !important;' class='btn btn-block btn-social btn-linkedin btn-custom-dec login-button' onClick='moOpenIdLogin(" . '"linkedin"' . ");'> <i style='padding-top:" . ($customHeight-35) . "px !important' class='fa fa-linkedin'></i>" . $buttonText . " LinkedIn</a>";
}
else{
$html .= "<a title= ' ".$customTextofTitle." LinkedIn' onClick='moOpenIdLogin(" . '"linkedin"' . ");' ><img alt='LinkedIn' style='width:" . $customSize ."px !important;height: " . $customSize ."px !important;margin-left: " . ($spacebetweenicons-4) ."px !important' src='" . plugins_url( 'includes/images/icons/linkedin.png', __FILE__ ) . "' class='login-button " .$selected_theme . "' ></a>";
}
}if( get_option('mo_openid_instagram_enable') ) {
if($selected_theme == 'longbutton'){
$html .= "<a style='width: " . $customWidth . "px !important;padding-top:" . ($customHeight-29) . "px !important;padding-bottom:" . ($customHeight-29) . "px !important;margin-bottom: " . ($spacebetweenicons-5) . "px !important;border-radius: " .$customBoundary. "px !important;' class='btn btn-block btn-social btn-instagram btn-custom-dec login-button' onClick='moOpenIdLogin(" . '"instagram"' . ");'> <i style='padding-top:" . ($customHeight-35) . "px !important' class='fa fa-instagram'></i>" . $buttonText . " Instagram</a>";
}
else{
$html .= "<a title= ' ".$customTextofTitle." Instagram' onClick='moOpenIdLogin(" . '"instagram"' . ");' ><img alt='Instagram' style='width:" . $customSize ."px !important;height: " . $customSize ."px !important;margin-left: " . ($spacebetweenicons-4) ."px !important' src='" . plugins_url( 'includes/images/icons/instagram.png', __FILE__ ) . "' class='login-button " .$selected_theme . "' ></a>";
}
}if( get_option('mo_openid_amazon_enable') ) {
if($selected_theme == 'longbutton'){
$html .= "<a style='width: " . $customWidth . "px !important;padding-top:" . ($customHeight-29) . "px !important;padding-bottom:" . ($customHeight-29) . "px !important;margin-bottom: " . ($spacebetweenicons-5) . "px !important;border-radius: " .$customBoundary. "px !important;' class='btn btn-block btn-social btn-soundcloud btn-custom-dec login-button' onClick='moOpenIdLogin(" . '"amazon"' . ");'> <i style='padding-top:" . ($customHeight-35) . "px !important' class='fa fa-amazon'></i>" . $buttonText . " Amazon</a>";
}
else{
$html .= "<a title= ' ".$customTextofTitle." Amazon' onClick='moOpenIdLogin(" . '"amazon"' . ");' ><img alt='Amazon' style='width:" . $customSize ."px !important;height: " . $customSize ."px !important;margin-left: " . ($spacebetweenicons-4) ."px !important' src='" . plugins_url( 'includes/images/icons/amazon.png', __FILE__ ) . "' class='login-button " .$selected_theme . "' ></a>";
}
}if( get_option('mo_openid_salesforce_enable') ) {
if($selected_theme == 'longbutton'){
$html .= "<a style='width: " . $customWidth . "px !important;padding-top:" . ($customHeight-29) . "px !important;padding-bottom:" . ($customHeight-29) . "px !important;margin-bottom: " . ($spacebetweenicons-5) . "px !important;border-radius: " .$customBoundary. "px !important;' class='btn btn-block btn-social btn-vimeo btn-custom-dec login-button' onClick='moOpenIdLogin(" . '"salesforce"' . ");'> <i style='padding-top:" . ($customHeight-35) . "px !important' class='fa fa-cloud'></i>" . $buttonText . " Salesforce</a>";
}
else{
$html .= "<a title= ' ".$customTextofTitle." Salesforce' onClick='moOpenIdLogin(" . '"salesforce"' . ");' ><img alt='Salesforce' style='width:" . $customSize ."px !important;height: " . $customSize ."px !important;margin-left: " . ($spacebetweenicons-4) ."px !important' src='" . plugins_url( 'includes/images/icons/salesforce.png', __FILE__ ) . "' class='login-button " .$selected_theme . "' ></a>";
}
}if( get_option('mo_openid_windowslive_enable') ) {
if($selected_theme == 'longbutton'){
$html .= "<a style='width: " . $customWidth . "px !important;padding-top:" . ($customHeight-29) . "px !important;padding-bottom:" . ($customHeight-29) . "px !important;margin-bottom: " . ($spacebetweenicons-5) . "px !important;border-radius: " .$customBoundary. "px !important;' class='btn btn-block btn-social btn-microsoft btn-custom-dec login-button' onClick='moOpenIdLogin(" . '"windowslive"' . ");'> <i style='padding-top:" . ($customHeight-35) . "px !important' class='fa fa-windows'></i>" . $buttonText . " Microsoft</a>";
}
else{
$html .= "<a title= ' ".$customTextofTitle." Microsoft' onClick='moOpenIdLogin(" . '"windowslive"' . ");' ><img alt='Windowslive' style='width:" . $customSize ."px !important;height: " . $customSize ."px !important;margin-left: " . ($spacebetweenicons-4) ."px !important' src='" . plugins_url( 'includes/images/icons/windowslive.png', __FILE__ ) . "' class='login-button " .$selected_theme . "' ></a>";
}
}
}
if($customTheme == 'custom'){
if( get_option('mo_openid_facebook_enable') ) {
if($selected_theme == 'longbutton'){
$html .= "<a onClick='moOpenIdLogin(" . '"facebook"' . ");' style='width:" . ($customWidth) . "px !important;padding-top:" . ($customHeight-29) . "px !important;padding-bottom:" . ($customHeight-29) . "px !important;margin-bottom:" . ($spacebetweenicons-5) . "px !important; background:#" . $customBackground . "!important;border-radius: " .$customBoundary. "px !important;' class='btn btn-block btn-social btn-customtheme btn-custom-dec login-button' > <i style='padding-top:" .($customHeight-35) . "px !important' class='fa fa-facebook'></i> " . $buttonText . " Facebook</a>";
}
else{
$html .= "<a title= ' ".$customTextofTitle." Facebook' onClick='moOpenIdLogin(" . '"facebook"' . ");' ><i style='width:" . $customSize . "px !important;height:" . $customSize . "px !important;margin-left:" . ($spacebetweenicons-4) . "px !important;background:#" . $customBackground . " !important;font-size: " . ($customSize-16) . "px !important;' class='fa fa-facebook custom-login-button " . $selected_theme . "' ></i></a>";
}
}
if( get_option('mo_openid_google_enable') ) {
if($selected_theme == 'longbutton'){
$html .= "<a onClick='moOpenIdLogin(" . '"google"' . ");' style='width:" . ($customWidth) . "px !important;padding-top:" . ($customHeight-29) . "px !important;padding-bottom:" . ($customHeight-29) . "px !important;margin-bottom:" . ($spacebetweenicons-5) . "px !important; background:#" . $customBackground . "!important;border-radius: " .$customBoundary. "px !important;' class='btn btn-block btn-social btn-customtheme btn-custom-dec login-button' > <i style='padding-top:" .($customHeight-35) . "px !important' class='fa fa-google-plus'></i> " . $buttonText . " Google</a>";
}
else{
$html .= "<a title= ' ".$customTextofTitle." Google' onClick='moOpenIdLogin(" . '"google"' . ");' title= ' ". $customTextofTitle." Google'><i style='width:" . $customSize . "px !important;height:" . $customSize . "px !important;margin-left:" . ($spacebetweenicons-4) . "px !important;background:#" . $customBackground . " !important;font-size: " . ($customSize-16) . "px !important;' class='fa fa-google-plus custom-login-button " . $selected_theme . "' ></i></a>";
}
}
if( get_option('mo_openid_vkontakte_enable') ) {
if($selected_theme == 'longbutton'){
$html .= "<a onClick='moOpenIdLogin(" . '"vkontakte"' . ");' style='width:" . ($customWidth) . "px !important;padding-top:" . ($customHeight-29) . "px !important;padding-bottom:" . ($customHeight-29) . "px !important;margin-bottom:" . ($spacebetweenicons-5) . "px !important; background:#" . $customBackground . "!important;border-radius: " .$customBoundary. "px !important;' class='btn btn-block btn-social btn-customtheme btn-custom-dec login-button' > <i style='padding-top:" .($customHeight-35) . "px !important' class='fa fa-vk'></i> " . $buttonText . " Vkontakte</a>";
}
else{
$html .= "<a title= ' ".$customTextofTitle." Vkontakte' onClick='moOpenIdLogin(" . '"vkontakte"' . ");' title= ' ". $customTextofTitle." Vkontakte'><i style='width:" . $customSize . "px !important;height:" . $customSize . "px !important;margin-left:" . ($spacebetweenicons-4) . "px !important;background:#" . $customBackground . " !important;font-size: " . ($customSize-16) . "px !important;' class='fa fa-vk custom-login-button " . $selected_theme . "' ></i></a>";
}
}
if( get_option('mo_openid_twitter_enable') ) {
if($selected_theme == 'longbutton'){
$html .= "<a onClick='moOpenIdLogin(" . '"twitter"' . ");' style='width:" . ($customWidth) . "px !important;padding-top:" . ($customHeight-29) . "px !important;padding-bottom:" . ($customHeight-29) . "px !important;margin-bottom:" . ($spacebetweenicons-5) . "px !important; background:#" . $customBackground . "!important;border-radius: " .$customBoundary. "px !important;' class='btn btn-block btn-social btn-customtheme btn-custom-dec login-button' > <i style='padding-top:" .($customHeight-35) . "px !important' class='fa fa-twitter'></i> " . $buttonText . " Twitter</a>";
}
else{
$html .= "<a title= ' ".$customTextofTitle." Twitter' onClick='moOpenIdLogin(" . '"twitter"' . ");' ><i style='width:" . $customSize . "px !important;height:" . $customSize . "px !important;margin-left:" . ($spacebetweenicons-4) . "px !important;background:#" . $customBackground . " !important;font-size: " . ($customSize-16) . "px !important;' class='fa fa-twitter custom-login-button " . $selected_theme . "' ></i></a>";
}
}
if( get_option('mo_openid_linkedin_enable') ) {
if($selected_theme == 'longbutton'){
$html .= "<a onClick='moOpenIdLogin(" . '"linkedin"' . ");' style='width:" . ($customWidth) . "px !important;padding-top:" . ($customHeight-29) . "px !important;padding-bottom:" . ($customHeight-29) . "px !important;margin-bottom:" . ($spacebetweenicons-5) . "px !important; background:#" . $customBackground . "!important;border-radius: " .$customBoundary. "px !important;' class='btn btn-block btn-social btn-customtheme btn-custom-dec login-button' > <i style='padding-top:" .($customHeight-35) . "px !important' class='fa fa-linkedin'></i> " . $buttonText . " LinkedIn</a>";
}
else{
$html .= "<a title= ' ".$customTextofTitle." LinkedIn' onClick='moOpenIdLogin(" . '"linkedin"' . ");' ><i style='width:" . $customSize . "px !important;height:" . $customSize . "px !important;margin-left:" . ($spacebetweenicons-4) . "px !important;background:#" . $customBackground . " !important;font-size: " . ($customSize-16) . "px !important;' class='fa fa-linkedin custom-login-button " . $selected_theme . "' ></i></a>";
}
}if( get_option('mo_openid_instagram_enable') ) {
if($selected_theme == 'longbutton'){
$html .= "<a onClick='moOpenIdLogin(" . '"instagram"' . ");' style='width:" . ($customWidth) . "px !important;padding-top:" . ($customHeight-29) . "px !important;padding-bottom:" . ($customHeight-29) . "px !important;margin-bottom:" . ($spacebetweenicons-5) . "px !important; background:#" . $customBackground . "!important;border-radius: " .$customBoundary. "px !important;' class='btn btn-block btn-social btn-customtheme btn-custom-dec login-button' > <i style='padding-top:" .($customHeight-35) . "px !important' class='fa fa-instagram'></i> " . $buttonText . " Instagram</a>";
}
else{
$html .= "<a title= ' ".$customTextofTitle." Instagram' onClick='moOpenIdLogin(" . '"instagram"' . ");' ><i style='width:" . $customSize . "px !important;height:" . $customSize . "px !important;margin-left:" . ($spacebetweenicons-4) . "px !important;background:#" . $customBackground . " !important;font-size: " . ($customSize-16) . "px !important;' class='fa fa-instagram custom-login-button " . $selected_theme . "' ></i></a>";
}
}if( get_option('mo_openid_amazon_enable') ) {
if($selected_theme == 'longbutton'){
$html .= "<a onClick='moOpenIdLogin(" . '"amazon"' . ");' style='width:" . ($customWidth) . "px !important;padding-top:" . ($customHeight-29) . "px !important;padding-bottom:" . ($customHeight-29) . "px !important;margin-bottom:" . ($spacebetweenicons-5) . "px !important; background:#" . $customBackground . "!important;border-radius: " .$customBoundary. "px !important;' class='btn btn-block btn-social btn-customtheme btn-custom-dec login-button' > <i style='padding-top:" .($customHeight-35) . "px !important' class='fa fa-amazon'></i> " . $buttonText . " Amazon</a>";
}
else{
$html .= "<a title= ' ".$customTextofTitle." Amazon' onClick='moOpenIdLogin(" . '"amazon"' . ");' ><i style='width:" . $customSize . "px !important;height:" . $customSize . "px !important;margin-left:" . ($spacebetweenicons-4) . "px !important;background:#" . $customBackground . " !important;font-size: " . ($customSize-16) . "px !important;' class='fa fa-amazon custom-login-button " . $selected_theme . "' ></i></a>";
}
}if( get_option('mo_openid_salesforce_enable') ) {
if($selected_theme == 'longbutton'){
$html .= "<a onClick='moOpenIdLogin(" . '"salesforce"' . ");' style='width:" . ($customWidth) . "px !important;padding-top:" . ($customHeight-29) . "px !important;padding-bottom:" . ($customHeight-29) . "px !important;margin-bottom:" . ($spacebetweenicons-5) . "px !important; background:#" . $customBackground . "!important;border-radius: " .$customBoundary. "px !important;' class='btn btn-block btn-social btn-customtheme btn-custom-dec login-button' > <i style='padding-top:" .($customHeight-35) . "px !important' class='fa fa-cloud'></i> " . $buttonText . " Salesforce</a>";
}
else{
$html .= "<a title= ' ".$customTextofTitle." Salesforce' onClick='moOpenIdLogin(" . '"salesforce"' . ");' ><i style='width:" . $customSize . "px !important;height:" . $customSize . "px !important;margin-left:" . ($spacebetweenicons-4) . "px !important;background:#" . $customBackground . " !important;font-size: " . ($customSize-16) . "px !important;' class='fa fa-cloud custom-login-button " . $selected_theme . "' ></i></a>";
}
}if( get_option('mo_openid_windowslive_enable') ) {
if($selected_theme == 'longbutton'){
$html .= "<a onClick='moOpenIdLogin(" . '"windowslive"' . ");' style='width:" . ($customWidth) . "px !important;padding-top:" . ($customHeight-29) . "px !important;padding-bottom:" . ($customHeight-29) . "px !important;margin-bottom:" . ($spacebetweenicons-5) . "px !important; background:#" . $customBackground . "!important;border-radius: " .$customBoundary. "px !important;' class='btn btn-block btn-social btn-customtheme btn-custom-dec login-button' > <i style='padding-top:" .($customHeight-35) . "px !important' class='fa fa-windows'></i> " . $buttonText . " Microsoft</a>";
}
else{
$html .= "<a title= ' ".$customTextofTitle." Microsoft' onClick='moOpenIdLogin(" . '"windowslive"' . ");' ><i style='width:" . $customSize . "px !important;height:" . $customSize . "px !important;margin-left:" . ($spacebetweenicons-4) . "px !important;background:#" . $customBackground . " !important;font-size: " . ($customSize-16) . "px !important;' class='fa fa-windows custom-login-button " . $selected_theme . "' ></i></a>";
}
}
}
$html .= '</div> <br>';
} else {
$html .= '<div>No apps configured. Please contact your administrator.</div>';
}
}else {
global $current_user;
get_currentuserinfo();
$link_with_username = __('Howdy, ', 'flw') . $current_user->display_name;
$flw = __("Logout","flw");
$html .= '<div id="logged_in_user" class="mo_openid_login_wid"> ' . $link_with_username . ' | <a href=' . $logoutUrl .' title=" ' . $flw . '"> ' . $flw . '</a></div>';
}
return $html;
}
private function mo_openid_load_login_script() {
?>
<script type="text/javascript">
function moOpenIdLogin(app_name) {
<?php
if(isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off'){
$http = "https://";
} else {
$http = "http://";
}
if ( strpos($_SERVER['REQUEST_URI'],'wp-login.php') !== FALSE){
$redirect_url = site_url() . '/?option=getMoSocialLogin&app_name=';
}else{
$redirect_url = $http . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if(strpos($redirect_url, '?') !== false) {
$redirect_url .= '&option=getMoSocialLogin&app_name=';
} else {
$redirect_url .= '?option=getMoSocialLogin&app_name=';
}
}
?>
window.location.href = '<?php echo $redirect_url; ?>' + app_name;
}
</script>
<?php
}
public function error_message(){
if(isset($_SESSION['msg']) and $_SESSION['msg']){
echo '<div class="'.$_SESSION['msg_class'].'">'.$_SESSION['msg'].'</div>';
unset($_SESSION['msg']);
unset($_SESSION['msg_class']);
}
}
}
/**
* Sharing Widget Horizontal
*
*/
class mo_openid_sharing_hor_wid extends WP_Widget {
public function __construct() {
parent::__construct(
'mo_openid_sharing_hor_wid',
'miniOrange Sharing - Horizontal',
array( 'description' => __( 'Share using horizontal widget. Lets you share with Social Apps like Google, Facebook, LinkedIn, Pinterest, Reddit.', 'flw' ), )
);
}
public function widget( $args, $instance ) {
extract( $args );
echo $args['before_widget'];
$this->show_sharing_buttons_horizontal();
echo $args['after_widget'];
}
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['wid_title'] = strip_tags( $new_instance['wid_title'] );
return $instance;
}
public function show_sharing_buttons_horizontal(){
global $post;
$title = str_replace('+', '%20', urlencode($post->post_title));
$content=strip_shortcodes( strip_tags( get_the_content() ) );
$post_content=$content;
$excerpt = '';
$landscape = 'horizontal';
include( plugin_dir_path( __FILE__ ) . 'class-mo-openid-social-share.php');
}
}
/**
* Sharing Vertical Widget
*
*/
class mo_openid_sharing_ver_wid extends WP_Widget {
public function __construct() {
parent::__construct(
'mo_openid_sharing_ver_wid',
'miniOrange Sharing - Vertical',
array( 'description' => __( 'Share using a vertical floating widget. Lets you share with Social Apps like Google, Facebook, LinkedIn, Pinterest, Reddit.', 'flw' ), )
);
}
public function widget( $args, $instance ) {
extract( $args );
extract( $instance );
$wid_title = apply_filters( 'widget_title', $instance['wid_title'] );
$alignment = apply_filters( 'alignment', isset($instance['alignment'])? $instance['alignment'] : 'left');
$left_offset = apply_filters( 'left_offset', isset($instance['left_offset'])? $instance['left_offset'] : '20');
$right_offset = apply_filters( 'right_offset', isset($instance['right_offset'])? $instance['right_offset'] : '0');
$top_offset = apply_filters( 'top_offset', isset($instance['top_offset'])? $instance['top_offset'] : '100');
$space_icons = apply_filters( 'space_icons', isset($instance['space_icons'])? $instance['space_icons'] : '10');
echo $args['before_widget'];
if ( ! empty( $wid_title ) )
echo $args['before_title'] . $wid_title . $args['after_title'];
echo "<div class='mo_openid_vertical' style='" .(isset($alignment) && $alignment != '' && isset($instance[$alignment.'_offset']) ? $alignment .': '. ( $instance[$alignment.'_offset'] == '' ? 0 : $instance[$alignment.'_offset'] ) .'px;' : '').(isset($top_offset) ? 'top: '. ( $top_offset == '' ? 0 : $top_offset ) .'px;' : '') ."'>";
$this->show_sharing_buttons_vertical($space_icons);
echo '</div>';
echo $args['after_widget'];
}
/*Called when user changes configuration in Widget Admin Panel*/
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['wid_title'] = strip_tags( $new_instance['wid_title'] );
$instance['alignment'] = $new_instance['alignment'];
$instance['left_offset'] = $new_instance['left_offset'];
$instance['right_offset'] = $new_instance['right_offset'];
$instance['top_offset'] = $new_instance['top_offset'];
$instance['space_icons'] = $new_instance['space_icons'];
return $instance;
}
public function show_sharing_buttons_vertical($space_icons){
global $post;
if($post->post_title) {
$title = str_replace('+', '%20', urlencode($post->post_title));
} else {
$title = get_bloginfo( 'name' );
}
$content=strip_shortcodes( strip_tags( get_the_content() ) );
$post_content=$content;
$excerpt = '';
$landscape = 'vertical';
include( plugin_dir_path( __FILE__ ) . 'class-mo-openid-social-share.php');
}
/** Widget edit form at admin panel */
function form( $instance ) {
/* Set up default widget settings. */
$defaults = array('alignment' => 'left', 'left_offset' => '20', 'right_offset' => '0', 'top_offset' => '100' , 'space_icons' => '10');
foreach( $instance as $key => $value ){
$instance[ $key ] = esc_attr( $value );
}
$instance = wp_parse_args( (array)$instance, $defaults );
?>
<p>
<script>
function moOpenIDVerticalSharingOffset(alignment){
if(alignment == 'left'){
jQuery('.moVerSharingLeftOffset').css('display', 'block');
jQuery('.moVerSharingRightOffset').css('display', 'none');
}else{
jQuery('.moVerSharingLeftOffset').css('display', 'none');
jQuery('.moVerSharingRightOffset').css('display', 'block');
}
}
</script>
<label for="<?php echo $this->get_field_id( 'alignment' ); ?>">Alignment</label>
<select onchange="moOpenIDVerticalSharingOffset(this.value)" style="width: 95%" id="<?php echo $this->get_field_id( 'alignment' ); ?>" name="<?php echo $this->get_field_name( 'alignment' ); ?>">
<option value="left" <?php echo $instance['alignment'] == 'left' ? 'selected' : ''; ?>>Left</option>
<option value="right" <?php echo $instance['alignment'] == 'right' ? 'selected' : ''; ?>>Right</option>
</select>
<div class="moVerSharingLeftOffset" <?php echo $instance['alignment'] == 'right' ? 'style="display: none"' : ''; ?>>
<label for="<?php echo $this->get_field_id( 'left_offset' ); ?>">Left Offset</label>
<input style="width: 95%" id="<?php echo $this->get_field_id( 'left_offset' ); ?>" name="<?php echo $this->get_field_name( 'left_offset' ); ?>" type="text" value="<?php echo $instance['left_offset']; ?>" />px<br/>
</div>
<div class="moVerSharingRightOffset" <?php echo $instance['alignment'] == 'left' ? 'style="display: none"' : ''; ?>>
<label for="<?php echo $this->get_field_id( 'right_offset' ); ?>">Right Offset</label>
<input style="width: 95%" id="<?php echo $this->get_field_id( 'right_offset' ); ?>" name="<?php echo $this->get_field_name( 'right_offset' ); ?>" type="text" value="<?php echo $instance['right_offset']; ?>" />px<br/>
</div>
<label for="<?php echo $this->get_field_id( 'top_offset' ); ?>">Top Offset</label>
<input style="width: 95%" id="<?php echo $this->get_field_id( 'top_offset' ); ?>" name="<?php echo $this->get_field_name( 'top_offset' ); ?>" type="text" value="<?php echo $instance['top_offset']; ?>" />px<br/>
<label for="<?php echo $this->get_field_id( 'space_icons' ); ?>">Space between icons</label>
<input style="width: 95%" id="<?php echo $this->get_field_id( 'space_icons' ); ?>" name="<?php echo $this->get_field_name( 'space_icons' ); ?>" type="text" value="<?php echo $instance['space_icons']; ?>" />px<br/>
</p>
<?php
}
}
function mo_openid_start_session() {
if( !session_id() ) {
session_start();
}
}
function mo_openid_end_session() {
if( session_id() ) {
session_destroy();
}
}
function mo_openid_login_validate(){
if( isset( $_REQUEST['option'] ) and strpos( $_REQUEST['option'], 'getMoSocialLogin' ) !== false ) {
$client_name = "wordpress";
$timestamp = round( microtime(true) * 1000 );
$api_key = get_option('mo_openid_admin_api_key');
$token = $client_name . ':' . number_format($timestamp, 0, '', ''). ':' . $api_key;
$customer_token = get_option('mo_openid_customer_token');
$blocksize = 16;
$pad = $blocksize - ( strlen( $token ) % $blocksize );
$token = $token . str_repeat( chr( $pad ), $pad );
$token_params_encrypt = mcrypt_encrypt( MCRYPT_RIJNDAEL_128, $customer_token, $token, MCRYPT_MODE_ECB );
$token_params_encode = base64_encode( $token_params_encrypt );
$token_params = urlencode( $token_params_encode );
$userdata = get_option('moopenid_user_attributes')?'true':'false';
$http = isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? "https://" : "http://";
$parts = parse_url($http . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
parse_str($parts['query'], $query);
$post = isset( $query['p'] ) ? '?p=' . $query['p'] : '';
$base_return_url = $http . $_SERVER["HTTP_HOST"] . strtok($_SERVER["REQUEST_URI"],'?') . $post;
$return_url = strpos($base_return_url, '?') !== false ? urlencode( $base_return_url . '&option=moopenid' ): urlencode( $base_return_url . '?option=moopenid' );
$url = get_option('mo_openid_host_name') . '/moas/openid-connect/client-app/authenticate?token=' . $token_params . '&userdata=' . $userdata. '&id=' . get_option('mo_openid_admin_customer_key') . '&encrypted=true&app=' . $_REQUEST['app_name'] . '_oauth&returnurl=' . $return_url . '&encrypt_response=true';
wp_redirect( $url );
exit;
}
if( isset( $_REQUEST['option'] ) and strpos( $_REQUEST['option'], 'moopenid' ) !== false ){
//Decrypt all entries
$decrypted_email = isset($_POST['email']) ? mo_openid_decrypt($_POST['email']): '';
$decrypted_user_name = isset($_POST['username']) ? mo_openid_decrypt($_POST['username']): '';
$decrypted_user_picture = isset($_POST['profilePic']) ? mo_openid_decrypt($_POST['profilePic']): '';
$decrypted_user_url = isset($_POST['profileUrl']) ? mo_openid_decrypt($_POST['profileUrl']): '';
$decrypted_first_name = isset($_POST['firstName']) ? mo_openid_decrypt($_POST['firstName']): '';
$decrypted_last_name = isset($_POST['lastName']) ? mo_openid_decrypt($_POST['lastName']): '';
//Calculate user email
if( isset( $decrypted_email ) && strcmp($decrypted_email,'')!=0 ) {
$user_email = $decrypted_email;
} else if( isset( $decrypted_user_name )){
$user_email = str_replace(" ","_",$decrypted_user_name).'@social-user.com';
}
//Set Display Picture
$user_picture = $decrypted_user_picture;
//Check if username is equal to full name, set username as email
if(empty($decrypted_user_name)){
$email = array();
$email = explode('@', $decrypted_email);
$username = $email[0];
} else {
if(strpos($decrypted_user_name, ' ') !== FALSE){
$username_split = explode("@", $decrypted_user_name);
$username = $username_split[0];
} else {
$username = $decrypted_user_name;
}
}
//Set User URL
$user_url = $decrypted_user_url;
//Set User Display Name
if(isset( $_POST['firstName'] ) && isset( $_POST['lastName'] )){
if(strcmp($decrypted_first_name, $decrypted_last_name)!=0)
$user_full_name = $decrypted_first_name.' '.$decrypted_last_name;
else
$user_full_name = $decrypted_first_name;
$first_name = $decrypted_first_name;
$last_name = $decrypted_last_name;
}
else
$user_full_name = $username;
if( $user_email ) {
global $wpdb;
$user_email = sanitize_email($user_email);
$username = preg_replace('/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F]/', '', $username);
$orignal_username = '';
$orignal_email = '';
//Check for string in another language
if(strlen($username) != mb_strlen($username, 'utf-8') || strlen($user_email) != mb_strlen($user_email, 'utf-8')){
$orignal_username = $username;
if(strlen($user_email) != mb_strlen($user_email, 'utf-8')) {
$orignal_email = $user_email;
$server_name = array();
if(strlen($user_full_name) != mb_strlen($user_full_name, 'utf-8')) {
$server_name = explode(".", $_SERVER['SERVER_NAME']);
$index = count($server_name) >= 3 ? 1 : 0;
$username = $server_name[$index] . '_' . get_option('mo_openid_user_number');
$user_email = $server_name[$index] . '_' . get_option('mo_openid_user_number') . '@social-user.com';
update_option('mo_openid_user_number', get_option('mo_openid_user_number') + 1);
} else {
$user_full_name = preg_replace('/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F]/', '', $user_full_name);
$username = str_replace(" ","_",$user_full_name);
$user_email = str_replace(" ","_",$user_full_name).'@social-user.com';
}
} else {
$email_explode = array();
$email_explode = explode("@", $user_email);
$username = $email_explode[0];
}
}
//Checking if email or username already exist
$email_user_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->users where user_email = %s", $user_email));
$username_user_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->users where user_login = %s", $username));
if( !isset($email_user_id) && !isset($username_user_id) && (!empty($orignal_username) || !empty($orignal_email))) {
$email_user_id = $wpdb->get_var($wpdb->prepare("SELECT user_id FROM $wpdb->usermeta where meta_key = 'moopenid_orignal_email' and meta_value = %s", $orignal_email));
$username_user_id = $wpdb->get_var($wpdb->prepare("SELECT user_id FROM $wpdb->usermeta where meta_key = 'moopenid_orignal_username' and meta_value = %s", $orignal_username));
}
if( isset($email_user_id)) { // user is a member
$user = get_user_by('id', $email_user_id );
$user_id = $user->ID;
if(get_option('moopenid_social_login_avatar') && isset($user_picture))
update_user_meta($user_id, 'moopenid_user_avatar', $user_picture);
do_action( 'wp_login', $user->user_login, $user );
wp_set_auth_cookie( $user_id, true );
} else if( isset($username_user_id) ) { // user is a member
$user = get_user_by('id', $username_user_id );
$user_id = $user->ID;
if(get_option('moopenid_social_login_avatar') && isset($user_picture))
update_user_meta($user_id, 'moopenid_user_avatar', $user_picture);
do_action( 'wp_login', $user->user_login, $user );
wp_set_auth_cookie( $user_id, true );
} else { // this user is a guest
if(get_option('mo_openid_auto_register_enable')) {
$random_password = wp_generate_password( 10, false );
$userdata = array(
'user_login' => $username,
'user_email' => $user_email,
'user_pass' => $random_password,
'display_name' => $user_full_name,
'first_name' => $first_name,
'last_name' => $last_name,
'user_url' => $user_url,
);
$user_id = wp_insert_user( $userdata);
if(is_wp_error( $user_id )) {
//print_r($user_id);
echo '<br/>There was an error in registration. Please contact your administrator.';
exit();
}
$user = get_user_by('email', $user_email );
if(get_option('mo_openid_login_role_mapping') && mo_openid_is_customer_valid()){
$user->set_role( get_option('mo_openid_login_role_mapping') );
}
//Add meta if username in other language
if(!empty($orignal_username)) {
update_user_meta($user_id, 'moopenid_orignal_username', $orignal_username);
}
//Add meta if email in other language
if(!empty($orignal_email)) {
update_user_meta($user_id, 'moopenid_orignal_email', $orignal_email);
}
if(get_option('moopenid_social_login_avatar') && isset($user_picture)){
update_user_meta($user_id, 'moopenid_user_avatar', $user_picture);
}
do_action( 'wp_login', $user->user_login, $user );
wp_set_auth_cookie( $user_id, true );
}
}
}
$redirect_url = mo_openid_get_redirect_url();
wp_redirect($redirect_url);
exit;
}
if(isset($_REQUEST['autoregister']) and strpos($_REQUEST['autoregister'],'false') !== false) {
if(!is_user_logged_in()) {
mo_openid_disabled_register_message();
}
}
}
function mo_openid_decrypt($param) {
if(strcmp($param,'null')!=0 && strcmp($param,'')!=0){
$customer_token = get_option('mo_openid_customer_token');
$base64decoded = base64_decode($param);
$token_params_decrypt = mcrypt_decrypt( MCRYPT_RIJNDAEL_128, $customer_token, $base64decoded, MCRYPT_MODE_ECB );
return $token_params_decrypt;
}else{
return '';
}
}
function mo_openid_disabled_register_message() {
wp_enqueue_script('thickbox');
wp_enqueue_style('thickbox');
wp_enqueue_script( 'mo-wp-settings-script',plugins_url('includes/js/settings_popup.js', __FILE__), array('jquery'));
add_thickbox();
$script = '<script>
function getAutoRegisterDisabledMessage() {
var disabledMessage = "' . get_option('mo_openid_register_disabled_message') . '";
return disabledMessage;
}
</script>';
echo $script;
}
function mo_openid_get_redirect_url() {
$option = get_option( 'mo_openid_login_redirect' );
$redirect_url = site_url();
if( $option == 'same' ) {
if(isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off'){
$http = "https://";
} else {
$http = "http://";
}
$redirect_url = urldecode(html_entity_decode(esc_url($http . $_SERVER["HTTP_HOST"] . str_replace('option=moopenid','',$_SERVER['REQUEST_URI']))));
if(html_entity_decode(esc_url(remove_query_arg('ss_message', $redirect_url))) == wp_login_url() || strpos($_SERVER['REQUEST_URI'],'wp-login.php') !== FALSE || strpos($_SERVER['REQUEST_URI'],'wp-admin') !== FALSE){
$redirect_url = site_url().'/';
}
} else if( $option == 'homepage' ) {
$redirect_url = site_url();
} else if( $option == 'dashboard' ) {
$redirect_url = admin_url();
} else if( $option == 'custom' ) {
$redirect_url = get_option('mo_openid_login_redirect_url');
}
if(strpos($redirect_url,'?') !== FALSE) {
$redirect_url .= get_option('mo_openid_auto_register_enable') ? '' : '&autoregister=false';
} else{
$redirect_url .= get_option('mo_openid_auto_register_enable') ? '' : '?autoregister=false';
}
return $redirect_url;
}
function mo_openid_redirect_after_logout($logout_url) {
if(get_option('mo_openid_logout_redirection_enable')){
$option = get_option( 'mo_openid_logout_redirect' );
$redirect_url = site_url();
if( $option == 'homepage' ) {
$redirect_url = $logout_url . '&redirect_to=' .home_url() ;
}
else if($option == 'currentpage'){
if(isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off'){
$http = "https://";
} else {
$http = "http://";
}
$redirect_url = $logout_url . '&redirect_to=' . $http . $_SERVER["HTTP_HOST"] . $_SERVER['REQUEST_URI'];
}
else if($option == 'login') {
$redirect_url = $logout_url . '&redirect_to=' . site_url() . '/wp-admin' ;
}
else if($option == 'custom') {
$redirect_url = $logout_url . '&redirect_to=' . site_url() . (null !== get_option('mo_openid_logout_redirect_url')?get_option('mo_openid_logout_redirect_url'):'');
}
return $redirect_url;
}else{
return $logout_url;
}
}
if(get_option('mo_openid_logout_redirection_enable') == 1){
add_filter( 'logout_url', 'mo_openid_redirect_after_logout',0,1);
}
add_action( 'widgets_init', create_function( '', 'register_widget( "mo_openid_login_wid" );' ) );
add_action( 'widgets_init', create_function( '', 'return register_widget( "mo_openid_sharing_ver_wid" );' ) );
add_action( 'widgets_init', create_function( '', 'return register_widget( "mo_openid_sharing_hor_wid" );' ) );
add_action( 'init', 'mo_openid_login_validate' );
add_action( 'init', 'mo_openid_start_session' );
add_action( 'wp_logout', 'mo_openid_end_session' );
}
?>
|
alogic/fightchoice
|
wp-content/plugins/miniorange-login-openid/class-mo-openid-login-widget.php
|
PHP
|
gpl-2.0
| 67,479
|
<?php
/**
* Polaris ILS Driver
*
* PHP version 5
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* @category VuFind2
* @package ILS_Drivers
* @author BookSite <vufind-tech@lists.sourceforge.net>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link http://vufind.org/wiki/building_an_ils_driver Wiki
*/
namespace VuFind\ILS\Driver;
use VuFind\Config\Reader as ConfigReader,
VuFind\Exception\ILS as ILSException;
/**
* VuFind Connector for Polaris
*
* Based on Polaris 1.4 API
*
* @category VuFind2
* @package ILS_Drivers
* @author BookSite <vufind-tech@lists.sourceforge.net>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link http://vufind.org/wiki/building_an_ils_driver Wiki
*/
class Polaris extends AbstractBase implements \VuFindHttp\HttpServiceAwareInterface
{
use \VuFindHttp\HttpServiceAwareTrait;
/**
* Web services host
*
* @var string
*/
protected $ws_host;
/**
* Web services application path
*
* @var string
*/
protected $ws_app;
/**
* Web services ID
*
* @var string
*/
protected $ws_api_id;
/**
* Web services key
*
* @var string
*/
protected $ws_api_key;
/**
* Web services requesting organization ID
*
* @var string
*/
protected $ws_requestingorgid;
/**
* Initialize the driver.
*
* Validate configuration and perform all resource-intensive tasks needed to
* make the driver active.
*
* @throws ILSException
* @return void
*/
public function init()
{
if (empty($this->config) || !isset($this->config['PAPI'])) {
throw new ILSException('Configuration needs to be set.');
}
// Define Polaris PAPI parameters
$this->ws_host = $this->config['PAPI']['ws_host'];
$this->ws_app = $this->config['PAPI']['ws_app'];
$this->ws_api_id = $this->config['PAPI']['ws_api_id'];
$this->ws_api_key = $this->config['PAPI']['ws_api_key'];
$this->ws_requestingorgid = $this->config['PAPI']['ws_requestingorgid'];
$this->defaultPickUpLocation
= isset($this->config['Holds']['defaultPickUpLocation'])
? $this->config['Holds']['defaultPickUpLocation'] : null;
}
/**
* Make Request
*
* Makes a request to the Polaris Restful API
*
* @param string $api_query Query string for request
* @param string $http_method HTTP method (default = GET)
* @param string $patronpassword Patron password (optional)
* @param bool $json Optional JSON attachment
*
* @throws ILSException
* @return obj
*/
protected function makeRequest($api_query, $http_method = "GET",
$patronpassword = "", $json = false
) {
// auth has to be in GMT, otherwise use config-level TZ
$site_config_TZ = date_default_timezone_get();
date_default_timezone_set('GMT');
$date = date("D, d M Y H:i:s T");
date_default_timezone_set($site_config_TZ);
$url = $this->ws_host . $this->ws_app . $api_query;
$signature_text = $http_method . $url . $date . $patronpassword;
$signature = base64_encode(
hash_hmac('sha1', $signature_text, $this->ws_api_key, true)
);
$auth_token = "PWS {$this->ws_api_id}:$signature";
$http_headers = [
"Content-type: application/json",
"Accept: application/json",
"PolarisDate: $date",
"Authorization: $auth_token"
];
try {
$client = $this->httpService->createClient($url);
// Attach JSON if necessary
if ($json !== false) {
$json_data = json_encode($json);
$client->setRawBody($json_data);
$client->setEncType('application/json');
}
// httpService doesn't explicitly support PUT, so add this:
if ($http_method == 'PUT') {
$http_headers[] = "Content-Length: " . strlen($json_data);
}
$client->setHeaders($http_headers);
$client->setMethod($http_method);
$result = $client->send();
} catch (\Exception $e) {
throw new ILSException($e->getMessage());
}
if (!$result->isSuccess()) {
throw new ILSException('HTTP error');
}
return json_decode($result->getBody());
}
/**
* Return human-readable date from text like Date(1360051200000-0800)
*
* @param string $jsontime Input
*
* @return string
*/
public function formatJSONTime($jsontime)
{
preg_match('/Date\((\d+)\-(\d){2}(\d){2}\)/', $jsontime, $matches);
if (count($matches) > 0) {
$matchestmp = intval($matches[1] / 1000);
$date = date("n-j-Y", $matchestmp);
} else {
$date = 'n/a';
}
return $date;
}
/**
* Encode from human-readable date to text like Date(1360051200000-0800)
*
* @param string $date Input
*
* @return string
*/
public function encodeJSONTime($date)
{
// auth has to be in GMT, otherwise use config-level TZ
//$site_config_TZ = date_default_timezone_get();
//date_default_timezone_set('GMT');
$unix_time = strtotime($date);
//date_default_timezone_set($site_config_TZ);
$json_time = "/Date(" . $unix_time . "000)/";
return $json_time;
}
/**
* Get Patron Holds
*
* This is responsible for retrieving all holds by a specific patron.
*
* @param array $patron The patron array from patronLogin
*
* @return mixed Array of the patron's holds on success.
*/
public function getMyHolds($patron)
{
$holds = [];
$response = $this->makeRequest(
"patron/{$patron['cat_username']}/holdrequests/all", 'GET',
$patron['cat_password']
);
$holds_response_array = $response->PatronHoldRequestsGetRows;
foreach ($holds_response_array as $holds_response) {
// only display item if it is NOT expired
if ($holds_response->StatusID > 8) {
continue;
}
$create = $this->formatJSONTime($holds_response->ActivationDate);
$expire = $this->formatJSONTime($holds_response->ExpirationDate);
$holds[] = [
'type' => $holds_response->StatusDescription,
'id' => $holds_response->BibID,
'location' => $holds_response->PickupBranchName,
'reqnum' => $holds_response->HoldRequestID,
'expire' => $expire,
'create' => $create,
'position' => $holds_response->QueuePosition,
'title' => $holds_response->Title,
];
}
return $holds;
}
/**
* Get Status
*
* This is responsible for retrieving the status information of a certain
* record.
*
* @param string $id The record id to retrieve the holdings for
*
* @return mixed On success, an associative array with the following keys:
* id, availability (boolean), status, location, reserve, callnumber.
*/
public function getStatus($id)
{
$holding = [];
$response = $this->makeRequest("bib/$id/holdings");
$holdings_response_array = $response->BibHoldingsGetRows;
$copy_count = 0;
foreach ($holdings_response_array as $holdings_response) {
//$holdings_response = $holdings_response_array[0];
$copy_count++;
$availability = 0;
if (($holdings_response->CircStatus == 'In')
|| ($holdings_response->CircStatus == 'Just Returned')
|| ($holdings_response->CircStatus == 'On Shelf')
|| ($holdings_response->CircStatus == 'Available - Check shelves')
) {
$availability = 1;
}
$duedate = '';
if ($holdings_response->DueDate) {
$duedate = date("n-j-Y", strtotime($holdings_response->DueDate));
}
$holding[] = [
'availability' => $availability,
'id' => $id,
'status' => $holdings_response->CircStatus,
'location' => $holdings_response->LocationName,
//'reserve' => 'No',
'callnumber' => $holdings_response->CallNumber,
'duedate' => $duedate,
//'number' => $holdings_response->ItemsIn,
'number' => $copy_count,
'barcode' => $holdings_response->Barcode,
'shelf_location' => $holdings_response->ShelfLocation,
'collection_name' => $holdings_response->CollectionName,
'per_item_holdable' => $per_item_holdable,
'designation' => $designation,
'holdable' => $holdings_response->Holdable,
];
}
return $holding;
}
/**
* Get Statuses
*
* This is responsible for retrieving the status information for a
* collection of records.
*
* @param array $ids The array of record ids to retrieve the status for
*
* @return mixed An array of getStatus() return values on success.
*/
public function getStatuses($ids)
{
$items = [];
$count = 0;
foreach ($ids as $id) {
$items[$count] = $this->getStatus($id);
$count++;
}
return $items;
}
/**
* Public Function which retrieves renew, hold and cancel settings from the
* driver ini file.
*
* @param string $function The name of the feature to be checked
* @param array $params Optional feature-specific parameters (array)
*
* @return array An array with key-value pairs.
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getConfig($function, $params = null)
{
if (isset($this->config[$function])) {
$functionConfig = $this->config[$function];
} else {
$functionConfig = false;
}
return $functionConfig;
}
/**
* Get Holding
*
* This is responsible for retrieving the holding information of a certain
* record.
*
* @param string $id The record id to retrieve the holdings for
* @param array $patron Patron data
*
* @return mixed On success, an associative array with the following
* keys: id, availability (boolean), status, location, reserve, callnumber,
* duedate, number, barcode.
*/
public function getHolding($id, array $patron = null)
{
return $this->getStatus($id);
}
/**
* Place Hold
*
* Attempts to place a hold or recall on a particular item and returns
* an array with result details.
*
* @param array $holdDetails An array of item and patron data
*
* @return mixed An array of data on the request including
* whether or not it was successful and a system message (if available)
*/
public function placeHold($holdDetails)
{
// what do workstation & userid really mean in this context?
$workstationid = '1';
$userid = '1';
// all activations are for now(), for now.
// microtime is msec or sec?? seems to have changed
$activationdate = '/Date(' . intval(microtime(true) * 1000) . ')/';
if (empty($holdDetails['barcode'])) {
$holdDetails['barcode'] = '';
}
$jsonrequest = [
'PatronID' => $holdDetails['patron']['id'],
'BibID' => $holdDetails['id'],
'ItemBarcode' => $holdDetails['barcode'],
'VolumeNumber' => '',
'Designation' => '',
'PickupOrgID' => $holdDetails['pickUpLocation'],
'IsBorrowByMail' => '0',
'PatronNotes' => $holdDetails['comment'],
'ActivationDate' => $activationdate,
'WorkstationID' => $workstationid,
'UserID' => $userid,
'RequestingOrgID' => $this->ws_requestingorgid,
'TargetGUID' => '',
];
$response = $this->makeRequest('holdrequest', 'POST', '', $jsonrequest);
if ($response->StatusValue == 1) {
return [ 'success' => true, 'sysMessage' => $response->Message ];
} elseif ($response->StatusValue == 5) {
// auto say "yes" to Conditional: Accept even with existing holds
// response
$reply_jsonrequest = [
// apparent bug in API, TxnGroupQualifer missing final "i"
'TxnGroupQualifier' => $response->TxnGroupQualifer,
'TxnQualifier' => $response->TxnQualifier,
'RequestingOrgID' => $this->ws_requestingorgid,
'Answer' => 1,
'State' => 5,
];
$reply_response = $this->makeRequest(
"holdrequest/{$response->RequestGUID}", 'PUT', '',
$reply_jsonrequest
);
if ($reply_response->StatusValue == 1) {
// auto-reply success
return [ 'success' => true, 'sysMessage' => $response->Message ];
} else {
return [ 'success' => false, 'sysMessage' => $response->Message ];
}
} else {
return [ 'success' => false, 'sysMessage' => $response->Message ];
}
}
/**
* Get Pick Up Locations
*
* This is responsible for gettting a list of valid library locations for
* holds / recall retrieval
*
* @param array $patron Patron information returned by the patronLogin
* method.
* @param array $holdDetails Optional array, only passed in when getting a list
* in the context of placing a hold; contains most of the same values passed to
* placeHold, minus the patron data. May be used to limit the pickup options
* or may be ignored. The driver must not add new options to the return array
* based on this data or other areas of VuFind may behave incorrectly.
*
* @throws ILSException
* @return array An array of associative arrays with locationID
* and locationDisplay keys
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getPickUpLocations($patron = false, $holdDetails = null)
{
if (isset($this->ws_pickUpLocations)) {
// hardcoded pickup locations in the .ini file? or...
foreach ($this->ws_pickUpLocations as $code => $library) {
$locations[] = [
'locationID' => $code,
'locationDisplay' => $library
];
}
} else {
// we get them from the API
$response = $this->makeRequest("organizations/branch");
$locations_response_array = $response->OrganizationsGetRows;
foreach ($locations_response_array as $location_response) {
$locations[] = [
'locationID' => $location_response->OrganizationID,
'locationDisplay' => $location_response->Name,
];
}
}
return $locations;
}
/**
* Get Default Pick Up Location
*
* Returns the default pick up location set in VoyagerRestful.ini
*
* @param array $patron Patron information returned by the patronLogin
* method.
* @param array $holdDetails Optional array, only passed in when getting a list
* in the context of placing a hold; contains most of the same values passed to
* placeHold, minus the patron data. May be used to limit the pickup options
* or may be ignored.
*
* @return string The default pickup location for the patron.
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getDefaultPickUpLocation($patron = false, $holdDetails = null)
{
return $this->defaultPickUpLocation;
}
/**
* Get Purchase History
*
* This is responsible for retrieving the acquisitions history data for the
* specific record (usually recently received issues of a serial).
*
* @param string $id The record id to retrieve the info for
*
* @return mixed An array with the acquisitions data on success.
*/
public function getPurchaseHistory($id)
{
return [];
}
/**
* Get New Items
*
* Retrieve the IDs of items recently added to the catalog.
*
* @param int $page Page number of results to retrieve (counting starts at 1)
* @param int $limit The size of each page of results to retrieve
* @param int $daysOld The maximum age of records to retrieve in days (max. 30)
* @param int $fundId optional fund ID to use for limiting results (use a value
* returned by getFunds, or exclude for no limit); note that "fund" may be a
* misnomer - if funds are not an appropriate way to limit your new item
* results, you can return a different set of values from getFunds. The
* important thing is that this parameter supports an ID returned by getFunds,
* whatever that may mean.
*
* @return array Associative array with 'count' and 'results' keys
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getNewItems($page, $limit, $daysOld, $fundId = null)
{
return ['count' => 0, 'results' => []];
}
/**
* Find Reserves
*
* Obtain information on course reserves.
*
* @param string $course ID from getCourses (empty string to match all)
* @param string $inst ID from getInstructors (empty string to match all)
* @param string $dept ID from getDepartments (empty string to match all)
*
* @return mixed An array of associative arrays representing reserve items.
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function findReserves($course, $inst, $dept)
{
return [];
}
/**
* Patron Login
*
* This is responsible for authenticating a patron against the catalog.
*
* @param string $username The patron username
* @param string $password The patron password
*
* @return mixed Associative array of patron info on successful login,
* null on unsuccessful login.
*/
public function patronLogin($username, $password)
{
// username == barcode
$response = $this->makeRequest("patron/$username", "GET", "$password");
if (!$response->ValidPatron) {
return null;
}
$user = [];
$user['id'] = $response->PatronID;
$user['firstname'] = null;
$user['lastname'] = null;
$user['cat_username'] = $response->PatronBarcode;
$user['cat_password'] = $password;
$user['email'] = null;
$user['major'] = null;
$user['college'] = null;
return $user;
}
/**
* Get Patron Fines
*
* This is responsible for retrieving all fines by a specific patron.
*
* @param array $patron The patron array from patronLogin
*
* @return mixed Array of the patron's fines on success.
*/
public function getMyFines($patron)
{
$fineList = [];
$response = $this->makeRequest(
"patron/{$patron['cat_username']}/account/outstanding", 'GET',
$patron['cat_password']
);
$fines_response_array = $response->PatronAccountGetRows;
foreach ($fines_response_array as $fines_response) {
$fineList[] = [
// fees in vufind are in pennies
'amount' => $fines_response->TransactionAmount * 100,
'checkout' => $this->formatJSONTime($fines_response->CheckOutDate),
'fine' => $fines_response->FeeDescription,
'balance' => $fines_response->OutstandingAmount * 100,
'duedate' => $this->formatJSONTime($fines_response->DueDate),
'createdate' => $this->formatJSONTime($fines_response->TransactionDate),
'id' => $fines_response->BibID,
'title' => $fines_response->Title,
];
}
return $fineList;
}
/**
* Get Patron Profile
*
* This is responsible for retrieving the profile for a specific patron.
*
* @param array $patron The patron array
*
* @throws ILSException
* @return array Array of the patron's profile data on success.
*/
public function getMyProfile($patron)
{
// firstname, lastname, address1, address2, zip, phone, group
$response = $this->makeRequest(
"patron/{$patron['cat_username']}/basicdata", 'GET',
$patron['cat_password']
);
$profile_response = $response->PatronBasicData;
$profile = [
'firstname' => $profile_response->NameFirst,
'lastname' => $profile_response->NameLast,
'phone' => $profile_response->PhoneNumber,
];
return $profile;
}
/**
* Get Patron Transactions
*
* This is responsible for retrieving all transactions (i.e. checked out items)
* by a specific patron.
*
* @param array $patron The patron array from patronLogin
*
* @return mixed Array of associative arrays of the patron's transactions on
* success.
*/
public function getMyTransactions($patron)
{
// duedate, id, barcode, renew (count), request (pending count),
// volume (vol number), publication_year, renewable, message, title, item_id
// polaris apis: PatronItemsOutGet, Patron_RewewBlocksGet
$transactions = [];
$response = $this->makeRequest(
"patron/{$patron['cat_username']}/itemsout/all", 'GET',
$patron['cat_password']
);
foreach ($response->PatronItemsOutGetRows as $trResponse) {
// any more renewals available?
if (($trResponse->RenewalLimit - $trResponse->RenewalCount) > 0) {
$renewable = true;
} else {
$renewable = false;
}
$transactions[] = [
'duedate' => $this->formatJSONTime($trResponse->DueDate),
'id' => $trResponse->BibID,
'barcode' => $trResponse->Barcode,
'renew' => $trResponse->RenewalCount,
'renewLimit' => $trResponse->RenewalLimit,
'renewable' => $renewable,
'title' => $trResponse->Title,
'item_id' => $trResponse->ItemID,
];
}
return $transactions;
}
/**
* Renew My Items
*
* Function for attempting to renew a patron's items. The data in
* $renewDetails['details'] is determined by getRenewDetails().
*
* @param array $renewDetails An array of data required for renewing items
* including the Patron ID and an array of renewal IDS
*
* @return array An array of renewal information keyed by item ID
*/
public function renewMyItems($renewDetails)
{
$renew_ids = $renewDetails['details'];
$patron = $renewDetails['patron'];
$count = 0;
$item_response = [];
$item_blocks = [];
foreach ($renew_ids as $renew_id) {
$jsonrequest = [];
$jsonrequest['Action'] = 'renew';
$jsonrequest['LogonBranchID'] = '1';
$jsonrequest['LogonUserID'] = '1';
$jsonrequest['LogonWorkstationID'] = '1';
$jsonrequest['RenewData']['IgnoreOverrideErrors'] = 'true';
$response = $this->makeRequest(
"patron/{$patron['cat_username']}/itemsout/$renew_id", 'PUT',
$patron['cat_password'], $jsonrequest
);
if ($response->PAPIErrorCode == 0) {
$count++;
$item_response[$renew_id] = [
'success' => true,
'new_date' => $this->formatJSONTime(
$response->ItemRenewResult->DueDateRows[0]->DueDate
),
'item_id' =>
$response->ItemRenewResult->DueDateRows[0]->ItemRecordID,
];
} elseif ($response->PAPIErrorCode == -2) {
$item_blocks[$renew_id]
= $response->ItemRenewResult->BlockRows[0]->ErrorDesc;
$item_response[$hold_id] = [
'success' => -1,
'new_date' => false,
'item_id' => $response->ItemRenewResult->BlockRows[0]->ItemRecordID,
'sysMessage' => $response->ItemRenewResult->BlockRows[0]->ErrorDesc,
];
}
}
$result = [
'count' => $count, 'details' => $item_response,
'blocks' => $item_blocks
];
return $result;
}
/**
* Get Renew Details
*
* In order to renew an item, Voyager requires the patron details and an item
* id. This function returns the item id as a string which is then used
* as submitted form data in checkedOut.php. This value is then extracted by
* the RenewMyItems function.
*
* @param array $checkOutDetails An array of item data
*
* @return string Data for use in a form field
*/
public function getRenewDetails($checkOutDetails)
{
$renewDetails = $checkOutDetails['item_id'];
return $renewDetails;
}
/**
* Cancel Holds
*
* Attempts to Cancel a hold or recall on a particular item. The
* data in $cancelDetails['details'] is determined by getCancelHoldDetails().
*
* @param array $cancelDetails An array of item and patron data
*
* @return array An array of data on each request including whether or not it
* was successful and a system message (if available)
*/
public function cancelHolds($cancelDetails)
{
$hold_ids = $cancelDetails['details'];
$patron = $cancelDetails['patron'];
$count = 0;
$item_response = [];
foreach ($hold_ids as $hold_id) {
$response = $this->makeRequest(
"patron/{$patron['cat_username']}/holdrequests/$hold_id/cancelled"
. "?wsid=1&userid=1", 'PUT', $patron['cat_password']
);
if ($response->PAPIErrorCode == 0) {
$count++;
$item_response[$hold_id] = [
'success' => true,
'status' => 'hold_cancel_success'
];
} else {
$item_response[$hold_id] = [
'success' => false,
'status' => 'hold_cancel_fail',
'sysMessage' => 'Failure calling ILS to cancel hold'
];
}
}
$result = [ 'count' => $count, 'items' => $item_response ];
return $result;
}
/**
* Get Cancel Hold Details
*
* @param array $holdDetails An array of item data
*
* @return string Data for use in a form field (just request id is all Polaris
* needs)
*/
public function getCancelHoldDetails($holdDetails)
{
return $holdDetails['reqnum'];
}
/**
* Get Checkout History
*
* Returns the patrons checkout / reading history
*
* @param array $patron The patron array from patronLogin
*
* @return mixed Array of the patron's checkouts on success.
*/
public function getCheckoutHistory($patron)
{
// get number of pages, only get most recent max 200 items (last 2 pages)
// TODO: use real pagination, not just recent items.
$items_per_page = 100;
$response = $this->makeRequest(
"patron/{$patron['cat_username']}/readinghistory?rowsperpage=1&page=-1",
'GET', $patron['cat_password']
);
// error code returns number of results
$count = $response->PAPIErrorCode;
if ($count == 0) {
return;
}
$offset = $count - $items_per_page;
$pages = ceil($count / $items_per_page);
$penultimate_page = $pages - 1;
if ($penultimate_page > 0) {
$page_offset = $penultimate_page;
} else {
$page_offset = $pages;
}
while ($page_offset <= $pages) {
$response = $this->makeRequest(
"patron/{$patron['cat_username']}/readinghistory?rowsperpage="
. "$items_per_page&page=$page_offset", 'GET',
$patron['cat_password']
);
$checkout_history_array = $response->PatronReadingHistoryGetRows;
foreach ($checkout_history_array as $checkout_response) {
$date = $this->formatJSONTime($checkout_response->CheckOutDate);
$checkouts[] = [
'id' => $checkout_response->BibID,
'title' => $checkout_response->Title,
'format' => $checkout_response->FormatDescription,
'location' => $checkout_response->LoaningBranchName,
'date' => $date,
'author' => $checkout_response->Author,
];
}
$page_offset++;
}
// show most recent checkouts first
$checkouts = array_reverse($checkouts);
return $checkouts;
}
/**
* Get Hold Count
*
* Returns the count of a hold based on API call to bibid
*
* @param array $id bib id
*
* @return string count of holds
*/
public function getHoldCount($id)
{
$response = $this->makeRequest("bib/$id");
$holdings_response_array = $response->BibGetRows;
$hold_count = 0;
foreach ($holdings_response_array as $response) {
if ($response->ElementID == '8') {
// that's the current holds field, could also be pulled by label
// instead?
if ($response->Value > 0) {
$hold_count = $response->Value;
}
break;
}
}
return $hold_count;
}
/**
* Suspend Holds
*
* Attempts to Suspend a hold or recall on a particular item. The
* data in $suspendDetails['details'] is determined by getSuspendHoldDetails().
*
* @param array $suspendDetails An array of item and patron data
*
* @return array An array of data on each request including whether or not it
* was successful and a system message (if available)
*/
public function suspendHolds($suspendDetails)
{
$hold_ids = $suspendDetails['details'];
$patron = $suspendDetails['patron'];
$jsondate = $this->encodeJSONTime($suspendDetails['date']);
$count = 0;
$item_response = [];
foreach ($hold_ids as $hold_id) {
$jsonrequest = [
'UserID' => '1',
'ActivationDate' => "$jsondate"
];
$response = $this->makeRequest(
"patron/{$patron['cat_username']}/holdrequests/$hold_id/inactive",
'PUT', $patron['cat_password'], $jsonrequest
);
if ($response->PAPIErrorCode == 0) {
$count++;
$item_response[$hold_id] = [
'success' => true,
'status' => 'hold_suspend_success'
];
} else {
$item_response[$hold_id] = [
'success' => false,
'status' => 'hold_suspend_fail',
'sysMessage' => 'Failure calling ILS to suspend hold'
];
}
}
$result = [ 'count' => $count, 'items' => $item_response ];
return $result;
}
/**
* Get Suspend Hold Details
*
* @param array $holdDetails An array of item data
*
* @return string Data for use in a form field (just request id is all Polaris
* needs)
*/
public function getSuspendHoldDetails($holdDetails)
{
return $holdDetails['reqnum'];
}
/**
* Reactivate Holds
*
* Attempts to Reactivate a hold or recall on a particular item. The
* data in $reactivateDetails['details'] is determined by
* getReactivateHoldDetails().
*
* @param array $reactivateDetails An array of item and patron data
*
* @return array An array of data on each request including whether or not it
* was successful and a system message (if available)
*/
public function reactivateHolds($reactivateDetails)
{
$hold_ids = $reactivateDetails['details'];
$patron = $reactivateDetails['patron'];
$date = date("d/M/Y");
$jsondate = $this->encodeJSONTime($date);
$count = 0;
$item_response = [];
foreach ($hold_ids as $hold_id) {
$jsonrequest = [
'UserID' => '1',
'ActivationDate' => "$jsondate"
];
$response = $this->makeRequest(
"patron/{$patron['cat_username']}/holdrequests/$hold_id/active",
'PUT', $patron['cat_password'], $jsonrequest
);
if ($response->PAPIErrorCode == 0) {
$count++;
$item_response[$hold_id] = [
'success' => true,
'status' => 'hold_reactivate_success'
];
} else {
$item_response[$hold_id] = [
'success' => false,
'status' => 'hold_reactivate_fail',
'sysMessage' => 'Failure calling ILS to reactivate hold'
];
}
}
$result = [ 'count' => $count, 'items' => $item_response ];
return $result;
}
}
|
paulusova/VuFind-2.x
|
module/VuFind/src/VuFind/ILS/Driver/Polaris.php
|
PHP
|
gpl-2.0
| 35,296
|
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* 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 only.
*
* 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.
*/
package net.pms.test.formats;
import ch.qos.logback.classic.LoggerContext;
import java.util.ArrayList;
import java.util.List;
import net.pms.PMS;
import net.pms.configuration.PmsConfiguration;
import net.pms.configuration.RendererConfiguration;
import net.pms.dlna.DLNAMediaAudio;
import net.pms.dlna.DLNAMediaInfo;
import net.pms.dlna.LibMediaInfoParser;
import net.pms.formats.DVRMS;
import net.pms.formats.Format;
import net.pms.formats.ISO;
import net.pms.formats.MKV;
import net.pms.formats.MPG;
import net.pms.formats.audio.M4A;
import net.pms.formats.audio.MP3;
import net.pms.formats.audio.OGA;
import net.pms.formats.audio.WAV;
import net.pms.formats.image.RAW;
import net.pms.network.HTTPResource;
import org.apache.commons.configuration.ConfigurationException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.LoggerFactory;
/**
* Test the recognition of formats.
*/
public class FormatRecognitionTest {
private static boolean mediaInfoParserIsValid;
private static PmsConfiguration configuration;
@BeforeClass
public static void setUpBeforeClass() throws ConfigurationException, InterruptedException {
PMS.configureJNA();
mediaInfoParserIsValid = LibMediaInfoParser.isValid();
// Silence all log messages from the DMS code that is being tested
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
context.reset();
// Initialize the RendererConfiguration
configuration = new PmsConfiguration(false);
RendererConfiguration.loadRendererConfigurations(configuration);
}
/**
* Test some basic functionality of {@link RendererConfiguration#isCompatible(DLNAMediaInfo, Format)}
*/
@Test
public void testRendererConfigurationBasics() {
// This test is only useful if the MediaInfo library is available
assumeTrue(mediaInfoParserIsValid);
RendererConfiguration conf = RendererConfiguration.getRendererConfigurationByName("Playstation 3");
assertNotNull("Renderer named \"Playstation 3\" found.", conf);
assertEquals("With nothing provided isCompatible() should return false", false,
conf.isCompatible(null, null, configuration));
}
/**
* Test the compatibility of the Playstation 3 with the MP3 format.
*/
@Test
public void testPlaystationAudioMp3Compatibility() {
// This test is only useful if the MediaInfo library is available
assumeTrue(mediaInfoParserIsValid);
RendererConfiguration conf = RendererConfiguration.getRendererConfigurationByName("Playstation 3");
assertNotNull("Renderer named \"Playstation 3\" found.", conf);
// Construct regular two channel MP3 information
DLNAMediaInfo info = new DLNAMediaInfo();
info.setContainer("mp3");
info.setMimeType(HTTPResource.AUDIO_MP3_TYPEMIME);
DLNAMediaAudio audio = new DLNAMediaAudio();
audio.setNumberOfChannels(2);
List<DLNAMediaAudio> audioCodes = new ArrayList<>();
audioCodes.add(audio);
info.setAudioTracksList(audioCodes);
Format format = new MP3();
format.match("test.mp3");
assertEquals("PS3 is compatible with MP3", true,
conf.isCompatible(info, format, configuration));
// Construct five channel MP3 that the PS3 does not support natively
audio.setNumberOfChannels(5);
assertEquals("PS3 is incompatible with five channel MP3", false,
conf.isCompatible(info, format, configuration));
}
/**
* Test the compatibility of the Playstation 3 with the MPG format.
*/
@Test
public void testPlaystationVideoMpgCompatibility() {
// This test is only useful if the MediaInfo library is available
assumeTrue(mediaInfoParserIsValid);
RendererConfiguration conf = RendererConfiguration.getRendererConfigurationByName("Playstation 3");
assertNotNull("Renderer named \"Playstation 3\" found.", conf);
// Construct regular two channel MPG information
DLNAMediaInfo info = new DLNAMediaInfo();
info.setContainer("avi");
DLNAMediaAudio audio = new DLNAMediaAudio();
audio.setCodecA("ac3");
audio.setNumberOfChannels(5);
List<DLNAMediaAudio> audioCodes = new ArrayList<>();
audioCodes.add(audio);
info.setAudioTracksList(audioCodes);
info.setCodecV("mpeg4sp");
Format format = new MPG();
format.match("test.avi");
assertEquals("PS3 is compatible with MPG", true,
conf.isCompatible(info, format, configuration));
// Construct MPG with wmv codec that the PS3 does not support natively
info.setCodecV("wmv");
assertEquals("PS3 is incompatible with MPG with wmv codec", false,
conf.isCompatible(info, format, configuration));
}
/**
* Test the compatibility of the Playstation 3 with the MPG format.
*/
@Test
public void testPlaystationVideoMkvCompatibility() {
// This test is only useful if the MediaInfo library is available
assumeTrue(mediaInfoParserIsValid);
RendererConfiguration conf = RendererConfiguration.getRendererConfigurationByName("Playstation 3");
assertNotNull("Renderer named \"Playstation 3\" found.", conf);
// Construct MKV information
DLNAMediaInfo info = new DLNAMediaInfo();
info.setContainer("mkv");
DLNAMediaAudio audio = new DLNAMediaAudio();
audio.setCodecA("ac3");
audio.setNumberOfChannels(5);
List<DLNAMediaAudio> audioCodes = new ArrayList<>();
audioCodes.add(audio);
info.setAudioTracksList(audioCodes);
info.setCodecV("mp4");
Format format = new MPG();
format.match("test.mkv");
assertEquals("PS3 is incompatible with MKV", false,
conf.isCompatible(info, format, configuration));
}
/**
* Test the compatibility of the
* {@link Format#isCompatible(DLNAMediaInfo, RendererConfiguration)} for the
* Playstation 3 renderer.
*/
@Test
public void testPS3Compatibility() {
// This test is only useful if the MediaInfo library is available
assumeTrue(mediaInfoParserIsValid);
RendererConfiguration conf = RendererConfiguration.getRendererConfigurationByName("Playstation 3");
assertNotNull("Renderer named \"Playstation 3\" found.", conf);
// DVRMS: false
DLNAMediaInfo info = new DLNAMediaInfo();
info.setContainer("dvr");
Format format = new DVRMS();
format.match("test.dvr");
assertFalse("isCompatible() gives the outcome false for DVRMS", conf.isCompatible(info, format, configuration));
// ISO: false
info = new DLNAMediaInfo();
info.setContainer("iso");
format = new ISO();
format.match("test.iso");
assertFalse("isCompatible() gives the outcome false for ISO", conf.isCompatible(info, format, configuration));
// M4A: false
info = new DLNAMediaInfo();
info.setContainer("m4a");
format = new M4A();
format.match("test.m4a");
assertTrue("isCompatible() gives the outcome true for M4A", conf.isCompatible(info, format, configuration));
// MKV: false
info = new DLNAMediaInfo();
info.setContainer("mkv");
format = new MKV();
format.match("test.mkv");
assertFalse("isCompatible() gives the outcome false for MKV", conf.isCompatible(info, format, configuration));
// MP3: true
info = new DLNAMediaInfo();
info.setContainer("mp3");
format = new MP3();
format.match("test.mp3");
assertTrue("isCompatible() gives the outcome true for MP3", conf.isCompatible(info, format, configuration));
// MPG: true
info = new DLNAMediaInfo();
info.setContainer("avi");
format = new MPG();
format.match("test.mpg");
assertTrue("isCompatible() gives the outcome true for MPG", conf.isCompatible(info, format, configuration));
// OGG: false
info = new DLNAMediaInfo();
info.setContainer("ogg");
format = new OGA();
format.match("test.ogg");
assertFalse("isCompatible() gives the outcome false for OGG", conf.isCompatible(info, format, configuration));
// RAW: false
info = new DLNAMediaInfo();
info.setContainer("raw");
format = new RAW();
format.match("test.arw");
assertFalse("isCompatible() gives the outcome false for RAW", conf.isCompatible(info, format, configuration));
// WAV: true
info = new DLNAMediaInfo();
info.setContainer("wav");
format = new WAV();
format.match("test.wav");
assertTrue("isCompatible() gives the outcome true for WAV", conf.isCompatible(info, format, configuration));
// WEB: type=VIDEO
info = new DLNAMediaInfo();
info.setContainer("avi");
format.setType(Format.VIDEO);
assertTrue("isCompatible() gives the outcome true for WEB video", conf.isCompatible(info, format, configuration));
}
/**
* When DMS is in the process of starting up, something particular happens.
* The RootFolder is initialized and several VirtualVideoActions are added
* as children. VirtualVideoActions use the MPG format and at the time of
* initialization getDefaultRenderer() is used to determine whether or not
* the format can be streamed.
* <p>
* Under these conditions Format.isCompatible() must return true, or
* selecting the VirtualVideoAction will result in a "Corrupted data"
* message.
* <p>
* This test verifies the case above.
* @throws InterruptedException
*/
@Test
public void testVirtualVideoActionInitializationCompatibility() throws InterruptedException {
// Continue the test if the LibMediaInfoParser can be loaded, otherwise skip it.
assumeTrue(mediaInfoParserIsValid);
// Construct media info exactly as VirtualVideoAction does
DLNAMediaInfo info = new DLNAMediaInfo();
info.setContainer("mpegps");
List<DLNAMediaAudio> audioCodes = new ArrayList<>();
info.setAudioTracksList(audioCodes);
info.setMimeType("video/mpeg");
info.setCodecV("mpeg2");
info.setMediaparsed(true);
Format format = new MPG();
format.match("test.mpg");
// Test without rendererConfiguration, as can happen when plugins
// create virtual video actions under a folder.
assertEquals("VirtualVideoAction is initialized as compatible with null configuration",
true, format.isCompatible(info, null));
}
}
|
Sami32/DigitalMediaServer
|
src/test/java/net/pms/test/formats/FormatRecognitionTest.java
|
Java
|
gpl-2.0
| 10,736
|
local name = "commweapon_partillery"
local weaponDef = {
name = [[Light Plasma Artillery]],
accuracy = 350,
areaOfEffect = 64,
customParams = {
is_unit_weapon = 1,
muzzleEffectFire = [[custom:thud_fire_fx]],
},
craterBoost = 0,
craterMult = 0,
damage = {
default = 320,
subs = 16,
},
edgeEffectiveness = 0.5,
explosionGenerator = [[custom:INGEBORG]],
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
myGravity = 0.09,
noSelfDamage = true,
range = 800,
reloadtime = 4,
soundHit = [[explosion/ex_med5]],
soundStart = [[weapon/cannon/cannon_fire1]],
turret = true,
weaponType = [[Cannon]],
weaponVelocity = 300,
}
return name, weaponDef
|
sprunk/Zero-K
|
gamedata/modularcomms/weapons/partillery.lua
|
Lua
|
gpl-2.0
| 945
|
/***************************************************************************
*
* Author: "Sjors H.W. Scheres"
* MRC Laboratory of Molecular Biology
*
* 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.
*
* This complete copyright notice must be included in any revised version of the
* source code. Additional authorship citations may be added, but existing
* author citations must be preserved.
***************************************************************************/
#include <src/args.h>
#include <src/strings.h>
#include <src/funcs.h>
#include <src/memory.h>
#include <src/euler.h>
#include <src/time.h>
#include <src/metadata_table.h>
class angular_error_parameters
{
public:
FileName fn_unt, fn_til, fn_out;
MetaDataTable MDunt, MDtil;
RFLOAT tilt, tilt0, tiltF, tiltStep;
RFLOAT rot, rot0, rotF, rotStep;
int size, dim;
int x0, xF, xStep;
int y0, yF, yStep;
RFLOAT acc;
int mind2;
bool do_opt;
RFLOAT best_rot, best_tilt;
int best_x, best_y;
Matrix2D<RFLOAT> Pass;
std::vector<int> p_unt, p_til, p_map, pairs_t2u;
// I/O Parser
IOParser parser;
void usage()
{
parser.writeUsage(std::cerr);
}
void read(int argc, char **argv)
{
parser.setCommandLine(argc, argv);
int general_section = parser.addSection("General Options");
fn_unt = parser.getOption("--u", "STAR file with the untilted xy-coordinates");
fn_til = parser.getOption("--t", "STAR file with the untilted xy-coordinates");
size = textToInteger(parser.getOption("--size", "Largest dimension of the micrograph (in pixels), e.g. 4096"));
dim = textToInteger(parser.getOption("--dim", "Dimension of boxed particles (for EMAN .box files in pixels)", "200"));
acc = textToFloat(parser.getOption("--acc", "Allowed accuracy (in pixels), e.g. half the particle diameter"));
tilt = textToFloat(parser.getOption("--tilt", "Fix tilt angle (in degrees)", "99999."));
rot = textToFloat(parser.getOption("--rot", "Fix direction of the tilt axis (in degrees), 0 = along y, 90 = along x", "99999."));
do_opt = !parser.checkOption("--dont_opt", "Skip optimization of the transformation matrix");
mind2 = ROUND(acc * acc);
int angle_section = parser.addSection("Specified tilt axis and translational search ranges");
tilt0 = textToFloat(parser.getOption("--tilt0", "Minimum tilt angle (in degrees)","0."));
tiltF = textToFloat(parser.getOption("--tiltF", "Maximum tilt angle (in degrees)","99999."));
if (tiltF == 99999.) tiltF = tilt0;
tiltStep = textToFloat(parser.getOption("--tiltStep", "Tilt angle step size (in degrees)","1."));
rot0 = textToFloat(parser.getOption("--rot0", "Minimum rot angle (in degrees)","0."));
rotF = textToFloat(parser.getOption("--rotF", "Maximum rot angle (in degrees)","99999."));
if (rotF == 99999.) rotF = rot0;
rotStep = textToFloat(parser.getOption("--rotStep", "Rot angle step size (in degrees)","1."));
x0 = textToInteger(parser.getOption("--x0", "Minimum X offset (pixels)","-99999"));
xF = textToInteger(parser.getOption("--xF", "Maximum X offset (pixels)","99999"));
xStep = textToInteger(parser.getOption("--xStep", "X offset step size (pixels)","-1"));
y0 = textToInteger(parser.getOption("--y0", "Minimum Y offset (pixels)","-99999"));
yF = textToInteger(parser.getOption("--yF", "Maximum Y offset (pixels)","99999"));
yStep = textToInteger(parser.getOption("--yStep", "Y offset step size (pixels)","-1"));
// Check for errors in the command-line option
if (parser.checkForErrors())
REPORT_ERROR("Errors encountered on the command line, exiting...");
// If tilt and rot were given: do not search those
if (tilt != 99999.)
{
tilt0 = tiltF = tilt;
tiltStep = 1.;
}
if (rot != 99999.)
{
rot0 = rotF = rot;
rotStep = 1.;
}
// By default search the entire micrograph
x0 = XMIPP_MAX(x0, -size);
xF = XMIPP_MIN(xF, size);
// By default use a xStep of one third the accuracy
if (xStep < 0)
xStep = acc / 3;
// By default treat y search in the same way as the x-search
if (y0 == -99999)
y0 = x0;
if (yF == 99999)
yF = xF;
if (yStep < 0)
yStep = xStep;
// Done reading, now fill p_unt and p_til
MDunt.read(fn_unt);
MDtil.read(fn_til);
// Check for the correct labels
if (!MDunt.containsLabel(EMDL_IMAGE_COORD_X) || !MDunt.containsLabel(EMDL_IMAGE_COORD_Y))
REPORT_ERROR("ERROR: Untilted STAR file does not contain the rlnCoordinateX or Y labels");
if (!MDtil.containsLabel(EMDL_IMAGE_COORD_X) || !MDtil.containsLabel(EMDL_IMAGE_COORD_Y))
REPORT_ERROR("ERROR: Tilted STAR file does not contain the rlnCoordinateX or Y labels");
RFLOAT x, y;
p_unt.clear();
FOR_ALL_OBJECTS_IN_METADATA_TABLE(MDunt)
{
MDunt.getValue(EMDL_IMAGE_COORD_X, x);
MDunt.getValue(EMDL_IMAGE_COORD_Y, y);
p_unt.push_back((int)x);
p_unt.push_back((int)y);
}
p_til.clear();
FOR_ALL_OBJECTS_IN_METADATA_TABLE(MDtil)
{
MDtil.getValue(EMDL_IMAGE_COORD_X, x);
MDtil.getValue(EMDL_IMAGE_COORD_Y, y);
p_til.push_back((int)x);
p_til.push_back((int)y);
}
// Initialize best transformation params
best_x = best_y = 9999;
best_rot = best_tilt = 9999.;
}
int getNumberOfPairs(int dx=0, int dy=0)
{
pairs_t2u.clear();
pairs_t2u.resize(p_til.size()/2, -1);
int result = 0;
for (int u = 0; u < p_map.size()/2; u++)
{
for (int t = 0; t < p_til.size()/2; t++)
{
// only search over particles that do not have a pair yet
if (pairs_t2u[t] < 0)
{
int XX = p_map[2*u]-p_til[2*t]+dx;
XX*= XX;
int YY = p_map[2*u+1]-p_til[2*t+1]+dy;
XX += YY*YY;
if (XX < mind2)
{
result++;
pairs_t2u[t] = u;
//No longer have to search for all the others in q
break;
}
}
}
}
return result;
}
RFLOAT getAverageDistance(int dx=0, int dy=0)
{
std::ofstream fh;
FileName fn_map;
fn_map = "dist.txt";
fh.open(fn_map.c_str(), std::ios::out);
RFLOAT result = 0.;
int count = 0;
for (int t = 0; t < pairs_t2u.size(); t++)
{
int u = pairs_t2u[t];
if (u >= 0)
{
int XX = p_map[2*u]-p_til[2*t]+dx;
XX*= XX;
int YY = p_map[2*u+1]-p_til[2*t+1]+dy;
XX += YY*YY;
//std::cerr << " sqrt(XX)= " << sqrt(XX) << " t= " << t << " u= " << u << std::endl;
result += sqrt(XX);
fh << sqrt(XX) << std::endl;
count ++;
}
}
result /= (RFLOAT)count;
fh.close();
return result;
}
int prunePairs(int dx=0, int dy=0)
{
int nprune = 0;
// Prune for RFLOAT pairs
for (int t = 0; t < pairs_t2u.size(); t++)
{
int u = pairs_t2u[t];
if (u >= 0)
{
for (int tp = t+1; tp < pairs_t2u.size(); tp++)
{
int up = pairs_t2u[tp];
// Find pairs to the same tilted position
if (up == u)
{
nprune++;
// Only keep the nearest neighbours as a pair
int XX = p_map[2*u]-p_til[2*t]+dx;
XX*= XX;
int YY = p_map[2*u+1]-p_til[2*t+1]+dy;
XX += YY*YY;
//up==p
int XXp = p_map[2*u]-p_til[2*tp]+dx;
XXp*= XXp;
int YYp = p_map[2*u+1]-p_til[2*tp+1]+dy;
XXp += YYp*YYp;
if (XX < XXp)
pairs_t2u[tp] = -1;
else
pairs_t2u[t] = -1;
}
}
}
}
return nprune;
}
void mapOntoTilt()
{
p_map.resize(p_unt.size());
for (int u = 0; u < p_map.size()/2; u++)
{
RFLOAT xu = (RFLOAT)p_unt[2*u];
RFLOAT yu = (RFLOAT)p_unt[2*u+1];
p_map[2*u] = ROUND(MAT_ELEM(Pass, 0, 0) * xu + MAT_ELEM(Pass, 0, 1) * yu + MAT_ELEM(Pass, 0, 2));
p_map[2*u+1] = ROUND(MAT_ELEM(Pass, 1, 0) * xu + MAT_ELEM(Pass, 1, 1) * yu + MAT_ELEM(Pass, 1, 2));
}
}
RFLOAT optimiseTransformationMatrix(bool do_optimise_nr_pairs)
{
std::vector<int> best_pairs_t2u, best_map;
RFLOAT score, best_score, best_dist=9999.;
if (do_optimise_nr_pairs)
best_score = 0.;
else
best_score = -999999.;
int nn = XMIPP_MAX(1., (rotF-rot0)/rotStep);
nn *= XMIPP_MAX(1., (tiltF-tilt0)/tiltStep);
nn *= XMIPP_MAX(1., (xF-x0)/xStep);
nn *= XMIPP_MAX(1., (yF-y0)/yStep);
int n = 0;
init_progress_bar(nn);
for (RFLOAT rot = rot0; rot <= rotF; rot+= rotStep)
{
for (RFLOAT tilt = tilt0; tilt <= tiltF; tilt+= tiltStep)
{
// Assume tilt-axis lies in-plane...
RFLOAT psi = -rot;
// Rotate all points correspondingly
Euler_angles2matrix(rot, tilt, psi, Pass);
//std::cerr << " Pass= " << Pass << std::endl;
// Zero-translations for now (these are added in the x-y loops below)
MAT_ELEM(Pass, 0, 2) = MAT_ELEM(Pass, 1, 2) = 0.;
mapOntoTilt();
for (int x = x0; x <= xF; x += xStep)
{
for (int y = y0; y <= yF; y += yStep, n++)
{
if (do_optimise_nr_pairs)
score = getNumberOfPairs(x, y);
else
score = -getAverageDistance(x, y); // negative because smaller distance is better!
bool is_best = false;
if (do_optimise_nr_pairs && score==best_score)
{
RFLOAT dist = getAverageDistance(x, y);
if (dist < best_dist)
{
best_dist = dist;
is_best = true;
}
}
if (score > best_score || is_best)
{
best_score = score;
best_pairs_t2u = pairs_t2u;
best_rot = rot;
best_tilt = tilt;
best_x = x;
best_y = y;
}
if (n%1000==0) progress_bar(n);
}
}
}
}
progress_bar(nn);
// Update pairs with the best_pairs
if (do_optimise_nr_pairs)
pairs_t2u = best_pairs_t2u;
// Update the Passing matrix and the mapping
Euler_angles2matrix(best_rot, best_tilt, -best_rot, Pass);
// Zero-translations for now (these are added in the x-y loops below)
MAT_ELEM(Pass, 0, 2) = MAT_ELEM(Pass, 1, 2) = 0.;
mapOntoTilt();
return best_score;
}
void optimiseTransformationMatrixContinuous()
{
// Get coordinates of all pairs:
Matrix2D<RFLOAT> Au, Bt;
Au.initZeros(3, 3);
Bt.initZeros(3, 3);
Pass.initZeros(4,4);
// Add all pairs to dependent matrices (adapted from add_point in Xmipps micrograph_mark main_widget_mark.cpp)
for (int t = 0; t < pairs_t2u.size(); t++)
{
int u = pairs_t2u[t];
if (u >= 0)
{
Au(0, 0) += (RFLOAT)(p_unt[2*u] * p_unt[2*u]);
Au(0, 1) += (RFLOAT)(p_unt[2*u] * p_unt[2*u+1]);
Au(0, 2) += (RFLOAT)(p_unt[2*u]);
Au(1, 0) = Au(0, 1);
Au(1, 1) += (RFLOAT)(p_unt[2*u+1] * p_unt[2*u+1]);
Au(1, 2) += (RFLOAT)(p_unt[2*u+1]);
Au(2, 0) = Au(0, 2);
Au(2, 1) = Au(1, 2);
Au(2, 2) += 1.;
Bt(0, 0) += (RFLOAT)(p_til[2*t] * p_unt[2*u]);
Bt(0, 1) += (RFLOAT)(p_til[2*t+1] * p_unt[2*u]);
Bt(0, 2) = Au(0, 2);
Bt(1, 0) += (RFLOAT)(p_til[2*t] * p_unt[2*u+1]);
Bt(1, 1) += (RFLOAT)(p_til[2*t+1] * p_unt[2*u+1]);
Bt(1, 2) = Au(1, 2);
Bt(2, 0) += (RFLOAT)(p_til[2*t]);
Bt(2, 1) += (RFLOAT)(p_til[2*t+1]);
Bt(2,2) += 1.;
}
}
// Solve equations
solve(Au, Bt, Pass);
Pass = Pass.transpose();
std::cout << " Optimised passing matrix= " << Pass << std::endl;
//These values can be complete CRAP. Better not show them at all....
//RFLOAT rotp, tiltp, psip;
//tiltp = acos(Pass(1,1));
//rotp = acos(Pass(1,0)/sin(tiltp));
//psip = acos(Pass(0,1)/-sin(tiltp));
//std::cout << " Optimised tilt angle= " << RAD2DEG(tiltp) << std::endl;
//std::cout << " Optimised in-plane rot angles= " << RAD2DEG(rotp) <<" and "<< RAD2DEG(psip) << std::endl;
// Map using the new matrix
mapOntoTilt();
}
void run()
{
// First do a crude search over the given parameter optimization space
// Optimize the number of pairs here...
int npart = optimiseTransformationMatrix(true);
// Get rid of RFLOAT pairs (two different untilted coordinates are close to a tilted coordinate)
int nprune = 0;
nprune = prunePairs(best_x, best_y);
// Calculate average distance between the pairs
RFLOAT avgdist = getAverageDistance(best_x, best_y);
std::cout << " Before optimization of the passing matrix: "<<std::endl;
std::cout << " - Number of pruned pairs= "<<nprune<<std::endl;
std::cout << " - best_rot= " << best_rot << " best_tilt= " << best_tilt << " best_x= " << best_x << " best_y= " << best_y << std::endl;
std::cout << " - Number of particle pairs= " << npart << " average distance= " <<avgdist<<std::endl;
#define WRITE_MAPPED
#ifdef WRITE_MAPPED
std::ofstream fh;
FileName fn_map;
fn_map = "mapped.box";
fh.open(fn_map.c_str(), std::ios::out);
for (int i = 0; i < p_map.size()/2; i++)
{
fh << p_map[2*i] + best_x -dim/2<< " " << p_map[2*i+1] + best_y -dim/2<< " "<<dim<<" "<<dim<<" -3"<<std::endl;
//if (pairs[i]>=0)
// std::cerr << " i= " << i << " pairs[i]= " << pairs[i] << std::endl;
}
fh.close();
#endif
if (do_opt)
{
optimiseTransformationMatrixContinuous();
npart = getNumberOfPairs();
nprune = prunePairs();
avgdist = getAverageDistance();
std::cout << " After optimization of the passing matrix: "<<std::endl;
std::cout << " - Number of pruned pairs= "<<nprune<<std::endl;
std::cout << " - Final number of particle pairs= " << npart << " average distance= " <<avgdist<<std::endl;
}
#ifdef WRITE_MAPPED
fn_map = "mapped_opt.box";
fh.open(fn_map.c_str(), std::ios::out);
for (int i = 0; i < p_map.size()/2; i++)
{
fh << p_map[2*i] -dim/2<< " " << p_map[2*i+1] -dim/2<<" "<<dim<<" "<<dim<<" -3"<< std::endl;
}
fh.close();
#endif
// Write out STAR files with the coordinates
MetaDataTable MDu, MDt;
for (int t = 0; t < p_til.size()/2; t++)
{
int u = pairs_t2u[t];
if (u >= 0)
{
MDu.addObject();
MDu.setValue(EMDL_IMAGE_COORD_X, ((RFLOAT)(p_unt[2*u])));
MDu.setValue(EMDL_IMAGE_COORD_Y, ((RFLOAT)(p_unt[2*u+1])));
MDt.addObject();
MDt.setValue(EMDL_IMAGE_COORD_X, ((RFLOAT)(p_til[2*t])));
MDt.setValue(EMDL_IMAGE_COORD_Y, ((RFLOAT)(p_til[2*t+1])));
}
}
fn_unt = fn_unt.withoutExtension() + "_pairs.star";
fn_til = fn_til.withoutExtension() + "_pairs.star";
MDu.write(fn_unt);
MDt.write(fn_til);
std::cout << " Written out coordinate STAR files: " << fn_unt << " and " << fn_til <<std::endl;
std::cout << " Done!" << std::endl;
}
};
int main(int argc, char *argv[])
{
angular_error_parameters prm;
try
{
prm.read(argc, argv);
prm.run();
}
catch (RelionError XE)
{
std::cerr << XE;
prm.usage();
exit(1);
}
return 0;
}
|
KryoEM/relion2
|
src/apps/find_tiltpairs.cpp
|
C++
|
gpl-2.0
| 15,288
|
/* Copyright (c) 2012-2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#ifndef __VIDC_HFI_API_H__
#define __VIDC_HFI_API_H__
#include <linux/platform_device.h>
#include <linux/types.h>
#include <media/msm_vidc.h>
#include "msm_vidc_resources.h"
#include "msm_smem.h"
#define CONTAINS(__a, __sz, __t) ({\
int __rc = __t >= __a && \
__t < __a + __sz; \
__rc; \
})
#define OVERLAPS(__t, __tsz, __a, __asz) ({\
int __rc = __t <= __a && \
__t + __tsz >= __a + __asz; \
__rc; \
})
#define HAL_BUFFERFLAG_EOS 0x00000001
#define HAL_BUFFERFLAG_STARTTIME 0x00000002
#define HAL_BUFFERFLAG_DECODEONLY 0x00000004
#define HAL_BUFFERFLAG_DATACORRUPT 0x00000008
#define HAL_BUFFERFLAG_ENDOFFRAME 0x00000010
#define HAL_BUFFERFLAG_SYNCFRAME 0x00000020
#define HAL_BUFFERFLAG_EXTRADATA 0x00000040
#define HAL_BUFFERFLAG_CODECCONFIG 0x00000080
#define HAL_BUFFERFLAG_TIMESTAMPINVALID 0x00000100
#define HAL_BUFFERFLAG_READONLY 0x00000200
#define HAL_BUFFERFLAG_ENDOFSUBFRAME 0x00000400
#define HAL_BUFFERFLAG_EOSEQ 0x00200000
#define HAL_BUFFERFLAG_MBAFF 0x08000000
#define HAL_BUFFERFLAG_DROP_FRAME 0x20000000
#define HAL_DEBUG_MSG_LOW 0x00000001
#define HAL_DEBUG_MSG_MEDIUM 0x00000002
#define HAL_DEBUG_MSG_HIGH 0x00000004
#define HAL_DEBUG_MSG_ERROR 0x00000008
#define HAL_DEBUG_MSG_FATAL 0x00000010
enum vidc_status {
VIDC_ERR_NONE = 0x0,
VIDC_ERR_FAIL = 0x80000000,
VIDC_ERR_ALLOC_FAIL,
VIDC_ERR_ILLEGAL_OP,
VIDC_ERR_BAD_PARAM,
VIDC_ERR_BAD_HANDLE,
VIDC_ERR_NOT_SUPPORTED,
VIDC_ERR_BAD_STATE,
VIDC_ERR_MAX_CLIENTS,
VIDC_ERR_IFRAME_EXPECTED,
VIDC_ERR_HW_FATAL,
VIDC_ERR_BITSTREAM_ERR,
VIDC_ERR_INDEX_NOMORE,
VIDC_ERR_SEQHDR_PARSE_FAIL,
VIDC_ERR_INSUFFICIENT_BUFFER,
VIDC_ERR_BAD_POWER_STATE,
VIDC_ERR_NO_VALID_SESSION,
VIDC_ERR_TIMEOUT,
VIDC_ERR_CMDQFULL,
VIDC_ERR_CLIENT_PRESENT = 0x90000001,
VIDC_ERR_CLIENT_FATAL,
VIDC_ERR_CMD_QUEUE_FULL,
VIDC_ERR_UNUSED = 0x10000000
};
enum hal_extradata_id {
HAL_EXTRADATA_NONE,
HAL_EXTRADATA_MB_QUANTIZATION,
HAL_EXTRADATA_INTERLACE_VIDEO,
HAL_EXTRADATA_VC1_FRAMEDISP,
HAL_EXTRADATA_VC1_SEQDISP,
HAL_EXTRADATA_TIMESTAMP,
HAL_EXTRADATA_S3D_FRAME_PACKING,
HAL_EXTRADATA_FRAME_RATE,
HAL_EXTRADATA_PANSCAN_WINDOW,
HAL_EXTRADATA_RECOVERY_POINT_SEI,
HAL_EXTRADATA_MULTISLICE_INFO,
HAL_EXTRADATA_INDEX,
HAL_EXTRADATA_NUM_CONCEALED_MB,
HAL_EXTRADATA_METADATA_FILLER,
HAL_EXTRADATA_ASPECT_RATIO,
HAL_EXTRADATA_MPEG2_SEQDISP,
HAL_EXTRADATA_FRAME_QP,
HAL_EXTRADATA_FRAME_BITS_INFO,
HAL_EXTRADATA_LTR_INFO,
HAL_EXTRADATA_METADATA_MBI,
HAL_EXTRADATA_STREAM_USERDATA,
};
enum hal_property {
HAL_CONFIG_FRAME_RATE = 0x04000001,
HAL_PARAM_UNCOMPRESSED_FORMAT_SELECT,
HAL_PARAM_UNCOMPRESSED_PLANE_ACTUAL_CONSTRAINTS_INFO,
HAL_PARAM_UNCOMPRESSED_PLANE_ACTUAL_INFO,
HAL_PARAM_EXTRA_DATA_HEADER_CONFIG,
HAL_PARAM_INDEX_EXTRADATA,
HAL_PARAM_FRAME_SIZE,
HAL_CONFIG_REALTIME,
HAL_PARAM_BUFFER_COUNT_ACTUAL,
HAL_PARAM_NAL_STREAM_FORMAT_SELECT,
HAL_PARAM_VDEC_OUTPUT_ORDER,
HAL_PARAM_VDEC_PICTURE_TYPE_DECODE,
HAL_PARAM_VDEC_OUTPUT2_KEEP_ASPECT_RATIO,
HAL_CONFIG_VDEC_POST_LOOP_DEBLOCKER,
HAL_PARAM_VDEC_MULTI_STREAM,
HAL_PARAM_VDEC_DISPLAY_PICTURE_BUFFER_COUNT,
HAL_PARAM_DIVX_FORMAT,
HAL_CONFIG_VDEC_MB_ERROR_MAP_REPORTING,
HAL_PARAM_VDEC_CONTINUE_DATA_TRANSFER,
HAL_CONFIG_VDEC_MB_ERROR_MAP,
HAL_CONFIG_VENC_REQUEST_IFRAME,
HAL_PARAM_VENC_MPEG4_SHORT_HEADER,
HAL_PARAM_VENC_MPEG4_AC_PREDICTION,
HAL_CONFIG_VENC_TARGET_BITRATE,
HAL_PARAM_PROFILE_LEVEL_CURRENT,
HAL_PARAM_VENC_H264_ENTROPY_CONTROL,
HAL_PARAM_VENC_RATE_CONTROL,
HAL_PARAM_VENC_MPEG4_TIME_RESOLUTION,
HAL_PARAM_VENC_MPEG4_HEADER_EXTENSION,
HAL_PARAM_VENC_H264_DEBLOCK_CONTROL,
HAL_PARAM_VENC_TEMPORAL_SPATIAL_TRADEOFF,
HAL_PARAM_VENC_SESSION_QP,
HAL_PARAM_VENC_SESSION_QP_RANGE,
HAL_CONFIG_VENC_INTRA_PERIOD,
HAL_CONFIG_VENC_IDR_PERIOD,
HAL_CONFIG_VPE_OPERATIONS,
HAL_PARAM_VENC_INTRA_REFRESH,
HAL_PARAM_VENC_MULTI_SLICE_CONTROL,
HAL_CONFIG_VPE_DEINTERLACE,
HAL_SYS_DEBUG_CONFIG,
HAL_CONFIG_BUFFER_REQUIREMENTS,
HAL_CONFIG_PRIORITY,
HAL_CONFIG_BATCH_INFO,
HAL_PARAM_METADATA_PASS_THROUGH,
HAL_SYS_IDLE_INDICATOR,
HAL_PARAM_UNCOMPRESSED_FORMAT_SUPPORTED,
HAL_PARAM_INTERLACE_FORMAT_SUPPORTED,
HAL_PARAM_CHROMA_SITE,
HAL_PARAM_PROPERTIES_SUPPORTED,
HAL_PARAM_PROFILE_LEVEL_SUPPORTED,
HAL_PARAM_CAPABILITY_SUPPORTED,
HAL_PARAM_NAL_STREAM_FORMAT_SUPPORTED,
HAL_PARAM_MULTI_VIEW_FORMAT,
HAL_PARAM_MAX_SEQUENCE_HEADER_SIZE,
HAL_PARAM_CODEC_SUPPORTED,
HAL_PARAM_VDEC_MULTI_VIEW_SELECT,
HAL_PARAM_VDEC_MB_QUANTIZATION,
HAL_PARAM_VDEC_NUM_CONCEALED_MB,
HAL_PARAM_VDEC_H264_ENTROPY_SWITCHING,
HAL_PARAM_VENC_SLICE_DELIVERY_MODE,
HAL_PARAM_VENC_MPEG4_DATA_PARTITIONING,
HAL_CONFIG_BUFFER_COUNT_ACTUAL,
HAL_CONFIG_VDEC_MULTI_STREAM,
HAL_PARAM_VENC_MULTI_SLICE_INFO,
HAL_CONFIG_VENC_TIMESTAMP_SCALE,
HAL_PARAM_VENC_LOW_LATENCY,
HAL_PARAM_VENC_SYNC_FRAME_SEQUENCE_HEADER,
HAL_PARAM_VDEC_SYNC_FRAME_DECODE,
HAL_PARAM_VENC_H264_ENTROPY_CABAC_MODEL,
HAL_CONFIG_VENC_MAX_BITRATE,
HAL_PARAM_VENC_H264_VUI_TIMING_INFO,
HAL_PARAM_VENC_H264_GENERATE_AUDNAL,
HAL_PARAM_VENC_MAX_NUM_B_FRAMES,
HAL_PARAM_BUFFER_ALLOC_MODE,
HAL_PARAM_VDEC_FRAME_ASSEMBLY,
HAL_PARAM_VDEC_CONCEAL_COLOR,
HAL_PARAM_VENC_LTRMODE,
HAL_CONFIG_VENC_MARKLTRFRAME,
HAL_CONFIG_VENC_USELTRFRAME,
HAL_CONFIG_VENC_LTRPERIOD,
HAL_CONFIG_VENC_HIER_P_NUM_FRAMES,
HAL_PARAM_VENC_HIER_P_MAX_ENH_LAYERS,
HAL_PARAM_VENC_ENABLE_INITIAL_QP,
};
enum hal_domain {
HAL_VIDEO_DOMAIN_VPE,
HAL_VIDEO_DOMAIN_ENCODER,
HAL_VIDEO_DOMAIN_DECODER,
HAL_UNUSED_DOMAIN = 0x10000000,
};
enum multi_stream {
HAL_VIDEO_DECODER_NONE = 0x00000000,
HAL_VIDEO_DECODER_PRIMARY = 0x00000001,
HAL_VIDEO_DECODER_SECONDARY = 0x00000002,
HAL_VIDEO_DECODER_BOTH_OUTPUTS = 0x00000004,
HAL_VIDEO_UNUSED_OUTPUTS = 0x10000000,
};
enum hal_core_capabilities {
HAL_VIDEO_ENCODER_ROTATION_CAPABILITY = 0x00000001,
HAL_VIDEO_ENCODER_SCALING_CAPABILITY = 0x00000002,
HAL_VIDEO_ENCODER_DEINTERLACE_CAPABILITY = 0x00000004,
HAL_VIDEO_DECODER_MULTI_STREAM_CAPABILITY = 0x00000008,
HAL_VIDEO_UNUSED_CAPABILITY = 0x10000000,
};
enum hal_video_codec {
HAL_VIDEO_CODEC_UNKNOWN = 0x00000000,
HAL_VIDEO_CODEC_MVC = 0x00000001,
HAL_VIDEO_CODEC_H264 = 0x00000002,
HAL_VIDEO_CODEC_H263 = 0x00000004,
HAL_VIDEO_CODEC_MPEG1 = 0x00000008,
HAL_VIDEO_CODEC_MPEG2 = 0x00000010,
HAL_VIDEO_CODEC_MPEG4 = 0x00000020,
HAL_VIDEO_CODEC_DIVX_311 = 0x00000040,
HAL_VIDEO_CODEC_DIVX = 0x00000080,
HAL_VIDEO_CODEC_VC1 = 0x00000100,
HAL_VIDEO_CODEC_SPARK = 0x00000200,
HAL_VIDEO_CODEC_VP6 = 0x00000400,
HAL_VIDEO_CODEC_VP7 = 0x00000800,
HAL_VIDEO_CODEC_VP8 = 0x00001000,
HAL_VIDEO_CODEC_HEVC = 0x00002000,
HAL_VIDEO_CODEC_HEVC_HYBRID = 0x00004000,
HAL_UNUSED_CODEC = 0x10000000,
};
enum hal_h263_profile {
HAL_H263_PROFILE_BASELINE = 0x00000001,
HAL_H263_PROFILE_H320CODING = 0x00000002,
HAL_H263_PROFILE_BACKWARDCOMPATIBLE = 0x00000004,
HAL_H263_PROFILE_ISWV2 = 0x00000008,
HAL_H263_PROFILE_ISWV3 = 0x00000010,
HAL_H263_PROFILE_HIGHCOMPRESSION = 0x00000020,
HAL_H263_PROFILE_INTERNET = 0x00000040,
HAL_H263_PROFILE_INTERLACE = 0x00000080,
HAL_H263_PROFILE_HIGHLATENCY = 0x00000100,
HAL_UNUSED_H263_PROFILE = 0x10000000,
};
enum hal_h263_level {
HAL_H263_LEVEL_10 = 0x00000001,
HAL_H263_LEVEL_20 = 0x00000002,
HAL_H263_LEVEL_30 = 0x00000004,
HAL_H263_LEVEL_40 = 0x00000008,
HAL_H263_LEVEL_45 = 0x00000010,
HAL_H263_LEVEL_50 = 0x00000020,
HAL_H263_LEVEL_60 = 0x00000040,
HAL_H263_LEVEL_70 = 0x00000080,
HAL_UNUSED_H263_LEVEL = 0x10000000,
};
enum hal_mpeg2_profile {
HAL_MPEG2_PROFILE_SIMPLE = 0x00000001,
HAL_MPEG2_PROFILE_MAIN = 0x00000002,
HAL_MPEG2_PROFILE_422 = 0x00000004,
HAL_MPEG2_PROFILE_SNR = 0x00000008,
HAL_MPEG2_PROFILE_SPATIAL = 0x00000010,
HAL_MPEG2_PROFILE_HIGH = 0x00000020,
HAL_UNUSED_MPEG2_PROFILE = 0x10000000,
};
enum hal_mpeg2_level {
HAL_MPEG2_LEVEL_LL = 0x00000001,
HAL_MPEG2_LEVEL_ML = 0x00000002,
HAL_MPEG2_LEVEL_H14 = 0x00000004,
HAL_MPEG2_LEVEL_HL = 0x00000008,
HAL_UNUSED_MEPG2_LEVEL = 0x10000000,
};
enum hal_mpeg4_profile {
HAL_MPEG4_PROFILE_SIMPLE = 0x00000001,
HAL_MPEG4_PROFILE_ADVANCEDSIMPLE = 0x00000002,
HAL_MPEG4_PROFILE_CORE = 0x00000004,
HAL_MPEG4_PROFILE_MAIN = 0x00000008,
HAL_MPEG4_PROFILE_NBIT = 0x00000010,
HAL_MPEG4_PROFILE_SCALABLETEXTURE = 0x00000020,
HAL_MPEG4_PROFILE_SIMPLEFACE = 0x00000040,
HAL_MPEG4_PROFILE_SIMPLEFBA = 0x00000080,
HAL_MPEG4_PROFILE_BASICANIMATED = 0x00000100,
HAL_MPEG4_PROFILE_HYBRID = 0x00000200,
HAL_MPEG4_PROFILE_ADVANCEDREALTIME = 0x00000400,
HAL_MPEG4_PROFILE_CORESCALABLE = 0x00000800,
HAL_MPEG4_PROFILE_ADVANCEDCODING = 0x00001000,
HAL_MPEG4_PROFILE_ADVANCEDCORE = 0x00002000,
HAL_MPEG4_PROFILE_ADVANCEDSCALABLE = 0x00004000,
HAL_MPEG4_PROFILE_SIMPLESCALABLE = 0x00008000,
HAL_UNUSED_MPEG4_PROFILE = 0x10000000,
};
enum hal_mpeg4_level {
HAL_MPEG4_LEVEL_0 = 0x00000001,
HAL_MPEG4_LEVEL_0b = 0x00000002,
HAL_MPEG4_LEVEL_1 = 0x00000004,
HAL_MPEG4_LEVEL_2 = 0x00000008,
HAL_MPEG4_LEVEL_3 = 0x00000010,
HAL_MPEG4_LEVEL_4 = 0x00000020,
HAL_MPEG4_LEVEL_4a = 0x00000040,
HAL_MPEG4_LEVEL_5 = 0x00000080,
HAL_MPEG4_LEVEL_VENDOR_START_UNUSED = 0x7F000000,
HAL_MPEG4_LEVEL_6 = 0x7F000001,
HAL_MPEG4_LEVEL_7 = 0x7F000002,
HAL_MPEG4_LEVEL_8 = 0x7F000003,
HAL_MPEG4_LEVEL_9 = 0x7F000004,
HAL_MPEG4_LEVEL_3b = 0x7F000005,
HAL_UNUSED_MPEG4_LEVEL = 0x10000000,
};
enum hal_h264_profile {
HAL_H264_PROFILE_BASELINE = 0x00000001,
HAL_H264_PROFILE_MAIN = 0x00000002,
HAL_H264_PROFILE_HIGH = 0x00000004,
HAL_H264_PROFILE_EXTENDED = 0x00000008,
HAL_H264_PROFILE_HIGH10 = 0x00000010,
HAL_H264_PROFILE_HIGH422 = 0x00000020,
HAL_H264_PROFILE_HIGH444 = 0x00000040,
HAL_H264_PROFILE_CONSTRAINED_BASE = 0x00000080,
HAL_H264_PROFILE_CONSTRAINED_HIGH = 0x00000100,
HAL_UNUSED_H264_PROFILE = 0x10000000,
};
enum hal_h264_level {
HAL_H264_LEVEL_1 = 0x00000001,
HAL_H264_LEVEL_1b = 0x00000002,
HAL_H264_LEVEL_11 = 0x00000004,
HAL_H264_LEVEL_12 = 0x00000008,
HAL_H264_LEVEL_13 = 0x00000010,
HAL_H264_LEVEL_2 = 0x00000020,
HAL_H264_LEVEL_21 = 0x00000040,
HAL_H264_LEVEL_22 = 0x00000080,
HAL_H264_LEVEL_3 = 0x00000100,
HAL_H264_LEVEL_31 = 0x00000200,
HAL_H264_LEVEL_32 = 0x00000400,
HAL_H264_LEVEL_4 = 0x00000800,
HAL_H264_LEVEL_41 = 0x00001000,
HAL_H264_LEVEL_42 = 0x00002000,
HAL_H264_LEVEL_5 = 0x00004000,
HAL_H264_LEVEL_51 = 0x00008000,
HAL_H264_LEVEL_52 = 0x00010000,
HAL_UNUSED_H264_LEVEL = 0x10000000,
};
enum hal_vpx_profile {
HAL_VPX_PROFILE_SIMPLE = 0x00000001,
HAL_VPX_PROFILE_ADVANCED = 0x00000002,
HAL_VPX_PROFILE_VERSION_0 = 0x00000004,
HAL_VPX_PROFILE_VERSION_1 = 0x00000008,
HAL_VPX_PROFILE_VERSION_2 = 0x00000010,
HAL_VPX_PROFILE_VERSION_3 = 0x00000020,
HAL_VPX_PROFILE_UNUSED = 0x10000000,
};
enum hal_vc1_profile {
HAL_VC1_PROFILE_SIMPLE = 0x00000001,
HAL_VC1_PROFILE_MAIN = 0x00000002,
HAL_VC1_PROFILE_ADVANCED = 0x00000004,
HAL_UNUSED_VC1_PROFILE = 0x10000000,
};
enum hal_vc1_level {
HAL_VC1_LEVEL_LOW = 0x00000001,
HAL_VC1_LEVEL_MEDIUM = 0x00000002,
HAL_VC1_LEVEL_HIGH = 0x00000004,
HAL_VC1_LEVEL_0 = 0x00000008,
HAL_VC1_LEVEL_1 = 0x00000010,
HAL_VC1_LEVEL_2 = 0x00000020,
HAL_VC1_LEVEL_3 = 0x00000040,
HAL_VC1_LEVEL_4 = 0x00000080,
HAL_UNUSED_VC1_LEVEL = 0x10000000,
};
enum hal_divx_format {
HAL_DIVX_FORMAT_4,
HAL_DIVX_FORMAT_5,
HAL_DIVX_FORMAT_6,
HAL_UNUSED_DIVX_FORMAT = 0x10000000,
};
enum hal_divx_profile {
HAL_DIVX_PROFILE_QMOBILE = 0x00000001,
HAL_DIVX_PROFILE_MOBILE = 0x00000002,
HAL_DIVX_PROFILE_MT = 0x00000004,
HAL_DIVX_PROFILE_HT = 0x00000008,
HAL_DIVX_PROFILE_HD = 0x00000010,
HAL_UNUSED_DIVX_PROFILE = 0x10000000,
};
enum hal_mvc_profile {
HAL_MVC_PROFILE_STEREO_HIGH = 0x00000001,
HAL_MVC_PROFILE_MV_HIGH = 0x00000002,
HAL_UNUSED_MVC_PROFILE = 0x10000000,
};
enum hal_mvc_level {
HAL_MVC_LEVEL_1 = 0x00000001,
HAL_MVC_LEVEL_1b = 0x00000002,
HAL_MVC_LEVEL_11 = 0x00000004,
HAL_MVC_LEVEL_12 = 0x00000008,
HAL_MVC_LEVEL_13 = 0x00000010,
HAL_MVC_LEVEL_2 = 0x00000020,
HAL_MVC_LEVEL_21 = 0x00000040,
HAL_MVC_LEVEL_22 = 0x00000080,
HAL_MVC_LEVEL_3 = 0x00000100,
HAL_MVC_LEVEL_31 = 0x00000200,
HAL_MVC_LEVEL_32 = 0x00000400,
HAL_MVC_LEVEL_4 = 0x00000800,
HAL_MVC_LEVEL_41 = 0x00001000,
HAL_MVC_LEVEL_42 = 0x00002000,
HAL_MVC_LEVEL_5 = 0x00004000,
HAL_MVC_LEVEL_51 = 0x00008000,
HAL_UNUSED_MVC_LEVEL = 0x10000000,
};
struct hal_frame_rate {
enum hal_buffer buffer_type;
u32 frame_rate;
};
enum hal_uncompressed_format {
HAL_COLOR_FORMAT_MONOCHROME = 0x00000001,
HAL_COLOR_FORMAT_NV12 = 0x00000002,
HAL_COLOR_FORMAT_NV21 = 0x00000004,
HAL_COLOR_FORMAT_NV12_4x4TILE = 0x00000008,
HAL_COLOR_FORMAT_NV21_4x4TILE = 0x00000010,
HAL_COLOR_FORMAT_YUYV = 0x00000020,
HAL_COLOR_FORMAT_YVYU = 0x00000040,
HAL_COLOR_FORMAT_UYVY = 0x00000080,
HAL_COLOR_FORMAT_VYUY = 0x00000100,
HAL_COLOR_FORMAT_RGB565 = 0x00000200,
HAL_COLOR_FORMAT_BGR565 = 0x00000400,
HAL_COLOR_FORMAT_RGB888 = 0x00000800,
HAL_COLOR_FORMAT_BGR888 = 0x00001000,
HAL_UNUSED_COLOR = 0x10000000,
};
enum hal_ssr_trigger_type {
SSR_ERR_FATAL = 1,
SSR_SW_DIV_BY_ZERO,
SSR_HW_WDOG_IRQ,
};
struct hal_uncompressed_format_select {
enum hal_buffer buffer_type;
enum hal_uncompressed_format format;
};
struct hal_uncompressed_plane_actual {
int actual_stride;
u32 actual_plane_buffer_height;
};
struct hal_uncompressed_plane_actual_info {
enum hal_buffer buffer_type;
u32 num_planes;
struct hal_uncompressed_plane_actual rg_plane_format[1];
};
struct hal_uncompressed_plane_constraints {
u32 stride_multiples;
u32 max_stride;
u32 min_plane_buffer_height_multiple;
u32 buffer_alignment;
};
struct hal_uncompressed_plane_actual_constraints_info {
enum hal_buffer buffer_type;
u32 num_planes;
struct hal_uncompressed_plane_constraints rg_plane_format[1];
};
struct hal_extra_data_header_config {
u32 type;
enum hal_buffer buffer_type;
u32 version;
u32 port_index;
u32 client_extradata_id;
};
struct hal_frame_size {
enum hal_buffer buffer_type;
u32 width;
u32 height;
};
struct hal_enable {
u32 enable;
};
struct hal_buffer_count_actual {
enum hal_buffer buffer_type;
u32 buffer_count_actual;
};
enum hal_nal_stream_format {
HAL_NAL_FORMAT_STARTCODES = 0x00000001,
HAL_NAL_FORMAT_ONE_NAL_PER_BUFFER = 0x00000002,
HAL_NAL_FORMAT_ONE_BYTE_LENGTH = 0x00000004,
HAL_NAL_FORMAT_TWO_BYTE_LENGTH = 0x00000008,
HAL_NAL_FORMAT_FOUR_BYTE_LENGTH = 0x00000010,
};
enum hal_output_order {
HAL_OUTPUT_ORDER_DISPLAY,
HAL_OUTPUT_ORDER_DECODE,
HAL_UNUSED_OUTPUT = 0x10000000,
};
enum hal_picture {
HAL_PICTURE_I = 0x01,
HAL_PICTURE_P = 0x02,
HAL_PICTURE_B = 0x04,
HAL_PICTURE_IDR = 0x08,
HAL_FRAME_NOTCODED = 0x7F002000,
HAL_FRAME_YUV = 0x7F004000,
HAL_UNUSED_PICT = 0x10000000,
};
struct hal_extradata_enable {
u32 enable;
enum hal_extradata_id index;
};
struct hal_enable_picture {
u32 picture_type;
};
struct hal_multi_stream {
enum hal_buffer buffer_type;
u32 enable;
u32 width;
u32 height;
};
struct hal_display_picture_buffer_count {
u32 enable;
u32 count;
};
struct hal_mb_error_map {
u32 error_map_size;
u8 rg_error_map[1];
};
struct hal_request_iframe {
u32 enable;
};
struct hal_bitrate {
u32 bit_rate;
u32 layer_id;
};
struct hal_profile_level {
u32 profile;
u32 level;
};
/*
struct hal_profile_level_range {
u32 profile;
u32 min_level;
u32 max_level;
}
struct hal_profile_level_supported {
u32 profile_count;
struct hal_profile_level_range profile_level[1];
};
*/
enum hal_h264_entropy {
HAL_H264_ENTROPY_CAVLC = 1,
HAL_H264_ENTROPY_CABAC = 2,
HAL_UNUSED_ENTROPY = 0x10000000,
};
enum hal_h264_cabac_model {
HAL_H264_CABAC_MODEL_0 = 1,
HAL_H264_CABAC_MODEL_1 = 2,
HAL_H264_CABAC_MODEL_2 = 4,
HAL_UNUSED_CABAC = 0x10000000,
};
struct hal_h264_entropy_control {
enum hal_h264_entropy entropy_mode;
enum hal_h264_cabac_model cabac_model;
};
enum hal_rate_control {
HAL_RATE_CONTROL_OFF,
HAL_RATE_CONTROL_VBR_VFR,
HAL_RATE_CONTROL_VBR_CFR,
HAL_RATE_CONTROL_CBR_VFR,
HAL_RATE_CONTROL_CBR_CFR,
HAL_UNUSED_RC = 0x10000000,
};
struct hal_mpeg4_time_resolution {
u32 time_increment_resolution;
};
struct hal_mpeg4_header_extension {
u32 header_extension;
};
enum hal_h264_db_mode {
HAL_H264_DB_MODE_DISABLE,
HAL_H264_DB_MODE_SKIP_SLICE_BOUNDARY,
HAL_H264_DB_MODE_ALL_BOUNDARY,
HAL_UNUSED_H264_DB = 0x10000000,
};
struct hal_h264_db_control {
enum hal_h264_db_mode mode;
int slice_alpha_offset;
int slice_beta_offset;
};
struct hal_temporal_spatial_tradeoff {
u32 ts_factor;
};
struct hal_quantization {
u32 qpi;
u32 qpp;
u32 qpb;
u32 layer_id;
};
struct hal_initial_quantization {
u32 qpi;
u32 qpp;
u32 qpb;
u32 initqp_enable;
};
struct hal_quantization_range {
u32 min_qp;
u32 max_qp;
u32 layer_id;
};
struct hal_intra_period {
u32 pframes;
u32 bframes;
};
struct hal_idr_period {
u32 idr_period;
};
enum hal_rotate {
HAL_ROTATE_NONE,
HAL_ROTATE_90,
HAL_ROTATE_180,
HAL_ROTATE_270,
HAL_UNUSED_ROTATE = 0x10000000,
};
enum hal_flip {
HAL_FLIP_NONE,
HAL_FLIP_HORIZONTAL,
HAL_FLIP_VERTICAL,
HAL_UNUSED_FLIP = 0x10000000,
};
struct hal_operations {
enum hal_rotate rotate;
enum hal_flip flip;
};
enum hal_intra_refresh_mode {
HAL_INTRA_REFRESH_NONE,
HAL_INTRA_REFRESH_CYCLIC,
HAL_INTRA_REFRESH_ADAPTIVE,
HAL_INTRA_REFRESH_CYCLIC_ADAPTIVE,
HAL_INTRA_REFRESH_RANDOM,
HAL_UNUSED_INTRA = 0x10000000,
};
struct hal_intra_refresh {
enum hal_intra_refresh_mode mode;
u32 air_mbs;
u32 air_ref;
u32 cir_mbs;
};
enum hal_multi_slice {
HAL_MULTI_SLICE_OFF,
HAL_MULTI_SLICE_BY_MB_COUNT,
HAL_MULTI_SLICE_BY_BYTE_COUNT,
HAL_MULTI_SLICE_GOB,
HAL_UNUSED_SLICE = 0x10000000,
};
struct hal_multi_slice_control {
enum hal_multi_slice multi_slice;
u32 slice_size;
};
struct hal_debug_config {
u32 debug_config;
};
struct hal_buffer_requirements {
enum hal_buffer buffer_type;
u32 buffer_size;
u32 buffer_region_size;
u32 buffer_hold_count;
u32 buffer_count_min;
u32 buffer_count_actual;
u32 contiguous;
u32 buffer_alignment;
};
enum hal_priority {/* Priority increases with number */
HAL_PRIORITY_LOW = 10,
HAL_PRIOIRTY_MEDIUM = 20,
HAL_PRIORITY_HIGH = 30,
HAL_UNUSED_PRIORITY = 0x10000000,
};
struct hal_batch_info {
u32 input_batch_count;
u32 output_batch_count;
};
struct hal_metadata_pass_through {
u32 enable;
u32 size;
};
struct hal_uncompressed_format_supported {
enum hal_buffer buffer_type;
u32 format_entries;
u32 rg_format_info[1];
};
enum hal_interlace_format {
HAL_INTERLACE_FRAME_PROGRESSIVE = 0x01,
HAL_INTERLACE_INTERLEAVE_FRAME_TOPFIELDFIRST = 0x02,
HAL_INTERLACE_INTERLEAVE_FRAME_BOTTOMFIELDFIRST = 0x04,
HAL_INTERLACE_FRAME_TOPFIELDFIRST = 0x08,
HAL_INTERLACE_FRAME_BOTTOMFIELDFIRST = 0x10,
HAL_UNUSED_INTERLACE = 0x10000000,
};
struct hal_interlace_format_supported {
enum hal_buffer buffer_type;
enum hal_interlace_format format;
};
enum hal_chroma_site {
HAL_CHROMA_SITE_0,
HAL_CHROMA_SITE_1,
HAL_UNUSED_CHROMA = 0x10000000,
};
struct hal_properties_supported {
u32 num_properties;
u32 rg_properties[1];
};
enum hal_capability {
HAL_CAPABILITY_FRAME_WIDTH,
HAL_CAPABILITY_FRAME_HEIGHT,
HAL_CAPABILITY_MBS_PER_FRAME,
HAL_CAPABILITY_MBS_PER_SECOND,
HAL_CAPABILITY_FRAMERATE,
HAL_CAPABILITY_SCALE_X,
HAL_CAPABILITY_SCALE_Y,
HAL_CAPABILITY_BITRATE,
HAL_UNUSED_CAPABILITY = 0x10000000,
};
struct hal_capability_supported {
enum hal_capability capability_type;
u32 min;
u32 max;
u32 step_size;
};
struct hal_capability_supported_info {
u32 num_capabilities;
struct hal_capability_supported rg_data[1];
};
struct hal_nal_stream_format_supported {
u32 nal_stream_format_supported;
};
struct hal_nal_stream_format_select {
u32 nal_stream_format_select;
};
struct hal_multi_view_format {
u32 views;
u32 rg_view_order[1];
};
struct hal_seq_header_info {
u32 nax_header_len;
};
struct hal_codec_supported {
u32 decoder_codec_supported;
u32 encoder_codec_supported;
};
struct hal_multi_view_select {
u32 view_index;
};
struct hal_timestamp_scale {
u32 time_stamp_scale;
};
struct hal_h264_vui_timing_info {
u32 enable;
u32 fixed_frame_rate;
u32 time_scale;
};
enum vidc_resource_id {
VIDC_RESOURCE_OCMEM = 0x00000001,
VIDC_UNUSED_RESORUCE = 0x10000000,
};
struct vidc_resource_hdr {
enum vidc_resource_id resource_id;
u32 resource_handle;
u32 size;
};
struct vidc_buffer_addr_info {
enum hal_buffer buffer_type;
u32 buffer_size;
u32 num_buffers;
u32 align_device_addr;
u32 extradata_size;
u32 extradata_addr;
u32 response_required;
};
struct hal_buffer_info {
u32 buffer_addr;
u32 extra_data_addr;
};
struct vidc_frame_plane_config {
u32 left;
u32 top;
u32 width;
u32 height;
u32 stride;
u32 scan_lines;
};
struct vidc_uncompressed_frame_config {
struct vidc_frame_plane_config luma_plane;
struct vidc_frame_plane_config chroma_plane;
};
struct vidc_frame_data {
enum hal_buffer buffer_type;
u32 device_addr;
u32 extradata_addr;
int64_t timestamp;
u32 flags;
u32 offset;
u32 alloc_len;
u32 filled_len;
u32 mark_target;
u32 mark_data;
u32 clnt_data;
u32 extradata_size;
};
struct vidc_seq_hdr {
u8 *seq_hdr;
u32 seq_hdr_len;
};
enum hal_flush {
HAL_FLUSH_INPUT,
HAL_FLUSH_OUTPUT,
HAL_FLUSH_OUTPUT2,
HAL_FLUSH_ALL,
HAL_UNUSED_FLUSH = 0x10000000,
};
enum hal_event_type {
HAL_EVENT_SEQ_CHANGED_SUFFICIENT_RESOURCES,
HAL_EVENT_SEQ_CHANGED_INSUFFICIENT_RESOURCES,
HAL_EVENT_RELEASE_BUFFER_REFERENCE,
HAL_UNUSED_SEQCHG = 0x10000000,
};
enum buffer_mode_type {
HAL_BUFFER_MODE_STATIC = 0x001,
HAL_BUFFER_MODE_RING = 0x010,
HAL_BUFFER_MODE_DYNAMIC = 0x100,
};
struct hal_buffer_alloc_mode {
enum hal_buffer buffer_type;
enum buffer_mode_type buffer_mode;
};
enum ltr_mode {
HAL_LTR_MODE_DISABLE,
HAL_LTR_MODE_MANUAL,
HAL_LTR_MODE_PERIODIC,
};
struct hal_ltrmode {
enum ltr_mode ltrmode;
u32 ltrcount;
u32 trustmode;
};
struct hal_ltruse {
u32 refltr;
u32 useconstrnt;
u32 frames;
};
struct hal_ltrmark {
u32 markframe;
};
/* HAL Response */
enum command_response {
/* SYSTEM COMMANDS_DONE*/
VIDC_EVENT_CHANGE,
SYS_INIT_DONE,
SET_RESOURCE_DONE,
RELEASE_RESOURCE_DONE,
PING_ACK_DONE,
PC_PREP_DONE,
SYS_IDLE,
SYS_DEBUG,
SYS_WATCHDOG_TIMEOUT,
SYS_ERROR,
/* SESSION COMMANDS_DONE */
SESSION_LOAD_RESOURCE_DONE,
SESSION_INIT_DONE,
SESSION_END_DONE,
SESSION_ABORT_DONE,
SESSION_START_DONE,
SESSION_STOP_DONE,
SESSION_ETB_DONE,
SESSION_FTB_DONE,
SESSION_FLUSH_DONE,
SESSION_SUSPEND_DONE,
SESSION_RESUME_DONE,
SESSION_SET_PROP_DONE,
SESSION_GET_PROP_DONE,
SESSION_PARSE_SEQ_HDR_DONE,
SESSION_GET_SEQ_HDR_DONE,
SESSION_RELEASE_BUFFER_DONE,
SESSION_RELEASE_RESOURCE_DONE,
SESSION_PROPERTY_INFO,
SESSION_ERROR,
RESPONSE_UNUSED = 0x10000000,
};
/* Command Callback structure */
struct msm_vidc_cb_cmd_done {
u32 device_id;
u32 session_id;
u32 status;
u32 size;
void *data;
};
struct msm_vidc_cb_event {
u32 device_id;
u32 session_id;
u32 status;
u32 height;
u32 width;
u32 hal_event_type;
u8 *packet_buffer;
u8 *exra_data_buffer;
};
/* Data callback structure */
struct vidc_hal_ebd {
u32 timestamp_hi;
u32 timestamp_lo;
u32 flags;
u32 status;
u32 mark_target;
u32 mark_data;
u32 stats;
u32 offset;
u32 alloc_len;
u32 filled_len;
enum hal_picture picture_type;
u8 *packet_buffer;
u8 *extra_data_buffer;
};
struct vidc_hal_fbd {
u32 stream_id;
u32 view_id;
u32 timestamp_hi;
u32 timestamp_lo;
u32 flags1;
u32 mark_target;
u32 mark_data;
u32 stats;
u32 alloc_len1;
u32 filled_len1;
u32 offset1;
u32 frame_width;
u32 frame_height;
u32 start_x_coord;
u32 start_y_coord;
u32 input_tag;
u32 input_tag1;
enum hal_picture picture_type;
u8 *packet_buffer1;
u8 *extra_data_buffer;
u32 flags2;
u32 alloc_len2;
u32 filled_len2;
u32 offset2;
u8 *packet_buffer2;
u32 flags3;
u32 alloc_len3;
u32 filled_len3;
u32 offset3;
u8 *packet_buffer3;
enum hal_buffer buffer_type;
};
struct msm_vidc_cb_data_done {
u32 device_id;
u32 session_id;
u32 status;
u32 size;
void *clnt_data;
union {
struct vidc_hal_ebd input_done;
struct vidc_hal_fbd output_done;
};
};
struct vidc_hal_sys_init_done {
u32 enc_codec_supported;
u32 dec_codec_supported;
};
struct vidc_hal_session_init_done {
struct hal_capability_supported width;
struct hal_capability_supported height;
struct hal_capability_supported mbs_per_frame;
struct hal_capability_supported mbs_per_sec;
struct hal_capability_supported frame_rate;
struct hal_capability_supported scale_x;
struct hal_capability_supported scale_y;
struct hal_capability_supported bitrate;
struct hal_capability_supported ltr_count;
struct hal_capability_supported hier_p;
struct hal_uncompressed_format_supported uncomp_format;
struct hal_interlace_format_supported HAL_format;
struct hal_nal_stream_format_supported nal_stream_format;
struct hal_intra_refresh intra_refresh;
struct hal_seq_header_info seq_hdr_info;
enum buffer_mode_type alloc_mode_out;
};
struct buffer_requirements {
struct hal_buffer_requirements buffer[HAL_BUFFER_MAX];
};
enum msm_vidc_hfi_type {
VIDC_HFI_VENUS,
VIDC_HFI_Q6,
};
enum mem_type {
DDR_MEM = 0x1,
OCMEM_MEM = 0x2,
};
enum fw_info {
FW_BASE_ADDRESS,
FW_REGISTER_BASE,
FW_REGISTER_SIZE,
FW_IRQ,
FW_INFO_MAX,
};
enum dev_info {
DEV_CLOCK_COUNT,
DEV_CLOCK_ENABLED,
DEV_PWR_COUNT,
DEV_PWR_ENABLED,
DEV_INFO_MAX
};
#define call_hfi_op(q, op, args...) \
(((q) && (q)->op) ? ((q)->op(args)) : 0)
struct hfi_device {
void *hfi_device_data;
/*Add function pointers for all the hfi functions below*/
int (*core_init)(void *device);
int (*core_release)(void *device);
int (*core_pc_prep)(void *device);
int (*core_ping)(void *device);
int (*core_trigger_ssr)(void *device, enum hal_ssr_trigger_type);
void *(*session_init)(void *device, u32 session_id,
enum hal_domain session_type, enum hal_video_codec codec_type);
int (*session_end)(void *session);
int (*session_abort)(void *session);
int (*session_set_buffers)(void *sess,
struct vidc_buffer_addr_info *buffer_info);
int (*session_release_buffers)(void *sess,
struct vidc_buffer_addr_info *buffer_info);
int (*session_load_res)(void *sess);
int (*session_release_res)(void *sess);
int (*session_start)(void *sess);
int (*session_stop)(void *sess);
int (*session_suspend)(void *sess);
int (*session_resume)(void *sess);
int (*session_etb)(void *sess,
struct vidc_frame_data *input_frame);
int (*session_ftb)(void *sess,
struct vidc_frame_data *output_frame);
int (*session_parse_seq_hdr)(void *sess,
struct vidc_seq_hdr *seq_hdr);
int (*session_get_seq_hdr)(void *sess,
struct vidc_seq_hdr *seq_hdr);
int (*session_get_buf_req)(void *sess);
int (*session_flush)(void *sess, enum hal_flush flush_mode);
int (*session_set_property)(void *sess, enum hal_property ptype,
void *pdata);
int (*session_get_property)(void *sess, enum hal_property ptype,
void *pdata);
int (*scale_clocks)(void *dev, int load);
int (*scale_bus)(void *dev, int load,
enum session_type type, enum mem_type mtype);
int (*unvote_bus)(void *dev, enum session_type type,
enum mem_type mtype);
int (*iommu_get_domain_partition)(void *dev, u32 flags, u32 buffer_type,
int *domain_num, int *partition_num);
int (*load_fw)(void *dev);
void (*unload_fw)(void *dev);
int (*resurrect_fw)(void *dev);
int (*get_fw_info)(void *dev, enum fw_info info);
int (*get_info) (void *dev, enum dev_info info);
int (*get_stride_scanline)(int color_fmt, int width,
int height, int *stride, int *scanlines);
int (*capability_check)(u32 fourcc, u32 width,
u32 *max_width, u32 *max_height);
int (*session_clean)(void *sess);
int (*get_core_capabilities)(void);
int (*power_enable)(void *dev);
int (*suspend)(void *dev);
};
typedef void (*hfi_cmd_response_callback) (enum command_response cmd,
void *data);
typedef void (*msm_vidc_callback) (u32 response, void *callback);
void *vidc_hfi_initialize(enum msm_vidc_hfi_type hfi_type, u32 device_id,
struct msm_vidc_platform_resources *res,
hfi_cmd_response_callback callback);
void vidc_hfi_deinitialize(enum msm_vidc_hfi_type hfi_type,
struct hfi_device *hdev);
#endif /*__VIDC_HFI_API_H__ */
|
invisiblek/android_kernel_lge_msm8610
|
drivers/media/platform/msm/vidc/vidc_hfi_api.h
|
C
|
gpl-2.0
| 29,080
|
#
# $Id$
# Copyright (C) 2004 Pascal Brisset, Antoine Drouin
#
# This file is part of paparazzi.
#
# paparazzi is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# paparazzi 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 paparazzi; see the file COPYING. If not, write to
# the Free Software Foundation, 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
#
# Quiet compilation
Q=@
OCAMLC = ocamlc
OCAMLOPT = ocamlopt
INCLUDES= $(shell ocamlfind query -r -i-format xml-light) $(shell ocamlfind query -r -i-format lablgtk2) -I ../lib/ocaml
all: play plotter plot sd2log plotprofile openlog2tlm
play : log_file.cmo play_core.cmo play.cmo
@echo OL $@
$(Q)$(OCAMLC) $(INCLUDES) -custom -o $@ unix.cma str.cma xml-light.cma glibivy-ocaml.cma $(shell ocamlfind query -r -i-format lablgtk2) -I ../lib/ocaml lablgtk.cma lib-pprz.cma gtkInit.cmo $^
play-nox : play_core.cmo play-nox.cmo
@echo OL $@
$(Q)$(OCAMLC) $(INCLUDES) -custom -o $@ unix.cma str.cma xml-light.cma glibivy-ocaml.cma $(shell ocamlfind query -r -i-format lablgtk2) -I ../lib/ocaml lablgtk.cma lib-pprz.cma $^
plotter : plotter.cmo
@echo OL $@
$(Q)$(OCAMLC) $(INCLUDES) -custom -o $@ unix.cma str.cma xml-light.cma glibivy-ocaml.cma lablgtk.cma lib-pprz.cma xlib-pprz.cma gtkInit.cmo $^
plot : log_file.cmx gtk_export.cmx export.cmx plot.cmx
@echo OL $@
$(Q)$(OCAMLOPT) $(INCLUDES) -o $@ unix.cmxa str.cmxa xml-light.cmxa glibivy-ocaml.cmxa lablgtk.cmxa lib-pprz.cmxa xlib-pprz.cmxa lablglade.cmxa gtkInit.cmx $^
sd2log : sd2log.cmo
@echo OL $@
$(Q)$(OCAMLC) $(INCLUDES) -custom -o $@ unix.cma str.cma xml-light.cma glibivy-ocaml.cma lib-pprz.cma $^
CC = gcc
CFLAGS=-g -O2 -Wall
LDFLAGS=
openlog2tlm: openlog2tlm.c
$(CC) $(CFLAGS) -g -o $@ $^
play play-nox plotter sd2log : ../lib/ocaml/lib-pprz.cma
plot : ../lib/ocaml/lib-pprz.cmxa
# Target for bytecode executable (if ocamlopt is not available)
# plot : log_file.cmo gtk_export.cmo export.cmo plot.cmo
# @echo OL $@
# $(Q)$(OCAMLC) $(INCLUDES) -o $@ unix.cma str.cma xml-light.cma glibivy-ocaml.cma lablgtk.cma lib-pprz.cma lablglade.cma gtkInit.cmo $^
%.cmo: %.ml
@echo OC $<
$(Q)$(OCAMLC) $(OCAMLCFLAGS) $(INCLUDES) -c $<
%.cmi: %.mli
@echo OCI $<
$(Q)$(OCAMLC) $(OCAMLCFLAGS) $(INCLUDES) -c $<
%.cmx: %.ml
@echo OOC $<
$(Q)$(OCAMLOPT) $(OCAMLCFLAGS) $(INCLUDES) -c $<
export.cmo : gtk_export.cmo
export.cmx : gtk_export.cmx
gtk_export.ml : export.glade
grep -v invisible_char $< > /tmp/$<
lablgladecc2 -root export -hide-default /tmp/$< | grep -B 1000000 " end" > $@
pt : ahrsview imuview ahrs2fg
CC = gcc
CFLAGS=-g -O2 -Wall `pkg-config gtk+-2.0 --cflags`
LDFLAGS=`pkg-config gtk+-2.0 --libs` -s -lgtkdatabox -lglibivy
motor_bench : motor_bench.c sliding_plot.c
$(CC) $(CFLAGS) -g -o $@ $^ $(LDFLAGS)
ahrsview : ahrsview.c sliding_plot.c
$(CC) $(CFLAGS) -g -o $@ $^ $(LDFLAGS)
imuview : imuview.c sliding_plot.c
$(CC) $(CFLAGS) -g -o $@ $^ $(LDFLAGS)
plot_roll_loop : plot_roll_loop.c sliding_plot.c
$(CC) $(CFLAGS) -g -o $@ $^ $(LDFLAGS)
test_sliding_plot: test_sliding_plot.c sliding_plot.c
$(CC) $(CFLAGS) -g -o $@ $^ $(LDFLAGS)
UNAME = $(shell uname -s)
ifeq ("$(UNAME)","Darwin")
IVY_C_LIBRARYS = $(shell if test -d /opt/paparazzi/lib; then echo "-L/opt/paparazzi/lib"; elif test -d /opt/local/lib; then echo "-L/opt/local/lib"; fi)
IVY_C_INCLUDES = $(shell if test -d /opt/paparazzi/include; then echo "-I/opt/paparazzi/include"; elif test -d /opt/local/include; then echo "-I/opt/local/include"; fi)
endif
MORE_FLAGS = -I/usr/include/gtk-1.2 -I/usr/include/glib-1.2 -I/usr/lib/glib/include -rdynamic /usr/lib/libgtkgl.so -L/usr/lib -L/usr/X11R6/lib /usr/lib/libgtk.so /usr/lib/libgdk.so /usr/lib/libgmodule.so /usr/lib/libglib.so -ldl -lXi -lXext -lX11 -lm -lGLU -lGL -Wl,--rpath -Wl,/usr/local/lib -lglibivy `pcre-config --libs`
MORE_CFLAGS = -DHAVE_DLFCN_H=1 -DSTDC_HEADERS=1 -I. -I. -I.. -g -O2 -I/usr/include/gtk-1.2 -I/usr/include/glib-1.2 -I/usr/lib/glib/include
disp3d: disp3d.c
$(CC) $(MORE_CFLAGS) -g -o $@ $^ $(MORE_FLAGS)
plotprofile: plotprofile.c
$(CC) $(IVY_C_LIBRARYS) $(IVY_C_INCLUDES) -g -O2 -Wall `pkg-config glib-2.0 --cflags` -o $@ $^ `pkg-config glib-2.0 --libs` -lglibivy -lpcre
test1: test1.c
$(CC) $(MORE_CFLAGS) -g -o $@ $^ $(MORE_FLAGS) -lglut
test3: test3.c sliding_plot.c
$(CC) $(CFLAGS) -g -o $@ $^ $(LDFLAGS)
#FGFS_PREFIX=/home/poine/local
FGFS_PREFIX=/home/poine/flightgear
#FGFS_PREFIX=/usr/local
#FGFS_ROOT = /home/poine/local
FGFS_ROOT = /home/poine/flightgear
FGFS = $(FGFS_PREFIX)/bin/fgfs
#FGFS = /usr/games/fgfs
#FGFS_ENV = LD_LIBRARY_PATH=/usr/local/lib:$(FGFS_ROOT)/lib
FGFS_ENV = LD_LIBRARY_PATH=$(FGFS_ROOT)/lib
FGFS_COMMON_ARGS = --fg-root=$(FGFS_ROOT) --aircraft=A320 --timeofday=noon
#FGFS_COMMON_ARGS = --aircraft=737-300 --timeofday=noon
FGFS_IN_FDM_ARGS = $(FGFS_COMMON_ARGS) --fdm=null --native-fdm=socket,in,30,,5501,udp
FGFS_OUT_FDM_ARGS = $(FGFS_COMMON_ARGS) --native-fdm=socket,out,30,,5500,udp
FGFS_IN_GUI_ARGS = $(FGFS_COMMON_ARGS) --fdm=null --native-gui=socket,in,30,,5501,udp
FGFS_OUT_GUI_ARGS = $(FGFS_COMMON_ARGS) --native-gui=socket,out,30,,5500,udp
FGFS_IN_CTRLS_ARGS = $(FGFS_COMMON_ARGS) --native-ctrls=socket,in,30,,5501,udp
FGFS_OUT_CTRLS_ARGS = $(FGFS_COMMON_ARGS) --native-ctrls=socket,out,30,,5500,udp
FGFS_OUT_MULTIPLAY_ARGS = $(FGFS_COMMON_ARGS) --multiplay=out,10,127.0.0.1,5500 --callsign=F-POINE
FGFS_IN_MULTIPLAY_ARGS = $(FGFS_COMMON_ARGS) --multiplay=in,10,127.0.0.1,5501 --callsign=F-POINE
FGFS_RCAM_ARGS = $(FGFS_COMMON_ARGS) --fdm=null --native-ctrls=socket,out,30,,5500,udp --native-fdm=socket,in,30,,5501,udp
FGFS_GAME_ARGS = $(FGFS_COMMON_ARGS) --control=joystick
FGFS_ARGS = $(FGFS_COMMON_ARGS) $(FGFS_IN_GUI_ARGS)
#FGFS_GAME_ARGS)
run_fg:
$(FGFS_ENV) $(FGFS) $(FGFS_ARGS)
ahrs2fg: ahrs2fg.c network.c flight_gear.c utils.c
$(CC) $(CFLAGS) -g -o $@ $^ $(LDFLAGS)
test_samere: test_samere.c network.c flight_gear.c utils.c
$(CC) $(CFLAGS) -I../airborne -I../airborne/test -I../include -g -o $@ $^ $(LDFLAGS)
ivy_example: ivy_example.c
$(CC) $(IVY_C_LIBRARYS) $(IVY_C_INCLUDES) -g -O2 -Wall `pkg-config glib-2.0 --cflags` -o $@ $^ `pkg-config glib-2.0 --libs` -lglibivy
tmclient: tmclient.c
$(CC) $(IVY_C_LIBRARYS) $(IVY_C_INCLUDES) -g -O1 -Wall `pkg-config glib-2.0 --cflags` -o $@ $^ `pkg-config glib-2.0 --libs` -lglibivy
ffjoystick: ffjoystick.c
$(CC) -g -O2 -Wall `pkg-config glib-2.0 --cflags` -o $@ $^ `pkg-config glib-2.0 --libs` -lglibivy -lm
ctrlstick: ctrlstick.c
$(CC) -g -O2 -Wall `pkg-config glib-2.0 --cflags` -o $@ $^ `pkg-config glib-2.0 --libs` -lglibivy
clean:
rm -f *.opt *.out *~ core *.o *.bak .depend *.cm* play ahrsview imuview ahrs2fg plot plotter gtk_export.ml openlog2tlm disp3d plotprofile test1 test3 test_samere ivy_example tmclient ffjoystick ctrlstick
#
# Dependencies
#
.depend: Makefile
ocamldep -I ../lib/ocaml *.ml* > .depend
ifneq ($(MAKECMDGOALS),clean)
-include .depend
endif
|
josibarns/paparazzi
|
sw/logalizer/Makefile
|
Makefile
|
gpl-2.0
| 7,368
|
#pragma once
#include <features.h>
|
fighterCui/L4ReFiascoOC
|
l4/pkg/uclibc/lib/uclibc/ARCH-all/include/sys/syscall.h
|
C
|
gpl-2.0
| 35
|
/*
* Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* Provides classes and interfaces for parsing and managing
* certificates, certificate revocation lists (CRLs), and
* certification paths. It contains support for X.509 v3
* certificates and X.509 v2 CRLs.
*
* <h2>Package Specification</h2>
*
* <ul>
* <li><a href="{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html">
* <b>Java™
* Cryptography Architecture (JCA) Reference Guide</b></a>
* <li>RFC 3280: Internet X.509 Public Key Infrastructure Certificate and
* Certificate Revocation List (CRL) Profile
* <li><a href="{@docRoot}/../technotes/guides/security/StandardNames.html">
* <b>Java™
* Cryptography Architecture Standard Algorithm Name
* Documentation</b></a></li>
* </ul>
*
* <h2>Related Documentation</h2>
*
* For information about X.509 certificates and CRLs, please see:
* <ul>
* <li><a href="http://www.ietf.org/rfc/rfc3280.txt">
* http://www.ietf.org/rfc/rfc3280.txt</a>
* <li><a href=
* "{@docRoot}/../technotes/guides/security/certpath/CertPathProgGuide.html">
* <b>Java™
* PKI Programmer's Guide</b></a>
* <li><a href="{@docRoot}/../technotes/guides/security/cert3.html">
* <b>X.509 Certificates and Certificate Revocation Lists (CRLs)</b></a>
* </ul>
*
* @since 1.2
*/
package java.security.cert;
|
openjdk/jdk7u
|
jdk/src/share/classes/java/security/cert/package-info.java
|
Java
|
gpl-2.0
| 2,553
|
const Slider = require('./hooters/slider.js');
window.SETTINGS.addDomScanListener(function ($scanContainer) {
window.SETTINGS.initElement($scanContainer, '[data-slider]', function() {
var options = {
stagePadding: 330,
margin: 0,
items: 1,
loop: true,
smartSpeed: 450,
fluidSpeed: 450,
dragEndSpeed: 450,
dots: true,
dotsContainer: '.bullet-nav',
dotsContainerTemplate: '.bullet-nav-template'
};
new Slider(this, options);
});
window.SETTINGS.initElement($scanContainer, '[data-slider-linked]', function() {
var $slider = this.find('.owl-carousel');
var $thumbs = this.find('.thumbs');
var animation = $slider.data('animation-style') ? $slider.data('animation-style') : false;
console.log(animation);
var owl = $slider.owlCarousel({
items: 1,
dots: false,
mouseDrag: false,
touchDrag: false,
pullDrag: false,
animateOut: animation
});
$thumbs.on('click', 'a', function(event) {
var idx = $(this).index();
$thumbs.find('a').removeClass('is-active');
$(this).addClass('is-active');
$slider.trigger('to.owl.carousel', [idx, 200, true]);
});
});
});
|
kiriaze/new-sg
|
src/modules/20_ui/slider/script.js
|
JavaScript
|
gpl-2.0
| 1,149
|
/*
GanttProject is an opensource project management tool.
Copyright (C) 2005-2011 GanttProject Team
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.sourceforge.ganttproject.action.view;
import java.awt.Component;
import java.awt.event.ActionEvent;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.border.EmptyBorder;
import biz.ganttproject.core.option.GPOptionGroup;
import net.sourceforge.ganttproject.ChartComponentBase;
import net.sourceforge.ganttproject.action.CancelAction;
import net.sourceforge.ganttproject.action.GPAction;
import net.sourceforge.ganttproject.action.OkAction;
import net.sourceforge.ganttproject.gui.UIFacade;
import net.sourceforge.ganttproject.gui.options.OptionsPageBuilder;
/**
* Action to show the options dialog for {@code myChart}.
*/
public class ViewChartOptionsDialogAction extends GPAction {
private final UIFacade myUIFacade;
private final ChartComponentBase myChart;
public ViewChartOptionsDialogAction(ChartComponentBase chart, UIFacade uifacade) {
super("chart.options");
myUIFacade = uifacade;
myChart = chart;
}
@Override
public void actionPerformed(ActionEvent e) {
for (GPOptionGroup group : myChart.getOptionGroups()) {
group.lock();
}
final OkAction okAction = new OkAction() {
@Override
public void actionPerformed(ActionEvent e) {
commit();
}
};
final CancelAction cancelAction = new CancelAction() {
@Override
public void actionPerformed(ActionEvent e) {
rollback();
}
};
myUIFacade.createDialog(createDialogComponent(), new Action[] { okAction, cancelAction }, "").show();
}
private void commit() {
for (GPOptionGroup group : myChart.getOptionGroups()) {
group.commit();
}
}
private void rollback() {
for (GPOptionGroup group : myChart.getOptionGroups()) {
group.rollback();
}
}
private Component createDialogComponent() {
OptionsPageBuilder builder = new OptionsPageBuilder();
JComponent comp = builder.buildPage(myChart.getOptionGroups(), "ganttChart");
comp.setBorder(new EmptyBorder(5, 5, 5, 5));
return comp;
}
@Override
protected String getIconFilePrefix() {
return "chartOptions_";
}
}
|
Prasad1337/GANTTing
|
ganttproject/src/net/sourceforge/ganttproject/action/view/ViewChartOptionsDialogAction.java
|
Java
|
gpl-2.0
| 2,915
|
require 'spec_helper'
# Specs in this file have access to a helper object that includes
# the Advanced::Water::QuestionOptionsHelper. For example:
#
# describe Advanced::Water::QuestionOptionsHelper do
# describe "string concat" do
# it "concats two strings with spaces" do
# helper.concat_strings("this","that").should == "this that"
# end
# end
# end
describe Advanced::Water::QuestionOptionsHelper do
pending "add some examples to (or delete) #{__FILE__}"
end
|
ircwash/WASHCost-tool
|
spec/helpers/advanced/water/question_options_helper_spec.rb
|
Ruby
|
gpl-2.0
| 484
|
<?php
/** Shortcode **/
if(!class_exists('em_displayshortcode')) {
class em_displayshortcode extends AQ_Block {
protected $the_options;
//set and create block
function __construct() {
$block_options = array(
'block_slug' => 'displayshortcode',
'pb_block_icon' => 'fa fa-cog',
'pb_block_icon_color' => '#2E99E6',
'name' => __('Shortcode','mthemelocal'),
'size' => 'span6',
'tab' => __('Elements','mthemelocal'),
'desc' => __('Add Shortcode','mthemelocal')
);
/*-----------------------------------------------------------------------------------*/
/* Toggle Config
/*-----------------------------------------------------------------------------------*/
$mtheme_shortcodes['displayshortcode'] = array(
'no_preview' => true,
'shortcode_desc' => __('Add Shortcode', 'mthemelocal'),
'params' => array(
'shortcode' => array(
'std' => __('Content','mthemelocal'),
'type' => 'textarea',
'label' => __('Shortcode', 'mthemelocal'),
'desc' => __('Shortcode to generate', 'mthemelocal'),
),
),
'shortcode' => '[displayshortcode shortcode="{{shortcode}}"]',
'popup_title' => __('Add Shortcode', 'mthemelocal')
);
$this->the_options = $mtheme_shortcodes['displayshortcode'];
//create the block
parent::__construct('em_displayshortcode', $block_options);
// Any script registers need to uncomment following line
//add_action('mtheme_aq-page-builder-admin-enqueue', array($this, 'admin_enqueue_scripts'));
}
function form($instance) {
$instance = wp_parse_args($instance);
echo mtheme_generate_builder_form($this->the_options,$instance);
//extract($instance);
}
function block($instance) {
extract($instance);
$the_shortcode = $instance['mtheme_shortcode'];
echo do_shortcode($the_shortcode);
}
public function admin_enqueue_scripts(){
//Any script registers go here
}
}
}
|
nontadech/wp_malailux
|
wp-content/plugins/imaginem-builder-r2/plugs/mpb-displayshortcode.php
|
PHP
|
gpl-2.0
| 2,015
|
###########################################################################
#
# Copyright (C) 2012 Zenoss Inc.
#
###########################################################################
from Products.Zuul.form import schema
from Products.Zuul.utils import ZuulMessageFactory as _t
from Products.Zuul.infos.component import IComponentInfo
from Products.Zuul.interfaces import IFacade
class IPuppetClientInfo(IComponentInfo):
signed = schema.Bool(title=_t(u'Is the client SSL signed?'), group='Details')
managedDevice = schema.TextLine(title=_t(u'Zenoss Device'), group='Details')
class IPuppetFacade (IFacade):
def exportDevices(deviceClass):
"""
Export out devices in zenbatchload format.
@parameter deviceClass: location to start exporting devices (default /)
@type deviceClass: string
@return: zenbatchload format file
@rtype: string
"""
def importDevices(data):
"""
Import devices from zenbatchload format string.
@parameter data: zenbatchload format file
@type data: string
@return: key/value pairs of import statistics
@rtype: dictionary of category and statistic
"""
|
zenoss/ZenPacks.zenoss.Puppet
|
ZenPacks/zenoss/Puppet/interfaces.py
|
Python
|
gpl-2.0
| 1,215
|
<?php
/**
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
/**
* Banners component helper.
*
* @package Joomla.Administrator
* @subpackage com_banners
* @since 1.6
*/
class BannersHelper
{
/**
* Configure the Linkbar.
*
* @param string The name of the active view.
*
* @return void
* @since 1.6
*/
public static function addSubmenu($vName)
{
JSubMenuHelper::addEntry(
JText::_('COM_BANNERS_SUBMENU_BANNERS'),
'index.php?option=com_banners&view=banners',
$vName == 'banners'
);
JSubMenuHelper::addEntry(
JText::_('COM_BANNERS_SUBMENU_CATEGORIES'),
'index.php?option=com_categories&extension=com_banners',
$vName == 'categories'
);
if ($vName=='categories') {
JToolBarHelper::title(
JText::sprintf('COM_CATEGORIES_CATEGORIES_TITLE', JText::_('com_banners')),
'banners-categories');
}
JSubMenuHelper::addEntry(
JText::_('COM_BANNERS_SUBMENU_CLIENTS'),
'index.php?option=com_banners&view=clients',
$vName == 'clients'
);
JSubMenuHelper::addEntry(
JText::_('COM_BANNERS_SUBMENU_TRACKS'),
'index.php?option=com_banners&view=tracks',
$vName == 'tracks'
);
}
/**
* Gets a list of the actions that can be performed.
*
* @param int The category ID.
*
* @return JObject
* @since 1.6
*/
public static function getActions($categoryId = 0)
{
$user = JFactory::getUser();
$result = new JObject;
if (empty($categoryId)) {
$assetName = 'com_banners';
$level = 'component';
} else {
$assetName = 'com_banners.category.'.(int) $categoryId;
$level = 'category';
}
$actions = JAccess::getActions('com_banners', $level);
foreach ($actions as $action) {
$result->set($action->name, $user->authorise($action->name, $assetName));
}
return $result;
}
/**
* @return boolean
* @since 1.6
*/
public static function updateReset()
{
$user = JFactory::getUser();
$db = JFactory::getDBO();
$nullDate = $db->getNullDate();
$now = JFactory::getDate();
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__banners');
$query->where("'".$now."' >= ".$db->quoteName('reset'));
$query->where($db->quoteName('reset').' != '.$db->quote($nullDate).' AND '.$db->quoteName('reset').'!=NULL');
$query->where('('.$db->quoteName('checked_out').' = 0 OR '.$db->quoteName('checked_out').' = '.(int) $db->Quote($user->id).')');
$db->setQuery((string)$query);
$rows = $db->loadObjectList();
// Check for a database error.
if ($db->getErrorNum()) {
JError::raiseWarning(500, $db->getErrorMsg());
return false;
}
JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . '/tables');
foreach ($rows as $row) {
$purchase_type = $row->purchase_type;
if ($purchase_type < 0 && $row->cid) {
$client = JTable::getInstance('Client', 'BannersTable');
$client->load($row->cid);
$purchase_type = $client->purchase_type;
}
if ($purchase_type < 0) {
$params = JComponentHelper::getParams('com_banners');
$purchase_type = $params->get('purchase_type');
}
switch($purchase_type) {
case 1:
$reset = $nullDate;
break;
case 2:
$date = JFactory::getDate('+1 year '.date('Y-m-d', strtotime('now')));
$reset = $db->Quote($date->toSql());
break;
case 3:
$date = JFactory::getDate('+1 month '.date('Y-m-d', strtotime('now')));
$reset = $db->Quote($date->toSql());
break;
case 4:
$date = JFactory::getDate('+7 day '.date('Y-m-d', strtotime('now')));
$reset = $db->Quote($date->toSql());
break;
case 5:
$date = JFactory::getDate('+1 day '.date('Y-m-d', strtotime('now')));
$reset = $db->Quote($date->toSql());
break;
}
// Update the row ordering field.
$query->clear();
$query->update($db->quoteName('#__banners'));
$query->set($db->quoteName('reset').' = '.$db->quote($reset));
$query->set($db->quoteName('impmade').' = '.$db->quote(0));
$query->set($db->quoteName('clicks').' = '.$db->quote(0));
$query->where($db->quoteName('id').' = '.$db->quote($row->id));
$db->setQuery((string)$query);
$db->query();
// Check for a database error.
if ($db->getErrorNum()) {
JError::raiseWarning(500, $db->getErrorMsg());
return false;
}
}
return true;
}
public static function getClientOptions()
{
// Initialize variables.
$options = array();
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('id As value, name As text');
$query->from('#__banner_clients AS a');
$query->order('a.name');
// Get the options.
$db->setQuery($query);
$options = $db->loadObjectList();
// Check for a database error.
if ($db->getErrorNum()) {
JError::raiseWarning(500, $db->getErrorMsg());
}
// Merge any additional options in the XML definition.
//$options = array_merge(parent::getOptions(), $options);
array_unshift($options, JHtml::_('select.option', '0', JText::_('COM_BANNERS_NO_CLIENT')));
return $options;
}
}
|
brKamil/joomla-zamarte
|
administrator/components/com_banners/helpers/banners.php
|
PHP
|
gpl-2.0
| 5,154
|
<?php
/*------------------------------------------------------------------------
# com_j2store - J2Store
# ------------------------------------------------------------------------
# author Ramesh Elamathi - Weblogicx India http://www.weblogicxindia.com
# copyright Copyright (C) 2014 - 19 Weblogicxindia.com. All Rights Reserved.
# @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# Websites: http://j2store.org
# Technical Support: Forum - http://j2store.org/forum/index.html
-------------------------------------------------------------------------*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
$html = $this->storeProfile->get('store_shipping_layout');
if(empty($html) || JString::strlen($html) < 5) {
//we dont have a profile set in the store profile. So use the default one.
$html = '<div class="row-fluid">
<div class="span6">[first_name] [last_name] [phone_1] [phone_2] [country_id] [zone_id]</div>
<div class="span6">[company] [address_1] [address_2] [city] [zip]</div>
</div>';
}
//first find all the checkout fields
preg_match_all("^\[(.*?)\]^",$html,$checkoutFields, PREG_PATTERN_ORDER);
//print_r($this->address);
$allFields = $this->fields;
?>
<?php foreach ($this->fields as $fieldName => $oneExtraField): ?>
<?php
$onWhat='onchange'; if($oneExtraField->field_type=='radio') $onWhat='onclick';
//echo $this->fieldsClass->display($oneExtraField,@$this->address->$fieldName,$fieldName,false);
if(property_exists($this->address, $fieldName)) {
$html = str_replace('['.$fieldName.']',$this->fieldsClass->getFormatedDisplay($oneExtraField,$this->address->$fieldName, $fieldName,false, $options = '', $test = false, $allFields, $allValues = null).'<br />',$html);
}
?>
<?php endforeach; ?>
<?php
//check for unprocessed fields. If the user forgot to add the fields to the checkout layout in store profile, we probably have some.
$unprocessedFields = array();
foreach($this->fields as $fieldName => $oneExtraField) {
if(!in_array($fieldName, $checkoutFields[1])) {
$unprocessedFields[$fieldName] = $oneExtraField;
}
}
//now we have unprocessed fields. remove any other square brackets found.
preg_match_all("^\[(.*?)\]^",$html,$removeFields, PREG_PATTERN_ORDER);
foreach($removeFields[1] as $fieldName) {
$html = str_replace('['.$fieldName.']', '', $html);
}
?>
<?php echo $html; ?>
<?php if(count($unprocessedFields)): ?>
<div class="row-fluid">
<div class="span12">
<?php $uhtml = '';?>
<?php foreach ($unprocessedFields as $fieldName => $oneExtraField): ?>
<?php
$onWhat='onchange'; if($oneExtraField->field_type=='radio') $onWhat='onclick';
//echo $this->fieldsClass->display($oneExtraField,@$this->address->$fieldName,$fieldName,false);
if(property_exists($this->address, $fieldName)) {
$uhtml .= $this->fieldsClass->getFormatedDisplay($oneExtraField,$this->address->$fieldName, $fieldName,false, $options = '', $test = false, $allFields, $allValues = null);
$uhtml .='<br />';
}
?>
<?php endforeach; ?>
<?php echo $uhtml; ?>
</div>
</div>
<?php endif; ?>
<?php echo J2Store::plugin()->eventWithHtml('CheckoutGuestShipping', array($this)); ?>
<br />
<div class="buttons">
<div class="right"><input type="button" value="<?php echo JText::_('J2STORE_CHECKOUT_CONTINUE'); ?>" id="button-guest-shipping" class="button btn btn-primary" /></div>
</div>
<script type="text/javascript"><!--
(function($) {
$('#shipping-address select[name=\'country_id\']').bind('change', function() {
if (this.value == '') return;
$.ajax({
url: 'index.php?option=com_j2store&view=carts&task=getCountry&country_id=' + this.value,
dataType: 'json',
beforeSend: function() {
$('#shipping-address select[name=\'country_id\']').after('<span class="wait"> <img src="<?php echo JUri::root(true); ?>/media/j2store/images/loader.gif" alt="" /></span>');
},
complete: function() {
$('.wait').remove();
},
success: function(json) {
if (json['postcode_required'] == '1') {
$('#shipping-postcode-required').show();
} else {
$('#shipping-postcode-required').hide();
}
html = '<option value=""><?php echo JText::_('J2STORE_SELECT_OPTION'); ?></option>';
if (json['zone'] != '') {
for (i = 0; i < json['zone'].length; i++) {
html += '<option value="' + json['zone'][i]['j2store_zone_id'] + '"';
if (json['zone'][i]['zone_id'] == '<?php echo $this->address->zone_id; ?>') {
html += ' selected="selected"';
}
html += '>' + json['zone'][i]['zone_name'] + '</option>';
}
} else {
html += '<option value="0" selected="selected"><?php echo JText::_('J2STORE_CHECKOUT_ZONE_NONE'); ?></option>';
}
$('#shipping-address select[name=\'zone_id\']').html(html);
},
error: function(xhr, ajaxOptions, thrownError) {
//alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
})(j2store.jQuery);
(function($) {
if($('#shipping-address select[name=\'country_id\']').length > 0) {
$('#shipping-address select[name=\'country_id\']').trigger('change');
}
})(j2store.jQuery);
//--></script>
|
franksun/wp
|
components/com_j2store/views/checkout/tmpl/default_guest_shipping.php
|
PHP
|
gpl-2.0
| 5,215
|
/**
* @file rtems/score/isr.h
*
* This include file contains all the constants and structures associated
* with the management of processor interrupt levels. This handler
* supports interrupt critical sections, vectoring of user interrupt
* handlers, nesting of interrupts, and manipulating interrupt levels.
*/
/*
* COPYRIGHT (c) 1989-2006.
* On-Line Applications Research Corporation (OAR).
*
* The license and distribution terms for this file may be
* found in the file LICENSE in this distribution or at
* http://www.rtems.com/license/LICENSE.
*
* $Id$
*/
#ifndef _RTEMS_SCORE_ISR_H
#define _RTEMS_SCORE_ISR_H
#include <rtems/score/percpu.h>
/**
* @defgroup ScoreISR ISR Handler
*
* @ingroup Score
*
* This handler encapsulates functionality which provides the foundation
* ISR services used in all of the APIs supported by RTEMS.
*
* The ISR Nest level counter variable is maintained as part of the
* per cpu data structure.
*/
/**@{*/
#ifdef __cplusplus
extern "C" {
#endif
/**
* The following type defines the type used to manage the vectors.
*/
typedef uint32_t ISR_Vector_number;
/**
* Return type for ISR Handler
*/
typedef void ISR_Handler;
/**
* Pointer to an ISR Handler
*/
#if (CPU_ISR_PASSES_FRAME_POINTER == 1)
typedef ISR_Handler ( *ISR_Handler_entry )(
ISR_Vector_number,
CPU_Interrupt_frame *
);
#else
typedef ISR_Handler ( *ISR_Handler_entry )(
ISR_Vector_number
);
#endif
/**
* This constant promotes out the number of vectors truly supported by
* the current CPU being used. This is usually the number of distinct vectors
* the cpu can vector.
*/
#define ISR_NUMBER_OF_VECTORS CPU_INTERRUPT_NUMBER_OF_VECTORS
/**
* This constant promotes out the highest valid interrupt vector number.
*/
#define ISR_INTERRUPT_MAXIMUM_VECTOR_NUMBER CPU_INTERRUPT_MAXIMUM_VECTOR_NUMBER
#if (CPU_SIMPLE_VECTORED_INTERRUPTS == TRUE)
/**
* The following declares the Vector Table. Application
* interrupt service routines are vectored by the ISR Handler via this table.
*/
SCORE_EXTERN ISR_Handler_entry *_ISR_Vector_table;
#endif
/**
* This routine performs the initialization necessary for this handler.
*/
void _ISR_Handler_initialization ( void );
/**
* @brief Disable Interrupts on This Core
*
* This routine disables all interrupts so that a critical section
* of code can be executing without being interrupted.
*
* @return The argument @a _level will contain the previous interrupt
* mask level.
*/
#define _ISR_Disable_on_this_core( _level ) \
do { \
_CPU_ISR_Disable( _level ); \
RTEMS_COMPILER_MEMORY_BARRIER(); \
} while (0)
/**
* @brief Enable Interrupts on This Core
*
* This routine enables interrupts to the previous interrupt mask
* LEVEL. It is used at the end of a critical section of code to
* enable interrupts so they can be processed again.
*
* @param[in] level contains the interrupt level mask level
* previously returned by @ref _ISR_Disable_on_this_core.
*/
#define _ISR_Enable_on_this_core( _level ) \
do { \
RTEMS_COMPILER_MEMORY_BARRIER(); \
_CPU_ISR_Enable( _level ); \
} while (0)
/**
* @brief Temporarily Enable Interrupts on This Core
*
* This routine temporarily enables interrupts to the previous
* interrupt mask level and then disables all interrupts so that
* the caller can continue into the second part of a critical
* section.
*
* This routine is used to temporarily enable interrupts
* during a long critical section. It is used in long sections of
* critical code when a point is reached at which interrupts can
* be temporarily enabled. Deciding where to flash interrupts
* in a long critical section is often difficult and the point
* must be selected with care to ensure that the critical section
* properly protects itself.
*
* @param[in] level contains the interrupt level mask level
* previously returned by @ref _ISR_Disable_on_this_core.
*/
#define _ISR_Flash_on_this_core( _level ) \
do { \
RTEMS_COMPILER_MEMORY_BARRIER(); \
_CPU_ISR_Flash( _level ); \
RTEMS_COMPILER_MEMORY_BARRIER(); \
} while (0)
#if defined(RTEMS_SMP)
/**
* @brief Initialize SMP Interrupt Critical Section Support
*
* This method initializes the variables required by the SMP implementation
* of interrupt critical section management.
*/
void _ISR_SMP_Initialize(void);
/**
* @brief Enter Interrupt Critical Section on SMP System
*
* This method is used to enter an interrupt critical section that
* is honored across all cores in an SMP system.
*
* @return This method returns the previous interrupt mask level.
*/
ISR_Level _ISR_SMP_Disable(void);
/**
* @brief Exit Interrupt Critical Section on SMP System
*
* This method is used to exit an interrupt critical section that
* is honored across all cores in an SMP system.
*
* @param[in] level contains the interrupt level mask level
* previously returned by @ref _ISR_SMP_Disable.
*/
void _ISR_SMP_Enable(ISR_Level level);
/**
* @brief Temporarily Exit Interrupt Critical Section on SMP System
*
* This method is used to temporarily exit an interrupt critical section
* that is honored across all cores in an SMP system.
*
* @param[in] level contains the interrupt level mask level
* previously returned by @ref _ISR_SMP_Disable.
*/
void _ISR_SMP_Flash(ISR_Level level);
/**
* @brief Enter SMP interrupt code
*
* This method is used to enter the SMP interrupt section.
*
* @return This method returns the isr level.
*/
int _ISR_SMP_Enter(void);
/**
* @brief Exit SMP interrupt code
*
* This method is used to exit the SMP interrupt.
*
* @return This method returns 0 on a simple return and returns 1 on a
* dispatching return.
*/
int _ISR_SMP_Exit(void);
#endif
/**
* @brief Enter Interrupt Disable Critical Section
*
* This routine enters an interrupt disable critical section. When
* in an SMP configuration, this involves obtaining a spinlock to ensure
* that only one core is inside an interrupt disable critical section.
* When on a single core system, this only involves disabling local
* CPU interrupts.
*
* @return The argument @a _level will contain the previous interrupt
* mask level.
*/
#if defined(RTEMS_SMP)
#define _ISR_Disable( _level ) \
_level = _ISR_SMP_Disable();
#else
#define _ISR_Disable( _level ) \
_ISR_Disable_on_this_core( _level );
#endif
/**
* @brief Exits Interrupt Disable Critical Section
*
* This routine exits an interrupt disable critical section. When
* in an SMP configuration, this involves releasing a spinlock.
* When on a single core system, this only involves disabling local
* CPU interrupts.
*
* @return The argument @a _level will contain the previous interrupt
* mask level.
*/
#if defined(RTEMS_SMP)
#define _ISR_Enable( _level ) \
_ISR_SMP_Enable( _level );
#else
#define _ISR_Enable( _level ) \
_ISR_Enable_on_this_core( _level );
#endif
/**
* @brief Temporarily Exit Interrupt Disable Critical Section
*
* This routine is used to temporarily enable interrupts
* during a long critical section. It is used in long sections of
* critical code when a point is reached at which interrupts can
* be temporarily enabled. Deciding where to flash interrupts
* in a long critical section is often difficult and the point
* must be selected with care to ensure that the critical section
* properly protects itself.
*
* @return The argument @a _level will contain the previous interrupt
* mask level.
*/
#if defined(RTEMS_SMP)
#define _ISR_Flash( _level ) \
_ISR_SMP_Flash( _level );
#else
#define _ISR_Flash( _level ) \
_ISR_Flash_on_this_core( _level );
#endif
/**
* @brief Install Interrupt Handler Vector
*
* This routine installs new_handler as the interrupt service routine
* for the specified vector. The previous interrupt service routine is
* returned as old_handler.
*
* @param[in] _vector is the vector number
* @param[in] _new_handler is ISR handler to install
* @param[in] _old_handler is a pointer to a variable which will be set
* to the old handler
*
* @return *_old_handler will be set to the old ISR handler
*/
#define _ISR_Install_vector( _vector, _new_handler, _old_handler ) \
_CPU_ISR_install_vector( _vector, _new_handler, _old_handler )
/**
* @brief Return Current Interrupt Level
*
* This routine returns the current interrupt level.
*
* @return This method returns the current level.
*/
#define _ISR_Get_level() \
_CPU_ISR_Get_level()
/**
* @brief Set Current Interrupt Level
*
* This routine sets the current interrupt level to that specified
* by @a _new_level. The new interrupt level is effective when the
* routine exits.
*
* @param[in] _new_level contains the desired interrupt level.
*/
#define _ISR_Set_level( _new_level ) \
do { \
RTEMS_COMPILER_MEMORY_BARRIER(); \
_CPU_ISR_Set_level( _new_level ); \
RTEMS_COMPILER_MEMORY_BARRIER(); \
} while (0)
/**
* @brief ISR Handler or Dispatcher
*
* This routine is the interrupt dispatcher. ALL interrupts
* are vectored to this routine so that minimal context can be saved
* and setup performed before the application's high-level language
* interrupt service routine is invoked. After the application's
* interrupt service routine returns control to this routine, it
* will determine if a thread dispatch is necessary. If so, it will
* ensure that the necessary thread scheduling operations are
* performed when the outermost interrupt service routine exits.
*
* @note Typically implemented in assembly language.
*/
void _ISR_Handler( void );
/**
* @brief ISR Wrapper for Thread Dispatcher
*
* This routine provides a wrapper so that the routine
* @ref _Thread_Dispatch can be invoked when a reschedule is necessary
* at the end of the outermost interrupt service routine. This
* wrapper is necessary to establish the processor context needed
* by _Thread_Dispatch and to save the processor context which is
* corrupted by _Thread_Dispatch. This context typically consists
* of registers which are not preserved across routine invocations.
*
* @note Typically mplemented in assembly language.
*/
void _ISR_Dispatch( void );
/**
* @brief Is an ISR in Progress
*
* This function returns true if the processor is currently servicing
* and interrupt and false otherwise. A return value of true indicates
* that the caller is an interrupt service routine, NOT a thread.
*
* @return This methods returns true when called from an ISR.
*/
#if (CPU_PROVIDES_ISR_IS_IN_PROGRESS == TRUE)
bool _ISR_Is_in_progress( void );
#else
#define _ISR_Is_in_progress() \
(_ISR_Nest_level != 0)
#endif
#include <rtems/score/isr.inl>
#ifdef __cplusplus
}
#endif
/**@}*/
#endif
/* end of include file */
|
daniel-hellstrom/leon-rtems
|
cpukit/score/include/rtems/score/isr.h
|
C
|
gpl-2.0
| 11,093
|
/** ARP (Address Resolution Protocol) functionality.
<keywords ARP (Address Resolution Protocol), Address Resolution Protocol (ARP)>
File: engine_arp.h
@copyright
Copyright (c) 2002 - 2006 SFNT Finland Oy, all rights reserved.
Definitions for ARP (Address Resolution Protocol). This code is
common to interfaces using ethernet (RFC 894) and IEEE 802 (RFC 1042
and RFC 1469) encapsulation for media headers. Services provided by
this file are used by both the ethernet and IEEE 802 (FDDI, Token
Ring) code.
Note: This file should not be included directly. Instead, the
engine_internal.h header file should be included, which will include
this file.
*/
#ifndef ENGINE_ARP_H
#define ENGINE_ARP_H
#ifndef SSH_IPSEC_IP_ONLY_INTERCEPTOR
/* ************ ARP functions for use by media-specific code ***********/
/* Flag masks for ssh_engine_arp_init. */
#define SSH_ENGINE_ARP_RFC1469_MCAST 0x01 /** RFC 1469 mcast (Token Ring). */
/** Size of the ARP cache hash table. This value should be a small
prime of approximately the same order of magnitude as the maximum
expected number of entries in the ARP cache. It does not matter if
the number of ARP cache entries goes above this, but performance
will suffer (slightly) if this value is exceeded by substantially
more than a factor of five. */
#define SSH_ENGINE_ARP_HASH_SIZE 101
/** The number of times to retry sending an ARP request before giving up. */
#define SSH_ENGINE_MAX_ARP_RETRIES 5
/** Time after which we resend the ARP request if we haven't received a
reply, expressed in microseconds. */
#define SSH_ENGINE_ARP_RESEND_TIMEOUT 1000000
/** The time (in seconds) that an incomplete or failed cache entry
will stay in the cache before being reclaimed. */
#define SSH_ENGINE_ARP_INCOMPLETE_LIFETIME 30
/** The time (in seconds) after which a complete ARP cache entry will
be reclaimed from the cache. Note that the lifetime is fixed; the
entry will be reclaimed after this time even if it is
continuously being used. This is to ensure that we will
eventually notice if a router has gone down, even if there is
outgoing traffic to it all the time. */
#define SSH_ENGINE_ARP_COMPLETE_LIFETIME 600
/** ARP cache timeouts are checked every this many seconds. */
#define SSH_ENGINE_ARP_LIFETIME_CHECK_INTERVAL 10
typedef enum
{
SSH_ENGINE_ARP_INCOMPLETE, /** ARP in progress. */
SSH_ENGINE_ARP_FAILED, /** No reply to ARP request. */
SSH_ENGINE_ARP_COMPLETE, /** Valid cache entry. */
SSH_ENGINE_ARP_PERMANENT /** Permanent valid cache entry. */
} SshEngineArpCacheEntryStatus;
/* Flags for ARP cache entry. */
#define SSH_ENGINE_ARP_F_PROXY 0x01 /** Do proxy ARP for the IP address. */
#define SSH_ENGINE_ARP_ON_LRU_LIST 0x02 /** Entry is on LRU list. */
#define SSH_ENGINE_ARP_F_GLOBAL 0x04 /** Global entry. */
/** Data structure for an ARP cache entry. All fields of this data structure
are protected by the Engine lock, unless otherwise mentioned. */
typedef struct SshEngineArpCacheEntryRec
{
/** The IP address of the ARP cache entry. */
SshIpAddrStruct ip_addr;
/** Scope of IP address in ARP lookups. */
SshEngineIfnum ifnum;
/** Status (SshEngineArpCacheEntryStatus) of the ARP cache entry.
If the entry is on the freelist, this is set to the magic value
0x7a. */
SshUInt8 status;
/** A Boolean flag indicating that this packet is on the retry list. */
SshUInt8 on_retry_list;
/** The number of times we have tried to send an ARP request
for this entry. */
SshUInt8 arp_retry_count;
/** Flags for the entry. */
SshUInt8 flags;
/** The ethernet address corresponding to the IP address. This is
only valid if `status' is SSH_ENGINE_ARP_COMPLETE or
SSH_ENGINE_ARP_PERMANENT. */
unsigned char ethernet_addr[6];
/** Expire time for this ARP entry; the entry will be removed if not
refreshed before this. */
SshTime expires;
/** The packet context for the packet that caused the ARP lookup.
Only the first such packet is saved; any remaining packets sent
while the lookup is in progress will be freed. */
SshEnginePacketContext queued_packet;
/** Pointer to the next entry in the slot of the ARP cache hash table.
If the entry is on the freelist, this points to the next entry on the
freelist. */
struct SshEngineArpCacheEntryRec *next;
/** Pointer to the next entry on the list of entries for which ARP
retries are still being sent. */
struct SshEngineArpCacheEntryRec *retry_list_next;
/** Pointers to next and previous entries in the LRU list of ARP
cache entries. */
struct SshEngineArpCacheEntryRec *lru_next;
struct SshEngineArpCacheEntryRec *lru_prev;
} *SshEngineArpCacheEntry, SshEngineArpCacheEntryStruct;
/** Data structure for the ARP cache. Warning: the IPsec Engine makes
an implicit assumption that all timeouts registered by the ARP code
have a context argument pointing to the media context (i.e., this
ARP cache structure for ethernet and ieee802). The assumption is
in ssh_engine_stop. */
typedef struct SshEngineArpCacheRec
{
/** The hash table containing the ARP cache entries. Each slot
contains a list of entries, linked by their `next' field. Access
to this field and data structures pointed to by it must be
protected by the engine->flow_table_lock. */
SshEngineArpCacheEntry hash[SSH_ENGINE_ARP_HASH_SIZE];
/** The total number of entries in the arp cache. This value is used in
protecting against denial-of-service attacks that try to fill the
ARP cache. Access to this field must be protected using the
engine->flow_table_lock. */
SshUInt32 num_entries;
/** Doubly linked list of ARP cache entries. This is used to remove
old entries from the list if the ARP cache becomes too full
(e.g., as a result of a denial-of-service attack). Access to
this list must be protected using the engine->flow_table_lock. */
SshEngineArpCacheEntry lru_head;
SshEngineArpCacheEntry lru_tail;
/** List of entries for which retries are being sent. Access to this
field must be protected using the engine->flow_table_lock. */
SshEngineArpCacheEntry retry_list;
/** Flag indicating that a retry timeout has been scheduled. Access
to this field must be protected using the engine->flow_table_lock. */
Boolean retry_timeout_scheduled;
/** Use token ring (RFC 1469) multicast Ethernet addresses when this
is TRUE. This field is initialized when the ARP cache is
created, and is not changed after that. */
Boolean token_ring_multicast;
/** List of packets waiting for their completion function to be called to
indicate failure. This list is used in ssh_engine_arp_free_entry
(which is called with engine->flow_table_lock held) to move calling
ssh_engine_arp_complete to a location where the lock is no longer
held. */
SshEnginePacketContext packets_waiting_completion;
} SshEngineArpCacheStruct, *SshEngineArpCache;
typedef enum {
/** The address was successfully mapped. */
SSH_ENGINE_ARP_OK,
/** Mapping could not be completed; an ARP lookup for the address is
in progress. The packet was queued and will be sent or freed
later. */
SSH_ENGINE_ARP_IN_PROGRESS,
/** An ARP request for the address has recently timed out. */
SSH_ENGINE_ARP_FAILURE
} SshEngineArpLookupError;
/** Initializes the data structures needed for ARP lookups and the ARP
cache. Possible flag bit masks were defined above. This function
will not be called concurrently for the same Engine. */
void ssh_engine_arp_init(SshEngine engine, SshUInt32 flags);
/** Uninitializes (frees) the data structures allocated for the ARP
cache. This will free any queued packets. This function will not
be called concurrently for the same Engine, and no other threads
will be executing in IPsec Engine code when this is called, except
possibly for timeouts. */
void ssh_engine_arp_uninit(SshEngine engine);
/** Clears the ARP cache. All entries are dropped from the cache, and
all pending ARP requests are gracefully completed (by calling their
callbacks with failure indication). This will momentarily take
engine->flow_table_lock to modify the cache data structures. */
void ssh_engine_arp_clear(SshEngine engine);
/** Processes an incoming ARP packet. This function will update the
ARP table as appropriate, and will cause the SshEngineArpComplete
callback to be called for any pending requests completed by this
packet. The packet in `pp' should not contain media header, but
the media header should be saved in pc->mediahdr.
This function can be called concurrently. This will momentarily lock
engine->flow_table_lock to modify the cache data structures.
@return
Normally, this will not free `pp' and returns TRUE, because the
packet will normally also be passed to the host TCP/IP stack. If
an error causes the packet to be freed, this returns FALSE.
*/
Boolean ssh_engine_arp_input(SshEngine engine, SshInterceptorPacket pp);
#if defined(WITH_IPV6)
/** Processes an incoming IPv6 neighbor advertisement packet. This
function will update the ARP table as appropriate, and will cause
the SshEngineArpComplete callback to be called for any pending
requests completed by this packet. The packet in `pp' should not
contain media header, but the media header should be saved in
pc->mediahdr.
This function can be called concurrently. This will momentarily lock
engine->flow_table_lock to modify the cache data structures.
@return
Normally, this will not free `pp' and returns TRUE,
because the packet will normally also be passed to the host TCP/IP
stack. If an error causes the packet to be freed, this returns
FALSE.
*/
Boolean ssh_engine_arp_neighbor_advertisement(SshEngine engine,
SshInterceptorPacket pp);
/** Processes an IPv6 neighbor solicitation packet. This
function will update the ARP table as appropriate, and reply to
the solicitation if it is an neighbor discovery. The packet
in `pp' should not contain media header, but the media header
should be saved in pd->mediahdr.
This function can be called concurrently. This will momentarily
lock the engine lock to modify the cache data structures.
@return
Normally, this will not free `pp' and returns TRUE, because the
packet will normally also be passed to the host TCP/IP stack. If
an error causes the packet to be freed, this returns FALSE.
*/
Boolean ssh_engine_arp_neighbor_solicitation(SshEngine engine,
SshInterceptorPacket pp);
#endif /** WITH_IPV6 */
/** A function of this type will perform the encapsulation into a media
header and sending the packet out after a successful ARP lookup.
This will eventually free `pc' (and pc->pp). The `src' and `dst'
values will only be valid for the duration of this call, and must
be copied if they are needed later.
This function may be called with engine->flow_table_lock held, and
this must not release it even momentarily. This may not perform
any actions which could require taking the lock again. This also
implies that this function cannot cancel any timeouts. If the ARP
lookup fails, then this will be called with `src' and `dst' NULL.
`pc' and pc->pp will still be valid if that happens. It is
guaranteed that this will be called once for every call to
ssh_engine_arp_lookup. */
typedef void (*SshEngineArpComplete)(SshEnginePacketContext pc,
const unsigned char *src,
const unsigned char *dst,
SshUInt16 ethertype);
/** Looks up the physical Ethernet addresses for the IP packet in `pp'.
The addresses may come from a number of sources: cached addresses from
de-encapsulating the packet, addresses in the ARP cache, or addresses
obtained using an ARP lookup that is obtained by this call.
This looks for the address `next_hop' attached to interface `ifnum'.
All ARP requests (or IPv6 neighbor solicitations) will be sent to the
interface `ifnum'.
This will call the `callback' function when done (see the declaration of
the prototype above for how errors are handled). It is guaranteed that
the function will be called exactly once for each request. The callback
may get called during this function or at a later time.
This function may be called concurrently; this will momentarily take
engine->flow_table_lock to protect data structures. */
void ssh_engine_arp_lookup(SshEnginePacketContext pc,
SshIpAddr next_hop,
SshEngineIfnum ifnum,
SshEngineArpComplete callback);
/** Adds a mapping for the given address and ifnum in the ARP cache as
a permanent entry. This function is called with
engine->flow_table_lock held; this may not release it even
momentarily.
If `permanent' is TRUE, the entry will be permanent
(never expired from the cache). If `proxy_arp' is TRUE, then
engine will do proxy ARP for the IP with the hardware address
`hw_addr'.
@return
The function returns TRUE if the ARP cache entry was
added and FALSE on error. If 'is_global' is TRUE, then
the 'ip_addr':'hw_addr' mapping will be effective for
all interfaces, and not just 'ifnum'. */
Boolean ssh_engine_arp_add(SshEngine engine,
SshIpAddr ip_addr,
SshEngineIfnum ifnum,
const unsigned char *hw_addr,
Boolean permanent,
Boolean proxy_arp,
Boolean is_global);
/** Removes any mapping for the given IP address and ifnum, even if permanent.
This function is called with engine->flow_table_lock held; this may
not release it even momentarily. The 'ip_address'/'ifnum' must match
those used in ssh_engine_arp_add(), even if is_global was TRUE. */
void ssh_engine_arp_delete(SshEngine engine,
SshIpAddr ip_addr, SshEngineIfnum ifnum);
/** A function of this type is called to inform the media-specific code
about network interfaces of that type that are available. For
Ethernet and ieee 802 networks, this registers the interface
addresses in the ARP cache as permanent entries. Entries for the
old interface structure will first be removed from the cache to
handle updates correctly. This function is called with
engine->flow_table_lock held; this must not release it even momentarily. */
void ssh_engine_arp_update_interface(SshEngine engine,
SshEngineIfnum ifnum,
SshInterceptorInterface *oldif,
SshInterceptorInterface *newif);
#ifdef SSH_ENGINE_MEDIA_ETHER_NO_ARP_RESPONSES
/** Updates an existing ARP cache entry the same way as
ssh_engine_arp_input would. */
void ssh_engine_arp_add_kludge(SshEngine engine,
SshIpAddr ip_addr,
SshEngineIfnum ifnum,
const unsigned char *hw_addr);
#endif /* SSH_ENGINE_MEDIA_ETHER_NO_ARP_RESPONSES */
#endif /* SSH_IPSEC_IP_ONLY_INTERCEPTOR */
#endif /* ENGINE_ARP_H */
|
invisiblek/kernel_808l
|
drivers/net/eip93_drivers/quickSec/src/ipsec/quicksec/engine/engine_arp.h
|
C
|
gpl-2.0
| 15,599
|
#ifndef DRBD_H
#define DRBD_H
#include <linux/connector.h>
#include <asm/types.h>
#ifdef __KERNEL__
#include <linux/types.h>
#include <asm/byteorder.h>
#else
#include <sys/types.h>
#include <sys/wait.h>
#include <limits.h>
#if __BYTE_ORDER == __LITTLE_ENDIAN
#define __LITTLE_ENDIAN_BITFIELD
#elif __BYTE_ORDER == __BIG_ENDIAN
#define __BIG_ENDIAN_BITFIELD
#else
# error "sorry, weird endianness on this box"
#endif
#endif
extern const char *drbd_buildtag(void);
#define REL_VERSION "8.3.8"
#define API_VERSION 88
#define PRO_VERSION_MIN 86
#define PRO_VERSION_MAX 94
enum drbd_io_error_p {
EP_PASS_ON, /* FIXME should the better be named "Ignore"? */
EP_CALL_HELPER,
EP_DETACH
};
enum drbd_fencing_p {
FP_DONT_CARE,
FP_RESOURCE,
FP_STONITH
};
enum drbd_disconnect_p {
DP_RECONNECT,
DP_DROP_NET_CONF,
DP_FREEZE_IO
};
enum drbd_after_sb_p {
ASB_DISCONNECT,
ASB_DISCARD_YOUNGER_PRI,
ASB_DISCARD_OLDER_PRI,
ASB_DISCARD_ZERO_CHG,
ASB_DISCARD_LEAST_CHG,
ASB_DISCARD_LOCAL,
ASB_DISCARD_REMOTE,
ASB_CONSENSUS,
ASB_DISCARD_SECONDARY,
ASB_CALL_HELPER,
ASB_VIOLENTLY
};
/* KEEP the order, do not delete or insert. Only append. */
enum drbd_ret_codes {
ERR_CODE_BASE = 100,
NO_ERROR = 101,
ERR_LOCAL_ADDR = 102,
ERR_PEER_ADDR = 103,
ERR_OPEN_DISK = 104,
ERR_OPEN_MD_DISK = 105,
ERR_DISK_NOT_BDEV = 107,
ERR_MD_NOT_BDEV = 108,
ERR_DISK_TO_SMALL = 111,
ERR_MD_DISK_TO_SMALL = 112,
ERR_BDCLAIM_DISK = 114,
ERR_BDCLAIM_MD_DISK = 115,
ERR_MD_IDX_INVALID = 116,
ERR_IO_MD_DISK = 118,
ERR_MD_INVALID = 119,
ERR_AUTH_ALG = 120,
ERR_AUTH_ALG_ND = 121,
ERR_NOMEM = 122,
ERR_DISCARD = 123,
ERR_DISK_CONFIGURED = 124,
ERR_NET_CONFIGURED = 125,
ERR_MANDATORY_TAG = 126,
ERR_MINOR_INVALID = 127,
ERR_INTR = 129, /* EINTR */
ERR_RESIZE_RESYNC = 130,
ERR_NO_PRIMARY = 131,
ERR_SYNC_AFTER = 132,
ERR_SYNC_AFTER_CYCLE = 133,
ERR_PAUSE_IS_SET = 134,
ERR_PAUSE_IS_CLEAR = 135,
ERR_PACKET_NR = 137,
ERR_NO_DISK = 138,
ERR_NOT_PROTO_C = 139,
ERR_NOMEM_BITMAP = 140,
ERR_INTEGRITY_ALG = 141, /* DRBD 8.2 only */
ERR_INTEGRITY_ALG_ND = 142, /* DRBD 8.2 only */
ERR_CPU_MASK_PARSE = 143, /* DRBD 8.2 only */
ERR_CSUMS_ALG = 144, /* DRBD 8.2 only */
ERR_CSUMS_ALG_ND = 145, /* DRBD 8.2 only */
ERR_VERIFY_ALG = 146, /* DRBD 8.2 only */
ERR_VERIFY_ALG_ND = 147, /* DRBD 8.2 only */
ERR_CSUMS_RESYNC_RUNNING= 148, /* DRBD 8.2 only */
ERR_VERIFY_RUNNING = 149, /* DRBD 8.2 only */
ERR_DATA_NOT_CURRENT = 150,
ERR_CONNECTED = 151, /* DRBD 8.3 only */
ERR_PERM = 152,
ERR_NEED_APV_93 = 153,
/* insert new ones above this line */
AFTER_LAST_ERR_CODE
};
#define DRBD_PROT_A 1
#define DRBD_PROT_B 2
#define DRBD_PROT_C 3
enum drbd_role {
R_UNKNOWN = 0,
R_PRIMARY = 1, /* role */
R_SECONDARY = 2, /* role */
R_MASK = 3,
};
enum drbd_conns {
C_STANDALONE,
C_DISCONNECTING, /* Temporal state on the way to StandAlone. */
C_UNCONNECTED, /* >= C_UNCONNECTED -> inc_net() succeeds */
/* These temporal states are all used on the way
* from >= C_CONNECTED to Unconnected.
* The 'disconnect reason' states
* I do not allow to change beween them. */
C_TIMEOUT,
C_BROKEN_PIPE,
C_NETWORK_FAILURE,
C_PROTOCOL_ERROR,
C_TEAR_DOWN,
C_WF_CONNECTION,
C_WF_REPORT_PARAMS, /* we have a socket */
C_CONNECTED, /* we have introduced each other */
C_STARTING_SYNC_S, /* starting full sync by admin request. */
C_STARTING_SYNC_T, /* stariing full sync by admin request. */
C_WF_BITMAP_S,
C_WF_BITMAP_T,
C_WF_SYNC_UUID,
/* All SyncStates are tested with this comparison
* xx >= C_SYNC_SOURCE && xx <= C_PAUSED_SYNC_T */
C_SYNC_SOURCE,
C_SYNC_TARGET,
C_VERIFY_S,
C_VERIFY_T,
C_PAUSED_SYNC_S,
C_PAUSED_SYNC_T,
C_MASK = 31
};
enum drbd_disk_state {
D_DISKLESS,
D_ATTACHING, /* In the process of reading the meta-data */
D_FAILED, /* Becomes D_DISKLESS as soon as we told it the peer */
/* when >= D_FAILED it is legal to access mdev->bc */
D_NEGOTIATING, /* Late attaching state, we need to talk to the peer */
D_INCONSISTENT,
D_OUTDATED,
D_UNKNOWN, /* Only used for the peer, never for myself */
D_CONSISTENT, /* Might be D_OUTDATED, might be D_UP_TO_DATE ... */
D_UP_TO_DATE, /* Only this disk state allows applications' IO ! */
D_MASK = 15
};
union drbd_state {
struct {
#if defined(__LITTLE_ENDIAN_BITFIELD)
unsigned role:2 ; /* 3/4 primary/secondary/unknown */
unsigned peer:2 ; /* 3/4 primary/secondary/unknown */
unsigned conn:5 ; /* 17/32 cstates */
unsigned disk:4 ; /* 8/16 from D_DISKLESS to D_UP_TO_DATE */
unsigned pdsk:4 ; /* 8/16 from D_DISKLESS to D_UP_TO_DATE */
unsigned susp:1 ; /* 2/2 IO suspended no/yes */
unsigned aftr_isp:1 ; /* isp .. imposed sync pause */
unsigned peer_isp:1 ;
unsigned user_isp:1 ;
unsigned _pad:11; /* 0 unused */
#elif defined(__BIG_ENDIAN_BITFIELD)
unsigned _pad:11; /* 0 unused */
unsigned user_isp:1 ;
unsigned peer_isp:1 ;
unsigned aftr_isp:1 ; /* isp .. imposed sync pause */
unsigned susp:1 ; /* 2/2 IO suspended no/yes */
unsigned pdsk:4 ; /* 8/16 from D_DISKLESS to D_UP_TO_DATE */
unsigned disk:4 ; /* 8/16 from D_DISKLESS to D_UP_TO_DATE */
unsigned conn:5 ; /* 17/32 cstates */
unsigned peer:2 ; /* 3/4 primary/secondary/unknown */
unsigned role:2 ; /* 3/4 primary/secondary/unknown */
#else
# error "this endianess is not supported"
#endif
};
unsigned int i;
};
enum drbd_state_ret_codes {
SS_CW_NO_NEED = 4,
SS_CW_SUCCESS = 3,
SS_NOTHING_TO_DO = 2,
SS_SUCCESS = 1,
SS_UNKNOWN_ERROR = 0, /* Used to sleep longer in _drbd_request_state */
SS_TWO_PRIMARIES = -1,
SS_NO_UP_TO_DATE_DISK = -2,
SS_NO_LOCAL_DISK = -4,
SS_NO_REMOTE_DISK = -5,
SS_CONNECTED_OUTDATES = -6,
SS_PRIMARY_NOP = -7,
SS_RESYNC_RUNNING = -8,
SS_ALREADY_STANDALONE = -9,
SS_CW_FAILED_BY_PEER = -10,
SS_IS_DISKLESS = -11,
SS_DEVICE_IN_USE = -12,
SS_NO_NET_CONFIG = -13,
SS_NO_VERIFY_ALG = -14, /* drbd-8.2 only */
SS_NEED_CONNECTION = -15, /* drbd-8.2 only */
SS_LOWER_THAN_OUTDATED = -16,
SS_NOT_SUPPORTED = -17, /* drbd-8.2 only */
SS_IN_TRANSIENT_STATE = -18, /* Retry after the next state change */
SS_CONCURRENT_ST_CHG = -19, /* Concurrent cluster side state change! */
SS_AFTER_LAST_ERROR = -20, /* Keep this at bottom */
};
/* from drbd_strings.c */
extern const char *drbd_conn_str(enum drbd_conns);
extern const char *drbd_role_str(enum drbd_role);
extern const char *drbd_disk_str(enum drbd_disk_state);
extern const char *drbd_set_st_err_str(enum drbd_state_ret_codes);
#define SHARED_SECRET_MAX 64
#define MDF_CONSISTENT (1 << 0)
#define MDF_PRIMARY_IND (1 << 1)
#define MDF_CONNECTED_IND (1 << 2)
#define MDF_FULL_SYNC (1 << 3)
#define MDF_WAS_UP_TO_DATE (1 << 4)
#define MDF_PEER_OUT_DATED (1 << 5)
#define MDF_CRASHED_PRIMARY (1 << 6)
enum drbd_uuid_index {
UI_CURRENT,
UI_BITMAP,
UI_HISTORY_START,
UI_HISTORY_END,
UI_SIZE, /* nl-packet: number of dirty bits */
UI_FLAGS, /* nl-packet: flags */
UI_EXTENDED_SIZE /* Everything. */
};
enum drbd_timeout_flag {
UT_DEFAULT = 0,
UT_DEGRADED = 1,
UT_PEER_OUTDATED = 2,
};
#define UUID_JUST_CREATED ((__u64)4)
#define DRBD_MAGIC 0x83740267
#define BE_DRBD_MAGIC __constant_cpu_to_be32(DRBD_MAGIC)
/* these are of type "int" */
#define DRBD_MD_INDEX_INTERNAL -1
#define DRBD_MD_INDEX_FLEX_EXT -2
#define DRBD_MD_INDEX_FLEX_INT -3
/* Start of the new netlink/connector stuff */
#define DRBD_NL_CREATE_DEVICE 0x01
#define DRBD_NL_SET_DEFAULTS 0x02
/* For searching a vacant cn_idx value */
#define CN_IDX_STEP 6977
struct drbd_nl_cfg_req {
int packet_type;
unsigned int drbd_minor;
int flags;
unsigned short tag_list[];
};
struct drbd_nl_cfg_reply {
int packet_type;
unsigned int minor;
int ret_code; /* enum ret_code or set_st_err_t */
unsigned short tag_list[]; /* only used with get_* calls */
};
#endif
|
luckasfb/OT_903D-kernel-2.6.35.7
|
kernel/include/linux/drbd.h
|
C
|
gpl-2.0
| 7,935
|
/*
* Freeplane - mind map editor
* Copyright (C) 2016 jberry
*
* This file author is jberry
*
* 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/>.
*/
package org.freeplane.features.styles.mindmapmode.styleeditorpanel;
import java.awt.Color;
import java.beans.PropertyChangeEvent;
import org.freeplane.core.resources.components.BooleanProperty;
import org.freeplane.core.resources.components.ColorProperty;
import org.freeplane.core.resources.components.IPropertyControl;
import org.freeplane.core.util.ColorUtils;
import org.freeplane.features.edge.EdgeController;
import org.freeplane.features.edge.EdgeModel;
import org.freeplane.features.edge.mindmapmode.MEdgeController;
import org.freeplane.features.map.NodeModel;
import com.jgoodies.forms.builder.DefaultFormBuilder;
/**
* @author Joe Berry
* Nov 27, 2016
*/
class EdgeColorControlGroup implements ControlGroup {
private static final String EDGE_COLOR = "edgecolor";
private BooleanProperty mSetEdgeColor;
private ColorProperty mEdgeColor;
private EdgeColorChangeListener propertyChangeListener;
private class EdgeColorChangeListener extends ControlGroupChangeListener {
public EdgeColorChangeListener(final BooleanProperty mSet, final IPropertyControl mProperty) {
super(mSet, mProperty);
}
@Override
void applyValue(final boolean enabled, final NodeModel node, final PropertyChangeEvent evt) {
final MEdgeController edgeController = (MEdgeController) MEdgeController.getController();
edgeController.setColor(node, enabled ? mEdgeColor.getColorValue() : null);
}
@Override
void setStyleOnExternalChange(NodeModel node) {
final EdgeModel edgeModel = EdgeModel.getModel(node);
final EdgeController edgeController = EdgeController.getController();
{
final Color edgeColor = edgeModel != null ? edgeModel.getColor() : null;
final Color viewColor = edgeController.getColor(node);
mSetEdgeColor.setValue(edgeColor != null);
mEdgeColor.setColorValue(viewColor);
}
}
}
public void addControlGroup(DefaultFormBuilder formBuilder) {
mSetEdgeColor = new BooleanProperty(ControlGroup.SET_RESOURCE);
mEdgeColor = new ColorProperty(EdgeColorControlGroup.EDGE_COLOR, ColorUtils.colorToString(EdgeController.STANDARD_EDGE_COLOR));
propertyChangeListener = new EdgeColorChangeListener(mSetEdgeColor, mEdgeColor);
mSetEdgeColor.addPropertyChangeListener(propertyChangeListener);
mEdgeColor.addPropertyChangeListener(propertyChangeListener);
mSetEdgeColor.layout(formBuilder);;
mEdgeColor.layout(formBuilder);;
}
public void setStyle(NodeModel node) {
propertyChangeListener.setStyle(node);
}
}
|
fnatter/freeplane-debian-dev
|
freeplane/src/main/java/org/freeplane/features/styles/mindmapmode/styleeditorpanel/EdgeColorControlGroup.java
|
Java
|
gpl-2.0
| 3,237
|
This repo exists to hold the core code for my passion project / MVP attempt at a product I'm calling MatchMakr. The project was begun on January 14th, 2015. While the code itself will remain open-source, all responsibility for the code and any resulting users/impact belong to Rent Masters, LLC, a registered corporation in the state of California.
Questions? please contact Brian at matchmakr.sf@gmail.com
|
bbensch09/matchmakr
|
README.md
|
Markdown
|
gpl-2.0
| 407
|
/* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
#ifdef PAIR_CLASS
PairStyle(lj/cut/coul/dsf,PairLJCutCoulDSF)
#else
#ifndef LMP_PAIR_LJ_CUT_COUL_DSF_H
#define LMP_PAIR_LJ_CUT_COUL_DSF_H
#include "pair.h"
namespace LAMMPS_NS {
class PairLJCutCoulDSF : public Pair {
public:
PairLJCutCoulDSF(class LAMMPS *);
~PairLJCutCoulDSF();
void compute(int, int);
void settings(int, char **);
void coeff(int, char **);
void init_style();
double init_one(int, int);
void write_restart(FILE *);
void read_restart(FILE *);
void write_restart_settings(FILE *);
void read_restart_settings(FILE *);
double single(int, int, int, int, double, double, double, double &);
void *extract(const char *, int &);
protected:
double cut_lj_global;
double **cut_lj,**cut_ljsq;
double **epsilon,**sigma;
double **lj1,**lj2,**lj3,**lj4,**offset;
double cut_coul,cut_coulsq;
double alpha;
double f_shift,e_shift;
void allocate();
};
}
#endif
#endif
/* ERROR/WARNING messages:
E: Illegal ... command
UNDOCUMENTED
E: Incorrect args for pair coefficients
UNDOCUMENTED
E: Pair style lj/cut/coul/dsf requires atom attribute q
UNDOCUMENTED
*/
|
jcarlson23/lammps
|
src/pair_lj_cut_coul_dsf.h
|
C
|
gpl-2.0
| 1,752
|
/*
* MPTCP implementation - MPTCP-control
*
* Initial Design & Implementation:
* Sébastien Barré <sebastien.barre@uclouvain.be>
*
* Current Maintainer & Author:
* Christoph Paasch <christoph.paasch@uclouvain.be>
*
* Additional authors:
* Jaakko Korkeaniemi <jaakko.korkeaniemi@aalto.fi>
* Gregory Detal <gregory.detal@uclouvain.be>
* Fabien Duchêne <fabien.duchene@uclouvain.be>
* Andreas Seelinger <Andreas.Seelinger@rwth-aachen.de>
* Lavkesh Lahngir <lavkesh51@gmail.com>
* Andreas Ripke <ripke@neclab.eu>
* Vlad Dogaru <vlad.dogaru@intel.com>
* Octavian Purdila <octavian.purdila@intel.com>
* John Ronan <jronan@tssg.org>
* Catalin Nicutar <catalin.nicutar@gmail.com>
* Brandon Heller <brandonh@stanford.edu>
*
*
* 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 <net/inet_common.h>
#include <net/inet6_hashtables.h>
#include <net/ipv6.h>
#include <net/ip6_checksum.h>
#include <net/mptcp.h>
#include <net/mptcp_v4.h>
#include <net/mptcp_v6.h>
#include <net/sock.h>
#include <net/tcp.h>
#include <net/tcp_states.h>
#include <net/transp_v6.h>
#include <net/xfrm.h>
#include <linux/cryptohash.h>
#include <linux/kconfig.h>
#include <linux/module.h>
#include <linux/list.h>
#include <linux/jhash.h>
#include <linux/tcp.h>
#include <linux/net.h>
#include <linux/in.h>
#include <linux/random.h>
#include <linux/inetdevice.h>
#include <linux/workqueue.h>
#include <linux/atomic.h>
#ifdef CONFIG_SYSCTL
#include <linux/sysctl.h>
#endif
static struct kmem_cache *mptcp_sock_cache __read_mostly;
static struct kmem_cache *mptcp_cb_cache __read_mostly;
static struct kmem_cache *mptcp_tw_cache __read_mostly;
int sysctl_mptcp_ndiffports __read_mostly = 1;
int sysctl_mptcp_enabled __read_mostly = 1;
int sysctl_mptcp_checksum __read_mostly = 1;
int sysctl_mptcp_debug __read_mostly;
EXPORT_SYMBOL(sysctl_mptcp_debug);
int sysctl_mptcp_syn_retries __read_mostly = MPTCP_SYN_RETRIES;
#ifdef CONFIG_SYSCTL
static struct ctl_table mptcp_table[] = {
{
.procname = "mptcp_ndiffports",
.data = &sysctl_mptcp_ndiffports,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec
},
{
.procname = "mptcp_enabled",
.data = &sysctl_mptcp_enabled,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec
},
{
.procname = "mptcp_checksum",
.data = &sysctl_mptcp_checksum,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec
},
{
.procname = "mptcp_debug",
.data = &sysctl_mptcp_debug,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec
},
{
.procname = "mptcp_syn_retries",
.data = &sysctl_mptcp_syn_retries,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec
},
{ }
};
#endif
static struct sock *mptcp_syn_recv_sock(struct sock *sk, struct sk_buff *skb,
struct request_sock *req,
struct dst_entry *dst)
{
#if IS_ENABLED(CONFIG_IPV6)
if (sk->sk_family == AF_INET6)
return tcp_v6_syn_recv_sock(sk, skb, req, dst);
/* sk->sk_family == AF_INET */
if (req->rsk_ops->family == AF_INET6)
return mptcp_v6v4_syn_recv_sock(sk, skb, req, dst);
#endif
/* sk->sk_family == AF_INET && req->rsk_ops->family == AF_INET */
return tcp_v4_syn_recv_sock(sk, skb, req, dst);
}
struct sock *mptcp_select_ack_sock(const struct sock *meta_sk, int copied)
{
struct tcp_sock *meta_tp = tcp_sk(meta_sk);
struct sock *sk, *subsk = NULL;
u32 max_data_seq = 0;
/* max_data_seq initialized to correct compiler-warning.
* But the initialization is handled by max_data_seq_set
*/
short max_data_seq_set = 0;
u32 min_time = 0xffffffff;
/* How do we select the subflow to send the window-update on?
*
* 1. He has to be in a state where he can send an ack.
* 2. He has to be one of those subflow who recently
* contributed to the received stream
* (this guarantees a working subflow)
* a) its latest data_seq received is after the original
* copied_seq.
* We select the one with the lowest rtt, so that the
* window-update reaches our peer the fastest.
* b) if no subflow has this kind of data_seq (e.g., very
* strange meta-level retransmissions going on), we take
* the subflow who last sent the highest data_seq.
*/
mptcp_for_each_sk(meta_tp->mpcb, sk) {
struct tcp_sock *tp = tcp_sk(sk);
if (!mptcp_sk_can_send_ack(sk))
continue;
/* Select among those who contributed to the
* current receive-queue.
*/
if (copied && after(tp->mptcp->last_data_seq, meta_tp->copied_seq - copied)) {
if (tp->srtt < min_time) {
min_time = tp->srtt;
subsk = sk;
max_data_seq_set = 0;
}
continue;
}
if (!subsk && !max_data_seq_set) {
max_data_seq = tp->mptcp->last_data_seq;
max_data_seq_set = 1;
subsk = sk;
}
/* Otherwise, take the one with the highest data_seq */
if ((!subsk || max_data_seq_set) &&
after(tp->mptcp->last_data_seq, max_data_seq)) {
max_data_seq = tp->mptcp->last_data_seq;
subsk = sk;
}
}
if (!subsk) {
mptcp_debug("%s subsk is null, copied %d, cseq %u\n", __func__,
copied, meta_tp->copied_seq);
mptcp_for_each_sk(meta_tp->mpcb, sk) {
struct tcp_sock *tp = tcp_sk(sk);
mptcp_debug("%s pi %d state %u last_dseq %u\n",
__func__, tp->mptcp->path_index, sk->sk_state,
tp->mptcp->last_data_seq);
}
}
return subsk;
}
static void mptcp_sock_def_error_report(struct sock *sk)
{
struct mptcp_cb *mpcb = tcp_sk(sk)->mpcb;
if (!sock_flag(sk, SOCK_DEAD))
mptcp_sub_close(sk, 0);
if (mpcb->infinite_mapping_rcv || mpcb->infinite_mapping_snd) {
struct sock *meta_sk = mptcp_meta_sk(sk);
meta_sk->sk_err = sk->sk_err;
meta_sk->sk_err_soft = sk->sk_err_soft;
if (!sock_flag(meta_sk, SOCK_DEAD))
meta_sk->sk_error_report(meta_sk);
tcp_done(meta_sk);
}
sk->sk_err = 0;
return;
}
static void mptcp_mpcb_put(struct mptcp_cb *mpcb)
{
if (atomic_dec_and_test(&mpcb->refcnt))
kmem_cache_free(mptcp_cb_cache, mpcb);
}
static void mptcp_sock_destruct(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
inet_sock_destruct(sk);
kmem_cache_free(mptcp_sock_cache, tp->mptcp);
tp->mptcp = NULL;
if (!is_meta_sk(sk) && !tp->was_meta_sk) {
/* Taken when mpcb pointer was set */
sock_put(mptcp_meta_sk(sk));
mptcp_mpcb_put(tp->mpcb);
} else {
struct mptcp_cb *mpcb = tp->mpcb;
struct mptcp_tw *mptw;
/* The mpcb is disappearing - we can make the final
* update to the rcv_nxt of the time-wait-sock and remove
* its reference to the mpcb.
*/
spin_lock_bh(&mpcb->tw_lock);
list_for_each_entry_rcu(mptw, &mpcb->tw_list, list) {
list_del_rcu(&mptw->list);
mptw->in_list = 0;
mptcp_mpcb_put(mpcb);
rcu_assign_pointer(mptw->mpcb, NULL);
}
spin_unlock_bh(&mpcb->tw_lock);
mptcp_mpcb_put(mpcb);
mptcp_debug("%s destroying meta-sk\n", __func__);
}
}
void mptcp_destroy_sock(struct sock *sk)
{
if (is_meta_sk(sk)) {
struct sock *sk_it, *tmpsk;
__skb_queue_purge(&tcp_sk(sk)->mpcb->reinject_queue);
mptcp_purge_ofo_queue(tcp_sk(sk));
/* We have to close all remaining subflows. Normally, they
* should all be about to get closed. But, if the kernel is
* forcing a closure (e.g., tcp_write_err), the subflows might
* not have been closed properly (as we are waiting for the
* DATA_ACK of the DATA_FIN).
*/
mptcp_for_each_sk_safe(tcp_sk(sk)->mpcb, sk_it, tmpsk) {
/* Already did call tcp_close - waiting for graceful
* closure.
*/
if (tcp_sk(sk_it)->closing)
continue;
/* Allow the delayed work first to prevent time-wait state */
if (delayed_work_pending(&tcp_sk(sk_it)->mptcp->work))
continue;
mptcp_sub_close(sk_it, 0);
}
} else {
mptcp_del_sock(sk);
}
}
static void mptcp_set_state(struct sock *sk)
{
struct sock *meta_sk = mptcp_meta_sk(sk);
/* Meta is not yet established - wake up the application */
if ((1 << meta_sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV) &&
sk->sk_state == TCP_ESTABLISHED) {
tcp_set_state(meta_sk, TCP_ESTABLISHED);
if (!sock_flag(meta_sk, SOCK_DEAD)) {
meta_sk->sk_state_change(meta_sk);
sk_wake_async(meta_sk, SOCK_WAKE_IO, POLL_OUT);
}
}
if (sk->sk_state == TCP_ESTABLISHED) {
tcp_sk(sk)->mptcp->establish_increased = 1;
tcp_sk(sk)->mpcb->cnt_established++;
}
}
void mptcp_set_keepalive(struct sock *sk, int val)
{
struct sock *sk_it;
mptcp_for_each_sk(tcp_sk(sk)->mpcb, sk_it) {
tcp_set_keepalive(sk_it, val);
sock_valbool_flag(sk, SOCK_KEEPOPEN, val);
}
}
u32 mptcp_secret[MD5_MESSAGE_BYTES / 4] ____cacheline_aligned;
u32 mptcp_key_seed = 0;
void mptcp_key_sha1(u64 key, u32 *token, u64 *idsn)
{
u32 workspace[SHA_WORKSPACE_WORDS];
u32 mptcp_hashed_key[SHA_DIGEST_WORDS];
u8 input[64];
int i;
memset(workspace, 0, sizeof(workspace));
/* Initialize input with appropriate padding */
memset(&input[9], 0, sizeof(input) - 10); /* -10, because the last byte
* is explicitly set too */
memcpy(input, &key, sizeof(key)); /* Copy key to the msg beginning */
input[8] = 0x80; /* Padding: First bit after message = 1 */
input[63] = 0x40; /* Padding: Length of the message = 64 bits */
sha_init(mptcp_hashed_key);
sha_transform(mptcp_hashed_key, input, workspace);
for (i = 0; i < 5; i++)
mptcp_hashed_key[i] = cpu_to_be32(mptcp_hashed_key[i]);
if (token)
*token = mptcp_hashed_key[0];
if (idsn)
*idsn = *((u64 *)&mptcp_hashed_key[3]);
}
void mptcp_hmac_sha1(u8 *key_1, u8 *key_2, u8 *rand_1, u8 *rand_2,
u32 *hash_out)
{
u32 workspace[SHA_WORKSPACE_WORDS];
u8 input[128]; /* 2 512-bit blocks */
int i;
memset(workspace, 0, sizeof(workspace));
/* Generate key xored with ipad */
memset(input, 0x36, 64);
for (i = 0; i < 8; i++)
input[i] ^= key_1[i];
for (i = 0; i < 8; i++)
input[i + 8] ^= key_2[i];
memcpy(&input[64], rand_1, 4);
memcpy(&input[68], rand_2, 4);
input[72] = 0x80; /* Padding: First bit after message = 1 */
memset(&input[73], 0, 53);
/* Padding: Length of the message = 512 + 64 bits */
input[126] = 0x02;
input[127] = 0x40;
sha_init(hash_out);
sha_transform(hash_out, input, workspace);
memset(workspace, 0, sizeof(workspace));
sha_transform(hash_out, &input[64], workspace);
memset(workspace, 0, sizeof(workspace));
for (i = 0; i < 5; i++)
hash_out[i] = cpu_to_be32(hash_out[i]);
/* Prepare second part of hmac */
memset(input, 0x5C, 64);
for (i = 0; i < 8; i++)
input[i] ^= key_1[i];
for (i = 0; i < 8; i++)
input[i + 8] ^= key_2[i];
memcpy(&input[64], hash_out, 20);
input[84] = 0x80;
memset(&input[85], 0, 41);
/* Padding: Length of the message = 512 + 160 bits */
input[126] = 0x02;
input[127] = 0xA0;
sha_init(hash_out);
sha_transform(hash_out, input, workspace);
memset(workspace, 0, sizeof(workspace));
sha_transform(hash_out, &input[64], workspace);
for (i = 0; i < 5; i++)
hash_out[i] = cpu_to_be32(hash_out[i]);
}
static void mptcp_mpcb_inherit_sockopts(struct sock *meta_sk, struct sock *master_sk)
{
/* Socket-options handled by mptcp_inherit_sk while creating the meta-sk.
* ======
* SO_SNDBUF, SO_SNDBUFFORCE, SO_RCVBUF, SO_RCVBUFFORCE, SO_RCVLOWAT,
* SO_RCVTIMEO, SO_SNDTIMEO, SO_ATTACH_FILTER, SO_DETACH_FILTER,
* TCP_NODELAY, TCP_CORK
*
* Socket-options handled in this function here
* ======
* SO_KEEPALIVE
* TCP_KEEP*
* TCP_DEFER_ACCEPT
*
* Socket-options on the todo-list
* ======
* SO_BINDTODEVICE - should probably prevent creation of new subsocks
* across other devices. - what about the api-draft?
* SO_DEBUG
* SO_REUSEADDR - probably we don't care about this
* SO_DONTROUTE, SO_BROADCAST
* SO_OOBINLINE
* SO_LINGER
* SO_TIMESTAMP* - I don't think this is of concern for a SOCK_STREAM
* SO_PASSSEC - I don't think this is of concern for a SOCK_STREAM
* SO_RXQ_OVFL
* TCP_COOKIE_TRANSACTIONS
* TCP_MAXSEG
* TCP_THIN_* - Handled by mptcp_inherit_sk, but we need to support this
* in mptcp_retransmit_timer. AND we need to check what is
* about the subsockets.
* TCP_LINGER2
* TCP_WINDOW_CLAMP
* TCP_USER_TIMEOUT
* TCP_MD5SIG
*
* Socket-options of no concern for the meta-socket (but for the subsocket)
* ======
* SO_PRIORITY
* SO_MARK
* TCP_CONGESTION
* TCP_SYNCNT
* TCP_QUICKACK
*/
struct tcp_sock *meta_tp = tcp_sk(meta_sk);
/****** KEEPALIVE-handler ******/
/* Keepalive-timer has been started already, but it is handled at the
* subflow level.
*/
if (sock_flag(meta_sk, SOCK_KEEPOPEN)) {
inet_csk_delete_keepalive_timer(meta_sk);
inet_csk_reset_keepalive_timer(master_sk, keepalive_time_when(meta_tp));
}
/****** DEFER_ACCEPT-handler ******/
/* DEFER_ACCEPT is not of concern for new subflows - we always accept
* them
*/
inet_csk(meta_sk)->icsk_accept_queue.rskq_defer_accept = 0;
}
static void mptcp_sub_inherit_sockopts(struct sock *meta_sk, struct sock *sub_sk)
{
struct tcp_sock *meta_tp = tcp_sk(meta_sk);
/* Keepalive is handled at the subflow-level */
if (sock_flag(meta_sk, SOCK_KEEPOPEN)) {
inet_csk_reset_keepalive_timer(sub_sk, keepalive_time_when(meta_tp));
sock_valbool_flag(sub_sk, SOCK_KEEPOPEN, keepalive_time_when(meta_tp));
}
/* IP_TOS also goes to the subflow. */
if (inet_sk(sub_sk)->tos != inet_sk(meta_sk)->tos) {
inet_sk(sub_sk)->tos = inet_sk(meta_sk)->tos;
sub_sk->sk_priority = meta_sk->sk_priority;
sk_dst_reset(sub_sk);
}
/* Inheris SO_REUSEADDR */
sub_sk->sk_reuse = meta_sk->sk_reuse;
}
int mptcp_backlog_rcv(struct sock *meta_sk, struct sk_buff *skb)
{
/* skb-sk may be NULL if we receive a packet immediatly after the
* SYN/ACK + MP_CAPABLE.
*/
struct sock *sk = skb->sk ? skb->sk : meta_sk;
int ret = 0;
if (unlikely(!atomic_inc_not_zero(&sk->sk_refcnt))) {
kfree_skb(skb);
return 0;
}
if (sk->sk_family == AF_INET)
ret = tcp_v4_do_rcv(sk, skb);
#if IS_ENABLED(CONFIG_IPV6)
else
ret = tcp_v6_do_rcv(sk, skb);
#endif
sock_put(sk);
return ret;
}
struct lock_class_key meta_key;
struct lock_class_key meta_slock_key;
/* Code heavily inspired from sk_clone() */
static int mptcp_inherit_sk(const struct sock *sk, struct sock *newsk,
int family, const gfp_t flags)
{
struct sk_filter *filter;
struct proto *prot = newsk->sk_prot;
const struct inet_connection_sock_af_ops *af_ops = inet_csk(newsk)->icsk_af_ops;
#ifdef CONFIG_SECURITY_NETWORK
void *sptr = newsk->sk_security;
#endif
if (sk->sk_family == AF_INET) {
memcpy(newsk, sk, offsetof(struct sock, sk_dontcopy_begin));
memcpy(&newsk->sk_dontcopy_end, &sk->sk_dontcopy_end,
sizeof(struct tcp_sock) - offsetof(struct sock, sk_dontcopy_end));
} else {
memcpy(newsk, sk, offsetof(struct sock, sk_dontcopy_begin));
memcpy(&newsk->sk_dontcopy_end, &sk->sk_dontcopy_end,
sizeof(struct tcp6_sock) - offsetof(struct sock, sk_dontcopy_end));
}
#ifdef CONFIG_SECURITY_NETWORK
newsk->sk_security = sptr;
security_sk_clone(sk, newsk);
#endif
/* Has been changed by sock_copy above - we may need an IPv6-socket */
newsk->sk_family = family;
newsk->sk_prot = prot;
newsk->sk_prot_creator = prot;
inet_csk(newsk)->icsk_af_ops = af_ops;
/* We don't yet have the mptcp-point. Thus we still need inet_sock_destruct */
newsk->sk_destruct = inet_sock_destruct;
/* SANITY */
get_net(sock_net(newsk));
sk_node_init(&newsk->sk_node);
sock_lock_init_class_and_name(newsk, "slock-AF_INET-MPTCP",
&meta_slock_key, "sk_lock-AF_INET-MPTCP",
&meta_key);
/* Unlocks are in:
*
* 1. If we are creating the master-sk
* * on client-side in tcp_rcv_state_process, "case TCP_SYN_SENT"
* * on server-side in tcp_child_process
* 2. If we are creating another subsock
* * Also in tcp_child_process
*/
bh_lock_sock(newsk);
newsk->sk_backlog.head = NULL;
newsk->sk_backlog.tail = NULL;
newsk->sk_backlog.len = 0;
atomic_set(&newsk->sk_rmem_alloc, 0);
atomic_set(&newsk->sk_wmem_alloc, 1);
atomic_set(&newsk->sk_omem_alloc, 0);
skb_queue_head_init(&newsk->sk_receive_queue);
skb_queue_head_init(&newsk->sk_write_queue);
#ifdef CONFIG_NET_DMA
skb_queue_head_init(&newsk->sk_async_wait_queue);
#endif
spin_lock_init(&newsk->sk_dst_lock);
rwlock_init(&newsk->sk_callback_lock);
lockdep_set_class_and_name(&newsk->sk_callback_lock,
af_callback_keys + newsk->sk_family,
af_family_clock_key_strings[newsk->sk_family]);
newsk->sk_dst_cache = NULL;
newsk->sk_rx_dst = NULL;
newsk->sk_wmem_queued = 0;
newsk->sk_forward_alloc = 0;
newsk->sk_send_head = NULL;
newsk->sk_userlocks = sk->sk_userlocks & ~SOCK_BINDPORT_LOCK;
tcp_sk(newsk)->mptcp = NULL;
sock_reset_flag(newsk, SOCK_DONE);
skb_queue_head_init(&newsk->sk_error_queue);
filter = rcu_dereference_protected(newsk->sk_filter, 1);
if (filter != NULL)
sk_filter_charge(newsk, filter);
if (unlikely(xfrm_sk_clone_policy(newsk))) {
/* It is still raw copy of parent, so invalidate
* destructor and make plain sk_free()
*/
newsk->sk_destruct = NULL;
bh_unlock_sock(newsk);
sk_free(newsk);
newsk = NULL;
return -ENOMEM;
}
newsk->sk_err = 0;
newsk->sk_priority = 0;
/* Before updating sk_refcnt, we must commit prior changes to memory
* (Documentation/RCU/rculist_nulls.txt for details)
*/
smp_wmb();
atomic_set(&newsk->sk_refcnt, 2);
/* Increment the counter in the same struct proto as the master
* sock (sk_refcnt_debug_inc uses newsk->sk_prot->socks, that
* is the same as sk->sk_prot->socks, as this field was copied
* with memcpy).
*
* This _changes_ the previous behaviour, where
* tcp_create_openreq_child always was incrementing the
* equivalent to tcp_prot->socks (inet_sock_nr), so this have
* to be taken into account in all callers. -acme
*/
sk_refcnt_debug_inc(newsk);
sk_set_socket(newsk, NULL);
newsk->sk_wq = NULL;
if (newsk->sk_prot->sockets_allocated)
percpu_counter_inc(newsk->sk_prot->sockets_allocated);
if (sock_flag(newsk, SOCK_TIMESTAMP) ||
sock_flag(newsk, SOCK_TIMESTAMPING_RX_SOFTWARE))
net_enable_timestamp();
return 0;
}
int mptcp_alloc_mpcb(struct sock *meta_sk, __u64 remote_key, u32 window)
{
struct mptcp_cb *mpcb;
struct sock *master_sk;
struct inet_connection_sock *master_icsk, *meta_icsk = inet_csk(meta_sk);
struct tcp_sock *master_tp, *meta_tp = tcp_sk(meta_sk);
struct sk_buff *skb, *tmp;
u64 idsn;
master_sk = sk_prot_alloc(meta_sk->sk_prot, GFP_ATOMIC | __GFP_ZERO,
meta_sk->sk_family);
if (!master_sk)
return -ENOBUFS;
master_tp = tcp_sk(master_sk);
master_icsk = inet_csk(master_sk);
/* Need to set this here - it is needed by mptcp_inherit_sk */
master_sk->sk_prot = meta_sk->sk_prot;
master_sk->sk_prot_creator = meta_sk->sk_prot;
master_icsk->icsk_af_ops = meta_icsk->icsk_af_ops;
mpcb = kmem_cache_zalloc(mptcp_cb_cache, GFP_ATOMIC);
if (!mpcb) {
sk_free(master_sk);
return -ENOBUFS;
}
/* master_sk inherits from meta_sk */
if (mptcp_inherit_sk(meta_sk, master_sk, meta_sk->sk_family, GFP_ATOMIC)) {
kmem_cache_free(mptcp_cb_cache, mpcb);
return -ENOBUFS;
}
#if IS_ENABLED(CONFIG_IPV6)
if (meta_icsk->icsk_af_ops == &ipv6_mapped) {
struct ipv6_pinfo *newnp, *np = inet6_sk(meta_sk);
inet_sk(master_sk)->pinet6 = &((struct tcp6_sock *)master_sk)->inet6;
newnp = inet6_sk(master_sk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
newnp->ipv6_mc_list = NULL;
newnp->ipv6_ac_list = NULL;
newnp->ipv6_fl_list = NULL;
newnp->opt = NULL;
newnp->pktoptions = NULL;
(void)xchg(&newnp->rxpmtu, NULL);
} else if (meta_sk->sk_family == AF_INET6) {
struct ipv6_pinfo *newnp;
/* Meta is IPv4. Initialize pinet6 for the master-sk. */
inet_sk(master_sk)->pinet6 = &((struct tcp6_sock *)master_sk)->inet6;
newnp = inet6_sk(master_sk);
newnp->hop_limit = -1;
newnp->mcast_hops = IPV6_DEFAULT_MCASTHOPS;
newnp->mc_loop = 1;
newnp->pmtudisc = IPV6_PMTUDISC_WANT;
newnp->ipv6only = sock_net(master_sk)->ipv6.sysctl.bindv6only;
}
#endif
meta_tp->mptcp = kmem_cache_zalloc(mptcp_sock_cache, GFP_ATOMIC);
if (!meta_tp->mptcp) {
kmem_cache_free(mptcp_cb_cache, mpcb);
sk_free(master_sk);
return -ENOBUFS;
}
/* Store the keys and generate the peer's token */
mpcb->mptcp_loc_key = meta_tp->mptcp_loc_key;
mpcb->mptcp_loc_token = meta_tp->mptcp_loc_token;
/* Generate Initial data-sequence-numbers */
mptcp_key_sha1(mpcb->mptcp_loc_key, NULL, &idsn);
idsn = ntohll(idsn) + 1;
mpcb->snd_high_order[0] = idsn >> 32;
mpcb->snd_high_order[1] = mpcb->snd_high_order[0] - 1;
meta_tp->write_seq = (u32)idsn;
meta_tp->snd_sml = meta_tp->write_seq;
meta_tp->snd_una = meta_tp->write_seq;
meta_tp->snd_nxt = meta_tp->write_seq;
meta_tp->pushed_seq = meta_tp->write_seq;
meta_tp->snd_up = meta_tp->write_seq;
mpcb->mptcp_rem_key = remote_key;
mptcp_key_sha1(mpcb->mptcp_rem_key, &mpcb->mptcp_rem_token, &idsn);
idsn = ntohll(idsn) + 1;
mpcb->rcv_high_order[0] = idsn >> 32;
mpcb->rcv_high_order[1] = mpcb->rcv_high_order[0] + 1;
meta_tp->copied_seq = (u32) idsn;
meta_tp->rcv_nxt = (u32) idsn;
meta_tp->rcv_wup = (u32) idsn;
meta_tp->snd_wl1 = meta_tp->rcv_nxt - 1;
meta_tp->snd_wnd = window;
meta_tp->packets_out = 0;
meta_tp->mptcp->snt_isn = meta_tp->write_seq; /* Initial data-sequence-number */
meta_icsk->icsk_probes_out = 0;
/* Set mptcp-pointers */
master_tp->mpcb = mpcb;
master_tp->meta_sk = meta_sk;
meta_tp->mpcb = mpcb;
meta_tp->meta_sk = meta_sk;
mpcb->meta_sk = meta_sk;
mpcb->master_sk = master_sk;
meta_tp->mpc = 1;
meta_tp->mptcp->attached = 0;
meta_tp->was_meta_sk = 0;
/* Initialize the queues */
skb_queue_head_init(&mpcb->reinject_queue);
skb_queue_head_init(&master_tp->out_of_order_queue);
tcp_prequeue_init(master_tp);
master_tp->tsq_flags = 0;
/* Copy the write-queue from the meta down to the master.
* This is necessary to get the SYN to the master-write-queue.
* No other data can be queued, before tcp_sendmsg waits for the
* connection to finish.
*/
skb_queue_walk_safe(&meta_sk->sk_write_queue, skb, tmp) {
skb_unlink(skb, &meta_sk->sk_write_queue);
skb_queue_tail(&master_sk->sk_write_queue, skb);
master_sk->sk_wmem_queued += skb->truesize;
sk_mem_charge(master_sk, skb->truesize);
}
meta_sk->sk_wmem_queued = 0;
meta_sk->sk_forward_alloc = 0;
mutex_init(&mpcb->mutex);
/* Initialize workqueue-struct */
INIT_WORK(&mpcb->subflow_work, mptcp_create_subflow_worker);
INIT_DELAYED_WORK(&mpcb->subflow_retry_work, mptcp_retry_subflow_worker);
INIT_WORK(&mpcb->address_work, mptcp_address_worker);
/* Init the accept_queue structure, we support a queue of 32 pending
* connections, it does not need to be huge, since we only store here
* pending subflow creations.
*/
if (reqsk_queue_alloc(&meta_icsk->icsk_accept_queue, 32, GFP_ATOMIC)) {
inet_put_port(master_sk);
kmem_cache_free(mptcp_sock_cache, meta_tp->mptcp);
kmem_cache_free(mptcp_cb_cache, mpcb);
sk_free(master_sk);
meta_tp->mpc = 0;
return -ENOMEM;
}
/* Redefine function-pointers as the meta-sk is now fully ready */
meta_sk->sk_backlog_rcv = mptcp_backlog_rcv;
meta_sk->sk_destruct = mptcp_sock_destruct;
mpcb->syn_recv_sock = mptcp_syn_recv_sock;
/* Meta-level retransmit timer */
meta_icsk->icsk_rto *= 2; /* Double of initial - rto */
tcp_init_xmit_timers(master_sk);
/* Has been set for sending out the SYN */
inet_csk_clear_xmit_timer(meta_sk, ICSK_TIME_RETRANS);
if (!meta_tp->inside_tk_table) {
/* Adding the meta_tp in the token hashtable - coming from server-side */
rcu_read_lock();
spin_lock(&mptcp_tk_hashlock);
__mptcp_hash_insert(meta_tp, mpcb->mptcp_loc_token);
spin_unlock(&mptcp_tk_hashlock);
rcu_read_unlock();
}
master_tp->inside_tk_table = 0;
/* Init time-wait stuff */
INIT_LIST_HEAD(&mpcb->tw_list);
spin_lock_init(&mpcb->tw_lock);
mptcp_mpcb_inherit_sockopts(meta_sk, master_sk);
mpcb->orig_sk_rcvbuf = meta_sk->sk_rcvbuf;
mpcb->orig_sk_sndbuf = meta_sk->sk_sndbuf;
mpcb->orig_window_clamp = meta_tp->window_clamp;
/* The meta is directly linked - set refcnt to 1 */
atomic_set(&mpcb->refcnt, 1);
mptcp_debug("%s: created mpcb with token %#x\n",
__func__, mpcb->mptcp_loc_token);
return 0;
}
struct sock *mptcp_sk_clone(const struct sock *sk, int family,
const gfp_t priority)
{
struct sock *newsk = NULL;
if (family == AF_INET && sk->sk_family == AF_INET) {
newsk = sk_prot_alloc(&tcp_prot, priority, family);
if (!newsk)
return NULL;
/* Set these pointers - they are needed by mptcp_inherit_sk */
newsk->sk_prot = &tcp_prot;
newsk->sk_prot_creator = &tcp_prot;
inet_csk(newsk)->icsk_af_ops = &ipv4_specific;
newsk->sk_family = AF_INET;
}
#if IS_ENABLED(CONFIG_IPV6)
else {
newsk = sk_prot_alloc(&tcpv6_prot, priority, family);
if (!newsk)
return NULL;
newsk->sk_prot = &tcpv6_prot;
newsk->sk_prot_creator = &tcpv6_prot;
if (family == AF_INET)
inet_csk(newsk)->icsk_af_ops = &ipv6_mapped;
else
inet_csk(newsk)->icsk_af_ops = &ipv6_specific;
newsk->sk_family = AF_INET6;
}
#endif
if (mptcp_inherit_sk(sk, newsk, family, priority))
return NULL;
return newsk;
}
void mptcp_fallback_meta_sk(struct sock *meta_sk)
{
kfree(inet_csk(meta_sk)->icsk_accept_queue.listen_opt);
kmem_cache_free(mptcp_sock_cache, tcp_sk(meta_sk)->mptcp);
kmem_cache_free(mptcp_cb_cache, tcp_sk(meta_sk)->mpcb);
}
int mptcp_add_sock(struct sock *meta_sk, struct sock *sk, u8 rem_id,
gfp_t flags)
{
struct mptcp_cb *mpcb = tcp_sk(meta_sk)->mpcb;
struct tcp_sock *tp = tcp_sk(sk);
tp->mptcp = kmem_cache_zalloc(mptcp_sock_cache, flags);
if (!tp->mptcp)
return -ENOMEM;
tp->mptcp->path_index = mptcp_set_new_pathindex(mpcb);
/* No more space for more subflows? */
if (!tp->mptcp->path_index) {
kmem_cache_free(mptcp_sock_cache, tp->mptcp);
return -EPERM;
}
tp->mptcp->tp = tp;
tp->mpcb = mpcb;
tp->meta_sk = meta_sk;
tp->mpc = 1;
tp->mptcp->rem_id = rem_id;
tp->mptcp->last_rbuf_opti = tcp_time_stamp;
/* The corresponding sock_put is in mptcp_sock_destruct(). It cannot be
* included in mptcp_del_sock(), because the mpcb must remain alive
* until the last subsocket is completely destroyed.
*/
sock_hold(meta_sk);
atomic_inc(&mpcb->refcnt);
tp->mptcp->next = mpcb->connection_list;
mpcb->connection_list = tp;
tp->mptcp->attached = 1;
mpcb->cnt_subflows++;
atomic_add(atomic_read(&((struct sock *)tp)->sk_rmem_alloc),
&meta_sk->sk_rmem_alloc);
mptcp_sub_inherit_sockopts(meta_sk, sk);
INIT_DELAYED_WORK(&tp->mptcp->work, mptcp_sub_close_wq);
/* As we successfully allocated the mptcp_tcp_sock, we have to
* change the function-pointers here (for sk_destruct to work correctly)
*/
sk->sk_error_report = mptcp_sock_def_error_report;
sk->sk_data_ready = mptcp_data_ready;
sk->sk_write_space = mptcp_write_space;
sk->sk_state_change = mptcp_set_state;
sk->sk_destruct = mptcp_sock_destruct;
if (sk->sk_family == AF_INET)
mptcp_debug("%s: token %#x pi %d, src_addr:%pI4:%d dst_addr:%pI4:%d, cnt_subflows now %d\n",
__func__ , mpcb->mptcp_loc_token,
tp->mptcp->path_index,
&((struct inet_sock *)tp)->inet_saddr,
ntohs(((struct inet_sock *)tp)->inet_sport),
&((struct inet_sock *)tp)->inet_daddr,
ntohs(((struct inet_sock *)tp)->inet_dport),
mpcb->cnt_subflows);
else
mptcp_debug("%s: token %#x pi %d, src_addr:%pI6:%d dst_addr:%pI6:%d, cnt_subflows now %d\n",
__func__ , mpcb->mptcp_loc_token,
tp->mptcp->path_index, &inet6_sk(sk)->saddr,
ntohs(((struct inet_sock *)tp)->inet_sport),
&inet6_sk(sk)->daddr,
ntohs(((struct inet_sock *)tp)->inet_dport),
mpcb->cnt_subflows);
return 0;
}
void mptcp_del_sock(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk), *tp_prev;
struct mptcp_cb *mpcb;
if (!tp->mptcp || !tp->mptcp->attached)
return;
mpcb = tp->mpcb;
tp_prev = mpcb->connection_list;
mptcp_debug("%s: Removing subsock tok %#x pi:%d state %d is_meta? %d\n",
__func__, mpcb->mptcp_loc_token, tp->mptcp->path_index,
sk->sk_state, is_meta_sk(sk));
if (tp_prev == tp) {
mpcb->connection_list = tp->mptcp->next;
} else {
for (; tp_prev && tp_prev->mptcp->next; tp_prev = tp_prev->mptcp->next) {
if (tp_prev->mptcp->next == tp) {
tp_prev->mptcp->next = tp->mptcp->next;
break;
}
}
}
mpcb->cnt_subflows--;
if (tp->mptcp->establish_increased)
mpcb->cnt_established--;
tp->mptcp->next = NULL;
tp->mptcp->attached = 0;
mpcb->path_index_bits &= ~(1 << tp->mptcp->path_index);
if (!skb_queue_empty(&sk->sk_write_queue))
mptcp_reinject_data(sk, 0);
if (is_master_tp(tp))
mpcb->master_sk = NULL;
else if (tp->mptcp->pre_established)
sk_stop_timer(sk, &tp->mptcp->mptcp_ack_timer);
sk->sk_prot->release_cb(sk);
rcu_assign_pointer(inet_sk(sk)->inet_opt, NULL);
}
/* Updates the metasocket ULID/port data, based on the given sock.
* The argument sock must be the sock accessible to the application.
* In this function, we update the meta socket info, based on the changes
* in the application socket (bind, address allocation, ...)
*/
void mptcp_update_metasocket(struct sock *sk, struct sock *meta_sk)
{
struct mptcp_cb *mpcb = tcp_sk(meta_sk)->mpcb;
switch (sk->sk_family) {
#if IS_ENABLED(CONFIG_IPV6)
case AF_INET6:
/* If the socket is v4 mapped, we continue with v4 operations */
if (!mptcp_v6_is_v4_mapped(sk)) {
mpcb->locaddr6[0].addr = inet6_sk(sk)->saddr;
mpcb->locaddr6[0].id = 0;
mpcb->locaddr6[0].port = 0;
mpcb->locaddr6[0].low_prio = 0;
mpcb->loc6_bits |= 1;
mpcb->next_v6_index = 1;
mptcp_v6_add_raddress(mpcb,
&inet6_sk(sk)->daddr, 0, 0);
mptcp_v6_set_init_addr_bit(mpcb, &inet6_sk(sk)->daddr);
break;
}
#endif
case AF_INET:
mpcb->locaddr4[0].addr.s_addr = inet_sk(sk)->inet_saddr;
mpcb->locaddr4[0].id = 0;
mpcb->locaddr4[0].port = 0;
mpcb->locaddr4[0].low_prio = 0;
mpcb->loc4_bits |= 1;
mpcb->next_v4_index = 1;
mptcp_v4_add_raddress(mpcb,
(struct in_addr *)&inet_sk(sk)->inet_daddr,
0, 0);
mptcp_v4_set_init_addr_bit(mpcb, inet_sk(sk)->inet_daddr);
break;
}
mptcp_set_addresses(meta_sk);
switch (sk->sk_family) {
case AF_INET:
tcp_sk(sk)->mptcp->low_prio = mpcb->locaddr4[0].low_prio;
break;
#if IS_ENABLED(CONFIG_IPV6)
case AF_INET6:
tcp_sk(sk)->mptcp->low_prio = mpcb->locaddr6[0].low_prio;
break;
#endif
}
tcp_sk(sk)->mptcp->send_mp_prio = tcp_sk(sk)->mptcp->low_prio;
}
/* Clean up the receive buffer for full frames taken by the user,
* then send an ACK if necessary. COPIED is the number of bytes
* tcp_recvmsg has given to the user so far, it speeds up the
* calculation of whether or not we must ACK for the sake of
* a window update.
*/
void mptcp_cleanup_rbuf(struct sock *meta_sk, int copied)
{
struct tcp_sock *meta_tp = tcp_sk(meta_sk);
struct sock *sk;
__u32 rcv_window_now = 0;
if (copied > 0 && !(meta_sk->sk_shutdown & RCV_SHUTDOWN)) {
rcv_window_now = tcp_receive_window(meta_tp);
if (2 * rcv_window_now > meta_tp->window_clamp)
rcv_window_now = 0;
}
mptcp_for_each_sk(meta_tp->mpcb, sk) {
struct tcp_sock *tp = tcp_sk(sk);
const struct inet_connection_sock *icsk = inet_csk(sk);
if (!mptcp_sk_can_send_ack(sk))
continue;
if (!inet_csk_ack_scheduled(sk))
goto second_part;
/* Delayed ACKs frequently hit locked sockets during bulk
* receive.
*/
if (icsk->icsk_ack.blocked ||
/* Once-per-two-segments ACK was not sent by tcp_input.c */
tp->rcv_nxt - tp->rcv_wup > icsk->icsk_ack.rcv_mss ||
/* If this read emptied read buffer, we send ACK, if
* connection is not bidirectional, user drained
* receive buffer and there was a small segment
* in queue.
*/
(copied > 0 &&
((icsk->icsk_ack.pending & ICSK_ACK_PUSHED2) ||
((icsk->icsk_ack.pending & ICSK_ACK_PUSHED) &&
!icsk->icsk_ack.pingpong)) &&
!atomic_read(&meta_sk->sk_rmem_alloc))) {
tcp_send_ack(sk);
continue;
}
second_part:
/* This here is the second part of tcp_cleanup_rbuf */
if (rcv_window_now) {
__u32 new_window = __tcp_select_window(sk);
/* Send ACK now, if this read freed lots of space
* in our buffer. Certainly, new_window is new window.
* We can advertise it now, if it is not less than
* current one.
* "Lots" means "at least twice" here.
*/
if (new_window && new_window >= 2 * rcv_window_now)
tcp_send_ack(sk);
}
}
}
static int mptcp_sub_send_fin(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *skb = tcp_write_queue_tail(sk);
int mss_now;
/* Optimization, tack on the FIN if we have a queue of
* unsent frames. But be careful about outgoing SACKS
* and IP options.
*/
mss_now = tcp_current_mss(sk);
if (tcp_send_head(sk) != NULL) {
TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_FIN;
TCP_SKB_CB(skb)->end_seq++;
tp->write_seq++;
} else {
skb = alloc_skb_fclone(MAX_TCP_HEADER, GFP_ATOMIC);
if (!skb)
return 1;
/* Reserve space for headers and prepare control bits. */
skb_reserve(skb, MAX_TCP_HEADER);
/* FIN eats a sequence byte, write_seq advanced by tcp_queue_skb(). */
tcp_init_nondata_skb(skb, tp->write_seq,
TCPHDR_ACK | TCPHDR_FIN);
tcp_queue_skb(sk, skb);
}
__tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_OFF);
return 0;
}
void mptcp_sub_close_wq(struct work_struct *work)
{
struct mptcp_tcp_sock *mptcp = container_of(work, struct mptcp_tcp_sock, work.work);
struct tcp_sock *tp = mptcp->tp;
struct sock *sk = (struct sock *)tp;
struct sock *meta_sk = mptcp_meta_sk(sk);
mutex_lock(&tp->mpcb->mutex);
lock_sock_nested(meta_sk, SINGLE_DEPTH_NESTING);
if (sock_flag(sk, SOCK_DEAD))
goto exit;
/* We come from tcp_disconnect. We are sure that meta_sk is set */
if (!tp->mpc) {
tp->closing = 1;
sock_rps_reset_flow(sk);
tcp_close(sk, 0);
goto exit;
}
if (meta_sk->sk_shutdown == SHUTDOWN_MASK || sk->sk_state == TCP_CLOSE) {
tp->closing = 1;
sock_rps_reset_flow(sk);
tcp_close(sk, 0);
} else if (tcp_close_state(sk)) {
sk->sk_shutdown |= SEND_SHUTDOWN;
tcp_send_fin(sk);
}
exit:
release_sock(meta_sk);
mutex_unlock(&tp->mpcb->mutex);
sock_put(sk);
}
void mptcp_sub_close(struct sock *sk, unsigned long delay)
{
struct tcp_sock *tp = tcp_sk(sk);
struct delayed_work *work = &tcp_sk(sk)->mptcp->work;
/* We are already closing - e.g., call from sock_def_error_report upon
* tcp_disconnect in tcp_close.
*/
if (tp->closing)
return;
/* Work already scheduled ? */
if (work_pending(&work->work)) {
/* Work present - who will be first ? */
if (jiffies + delay > work->timer.expires)
return;
/* Try canceling - if it fails, work will be executed soon */
if (!cancel_delayed_work(work))
return;
sock_put(sk);
}
if (!delay) {
unsigned char old_state = sk->sk_state;
/* If we are in user-context we can directly do the closing
* procedure. No need to schedule a work-queue.
*/
if (!in_softirq()) {
if (sock_flag(sk, SOCK_DEAD))
return;
if (!tp->mpc) {
tp->closing = 1;
sock_rps_reset_flow(sk);
tcp_close(sk, 0);
return;
}
if (mptcp_meta_sk(sk)->sk_shutdown == SHUTDOWN_MASK ||
sk->sk_state == TCP_CLOSE) {
tp->closing = 1;
sock_rps_reset_flow(sk);
tcp_close(sk, 0);
} else if (tcp_close_state(sk)) {
sk->sk_shutdown |= SEND_SHUTDOWN;
tcp_send_fin(sk);
}
return;
}
/* We directly send the FIN. Because it may take so a long time,
* untile the work-queue will get scheduled...
*
* If mptcp_sub_send_fin returns 1, it failed and thus we reset
* the old state so that tcp_close will finally send the fin
* in user-context.
*/
if (!sk->sk_err && old_state != TCP_CLOSE &&
tcp_close_state(sk) && mptcp_sub_send_fin(sk)) {
if (old_state == TCP_ESTABLISHED)
TCP_INC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
sk->sk_state = old_state;
}
}
sock_hold(sk);
queue_delayed_work(mptcp_wq, work, delay);
}
/* Update the mpcb send window, based on the contributions
* of each subflow
*/
void mptcp_update_sndbuf(struct mptcp_cb *mpcb)
{
struct sock *meta_sk = mpcb->meta_sk, *sk;
int new_sndbuf = 0;
mptcp_for_each_sk(mpcb, sk) {
if (!mptcp_sk_can_send(sk))
continue;
new_sndbuf += sk->sk_sndbuf;
if (new_sndbuf > sysctl_tcp_wmem[2] || new_sndbuf < 0) {
new_sndbuf = sysctl_tcp_wmem[2];
break;
}
}
meta_sk->sk_sndbuf = max(min(new_sndbuf, sysctl_tcp_wmem[2]), meta_sk->sk_sndbuf);
}
void mptcp_close(struct sock *meta_sk, long timeout)
{
struct tcp_sock *meta_tp = tcp_sk(meta_sk);
struct sock *sk_it, *tmpsk;
struct mptcp_cb *mpcb = meta_tp->mpcb;
struct sk_buff *skb;
int data_was_unread = 0;
int state;
mptcp_debug("%s: Close of meta_sk with tok %#x\n",
__func__, mpcb->mptcp_loc_token);
mutex_lock(&mpcb->mutex);
lock_sock(meta_sk);
if (meta_tp->inside_tk_table) {
/* Detach the mpcb from the token hashtable */
mptcp_hash_remove_bh(meta_tp);
reqsk_queue_destroy(&inet_csk(meta_sk)->icsk_accept_queue);
}
meta_sk->sk_shutdown = SHUTDOWN_MASK;
/* We need to flush the recv. buffs. We do this only on the
* descriptor close, not protocol-sourced closes, because the
* reader process may not have drained the data yet!
*/
while ((skb = __skb_dequeue(&meta_sk->sk_receive_queue)) != NULL) {
u32 len = TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq -
tcp_hdr(skb)->fin;
data_was_unread += len;
__kfree_skb(skb);
}
sk_mem_reclaim(meta_sk);
/* If socket has been already reset (e.g. in tcp_reset()) - kill it. */
if (meta_sk->sk_state == TCP_CLOSE) {
mptcp_for_each_sk_safe(mpcb, sk_it, tmpsk)
mptcp_sub_close(sk_it, 0);
goto adjudge_to_death;
}
if (data_was_unread) {
/* Unread data was tossed, zap the connection. */
NET_INC_STATS_USER(sock_net(meta_sk), LINUX_MIB_TCPABORTONCLOSE);
tcp_set_state(meta_sk, TCP_CLOSE);
tcp_send_active_reset(meta_sk, meta_sk->sk_allocation);
} else if (sock_flag(meta_sk, SOCK_LINGER) && !meta_sk->sk_lingertime) {
/* Check zero linger _after_ checking for unread data. */
meta_sk->sk_prot->disconnect(meta_sk, 0);
NET_INC_STATS_USER(sock_net(meta_sk), LINUX_MIB_TCPABORTONDATA);
} else if (tcp_close_state(meta_sk)) {
mptcp_send_fin(meta_sk);
} else if (meta_tp->snd_una == meta_tp->write_seq) {
/* The DATA_FIN has been sent and acknowledged
* (e.g., by sk_shutdown). Close all the other subflows
*/
mptcp_for_each_sk_safe(mpcb, sk_it, tmpsk) {
unsigned long delay = 0;
/* If we are the passive closer, don't trigger
* subflow-fin until the subflow has been finned
* by the peer. - thus we add a delay
*/
if (mpcb->passive_close &&
sk_it->sk_state == TCP_ESTABLISHED)
delay = inet_csk(sk_it)->icsk_rto << 3;
mptcp_sub_close(sk_it, delay);
}
}
sk_stream_wait_close(meta_sk, timeout);
adjudge_to_death:
state = meta_sk->sk_state;
sock_hold(meta_sk);
sock_orphan(meta_sk);
/* socket will be freed after mptcp_close - we have to prevent
* access from the subflows.
*/
mptcp_for_each_sk(mpcb, sk_it) {
/* Similar to sock_orphan, but we don't set it DEAD, because
* the callbacks are still set and must be called.
*/
write_lock_bh(&sk_it->sk_callback_lock);
sk_set_socket(sk_it, NULL);
sk_it->sk_wq = NULL;
write_unlock_bh(&sk_it->sk_callback_lock);
}
/* It is the last release_sock in its life. It will remove backlog. */
release_sock(meta_sk);
/* Now socket is owned by kernel and we acquire BH lock
* to finish close. No need to check for user refs.
*/
local_bh_disable();
bh_lock_sock(meta_sk);
WARN_ON(sock_owned_by_user(meta_sk));
percpu_counter_inc(meta_sk->sk_prot->orphan_count);
/* Have we already been destroyed by a softirq or backlog? */
if (state != TCP_CLOSE && meta_sk->sk_state == TCP_CLOSE)
goto out;
/* This is a (useful) BSD violating of the RFC. There is a
* problem with TCP as specified in that the other end could
* keep a socket open forever with no application left this end.
* We use a 3 minute timeout (about the same as BSD) then kill
* our end. If they send after that then tough - BUT: long enough
* that we won't make the old 4*rto = almost no time - whoops
* reset mistake.
*
* Nope, it was not mistake. It is really desired behaviour
* f.e. on http servers, when such sockets are useless, but
* consume significant resources. Let's do it with special
* linger2 option. --ANK
*/
if (meta_sk->sk_state == TCP_FIN_WAIT2) {
if (meta_tp->linger2 < 0) {
tcp_set_state(meta_sk, TCP_CLOSE);
tcp_send_active_reset(meta_sk, GFP_ATOMIC);
NET_INC_STATS_BH(sock_net(meta_sk),
LINUX_MIB_TCPABORTONLINGER);
} else {
const int tmo = tcp_fin_time(meta_sk);
if (tmo > TCP_TIMEWAIT_LEN) {
inet_csk_reset_keepalive_timer(meta_sk,
tmo - TCP_TIMEWAIT_LEN);
} else {
tcp_time_wait(meta_sk, TCP_FIN_WAIT2, tmo);
goto out;
}
}
}
if (meta_sk->sk_state != TCP_CLOSE) {
sk_mem_reclaim(meta_sk);
if (tcp_too_many_orphans(meta_sk, 0)) {
if (net_ratelimit())
pr_info("MPTCP: too many of orphaned sockets\n");
tcp_set_state(meta_sk, TCP_CLOSE);
tcp_send_active_reset(meta_sk, GFP_ATOMIC);
NET_INC_STATS_BH(sock_net(meta_sk),
LINUX_MIB_TCPABORTONMEMORY);
}
}
if (meta_sk->sk_state == TCP_CLOSE)
inet_csk_destroy_sock(meta_sk);
/* Otherwise, socket is reprieved until protocol close. */
out:
bh_unlock_sock(meta_sk);
local_bh_enable();
mutex_unlock(&mpcb->mutex);
sock_put(meta_sk); /* Taken by sock_hold */
}
/* Returns 1 if we should enable MPTCP for that socket. */
int mptcp_doit(struct sock *sk)
{
/* Socket may already be established (e.g., called from tcp_recvmsg) */
if (tcp_sk(sk)->mpc || tcp_sk(sk)->request_mptcp)
return 1;
if (!sysctl_mptcp_enabled)
return 0;
/* Don't do mptcp over loopback or local addresses */
if (sk->sk_family == AF_INET &&
(ipv4_is_loopback(inet_sk(sk)->inet_daddr) ||
ipv4_is_loopback(inet_sk(sk)->inet_saddr)))
return 0;
if (sk->sk_family == AF_INET6 &&
(ipv6_addr_loopback(&inet6_sk(sk)->daddr) ||
ipv6_addr_loopback(&inet6_sk(sk)->saddr)))
return 0;
if (mptcp_v6_is_v4_mapped(sk) &&
ipv4_is_loopback(inet_sk(sk)->inet_saddr))
return 0;
return 1;
}
int mptcp_create_master_sk(struct sock *meta_sk, __u64 remote_key, u32 window)
{
struct tcp_sock *master_tp;
struct sock *master_sk;
if (mptcp_alloc_mpcb(meta_sk, remote_key, window))
goto err_alloc_mpcb;
master_sk = tcp_sk(meta_sk)->mpcb->master_sk;
master_tp = tcp_sk(master_sk);
if (mptcp_add_sock(meta_sk, master_sk, 0, GFP_ATOMIC))
goto err_add_sock;
if (__inet_inherit_port(meta_sk, master_sk) < 0)
goto err_add_sock;
meta_sk->sk_prot->unhash(meta_sk);
if (master_sk->sk_family == AF_INET || mptcp_v6_is_v4_mapped(master_sk))
__inet_hash_nolisten(master_sk, NULL);
#if IS_ENABLED(CONFIG_IPV6)
else
__inet6_hash(master_sk, NULL);
#endif
master_tp->mptcp->init_rcv_wnd = master_tp->rcv_wnd;
return 0;
err_add_sock:
mptcp_fallback_meta_sk(meta_sk);
inet_csk_prepare_forced_close(master_sk);
tcp_done(master_sk);
inet_csk_prepare_forced_close(meta_sk);
tcp_done(meta_sk);
err_alloc_mpcb:
return -ENOBUFS;
}
int mptcp_check_req_master(struct sock *sk, struct sock *child,
struct request_sock *req,
struct request_sock **prev,
struct mptcp_options_received *mopt)
{
struct tcp_sock *child_tp = tcp_sk(child);
struct sock *meta_sk = child;
struct mptcp_cb *mpcb;
struct mptcp_request_sock *mtreq;
if (!tcp_rsk(req)->saw_mpc)
return 1;
/* Just set this values to pass them to mptcp_alloc_mpcb */
mtreq = mptcp_rsk(req);
child_tp->mptcp_loc_key = mtreq->mptcp_loc_key;
child_tp->mptcp_loc_token = mtreq->mptcp_loc_token;
if (mptcp_create_master_sk(meta_sk, mtreq->mptcp_rem_key,
child_tp->snd_wnd))
return -ENOBUFS;
child = tcp_sk(child)->mpcb->master_sk;
child_tp = tcp_sk(child);
mpcb = child_tp->mpcb;
child_tp->mptcp->snt_isn = tcp_rsk(req)->snt_isn;
child_tp->mptcp->rcv_isn = tcp_rsk(req)->rcv_isn;
mpcb->dss_csum = mtreq->dss_csum;
mpcb->server_side = 1;
/* Will be moved to ESTABLISHED by tcp_rcv_state_process() */
mptcp_update_metasocket(child, meta_sk);
/* Needs to be done here additionally, because when accepting a
* new connection we pass by __reqsk_free and not reqsk_free.
*/
mptcp_reqsk_remove_tk(req);
/* Hold when creating the meta-sk in tcp_vX_syn_recv_sock. */
sock_put(meta_sk);
inet_csk_reqsk_queue_unlink(sk, req, prev);
inet_csk_reqsk_queue_removed(sk, req);
inet_csk_reqsk_queue_add(sk, req, meta_sk);
return 0;
}
struct sock *mptcp_check_req_child(struct sock *meta_sk, struct sock *child,
struct request_sock *req,
struct request_sock **prev,
struct mptcp_options_received *mopt)
{
struct tcp_sock *child_tp = tcp_sk(child);
struct mptcp_request_sock *mtreq = mptcp_rsk(req);
struct mptcp_cb *mpcb = mtreq->mpcb;
u8 hash_mac_check[20];
child_tp->inside_tk_table = 0;
if (!mopt->join_ack)
goto teardown;
mptcp_hmac_sha1((u8 *)&mpcb->mptcp_rem_key,
(u8 *)&mpcb->mptcp_loc_key,
(u8 *)&mtreq->mptcp_rem_nonce,
(u8 *)&mtreq->mptcp_loc_nonce,
(u32 *)hash_mac_check);
if (memcmp(hash_mac_check, (char *)&mopt->mptcp_recv_mac, 20))
goto teardown;
/* Point it to the same struct socket and wq as the meta_sk */
sk_set_socket(child, meta_sk->sk_socket);
child->sk_wq = meta_sk->sk_wq;
if (mptcp_add_sock(meta_sk, child, mtreq->rem_id, GFP_ATOMIC)) {
child_tp->mpc = 0; /* Has been inherited, but now
* child_tp->mptcp is NULL
*/
/* TODO when we support acking the third ack for new subflows,
* we should silently discard this third ack, by returning NULL.
*
* Maybe, at the retransmission we will have enough memory to
* fully add the socket to the meta-sk.
*/
goto teardown;
}
/* The child is a clone of the meta socket, we must now reset
* some of the fields
*/
child_tp->mptcp->rcv_low_prio = mtreq->low_prio;
/* We should allow proper increase of the snd/rcv-buffers. Thus, we
* use the original values instead of the bloated up ones from the
* clone.
*/
child->sk_sndbuf = mpcb->orig_sk_sndbuf;
child->sk_rcvbuf = mpcb->orig_sk_rcvbuf;
child_tp->mptcp->slave_sk = 1;
child_tp->mptcp->snt_isn = tcp_rsk(req)->snt_isn;
child_tp->mptcp->rcv_isn = tcp_rsk(req)->rcv_isn;
child_tp->mptcp->init_rcv_wnd = req->rcv_wnd;
child_tp->tsq_flags = 0;
/* Subflows do not use the accept queue, as they
* are attached immediately to the mpcb.
*/
inet_csk_reqsk_queue_drop(meta_sk, req, prev);
return child;
teardown:
/* Drop this request - sock creation failed. */
inet_csk_reqsk_queue_drop(meta_sk, req, prev);
inet_csk_prepare_forced_close(child);
tcp_done(child);
return meta_sk;
}
int mptcp_time_wait(struct sock *sk, struct tcp_timewait_sock *tw)
{
struct mptcp_tw *mptw;
struct tcp_sock *tp = tcp_sk(sk);
struct mptcp_cb *mpcb = tp->mpcb;
/* Alloc MPTCP-tw-sock */
mptw = kmem_cache_alloc(mptcp_tw_cache, GFP_ATOMIC);
if (!mptw)
return -ENOBUFS;
atomic_inc(&mpcb->refcnt);
tw->mptcp_tw = mptw;
mptw->loc_key = mpcb->mptcp_loc_key;
mptw->meta_tw = mpcb->in_time_wait;
if (mptw->meta_tw) {
mptw->rcv_nxt = mptcp_get_rcv_nxt_64(mptcp_meta_tp(tp));
if (mpcb->mptw_state != TCP_TIME_WAIT)
mptw->rcv_nxt++;
}
rcu_assign_pointer(mptw->mpcb, mpcb);
spin_lock(&mpcb->tw_lock);
list_add_rcu(&mptw->list, &tp->mpcb->tw_list);
mptw->in_list = 1;
spin_unlock(&mpcb->tw_lock);
return 0;
}
void mptcp_twsk_destructor(struct tcp_timewait_sock *tw)
{
struct mptcp_cb *mpcb;
rcu_read_lock();
mpcb = rcu_dereference(tw->mptcp_tw->mpcb);
/* If we are still holding a ref to the mpcb, we have to remove ourself
* from the list and drop the ref properly.
*/
if (mpcb && atomic_inc_not_zero(&mpcb->refcnt)) {
spin_lock(&mpcb->tw_lock);
if (tw->mptcp_tw->in_list) {
list_del_rcu(&tw->mptcp_tw->list);
tw->mptcp_tw->in_list = 0;
}
spin_unlock(&mpcb->tw_lock);
/* Twice, because we increased it above */
mptcp_mpcb_put(mpcb);
mptcp_mpcb_put(mpcb);
}
rcu_read_unlock();
kmem_cache_free(mptcp_tw_cache, tw->mptcp_tw);
}
/* Updates the rcv_nxt of the time-wait-socks and allows them to ack a
* data-fin.
*/
void mptcp_update_tw_socks(const struct tcp_sock *tp, int state)
{
struct mptcp_tw *mptw;
/* Used for sockets that go into tw after the meta
* (see mptcp_time_wait())
*/
tp->mpcb->in_time_wait = 1;
tp->mpcb->mptw_state = state;
/* Update the time-wait-sock's information */
rcu_read_lock_bh();
list_for_each_entry_rcu(mptw, &tp->mpcb->tw_list, list) {
mptw->meta_tw = 1;
mptw->rcv_nxt = mptcp_get_rcv_nxt_64(tp);
/* We want to ack a DATA_FIN, but are yet in FIN_WAIT_2 -
* pretend as if the DATA_FIN has already reached us, that way
* the checks in tcp_timewait_state_process will be good as the
* DATA_FIN comes in.
*/
if (state != TCP_TIME_WAIT)
mptw->rcv_nxt++;
}
rcu_read_unlock_bh();
}
struct workqueue_struct *mptcp_wq;
/* General initialization of mptcp */
void __init mptcp_init(void)
{
#ifdef CONFIG_SYSCTL
struct ctl_table_header *mptcp_sysctl;
#endif
mptcp_sock_cache = kmem_cache_create("mptcp_sock",
sizeof(struct mptcp_tcp_sock),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (!mptcp_sock_cache)
goto out;
mptcp_cb_cache = kmem_cache_create("mptcp_cb", sizeof(struct mptcp_cb),
0, SLAB_DESTROY_BY_RCU|SLAB_HWCACHE_ALIGN,
NULL);
if (!mptcp_cb_cache)
goto mptcp_cb_cache_failed;
mptcp_tw_cache = kmem_cache_create("mptcp_tw", sizeof(struct mptcp_tw),
0, SLAB_DESTROY_BY_RCU|SLAB_HWCACHE_ALIGN,
NULL);
if (!mptcp_tw_cache)
goto mptcp_tw_cache_failed;
get_random_bytes(mptcp_secret, sizeof(mptcp_secret));
mptcp_wq = alloc_workqueue("mptcp_wq", WQ_UNBOUND | WQ_MEM_RECLAIM, 8);
if (!mptcp_wq)
goto alloc_workqueue_failed;
if (mptcp_pm_init())
goto mptcp_pm_failed;
#ifdef CONFIG_SYSCTL
mptcp_sysctl = register_net_sysctl(&init_net, "net/mptcp", mptcp_table);
if (!mptcp_sysctl)
goto register_sysctl_failed;
#endif
pr_info("MPTCP: Stable release v0.87.0");
out:
return;
#ifdef CONFIG_SYSCTL
register_sysctl_failed:
mptcp_pm_undo();
#endif
mptcp_pm_failed:
destroy_workqueue(mptcp_wq);
alloc_workqueue_failed:
kmem_cache_destroy(mptcp_tw_cache);
mptcp_tw_cache_failed:
kmem_cache_destroy(mptcp_cb_cache);
mptcp_cb_cache_failed:
kmem_cache_destroy(mptcp_sock_cache);
}
|
teto/mptcp-old
|
net/mptcp/mptcp_ctrl.c
|
C
|
gpl-2.0
| 50,671
|
package array;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class ProtoSlice<T> implements Iterable<ProtoSlice.ArrayAccessor<T>>{
final ArrayAccessor<T> aa;
final int size;
final int beginIdx;
private ProtoSlice(ArrayAccessor<T> accessor, int beginIdx, int size) {
this.aa = accessor;
this.size = size;
this.beginIdx = beginIdx;
}
@Override
public Iterator<ArrayAccessor<T>> iterator() {
return new AccessorIterator<T>(beginIdx, size, aa);
}
@Override
public Spliterator<ArrayAccessor<T>> spliterator() {
return new AccessorSpliterator<T>(beginIdx, size-1, estimateReasonableSplitSize(size), aa);
}
public Stream<ArrayAccessor<T>> stream(boolean parallel) {
return StreamSupport.stream(spliterator(), parallel);
}
public Stream<ArrayAccessor<T>> stream() {
return stream(false);
}
public Stream<ArrayAccessor<T>> parallelStream() {
return stream(true);
}
@Override
public void forEach(Consumer<? super ArrayAccessor<T>> action) {
Iterable.super.forEach(action);
}
public void forEachParallel(Consumer<? super ArrayAccessor<T>> action) {
parallelStream().forEach(action);
}
public ProtoSlice<T> copy() {
return new ProtoSlice<T>(aa.copy(),beginIdx,size);
}
public T getAt(int i){
return aa.get(i);
}
public void setAt(int i, T e){
aa.set(i, e);
}
public int length() {
return size;
}
public int size() {
return size;
}
public int getBeginIdx() {
return beginIdx;
}
///////////////////////////////
// Constructors
///////////////////////////////
////MKNATIVE>>>>
static /*RM*/<T>/**/ ProtoSlice</*G*/T/**/> get(/*N*/T/**/[] array, int beginIdx, int length){
return new ProtoSlice</*G*/T/**/>(new /*RPLC:Generic*/GenericAccessor/**//*RM*/<T>/**/(array), beginIdx, length);
}
static /*RM*/<T>/**/ ProtoSlice</*G*/T/**/> get(/*N*/T/**/[] array){
return get(array, 0, array.length);
}
////<<<<
///////////////////////////////
// Static Streaming
///////////////////////////////
static int estimateReasonableSplitSize(int length) {
final int tasksPerProcessor = 16;
final int concurrentLimit = Runtime.getRuntime().availableProcessors()*tasksPerProcessor;
final int minReasonable = 512;
return Math.max(minReasonable, Integer.highestOneBit(length/concurrentLimit));
}
////MKNATIVE>>>>
public static /*RM*/<T>/**/ Stream<ArrayAccessor</*G*/T/**/>> stream(/*N*/T/**/[] array, boolean parallel, int beginIndex, int length, int minSplitSize){
return StreamSupport.stream(new AccessorSpliterator</*G*/T/**/>(beginIndex, beginIndex+length-1, minSplitSize, new /*RPLC:Generic*/GenericAccessor/**//*RM*/<T>/**/(array)), parallel);
}
public static /*RM*/<T>/**/ Stream<ArrayAccessor</*G*/T/**/>> stream(/*N*/T/**/[] array, boolean parallel, int beginIndex, int length){
return stream(array, parallel, beginIndex, length, estimateReasonableSplitSize(length));
}
public static /*RM*/<T>/**/ Stream<ArrayAccessor</*G*/T/**/>> stream(/*N*/T/**/[] array, boolean parallel){
return stream(array, parallel, 0, array.length);
}
////<<<<
///////////////////////////////
// Accessors
///////////////////////////////
public static abstract class ArrayAccessor<T> implements Cloneable {
protected int index;
public abstract T get();
public abstract void set(T e);
protected abstract T get(int i);
protected abstract void set(int i, T e);
public final int getIndex(){ return index; }
public final void setIndex(int i){index = i; }
/** only copies reference */
protected abstract ArrayAccessor<T> clone();
/** allocates new array */
protected abstract ArrayAccessor<T> copy();
@Override
public String toString() {
return String.format("[%s] at index %d", getClass().getSimpleName(), index);
}
}
////MKNATIVE>>>>
static class /*RPLC:Generic*/GenericAccessor/**//*RM*/<T>/**/ extends ArrayAccessor</*G*/T/**/> {
/*N*/T/**/[] array;
public /*RPLC:Generic*/GenericAccessor/**/(/*N*/T/**/[] array) {
this.array=array;
}
@Override
public /*G*/T/**/ get() {return array[index];}
@Override
public void set(/*G*/T/**/ e) {array[index] = e;}
@Override
protected /*G*/T/**/ get(int i) {return array[i];}
@Override
protected void set(int i, /*G*/T/**/ e) {array[i] = e;}
@Override
protected /*RPLC:Generic*/GenericAccessor/**//*RM*/<T>/**/ clone() {
/*RPLC:Generic*/GenericAccessor/**//*RM*/<T>/**/ clon = new /*RPLC:Generic*/GenericAccessor/**//*RM*/<>/**/(array);
clon.setIndex(index);
return clon;
}
@Override
protected /*RPLC:Generic*/GenericAccessor/**//*RM*/<T>/**/ copy() {
/*RPLC:Generic*/GenericAccessor/**//*RM*/<T>/**/ cpy = new /*RPLC:Generic*/GenericAccessor/**//*RM*/<T>/**/(Arrays.copyOf(array, array.length));
cpy.setIndex(index);
return cpy;
}
}
////<<<<
///////////////////////////////
// Iterator & Spliterator
///////////////////////////////
static class AccessorIterator<T> implements Iterator<ArrayAccessor<T>> {
int i;
final int endIndexExcl;
final ArrayAccessor<T> acc;
public AccessorIterator(int startIndex, int endIndexExcl, ArrayAccessor<T> acc) {
this.acc = acc.clone();
this.i = startIndex-1;
this.endIndexExcl = endIndexExcl;
}
@Override
public boolean hasNext() {
return i+1 < endIndexExcl;
}
@Override
public ArrayAccessor<T> next() {
i++;
acc.setIndex(i);
return acc;
}
@Override
public void forEachRemaining(Consumer<? super ArrayAccessor<T>> action) {
i++;
for(; i < endIndexExcl; i++){
acc.setIndex(i);
}
}
}
static class AccessorSpliterator<T> implements Spliterator<ArrayAccessor<T>> {
final ArrayAccessor<T> acc;
int endIndex;
final int minimumSplitSize;
/**
* Constructs a new ImgSpliterator for the specified index range
* @param startIndex first index of the range (inclusive)
* @param endIndex last index of the range (inclusive)
* @param minSplitSize minimum split size for this spliterator (minimum number of elements in a split)
*/
AccessorSpliterator(int startIndex, int endIndex, int minSplitSize, ArrayAccessor<T> acc) {
this.acc = acc.clone();
this.acc.setIndex(startIndex);
this.endIndex = endIndex;
this.minimumSplitSize = minSplitSize;
}
private void setEndIndex(int endIndex) {
this.endIndex = endIndex;
}
@Override
public boolean tryAdvance(final Consumer<? super ArrayAccessor<T>> action) {
if(acc.getIndex() <= endIndex){
int index = acc.getIndex();
action.accept(acc);
acc.setIndex(index+1);
return true;
} else {
return false;
}
}
@Override
public void forEachRemaining(final Consumer<? super ArrayAccessor<T>> action) {
int idx = acc.getIndex();
for(;idx <= endIndex; acc.setIndex(++idx)){
action.accept(acc);
}
}
@Override
public Spliterator<ArrayAccessor<T>> trySplit() {
int currentIdx = Math.min(acc.getIndex(), endIndex);
int midIdx = currentIdx + (endIndex-currentIdx)/2;
if(midIdx > currentIdx+minimumSplitSize){
AccessorSpliterator<T> split = new AccessorSpliterator<T>(midIdx, endIndex, minimumSplitSize, acc);
setEndIndex(midIdx-1);
return split;
} else {
return null;
}
}
@Override
public long estimateSize() {
int currentIndex = acc.getIndex();
int lastIndexPlusOne = endIndex+1;
return lastIndexPlusOne-currentIndex;
}
@Override
public int characteristics() {
return NONNULL | SIZED | CONCURRENT | SUBSIZED | IMMUTABLE;
}
}
}
|
hageldave/UsefulStuff
|
src/main/java/array/ProtoSlice.java
|
Java
|
gpl-2.0
| 7,941
|
#!/bin/bash
# -------------------------------------------
# Subtitle downloader for subhd.com
# by luodan@gmail.com
# v0.9 2015.08.12
# -------------------------------------------
CDIR=`dirname "$0"`
[ ! -f "$CDIR/lib.engines.sh" ] && echo "ERROR: Subtitle engine library file not found, abort!" && exit 1
. "$CDIR/lib.engines.sh"
[ "x$DOWNLOAD_URL" == "x" ] && log "ERROR: Detail page URL not found, abort!" && exit 1
if [ "x$DOWNLOAD_DIRECTORY" == "x" -o ! -d "$DOWNLOAD_DIRECTORY" -o ! -w "$DOWNLOAD_DIRECTORY" ]; then
log "ERROR: Download directory not found or not accessable, abort."
exit 1
fi
ENGINE_SITE=http://subhd.com
CURL_FILE="$CSD_TEMP_DIRECTORY/detail.$MODEL_NAME.$VIDEO_FILE_NAME.html"
SUBTITLE_ID="${DOWNLOAD_URL##*/}"
log "Download subtitle from $ENGINE_SITE ..."
[ ! -f "$CURL_FILE" ] && curl --connect-timeout $CONNECT_TIMEOUT -s -o "$CURL_FILE" -A "$USER_AGENT" -e "$DOWNLOAD_URL" -d "sub_id=$SUBTITLE_ID" "http://subhd.com/ajax/down_ajax"
SUBTITLE_URL="`cat "$CURL_FILE"|awk '{s="";if (match($0,/"url":"[^"]+"/)){s=substr($0,RSTART+7,RLENGTH-8);}gsub(/\\\\/,"",s);print s;}'`"
#rm -rf "$CURL_FILE"
# Download subtitle
[ "x$SUBTITLE_URL" == "x" ] && log "Video page founded, but no subtitle URL found." && exit 1
regularize_request_url "$SUBTITLE_URL"
( cd "$DOWNLOAD_DIRECTORY"; curl --connect-timeout $CONNECT_TIMEOUT -A "$USER_AGENT" -k -s -O -J "$REQUEST_URL"; )
# Notice: curl has no overwrite checking for -O or -J, so I can't know if it's downloaded successfully when there is already same file exists.
log "Subtitle (or packed file) downloaded."
exit 0
|
lu0dan/chinese-subtitle-downloader
|
scripts/download_subhd.sh
|
Shell
|
gpl-2.0
| 1,594
|
$(document).ready(function() {
status('Choose a file :)');
var timerId;
timerId = setInterval(function() {
if($('#userPhotoInput').val() !== '') {
clearInterval(timerId);
$('#uploadForm').submit();
}
}, 500);
$('#uploadForm').submit(function() {
status('uploading the file ...');
$(this).ajaxSubmit({
dataType: 'text',
error: function(xhr) {
status('Error: ' + xhr.status);
},
success: function(response) {
try {
response = $.parseJSON(response);
}
catch(e) {
status('Bad response from server');
return;
}
if(response.error) {
status('Oops, something bad happened');
return;
}
var imageUrlOnServer = response.path;
status('Success, file uploaded to:' + imageUrlOnServer);
}
});
return false;
});
function status(message) {
$('#status').text(message);
}
});
|
proyecto2015daw/nodibrary
|
views/js/upload.js
|
JavaScript
|
gpl-2.0
| 1,186
|
package org.nwnx.nwnx2.jvm.constants;
/**
* This class contains all unique constants beginning with "FAMILIAR_CREATURE".
* Non-distinct keys are filtered; only the LAST appearing was
* kept.
*/
public final class FamiliarCreature {
private FamiliarCreature() {}
public final static int TYPE_BAT = 0;
public final static int TYPE_CRAGCAT = 1;
public final static int TYPE_EYEBALL = 10;
public final static int TYPE_FAIRY_DRAGON = 8;
public final static int TYPE_FIREMEPHIT = 4;
public final static int TYPE_HELLHOUND = 2;
public final static int TYPE_ICEMEPHIT = 5;
public final static int TYPE_IMP = 3;
public final static int TYPE_NONE = 255;
public final static int TYPE_PIXIE = 6;
public final static int TYPE_PSEUDO_DRAGON = 9;
public final static int TYPE_RAVEN = 7;
public static String nameOf(int value) {
if (value == 0) return "FamiliarCreature.TYPE_BAT";
if (value == 1) return "FamiliarCreature.TYPE_CRAGCAT";
if (value == 10) return "FamiliarCreature.TYPE_EYEBALL";
if (value == 8) return "FamiliarCreature.TYPE_FAIRY_DRAGON";
if (value == 4) return "FamiliarCreature.TYPE_FIREMEPHIT";
if (value == 2) return "FamiliarCreature.TYPE_HELLHOUND";
if (value == 5) return "FamiliarCreature.TYPE_ICEMEPHIT";
if (value == 3) return "FamiliarCreature.TYPE_IMP";
if (value == 255) return "FamiliarCreature.TYPE_NONE";
if (value == 6) return "FamiliarCreature.TYPE_PIXIE";
if (value == 9) return "FamiliarCreature.TYPE_PSEUDO_DRAGON";
if (value == 7) return "FamiliarCreature.TYPE_RAVEN";
return "FamiliarCreature.(not found: " + value + ")";
}
public static String nameOf(float value) {
return "FamiliarCreature.(not found: " + value + ")";
}
public static String nameOf(String value) {
return "FamiliarCreature.(not found: " + value + ")";
}
}
|
Baaleos/nwnx2-linux
|
plugins/jvm/java/src/org/nwnx/nwnx2/jvm/constants/FamiliarCreature.java
|
Java
|
gpl-2.0
| 1,854
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Wishlist\Block\Customer\Wishlist;
class ItemsTest extends \PHPUnit\Framework\TestCase
{
public function testGetColumns()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$layout = $objectManager->get(
\Magento\Framework\View\LayoutInterface::class
);
$block = $layout->addBlock(\Magento\Wishlist\Block\Customer\Wishlist\Items::class, 'test');
$child = $this->getMockBuilder(\Magento\Wishlist\Block\Customer\Wishlist\Item\Column::class)
->setMethods(['isEnabled'])
->disableOriginalConstructor()
->getMock();
$child->expects($this->any())->method('isEnabled')->will($this->returnValue(true));
$layout->addBlock($child, 'child', 'test');
$expected = $child->getType();
$columns = $block->getColumns();
$this->assertNotEmpty($columns);
foreach ($columns as $column) {
$this->assertSame($expected, $column->getType());
}
}
}
|
kunj1988/Magento2
|
dev/tests/integration/testsuite/Magento/Wishlist/Block/Customer/Wishlist/ItemsTest.php
|
PHP
|
gpl-2.0
| 1,145
|
<?
require_once( "commandLine.inc" );
$wgUser = User::newFromName("LinkTool");
$ignore_pages = array(
"main page",
"about wikihow",
);
$ignore_words = explode(",", "get,create,choose,stop,clean,avoid,keep,start,tell,remove,take,draw,survive,install,change,put,know,prepare,act,buy,cope,not,convince,set,win,fix,add,care,learn,convert,eat,throw,perform,give,improve,understand,apply,how,cook,teach,treat,save,turn,grow,organize,beat,catch,talk,run,plan,read,rid,of,your,own,be");
function getPhrases ($filename) {
$phrases = array();
$f = file_get_contents($filename);
$lines = split("\n", $f);
shuffle($lines); // why not?
foreach ($lines as $line) {
if (trim($line)== "") continue;
$tokens = split("\t", $line);
$phrases[$tokens[0]] = $tokens[1];
}
return $phrases;
}
function recentlyProcessedPhrase($phrase) {
$dbr = wfGetDB(DB_SLAVE);
$count = $dbr->selectField('recentchanges',
array('count(*)'),
array(
//'rc_cur_id' => $result->getArticleID(),
'rc_comment' => "Adding keyword links for phrase " . $phrase
)
);
return $count > 0;
}
function recentlyEdited($result, $phrase) {
$dbr = wfGetDB(DB_SLAVE);
$count = $dbr->selectField('recentchanges',
array('count(*)'),
array('rc_cur_id' => $result->getArticleID(),
'rc_comment' => "Adding keyword links for phrase " . $phrase
)
);
return $count > 0;
}
function markPatrolled() {
$dbw = wfGetDB(DB_MASTER);
$dbw->update('recentchanges',
array('rc_patrolled=1'),
array('rc_user_text' => "LinkTool")
);
return $count > 0;
}
# takes an article ($result), and links occurences
# of $phrase with a link to $title
function smartReplace($phrase, $title, $result, &$numreplace) {
#fake word boundary
$fb = "[^a-zA-Z0-9_|\[\]]";
#echo "Smart replace called on p: {$phrase}, t:{$title}, r:{$result->getText()}\n";
$tObj = Title::newFromText($title);
if (!$tObj || $tObj->getArticleID() == 0) {
#echo "No article for $title\n";
return;
}
$title = $tObj->getText();
$rev = Revision::newFromTitle($result);
if (!$rev) return 0;
$text = $rev->getText();
if (stripos($text, $phrase) === false) return 0;
# @(\[{1,2}[^\]]*\]{1,2})@m
$re = '\[{1,2}[^\]]*\]{1,2}|'
. '\<[^>]*>|'
.'\{{1,2}[^\}]*\}{1,2}';
$parts = preg_split('@(' . $re . ')@m', $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$ret = "";
$replaced = 0;
$inlink = false; // for hardcoded <a href=> links.
while ($p = array_shift($parts)) {
if (strpos($p, "[") === 0) {
} else if (strpos($p, "{") === 0) {
} else if (stripos($p, "<a") === 0) {
$inlink = true;
} else if (stripos($p, "</a>") === 0) {
$inlink = false;
} else if (!$inklink) {
$p = preg_replace("@($fb)({$phrase}[s]?)($fb)@im", "$1[[{$title}|$2]]$3", $p, 1, $replaced);
}
$ret .= $p;
if ($replaced > 0)
break;
}
// anything at the end?
$ret .= implode("", $parts);
if ($replaced > 0) {
#debug this a bit
$a = new Article($result);
if (!recentlyEdited($result, $phrase)) {
if ($ret == $text) {
echo "No changes detected for {$result->getText()}, WTF?\n";
} else if ($a->updateArticle($ret, "Adding keyword links for phrase " . $phrase, true, false)) {
$numreplace = $replaced;
echo "{$phrase}\t{$title}\t{$result->getText()}\n";
} else {
echo "Couldn't update article {$result->getText()}, WTF?\n";
}
} else {
#echo "{$result->getText()} was recently linked... skipping.\n";
}
} else {
#echo "Couldn't find {$phrase} in this text\n\n";
#echo "$text ------\n\n------\n\n";
}
return $ret;
}
function getFirstWord($t) {
global $ignore_words;
$words = preg_split("/\s/", strtolower($t));
foreach ($words as $w) {
$ret .= $w . " ";
if (!in_array($w, $ignore_words)) {
break;
}
}
return trim($ret);
}
$phrases = getPhrases(isset($argv[0]) ? $argv[0] : "/var/www/html/wiki/maintenance/keywords_to_link.txt");
# iterate over the list of phrases
$totallinks = 0;
foreach ($phrases as $phrase=>$title) {
// skip ones we've already done recently
if (recentlyProcessedPhrase($phrase))
continue;
$titleObj = Title::newFromText($title);
if (!$titleObj) {
$errs .= "<li>Could not generate at title for '{$title}'</li>";
continue;
}
if ($titleObj->getArticleID() == 0)
$titleObj = Title::newFromURL($title);
if (!$titleObj || $titleObj->getArticleID() == 0) {
$errs .= "<li>The article for '{$title}' does not exist</li>";
continue;
}
# get results from the Google Mini
$l = new LSearch();
$results = $l->googleSearchResultTitles('"' . $phrase. '"');
$newresults = array();
# filter out some of the results (links to their own pages, videos, etc)
foreach ($results as $r) {
if (strtolower($r->getText()) == strtolower($title)) continue;
if ($r->getNamespace() != NS_MAIN || strpos($r->getText(), "Video/") !== false) continue;
$a = new Article($r);
if ($a->isRedirect()) continue;
if (in_array(strtolower($r->getText()), $ignore_pages)) continue;
$first_w_r = getFirstWord($r->getText());
$first_w_p = getFirstWord($phrase);
if ($first_w_r == $first_w_p) {
#echo "The first words ({$first_w_p}, {$first_w_r}) match for phrase '{$phrase}' and result '{$r->getText()}', skipping...\n";
continue;
} else {
#echo "({$first_w_p}, {$first_w_r}) DO NOT match for phrase {$phrase} and result {$r->getText()}\n";
}
$newresults[] = $r;
}
# any results?
$newlinks = 0; // # of new links linking phrase to title
foreach ($newresults as $r) {
$numreplace= 0;
smartReplace($phrase, $title, $r, &$numreplace);
$newlinks += $numreplace;
$totallinks += $numreplace;
markPatrolled();
}
if ($totallinks >= 500) {
echo "Created $totallinks ... exiting..\n";
break;
}
}
|
legoktm/wikihow-src
|
maintenance/addGoogleKeywordsLinksWithMini.php
|
PHP
|
gpl-2.0
| 5,864
|
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ro" version="2.0">
<context>
<name>MainWindow</name>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="14"/>
<source>Octopi</source>
<translation>Octopi</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="110"/>
<source>Info</source>
<translation>Info</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="115"/>
<source>Files</source>
<translation>Fișiere</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="120"/>
<location filename="Projects/octopi/ui/mainwindow.ui" line="164"/>
<source>Transaction</source>
<translation>Tranzacție</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="125"/>
<source>Output</source>
<translation>Rezultat</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="147"/>
<source>Help</source>
<translation>Ajutor</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="155"/>
<source>View</source>
<translation>Mod afișare</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="171"/>
<source>File</source>
<translation>Fișier</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="184"/>
<source>Search</source>
<translation>Căutare</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="193"/>
<source>Tools</source>
<translation>Unelte</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="222"/>
<location filename="Projects/octopi/ui/mainwindow.ui" line="225"/>
<source>About</source>
<translation>Despre</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="239"/>
<source>Non installed</source>
<translation>Neinstalate</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="248"/>
<source>Commit</source>
<translation>Comite</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="251"/>
<source>Ctrl+M</source>
<translation>Ctrl+M</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="260"/>
<source>Rollback</source>
<translation>Anulează</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="263"/>
<source>Ctrl+B</source>
<translation>Ctrl+B</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="272"/>
<source>Sync database</source>
<translation>Sincronizează baza de date</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="275"/>
<source>Ctrl+D</source>
<translation>Ctrl+D</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="284"/>
<source>Exit</source>
<translation>Ieșire</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="287"/>
<source>Ctrl+Q</source>
<translation>Ctrl+Q</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="296"/>
<source>System upgrade</source>
<translation>Actualizare de sistem</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="299"/>
<source>Ctrl+U</source>
<translation>Ctrl+U</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="308"/>
<location filename="Projects/octopi/ui/mainwindow.ui" line="311"/>
<location filename="Projects/octopi/ui/mainwindow.ui" line="513"/>
<source>Install</source>
<translation>Instalează</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="320"/>
<location filename="Projects/octopi/ui/mainwindow.ui" line="323"/>
<source>Remove</source>
<translation>Șterge</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="328"/>
<source>Outdated packages</source>
<translation>Pachete învechite</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="337"/>
<source>Get latest distro news</source>
<translation>Obține ultimele știri ale distribuției</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="340"/>
<source>Ctrl+G</source>
<translation>Ctrl+G</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="349"/>
<source>Remove group</source>
<translation>Șterge grupa</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="358"/>
<source>Install group</source>
<translation>Instalează grupa</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="367"/>
<source>Collapse item</source>
<translation>Pliază elementul</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="376"/>
<source>Expand item</source>
<translation>Desfășoară elementul</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="385"/>
<source>Collapse all items</source>
<translation>Pliază toate elementele</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="394"/>
<source>Expand all items</source>
<translation>Desfășoară toate elementele</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="403"/>
<source>Open file</source>
<translation>Deschide fișier</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="412"/>
<source>Edit file</source>
<translation>Editează fișier</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="421"/>
<source>Open directory</source>
<translation>Deschide director</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="430"/>
<source>Open terminal here</source>
<translation>Deschide un terminal aici</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="439"/>
<source>Remove item</source>
<translation>Șterge element</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="451"/>
<source>Remove items</source>
<translation>Șterge elemente</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="462"/>
<source>By description</source>
<translation>După descriere</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="470"/>
<source>By name</source>
<translation>După nume</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="479"/>
<source>Find a file</source>
<translation>Găsește un fișier</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="488"/>
<source>Open root terminal</source>
<translation>Deschide terminal rădăcină</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="493"/>
<source>Usage</source>
<translation>Folosință</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="496"/>
<source>F1</source>
<translation>F1</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="504"/>
<source>Install local package...</source>
<translation>Instalează pachet local...</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="521"/>
<source>Pacman Log Viewer</source>
<translation>Vizualizator istoric Pacman</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="533"/>
<source>Repository Editor</source>
<translation>Editor depozite</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="541"/>
<source>Installed</source>
<translation>Instalate</translation>
</message>
<message>
<location filename="Projects/octopi/ui/mainwindow.ui" line="557"/>
<source>By file</source>
<translation>După fișier</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="55"/>
<source>For more information, visit:</source>
<translation>Pentru mai multe informații vizitați:</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="58"/>
<source>A Qt-based Pacman frontend,</source>
<translation>O interfață Pacman bazată pe Qt,</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="59"/>
<source>licensed under the terms of</source>
<translation>licențiată în termenii</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="77"/>
<source>Package classification:</source>
<translation>Clasificarea pachetelor:</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="80"/>
<source>An installed package</source>
<translation>Un pachet instalat</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="82"/>
<source>An installed package (not required by others)</source>
<translation>Un pachet instalat (ce nu e necesitat de altele)</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="85"/>
<source>A foreign package, installed from</source>
<translation>Un pachet străin, instalat din</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="88"/>
<source>A non installed package</source>
<translation>Un pachet neinstalat</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="91"/>
<source>An outdated package</source>
<translation>Un pachet învechit</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="94"/>
<source>An outdated foreign package</source>
<translation>Un pachet străin învechit</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="97"/>
<source>A newer than repository package</source>
<translation>Un pachet mai nou decât în depozit</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="100"/>
<source>Basic usage help:</source>
<translation>Ajutor de bază:</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="102"/>
<source>Position the mouse over a package to see its description</source>
<translation>Poziționați cursorul pe un pachet pentru a-i vedea descrierea</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="104"/>
<source>Double click an installed package to see its contents</source>
<translation>Dublu-clic pe un pachet instalat pentru a-i vedea conținutul</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="106"/>
<source>Right click package to install/reinstall or remove it</source>
<translation>Clic-dreapta pe un pachet pentru a-l (dez)instala sau șterge</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="109"/>
<source>Alt+key sequences:</source>
<translation>Secvențe cu tasta Alt:</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="111"/>
<source>Alt+1 to switch to 'Info' tab</source>
<translation>Alt+1 pentru a trece la fila „Info”</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="113"/>
<source>Alt+2 to switch to 'Files' tab</source>
<translation>Alt+2 pentru a trece la file „Fișiere”</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="115"/>
<source>Alt+3 to switch to 'Transaction' tab</source>
<translation>Alt+3 pentru a trece la fila „Tranzacții”</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="117"/>
<source>Alt+4 to switch to 'Output' tab</source>
<translation>Alt+4 pentru a trece la fila „Rezultat”</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="119"/>
<source>Alt+5 to switch to 'News' tab</source>
<translation>Alt+5 pentru a trece la fila „Știri”</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="121"/>
<source>Alt+6 or 'F1' to show this help page</source>
<translation>Alt+6 sau F1 pentru a reveni aici</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="124"/>
<source>Control+key sequences:</source>
<translation>Secvențe cu tasta Ctrl:</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="126"/>
<source>Ctrl+D or 'File/Sync database' to sync the local database with latest remote changes (pacman -Sy)</source>
<translation>Ctrl+D sau „Fișier/Sincronizează baza de date” pentru a sincroniza baza de date locală cu ultimele schimbări de la distanță (pacman -Sy)</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="128"/>
<source>Ctrl+U or 'File/System upgrade' to make a full system upgrade (pacman -Su)</source>
<translation>Ctrl+U sau „Fișier/Actualizare de sistem” pentru a face o actualizare de sistem completă (pacman -Su)</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="130"/>
<source>Ctrl+L to find a package in the package list</source>
<translation>Ctrl+L pentru a găsi un pachet în lista de pachete</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="132"/>
<source>Ctrl+F to search for text inside tab Files, News and Usage</source>
<translation>Ctrl+F pentru a căuta text în interiorul taburilor Fișiere, Știri și Folosință</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="136"/>
<source>Ctrl+M or 'Transaction/Commit' to start installation/removal of selected packages</source>
<translation>Ctrl+M sau „Tranzacție/Comite” pentru a începe instalarea/ștergerea pachetelor selectate</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="138"/>
<source>Ctrl+B or 'Transaction/Rollback' to clear the selection of to be removed/installed packages</source>
<translation>Ctrl+B sau „Tranzacție/Anulează” pentru a goli selecția din pachetele de instalat/șters</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="140"/>
<source>Ctrl+G or 'File/Get latest distro news' to retrieve the latest RSS based distro news</source>
<translation>Ctrl+G sai „Fișier/Obține ultimele știri ale distribuției” pentru a oține ultimele știri pe RSS</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="142"/>
<source>Ctrl+Q or 'File/Exit' to exit the application</source>
<translation>Ctrl+Q sau „Fișier/Ieșire” pentru a ieși din aplicație</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="145"/>
<source>Control+shift+key sequences:</source>
<translation>Secvențe cu tastele Ctrl+Shift:</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="147"/>
<source>Ctrl+Shift+C to clean local packages cache (pacman -Sc)</source>
<translation>Ctrl+Shift+C pentru a curăța cache-ul local de pachete (pacman -Sc)</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="149"/>
<source>Ctrl+Shift+G to display all package groups</source>
<translation>Ctrl+Shift+G pentru a arăta toate grupele de pachete</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="151"/>
<source>Ctrl+Shift+R to remove Pacman's transaction lock file</source>
<translation>Ctrl+Shift+R pentru a elimina fișierul de blocare a tranzacției Pacman</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="153"/>
<source>Ctrl+Shift+Y to display %1 group</source>
<translation>Ctrl+Shift+Y pentru a arăta grupul %1</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="156"/>
<source>F+key sequences:</source>
<translation>Secvențe cu tastele de funcții:</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="158"/>
<source>F1 to show this help page</source>
<translation>F1 pentru a reveni aici</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="160"/>
<source>F4 to open a Terminal whitin the selected directory at Files tab</source>
<translation>F4 pentru a deschide un terminal în directorul selectat în fila Fișiere</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="162"/>
<source>F6 to open a File Manager whitin the selected directory at Files tab</source>
<translation>F6 pentru a deschide administratorul de fișiere în directorul selectat în fila Fișiere</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="164"/>
<source>F10 to maximize/demaximize package list view</source>
<translation>F10 pentru a maximiza/demaximiza afișajul listei de pachete</translation>
</message>
<message>
<location filename="Projects/octopi/src/mainwindow_help.cpp" line="166"/>
<source>F12 to maximize/demaximize Tab's view</source>
<translation>F12 pentru a maximiza/demaximiza afișajul filelor</translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="41"/>
<source>Octopi usage help:</source>
<translation>Ajutor de utilizare Octopi:</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="42"/>
<source>show application version.</source>
<translation>arată versiunea aplicației.</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="43"/>
<source>use a different Qt4 style (ex: -style gtk).</source>
<translation>folosește un stil Qt4 diferit (ex.: -style gtk).</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="44"/>
<source>use a different remove command (ex: -removecmd R).</source>
<translation>folosește o comandă disferită de ștergere (ex.: -removecmd R).</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="45"/>
<source>force a system upgrade at startup.</source>
<translation>forțează o actualizare de sistem la pornire.</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="51"/>
<source>All</source>
<translation>Toate</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="116"/>
<source>Antergos news</source>
<translation>Știri Antergos</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="120"/>
<source>ArchBSD news</source>
<translation>Știri ArchBSD</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="124"/>
<source>Arch Linux news</source>
<translation>Știri Arch Linux</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="128"/>
<source>Chakra news</source>
<translation>Știri Chakra</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="132"/>
<source>KaOS news</source>
<translation>Știri KaOS</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="136"/>
<source>Manjaro Linux news</source>
<translation>Știri Manjaro Linux</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="140"/>
<source>Netrunner Rolling news</source>
<translation>Știri Netrunner Rolling</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="144"/>
<source>No news could be found! Press Ctrl+G to download the latest news.</source>
<translation>Nu s-au găsit știri! Apăsați Ctrl+G pentru a descărca ultimele știri.</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="148"/>
<source>This Linux distro seems to be incompatible with Octopi!</source>
<translation>Această distribuție Linux pare incompatibilă cu Octopi!</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="152"/>
<source>Internet seems unavailable!</source>
<translation>Internetul pare nedisponibil!</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="156"/>
<source>Display all groups</source>
<translation>Arată toate grupele</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="167"/>
<source>Usage</source>
<translation>Folosință</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="171"/>
<source>About</source>
<translation>Despre</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="175"/>
<source>Name</source>
<translation>Nume</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="179"/>
<source>Version</source>
<translation>Versiune</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="183"/>
<source>Outdated version</source>
<translation>Versiune învechită</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="187"/>
<source>Available version</source>
<translation>Versiune disponibilă</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="191"/>
<source>No description available.</source>
<translation>Nu există descriere.</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="195"/>
<source>URL</source>
<translation>URL</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="199"/>
<source>Repository</source>
<translation>Depozit</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="203"/>
<source>Licenses</source>
<translation>Licențe</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="207"/>
<source>Group</source>
<translation>Grup</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="211"/>
<source>Groups</source>
<translation>Grupe</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="215"/>
<source>Provides</source>
<translation>Furnizează</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="219"/>
<source>Depends On</source>
<translation>Depinde de</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="223"/>
<source>Required By</source>
<translation>Cerut de</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="227"/>
<source>Optional For</source>
<translation>Opțional pentru</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="231"/>
<source>Optional Deps</source>
<translation>Dependențe opționale</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="235"/>
<source>Conflicts With</source>
<translation>În conflict cu</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="239"/>
<source>Replaces</source>
<translation>Înlocuiește</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="243"/>
<source>Popularity</source>
<translation>Popularitate</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="247"/>
<source>votes</source>
<translation>voturi</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="251"/>
<source>Download Size</source>
<translation>Mărime descărcare</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="255"/>
<source>Installed Size</source>
<translation>Mărime instalată</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="259"/>
<source>Packager</source>
<translation>Împachetator</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="263"/>
<source>Package</source>
<translation>Pachet</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="267"/>
<source>Packages</source>
<translation>Pachete</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="271"/>
<source>Architecture</source>
<translation>Arhitectură</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="275"/>
<source>Build Date</source>
<translation>Data construirii</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="279"/>
<source>Description</source>
<translation>Descriere</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="283"/>
<source>Attention</source>
<translation>Atenție</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="287"/>
<source>automatic</source>
<translation>automat</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="291"/>
<source>Password</source>
<translation>Parolă</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="295"/>
<source>Info</source>
<translation>Info</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="299"/>
<source>Files</source>
<translation>Fișiere</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="303"/>
<source>Transaction</source>
<translation>Tranzacție</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="307"/>
<source>Output</source>
<translation>Rezultat</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="311"/>
<source>News</source>
<translation>Știri</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="315"/>
<source>Contents of "%1"</source>
<translation>Conținutul lui „%1”</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="319"/>
<source>Find</source>
<translation>Găsește</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="323"/>
<source>Clear</source>
<translation>Golește</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="327"/>
<source> (outdated installed version is %1)</source>
<translation>(versiunea învechită instalată este %1)</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="331"/>
<source> (newer installed version is %1)</source>
<translation>(versiunea mai nouă instalată este %1)</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="335"/>
<source>Building package list...</source>
<translation>Se generează lista de pachete...</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="339"/>
<source>Searching for %1 latest news...</source>
<translation>Se caută ultimele %1 știri...</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="343"/>
<source>There is one outdated package in your system:</source>
<translation>Există un pachet învechit în sistemul vostru:</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="347"/>
<source>There are %1 outdated packages in your system:</source>
<translation>Există %1 pachete învechite în sistemul vostru:</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="351"/>
<source>(version %1 is available)</source>
<translation>(versiunea %1 este disponibilă)</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="355"/>
<source>%1 (%2) packages</source>
<translation>%1 (%2) pachete</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="359"/>
<source>%1 installed</source>
<translation>%1 instalat</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="363"/>
<source>%1 outdated</source>
<translation>%1 învechit</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="367"/>
<source>%1 available</source>
<translation>%1 disponibil</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="371"/>
<source>Cleaning package cache...</source>
<translation>Se curăță cache-ul pachetelor...</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="375"/>
<source>Removing Pacman's transaction lock file...</source>
<translation>Se elimină fișierul de blocare a tranzacției Pacman...</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="379"/>
<source>Syncing</source>
<translation>Se sincronizează</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="383"/>
<source>Press any key to continue...</source>
<translation>Apăsați orice tastă pentru a continua...</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="391"/>
<source>Synchronizing databases...</source>
<translation>Se sincronizează bazele de date...</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="395"/>
<source>is up to date</source>
<translation>este actualizat</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="399"/>
<source>Starting full system upgrade...</source>
<translation>Începe actualizarea sistemului...</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="403"/>
<source>Installing selected packages...</source>
<translation>Se instalează pachetele selectate...</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="407"/>
<source>Removing selected packages...</source>
<translation>Se șterg pachetele selectate...</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="411"/>
<source>Removing/installing selected packages...</source>
<translation>Se șterg/se instalează pachetele selectate...</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="415"/>
<source>Running command in terminal...</source>
<translation>Se rulează comanda în teminal...</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="419"/>
<source>Command finished OK!</source>
<translation>Comanda s-a terminat bine!</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="423"/>
<source>Command finished with errors!</source>
<translation>Comanda s-a terminat cu erori!</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="427"/>
<source>Retrieving %1</source>
<translation>Se preia %1</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="431"/>
<source>Total download size: %1 KB</source>
<translation>Mărime totală a descărcării: %1 KB</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="435"/>
<source>The following target needs to be retrieved</source>
<translation>Următoarea țintă trebuie să fie preluată</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="439"/>
<source>The following target will be removed</source>
<translation>Următoarea țintă va fi ștearsă</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="443"/>
<source>The following %1 targets need to be retrieved</source>
<translation>Următoarele %1 ținte trebuie să fie preluate</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="447"/>
<source>The following %1 targets will be removed</source>
<translation>Următoarele %1 ținte vor fi șterse</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="451"/>
<source>There are forbidden packages in the removal list!</source>
<translation>Există pachete interzise în lista de ștergere!</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="455"/>
<source>There are no new updates available!</source>
<translation>Nu există actualizări disponibile!</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="459"/>
<source>There is an update available!</source>
<translation>Există o actualizare disponibilă!</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="463"/>
<source>There are %1 updates available!</source>
<translation>Există %1 actualizări disponibile!</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="467"/>
<source>Confirm?</source>
<translation>Confirmați?</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="471"/>
<source>Warning!!!</source>
<translation>Avertizare!!!</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="475"/>
<source>Confirmation</source>
<translation>Confirmare</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="479"/>
<source>There has been a transaction error!</source>
<translation>S-a produs o eroare de tranzacție!</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="483"/>
<source>Do you want to execute this transaction in a Terminal?</source>
<translation>Vreți să executați această tranzacție în terminal?</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="487"/>
<source>Do you really want to clean the package cache?</source>
<translation>Vreți să curățați cache-ul pachetelor?</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="491"/>
<source>Do you really want to remove Pacman's transaction lock file?</source>
<translation>Chiar vreți să eliminați fișierul de blocare a tranzacției Pacman?</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="495"/>
<source>Do you really want to rollback the transaction?</source>
<translation>Vreți să anulați tranzacția?</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="499"/>
<source>Please, enter the administrator's password</source>
<translation>Introduceți parola de administrator</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="505"/>
<source>There are no means to get administrator's credentials.</source>
<translation>Nu există mijloace pentru a obține certificarea de administrator.</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="509"/>
<source>You'll need to install a su frontend like gksu or kdesu.</source>
<translation>Va trebui să instalați o interfață su, precum gksu sau kdesu.</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="513"/>
<source>You can not run Octopi with administrator's credentials.</source>
<translation>Nu puteți rula Octopi cu certificare de administrator.</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="517"/>
<source>There is a pending transaction</source>
<translation>Există o tranzacție în așteptare</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="521"/>
<source>Do you really want to quit?</source>
<translation>Vreți să ieșiți?</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="525"/>
<source>Executing command</source>
<translation>Se execută comanda</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="529"/>
<source>Run in terminal</source>
<translation>Rulează în terminal</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="533"/>
<source>Needs application restart to take effect</source>
<translation>E nevoie de repornirea aplicației pentru a avea efect</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="537"/>
<source>These changes need application restart to take effect!</source>
<translation>Aceste schimbări au nevoie de repornirea aplicației pentru a avea efect!</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="541"/>
<source>Select the packages you want to install</source>
<translation>Selectați pachetele pe care le vreți instalate</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="545"/>
<source>This file does not appear to be a simple text.
Are you sure you want to open it?</source>
<translation>Acest fișier nu pare a fi un simplu text.
Sunteți sigur că vreți să-l deschideți?</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="550"/>
<source>To be installed</source>
<translation>De instalat</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="554"/>
<source>To be removed</source>
<translation>De șters</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="558"/>
<source>remove</source>
<translation>șterge</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="562"/>
<source>install</source>
<translation>instalează</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="566"/>
<source>Remove item</source>
<translation>Șterge elementul</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="570"/>
<source>Remove items</source>
<translation>Șterge elementele</translation>
</message>
<message>
<location filename="Projects/octopi/src/strconstants.h" line="574"/>
<source>Press Ctrl+A to select/deselect all</source>
<translation>Apăsați Ctrl+A pentru a (de)selecta toate</translation>
</message>
</context>
<context>
<name>SearchBar</name>
<message>
<location filename="Projects/octopi/src/searchbar.cpp" line="63"/>
<source>Previous</source>
<translation>Înapoi</translation>
</message>
<message>
<location filename="Projects/octopi/src/searchbar.cpp" line="67"/>
<source>Next</source>
<translation>Înainte</translation>
</message>
<message>
<location filename="Projects/octopi/src/searchbar.cpp" line="79"/>
<source>Close</source>
<translation>Închide</translation>
</message>
</context>
<context>
<name>TransactionDialog</name>
<message>
<location filename="Projects/octopi/ui/transactiondialog.ui" line="20"/>
<source>Form</source>
<translation>Formular</translation>
</message>
<message>
<location filename="Projects/octopi/ui/transactiondialog.ui" line="133"/>
<source>Run in terminal</source>
<translation>Rulează în terminal</translation>
</message>
</context>
</TS>
|
msys2/octopi
|
resources/translations/octopi_ro.ts
|
TypeScript
|
gpl-2.0
| 47,932
|
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/spinlock.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <linux/gpio.h>
#include <linux/idr.h>
#include <linux/slab.h>
/* Optional implementation infrastructure for GPIO interfaces.
*
* Platforms may want to use this if they tend to use very many GPIOs
* that aren't part of a System-On-Chip core; or across I2C/SPI/etc.
*
* When kernel footprint or instruction count is an issue, simpler
* implementations may be preferred. The GPIO programming interface
* allows for inlining speed-critical get/set operations for common
* cases, so that access to SOC-integrated GPIOs can sometimes cost
* only an instruction or two per bit.
*/
/* When debugging, extend minimal trust to callers and platform code.
* Also emit diagnostic messages that may help initial bringup, when
* board setup or driver bugs are most common.
*
* Otherwise, minimize overhead in what may be bitbanging codepaths.
*/
#ifdef DEBUG
#define extra_checks 1
#else
#define extra_checks 0
#endif
/* gpio_lock prevents conflicts during gpio_desc[] table updates.
* While any GPIO is requested, its gpio_chip is not removable;
* each GPIO's "requested" flag serves as a lock and refcount.
*/
static DEFINE_SPINLOCK(gpio_lock);
struct gpio_desc {
struct gpio_chip *chip;
unsigned long flags;
/* flag symbols are bit numbers */
#define FLAG_REQUESTED 0
#define FLAG_IS_OUT 1
#define FLAG_RESERVED 2
#define FLAG_EXPORT 3 /* protected by sysfs_lock */
#define FLAG_SYSFS 4 /* exported via /sys/class/gpio/control */
#define FLAG_TRIG_FALL 5 /* trigger on falling edge */
#define FLAG_TRIG_RISE 6 /* trigger on rising edge */
#define FLAG_ACTIVE_LOW 7 /* sysfs value has active low */
#define PDESC_ID_SHIFT 16 /* add new flags before this one */
#define GPIO_FLAGS_MASK ((1 << PDESC_ID_SHIFT) - 1)
#define GPIO_TRIGGER_MASK (BIT(FLAG_TRIG_FALL) | BIT(FLAG_TRIG_RISE))
#ifdef CONFIG_DEBUG_FS
const char *label;
#endif
};
static struct gpio_desc gpio_desc[ARCH_NR_GPIOS];
#ifdef CONFIG_GPIO_SYSFS
struct poll_desc {
struct work_struct work;
struct sysfs_dirent *value_sd;
};
static struct idr pdesc_idr;
#endif
static inline void desc_set_label(struct gpio_desc *d, const char *label)
{
#ifdef CONFIG_DEBUG_FS
d->label = label;
#endif
}
/* Warn when drivers omit gpio_request() calls -- legal but ill-advised
* when setting direction, and otherwise illegal. Until board setup code
* and drivers use explicit requests everywhere (which won't happen when
* those calls have no teeth) we can't avoid autorequesting. This nag
* message should motivate switching to explicit requests... so should
* the weaker cleanup after faults, compared to gpio_request().
*
* NOTE: the autorequest mechanism is going away; at this point it's
* only "legal" in the sense that (old) code using it won't break yet,
* but instead only triggers a WARN() stack dump.
*/
static int gpio_ensure_requested(struct gpio_desc *desc, unsigned offset)
{
const struct gpio_chip *chip = desc->chip;
const int gpio = chip->base + offset;
if (WARN(test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0,
"autorequest GPIO-%d\n", gpio)) {
if (!try_module_get(chip->owner)) {
pr_err("GPIO-%d: module can't be gotten \n", gpio);
clear_bit(FLAG_REQUESTED, &desc->flags);
/* lose */
return -EIO;
}
desc_set_label(desc, "[auto]");
/* caller must chip->request() w/o spinlock */
if (chip->request)
return 1;
}
return 0;
}
/* caller holds gpio_lock *OR* gpio is marked as requested */
static inline struct gpio_chip *gpio_to_chip(unsigned gpio)
{
return gpio_desc[gpio].chip;
}
/* dynamic allocation of GPIOs, e.g. on a hotplugged device */
static int gpiochip_find_base(int ngpio)
{
int i;
int spare = 0;
int base = -ENOSPC;
for (i = ARCH_NR_GPIOS - 1; i >= 0 ; i--) {
struct gpio_desc *desc = &gpio_desc[i];
struct gpio_chip *chip = desc->chip;
if (!chip && !test_bit(FLAG_RESERVED, &desc->flags)) {
spare++;
if (spare == ngpio) {
base = i;
break;
}
} else {
spare = 0;
if (chip)
i -= chip->ngpio - 1;
}
}
if (gpio_is_valid(base))
pr_debug("%s: found new base at %d\n", __func__, base);
return base;
}
/**
* gpiochip_reserve() - reserve range of gpios to use with platform code only
* @start: starting gpio number
* @ngpio: number of gpios to reserve
* Context: platform init, potentially before irqs or kmalloc will work
*
* Returns a negative errno if any gpio within the range is already reserved
* or registered, else returns zero as a success code. Use this function
* to mark a range of gpios as unavailable for dynamic gpio number allocation,
* for example because its driver support is not yet loaded.
*/
int __init gpiochip_reserve(int start, int ngpio)
{
int ret = 0;
unsigned long flags;
int i;
if (!gpio_is_valid(start) || !gpio_is_valid(start + ngpio - 1))
return -EINVAL;
spin_lock_irqsave(&gpio_lock, flags);
for (i = start; i < start + ngpio; i++) {
struct gpio_desc *desc = &gpio_desc[i];
if (desc->chip || test_bit(FLAG_RESERVED, &desc->flags)) {
ret = -EBUSY;
goto err;
}
set_bit(FLAG_RESERVED, &desc->flags);
}
pr_debug("%s: reserved gpios from %d to %d\n",
__func__, start, start + ngpio - 1);
err:
spin_unlock_irqrestore(&gpio_lock, flags);
return ret;
}
#ifdef CONFIG_GPIO_SYSFS
/* lock protects against unexport_gpio() being called while
* sysfs files are active.
*/
static DEFINE_MUTEX(sysfs_lock);
/*
* /sys/class/gpio/gpioN... only for GPIOs that are exported
* /direction
* * MAY BE OMITTED if kernel won't allow direction changes
* * is read/write as "in" or "out"
* * may also be written as "high" or "low", initializing
* output value as specified ("out" implies "low")
* /value
* * always readable, subject to hardware behavior
* * may be writable, as zero/nonzero
* /edge
* * configures behavior of poll(2) on /value
* * available only if pin can generate IRQs on input
* * is read/write as "none", "falling", "rising", or "both"
* /active_low
* * configures polarity of /value
* * is read/write as zero/nonzero
* * also affects existing and subsequent "falling" and "rising"
* /edge configuration
*/
static ssize_t gpio_direction_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
const struct gpio_desc *desc = dev_get_drvdata(dev);
ssize_t status;
mutex_lock(&sysfs_lock);
if (!test_bit(FLAG_EXPORT, &desc->flags))
status = -EIO;
else
status = sprintf(buf, "%s\n",
test_bit(FLAG_IS_OUT, &desc->flags)
? "out" : "in");
mutex_unlock(&sysfs_lock);
return status;
}
static ssize_t gpio_direction_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
const struct gpio_desc *desc = dev_get_drvdata(dev);
unsigned gpio = desc - gpio_desc;
ssize_t status;
mutex_lock(&sysfs_lock);
if (!test_bit(FLAG_EXPORT, &desc->flags))
status = -EIO;
else if (sysfs_streq(buf, "high"))
status = gpio_direction_output(gpio, 1);
else if (sysfs_streq(buf, "out") || sysfs_streq(buf, "low"))
status = gpio_direction_output(gpio, 0);
else if (sysfs_streq(buf, "in"))
status = gpio_direction_input(gpio);
else
status = -EINVAL;
mutex_unlock(&sysfs_lock);
return status ? : size;
}
static /* const */ DEVICE_ATTR(direction, 0644,
gpio_direction_show, gpio_direction_store);
static ssize_t gpio_value_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
const struct gpio_desc *desc = dev_get_drvdata(dev);
unsigned gpio = desc - gpio_desc;
ssize_t status;
mutex_lock(&sysfs_lock);
if (!test_bit(FLAG_EXPORT, &desc->flags)) {
status = -EIO;
} else {
int value;
value = !!gpio_get_value_cansleep(gpio);
if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
value = !value;
status = sprintf(buf, "%d\n", value);
}
mutex_unlock(&sysfs_lock);
return status;
}
static ssize_t gpio_value_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
const struct gpio_desc *desc = dev_get_drvdata(dev);
unsigned gpio = desc - gpio_desc;
ssize_t status;
mutex_lock(&sysfs_lock);
if (!test_bit(FLAG_EXPORT, &desc->flags))
status = -EIO;
else if (!test_bit(FLAG_IS_OUT, &desc->flags))
status = -EPERM;
else {
long value;
status = strict_strtol(buf, 0, &value);
if (status == 0) {
if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
value = !value;
gpio_set_value_cansleep(gpio, value != 0);
status = size;
}
}
mutex_unlock(&sysfs_lock);
return status;
}
static const DEVICE_ATTR(value, 0644,
gpio_value_show, gpio_value_store);
static irqreturn_t gpio_sysfs_irq(int irq, void *priv)
{
struct work_struct *work = priv;
schedule_work(work);
return IRQ_HANDLED;
}
static void gpio_notify_sysfs(struct work_struct *work)
{
struct poll_desc *pdesc;
pdesc = container_of(work, struct poll_desc, work);
sysfs_notify_dirent(pdesc->value_sd);
}
static int gpio_setup_irq(struct gpio_desc *desc, struct device *dev,
unsigned long gpio_flags)
{
struct poll_desc *pdesc;
unsigned long irq_flags;
int ret, irq, id;
if ((desc->flags & GPIO_TRIGGER_MASK) == gpio_flags)
return 0;
irq = gpio_to_irq(desc - gpio_desc);
if (irq < 0)
return -EIO;
id = desc->flags >> PDESC_ID_SHIFT;
pdesc = idr_find(&pdesc_idr, id);
if (pdesc) {
free_irq(irq, &pdesc->work);
cancel_work_sync(&pdesc->work);
}
desc->flags &= ~GPIO_TRIGGER_MASK;
if (!gpio_flags) {
ret = 0;
goto free_sd;
}
irq_flags = IRQF_SHARED;
if (test_bit(FLAG_TRIG_FALL, &gpio_flags))
irq_flags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
if (test_bit(FLAG_TRIG_RISE, &gpio_flags))
irq_flags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
if (!pdesc) {
pdesc = kmalloc(sizeof(*pdesc), GFP_KERNEL);
if (!pdesc) {
ret = -ENOMEM;
goto err_out;
}
do {
ret = -ENOMEM;
if (idr_pre_get(&pdesc_idr, GFP_KERNEL))
ret = idr_get_new_above(&pdesc_idr,
pdesc, 1, &id);
} while (ret == -EAGAIN);
if (ret)
goto free_mem;
desc->flags &= GPIO_FLAGS_MASK;
desc->flags |= (unsigned long)id << PDESC_ID_SHIFT;
if (desc->flags >> PDESC_ID_SHIFT != id) {
ret = -ERANGE;
goto free_id;
}
pdesc->value_sd = sysfs_get_dirent(dev->kobj.sd, NULL, "value");
if (!pdesc->value_sd) {
ret = -ENODEV;
goto free_id;
}
INIT_WORK(&pdesc->work, gpio_notify_sysfs);
}
ret = request_irq(irq, gpio_sysfs_irq, irq_flags,
"gpiolib", &pdesc->work);
if (ret)
goto free_sd;
desc->flags |= gpio_flags;
return 0;
free_sd:
if (pdesc)
sysfs_put(pdesc->value_sd);
free_id:
idr_remove(&pdesc_idr, id);
desc->flags &= GPIO_FLAGS_MASK;
free_mem:
kfree(pdesc);
err_out:
return ret;
}
static const struct {
const char *name;
unsigned long flags;
} trigger_types[] = {
{ "none", 0 },
{ "falling", BIT(FLAG_TRIG_FALL) },
{ "rising", BIT(FLAG_TRIG_RISE) },
{ "both", BIT(FLAG_TRIG_FALL) | BIT(FLAG_TRIG_RISE) },
};
static ssize_t gpio_edge_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
const struct gpio_desc *desc = dev_get_drvdata(dev);
ssize_t status;
mutex_lock(&sysfs_lock);
if (!test_bit(FLAG_EXPORT, &desc->flags))
status = -EIO;
else {
int i;
status = 0;
for (i = 0; i < ARRAY_SIZE(trigger_types); i++)
if ((desc->flags & GPIO_TRIGGER_MASK)
== trigger_types[i].flags) {
status = sprintf(buf, "%s\n",
trigger_types[i].name);
break;
}
}
mutex_unlock(&sysfs_lock);
return status;
}
static ssize_t gpio_edge_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct gpio_desc *desc = dev_get_drvdata(dev);
ssize_t status;
int i;
for (i = 0; i < ARRAY_SIZE(trigger_types); i++)
if (sysfs_streq(trigger_types[i].name, buf))
goto found;
return -EINVAL;
found:
mutex_lock(&sysfs_lock);
if (!test_bit(FLAG_EXPORT, &desc->flags))
status = -EIO;
else {
status = gpio_setup_irq(desc, dev, trigger_types[i].flags);
if (!status)
status = size;
}
mutex_unlock(&sysfs_lock);
return status;
}
static DEVICE_ATTR(edge, 0644, gpio_edge_show, gpio_edge_store);
static int sysfs_set_active_low(struct gpio_desc *desc, struct device *dev,
int value)
{
int status = 0;
if (!!test_bit(FLAG_ACTIVE_LOW, &desc->flags) == !!value)
return 0;
if (value)
set_bit(FLAG_ACTIVE_LOW, &desc->flags);
else
clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
/* reconfigure poll(2) support if enabled on one edge only */
if (dev != NULL && (!!test_bit(FLAG_TRIG_RISE, &desc->flags) ^
!!test_bit(FLAG_TRIG_FALL, &desc->flags))) {
unsigned long trigger_flags = desc->flags & GPIO_TRIGGER_MASK;
gpio_setup_irq(desc, dev, 0);
status = gpio_setup_irq(desc, dev, trigger_flags);
}
return status;
}
static ssize_t gpio_active_low_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
const struct gpio_desc *desc = dev_get_drvdata(dev);
ssize_t status;
mutex_lock(&sysfs_lock);
if (!test_bit(FLAG_EXPORT, &desc->flags))
status = -EIO;
else
status = sprintf(buf, "%d\n",
!!test_bit(FLAG_ACTIVE_LOW, &desc->flags));
mutex_unlock(&sysfs_lock);
return status;
}
static ssize_t gpio_active_low_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct gpio_desc *desc = dev_get_drvdata(dev);
ssize_t status;
mutex_lock(&sysfs_lock);
if (!test_bit(FLAG_EXPORT, &desc->flags)) {
status = -EIO;
} else {
long value;
status = strict_strtol(buf, 0, &value);
if (status == 0)
status = sysfs_set_active_low(desc, dev, value != 0);
}
mutex_unlock(&sysfs_lock);
return status ? : size;
}
static const DEVICE_ATTR(active_low, 0644,
gpio_active_low_show, gpio_active_low_store);
static ssize_t gpio_irq_wake_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
const struct gpio_desc *desc = dev_get_drvdata(dev);
unsigned gpio = desc - gpio_desc;
ssize_t status;
mutex_lock(&sysfs_lock);
if (!test_bit(FLAG_EXPORT, &desc->flags))
status = -EIO;
else if (sysfs_streq(buf, "enable") || sysfs_streq(buf, "1"))
status = enable_irq_wake(gpio_to_irq(gpio));
else if (sysfs_streq(buf, "disable") || sysfs_streq(buf, "0"))
status = disable_irq_wake(gpio_to_irq(gpio));
else
status = -EINVAL;
mutex_unlock(&sysfs_lock);
return status ? : size;
}
static ssize_t gpio_irq_wake_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
const struct gpio_desc *desc = dev_get_drvdata(dev);
unsigned gpio = desc - gpio_desc;
int irq = gpio_to_irq(gpio);
struct irq_desc *idesc = irq_to_desc(irq);
ssize_t status;
mutex_lock(&sysfs_lock);
status = sprintf(buf, " Wakeup %s\n",
(idesc->status & IRQ_WAKEUP)
? " enable" : "disable");
mutex_unlock(&sysfs_lock);
return status;
}
static const DEVICE_ATTR(irq_wake, 0644,
gpio_irq_wake_show, gpio_irq_wake_store);
static const struct attribute *gpio_attrs[] = {
&dev_attr_value.attr,
&dev_attr_active_low.attr,
NULL,
};
static const struct attribute_group gpio_attr_group = {
.attrs = (struct attribute **) gpio_attrs,
};
/*
* /sys/class/gpio/gpiochipN/
* /base ... matching gpio_chip.base (N)
* /label ... matching gpio_chip.label
* /ngpio ... matching gpio_chip.ngpio
*/
static ssize_t chip_base_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
const struct gpio_chip *chip = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", chip->base);
}
static DEVICE_ATTR(base, 0444, chip_base_show, NULL);
static ssize_t chip_label_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
const struct gpio_chip *chip = dev_get_drvdata(dev);
return sprintf(buf, "%s\n", chip->label ? : "");
}
static DEVICE_ATTR(label, 0444, chip_label_show, NULL);
static ssize_t chip_ngpio_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
const struct gpio_chip *chip = dev_get_drvdata(dev);
return sprintf(buf, "%u\n", chip->ngpio);
}
static DEVICE_ATTR(ngpio, 0444, chip_ngpio_show, NULL);
static const struct attribute *gpiochip_attrs[] = {
&dev_attr_base.attr,
&dev_attr_label.attr,
&dev_attr_ngpio.attr,
NULL,
};
static const struct attribute_group gpiochip_attr_group = {
.attrs = (struct attribute **) gpiochip_attrs,
};
/*
* /sys/class/gpio/export ... write-only
* integer N ... number of GPIO to export (full access)
* /sys/class/gpio/unexport ... write-only
* integer N ... number of GPIO to unexport
*/
static ssize_t export_store(struct class *class,
struct class_attribute *attr,
const char *buf, size_t len)
{
long gpio;
int status;
status = strict_strtol(buf, 0, &gpio);
if (status < 0)
goto done;
/* No extra locking here; FLAG_SYSFS just signifies that the
* request and export were done by on behalf of userspace, so
* they may be undone on its behalf too.
*/
status = gpio_request(gpio, "sysfs");
if (status < 0)
goto done;
status = gpio_export(gpio, true);
if (status < 0)
gpio_free(gpio);
else
set_bit(FLAG_SYSFS, &gpio_desc[gpio].flags);
done:
if (status)
pr_debug("%s: status %d\n", __func__, status);
return status ? : len;
}
static ssize_t unexport_store(struct class *class,
struct class_attribute *attr,
const char *buf, size_t len)
{
long gpio;
int status;
status = strict_strtol(buf, 0, &gpio);
if (status < 0)
goto done;
status = -EINVAL;
/* reject bogus commands (gpio_unexport ignores them) */
if (!gpio_is_valid(gpio))
goto done;
/* No extra locking here; FLAG_SYSFS just signifies that the
* request and export were done by on behalf of userspace, so
* they may be undone on its behalf too.
*/
if (test_and_clear_bit(FLAG_SYSFS, &gpio_desc[gpio].flags)) {
status = 0;
gpio_free(gpio);
}
done:
if (status)
pr_debug("%s: status %d\n", __func__, status);
return status ? : len;
}
static struct class_attribute gpio_class_attrs[] = {
__ATTR(export, 0200, NULL, export_store),
__ATTR(unexport, 0200, NULL, unexport_store),
__ATTR_NULL,
};
static struct class gpio_class = {
.name = "gpio",
.owner = THIS_MODULE,
.class_attrs = gpio_class_attrs,
};
/**
* gpio_export - export a GPIO through sysfs
* @gpio: gpio to make available, already requested
* @direction_may_change: true if userspace may change gpio direction
* Context: arch_initcall or later
*
* When drivers want to make a GPIO accessible to userspace after they
* have requested it -- perhaps while debugging, or as part of their
* public interface -- they may use this routine. If the GPIO can
* change direction (some can't) and the caller allows it, userspace
* will see "direction" sysfs attribute which may be used to change
* the gpio's direction. A "value" attribute will always be provided.
*
* Returns zero on success, else an error.
*/
int gpio_export(unsigned gpio, bool direction_may_change)
{
unsigned long flags;
struct gpio_desc *desc;
int status = -EINVAL;
const char *ioname = NULL;
/* can't export until sysfs is available ... */
if (!gpio_class.p) {
pr_debug("%s: called too early!\n", __func__);
return -ENOENT;
}
if (!gpio_is_valid(gpio))
goto done;
mutex_lock(&sysfs_lock);
spin_lock_irqsave(&gpio_lock, flags);
desc = &gpio_desc[gpio];
if (test_bit(FLAG_REQUESTED, &desc->flags)
&& !test_bit(FLAG_EXPORT, &desc->flags)) {
status = 0;
if (!desc->chip->direction_input
|| !desc->chip->direction_output)
direction_may_change = false;
}
spin_unlock_irqrestore(&gpio_lock, flags);
if (desc->chip->names && desc->chip->names[gpio - desc->chip->base])
ioname = desc->chip->names[gpio - desc->chip->base];
if (status == 0) {
struct device *dev;
dev = device_create(&gpio_class, desc->chip->dev, MKDEV(0, 0),
desc, ioname ? ioname : "gpio%u", gpio);
if (!IS_ERR(dev)) {
status = sysfs_create_group(&dev->kobj,
&gpio_attr_group);
if (!status && direction_may_change)
status = device_create_file(dev,
&dev_attr_direction);
if (!status && gpio_to_irq(gpio) >= 0
&& (direction_may_change
|| !test_bit(FLAG_IS_OUT,
&desc->flags))) {
status = device_create_file(dev,
&dev_attr_edge);
if (!status)
status = device_create_file(dev,
&dev_attr_irq_wake);
}
if (status != 0)
device_unregister(dev);
} else
status = PTR_ERR(dev);
if (status == 0)
set_bit(FLAG_EXPORT, &desc->flags);
}
mutex_unlock(&sysfs_lock);
done:
if (status)
pr_debug("%s: gpio%d status %d\n", __func__, gpio, status);
return status;
}
EXPORT_SYMBOL_GPL(gpio_export);
static int match_export(struct device *dev, void *data)
{
return dev_get_drvdata(dev) == data;
}
/**
* gpio_export_link - create a sysfs link to an exported GPIO node
* @dev: device under which to create symlink
* @name: name of the symlink
* @gpio: gpio to create symlink to, already exported
*
* Set up a symlink from /sys/.../dev/name to /sys/class/gpio/gpioN
* node. Caller is responsible for unlinking.
*
* Returns zero on success, else an error.
*/
int gpio_export_link(struct device *dev, const char *name, unsigned gpio)
{
struct gpio_desc *desc;
int status = -EINVAL;
if (!gpio_is_valid(gpio))
goto done;
mutex_lock(&sysfs_lock);
desc = &gpio_desc[gpio];
if (test_bit(FLAG_EXPORT, &desc->flags)) {
struct device *tdev;
tdev = class_find_device(&gpio_class, NULL, desc, match_export);
if (tdev != NULL) {
status = sysfs_create_link(&dev->kobj, &tdev->kobj,
name);
} else {
status = -ENODEV;
}
}
mutex_unlock(&sysfs_lock);
done:
if (status)
pr_debug("%s: gpio%d status %d\n", __func__, gpio, status);
return status;
}
EXPORT_SYMBOL_GPL(gpio_export_link);
/**
* gpio_sysfs_set_active_low - set the polarity of gpio sysfs value
* @gpio: gpio to change
* @value: non-zero to use active low, i.e. inverted values
*
* Set the polarity of /sys/class/gpio/gpioN/value sysfs attribute.
* The GPIO does not have to be exported yet. If poll(2) support has
* been enabled for either rising or falling edge, it will be
* reconfigured to follow the new polarity.
*
* Returns zero on success, else an error.
*/
int gpio_sysfs_set_active_low(unsigned gpio, int value)
{
struct gpio_desc *desc;
struct device *dev = NULL;
int status = -EINVAL;
if (!gpio_is_valid(gpio))
goto done;
mutex_lock(&sysfs_lock);
desc = &gpio_desc[gpio];
if (test_bit(FLAG_EXPORT, &desc->flags)) {
dev = class_find_device(&gpio_class, NULL, desc, match_export);
if (dev == NULL) {
status = -ENODEV;
goto unlock;
}
}
status = sysfs_set_active_low(desc, dev, value);
unlock:
mutex_unlock(&sysfs_lock);
done:
if (status)
pr_debug("%s: gpio%d status %d\n", __func__, gpio, status);
return status;
}
EXPORT_SYMBOL_GPL(gpio_sysfs_set_active_low);
/**
* gpio_unexport - reverse effect of gpio_export()
* @gpio: gpio to make unavailable
*
* This is implicit on gpio_free().
*/
void gpio_unexport(unsigned gpio)
{
struct gpio_desc *desc;
int status = 0;
if (!gpio_is_valid(gpio)) {
status = -EINVAL;
goto done;
}
mutex_lock(&sysfs_lock);
desc = &gpio_desc[gpio];
if (test_bit(FLAG_EXPORT, &desc->flags)) {
struct device *dev = NULL;
dev = class_find_device(&gpio_class, NULL, desc, match_export);
if (dev) {
gpio_setup_irq(desc, dev, 0);
clear_bit(FLAG_EXPORT, &desc->flags);
put_device(dev);
device_unregister(dev);
} else
status = -ENODEV;
}
mutex_unlock(&sysfs_lock);
done:
if (status)
pr_debug("%s: gpio%d status %d\n", __func__, gpio, status);
}
EXPORT_SYMBOL_GPL(gpio_unexport);
static int gpiochip_export(struct gpio_chip *chip)
{
int status;
struct device *dev;
/* Many systems register gpio chips for SOC support very early,
* before driver model support is available. In those cases we
* export this later, in gpiolib_sysfs_init() ... here we just
* verify that _some_ field of gpio_class got initialized.
*/
if (!gpio_class.p)
return 0;
/* use chip->base for the ID; it's already known to be unique */
mutex_lock(&sysfs_lock);
dev = device_create(&gpio_class, chip->dev, MKDEV(0, 0), chip,
"gpiochip%d", chip->base);
if (!IS_ERR(dev)) {
status = sysfs_create_group(&dev->kobj,
&gpiochip_attr_group);
} else
status = PTR_ERR(dev);
chip->exported = (status == 0);
mutex_unlock(&sysfs_lock);
if (status) {
unsigned long flags;
unsigned gpio;
spin_lock_irqsave(&gpio_lock, flags);
gpio = chip->base;
while (gpio_desc[gpio].chip == chip)
gpio_desc[gpio++].chip = NULL;
spin_unlock_irqrestore(&gpio_lock, flags);
pr_debug("%s: chip %s status %d\n", __func__,
chip->label, status);
}
return status;
}
static void gpiochip_unexport(struct gpio_chip *chip)
{
int status;
struct device *dev;
mutex_lock(&sysfs_lock);
dev = class_find_device(&gpio_class, NULL, chip, match_export);
if (dev) {
put_device(dev);
device_unregister(dev);
chip->exported = 0;
status = 0;
} else
status = -ENODEV;
mutex_unlock(&sysfs_lock);
if (status)
pr_debug("%s: chip %s status %d\n", __func__,
chip->label, status);
}
static int __init gpiolib_sysfs_init(void)
{
int status;
unsigned long flags;
unsigned gpio;
idr_init(&pdesc_idr);
status = class_register(&gpio_class);
if (status < 0)
return status;
/* Scan and register the gpio_chips which registered very
* early (e.g. before the class_register above was called).
*
* We run before arch_initcall() so chip->dev nodes can have
* registered, and so arch_initcall() can always gpio_export().
*/
spin_lock_irqsave(&gpio_lock, flags);
for (gpio = 0; gpio < ARCH_NR_GPIOS; gpio++) {
struct gpio_chip *chip;
chip = gpio_desc[gpio].chip;
if (!chip || chip->exported)
continue;
spin_unlock_irqrestore(&gpio_lock, flags);
status = gpiochip_export(chip);
spin_lock_irqsave(&gpio_lock, flags);
}
spin_unlock_irqrestore(&gpio_lock, flags);
return status;
}
postcore_initcall(gpiolib_sysfs_init);
#else
static inline int gpiochip_export(struct gpio_chip *chip)
{
return 0;
}
static inline void gpiochip_unexport(struct gpio_chip *chip)
{
}
#endif /* CONFIG_GPIO_SYSFS */
/**
* gpiochip_add() - register a gpio_chip
* @chip: the chip to register, with chip->base initialized
* Context: potentially before irqs or kmalloc will work
*
* Returns a negative errno if the chip can't be registered, such as
* because the chip->base is invalid or already associated with a
* different chip. Otherwise it returns zero as a success code.
*
* When gpiochip_add() is called very early during boot, so that GPIOs
* can be freely used, the chip->dev device must be registered before
* the gpio framework's arch_initcall(). Otherwise sysfs initialization
* for GPIOs will fail rudely.
*
* If chip->base is negative, this requests dynamic assignment of
* a range of valid GPIOs.
*/
int gpiochip_add(struct gpio_chip *chip)
{
unsigned long flags;
int status = 0;
unsigned id;
int base = chip->base;
if ((!gpio_is_valid(base) || !gpio_is_valid(base + chip->ngpio - 1))
&& base >= 0) {
status = -EINVAL;
goto fail;
}
spin_lock_irqsave(&gpio_lock, flags);
if (base < 0) {
base = gpiochip_find_base(chip->ngpio);
if (base < 0) {
status = base;
goto unlock;
}
chip->base = base;
}
/* these GPIO numbers must not be managed by another gpio_chip */
for (id = base; id < base + chip->ngpio; id++) {
if (gpio_desc[id].chip != NULL) {
status = -EBUSY;
break;
}
}
if (status == 0) {
for (id = base; id < base + chip->ngpio; id++) {
gpio_desc[id].chip = chip;
/* REVISIT: most hardware initializes GPIOs as
* inputs (often with pullups enabled) so power
* usage is minimized. Linux code should set the
* gpio direction first thing; but until it does,
* we may expose the wrong direction in sysfs.
*/
gpio_desc[id].flags = !chip->direction_input
? (1 << FLAG_IS_OUT)
: 0;
}
}
unlock:
spin_unlock_irqrestore(&gpio_lock, flags);
if (status == 0)
status = gpiochip_export(chip);
fail:
/* failures here can mean systems won't boot... */
if (status)
pr_err("gpiochip_add: gpios %d..%d (%s) failed to register\n",
chip->base, chip->base + chip->ngpio - 1,
chip->label ? : "generic");
return status;
}
EXPORT_SYMBOL_GPL(gpiochip_add);
/**
* gpiochip_remove() - unregister a gpio_chip
* @chip: the chip to unregister
*
* A gpio_chip with any GPIOs still requested may not be removed.
*/
int gpiochip_remove(struct gpio_chip *chip)
{
unsigned long flags;
int status = 0;
unsigned id;
spin_lock_irqsave(&gpio_lock, flags);
for (id = chip->base; id < chip->base + chip->ngpio; id++) {
if (test_bit(FLAG_REQUESTED, &gpio_desc[id].flags)) {
status = -EBUSY;
break;
}
}
if (status == 0) {
for (id = chip->base; id < chip->base + chip->ngpio; id++)
gpio_desc[id].chip = NULL;
}
spin_unlock_irqrestore(&gpio_lock, flags);
if (status == 0)
gpiochip_unexport(chip);
return status;
}
EXPORT_SYMBOL_GPL(gpiochip_remove);
/* These "optional" allocation calls help prevent drivers from stomping
* on each other, and help provide better diagnostics in debugfs.
* They're called even less than the "set direction" calls.
*/
int gpio_request(unsigned gpio, const char *label)
{
struct gpio_desc *desc;
struct gpio_chip *chip;
int status = -EINVAL;
unsigned long flags;
spin_lock_irqsave(&gpio_lock, flags);
if (!gpio_is_valid(gpio))
goto done;
desc = &gpio_desc[gpio];
chip = desc->chip;
if (chip == NULL)
goto done;
if (!try_module_get(chip->owner))
goto done;
/* NOTE: gpio_request() can be called in early boot,
* before IRQs are enabled, for non-sleeping (SOC) GPIOs.
*/
if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
desc_set_label(desc, label ? : "?");
status = 0;
} else {
status = -EBUSY;
module_put(chip->owner);
goto done;
}
if (chip->request) {
/* chip->request may sleep */
spin_unlock_irqrestore(&gpio_lock, flags);
status = chip->request(chip, gpio - chip->base);
spin_lock_irqsave(&gpio_lock, flags);
if (status < 0) {
desc_set_label(desc, NULL);
module_put(chip->owner);
clear_bit(FLAG_REQUESTED, &desc->flags);
}
}
done:
if (status)
pr_debug("gpio_request: gpio-%d (%s) status %d\n",
gpio, label ? : "?", status);
spin_unlock_irqrestore(&gpio_lock, flags);
return status;
}
EXPORT_SYMBOL_GPL(gpio_request);
void gpio_free(unsigned gpio)
{
unsigned long flags;
struct gpio_desc *desc;
struct gpio_chip *chip;
might_sleep();
if (!gpio_is_valid(gpio)) {
WARN_ON(extra_checks);
return;
}
gpio_unexport(gpio);
spin_lock_irqsave(&gpio_lock, flags);
desc = &gpio_desc[gpio];
chip = desc->chip;
if (chip && test_bit(FLAG_REQUESTED, &desc->flags)) {
if (chip->free) {
spin_unlock_irqrestore(&gpio_lock, flags);
might_sleep_if(extra_checks && chip->can_sleep);
chip->free(chip, gpio - chip->base);
spin_lock_irqsave(&gpio_lock, flags);
}
desc_set_label(desc, NULL);
module_put(desc->chip->owner);
clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
clear_bit(FLAG_REQUESTED, &desc->flags);
} else
WARN_ON(extra_checks);
spin_unlock_irqrestore(&gpio_lock, flags);
}
EXPORT_SYMBOL_GPL(gpio_free);
/**
* gpio_request_one - request a single GPIO with initial configuration
* @gpio: the GPIO number
* @flags: GPIO configuration as specified by GPIOF_*
* @label: a literal description string of this GPIO
*/
int gpio_request_one(unsigned gpio, unsigned long flags, const char *label)
{
int err;
err = gpio_request(gpio, label);
if (err)
return err;
if (flags & GPIOF_DIR_IN)
err = gpio_direction_input(gpio);
else
err = gpio_direction_output(gpio,
(flags & GPIOF_INIT_HIGH) ? 1 : 0);
return err;
}
EXPORT_SYMBOL_GPL(gpio_request_one);
/**
* gpio_request_array - request multiple GPIOs in a single call
* @array: array of the 'struct gpio'
* @num: how many GPIOs in the array
*/
int gpio_request_array(struct gpio *array, size_t num)
{
int i, err;
for (i = 0; i < num; i++, array++) {
err = gpio_request_one(array->gpio, array->flags, array->label);
if (err)
goto err_free;
}
return 0;
err_free:
while (i--)
gpio_free((--array)->gpio);
return err;
}
EXPORT_SYMBOL_GPL(gpio_request_array);
/**
* gpio_free_array - release multiple GPIOs in a single call
* @array: array of the 'struct gpio'
* @num: how many GPIOs in the array
*/
void gpio_free_array(struct gpio *array, size_t num)
{
while (num--)
gpio_free((array++)->gpio);
}
EXPORT_SYMBOL_GPL(gpio_free_array);
/**
* gpiochip_is_requested - return string iff signal was requested
* @chip: controller managing the signal
* @offset: of signal within controller's 0..(ngpio - 1) range
*
* Returns NULL if the GPIO is not currently requested, else a string.
* If debugfs support is enabled, the string returned is the label passed
* to gpio_request(); otherwise it is a meaningless constant.
*
* This function is for use by GPIO controller drivers. The label can
* help with diagnostics, and knowing that the signal is used as a GPIO
* can help avoid accidentally multiplexing it to another controller.
*/
const char *gpiochip_is_requested(struct gpio_chip *chip, unsigned offset)
{
unsigned gpio = chip->base + offset;
if (!gpio_is_valid(gpio) || gpio_desc[gpio].chip != chip)
return NULL;
if (test_bit(FLAG_REQUESTED, &gpio_desc[gpio].flags) == 0)
return NULL;
#ifdef CONFIG_DEBUG_FS
return gpio_desc[gpio].label;
#else
return "?";
#endif
}
EXPORT_SYMBOL_GPL(gpiochip_is_requested);
/* Drivers MUST set GPIO direction before making get/set calls. In
* some cases this is done in early boot, before IRQs are enabled.
*
* As a rule these aren't called more than once (except for drivers
* using the open-drain emulation idiom) so these are natural places
* to accumulate extra debugging checks. Note that we can't (yet)
* rely on gpio_request() having been called beforehand.
*/
int gpio_direction_input(unsigned gpio)
{
unsigned long flags;
struct gpio_chip *chip;
struct gpio_desc *desc = &gpio_desc[gpio];
int status = -EINVAL;
spin_lock_irqsave(&gpio_lock, flags);
if (!gpio_is_valid(gpio))
goto fail;
chip = desc->chip;
if (!chip || !chip->get || !chip->direction_input)
goto fail;
gpio -= chip->base;
if (gpio >= chip->ngpio)
goto fail;
status = gpio_ensure_requested(desc, gpio);
if (status < 0)
goto fail;
/* now we know the gpio is valid and chip won't vanish */
spin_unlock_irqrestore(&gpio_lock, flags);
might_sleep_if(extra_checks && chip->can_sleep);
if (status) {
status = chip->request(chip, gpio);
if (status < 0) {
pr_debug("GPIO-%d: chip request fail, %d\n",
chip->base + gpio, status);
/* and it's not available to anyone else ...
* gpio_request() is the fully clean solution.
*/
goto lose;
}
}
status = chip->direction_input(chip, gpio);
if (status == 0)
clear_bit(FLAG_IS_OUT, &desc->flags);
lose:
return status;
fail:
spin_unlock_irqrestore(&gpio_lock, flags);
if (status)
pr_debug("%s: gpio-%d status %d\n",
__func__, gpio, status);
return status;
}
EXPORT_SYMBOL_GPL(gpio_direction_input);
int gpio_direction_output(unsigned gpio, int value)
{
unsigned long flags;
struct gpio_chip *chip;
struct gpio_desc *desc = &gpio_desc[gpio];
int status = -EINVAL;
spin_lock_irqsave(&gpio_lock, flags);
if (!gpio_is_valid(gpio))
goto fail;
chip = desc->chip;
if (!chip || !chip->set || !chip->direction_output)
goto fail;
gpio -= chip->base;
if (gpio >= chip->ngpio)
goto fail;
status = gpio_ensure_requested(desc, gpio);
if (status < 0)
goto fail;
/* now we know the gpio is valid and chip won't vanish */
spin_unlock_irqrestore(&gpio_lock, flags);
might_sleep_if(extra_checks && chip->can_sleep);
if (status) {
status = chip->request(chip, gpio);
if (status < 0) {
pr_debug("GPIO-%d: chip request fail, %d\n",
chip->base + gpio, status);
/* and it's not available to anyone else ...
* gpio_request() is the fully clean solution.
*/
goto lose;
}
}
status = chip->direction_output(chip, gpio, value);
if (status == 0)
set_bit(FLAG_IS_OUT, &desc->flags);
lose:
return status;
fail:
spin_unlock_irqrestore(&gpio_lock, flags);
if (status)
pr_debug("%s: gpio-%d status %d\n",
__func__, gpio, status);
return status;
}
EXPORT_SYMBOL_GPL(gpio_direction_output);
/**
* gpio_set_debounce - sets @debounce time for a @gpio
* @gpio: the gpio to set debounce time
* @debounce: debounce time is microseconds
*/
int gpio_set_debounce(unsigned gpio, unsigned debounce)
{
unsigned long flags;
struct gpio_chip *chip;
struct gpio_desc *desc = &gpio_desc[gpio];
int status = -EINVAL;
spin_lock_irqsave(&gpio_lock, flags);
if (!gpio_is_valid(gpio))
goto fail;
chip = desc->chip;
if (!chip || !chip->set || !chip->set_debounce)
goto fail;
gpio -= chip->base;
if (gpio >= chip->ngpio)
goto fail;
status = gpio_ensure_requested(desc, gpio);
if (status < 0)
goto fail;
/* now we know the gpio is valid and chip won't vanish */
spin_unlock_irqrestore(&gpio_lock, flags);
might_sleep_if(extra_checks && chip->can_sleep);
return chip->set_debounce(chip, gpio, debounce);
fail:
spin_unlock_irqrestore(&gpio_lock, flags);
if (status)
pr_debug("%s: gpio-%d status %d\n",
__func__, gpio, status);
return status;
}
EXPORT_SYMBOL_GPL(gpio_set_debounce);
/* I/O calls are only valid after configuration completed; the relevant
* "is this a valid GPIO" error checks should already have been done.
*
* "Get" operations are often inlinable as reading a pin value register,
* and masking the relevant bit in that register.
*
* When "set" operations are inlinable, they involve writing that mask to
* one register to set a low value, or a different register to set it high.
* Otherwise locking is needed, so there may be little value to inlining.
*
*------------------------------------------------------------------------
*
* IMPORTANT!!! The hot paths -- get/set value -- assume that callers
* have requested the GPIO. That can include implicit requesting by
* a direction setting call. Marking a gpio as requested locks its chip
* in memory, guaranteeing that these table lookups need no more locking
* and that gpiochip_remove() will fail.
*
* REVISIT when debugging, consider adding some instrumentation to ensure
* that the GPIO was actually requested.
*/
/**
* __gpio_get_value() - return a gpio's value
* @gpio: gpio whose value will be returned
* Context: any
*
* This is used directly or indirectly to implement gpio_get_value().
* It returns the zero or nonzero value provided by the associated
* gpio_chip.get() method; or zero if no such method is provided.
*/
int __gpio_get_value(unsigned gpio)
{
struct gpio_chip *chip;
chip = gpio_to_chip(gpio);
WARN_ON(extra_checks && chip->can_sleep);
return chip->get ? chip->get(chip, gpio - chip->base) : 0;
}
EXPORT_SYMBOL_GPL(__gpio_get_value);
/**
* __gpio_set_value() - assign a gpio's value
* @gpio: gpio whose value will be assigned
* @value: value to assign
* Context: any
*
* This is used directly or indirectly to implement gpio_set_value().
* It invokes the associated gpio_chip.set() method.
*/
void __gpio_set_value(unsigned gpio, int value)
{
struct gpio_chip *chip;
chip = gpio_to_chip(gpio);
WARN_ON(extra_checks && chip->can_sleep);
chip->set(chip, gpio - chip->base, value);
}
EXPORT_SYMBOL_GPL(__gpio_set_value);
/**
* __gpio_cansleep() - report whether gpio value access will sleep
* @gpio: gpio in question
* Context: any
*
* This is used directly or indirectly to implement gpio_cansleep(). It
* returns nonzero if access reading or writing the GPIO value can sleep.
*/
int __gpio_cansleep(unsigned gpio)
{
struct gpio_chip *chip;
/* only call this on GPIOs that are valid! */
chip = gpio_to_chip(gpio);
return chip->can_sleep;
}
EXPORT_SYMBOL_GPL(__gpio_cansleep);
/**
* __gpio_to_irq() - return the IRQ corresponding to a GPIO
* @gpio: gpio whose IRQ will be returned (already requested)
* Context: any
*
* This is used directly or indirectly to implement gpio_to_irq().
* It returns the number of the IRQ signaled by this (input) GPIO,
* or a negative errno.
*/
int __gpio_to_irq(unsigned gpio)
{
struct gpio_chip *chip;
chip = gpio_to_chip(gpio);
return chip->to_irq ? chip->to_irq(chip, gpio - chip->base) : -ENXIO;
}
EXPORT_SYMBOL_GPL(__gpio_to_irq);
/* There's no value in making it easy to inline GPIO calls that may sleep.
* Common examples include ones connected to I2C or SPI chips.
*/
int gpio_get_value_cansleep(unsigned gpio)
{
struct gpio_chip *chip;
might_sleep_if(extra_checks);
chip = gpio_to_chip(gpio);
return chip->get ? chip->get(chip, gpio - chip->base) : 0;
}
EXPORT_SYMBOL_GPL(gpio_get_value_cansleep);
void gpio_set_value_cansleep(unsigned gpio, int value)
{
struct gpio_chip *chip;
might_sleep_if(extra_checks);
chip = gpio_to_chip(gpio);
chip->set(chip, gpio - chip->base, value);
}
EXPORT_SYMBOL_GPL(gpio_set_value_cansleep);
#ifdef CONFIG_DEBUG_FS
static void gpiolib_dbg_show(struct seq_file *s, struct gpio_chip *chip)
{
unsigned i;
unsigned gpio = chip->base;
struct gpio_desc *gdesc = &gpio_desc[gpio];
int is_out;
for (i = 0; i < chip->ngpio; i++, gpio++, gdesc++) {
if (!test_bit(FLAG_REQUESTED, &gdesc->flags))
continue;
is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
seq_printf(s, " gpio-%-3d (%-20.20s) %s %s",
gpio, gdesc->label,
is_out ? "out" : "in ",
chip->get
? (chip->get(chip, i) ? "hi" : "lo")
: "? ");
if (!is_out) {
int irq = gpio_to_irq(gpio);
struct irq_desc *desc = irq_to_desc(irq);
/* This races with request_irq(), set_irq_type(),
* and set_irq_wake() ... but those are "rare".
*
* More significantly, trigger type flags aren't
* currently maintained by genirq.
*/
if (irq >= 0 && desc->action) {
char *trigger;
switch (desc->status & IRQ_TYPE_SENSE_MASK) {
case IRQ_TYPE_NONE:
trigger = "(default)";
break;
case IRQ_TYPE_EDGE_FALLING:
trigger = "edge-falling";
break;
case IRQ_TYPE_EDGE_RISING:
trigger = "edge-rising";
break;
case IRQ_TYPE_EDGE_BOTH:
trigger = "edge-both";
break;
case IRQ_TYPE_LEVEL_HIGH:
trigger = "level-high";
break;
case IRQ_TYPE_LEVEL_LOW:
trigger = "level-low";
break;
default:
trigger = "?trigger?";
break;
}
seq_printf(s, " irq-%d %s%s",
irq, trigger,
(desc->status & IRQ_WAKEUP)
? " wakeup" : "");
}
}
seq_printf(s, "\n");
}
}
static int gpiolib_show(struct seq_file *s, void *unused)
{
struct gpio_chip *chip = NULL;
unsigned gpio;
int started = 0;
/* REVISIT this isn't locked against gpio_chip removal ... */
for (gpio = 0; gpio_is_valid(gpio); gpio++) {
struct device *dev;
if (chip == gpio_desc[gpio].chip)
continue;
chip = gpio_desc[gpio].chip;
if (!chip)
continue;
seq_printf(s, "%sGPIOs %d-%d",
started ? "\n" : "",
chip->base, chip->base + chip->ngpio - 1);
dev = chip->dev;
if (dev)
seq_printf(s, ", %s/%s",
dev->bus ? dev->bus->name : "no-bus",
dev_name(dev));
if (chip->label)
seq_printf(s, ", %s", chip->label);
if (chip->can_sleep)
seq_printf(s, ", can sleep");
seq_printf(s, ":\n");
started = 1;
if (chip->dbg_show)
chip->dbg_show(s, chip);
else
gpiolib_dbg_show(s, chip);
}
return 0;
}
static int gpiolib_open(struct inode *inode, struct file *file)
{
return single_open(file, gpiolib_show, NULL);
}
static const struct file_operations gpiolib_operations = {
.open = gpiolib_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int __init gpiolib_debugfs_init(void)
{
/* /sys/kernel/debug/gpio */
(void) debugfs_create_file("gpio", S_IFREG | S_IRUGO,
NULL, NULL, &gpiolib_operations);
return 0;
}
subsys_initcall(gpiolib_debugfs_init);
#endif /* DEBUG_FS */
|
archos-sa/archos-gpl-gen9-kernel
|
drivers/gpio/gpiolib.c
|
C
|
gpl-2.0
| 44,350
|
V =
PROGRAM = monoburg
OBJS = \
monoburg.o \
parser.o
CC ?= gcc
LINK ?= $(CC)
DEFAULT_CFLAGS += -Wall -g -rdynamic -std=gnu99
WARNINGS = -Wundef
DEFAULT_CFLAGS += $(WARNINGS)
OPTIMIZATIONS = -Os
DEFAULT_CFLAGS += $(OPTIMIZATIONS)
DEFINES = -DYYENABLE_NLS=0 -DYYLTYPE_IS_TRIVIAL=0
DEFAULT_CFLAGS += $(DEFINES)
INCLUDES = -I. -I..
DEFAULT_CFLAGS += $(INCLUDES)
DEFAULT_CFLAGS += $(shell pkg-config --cflags glib-2.0)
DEFAULT_LIBS += $(shell pkg-config --libs glib-2.0)
ifeq ($(strip $(V)),)
E = @echo
Q = @
else
E = @\#
Q =
endif
export E Q
all: $(PROGRAM)
.PHONY: all
.DEFAULT: all
%.o: %.c
$(E) " CC " $@
$(Q) $(CC) -c $(DEFAULT_CFLAGS) $(CFLAGS) $< -o $@
$(Q) $(CC) -MM $(DEFAULT_CFLAGS) $(CFLAGS) -MT $@ $*.c -o $*.d
$(OBJS):
$(PROGRAM): $(OBJS)
$(E) " LINK " $@
$(Q) $(LINK) $(DEFAULT_CFLAGS) $(CFLAGS) $(OBJS) -o $(PROGRAM) $(LIBS) $(DEFAULT_LIBS)
%.o: %.c
$(E) " CC " $@
$(Q) $(CC) -c $(DEFAULT_CFLAGS) $(CFLAGS) $< -o $@
parser.c: monoburg.y
$(E) " BISON " $@
$(Q) bison monoburg.y -o parser.c
clean:
$(E) " CLEAN"
$(Q) - rm -f parser.c monoburg *.o
.PHONY: all
|
headius/jato
|
tools/monoburg/Makefile
|
Makefile
|
gpl-2.0
| 1,124
|
<?php
// No direct access
defined('_JEXEC') or die('Restricted access');
// import Joomla nested table library
jimport('joomla.database.table');
/**
* Hello Table class
*/
class RentalTablePropertyAttributes extends JTable {
/**
* Constructor
*
* @param object Database connector object
*/
function __construct(&$db) {
parent::__construct('#__unit_attributes', 'property_id', $db);
}
/**
* Overloaded save function
* Takes the facilities and saves them into the availability table.
*
*
*/
public function save($id = null, $attributes = array(), $old_version_id = '', $new_version_id = '') {
if (!$this->check()) {
//JLog::add('JDatabaseMySQL::queryBatch() is deprecated.', JLog::WARNING, 'deprecated');
return false;
} else {
// Firstly need to delete these...in a transaction would be better
$query = $this->_db->getQuery(true);
// If we're updating either a new unit or an new unit version
if ($old_version_id == $new_version_id) {
$query->delete('#__unit_attributes')->where('version_id = ' . $old_version_id);
$this->_db->setQuery($query);
if (!$this->_db->execute()) {
$e = new JException(JText::sprintf('JLIB_DATABASE_ERROR_STORE_FAILED_UPDATE_ASSET_ID', $this->_db->getErrorMsg()));
$this->setError($e);
return false;
}
}
$query = $this->_db->getQuery(true);
$query->insert('#__unit_attributes');
$query->columns(array('version_id', 'property_id', 'attribute_id'));
foreach ($attributes as $attribute) {
$insert_string = "$new_version_id, $id," . $attribute . "";
$query->values($insert_string);
}
$this->_db->setQuery($query);
if (!$this->_db->execute()) {
$e = new JException(JText::sprintf('JLIB_DATABASE_ERROR_STORE_FAILED_UPDATE_ASSET_ID', $this->_db->getErrorMsg()));
$this->setError($e);
return false;
}
// Tick the availability progress flag to true
JApplication::setUserState('com_rental.facilities.progress', true);
return true;
}
}
/**
* Overloaded check function. This should sanity check the data we are about to insert.
* Perhaps do this before deleting?
*
* @return boolean
*/
public function check() {
return true;
}
}
|
adster101/French-Connections-
|
administrator/components/com_rental/tables/propertyattributes.php
|
PHP
|
gpl-2.0
| 2,357
|
// Copyright 2017 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include "DolphinQt2/Debugger/RegisterWidget.h"
#include "Core/Core.h"
#include "Core/HW/ProcessorInterface.h"
#include "Core/PowerPC/PowerPC.h"
#include "DolphinQt2/QtUtils/ActionHelper.h"
#include "DolphinQt2/Settings.h"
#include <QHeaderView>
#include <QMenu>
#include <QTableWidget>
#include <QVBoxLayout>
RegisterWidget::RegisterWidget(QWidget* parent) : QDockWidget(parent)
{
setWindowTitle(tr("Registers"));
setObjectName(QStringLiteral("registers"));
setAllowedAreas(Qt::AllDockWidgetAreas);
auto& settings = Settings::GetQSettings();
restoreGeometry(settings.value(QStringLiteral("registerwidget/geometry")).toByteArray());
setFloating(settings.value(QStringLiteral("registerwidget/floating")).toBool());
CreateWidgets();
PopulateTable();
ConnectWidgets();
connect(&Settings::Instance(), &Settings::EmulationStateChanged, [this](Core::State state) {
if (Settings::Instance().IsDebugModeEnabled() && Core::GetState() == Core::State::Paused)
emit RequestTableUpdate();
});
connect(this, &RegisterWidget::RequestTableUpdate, [this] {
m_updating = true;
emit UpdateTable();
m_updating = false;
});
connect(&Settings::Instance(), &Settings::RegistersVisibilityChanged,
[this](bool visible) { setHidden(!visible); });
connect(&Settings::Instance(), &Settings::DebugModeToggled, [this](bool enabled) {
setHidden(!enabled || !Settings::Instance().IsRegistersVisible());
});
setHidden(!Settings::Instance().IsRegistersVisible() ||
!Settings::Instance().IsDebugModeEnabled());
}
RegisterWidget::~RegisterWidget()
{
auto& settings = Settings::GetQSettings();
settings.setValue(QStringLiteral("registerwidget/geometry"), saveGeometry());
settings.setValue(QStringLiteral("registerwidget/floating"), isFloating());
}
void RegisterWidget::closeEvent(QCloseEvent*)
{
Settings::Instance().SetRegistersVisible(false);
}
void RegisterWidget::CreateWidgets()
{
m_table = new QTableWidget;
m_table->setColumnCount(9);
m_table->verticalHeader()->setVisible(false);
m_table->setContextMenuPolicy(Qt::CustomContextMenu);
m_table->setSelectionMode(QAbstractItemView::SingleSelection);
QStringList empty_list;
for (auto i = 0; i < 9; i++)
empty_list << QStringLiteral("");
m_table->setHorizontalHeaderLabels(empty_list);
QWidget* widget = new QWidget;
auto* layout = new QVBoxLayout;
layout->addWidget(m_table);
widget->setLayout(layout);
setWidget(widget);
}
void RegisterWidget::ConnectWidgets()
{
connect(m_table, &QTableWidget::customContextMenuRequested, this,
&RegisterWidget::ShowContextMenu);
connect(m_table, &QTableWidget::itemChanged, this, &RegisterWidget::OnItemChanged);
}
void RegisterWidget::OnItemChanged(QTableWidgetItem* item)
{
if (!item->data(DATA_TYPE).isNull() && !m_updating)
static_cast<RegisterColumn*>(item)->SetValue();
}
void RegisterWidget::ShowContextMenu()
{
QMenu* menu = new QMenu(this);
if (m_table->selectedItems().size())
{
auto variant = m_table->selectedItems()[0]->data(DATA_TYPE);
if (!variant.isNull())
{
auto* item = reinterpret_cast<RegisterColumn*>(m_table->selectedItems()[0]);
auto type = static_cast<RegisterType>(item->data(DATA_TYPE).toInt());
auto display = item->GetDisplay();
AddAction(menu, tr("Add to &watch"), this,
[this, item] { emit RequestMemoryBreakpoint(item->GetValue()); });
menu->addAction(tr("View &memory"));
menu->addAction(tr("View &code"));
menu->addSeparator();
QActionGroup* group = new QActionGroup(menu);
group->setExclusive(true);
auto* view_hex = menu->addAction(tr("Hexadecimal"));
auto* view_int = menu->addAction(tr("Signed Integer"));
auto* view_uint = menu->addAction(tr("Unsigned Integer"));
// i18n: A floating point number
auto* view_float = menu->addAction(tr("Float"));
// i18n: A double precision floating point number
auto* view_double = menu->addAction(tr("Double"));
for (auto* action : {view_hex, view_int, view_uint, view_float, view_double})
{
action->setCheckable(true);
action->setVisible(false);
action->setActionGroup(group);
}
switch (display)
{
case RegisterDisplay::Hex:
view_hex->setChecked(true);
break;
case RegisterDisplay::SInt32:
view_int->setChecked(true);
break;
case RegisterDisplay::UInt32:
view_uint->setChecked(true);
break;
case RegisterDisplay::Float:
view_float->setChecked(true);
break;
case RegisterDisplay::Double:
view_double->setChecked(true);
break;
}
switch (type)
{
case RegisterType::gpr:
view_hex->setVisible(true);
view_int->setVisible(true);
view_uint->setVisible(true);
view_float->setVisible(true);
break;
case RegisterType::fpr:
view_hex->setVisible(true);
view_double->setVisible(true);
break;
default:
break;
}
connect(view_hex, &QAction::triggered, [this, item] {
m_updating = true;
item->SetDisplay(RegisterDisplay::Hex);
m_updating = false;
});
connect(view_int, &QAction::triggered, [this, item] {
m_updating = true;
item->SetDisplay(RegisterDisplay::SInt32);
m_updating = false;
});
connect(view_uint, &QAction::triggered, [this, item] {
m_updating = true;
item->SetDisplay(RegisterDisplay::UInt32);
m_updating = false;
});
connect(view_float, &QAction::triggered, [this, item] {
m_updating = true;
item->SetDisplay(RegisterDisplay::Float);
m_updating = false;
});
connect(view_double, &QAction::triggered, [this, item] {
m_updating = true;
item->SetDisplay(RegisterDisplay::Double);
m_updating = false;
});
menu->addSeparator();
}
}
AddAction(menu, tr("Update"), this, [this] { emit RequestTableUpdate(); });
menu->exec(QCursor::pos());
}
void RegisterWidget::PopulateTable()
{
for (int i = 0; i < 32; i++)
{
// General purpose registers (int)
AddRegister(i, 0, RegisterType::gpr, "r" + std::to_string(i), [i] { return GPR(i); },
[i](u64 value) { GPR(i) = value; });
// Floating point registers (double)
AddRegister(i, 2, RegisterType::fpr, "f" + std::to_string(i), [i] { return riPS0(i); },
[i](u64 value) { riPS0(i) = value; });
AddRegister(i, 4, RegisterType::fpr, "", [i] { return riPS1(i); },
[i](u64 value) { riPS1(i) = value; });
}
for (int i = 0; i < 8; i++)
{
// IBAT registers
AddRegister(i, 5, RegisterType::ibat, "IBAT" + std::to_string(i),
[i] {
return (static_cast<u64>(PowerPC::ppcState.spr[SPR_IBAT0U + i * 2]) << 32) +
PowerPC::ppcState.spr[SPR_IBAT0L + i * 2];
},
nullptr);
// DBAT registers
AddRegister(i + 8, 5, RegisterType::dbat, "DBAT" + std::to_string(i),
[i] {
return (static_cast<u64>(PowerPC::ppcState.spr[SPR_DBAT0U + i * 2]) << 32) +
PowerPC::ppcState.spr[SPR_DBAT0L + i * 2];
},
nullptr);
// Graphics quantization registers
AddRegister(i + 16, 7, RegisterType::gqr, "GQR" + std::to_string(i),
[i] { return PowerPC::ppcState.spr[SPR_GQR0 + i]; }, nullptr);
}
for (int i = 0; i < 16; i++)
{
// SR registers
AddRegister(i, 7, RegisterType::sr, "SR" + std::to_string(i),
[i] { return PowerPC::ppcState.sr[i]; },
[i](u64 value) { PowerPC::ppcState.sr[i] = value; });
}
// Special registers
// TB
AddRegister(16, 5, RegisterType::tb, "TB",
[] {
return static_cast<u64>(PowerPC::ppcState.spr[SPR_TU]) << 32 |
PowerPC::ppcState.spr[SPR_TL];
},
nullptr);
// PC
AddRegister(17, 5, RegisterType::pc, "PC", [] { return PowerPC::ppcState.pc; },
[](u64 value) { PowerPC::ppcState.pc = value; });
// LR
AddRegister(18, 5, RegisterType::lr, "LR", [] { return PowerPC::ppcState.spr[SPR_LR]; },
[](u64 value) { PowerPC::ppcState.spr[SPR_LR] = value; });
// CTR
AddRegister(19, 5, RegisterType::ctr, "CTR", [] { return PowerPC::ppcState.spr[SPR_CTR]; },
[](u64 value) { PowerPC::ppcState.spr[SPR_CTR] = value; });
// CR
AddRegister(20, 5, RegisterType::cr, "CR", [] { return PowerPC::GetCR(); },
[](u64 value) { PowerPC::SetCR(value); });
// XER
AddRegister(21, 5, RegisterType::xer, "XER", [] { return PowerPC::GetXER().Hex; },
[](u64 value) { PowerPC::SetXER(UReg_XER(value)); });
// FPSCR
AddRegister(22, 5, RegisterType::fpscr, "FPSCR", [] { return PowerPC::ppcState.fpscr; },
[](u64 value) { PowerPC::ppcState.fpscr = value; });
// MSR
AddRegister(23, 5, RegisterType::msr, "MSR", [] { return PowerPC::ppcState.msr; },
[](u64 value) { PowerPC::ppcState.msr = value; });
// SRR 0-1
AddRegister(24, 5, RegisterType::srr, "SRR0", [] { return PowerPC::ppcState.spr[SPR_SRR0]; },
[](u64 value) { PowerPC::ppcState.spr[SPR_SRR0] = value; });
AddRegister(25, 5, RegisterType::srr, "SRR1", [] { return PowerPC::ppcState.spr[SPR_SRR1]; },
[](u64 value) { PowerPC::ppcState.spr[SPR_SRR1] = value; });
// Exceptions
AddRegister(26, 5, RegisterType::exceptions, "Exceptions",
[] { return PowerPC::ppcState.Exceptions; },
[](u64 value) { PowerPC::ppcState.Exceptions = value; });
// Int Mask
AddRegister(27, 5, RegisterType::int_mask, "Int Mask",
[] { return ProcessorInterface::GetMask(); }, nullptr);
// Int Cause
AddRegister(28, 5, RegisterType::int_cause, "Int Cause",
[] { return ProcessorInterface::GetCause(); }, nullptr);
// DSISR
AddRegister(29, 5, RegisterType::dsisr, "DSISR", [] { return PowerPC::ppcState.spr[SPR_DSISR]; },
[](u64 value) { PowerPC::ppcState.spr[SPR_DSISR] = value; });
// DAR
AddRegister(30, 5, RegisterType::dar, "DAR", [] { return PowerPC::ppcState.spr[SPR_DAR]; },
[](u64 value) { PowerPC::ppcState.spr[SPR_DAR] = value; });
// Hash Mask
AddRegister(
31, 5, RegisterType::pt_hashmask, "Hash Mask",
[] { return (PowerPC::ppcState.pagetable_hashmask << 6) | PowerPC::ppcState.pagetable_base; },
nullptr);
emit RequestTableUpdate();
m_table->resizeColumnsToContents();
}
void RegisterWidget::AddRegister(int row, int column, RegisterType type, std::string register_name,
std::function<u64()> get_reg, std::function<void(u64)> set_reg)
{
auto* value = new RegisterColumn(type, get_reg, set_reg);
if (m_table->rowCount() <= row)
m_table->setRowCount(row + 1);
bool has_label = !register_name.empty();
if (has_label)
{
auto* label = new QTableWidgetItem(QString::fromStdString(register_name));
label->setFlags(Qt::ItemIsEnabled);
QFont label_font = label->font();
label_font.setBold(true);
label->setFont(label_font);
m_table->setItem(row, column, label);
m_table->setItem(row, column + 1, value);
}
else
{
m_table->setItem(row, column, value);
}
connect(this, &RegisterWidget::UpdateTable, [value] { value->RefreshValue(); });
}
|
TurboK234/dolphin
|
Source/Core/DolphinQt2/Debugger/RegisterWidget.cpp
|
C++
|
gpl-2.0
| 11,721
|
let path = require('path');
let fs = require('fs');
let Site = require('./Site.js');
let option = require('optionJS');
let File = require('./File.js');
let Font = require('./Font.js');
let Style = require('./Style.js');
let Script = require('./Script.js');
// 帮助信息
function showHelp() {
console.log('使用方法:');
console.log(' -d --domain=feDomain\t设定域名');
console.log(' -o --out=outputPath\t目标目录');
console.log(' -w --watch\t\t开启监听');
console.log(' -v --version\t\t显示版本号并退出');
console.log(' -h --help\t\t显示帮助信息并退出');
process.exit(0);
};
// 转换绝对路径
function toAbsolute(cwd, value) {
let foo = value;
if (!path.isAbsolute(value)) {
foo = path.normalize(path.join(cwd, value));
}
return foo.length ? foo : cwd;
}
// 参数检查
function argCheck(args, cwd = '.') {
if (args['version']) {
console.log('fe-builder 0.1 (C) 2017 JamesWatson LICENSE GPL2.0');
process.exit(0);
}
if (args['help'] || !args.out || '' === args.out || !args.default || '' === args.default || !args.domain || '' === args.domain) {
showHelp();
}
cwd = fs.realpathSync(cwd);
args['default'] = toAbsolute(cwd, args['default']);
args['out'] = toAbsolute(cwd, args['out']);
}
// 编译字体文件
function mkFont(input, incName, outFontFile, outCssFile, callback) {
let iconFont = new Font(input);
let style = `@font-face{font-family:"${iconFont.fontName}";src:url(${incName}?_=${new Date().getTime()}) format("woff")}.${iconFont.fontName}{display:inline;vertical-align: middle}.${iconFont.fontName}:after{display:inline;width:1em;font-family:"${iconFont.fontName}";font-style:normal}`;
let writed = 0;
// 生成svg字体文件
iconFont.on('toSvg', () => {
// 转成woff
iconFont.toWOFF();
// 拼装css
style += iconFont.fontVector.map((icon) => {
return `.${iconFont.fontName}.icon-${icon.name}:after{content:"\\${icon.code}"}`;
}).join(' ');
// 写入woff文件
iconFont
.on('writed', (err) => {
writed++;
if ((err || 2 === writed) && callback) {
writed += 2;
let handle = setTimeout(() => {
clearTimeout(handle);
callback(err);
}, 0);
}
})
.writeWoff(outFontFile);
// 写入css文件
new Style(style)
.compress()
.on('writed', (err) => {
writed++;
if ((err || 2 === writed) && callback) {
writed += 2;
let handle = setTimeout(() => {
clearTimeout(handle);
callback(err);
}, 0);
}
}).write(outCssFile);
});
}
let foo = {
'.less': function(fileObj, info) {
return new Promise((resolve, reject) => {
let styleFile = new Style(fileObj);
styleFile.fileName = info.srcFileName;
styleFile
.less()
.then(() => {
// 解析less完成
styleFile.compress();
resolve([styleFile]);
})
.catch(reject);
});
},
'.es6': function(fileObj) {
let scriptFile = new Script(fileObj).es6().compress();
return new Promise((resolve, reject) => {
resolve([scriptFile]);
});
}
};
function parseAFile(fileObj, info) {
let func = foo[info.type];
if ('function' === typeof func) {
return func(fileObj, info);
}
return new Promise((resolve, reject) => {
resolve([fileObj, {
hash: false,
min: false
}]);
});
}
function main(args) {
console.log('start...');
// 参数检查
argCheck(args);
// 初始化一个网站
let site = new Site(args['out'], args['domain'], args['default']);
let count = 0;
let htmls = [];
site
.map()
.then((mapper) => {
//mkFont()
// 遍历引用关系图
console.log('共发现' + mapper.size + '个文件');
let mapFinish = false;
for (let [index, info] of mapper) {
// 跳过不存在的文件
if (info.notFound) {
continue;
}
if (info.html) {
htmls.push(info);
continue;
}
count++;
File
.read(info.srcFileName)
// 读取完成,开始解析
.then((fileObj) => {
return parseAFile(fileObj, info);
})
// 解析完成,写入目标文件
.then(([fileObj, opt]) => {
if (!fileObj)
return new Promise((resolve, reject) => {
resolve();
});
return info.writeRes(fileObj, opt);
})
// 写入完成
.then(() => {
if (0 !== --count || !mapFinish)
return;
console.log(`html页面共计${htmls.length}个`);
for (page of htmls) {
// 引用替换
page.link.forEach((item) => {
// 查找对应的资源文件
let resFileObj = mapper.get(item);
if (!resFileObj || resFileObj.notFound) {
return;
}
page.html._out = page.html._out.replace(item, resFileObj.outFileIndex);
});
// 写入
page.html.write(path.format(page.outFileName)).on('writed', () => {
// 重置
page.html.reset();
});
}
})
// 出错
.catch(console.error);
}
mapFinish = true;
})
.catch(console.error);
console.log('mapping...');
return 0;
}
(function() {
main(option([{
opt: 'v',
option: 'version',
argument: false
}, {
opt: 'h',
option: 'help',
argument: false
}, {
opt: 'w',
option: 'watch',
argument: false
}, {
opt: 'o',
option: 'out',
argument: true
}, {
opt: 'd',
option: 'domain',
argument: true
}]));
})();
|
watsonserve/fe-builder
|
lib/index.js
|
JavaScript
|
gpl-2.0
| 5,812
|
package de.steinberg.gyp.gui.logging;
import de.steinberg.gyp.gui.FXMLElementsAccessor;
import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
import javax.inject.Inject;
import java.io.IOException;
import java.io.Writer;
/**
* Created by LKLeen on 19.12.2014.
*/
public class LogWriter extends Writer {
final TextArea logOutput;
public LogWriter(TextArea logOutput) {
this.logOutput = logOutput;
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
String text = new String(cbuf, off, len);
logOutput.appendText(text);
}
@Override
public void flush() throws IOException {
}
@Override
public void close() throws IOException {
}
}
|
lkleen/de.steinberg.gyp
|
gui/src/main/java/de/steinberg/gyp/gui/logging/LogWriter.java
|
Java
|
gpl-2.0
| 751
|
/*
Theme Name: Spotfin Starter Theme
Adding support for language written in a Right To Left (RTL) direction is easy -
it's just a matter of overwriting all the horizontal positioning attributes
of your CSS stylesheet in a separate stylesheet file named rtl.css.
http://codex.wordpress.org/Right_to_Left_Language_Support
*/
/*
body {
direction: rtl;
unicode-bidi: embed;
}
*/
|
bmoredrew/spotfin-starter-theme
|
rtl.css
|
CSS
|
gpl-2.0
| 380
|
/***************************************************************************
qgslegendlayer.cpp
---------------------
begin : January 2007
copyright : (C) 2007 by Martin Dobias
email : wonder dot sk at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsapplication.h"
#include "qgisapp.h"
#include "qgslegend.h"
#include "qgslegendlayer.h"
#include "qgslegendsymbologyitem.h"
#include "qgslogger.h"
#include "qgsfield.h"
#include "qgsmapcanvasmap.h"
#include "qgsmaplayerregistry.h"
#include "qgspluginlayer.h"
#include "qgsrasterlayer.h"
#include "qgsvectorlayer.h"
#include "qgsvectordataprovider.h"
#include "qgsrendererv2.h"
#include "qgssymbolv2.h"
#include "qgssinglesymbolrendererv2.h"
#include "qgscategorizedsymbolrendererv2.h"
#include "qgsgraduatedsymbolrendererv2.h"
#include <QAction>
#include <QCoreApplication>
#include <QIcon>
#include <QMenu>
#include <QMessageBox>
#include <QPainter>
#include <QSettings>
#include <QFileDialog>
#include <QProgressDialog>
QgsLegendLayer::QgsLegendLayer( QgsMapLayer* layer )
: QgsLegendItem( )
, mLyr( layer )
, mDrawingOrder( -1 )
, mShowFeatureCount( false )
{
mType = LEGEND_LAYER;
Qt::ItemFlags flags = Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;
QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( layer );
if ( !vlayer || vlayer->hasGeometryType() )
{
flags |= Qt::ItemIsUserCheckable;
}
setFlags( flags );
setCheckState( 0, Qt::Checked );
layerNameChanged();
setupFont();
// Set the initial visibility flag for layers
// This user option allows the user to turn off initial drawing of
// layers when they are added to the map. This is useful when adding
// many layers and the user wants to adjusty symbology, etc prior to
// actually viewing the layer.
QSettings settings;
bool visible = settings.value( "/qgis/new_layers_visible", true ).toBool();
mLyr.setVisible( visible );
// not in overview by default
mLyr.setInOverview( false );
// setup connections that will update the layer icons
if ( qobject_cast<QgsVectorLayer *>( layer ) )
{
QgsDebugMsg( "Connecting signals for updating icons, layer " + layer->name() );
connect( layer, SIGNAL( editingStarted() ), this, SLOT( updateIcon() ) );
connect( layer, SIGNAL( editingStopped() ), this, SLOT( updateIcon() ) );
connect( layer, SIGNAL( layerModified() ), this, SLOT( updateAfterLayerModification() ) ); // TODO[MD]: should have symbologyChanged signal
}
if ( qobject_cast<QgsRasterLayer *>( layer ) )
{
connect( layer, SIGNAL( dataChanged() ), this, SLOT( updateAfterLayerModification() ) );
}
connect( layer, SIGNAL( layerNameChanged() ), this, SLOT( layerNameChanged() ) );
updateIcon();
setToolTip( 0, layer->publicSource() );
}
QgsLegendLayer::~QgsLegendLayer()
{
mType = LEGEND_LAYER;
}
void QgsLegendLayer::setCheckState( int column, Qt::CheckState state )
{
if ( flags() & Qt::ItemIsUserCheckable )
{
QTreeWidgetItem::setCheckState( column, state );
}
}
void QgsLegendLayer::setupFont()
{
QSettings settings;
QFont myFont = font( 0 );
//visually differentiate layer labels from the rest
myFont.setBold( settings.value( "/qgis/legendLayersBold", true ).toBool() );
setFont( 0, myFont );
}
QgsMapLayer* QgsLegendLayer::layer()
{
return mLyr.layer();
}
void QgsLegendLayer::refreshSymbology( const QString& key )
{
QgsMapLayer* theMapLayer = QgsMapLayerRegistry::instance()->mapLayer( key );
if ( !theMapLayer )
{
return;
}
if ( theMapLayer->type() == QgsMapLayer::VectorLayer ) // VECTOR
{
QgsVectorLayer* vlayer = qobject_cast<QgsVectorLayer *>( theMapLayer );
vectorLayerSymbologyV2( vlayer );
}
else if ( theMapLayer->type() == QgsMapLayer::RasterLayer ) // RASTER
{
QgsRasterLayer* rlayer = qobject_cast<QgsRasterLayer *>( theMapLayer );
rasterLayerSymbology( rlayer ); // get and change symbology
}
else if ( theMapLayer->type() == QgsMapLayer::PluginLayer )
{
QgsPluginLayer* player = qobject_cast<QgsPluginLayer *>( theMapLayer );
QSize iconSize( 16, 16 );
SymbologyList itemList = player->legendSymbologyItems( iconSize );
changeSymbologySettings( theMapLayer, itemList );
}
updateIcon();
}
void QgsLegendLayer::changeSymbologySettings( const QgsMapLayer* theMapLayer,
const SymbologyList& newSymbologyItems )
{
if ( !theMapLayer )
{
return;
}
QgsLegendSymbologyItem* theSymbologyItem = 0;
//remove the symbology items under the legend layer
for ( int i = childCount(); i >= 0; --i )
{
theSymbologyItem = dynamic_cast<QgsLegendSymbologyItem *>( child( i ) );
if ( theSymbologyItem )
{
delete takeChild( i );
}
}
//add the new symbology items
int childposition = 0; //position to insert the items
for ( SymbologyList::const_iterator it = newSymbologyItems.begin(); it != newSymbologyItems.end(); ++it )
{
QgsLegendSymbologyItem* theItem = new QgsLegendSymbologyItem( it->second.width(), it->second.height() );
theItem->setText( 0, it->first );
theItem->setIcon( 0, QIcon( it->second ) );
insertChild( childposition, theItem );
++childposition;
}
}
void QgsLegendLayer::vectorLayerSymbologyV2( QgsVectorLayer* layer )
{
QSize iconSize( 16, 16 );
QgsFeatureRendererV2* renderer = layer->rendererV2();
if ( renderer )
{
SymbologyList itemList = renderer->legendSymbologyItems( iconSize );
if ( mShowFeatureCount )
{
updateItemListCountV2( itemList, layer );
}
changeSymbologySettings( layer, itemList );
layerNameChanged(); // update total count
}
}
void QgsLegendLayer::rasterLayerSymbology( QgsRasterLayer* layer )
{
SymbologyList itemList;
QList< QPair< QString, QColor > > rasterItemList = layer->legendSymbologyItems();
QList< QPair< QString, QColor > >::const_iterator itemIt = rasterItemList.constBegin();
itemList.reserve( rasterItemList.size() );
// GetLegendGraphics in case of WMS service... pixmap can return null if GetLegendGraphics
// is not supported by the server
QgsDebugMsg( QString( "layer providertype:: %1" ).arg( layer->providerType() ) );
if ( layer->providerType() == "wms" )
{
double currentScale = legend()->canvas()->scale();
QImage legendGraphic = layer->dataProvider()->getLegendGraphic( currentScale );
if ( !legendGraphic.isNull() )
{
QgsDebugMsg( QString( "downloaded legend with dimension width:" ) + QString::number( legendGraphic.width() ) + QString( " and Height:" ) + QString::number( legendGraphic.height() ) );
if ( rasterItemList.size() == 0 )
itemList.reserve( 1 );
itemList.append( qMakePair( QString( "" ), QPixmap::fromImage( legendGraphic ) ) );
}
}
// Paletted raster may have many colors, for example UInt16 may have 65536 colors
// and it is very slow, so we limit max count
QSize iconSize = treeWidget()->iconSize();
int count = 0;
int max_count = 1000;
for ( ; itemIt != rasterItemList.constEnd(); ++itemIt )
{
QPixmap itemPixmap( iconSize );
itemPixmap.fill( itemIt->second );
// This is very slow, not clear why, it should not be, probably realloc,
// but it seems to be non linear
itemList.append( qMakePair( itemIt->first, itemPixmap ) );
count++;
if ( count == max_count )
{
itemPixmap = QPixmap( iconSize );
itemPixmap.fill( Qt::transparent );
QString label = tr( "following %1 items\nnot displayed" ).arg( rasterItemList.size() - max_count );
itemList.append( qMakePair( label, itemPixmap ) );
break;
}
}
changeSymbologySettings( layer, itemList );
}
void QgsLegendLayer::updateIcon()
{
QPixmap newIcon( getOriginalPixmap() );
QgsMapLayer* theLayer = layer();
//overview
// FIXME: overview icon is missing
/*
if ( theFile->isInOverview() )
{
// Overlay the overview icon on the default icon
QPixmap myPixmap = QgsApplication::getThemePixmap( "/mIconOverview.png" );
QPainter p( &newIcon );
p.drawPixmap( 0, 0, myPixmap );
p.end();
}*/
//editable
if ( theLayer->isEditable() )
{
QPixmap myPixmap;
QgsVectorLayer* vlayer = qobject_cast<QgsVectorLayer *>( theLayer );
if ( vlayer->isModified() )
{
myPixmap = QgsApplication::getThemePixmap( "/mIconEditableEdits.png" );
}
else
{
myPixmap = QgsApplication::getThemePixmap( "/mIconEditable.png" );
}
// use editable icon instead of the layer's type icon
newIcon = myPixmap;
// Overlay the editable icon on the default icon
/*QPainter p( &newIcon );
p.drawPixmap( 0, 0, myPixmap );
p.end();*/
}
// TODO: projection error icon?
QIcon theIcon( newIcon );
QgsLegend* l = legend();
if ( l )
{
l->blockSignals( true ); //prevent unnecessary canvas redraw
}
setIcon( 0, theIcon );
if ( l )
{
l->blockSignals( false );
}
}
QPixmap QgsLegendLayer::getOriginalPixmap()
{
QgsMapLayer* theLayer = layer();
if ( theLayer )
{
if ( theLayer->type() == QgsMapLayer::VectorLayer )
{
QgsVectorLayer* vlayer = qobject_cast<QgsVectorLayer *>( theLayer );
switch ( vlayer->geometryType() )
{
case QGis::Point:
return QgsApplication::getThemePixmap( "/mIconPointLayer.svg" );
case QGis::Line:
return QgsApplication::getThemePixmap( "/mIconLineLayer.svg" );
case QGis::Polygon:
return QgsApplication::getThemePixmap( "/mIconPolygonLayer.svg" );
case QGis::NoGeometry:
return QgsApplication::getThemePixmap( "/mIconTableLayer.png" );
default:
return QgsApplication::getThemePixmap( "/mIconLayer.png" );
}
}
else if ( theLayer->type() == QgsMapLayer::RasterLayer )
{
QSettings s;
if ( s.value( "/qgis/createRasterLegendIcons", false ).toBool() )
{
QgsRasterLayer* rlayer = qobject_cast<QgsRasterLayer *>( theLayer );
return rlayer->previewAsPixmap( QSize( 32, 32 ) );
}
else
{
return QgsApplication::getThemePixmap( "/mIconRasterLayer.svg" );
}
}
}
// undefined - should never reach this
return QgsApplication::getThemePixmap( "/mIconLayer.png" );
}
void QgsLegendLayer::addToPopupMenu( QMenu& theMenu )
{
QgsMapLayer *lyr = layer();
QAction *toggleEditingAction = QgisApp::instance()->actionToggleEditing();
QAction *saveLayerEditsAction = QgisApp::instance()->actionSaveActiveLayerEdits();
QAction *allEditsAction = QgisApp::instance()->actionAllEdits();
// zoom to layer extent
theMenu.addAction( QgsApplication::getThemeIcon( "/mActionZoomToLayer.svg" ),
tr( "&Zoom to Layer Extent" ), legend(), SLOT( legendLayerZoom() ) );
if ( lyr->type() == QgsMapLayer::RasterLayer )
{
theMenu.addAction( tr( "&Zoom to Best Scale (100%)" ), legend(), SLOT( legendLayerZoomNative() ) );
QgsRasterLayer *rasterLayer = qobject_cast<QgsRasterLayer *>( lyr );
if ( rasterLayer && rasterLayer->rasterType() != QgsRasterLayer::Palette )
{
theMenu.addAction( tr( "&Stretch Using Current Extent" ), legend(), SLOT( legendLayerStretchUsingCurrentExtent() ) );
}
}
// show in overview
QAction* showInOverviewAction = theMenu.addAction( tr( "&Show in Overview" ), this, SLOT( showInOverview() ) );
showInOverviewAction->setCheckable( true );
showInOverviewAction->blockSignals( true );
showInOverviewAction->setChecked( mLyr.isInOverview() );
showInOverviewAction->blockSignals( false );
// remove from canvas
theMenu.addAction( QgsApplication::getThemeIcon( "/mActionRemoveLayer.svg" ), tr( "&Remove" ), QgisApp::instance(), SLOT( removeLayer() ) );
// duplicate layer
QAction* duplicateLayersAction = theMenu.addAction( QgsApplication::getThemeIcon( "/mActionDuplicateLayer.svg" ), tr( "&Duplicate" ), QgisApp::instance(), SLOT( duplicateLayers() ) );
// set layer crs
theMenu.addAction( QgsApplication::getThemeIcon( "/mActionSetCRS.png" ), tr( "&Set Layer CRS" ), QgisApp::instance(), SLOT( setLayerCRS() ) );
// assign layer crs to project
theMenu.addAction( QgsApplication::getThemeIcon( "/mActionSetProjectCRS.png" ), tr( "Set &Project CRS from Layer" ), QgisApp::instance(), SLOT( setProjectCRSFromLayer() ) );
theMenu.addSeparator();
if ( lyr->type() == QgsMapLayer::VectorLayer )
{
QgsVectorLayer* vlayer = qobject_cast<QgsVectorLayer *>( lyr );
// attribute table
theMenu.addAction( QgsApplication::getThemeIcon( "/mActionOpenTable.png" ), tr( "&Open Attribute Table" ),
QgisApp::instance(), SLOT( attributeTable() ) );
// allow editing
int cap = vlayer->dataProvider()->capabilities();
if ( cap & QgsVectorDataProvider::EditingCapabilities )
{
if ( toggleEditingAction )
{
theMenu.addAction( toggleEditingAction );
toggleEditingAction->setChecked( vlayer->isEditable() );
}
if ( saveLayerEditsAction && vlayer->isModified() )
{
theMenu.addAction( saveLayerEditsAction );
}
}
if ( allEditsAction->isEnabled() )
{
theMenu.addAction( allEditsAction );
}
// disable duplication of memory layers
if ( vlayer->storageType() == "Memory storage" && legend()->selectedLayers().count() == 1 )
{
duplicateLayersAction->setEnabled( false );
}
// save as vector file
theMenu.addAction( tr( "Save As..." ), QgisApp::instance(), SLOT( saveAsFile() ) );
// save selection as vector file
QAction* saveSelectionAsAction = theMenu.addAction( tr( "Save Selection As..." ), QgisApp::instance(), SLOT( saveSelectionAsVectorFile() ) );
if ( vlayer->selectedFeatureCount() == 0 )
{
saveSelectionAsAction->setEnabled( false );
}
if ( !vlayer->isEditable() && vlayer->dataProvider()->supportsSubsetString() && vlayer->vectorJoins().isEmpty() )
theMenu.addAction( tr( "&Filter..." ), QgisApp::instance(), SLOT( layerSubsetString() ) );
//show number of features in legend if requested
QAction* showNFeaturesAction = new QAction( tr( "Show Feature Count" ), &theMenu );
showNFeaturesAction->setCheckable( true );
showNFeaturesAction->setChecked( mShowFeatureCount );
QObject::connect( showNFeaturesAction, SIGNAL( toggled( bool ) ), this, SLOT( setShowFeatureCount( bool ) ) );
theMenu.addAction( showNFeaturesAction );
theMenu.addSeparator();
}
else if ( lyr->type() == QgsMapLayer::RasterLayer )
{
theMenu.addAction( tr( "Save As..." ), QgisApp::instance(), SLOT( saveAsRasterFile() ) );
}
else if ( lyr->type() == QgsMapLayer::PluginLayer && legend()->selectedLayers().count() == 1 )
{
// disable duplication of plugin layers
duplicateLayersAction->setEnabled( false );
}
}
//////////
void QgsLegendLayer::setVisible( bool visible )
{
mLyr.setVisible( visible );
}
bool QgsLegendLayer::isVisible()
{
return mLyr.isVisible();
}
void QgsLegendLayer::setInOverview( bool isInOverview )
{
mLyr.setInOverview( isInOverview );
}
bool QgsLegendLayer::isInOverview()
{
return mLyr.isInOverview();
}
void QgsLegendLayer::showInOverview()
{
// toggle current status
setInOverview( ! isInOverview() );
legend()->updateMapCanvasLayerSet();
legend()->updateOverview();
}
QString QgsLegendLayer::nameFromLayer( QgsMapLayer* layer )
{
QString sourcename = layer->publicSource(); //todo: move this duplicated code into a new function
if ( sourcename.startsWith( "host", Qt::CaseInsensitive ) )
{
//this layer is a database layer
//modify source string such that password is not visible
sourcename = layer->name();
}
else
{
//modify source name such that only the file is visible
sourcename = layer->publicSource().section( '/', -1, -1 );
}
return sourcename;
}
QgsMapCanvasLayer& QgsLegendLayer::canvasLayer()
{
return mLyr;
}
QString QgsLegendLayer::label()
{
QString name = mLyr.layer()->name();
QgsVectorLayer *vlayer = dynamic_cast<QgsVectorLayer *>( mLyr.layer() );
if ( mShowFeatureCount && vlayer && vlayer->pendingFeatureCount() >= 0 )
{
name += QString( " [%1]" ).arg( vlayer->pendingFeatureCount() );
}
return name;
}
void QgsLegendLayer::layerNameChanged()
{
setText( 0, label() );
}
void QgsLegendLayer::beforeEdit()
{
// Reset to layer name without possible feature count
setText( 0, mLyr.layer()->name() );
}
void QgsLegendLayer::afterEdit()
{
// Reset label with possible feature count, important if text was not changed
layerNameChanged();
}
QString QgsLegendLayer::layerName()
{
// The text could be edited (Rename), in that case we have to return the new name
if ( text( 0 ) != label() && text( 0 ) != mLyr.layer()->name() )
{
return text( 0 );
}
return mLyr.layer()->name();
}
void QgsLegendLayer::updateAfterLayerModification()
{
refreshSymbology( mLyr.layer()->id() );
layerNameChanged();
}
void QgsLegendLayer::updateItemListCountV2( SymbologyList& itemList, QgsVectorLayer* layer )
{
if ( !layer )
{
return;
}
QgsFeatureRendererV2* renderer = layer->rendererV2();
if ( !renderer )
{
return;
}
// Count features
if ( !layer->countSymbolFeatures() )
{
QgsDebugMsg( "Cannot get feature counts" );
return;
}
QMap<QString, QPixmap> itemMap;
SymbologyList::const_iterator symbologyIt = itemList.constBegin();
for ( ; symbologyIt != itemList.constEnd(); ++ symbologyIt )
{
itemMap.insert( symbologyIt->first, symbologyIt->second );
}
itemList.clear();
QgsLegendSymbolList symbolList = renderer->legendSymbolItems();
QgsLegendSymbolList::const_iterator symbolIt = symbolList.constBegin();
for ( ; symbolIt != symbolList.constEnd(); ++symbolIt )
{
itemList.push_back( qMakePair( symbolIt->first + " [" + QString::number( layer->featureCount( symbolIt->second ) ) + "]", itemMap[symbolIt->first] ) );
}
}
void QgsLegendLayer::setShowFeatureCount( bool show, bool update )
{
if ( show != mShowFeatureCount )
{
mShowFeatureCount = show;
if ( update )
{
updateAfterLayerModification();
}
}
}
void QgsLegendLayer::setDrawingOrder( int order )
{
QgsDebugMsg( QString( "order %1: %2=>%3" ).arg( mLyr.layer()->name() ).arg( mDrawingOrder ).arg( order ) );
mDrawingOrder = order;
}
|
kiith-sa/QGIS
|
src/app/legend/qgslegendlayer.cpp
|
C++
|
gpl-2.0
| 18,973
|
#
# Copyright (C) 2014-2015 OpenWrt.org
#
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.
#
include $(TOPDIR)/rules.mk
PKG_NAME:=python3-setuptools
PKG_VERSION:=19.4
PKG_RELEASE:=1
PKG_SOURCE:=setuptools-$(PKG_VERSION).tar.gz
PKG_SOURCE_URL:=https://pypi.python.org/packages/source/s/setuptools/
PKG_MD5SUM:=c5a7d90c1e0acf8c4ec5c2bf31bc25b5
PKG_LICENSE:=PSF
PKG_BUILD_DIR:=$(BUILD_DIR)/setuptools-$(PKG_VERSION)
include $(INCLUDE_DIR)/package.mk
$(call include_mk, python3-package.mk)
define Package/python3-setuptools
SUBMENU:=Python
SECTION:=lang
CATEGORY:=Languages
TITLE:=Tool for installing Python $(PYTHON3_VERSION) packages.
URL:=https://bitbucket.org/pypa/setuptools
DEPENDS:=+python3 +python3-dev +python3-lib2to3
MAINTAINER:=Alexandru Ardelean <ardeleanalex@gmail.com>
endef
define Package/python3-setuptools/description
Easily download, build, install, upgrade, and uninstall Python $(PYTHON3_VERSION) packages
endef
define Build/Compile
$(call Build/Compile/Py3Mod,,\
install --root="$(PKG_INSTALL_DIR)" --prefix="/usr" \
--single-version-externally-managed \
)
endef
define Build/InstallDev
$(INSTALL_DIR) $(PYTHON3_LIB_DIR)
$(CP) \
$(PKG_INSTALL_DIR)$(PYTHON3_PKG_DIR)/* \
$(PYTHON3_LIB_DIR)
endef
define Py3Package/python3-setuptools/install
$(INSTALL_DIR) $(1)/usr/bin
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/easy_install-$(PYTHON3_VERSION) $(1)/usr/bin/
$(LN) easy_install-$(PYTHON3_VERSION) $(1)/usr/bin/easy_install3
endef
$(eval $(call Py3Package,python3-setuptools))
$(eval $(call BuildPackage,python3-setuptools))
|
stas2z/openwrt-witi
|
feeds/packages/lang/python3-setuptools/Makefile
|
Makefile
|
gpl-2.0
| 1,637
|
#!/usr/bin/env python3
# coding: utf-8
import BRT
from collections import namedtuple
import configparser
import os
import logging
from os.path import expanduser
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--submit', help='Execute the submission', action='store_true')
parser.add_argument('-q', '--quiet', help='Jast do the job. Stay quiet', action='store_true')
parser.add_argument('-v', '--verbose', help='Print more status info', action='store_true')
parser.add_argument('-d', '--debug', help='Print debugging info', action='store_true')
args = parser.parse_args()
if args.verbose :
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
if args.debug :
logging.basicConfig(level=os.environ.get("LOGLEVEL", "DEBUG"))
log = logging.getLogger(__name__)
VStar=namedtuple('VStar', 'name comm expos')
config = configparser.ConfigParser()
config.read(expanduser('~/.config/telescope.ini'))
log.info('Log in to telescope.org ...')
brt=BRT.Telescope(config['telescope.org']['user'], config['telescope.org']['password'])
BRT.astrometryAPIkey=config['astrometry.net']['apikey']
def qprint(*ar, **kwar):
if not args.quiet:
print(*ar, **kwar)
def vprint(*ar, **kwar):
if args.verbose and not args.quiet:
print(*ar, **kwar)
obslst=[
VStar('S Ori', comm='Mira AAVSO', expos=120),
VStar('CH Cyg', comm='Symbiotic AAVSO', expos=60),
VStar('SS Cyg', comm='Mira', expos=180),
VStar('EU Cyg', comm='Mira', expos=180),
VStar('IP Cyg', comm='Mira', expos=180),
VStar('V686 Cyg', comm='Mira', expos=180),
#VStar('AS Lac', comm='Mira', expos=120),
VStar('BI Her', comm='Mira', expos=180),
VStar('DX Vul', comm='Mira', expos=180),
VStar('DQ Vul', comm='Mira', expos=180),
VStar('EQ Lyr', comm='Mira', expos=180),
VStar('LX Cyg', comm='AAVSO', expos=180),
]
log.info('Getting observing queue ...')
reqlst=brt.get_user_requests(sort='completion')
q=[r for r in reqlst if int(r['status'])<8]
qn=[r['objectname'] for r in q]
missing = [vs for vs in obslst if vs.name not in qn]
if missing :
if args.submit:
qprint('Submitting missing jobs:')
else:
qprint('Dry run. Add -s to the command line to do actual submissions.')
for vs in missing:
qprint(f'{vs.name.split()[0]:>8} {vs.name.split()[1]} exp:{vs.expos:3.1f}s {vs.comm}', end='')
if args.submit :
r, i = brt.submitVarStar(vs.name, expos=vs.expos, comm=vs.comm)
if r :
qprint(f' => id: {i}', end='')
else :
qprint(f' Failure:{i}', end='')
qprint()
else :
qprint('No missing jobs. Nothing to do!')
log.info('Done.')
|
jochym/brt
|
submit_batch.py
|
Python
|
gpl-2.0
| 2,720
|
-- LessAnimeTabbing. Keep track of your anime without tabbing!
-- Copyright (C) 2014 Linus Sörensen
-- 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.
-- col row width height
--- Defines the GUI class.
-- @return nil.
function define_GUI()
--- GUI class.
-- Contains methods to handle the VLC qt4 interface.
-- @class GUI
-- @field _dialog qt4 dialog userdata object.
-- @field _input Dialog input table.
-- @field _locale Contains an instance of @class Locale.
-- @field _widgets Table containing active qt4 widgets.
-- @field _publisher Optional instance of @class Publisher.
GUI = inherits(nil)
GUI._dialog = nil
GUI._input = {}
GUI._locale = nil
GUI._widgets = {}
GUI._publisher = nil
GUI._new = GUI.new
--- GUI constructor.
-- Creates a new instance of @class GUI.
-- @class GUI
-- @param publisher Optional instance of @class Publisher.
-- @param locale An instance of @class Locale.
-- @return Instance of @class GUI.
function GUI:new(publisher, locale)
return self._new(self, {
_locale = locale,
_publisher = publisher
})
end
--- Publish a message.
-- Publishes a message using the injected publisher if there is one.
-- This method is for internal use only.
-- @class GUI
-- @param msg Message to publish.
-- @param ... Message args to send.
-- @return nil.
function GUI:_publish(msg, ...)
if type(self._publisher) == "table" and type(self._publisher.publish) == "function" then
self._publisher:publish(msg, ...)
end
end
--- Clears input table.
-- Clears all user input data from @field _input.
-- @class GUI
-- @return nil.
function GUI:clear_input()
for k, _ in pairs(self._input) do
self._input[k] = nil
end
end
--- Close the dialog.
-- Closes and deletes the dialog if present.
-- @class GUI
-- @return nil.
function GUI:close()
if self._dialog ~= nil then
self._dialog:hide()
for k, _ in pairs(self._widgets) do
self._widgets[k] = nil
end
-- self._dialog:delete()
self._dialog = nil
collectgarbage()
end
end
--- Get user input data.
-- Attempt to retreive the input data matching supplied key.
-- @class GUI
-- @param key Key to look for.
-- @return Value matching key or nil.
function GUI:get(key)
return self._input[key]
end
--- Get publisher.
-- Getter for @field _publisher.
-- @class GUI
-- @return Instance of @class Publisher or nil if not injected.
function GUI:publisher()
return self._publisher
end
end
|
SouD/LessAnimeTabbing
|
src/GUI.lua
|
Lua
|
gpl-2.0
| 3,450
|
/*
* sleep.c - ACPI sleep support.
*
* Copyright (c) 2005 Alexey Starikovskiy <alexey.y.starikovskiy@intel.com>
* Copyright (c) 2004 David Shaohua Li <shaohua.li@intel.com>
* Copyright (c) 2000-2003 Patrick Mochel
* Copyright (c) 2003 Open Source Development Lab
*
* This file is released under the GPLv2.
*
*/
#include <linux/delay.h>
#include <linux/irq.h>
#include <linux/dmi.h>
#include <linux/device.h>
#include <linux/suspend.h>
#include <linux/reboot.h>
#include <linux/acpi.h>
#include <linux/module.h>
#include <asm/io.h>
#include <acpi/acpi_bus.h>
#include <acpi/acpi_drivers.h>
#include "internal.h"
#include "sleep.h"
static u8 sleep_states[ACPI_S_STATE_COUNT];
static void acpi_sleep_tts_switch(u32 acpi_state)
{
union acpi_object in_arg = { ACPI_TYPE_INTEGER };
struct acpi_object_list arg_list = { 1, &in_arg };
acpi_status status = AE_OK;
in_arg.integer.value = acpi_state;
status = acpi_evaluate_object(NULL, "\\_TTS", &arg_list, NULL);
if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) {
/*
* OS can't evaluate the _TTS object correctly. Some warning
* message will be printed. But it won't break anything.
*/
printk(KERN_NOTICE "Failure in evaluating _TTS object\n");
}
}
static int tts_notify_reboot(struct notifier_block *this,
unsigned long code, void *x)
{
acpi_sleep_tts_switch(ACPI_STATE_S5);
return NOTIFY_DONE;
}
static struct notifier_block tts_notifier = {
.notifier_call = tts_notify_reboot,
.next = NULL,
.priority = 0,
};
static int acpi_sleep_prepare(u32 acpi_state)
{
#ifdef CONFIG_ACPI_SLEEP
/* do we have a wakeup address for S2 and S3? */
if (acpi_state == ACPI_STATE_S3) {
if (!acpi_wakeup_address)
return -EFAULT;
acpi_set_firmware_waking_vector(acpi_wakeup_address);
}
ACPI_FLUSH_CPU_CACHE();
#endif
printk(KERN_INFO PREFIX "Preparing to enter system sleep state S%d\n",
acpi_state);
acpi_enable_wakeup_devices(acpi_state);
acpi_enter_sleep_state_prep(acpi_state);
return 0;
}
static bool acpi_sleep_state_supported(u8 sleep_state)
{
acpi_status status;
u8 type_a, type_b;
status = acpi_get_sleep_type_data(sleep_state, &type_a, &type_b);
return ACPI_SUCCESS(status) && (!acpi_gbl_reduced_hardware
|| (acpi_gbl_FADT.sleep_control.address
&& acpi_gbl_FADT.sleep_status.address));
}
#ifdef CONFIG_ACPI_SLEEP
static u32 acpi_target_sleep_state = ACPI_STATE_S0;
u32 acpi_target_system_state(void)
{
return acpi_target_sleep_state;
}
static bool pwr_btn_event_pending;
/*
* The ACPI specification wants us to save NVS memory regions during hibernation
* and to restore them during the subsequent resume. Windows does that also for
* suspend to RAM. However, it is known that this mechanism does not work on
* all machines, so we allow the user to disable it with the help of the
* 'acpi_sleep=nonvs' kernel command line option.
*/
static bool nvs_nosave;
void __init acpi_nvs_nosave(void)
{
nvs_nosave = true;
}
/*
* The ACPI specification wants us to save NVS memory regions during hibernation
* but says nothing about saving NVS during S3. Not all versions of Windows
* save NVS on S3 suspend either, and it is clear that not all systems need
* NVS to be saved at S3 time. To improve suspend/resume time, allow the
* user to disable saving NVS on S3 if their system does not require it, but
* continue to save/restore NVS for S4 as specified.
*/
static bool nvs_nosave_s3;
void __init acpi_nvs_nosave_s3(void)
{
nvs_nosave_s3 = true;
}
/*
* ACPI 1.0 wants us to execute _PTS before suspending devices, so we allow the
* user to request that behavior by using the 'acpi_old_suspend_ordering'
* kernel command line option that causes the following variable to be set.
*/
static bool old_suspend_ordering;
void __init acpi_old_suspend_ordering(void)
{
old_suspend_ordering = true;
}
static int __init init_old_suspend_ordering(const struct dmi_system_id *d)
{
acpi_old_suspend_ordering();
return 0;
}
static int __init init_nvs_nosave(const struct dmi_system_id *d)
{
acpi_nvs_nosave();
return 0;
}
static struct dmi_system_id __initdata acpisleep_dmi_table[] = {
{
.callback = init_old_suspend_ordering,
.ident = "Abit KN9 (nForce4 variant)",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "http://www.abit.com.tw/"),
DMI_MATCH(DMI_BOARD_NAME, "KN9 Series(NF-CK804)"),
},
},
{
.callback = init_old_suspend_ordering,
.ident = "HP xw4600 Workstation",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"),
DMI_MATCH(DMI_PRODUCT_NAME, "HP xw4600 Workstation"),
},
},
{
.callback = init_old_suspend_ordering,
.ident = "Asus Pundit P1-AH2 (M2N8L motherboard)",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTek Computer INC."),
DMI_MATCH(DMI_BOARD_NAME, "M2N8L"),
},
},
{
.callback = init_old_suspend_ordering,
.ident = "Panasonic CF51-2L",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR,
"Matsushita Electric Industrial Co.,Ltd."),
DMI_MATCH(DMI_BOARD_NAME, "CF51-2L"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VGN-FW41E_H",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VGN-FW41E_H"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VGN-FW21E",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VGN-FW21E"),
},
},
{
.callback = init_nvs_nosave,
<<<<<<< HEAD
=======
.ident = "Sony Vaio VGN-FW21M",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VGN-FW21M"),
},
},
{
.callback = init_nvs_nosave,
>>>>>>> common/android-3.10.y
.ident = "Sony Vaio VPCEB17FX",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VPCEB17FX"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VGN-SR11M",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VGN-SR11M"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Everex StepNote Series",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Everex Systems, Inc."),
DMI_MATCH(DMI_PRODUCT_NAME, "Everex StepNote Series"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VPCEB1Z1E",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VPCEB1Z1E"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VGN-NW130D",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VGN-NW130D"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VPCCW29FX",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VPCCW29FX"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Averatec AV1020-ED2",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "AVERATEC"),
DMI_MATCH(DMI_PRODUCT_NAME, "1000 Series"),
},
},
{
.callback = init_old_suspend_ordering,
.ident = "Asus A8N-SLI DELUXE",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTeK Computer INC."),
DMI_MATCH(DMI_BOARD_NAME, "A8N-SLI DELUXE"),
},
},
{
.callback = init_old_suspend_ordering,
.ident = "Asus A8N-SLI Premium",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTeK Computer INC."),
DMI_MATCH(DMI_BOARD_NAME, "A8N-SLI Premium"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VGN-SR26GN_P",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VGN-SR26GN_P"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VPCEB1S1E",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VPCEB1S1E"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Sony Vaio VGN-FW520F",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "VGN-FW520F"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Asus K54C",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "ASUSTeK Computer Inc."),
DMI_MATCH(DMI_PRODUCT_NAME, "K54C"),
},
},
{
.callback = init_nvs_nosave,
.ident = "Asus K54HR",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "ASUSTeK Computer Inc."),
DMI_MATCH(DMI_PRODUCT_NAME, "K54HR"),
},
},
{},
};
static void acpi_sleep_dmi_check(void)
{
dmi_check_system(acpisleep_dmi_table);
}
/**
* acpi_pm_freeze - Disable the GPEs and suspend EC transactions.
*/
static int acpi_pm_freeze(void)
{
acpi_disable_all_gpes();
acpi_os_wait_events_complete();
acpi_ec_block_transactions();
return 0;
}
/**
* acpi_pre_suspend - Enable wakeup devices, "freeze" EC and save NVS.
*/
static int acpi_pm_pre_suspend(void)
{
acpi_pm_freeze();
return suspend_nvs_save();
}
/**
* __acpi_pm_prepare - Prepare the platform to enter the target state.
*
* If necessary, set the firmware waking vector and do arch-specific
* nastiness to get the wakeup code to the waking vector.
*/
static int __acpi_pm_prepare(void)
{
int error = acpi_sleep_prepare(acpi_target_sleep_state);
if (error)
acpi_target_sleep_state = ACPI_STATE_S0;
return error;
}
/**
* acpi_pm_prepare - Prepare the platform to enter the target sleep
* state and disable the GPEs.
*/
static int acpi_pm_prepare(void)
{
int error = __acpi_pm_prepare();
if (!error)
error = acpi_pm_pre_suspend();
return error;
}
static int find_powerf_dev(struct device *dev, void *data)
{
struct acpi_device *device = to_acpi_device(dev);
const char *hid = acpi_device_hid(device);
return !strcmp(hid, ACPI_BUTTON_HID_POWERF);
}
/**
* acpi_pm_finish - Instruct the platform to leave a sleep state.
*
* This is called after we wake back up (or if entering the sleep state
* failed).
*/
static void acpi_pm_finish(void)
{
struct device *pwr_btn_dev;
u32 acpi_state = acpi_target_sleep_state;
acpi_ec_unblock_transactions();
suspend_nvs_free();
if (acpi_state == ACPI_STATE_S0)
return;
printk(KERN_INFO PREFIX "Waking up from system sleep state S%d\n",
acpi_state);
acpi_disable_wakeup_devices(acpi_state);
acpi_leave_sleep_state(acpi_state);
/* reset firmware waking vector */
acpi_set_firmware_waking_vector((acpi_physical_address) 0);
acpi_target_sleep_state = ACPI_STATE_S0;
acpi_resume_power_resources();
/* If we were woken with the fixed power button, provide a small
* hint to userspace in the form of a wakeup event on the fixed power
* button device (if it can be found).
*
* We delay the event generation til now, as the PM layer requires
* timekeeping to be running before we generate events. */
if (!pwr_btn_event_pending)
return;
pwr_btn_event_pending = false;
pwr_btn_dev = bus_find_device(&acpi_bus_type, NULL, NULL,
find_powerf_dev);
if (pwr_btn_dev) {
pm_wakeup_event(pwr_btn_dev, 0);
put_device(pwr_btn_dev);
}
}
/**
* acpi_pm_end - Finish up suspend sequence.
*/
static void acpi_pm_end(void)
{
/*
* This is necessary in case acpi_pm_finish() is not called during a
* failing transition to a sleep state.
*/
acpi_target_sleep_state = ACPI_STATE_S0;
acpi_sleep_tts_switch(acpi_target_sleep_state);
}
#else /* !CONFIG_ACPI_SLEEP */
#define acpi_target_sleep_state ACPI_STATE_S0
static inline void acpi_sleep_dmi_check(void) {}
#endif /* CONFIG_ACPI_SLEEP */
#ifdef CONFIG_SUSPEND
static u32 acpi_suspend_states[] = {
[PM_SUSPEND_ON] = ACPI_STATE_S0,
[PM_SUSPEND_STANDBY] = ACPI_STATE_S1,
[PM_SUSPEND_MEM] = ACPI_STATE_S3,
[PM_SUSPEND_MAX] = ACPI_STATE_S5
};
/**
* acpi_suspend_begin - Set the target system sleep state to the state
* associated with given @pm_state, if supported.
*/
static int acpi_suspend_begin(suspend_state_t pm_state)
{
u32 acpi_state = acpi_suspend_states[pm_state];
int error = 0;
error = (nvs_nosave || nvs_nosave_s3) ? 0 : suspend_nvs_alloc();
if (error)
return error;
if (sleep_states[acpi_state]) {
acpi_target_sleep_state = acpi_state;
acpi_sleep_tts_switch(acpi_target_sleep_state);
} else {
printk(KERN_ERR "ACPI does not support this state: %d\n",
pm_state);
error = -ENOSYS;
}
return error;
}
/**
* acpi_suspend_enter - Actually enter a sleep state.
* @pm_state: ignored
*
* Flush caches and go to sleep. For STR we have to call arch-specific
* assembly, which in turn call acpi_enter_sleep_state().
* It's unfortunate, but it works. Please fix if you're feeling frisky.
*/
static int acpi_suspend_enter(suspend_state_t pm_state)
{
acpi_status status = AE_OK;
u32 acpi_state = acpi_target_sleep_state;
int error;
ACPI_FLUSH_CPU_CACHE();
switch (acpi_state) {
case ACPI_STATE_S1:
barrier();
status = acpi_enter_sleep_state(acpi_state);
break;
case ACPI_STATE_S3:
error = acpi_suspend_lowlevel();
if (error)
return error;
pr_info(PREFIX "Low-level resume complete\n");
break;
}
/* This violates the spec but is required for bug compatibility. */
acpi_write_bit_register(ACPI_BITREG_SCI_ENABLE, 1);
/* Reprogram control registers */
acpi_leave_sleep_state_prep(acpi_state);
/* ACPI 3.0 specs (P62) says that it's the responsibility
* of the OSPM to clear the status bit [ implying that the
* POWER_BUTTON event should not reach userspace ]
*
* However, we do generate a small hint for userspace in the form of
* a wakeup event. We flag this condition for now and generate the
* event later, as we're currently too early in resume to be able to
* generate wakeup events.
*/
if (ACPI_SUCCESS(status) && (acpi_state == ACPI_STATE_S3)) {
acpi_event_status pwr_btn_status;
acpi_get_event_status(ACPI_EVENT_POWER_BUTTON, &pwr_btn_status);
if (pwr_btn_status & ACPI_EVENT_FLAG_SET) {
acpi_clear_event(ACPI_EVENT_POWER_BUTTON);
/* Flag for later */
pwr_btn_event_pending = true;
}
}
/*
* Disable and clear GPE status before interrupt is enabled. Some GPEs
* (like wakeup GPE) haven't handler, this can avoid such GPE misfire.
* acpi_leave_sleep_state will reenable specific GPEs later
*/
acpi_disable_all_gpes();
/* Allow EC transactions to happen. */
acpi_ec_unblock_transactions_early();
suspend_nvs_restore();
return ACPI_SUCCESS(status) ? 0 : -EFAULT;
}
static int acpi_suspend_state_valid(suspend_state_t pm_state)
{
u32 acpi_state;
switch (pm_state) {
case PM_SUSPEND_ON:
case PM_SUSPEND_STANDBY:
case PM_SUSPEND_MEM:
acpi_state = acpi_suspend_states[pm_state];
return sleep_states[acpi_state];
default:
return 0;
}
}
static const struct platform_suspend_ops acpi_suspend_ops = {
.valid = acpi_suspend_state_valid,
.begin = acpi_suspend_begin,
.prepare_late = acpi_pm_prepare,
.enter = acpi_suspend_enter,
.wake = acpi_pm_finish,
.end = acpi_pm_end,
};
/**
* acpi_suspend_begin_old - Set the target system sleep state to the
* state associated with given @pm_state, if supported, and
* execute the _PTS control method. This function is used if the
* pre-ACPI 2.0 suspend ordering has been requested.
*/
static int acpi_suspend_begin_old(suspend_state_t pm_state)
{
int error = acpi_suspend_begin(pm_state);
if (!error)
error = __acpi_pm_prepare();
return error;
}
/*
* The following callbacks are used if the pre-ACPI 2.0 suspend ordering has
* been requested.
*/
static const struct platform_suspend_ops acpi_suspend_ops_old = {
.valid = acpi_suspend_state_valid,
.begin = acpi_suspend_begin_old,
.prepare_late = acpi_pm_pre_suspend,
.enter = acpi_suspend_enter,
.wake = acpi_pm_finish,
.end = acpi_pm_end,
.recover = acpi_pm_finish,
};
<<<<<<< HEAD
#endif /* CONFIG_SUSPEND */
=======
static void acpi_sleep_suspend_setup(void)
{
int i;
for (i = ACPI_STATE_S1; i < ACPI_STATE_S4; i++)
if (acpi_sleep_state_supported(i))
sleep_states[i] = 1;
suspend_set_ops(old_suspend_ordering ?
&acpi_suspend_ops_old : &acpi_suspend_ops);
}
#else /* !CONFIG_SUSPEND */
static inline void acpi_sleep_suspend_setup(void) {}
#endif /* !CONFIG_SUSPEND */
>>>>>>> common/android-3.10.y
#ifdef CONFIG_HIBERNATION
static unsigned long s4_hardware_signature;
static struct acpi_table_facs *facs;
static bool nosigcheck;
void __init acpi_no_s4_hw_signature(void)
{
nosigcheck = true;
}
static int acpi_hibernation_begin(void)
{
int error;
error = nvs_nosave ? 0 : suspend_nvs_alloc();
if (!error) {
acpi_target_sleep_state = ACPI_STATE_S4;
acpi_sleep_tts_switch(acpi_target_sleep_state);
}
return error;
}
static int acpi_hibernation_enter(void)
{
acpi_status status = AE_OK;
ACPI_FLUSH_CPU_CACHE();
/* This shouldn't return. If it returns, we have a problem */
status = acpi_enter_sleep_state(ACPI_STATE_S4);
/* Reprogram control registers */
acpi_leave_sleep_state_prep(ACPI_STATE_S4);
return ACPI_SUCCESS(status) ? 0 : -EFAULT;
}
static void acpi_hibernation_leave(void)
{
/*
* If ACPI is not enabled by the BIOS and the boot kernel, we need to
* enable it here.
*/
acpi_enable();
/* Reprogram control registers */
acpi_leave_sleep_state_prep(ACPI_STATE_S4);
/* Check the hardware signature */
if (facs && s4_hardware_signature != facs->hardware_signature) {
printk(KERN_EMERG "ACPI: Hardware changed while hibernated, "
"cannot resume!\n");
panic("ACPI S4 hardware signature mismatch");
}
/* Restore the NVS memory area */
suspend_nvs_restore();
/* Allow EC transactions to happen. */
acpi_ec_unblock_transactions_early();
}
static void acpi_pm_thaw(void)
{
acpi_ec_unblock_transactions();
acpi_enable_all_runtime_gpes();
}
static const struct platform_hibernation_ops acpi_hibernation_ops = {
.begin = acpi_hibernation_begin,
.end = acpi_pm_end,
.pre_snapshot = acpi_pm_prepare,
.finish = acpi_pm_finish,
.prepare = acpi_pm_prepare,
.enter = acpi_hibernation_enter,
.leave = acpi_hibernation_leave,
.pre_restore = acpi_pm_freeze,
.restore_cleanup = acpi_pm_thaw,
};
/**
* acpi_hibernation_begin_old - Set the target system sleep state to
* ACPI_STATE_S4 and execute the _PTS control method. This
* function is used if the pre-ACPI 2.0 suspend ordering has been
* requested.
*/
static int acpi_hibernation_begin_old(void)
{
int error;
/*
* The _TTS object should always be evaluated before the _PTS object.
* When the old_suspended_ordering is true, the _PTS object is
* evaluated in the acpi_sleep_prepare.
*/
acpi_sleep_tts_switch(ACPI_STATE_S4);
error = acpi_sleep_prepare(ACPI_STATE_S4);
if (!error) {
if (!nvs_nosave)
error = suspend_nvs_alloc();
if (!error)
acpi_target_sleep_state = ACPI_STATE_S4;
}
return error;
}
/*
* The following callbacks are used if the pre-ACPI 2.0 suspend ordering has
* been requested.
*/
static const struct platform_hibernation_ops acpi_hibernation_ops_old = {
.begin = acpi_hibernation_begin_old,
.end = acpi_pm_end,
.pre_snapshot = acpi_pm_pre_suspend,
.prepare = acpi_pm_freeze,
.finish = acpi_pm_finish,
.enter = acpi_hibernation_enter,
.leave = acpi_hibernation_leave,
.pre_restore = acpi_pm_freeze,
.restore_cleanup = acpi_pm_thaw,
.recover = acpi_pm_finish,
};
static void acpi_sleep_hibernate_setup(void)
{
if (!acpi_sleep_state_supported(ACPI_STATE_S4))
return;
hibernation_set_ops(old_suspend_ordering ?
&acpi_hibernation_ops_old : &acpi_hibernation_ops);
sleep_states[ACPI_STATE_S4] = 1;
if (nosigcheck)
return;
acpi_get_table(ACPI_SIG_FACS, 1, (struct acpi_table_header **)&facs);
if (facs)
s4_hardware_signature = facs->hardware_signature;
}
#else /* !CONFIG_HIBERNATION */
static inline void acpi_sleep_hibernate_setup(void) {}
#endif /* !CONFIG_HIBERNATION */
int acpi_suspend(u32 acpi_state)
{
suspend_state_t states[] = {
[1] = PM_SUSPEND_STANDBY,
[3] = PM_SUSPEND_MEM,
[5] = PM_SUSPEND_MAX
};
if (acpi_state < 6 && states[acpi_state])
return pm_suspend(states[acpi_state]);
if (acpi_state == 4)
return hibernate();
return -EINVAL;
}
<<<<<<< HEAD
#ifdef CONFIG_PM
/**
* acpi_pm_device_sleep_state - return preferred power state of ACPI device
* in the system sleep state given by %acpi_target_sleep_state
* @dev: device to examine; its driver model wakeup flags control
* whether it should be able to wake up the system
* @d_min_p: used to store the upper limit of allowed states range
* Return value: preferred power state of the device on success, -ENODEV on
* failure (ie. if there's no 'struct acpi_device' for @dev)
*
* Find the lowest power (highest number) ACPI device power state that
* device @dev can be in while the system is in the sleep state represented
* by %acpi_target_sleep_state. If @wake is nonzero, the device should be
* able to wake up the system from this sleep state. If @d_min_p is set,
* the highest power (lowest number) device power state of @dev allowed
* in this system sleep state is stored at the location pointed to by it.
*
* The caller must ensure that @dev is valid before using this function.
* The caller is also responsible for figuring out if the device is
* supposed to be able to wake up the system and passing this information
* via @wake.
*/
int acpi_pm_device_sleep_state(struct device *dev, int *d_min_p)
{
acpi_handle handle = DEVICE_ACPI_HANDLE(dev);
struct acpi_device *adev;
char acpi_method[] = "_SxD";
unsigned long long d_min, d_max;
if (!handle || ACPI_FAILURE(acpi_bus_get_device(handle, &adev))) {
printk(KERN_DEBUG "ACPI handle has no context!\n");
return -ENODEV;
}
acpi_method[2] = '0' + acpi_target_sleep_state;
/*
* If the sleep state is S0, we will return D3, but if the device has
* _S0W, we will use the value from _S0W
*/
d_min = ACPI_STATE_D0;
d_max = ACPI_STATE_D3;
/*
* If present, _SxD methods return the minimum D-state (highest power
* state) we can use for the corresponding S-states. Otherwise, the
* minimum D-state is D0 (ACPI 3.x).
*
* NOTE: We rely on acpi_evaluate_integer() not clobbering the integer
* provided -- that's our fault recovery, we ignore retval.
*/
if (acpi_target_sleep_state > ACPI_STATE_S0)
acpi_evaluate_integer(handle, acpi_method, NULL, &d_min);
/*
* If _PRW says we can wake up the system from the target sleep state,
* the D-state returned by _SxD is sufficient for that (we assume a
* wakeup-aware driver if wake is set). Still, if _SxW exists
* (ACPI 3.x), it should return the maximum (lowest power) D-state that
* can wake the system. _S0W may be valid, too.
*/
if (acpi_target_sleep_state == ACPI_STATE_S0 ||
(device_may_wakeup(dev) && adev->wakeup.flags.valid &&
adev->wakeup.sleep_state >= acpi_target_sleep_state)) {
acpi_status status;
acpi_method[3] = 'W';
status = acpi_evaluate_integer(handle, acpi_method, NULL,
&d_max);
if (ACPI_FAILURE(status)) {
if (acpi_target_sleep_state != ACPI_STATE_S0 ||
status != AE_NOT_FOUND)
d_max = d_min;
} else if (d_max < d_min) {
/* Warn the user of the broken DSDT */
printk(KERN_WARNING "ACPI: Wrong value from %s\n",
acpi_method);
/* Sanitize it */
d_min = d_max;
}
}
if (d_min_p)
*d_min_p = d_min;
return d_max;
}
#endif /* CONFIG_PM */
#ifdef CONFIG_PM_SLEEP
/**
* acpi_pm_device_run_wake - Enable/disable wake-up for given device.
* @phys_dev: Device to enable/disable the platform to wake-up the system for.
* @enable: Whether enable or disable the wake-up functionality.
*
* Find the ACPI device object corresponding to @pci_dev and try to
* enable/disable the GPE associated with it.
*/
int acpi_pm_device_run_wake(struct device *phys_dev, bool enable)
{
struct acpi_device *dev;
acpi_handle handle;
if (!device_run_wake(phys_dev))
return -EINVAL;
handle = DEVICE_ACPI_HANDLE(phys_dev);
if (!handle || ACPI_FAILURE(acpi_bus_get_device(handle, &dev))) {
dev_dbg(phys_dev, "ACPI handle has no context in %s!\n",
__func__);
return -ENODEV;
}
if (enable) {
acpi_enable_wakeup_device_power(dev, ACPI_STATE_S0);
acpi_enable_gpe(dev->wakeup.gpe_device, dev->wakeup.gpe_number);
} else {
acpi_disable_gpe(dev->wakeup.gpe_device, dev->wakeup.gpe_number);
acpi_disable_wakeup_device_power(dev);
}
return 0;
}
/**
* acpi_pm_device_sleep_wake - enable or disable the system wake-up
* capability of given device
* @dev: device to handle
* @enable: 'true' - enable, 'false' - disable the wake-up capability
*/
int acpi_pm_device_sleep_wake(struct device *dev, bool enable)
{
acpi_handle handle;
struct acpi_device *adev;
int error;
if (!device_can_wakeup(dev))
return -EINVAL;
handle = DEVICE_ACPI_HANDLE(dev);
if (!handle || ACPI_FAILURE(acpi_bus_get_device(handle, &adev))) {
dev_dbg(dev, "ACPI handle has no context in %s!\n", __func__);
return -ENODEV;
}
error = enable ?
acpi_enable_wakeup_device_power(adev, acpi_target_sleep_state) :
acpi_disable_wakeup_device_power(adev);
if (!error)
dev_info(dev, "wake-up capability %s by ACPI\n",
enable ? "enabled" : "disabled");
return error;
}
#endif /* CONFIG_PM_SLEEP */
=======
>>>>>>> common/android-3.10.y
static void acpi_power_off_prepare(void)
{
/* Prepare to power off the system */
acpi_sleep_prepare(ACPI_STATE_S5);
acpi_disable_all_gpes();
}
static void acpi_power_off(void)
{
/* acpi_sleep_prepare(ACPI_STATE_S5) should have already been called */
printk(KERN_DEBUG "%s called\n", __func__);
local_irq_disable();
acpi_enter_sleep_state(ACPI_STATE_S5);
}
int __init acpi_sleep_init(void)
{
<<<<<<< HEAD
acpi_status status;
u8 type_a, type_b;
#ifdef CONFIG_SUSPEND
int i = 0;
#endif
=======
char supported[ACPI_S_STATE_COUNT * 3 + 1];
char *pos = supported;
int i;
>>>>>>> common/android-3.10.y
if (acpi_disabled)
return 0;
acpi_sleep_dmi_check();
<<<<<<< HEAD
sleep_states[ACPI_STATE_S0] = 1;
printk(KERN_INFO PREFIX "(supports S0");
=======
>>>>>>> common/android-3.10.y
sleep_states[ACPI_STATE_S0] = 1;
acpi_sleep_suspend_setup();
acpi_sleep_hibernate_setup();
if (acpi_sleep_state_supported(ACPI_STATE_S5)) {
sleep_states[ACPI_STATE_S5] = 1;
pm_power_off_prepare = acpi_power_off_prepare;
pm_power_off = acpi_power_off;
}
supported[0] = 0;
for (i = 0; i < ACPI_S_STATE_COUNT; i++) {
if (sleep_states[i])
pos += sprintf(pos, " S%d", i);
}
pr_info(PREFIX "(supports%s)\n", supported);
/*
* Register the tts_notifier to reboot notifier list so that the _TTS
* object can also be evaluated when the system enters S5.
*/
register_reboot_notifier(&tts_notifier);
return 0;
}
|
javelinanddart/android_kernel_3.10_ville
|
drivers/acpi/sleep.c
|
C
|
gpl-2.0
| 26,227
|
/*
* Copyright (C) 2008-2009 Martin Willi
* Hochschule fuer Technik Rapperswil
*
* 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. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
#include "eap_aka_3gpp2_plugin.h"
#include "eap_aka_3gpp2_card.h"
#include "eap_aka_3gpp2_provider.h"
#include "eap_aka_3gpp2_functions.h"
#include <daemon.h>
typedef struct private_eap_aka_3gpp2_t private_eap_aka_3gpp2_t;
/**
* Private data of an eap_aka_3gpp2_t object.
*/
struct private_eap_aka_3gpp2_t {
/**
* Public eap_aka_3gpp2_plugin_t interface.
*/
eap_aka_3gpp2_plugin_t public;
/**
* SIM card
*/
eap_aka_3gpp2_card_t *card;
/**
* SIM provider
*/
eap_aka_3gpp2_provider_t *provider;
/**
* AKA functions
*/
eap_aka_3gpp2_functions_t *functions;
};
/**
* Implementation of eap_aka_3gpp2_t.destroy.
*/
static void destroy(private_eap_aka_3gpp2_t *this)
{
charon->sim->remove_card(charon->sim, &this->card->card);
charon->sim->remove_provider(charon->sim, &this->provider->provider);
this->card->destroy(this->card);
this->provider->destroy(this->provider);
this->functions->destroy(this->functions);
free(this);
}
/**
* See header
*/
plugin_t *eap_aka_3gpp2_plugin_create()
{
private_eap_aka_3gpp2_t *this = malloc_thing(private_eap_aka_3gpp2_t);
this->public.plugin.destroy = (void(*)(plugin_t*))destroy;
this->functions = eap_aka_3gpp2_functions_create();
if (!this->functions)
{
free(this);
return NULL;
}
this->card = eap_aka_3gpp2_card_create(this->functions);
this->provider = eap_aka_3gpp2_provider_create(this->functions);
charon->sim->add_card(charon->sim, &this->card->card);
charon->sim->add_provider(charon->sim, &this->provider->provider);
return &this->public.plugin;
}
|
ramarnat/astaro-strongswan
|
src/libcharon/plugins/eap_aka_3gpp2/eap_aka_3gpp2_plugin.c
|
C
|
gpl-2.0
| 2,190
|
<?php
namespace Damis\AlgorithmBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class DamisAlgorithmBundle extends Bundle
{
}
|
InScience/DAMIS-GUI
|
src/Damis/AlgorithmBundle/DamisAlgorithmBundle.php
|
PHP
|
gpl-2.0
| 136
|
# $Id: ts_aws.rb,v 1.4 2008/06/16 20:07:19 ianmacd Exp $
#
require 'test/unit'
require 'tc_amazon'
require 'tc_aws'
require 'tc_serialisation'
require 'tc_operation_request'
require 'tc_item_search'
require 'tc_multiple_operation'
require 'tc_shopping_cart'
|
res0nat0r/ruby-aws
|
test/ts_aws.rb
|
Ruby
|
gpl-2.0
| 260
|
/***************************************************************************
* Copyright (C) 2008 by Alexey Balakin *
* mathgl.abalakin@gmail.com *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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 <QLabel>
#include <QLayout>
#include <QLineEdit>
#include <QComboBox>
#include <QPushButton>
#include <QMessageBox>
#include "opt_dlg.h"
//-----------------------------------------------------------------------------
OptionDialog::OptionDialog(QWidget *parent) : QDialog(parent)
{
setWindowTitle(tr("UDAV - Add options"));
QHBoxLayout *a;
QGridLayout *g;
QLabel *lbl;
QPushButton *b;
QVBoxLayout *o = new QVBoxLayout(this); //o->setSpacing(6);
g = new QGridLayout(); o->addLayout(g);
lbl = new QLabel(tr("X-range"),this); g->addWidget(lbl,0,0);
x1 = new QLineEdit(this); g->addWidget(x1,0,1);
x2 = new QLineEdit(this); g->addWidget(x2,0,2);
lbl = new QLabel(tr("Y-range"),this); g->addWidget(lbl,0,3);
y1 = new QLineEdit(this); g->addWidget(y1,0,4);
y2 = new QLineEdit(this); g->addWidget(y2,0,5);
lbl = new QLabel(tr("Z-range"),this); g->addWidget(lbl,1,0);
z1 = new QLineEdit(this); g->addWidget(z1,1,1);
z2 = new QLineEdit(this); g->addWidget(z2,1,2);
lbl = new QLabel(tr("C-range"),this); g->addWidget(lbl,1,3);
c1 = new QLineEdit(this); g->addWidget(c1,1,4);
c2 = new QLineEdit(this); g->addWidget(c2,1,5);
lbl = new QLabel(tr("Alpha"),this); g->addWidget(lbl,2,0);
alpha = new QLineEdit(this); g->addWidget(alpha,2,1);
lbl = new QLabel(tr("Mesh num"),this); g->addWidget(lbl,2,3);
mn = new QLineEdit(this); g->addWidget(mn,2,4);
lbl = new QLabel(tr("Ambient"),this); g->addWidget(lbl,3,0);
amb = new QLineEdit(this); g->addWidget(amb,3,1);
lbl = new QLabel(tr("Diffuse"),this); g->addWidget(lbl,3,3);
dif = new QLineEdit(this); g->addWidget(dif,3,4);
lbl = new QLabel(tr("Cutting"),this); g->addWidget(lbl,4,0);
cut = new QComboBox(this); g->addWidget(cut,4,1);
cut->insertItem(0,tr("default")); cut->insertItem(1,tr("on")); cut->insertItem(2,tr("off"));
lbl = new QLabel(tr("Light"),this); g->addWidget(lbl,4,3);
lig = new QComboBox(this); g->addWidget(lig,4,4);
lig->insertItem(0,tr("default")); lig->insertItem(1,tr("on")); lig->insertItem(2,tr("off"));
lbl = new QLabel(tr("Value"),this); g->addWidget(lbl,5,0);
val = new QLineEdit(this); g->addWidget(val,5,1);
lbl = new QLabel(tr("Size"),this); g->addWidget(lbl,5,3);
fs = new QLineEdit(this); g->addWidget(fs,5,4);
a = new QHBoxLayout(); o->addLayout(a);
lbl = new QLabel(tr("Legend"),this); a->addWidget(lbl);
leg = new QLineEdit(this); a->addWidget(leg);
a = new QHBoxLayout(); o->addLayout(a);
a->addStretch(1);
b = new QPushButton(tr("Cancel"), this); a->addWidget(b);
connect(b, SIGNAL(clicked()),this, SLOT(reject()));
b = new QPushButton(tr("OK"), this); a->addWidget(b);
connect(b, SIGNAL(clicked()),this, SLOT(prepareResult()));
b->setDefault(true);
}
//-----------------------------------------------------------------------------
OptionDialog::~OptionDialog() {}
//-----------------------------------------------------------------------------
void OptionDialog::prepareResult()
{
result = "";
if(!x1->text().isEmpty() && !x2->text().isEmpty())
result = result + "; xrange "+x1->text()+" "+x2->text();
if((x1->text().isEmpty()) ^ (x2->text().isEmpty()))
{
QMessageBox::warning(this,tr("UDAV - command options"), tr("Both fields in xrange must be filled"));
return;
}
if(!y1->text().isEmpty() && !y2->text().isEmpty())
result = result + "; yrange "+y1->text()+" "+y2->text();
if((y1->text().isEmpty()) ^ (y2->text().isEmpty()))
{
QMessageBox::warning(this,tr("UDAV - command options"), tr("Both fields in yrange must be filled"));
return;
}
if(!z1->text().isEmpty() && !z2->text().isEmpty())
result = result + "; zrange "+z1->text()+" "+z2->text();
if((z1->text().isEmpty()) ^ (z2->text().isEmpty()))
{
QMessageBox::warning(this,tr("UDAV - command options"), tr("Both fields in zrange must be filled"));
return;
}
if(!c1->text().isEmpty() && !c2->text().isEmpty())
result = result + "; crange "+c1->text()+" "+c2->text();
if((c1->text().isEmpty()) ^ (c2->text().isEmpty()))
{
QMessageBox::warning(this,tr("UDAV - command options"), tr("Both fields in crange must be filled"));
return;
}
if(!val->text().isEmpty()) result = result+"; value "+val->text();
if(!alpha->text().isEmpty())result = result+"; alpha "+alpha->text();
if(!amb->text().isEmpty()) result = result+"; ambient "+amb->text();
if(!dif->text().isEmpty()) result = result+"; diffuse "+dif->text();
if(!mn->text().isEmpty()) result = result+"; meshnum "+mn->text();
if(!fs->text().isEmpty()) result = result+"; size "+fs->text();
if(cut->currentIndex()==1) result = result+"; cut on";
if(cut->currentIndex()==2) result = result+"; cut off";
if(lig->currentIndex()==1) result = result+"; light on";
if(lig->currentIndex()==2) result = result+"; light off";
if(!leg->text().isEmpty()) result = result+"; legend '"+leg->text()+"'";
accept();
}
//-----------------------------------------------------------------------------
|
drazenzadravec/nequeo
|
Tools/Math/MathGL/mathgl-2.2.2.1/udav/opt_dlg.cpp
|
C++
|
gpl-2.0
| 6,346
|
#!/usr/bin/env python3
#
# Script for polling N64/GC SI bus devices
#
# This script uses the serial bridge and pool in loops
# for the buttons status.
#
# It currently supports N64 controllers, N64 mouses & GameCube controllers.
#
# --Jacques Gagnon <darthcloud@gmail.com>
#
from bus import Bus
from collections import namedtuple, OrderedDict
import struct, time, os, sys
bmap = namedtuple('status', 'name mask color')
identity_req = namedtuple('identity_req', 'cmd')
status_req = namedtuple('status_req', 'cmd')
read_req = namedtuple('read_req', 'cmd address')
write_req = namedtuple('write_req', 'cmd address data')
dol_status_req = namedtuple('dol_status_req', 'cmd unknown rumble')
dol_wb_assoc_req = namedtuple('dol_wb_assoc_req', 'cmd id')
identity_resp = namedtuple('identity_resp', 'id info')
status_resp = namedtuple('status_resp', 'buttons x_axis y_axis')
dol_status_resp = namedtuple('dol_status_resp', 'buttons x_axis y_axis cx_axis cy_axis l_trigger r_trigger')
RED='\x1b[1;91m'
GREEN='\x1b[1;92m'
YELLOW='\x1b[1;93m'
BLUE='\x1b[1;94m'
MAGENTA='\x1b[1;95m'
CYAN='\x1b[1;96m'
LGRAY='\x1b[1;37m'
DGRAY='\x1b[1;90m'
END='\x1b[0m'
IDENTIFY = 0x00
STATUS = 0x01
READ = 0x02
WRITE = 0x03
DOL_STATUS = 0x40
WB_INIT = 0x4E
MOUSE = 0x02
NUS = 0x05
DOL = 0x09
WB_DOWN = 0xA8
WB_AUTH = 0xE9
WB_ASSOC = 0xEB
EMPTY = 0x00
OCCUPY = 0x01
EMPTIED = 0x02
INSERT = 0x03
BUTTON = {NUS:OrderedDict(
[('buttons',[bmap('A',0x8000,BLUE),
bmap('B',0x4000,GREEN),
bmap('Z',0x2000,LGRAY),
bmap('St',0x1000,RED),
bmap('Up',0x0800,LGRAY),
bmap('Dn',0x0400,LGRAY),
bmap('Lt',0x0200,LGRAY),
bmap('Rt',0x0100,LGRAY),
bmap('L',0x0020,LGRAY),
bmap('R',0x0010,LGRAY),
bmap('CUp',0x0008,YELLOW),
bmap('CDn',0x0004,YELLOW),
bmap('CLt',0x0002,YELLOW),
bmap('CRt',0x0001,YELLOW)]),
('x_axis', [bmap('X',0xFF,LGRAY)]),
('y_axis', [bmap('Y',0xFF,LGRAY)])]),
DOL:OrderedDict(
[('buttons',[bmap('St',0x1000,LGRAY),
bmap('Y',0x0800,LGRAY),
bmap('X',0x0400,LGRAY),
bmap('B',0x0200,RED),
bmap('A',0x0100,CYAN),
bmap('L',0x0040,LGRAY),
bmap('R',0x0020,LGRAY),
bmap('Z',0x0010,MAGENTA),
bmap('Up',0x0008,LGRAY),
bmap('Dn',0x0004,LGRAY),
bmap('Rt',0x0002,LGRAY),
bmap('Lt',0x0001,LGRAY)]),
('x_axis', [bmap('X',0xFF,LGRAY)]),
('y_axis', [bmap('Y',0xFF,LGRAY)]),
('cx_axis', [bmap('CX',0xFF,YELLOW)]),
('cy_axis', [bmap('CY',0xFF,YELLOW)]),
('l_trigger', [bmap('AL',0xFF,LGRAY)]),
('r_trigger', [bmap('AR',0xFF,LGRAY)])])}
class Bus(Bus):
def identify(self):
reply = self.bridge.write(bytes([IDENTIFY]), 3)[1]
if reply[0] == MOUSE:
return {'system':NUS, 'type':'mouse'}
elif reply[0] == NUS:
if reply[2] == EMPTY:
return {'system':NUS, 'type':'controller', 'slot':'Empty '}
elif reply[2] == OCCUPY:
return {'system':NUS, 'type':'controller', 'slot':'Occupy '}
elif reply[2] == EMPTIED:
return {'system':NUS, 'type':'controller', 'slot':'Emptied'}
elif reply[2] == INSERT:
return {'system':NUS, 'type':'controller', 'slot':'Insert '}
else:
print("Unknown N64 controller slot state: {}".format(reply))
sys.exit()
elif reply[0] == DOL:
return {'system':DOL, 'type':'controller'}
elif reply[0] == WB_DOWN:
return {'system':WB_DOWN, 'type':'wavebird'}
elif reply[0] == WB_AUTH:
return {'system':WB_AUTH, 'type':'wavebird', 'id':reply[-2:]}
elif reply[0] == WB_ASSOC:
return {'system':DOL, 'type':'wavebird'}
else:
print("Unknown device identity: {}".format(reply))
sys.exit()
def status(self, system):
if system == NUS:
reply = self.bridge.write(bytes([STATUS]), 4)[1]
return status_resp._make(struct.unpack('>H2b', reply))
elif system == DOL:
reply = self.bridge.write(struct.pack(">BH", DOL_STATUS, 0x0300), 8)[1]
return dol_status_resp._make(struct.unpack('>H6B', reply))
else:
print("Unknown system ID: {}".format(system))
sys.exit()
def wavebird_init(self, id):
return self.bridge.write(struct.pack(">BBB", WB_INIT, (id[0] | 0x20) & 0x10, id[1]), 3)[1]
def poll():
os.system('setterm -cursor off')
interface = Bus()
device = interface.identify()
time.sleep(0.02)
while device['system'] == WB_DOWN:
device = interface.identify()
time.sleep(1)
if device['system'] == WB_AUTH:
interface.wavebird_init(device['id'])
try:
while 1:
device = interface.identify()
time.sleep(0.02)
status = interface.status(device['system'])
for field, values in BUTTON[device['system']].items():
for value in values:
if value.mask != 0xFF:
print("{}{}{} ".format(value.color if getattr(status, field) & value.mask else DGRAY, value.name, END), end='')
else:
print("{}{}:{:+03X}{} ".format(value.color, value.name, getattr(status, field), END), end='')
if 'slot' in device:
print("slot:{}".format(device['slot']), end='')
print("\r", end='')
time.sleep(0.02)
except KeyboardInterrupt:
pass
os.system('setterm -cursor on')
print("")
if __name__ == "__main__":
poll()
### The End ###
|
darthcloud/cube64-dx
|
notes/poll.py
|
Python
|
gpl-2.0
| 6,079
|
/****************************************************************************
** Meta object code from reading C++ file 'mainwindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.2.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../qt_gl_gst/mainwindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'mainwindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.2.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_MainWindow_t {
QByteArrayData data[1];
char stringdata[12];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
offsetof(qt_meta_stringdata_MainWindow_t, stringdata) + ofs \
- idx * sizeof(QByteArrayData) \
)
static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = {
{
QT_MOC_LITERAL(0, 0, 10)
},
"MainWindow\0"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MainWindow[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObject MainWindow::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow.data,
qt_meta_data_MainWindow, qt_static_metacall, 0, 0}
};
const QMetaObject *MainWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MainWindow::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata))
return static_cast<void*>(const_cast< MainWindow*>(this));
return QMainWindow::qt_metacast(_clname);
}
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
|
dallinbriggs/Multi_Sensor_UAV_Environment
|
src/build-qt_gl_gst-Desktop-Debug/moc_mainwindow.cpp
|
C++
|
gpl-2.0
| 2,584
|
/*
belle-sip - SIP (RFC3261) library.
Copyright (C) 2010-2018 Belledonne Communications SARL
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/>.
*/
#ifndef belle_sip_resolver_h
#define belle_sip_resolver_h
typedef struct belle_sip_dns_srv belle_sip_dns_srv_t;
#define BELLE_SIP_DNS_SRV(obj) BELLE_SIP_CAST(obj,belle_sip_dns_srv_t)
typedef struct belle_sip_resolver_context belle_sip_resolver_context_t;
#define BELLE_SIP_RESOLVER_CONTEXT(obj) BELLE_SIP_CAST(obj,belle_sip_resolver_context_t)
/**
* Callback prototype for asynchronous DNS SRV resolution.
* The srv_list contains struct dns_srv elements that must be taken and (possibly later) freed by the callee, using belle_sip_free().
*/
typedef void (*belle_sip_resolver_srv_callback_t)(void *data, const char *name, belle_sip_list_t *srv_list, uint32_t ttl);
/**
* Callback prototype for asynchronous DNS A and AAAA resolution.
* The ai_list contains addrinfo elements that must be taken and (possibly later) freed by the callee, using freeaddrinfo().
* These elements are linked by their ai_next field.
**/
typedef void (*belle_sip_resolver_callback_t)(void *data, const char *name, struct addrinfo *ai_list, uint32_t ttl);
BELLE_SIP_BEGIN_DECLS
BELLESIP_EXPORT const char *belle_sip_dns_srv_get_target(const belle_sip_dns_srv_t *obj);
BELLESIP_EXPORT unsigned short belle_sip_dns_srv_get_priority(const belle_sip_dns_srv_t *obj);
BELLESIP_EXPORT unsigned short belle_sip_dns_srv_get_weight(const belle_sip_dns_srv_t *obj);
BELLESIP_EXPORT unsigned short belle_sip_dns_srv_get_port(const belle_sip_dns_srv_t *obj);
/**
* Asynchronously performs DNS SRV followed A/AAAA query. Automatically fallbacks to A/AAAA if SRV isn't found.
* @param stack the belle_sip_stack_t, used to schedule asynchronous execution.
* @param service the queried service ("sip", "stun", "turn"...)
* @param transport the queried transport ("udp", "tcp", "tls")
* @param name the SIP domain name
* @param port a port that will be filled in the addrinfo list returned by the callback, for the case where no SRV records are found.
* @param family address family expected in the addrinfo result list. AF_INET or AF_INET6. If AF_INET6 is used but no IPv6 records are found, the IPv4 addresses
* will be returned as IPv6 with v4 mapping (AI_V4MAPPED).
* @param cb a callback function that will be called to notify the results.
* @param data a user pointer passed through the callback as first argument.
* @return a #belle_sip_resolver_context_t that can be used to cancel the resolution if needed. The context must have been ref'd with belle_sip_object_ref().
**/
BELLESIP_EXPORT belle_sip_resolver_context_t * belle_sip_stack_resolve(belle_sip_stack_t *stack, const char *service, const char *transport, const char *name, int port, int family,
belle_sip_resolver_callback_t cb, void *data);
/**
* Asynchronously performs DNS A or AAAA query.
* @param stack the belle_sip_stack_t, used to schedule asynchronous execution.
* @param name the SIP domain name
* @param port a port that will be filled in the addrinfo list returned by the callback, for the case where no SRV records are found.
* @param family address family expected in the addrinfo result list. AF_INET or AF_INET6. If AF_INET6 is used but no IPv4 records are found, the IPv4 addresses
* will be returned as IPv6 with v4 mapping (AI_V4MAPPED).
* @param cb a callback function that will be called to notify the results.
* @param data a user pointer passed through the callback as first argument.
* @return a #belle_sip_resolver_context_t that can be used to cancel the resolution if needed. The context must have been ref'd with belle_sip_object_ref().
**/
BELLESIP_EXPORT belle_sip_resolver_context_t * belle_sip_stack_resolve_a(belle_sip_stack_t *stack, const char *name, int port, int family, belle_sip_resolver_callback_t cb, void *data);
/**
* Asynchronously performs DNS SRV query.
* @return a #belle_sip_resolver_context_t that can be used to cancel the resolution if needed. The context must have been ref'd with belle_sip_object_ref().
**/
BELLESIP_EXPORT belle_sip_resolver_context_t * belle_sip_stack_resolve_srv(belle_sip_stack_t *stack, const char *service, const char *transport, const char *name, belle_sip_resolver_srv_callback_t cb, void *data);
/**
* Cancel a pending asynchronous DNS query. The context is unref'd automatically, as a result the context shall no longer be used after this call.
* If the query is already performed, cancellation has no effect, but context is unref'd anyway.
**/
BELLESIP_EXPORT void belle_sip_resolver_context_cancel(belle_sip_resolver_context_t *ctx);
/**
* Lookups the source address from local interface that can be used to connect to a destination address.
* local_port is only used to be assigned into the result source address.
* This function always puts something in src and srclen (the loopback address) even if anything fails.
* The return code is 0 if successful, or -errno if an error was encoutered. Typical error is -ENETUNREACH when IPv6 network is not reachable.
**/
BELLESIP_EXPORT int belle_sip_get_src_addr_for(const struct sockaddr *dest, socklen_t destlen, struct sockaddr *src, socklen_t *srclen, int local_port);
BELLE_SIP_END_DECLS
#endif
|
raj-bhatia/grooveip-ios-public
|
submodules/belle-sip/include/belle-sip/resolver.h
|
C
|
gpl-2.0
| 5,830
|
package argendata.dao.semantic.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import argendata.dao.semantic.ConceptDao;
import argendata.model.skos.Concept;
import argendata.model.skos.ConceptScheme;
import argendata.util.Properties;
@Repository
public class ElmoConceptDao extends ElmoGenericDao<Concept> implements ConceptDao {
private RepositoryConnectionManager connectionManager;
@Autowired
public ElmoConceptDao(RepositoryConnectionManager cm, Properties properties) {
this.connectionManager = cm;
super.setManager(connectionManager.getManager());
super.setProperties(properties);
}
@Override
public Iterable<Concept> getAll(){
return super.getAll();
}
public Concept newConcept(String title) {
Concept resp = super.newElement("Concept:"+title);
return resp;
}
public ConceptScheme newConceptScheme(String title) {
ConceptScheme resp = super.newElement("ConceptScheme:"+title,ConceptScheme.class);
return resp;
}
}
|
sdvf/itba-proyectofinal-2011
|
src/main/java/argendata/dao/semantic/impl/ElmoConceptDao.java
|
Java
|
gpl-2.0
| 1,068
|
/* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein
* is confidential and proprietary to MediaTek Inc. and/or its licensors.
* Without the prior written permission of MediaTek inc. and/or its licensors,
* any reproduction, modification, use or disclosure of MediaTek Software,
* and information contained herein, in whole or in part, shall be strictly prohibited.
*
* MediaTek Inc. (C) 2011. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
* THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
* CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
* SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
* CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek Software")
* have been modified by MediaTek Inc. All revisions are subject to any receiver's
* applicable license agreements with MediaTek Inc.
*/
#ifndef _LIBMTK_CIPHER_EXPORT_H
#define _LIBMTK_CIPHER_EXPORT_H
#define HEVC_BLK_LEN (20480) // bytes
#define HEVC_MOD "HEVC_MOD"
#define HEVC_NANO 1000000000ULL
#define HEVC_CIPHER_LEN (102400) // bytes
typedef struct
{
unsigned char buf[HEVC_BLK_LEN];
unsigned int len;
} HEVC_BLK;
typedef enum
{
VIDEO_ENCRYPT_CODEC_NONE = 0x0,
VIDEO_ENCRYPT_CODEC_HEVC_ENC = 0x1,
VIDEO_ENCRYPT_CODEC_HEVC_DEC = 0x2,
VIDEO_ENCRYPT_CODEC_MAX = 0xffffffff
} VIDEO_ENCRYPT_CODEC_T;
typedef int (*hevc_api_funp)(HEVC_BLK *p_hevc_blk);
typedef int (*hevc_api_initk_funp)(unsigned char *key, unsigned int klen);
#define SEC_OK 0x0
#define SEC_FAIL 0x1
/* HEVC shared lib*/
#define ERR_HEVC_NOT_CORRECT_MODE 0x10000
#define ERR_HEVC_DATA_NOT_ALIGNED 0x10001
#define ERR_HEVC_ENC_IOCTL_FAIL 0x10002
#define ERR_HEVC_DEC_IOCTL_FAIL 0x10002
#define ERR_HEVC_CIPHER_UT_FAIL 0x10003
#define ERR_HEVC_DATA_IS_NULL 0x10004
#define ERR_HEVC_DATA_LENGTH_NOT_VALID 0x10005
#define ERR_HEVC_SW_ENC_ERROR 0x10006
#define ERR_HEVC_SW_DEC_ERROR 0x10007
#define ERR_HEVC_INIT_SW_KEY_ERROR 0x10008
/* HEVC sample*/
#define ERR_HEVC_CIPHER_LIB_NOT_FOUND 0x20001
#define ERR_HEVC_SW_DEC_BLOCK_SYM_NOT_FOUND 0x20002
#define ERR_HEVC_HW_ENC_BLOCK_SYM_NOT_FOUND 0x20003
#define ERR_HEVC_INIT_SW_KEY_SYM_NOT_FOUND 0x20004
#define ERR_HEVC_INPUT_FILE_NOT_FOUND 0x20005
#define ERR_HEVC_OUTPUT_FILE_NOT_FOUND 0x20006
#define ERR_HEVC_SW_DEC_FILE_SYM_NOT_FOUND 0x20007
#define ERR_HEVC_SW_DEC_FILE_FAILED 0x20008
#define ERR_HEVC_UNKNOWN 0x2FFFF
/* Define LOG LEVEL*/
#define SEC_LOG_TRACE 0 //For source code trace
#define SEC_LOG_DEBUG 0 //For debug purpose
#define SEC_LOG_ERROR 1 //For critical error dump
#define SEC_LOG_INFO 1 //For information to know when processing in normal
/* DEBUG MACRO */
#define SMSG_TRACE(...) \
do { if (SEC_LOG_TRACE) printf(__VA_ARGS__); } while (0)
#define SMSG_DEBUG(...) \
do { if (SEC_LOG_DEBUG) printf(__VA_ARGS__); } while (0)
#define SMSG_ERROR(...) \
do { if (SEC_LOG_ERROR) printf(__VA_ARGS__); } while (0)
#define SMSG_INFO(...) \
do { if (SEC_LOG_INFO) printf(__VA_ARGS__); } while (0)
#define HEVC_ENCRYTP_FILE_PATH "/data/mediaserver"
#define HEVC_ENC_SW_ENCRYPT_FILE_PATH "/system/lib/libhevce_sb.ca7.android.so"
#define HEVC_ENC_HW_ENCRYPT_FILE_PATH "/data/mediaserver/sb.ca7.android_hwenc.so"
#define HEVC_ENC_HW_DECRYPT_FILE_PATH "/data/mediaserver/sb.ca7.android_hwdec.so"
#define HEVC_DEC_SW_ENCRYTP_FILE_PATH "/system/lib/libHEVCdec_sa.ca7.android.so"
#define HEVC_DEC_HW_ENCRYPT_FILE_PATH "/data/mediaserver/dec_sa.ca7.android_hwenc.so"
#define HEVC_DEC_HW_DECRYPT_FILE_PATH "/data/mediaserver/dec_sa.ca7.android_hwdec.so"
#endif /*_LIBMTK_CIPHER_EXPORT_H*/
|
evil-god/runbo-q5x6
|
mediatek/kernel/include/linux/libmtk_cipher_export.h
|
C
|
gpl-2.0
| 5,428
|
# Sites
This directory contains test sites which are used for running and testing
SiteDiff using rspec tests.
|
evolvingweb/sitediff
|
spec/sites/README.md
|
Markdown
|
gpl-2.0
| 111
|
{% load markup %}
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html> <head>
<title>WebTest</title>
<script src="/appmedia/omeroweb/javascript/jquery_1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">
function openPopup(url) {
owindow = window.open(url, '', config='height=600,width=850,left=50,top=50,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,directories=no,status=no');
if(!owindow.closed) owindow.focus();
return false;
}
$(document).ready(function()
{
$('.can-collapse').click(function () {
$(this).toggleClass('closed').next().slideToggle();
});
$('.can-collapse.defclose').each(function () {
$(this).removeClass('defclose').toggleClass('closed').next().hide();
});
});
</script>
</head>
<body>
<h1>WebTest</h1>
<div>
<div id="annotation_tabs" class="ui-tabs">
{% if image %}
<!-- VIEWER -->
<div id="preview_tab">
<h1>{{ image.name }}</h1>
<div class="miniview" id="viewport"></div>
</div>
{% endif %}
<!-- METADATA -->
<div id="metadata_tab">
<table>
<tr><td rowspan="2"><a href="#" onclick="return openPopup('{% url image_viewer image.id %}')"><img id="{{ image.id }}" src="{% url render_thumbnail_resize 64 image.id %}" alt="image" title="image" class="thumbnail"/></a></td>
<td><label>{{ image.name }}</label></td></tr>
<tr><td>Created on: {{ image.getDate|date:"Y-m-d H:i:s" }}</td></tr>
<tr><td colspan="2">
{% if image.countAnnotations %}{{ image.countAnnotations }} annotations{% endif %}
{% if image.isPublic %} Public{% else %}{% if image.isShared %} Shared{% else %}{% if image.isPrivate %} Private{% endif %}{% endif %}{% endif %}
{% if image.isReadOnly %} (read-only){% endif %}
{% if not image.isOwned %} Owned by {{ image.getOwner.getFullName }}{% endif %}
</td></tr>
<tr><td colspan="2"><label>{{ image.description|default_if_none:""|linebreaks }}</label></td></tr>
</table>
<h1>Acquisition metadata:</h1>
<table class="metadata_details">
<tr><td><label>Dimensions (XYZT): </label></td><td>{{ image.getSizeX }} x {{ image.getSizeY }} x {{ image.getSizeZ }} x {{ image.getSizeT }}</td></tr>
<tr><td><label>Pixel size (XYZ) [µm]: </label></td><td>{{ image.getPixelSizeX|default_if_none:"-" }} x {{ image.getPixelSizeY|default_if_none:"-" }} x {{ image.getPixelSizeZ|default_if_none:"-" }}</td></tr>
<tr><th colspan="3"><br/></th></tr>
</table>
{% if global_metadata %}
<h1 class="can-collapse defclose">Global metadata: <input type="button" value="Download" onClick="document.location.href=' url download_annotation "download" original_metadata.id ';"/></h1>
<div><table class="metadata_details">
{% for gm in global_metadata %}
<tr><td><label>{{ gm.0 }}</label></td><td>{{ gm.1 }}</td></tr>
{% endfor %}
<tr><th colspan="3"><br/></th></tr>
</table></div>
{% endif %}
{% if series_metadata %}
<h1 class="can-collapse defclose">Series metadata: <input type="button" value="Download" onClick="document.location.href=' url download_annotation 'download' original_metadata.id ';"/></h1>
<div><table class="metadata_details">
{% for sm in series_metadata %}
<tr><td><label>{{ sm.0 }}</label></td><td>{{ sm.1 }}</td></tr>
{% endfor %}
<tr><th colspan="3"><br/></th></tr>
</table></div>
{% endif %}
{% if form_objective or form_environment or form_stageLabel %}
<h1 class="can-collapse defclose">Image:</h1>
<div><table class="metadata_details">
{% if form_objective %}
<tr><th><br/>Objective:</th><th colspan="2"></th></tr>
{% for field in form_objective %}
<tr><td>{{ field.label_tag }}{% if field.field.required %}*{% endif %}</td>
<td>{{ field }}</td><td>{% if field.errors %}{{ field.errors }}{% endif %}<br/>{{ field.help_text|safe }}</td>
</tr>
{% endfor %}
{% endif %}
{% if form_environment %}
<tr><th><br/>Environment:</th><th colspan="2"></th></tr>
{% for field in form_environment %}
<tr><td>{{ field.label_tag }}{% if field.field.required %}*{% endif %}</td>
<td>{{ field }}</td><td>{% if field.errors %}{{ field.errors }}{% endif %}<br/>{{ field.help_text|safe }}</td>
</tr>
{% endfor %}
{% endif %}
{% if form_stageLabel %}
<tr><th><br/>Stage label:</th><th colspan="2"></th></tr>
{% for field in form_stageLabel %}
<tr><td>{{ field.label_tag }}{% if field.field.required %}*{% endif %}</td>
<td>{{ field }}</td><td>{% if field.errors %}{{ field.errors }}{% endif %}<br/>{{ field.help_text|safe }}</td>
</tr>
{% endfor %}
{% endif %}
<tr><th colspan="3"><br/></th></tr>
</table></div>
{% endif %}
{% if form_objective or form_filters or form_detectors %}
<h1 class="can-collapse defclose">Microscope:</h1>
<div><table class="metadata_details">
{% if form_microscope %}
{% for field in form_microscope %}
<tr><td>{{ field.label_tag }}{% if field.field.required %}*{% endif %}</td>
<td>{{ field }}</td><td>{% if field.errors %}{{ field.errors }}{% endif %}<br/>{{ field.help_text|safe }}</td>
</tr>
{% endfor %}
{% endif %}
{% if form_objective %}
<tr><th><br/>Objective:</th><th colspan="2"></th></tr>
{% for field in form_objective %}
<tr><td>{{ field.label_tag }}{% if field.field.required %}*{% endif %}</td>
<td>{{ field }}</td><td>{% if field.errors %}{{ field.errors }}{% endif %}<br/>{{ field.help_text|safe }}</td>
</tr>
{% endfor %}
{% endif %}
{% for form in form_filters %}
<tr><th><br/>Filter:</th><th colspan="2"></th></tr>
{% for field in form %}
<tr><td>{{ field.label_tag }}{% if field.field.required %}*{% endif %}</td>
<td>{{ field }}</td><td>{% if field.errors %}{{ field.errors }}{% endif %}<br/>{{ field.help_text|safe }}</td>
</tr>
{% endfor %}
{% endfor %}
{% for form in form_detectors %}
<tr><th><br/>Detector:</th><th colspan="2"></th></tr>
{% for field in form %}
<tr><td>{{ field.label_tag }}{% if field.field.required %}*{% endif %}</td>
<td>{{ field }}</td><td>{% if field.errors %}{{ field.errors }}{% endif %}<br/>{{ field.help_text|safe }}</td>
</tr>
{% endfor %}
{% endfor %}
{% for form in form_lasers %}
<tr><th><br/>Laser:</th><th colspan="2"></th></tr>
{% for field in form %}
<tr><td>{{ field.label_tag }}{% if field.field.required %}*{% endif %}</td>
<td>{{ field }}</td><td>{% if field.errors %}{{ field.errors }}{% endif %}<br/>{{ field.help_text|safe }}</td>
</tr>
{% endfor %}
{% endfor %}
<tr><th colspan="3"><br/></th></tr>
</table></div>
{% endif %}
{% for ch in form_channels %}
<h1 class="can-collapse defclose">Channel: <span style="padding:0 3px; color:#000; border:1px solid #bbb; background-color: #{{ ch.color }};">{{ ch.name }}</span></h1>
<div><table class="metadata_details">
{% for field in ch.form %}
<tr><td>{{ field.label_tag }}{% if field.field.required %}*{% endif %}</td>
<td>{{ field }}</td><td>{% if field.errors %}{{ field.errors }}{% endif %}<br/>{{ field.help_text|safe }}</td>
</tr>
{% endfor %}
{% if ch.form_emission_filter %}
<tr><th><br/>Filter:</th><th colspan="2"></th></tr>
{% for field in ch.form_emission_filter %}
<tr><td>{{ field.label_tag }}{% if field.field.required %}*{% endif %}</td>
<td>{{ field }}</td><td>{% if field.errors %}{{ field.errors }}{% endif %}<br/>{{ field.help_text|safe }}</td>
</tr>
{% endfor %}
{% endif %}
{% if ch.form_detector_settings %}
<tr><th><br/>Detector:</th><th colspan="2"></th></tr>
{% for field in ch.form_detector_settings %}
<tr><td>{{ field.label_tag }}{% if field.field.required %}*{% endif %}</td>
<td>{{ field }}</td><td>{% if field.errors %}{{ field.errors }}{% endif %}<br/>{{ field.help_text|safe }}</td>
</tr>
{% endfor %}
{% endif %}
{% if ch.form_dichroic %}
<tr><th><br/>Dichroic:</th><th colspan="2"></th></tr>
{% for field in ch.form_dichroic %}
<tr><td>{{ field.label_tag }}{% if field.field.required %}*{% endif %}</td>
<td>{{ field }}</td><td>{% if field.errors %}{{ field.errors }}{% endif %}<br/>{{ field.help_text|safe }}</td>
</tr>
{% endfor %}
{% endif %}
{% if ch.form_light_source %}
<tr><th><br/>Laser:</th><th colspan="2"></th></tr>
{% for field in ch.form_light_source %}
<tr><td>{{ field.label_tag }}{% if field.field.required %}*{% endif %}</td>
<td>{{ field }}</td><td>{% if field.errors %}{{ field.errors }}{% endif %}<br/>{{ field.help_text|safe }}</td>
</tr>
{% endfor %}
{% endif %}
<tr><th colspan="3"><br/></th></tr>
</table></div>
{% endfor %}
<br/><p>*N/A - this value is not available.</p>
<div class="clear"></div>
</div>
<!-- ANNOTATIONS -->
<div id="annotation_tab">
<h1>Comments:</h1>
{% if txannSize %}
<div class="lncomments">
{% for tann in text_annotations %}
<div class="ann_comment_wrapper">
<div class="avatar"><img src="{% url load_photo tann.details.owner.id.val %}" alt="{{ tann.getOwner.getFullName }}" title="{{ tann.getOwner.getFullName }}" width="40" height="40" /></div>
<div><span class="ann_comment_header">{{ tann.getOwner.getFullName }} posted comment at {{ tann.creationEventDate|date:"Y-m-d H:i:s" }}</span><br/>
{{ tann.textValue|safe|linebreaks }}
</div>
</div>
{% endfor %}
</div>
{% else %}
<p>Have not been commented yet.</p>
{% endif %}
<div class="clear"></div>
<!-- TAGS -->
<h1>Tags:</h1>
{% if tgannSize %}
<div class="lntags"> <h1>
{% for tag in tag_annotations %}
{{ tag.textValue }},
{% endfor %}
</h1></div>
{% else %}
<p>Have not been tagged yet.</p>
{% endif %}
<div class="clear"></div>
<!-- FILES -->
<h1>Files:</h1>
{% if fileannSize %}
<div class="lnfiles">
{% for fileann in file_annotations %}
<p>{{ fileann.getFileName }} ({{ fileann.getFileSize|default_if_none:0|filesizeformat }}) by {{ fileann.getDetails.getOwner.getNameWithInitial }} at {{ fileann.creationEventDate|date:"Y-m-d H:i:s" }}</p>
{% endfor %}
</div>
{% else %}
<p>No file has been attached yet.</p>
{% endif %}
<div class="clear"></div>
</div>
</div>
</div>
<a href="{% url webtest_logout %}">logout</a>
<hr>
</body> </html>
|
joshmoore/openmicroscopy
|
components/tools/OmeroWeb/omeroweb/webtest/templates/webtest/metadata.html
|
HTML
|
gpl-2.0
| 13,339
|
/*
* Copyright (C) 2005-2012 Team XBMC
* http://www.xbmc.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, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "network/Network.h"
#include "system.h"
#include "utils/AlarmClock.h"
#include "utils/Screenshot.h"
#include "Application.h"
#include "ApplicationMessenger.h"
#include "Autorun.h"
#include "Builtins.h"
#include "input/ButtonTranslator.h"
#include "FileItem.h"
#include "addons/GUIDialogAddonSettings.h"
#include "dialogs/GUIDialogFileBrowser.h"
#include "guilib/GUIKeyboardFactory.h"
#include "dialogs/GUIDialogKaiToast.h"
#include "dialogs/GUIDialogNumeric.h"
#include "dialogs/GUIDialogProgress.h"
#include "dialogs/GUIDialogYesNo.h"
#include "GUIUserMessages.h"
#include "windows/GUIWindowLoginScreen.h"
#include "video/windows/GUIWindowVideoBase.h"
#include "addons/GUIWindowAddonBrowser.h"
#include "addons/Addon.h" // for TranslateType, TranslateContent
#include "addons/AddonInstaller.h"
#include "addons/AddonManager.h"
#include "addons/PluginSource.h"
#include "music/LastFmManager.h"
#include "utils/LCD.h"
#include "utils/log.h"
#include "storage/MediaManager.h"
#include "utils/RssReader.h"
#include "PartyModeManager.h"
#include "settings/Settings.h"
#include "utils/StringUtils.h"
#include "utils/URIUtils.h"
#include "Util.h"
#include "URL.h"
#include "music/MusicDatabase.h"
#include "filesystem/PluginDirectory.h"
#ifdef HAS_FILESYSTEM_RAR
#include "filesystem/RarManager.h"
#endif
#include "filesystem/ZipManager.h"
#include "guilib/GUIWindowManager.h"
#include "guilib/LocalizeStrings.h"
#ifdef HAS_LIRC
#include "input/linux/LIRC.h"
#endif
#ifdef HAS_IRSERVERSUITE
#include "input/windows/IRServerSuite.h"
#endif
#ifdef HAS_PYTHON
#include "interfaces/python/XBPython.h"
#endif
#if defined(TARGET_DARWIN)
#include "filesystem/SpecialProtocol.h"
#include "osx/CocoaInterface.h"
#endif
#ifdef HAS_CDDA_RIPPER
#include "cdrip/CDDARipper.h"
#endif
#include <vector>
#include "xbmc/settings/AdvancedSettings.h"
#include "cores/VideoRenderers/RenderManager.h"
#include "cores/VideoRenderers/LinuxRendererA10.h"
#include "GUIInfoManager.h"
using namespace std;
using namespace XFILE;
using namespace ADDON;
#ifdef HAS_DVD_DRIVE
using namespace MEDIA_DETECT;
#endif
typedef struct
{
const char* command;
bool needsParameters;
const char* description;
} BUILT_IN;
const BUILT_IN commands[] = {
{ "Help", false, "This help message" },
{ "Reboot", false, "Reboot the system" },
{ "Restart", false, "Restart the system (same as reboot)" },
{ "ShutDown", false, "Shutdown the system" },
{ "Powerdown", false, "Powerdown system" },
{ "Quit", false, "Quit XBMC" },
{ "Hibernate", false, "Hibernates the system" },
{ "Suspend", false, "Suspends the system" },
{ "InhibitIdleShutdown", false, "Inhibit idle shutdown" },
{ "AllowIdleShutdown", false, "Allow idle shutdown" },
{ "RestartApp", false, "Restart XBMC" },
{ "Minimize", false, "Minimize XBMC" },
{ "Reset", false, "Reset the system (same as reboot)" },
{ "Mastermode", false, "Control master mode" },
{ "ActivateWindow", true, "Activate the specified window" },
{ "ActivateWindowAndFocus", true, "Activate the specified window and sets focus to the specified id" },
{ "ReplaceWindow", true, "Replaces the current window with the new one" },
{ "TakeScreenshot", false, "Takes a Screenshot" },
{ "RunScript", true, "Run the specified script" },
{ "StopScript", true, "Stop the script by ID or path, if running" },
#if defined(TARGET_DARWIN)
{ "RunAppleScript", true, "Run the specified AppleScript command" },
#endif
{ "RunPlugin", true, "Run the specified plugin" },
{ "RunAddon", true, "Run the specified plugin/script" },
{ "Extract", true, "Extracts the specified archive" },
{ "PlayMedia", true, "Play the specified media file (or playlist)" },
{ "SlideShow", true, "Run a slideshow from the specified directory" },
{ "RecursiveSlideShow", true, "Run a slideshow from the specified directory, including all subdirs" },
{ "ReloadSkin", false, "Reload XBMC's skin" },
{ "UnloadSkin", false, "Unload XBMC's skin" },
{ "RefreshRSS", false, "Reload RSS feeds from RSSFeeds.xml"},
{ "PlayerControl", true, "Control the music or video player" },
{ "Playlist.PlayOffset", true, "Start playing from a particular offset in the playlist" },
{ "Playlist.Clear", false, "Clear the current playlist" },
{ "EjectTray", false, "Close or open the DVD tray" },
{ "AlarmClock", true, "Prompt for a length of time and start an alarm clock" },
{ "CancelAlarm", true, "Cancels an alarm" },
{ "Action", true, "Executes an action for the active window (same as in keymap)" },
{ "Notification", true, "Shows a notification on screen, specify header, then message, and optionally time in milliseconds and a icon." },
{ "PlayDVD", false, "Plays the inserted CD or DVD media from the DVD-ROM Drive!" },
{ "RipCD", false, "Rip the currently inserted audio CD"},
{ "Skin.ToggleSetting", true, "Toggles a skin setting on or off" },
{ "Skin.SetString", true, "Prompts and sets skin string" },
{ "Skin.SetNumeric", true, "Prompts and sets numeric input" },
{ "Skin.SetPath", true, "Prompts and sets a skin path" },
{ "Skin.Theme", true, "Control skin theme" },
{ "Skin.SetImage", true, "Prompts and sets a skin image" },
{ "Skin.SetLargeImage", true, "Prompts and sets a large skin images" },
{ "Skin.SetFile", true, "Prompts and sets a file" },
{ "Skin.SetAddon", true, "Prompts and set an addon" },
{ "Skin.SetBool", true, "Sets a skin setting on" },
{ "Skin.Reset", true, "Resets a skin setting to default" },
{ "Skin.ResetSettings", false, "Resets all skin settings" },
{ "Mute", false, "Mute the player" },
{ "SetVolume", true, "Set the current volume" },
{ "Dialog.Close", true, "Close a dialog" },
{ "System.LogOff", false, "Log off current user" },
{ "System.Exec", true, "Execute shell commands" },
{ "System.ExecWait", true, "Execute shell commands and freezes XBMC until shell is closed" },
{ "Resolution", true, "Change XBMC's Resolution" },
{ "SetFocus", true, "Change current focus to a different control id" },
{ "UpdateLibrary", true, "Update the selected library (music or video)" },
{ "CleanLibrary", true, "Clean the video/music library" },
{ "ExportLibrary", true, "Export the video/music library" },
{ "PageDown", true, "Send a page down event to the pagecontrol with given id" },
{ "PageUp", true, "Send a page up event to the pagecontrol with given id" },
{ "LastFM.Love", false, "Add the current playing last.fm radio track to the last.fm loved tracks" },
{ "LastFM.Ban", false, "Ban the current playing last.fm radio track" },
{ "Container.Refresh", false, "Refresh current listing" },
{ "Container.Update", false, "Update current listing. Send Container.Update(path,replace) to reset the path history" },
{ "Container.NextViewMode", false, "Move to the next view type (and refresh the listing)" },
{ "Container.PreviousViewMode", false, "Move to the previous view type (and refresh the listing)" },
{ "Container.SetViewMode", true, "Move to the view with the given id" },
{ "Container.NextSortMethod", false, "Change to the next sort method" },
{ "Container.PreviousSortMethod",false, "Change to the previous sort method" },
{ "Container.SetSortMethod", true, "Change to the specified sort method" },
{ "Container.SortDirection", false, "Toggle the sort direction" },
{ "Control.Move", true, "Tells the specified control to 'move' to another entry specified by offset" },
{ "Control.SetFocus", true, "Change current focus to a different control id" },
{ "Control.Message", true, "Send a given message to a control within a given window" },
{ "SendClick", true, "Send a click message from the given control to the given window" },
{ "LoadProfile", true, "Load the specified profile (note; if locks are active it won't work)" },
{ "SetProperty", true, "Sets a window property for the current focused window/dialog (key,value)" },
{ "ClearProperty", true, "Clears a window property for the current focused window/dialog (key,value)" },
{ "PlayWith", true, "Play the selected item with the specified core" },
{ "WakeOnLan", true, "Sends the wake-up packet to the broadcast address for the specified MAC address" },
{ "Addon.Default.OpenSettings", true, "Open a settings dialog for the default addon of the given type" },
{ "Addon.Default.Set", true, "Open a select dialog to allow choosing the default addon of the given type" },
{ "Addon.OpenSettings", true, "Open a settings dialog for the addon of the given id" },
{ "UpdateAddonRepos", false, "Check add-on repositories for updates" },
{ "UpdateLocalAddons", false, "Check for local add-on changes" },
{ "ToggleDPMS", false, "Toggle DPMS mode manually"},
{ "Weather.Refresh", false, "Force weather data refresh"},
{ "Weather.LocationNext", false, "Switch to next weather location"},
{ "Weather.LocationPrevious", false, "Switch to previous weather location"},
{ "Weather.LocationSet", true, "Switch to given weather location (parameter can be 1-3)"},
#if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
{ "LIRC.Stop", false, "Removes XBMC as LIRC client" },
{ "LIRC.Start", false, "Adds XBMC as LIRC client" },
{ "LIRC.Send", true, "Sends a command to LIRC" },
#endif
#ifdef HAS_LCD
{ "LCD.Suspend", false, "Suspends LCDproc" },
{ "LCD.Resume", false, "Resumes LCDproc" },
#endif
{ "VideoLibrary.Search", false, "Brings up a search dialog which will search the library" },
{ "ToggleDebug", false, "Enables/disables debug mode" },
{ "StartPVRManager", false, "(Re)Starts the PVR manager" },
{ "StopPVRManager", false, "Stops the PVR manager" },
{ "SetSizeManual", true, "Set the size of SlideShow and Video"},
{ "UpdateTwitter", true, "UpdateTwitter"},
};
bool CBuiltins::HasCommand(const CStdString& execString)
{
CStdString function;
vector<CStdString> parameters;
CUtil::SplitExecFunction(execString, function, parameters);
for (unsigned int i = 0; i < sizeof(commands)/sizeof(BUILT_IN); i++)
{
if (function.CompareNoCase(commands[i].command) == 0 && (!commands[i].needsParameters || parameters.size()))
return true;
}
return false;
}
void CBuiltins::GetHelp(CStdString &help)
{
help.Empty();
for (unsigned int i = 0; i < sizeof(commands)/sizeof(BUILT_IN); i++)
{
help += commands[i].command;
help += "\t";
help += commands[i].description;
help += "\n";
}
}
int CBuiltins::Execute(const CStdString& execString)
{
// Get the text after the "XBMC."
CStdString execute;
vector<CStdString> params;
CUtil::SplitExecFunction(execString, execute, params);
execute.ToLower();
CStdString parameter = params.size() ? params[0] : "";
CStdString strParameterCaseIntact = parameter;
if (execute.Equals("reboot") || execute.Equals("restart") || execute.Equals("reset")) //Will reboot the system
{
CApplicationMessenger::Get().Restart();
}
else if (execute.Equals("shutdown"))
{
CApplicationMessenger::Get().Shutdown();
}
else if (execute.Equals("powerdown"))
{
CApplicationMessenger::Get().Powerdown();
}
else if (execute.Equals("restartapp"))
{
CApplicationMessenger::Get().RestartApp();
}
else if (execute.Equals("hibernate"))
{
CApplicationMessenger::Get().Hibernate();
}
else if (execute.Equals("suspend"))
{
CApplicationMessenger::Get().Suspend();
}
else if (execute.Equals("quit"))
{
CApplicationMessenger::Get().Quit();
}
else if (execute.Equals("inhibitidleshutdown"))
{
bool inhibit = (params.size() == 1 && params[0].Equals("true"));
CApplicationMessenger::Get().InhibitIdleShutdown(inhibit);
}
else if (execute.Equals("minimize"))
{
CApplicationMessenger::Get().Minimize();
}
else if (execute.Equals("loadprofile"))
{
int index = g_settings.GetProfileIndex(parameter);
bool prompt = (params.size() == 2 && params[1].Equals("prompt"));
bool bCanceled;
if (index >= 0
&& (g_settings.GetMasterProfile().getLockMode() == LOCK_MODE_EVERYONE
|| g_passwordManager.IsProfileLockUnlocked(index,bCanceled,prompt)))
{
CApplicationMessenger::Get().LoadProfile(index);
}
}
else if (execute.Equals("mastermode"))
{
if (g_passwordManager.bMasterUser)
{
g_passwordManager.bMasterUser = false;
g_passwordManager.LockSources(true);
CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Warning, g_localizeStrings.Get(20052),g_localizeStrings.Get(20053));
}
else if (g_passwordManager.IsMasterLockUnlocked(true))
{
g_passwordManager.LockSources(false);
g_passwordManager.bMasterUser = true;
CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Warning, g_localizeStrings.Get(20052),g_localizeStrings.Get(20054));
}
CUtil::DeleteVideoDatabaseDirectoryCache();
CGUIMessage msg(GUI_MSG_NOTIFY_ALL, 0, 0, GUI_MSG_UPDATE);
g_windowManager.SendMessage(msg);
}
else if (execute.Equals("takescreenshot"))
{
CScreenShot::TakeScreenshot();
}
else if (execute.Equals("activatewindow") || execute.Equals("replacewindow"))
{
// get the parameters
CStdString strWindow;
if (params.size())
{
strWindow = params[0];
params.erase(params.begin());
}
// confirm the window destination is valid prior to switching
int iWindow = CButtonTranslator::TranslateWindow(strWindow);
if (iWindow != WINDOW_INVALID)
{
// disable the screensaver
g_application.WakeUpScreenSaverAndDPMS();
#if defined(TARGET_DARWIN_IOS)
if (params[0].Equals("shutdownmenu"))
CBuiltins::Execute("Quit");
#endif
g_windowManager.ActivateWindow(iWindow, params, !execute.Equals("activatewindow"));
}
else
{
CLog::Log(LOGERROR, "Activate/ReplaceWindow called with invalid destination window: %s", strWindow.c_str());
return false;
}
}
else if ((execute.Equals("setfocus") || execute.Equals("control.setfocus")) && params.size())
{
int controlID = atol(params[0].c_str());
int subItem = (params.size() > 1) ? atol(params[1].c_str())+1 : 0;
CGUIMessage msg(GUI_MSG_SETFOCUS, g_windowManager.GetFocusedWindow(), controlID, subItem);
g_windowManager.SendMessage(msg);
}
else if ((execute.Equals("activatewindowandfocus")) && params.size())
{
CStdString strWindow = params[0];
// confirm the window destination is valid prior to switching
int iWindow = CButtonTranslator::TranslateWindow(strWindow);
if (iWindow != WINDOW_INVALID)
{
// disable the screensaver
g_application.WakeUpScreenSaverAndDPMS();
#if defined(__APPLE__) && defined(__arm__)
if (params[0].Equals("shutdownmenu"))
CBuiltins::Execute("Quit");
#endif
vector<CStdString> dummy;
g_windowManager.ActivateWindow(iWindow, dummy, false);
unsigned int iPtr = 1;
while (params.size() > iPtr + 1)
{
CGUIMessage msg(GUI_MSG_SETFOCUS, g_windowManager.GetFocusedWindow(),
atol(params[iPtr].c_str()),
(params.size() >= iPtr + 2) ? atol(params[iPtr + 1].c_str())+1 : 0);
g_windowManager.SendMessage(msg);
iPtr += 2;
}
}
else
{
CLog::Log(LOGERROR, "ActivateWindowAndFocus called with invalid destination window: %s", strWindow.c_str());
return false;
}
}
else if (execute.Equals("runscript") && params.size())
{
#if defined(TARGET_DARWIN_OSX)
if (URIUtils::GetExtension(strParameterCaseIntact) == ".applescript" ||
URIUtils::GetExtension(strParameterCaseIntact) == ".scpt")
{
CStdString osxPath = CSpecialProtocol::TranslatePath(strParameterCaseIntact);
Cocoa_DoAppleScriptFile(osxPath.c_str());
}
else
#endif
{
#ifdef HAS_PYTHON
vector<CStdString> argv = params;
vector<CStdString> path;
//split the path up to find the filename
StringUtils::SplitString(params[0],"\\",path);
if (path.size())
argv[0] = path[path.size() - 1];
AddonPtr script;
CStdString scriptpath(params[0]);
if (CAddonMgr::Get().GetAddon(params[0], script))
scriptpath = script->LibPath();
g_pythonParser.evalFile(scriptpath, argv,script);
#endif
}
}
#if defined(TARGET_DARWIN_OSX)
else if (execute.Equals("runapplescript"))
{
Cocoa_DoAppleScript(strParameterCaseIntact.c_str());
}
#endif
else if (execute.Equals("stopscript"))
{
#ifdef HAS_PYTHON
CStdString scriptpath(params[0]);
// Test to see if the param is an addon ID
AddonPtr script;
if (CAddonMgr::Get().GetAddon(params[0], script))
scriptpath = script->LibPath();
g_pythonParser.StopScript(scriptpath);
#endif
}
else if (execute.Equals("system.exec"))
{
CApplicationMessenger::Get().Minimize();
CApplicationMessenger::Get().ExecOS(parameter, false);
}
else if (execute.Equals("system.execwait"))
{
CApplicationMessenger::Get().Minimize();
CApplicationMessenger::Get().ExecOS(parameter, true);
}
else if (execute.Equals("resolution"))
{
RESOLUTION res = RES_PAL_4x3;
if (parameter.Equals("pal")) res = RES_PAL_4x3;
else if (parameter.Equals("pal16x9")) res = RES_PAL_16x9;
else if (parameter.Equals("ntsc")) res = RES_NTSC_4x3;
else if (parameter.Equals("ntsc16x9")) res = RES_NTSC_16x9;
else if (parameter.Equals("720p")) res = RES_HDTV_720p;
else if (parameter.Equals("720pSBS")) res = RES_HDTV_720pSBS;
else if (parameter.Equals("720pTB")) res = RES_HDTV_720pTB;
else if (parameter.Equals("1080pSBS")) res = RES_HDTV_1080pSBS;
else if (parameter.Equals("1080pTB")) res = RES_HDTV_1080pTB;
else if (parameter.Equals("1080i")) res = RES_HDTV_1080i;
if (g_graphicsContext.IsValidResolution(res))
{
g_guiSettings.SetResolution(res);
g_graphicsContext.SetVideoResolution(res);
g_application.ReloadSkin();
}
}
else if (execute.Equals("extract") && params.size())
{
// Detects if file is zip or zip then extracts
CStdString strDestDirect = "";
if (params.size() < 2)
URIUtils::GetDirectory(params[0],strDestDirect);
else
strDestDirect = params[1];
URIUtils::AddSlashAtEnd(strDestDirect);
if (URIUtils::IsZIP(params[0]))
g_ZipManager.ExtractArchive(params[0],strDestDirect);
#ifdef HAS_FILESYSTEM_RAR
else if (URIUtils::IsRAR(params[0]))
g_RarManager.ExtractArchive(params[0],strDestDirect);
#endif
else
CLog::Log(LOGERROR, "XBMC.Extract, No archive given");
}
else if (execute.Equals("runplugin"))
{
if (params.size())
{
CFileItem item(params[0]);
if (!item.m_bIsFolder)
{
item.SetPath(params[0]);
CPluginDirectory::RunScriptWithParams(item.GetPath());
}
}
else
{
CLog::Log(LOGERROR, "XBMC.RunPlugin called with no arguments.");
}
}
else if (execute.Equals("runaddon"))
{
if (params.size())
{
AddonPtr addon;
if (CAddonMgr::Get().GetAddon(params[0],addon) && addon)
{
PluginPtr plugin = boost::dynamic_pointer_cast<CPluginSource>(addon);
CStdString cmd;
if (plugin && addon->Type() == ADDON_PLUGIN)
{
if (plugin->Provides(CPluginSource::VIDEO))
cmd.Format("ActivateWindow(Video,plugin://%s,return)",params[0]);
else if (plugin->Provides(CPluginSource::AUDIO))
cmd.Format("ActivateWindow(Music,plugin://%s,return)",params[0]);
else if (plugin->Provides(CPluginSource::EXECUTABLE))
cmd.Format("ActivateWindow(Programs,plugin://%s,return)",params[0]);
else if (plugin->Provides(CPluginSource::IMAGE))
cmd.Format("ActivateWindow(Pictures,plugin://%s,return)",params[0]);
else
// Pass the script name (params[0]) and all the parameters
// (params[1] ... params[x]) separated by a comma to RunPlugin
cmd.Format("RunPlugin(%s)", StringUtils::JoinString(params, ","));
}
else if (addon->Type() >= ADDON_SCRIPT && addon->Type() <= ADDON_SCRIPT_LYRICS)
// Pass the script name (params[0]) and all the parameters
// (params[1] ... params[x]) separated by a comma to RunScript
cmd.Format("RunScript(%s)", StringUtils::JoinString(params, ","));
return Execute(cmd);
}
}
else
{
CLog::Log(LOGERROR, "XBMC.RunAddon called with no arguments.");
}
}
else if (execute.Equals("playmedia"))
{
if (!params.size())
{
CLog::Log(LOGERROR, "XBMC.PlayMedia called with empty parameter");
return -3;
}
CFileItem item(params[0], false);
if (URIUtils::HasSlashAtEnd(params[0]))
item.m_bIsFolder = true;
// restore to previous window if needed
if( g_windowManager.GetActiveWindow() == WINDOW_SLIDESHOW ||
g_windowManager.GetActiveWindow() == WINDOW_FULLSCREEN_VIDEO ||
g_windowManager.GetActiveWindow() == WINDOW_VISUALISATION )
g_windowManager.PreviousWindow();
// reset screensaver
g_application.ResetScreenSaver();
g_application.WakeUpScreenSaverAndDPMS();
// ask if we need to check guisettings to resume
bool askToResume = true;
int playOffset = 0;
for (unsigned int i = 1 ; i < params.size() ; i++)
{
if (params[i].Equals("isdir"))
item.m_bIsFolder = true;
else if (params[i].Equals("1")) // set fullscreen or windowed
g_settings.m_bStartVideoWindowed = true;
else if (params[i].Equals("resume"))
{
// force the item to resume (if applicable) (see CApplication::PlayMedia)
item.m_lStartOffset = STARTOFFSET_RESUME;
askToResume = false;
}
else if (params[i].Equals("noresume"))
{
// force the item to start at the beginning (m_lStartOffset is initialized to 0)
askToResume = false;
}
else if (params[i].Left(11).Equals("playoffset=")) {
playOffset = atoi(params[i].Mid(11)) - 1;
item.SetProperty("playlist_starting_track", playOffset);
}
}
if (!item.m_bIsFolder && item.IsPlugin())
item.SetProperty("IsPlayable", true);
if ( askToResume == true )
{
if ( CGUIWindowVideoBase::ShowResumeMenu(item) == false )
return false;
}
if (item.m_bIsFolder)
{
CFileItemList items;
CDirectory::GetDirectory(item.GetPath(),items,g_settings.m_videoExtensions);
int playlist = PLAYLIST_MUSIC;
for (int i = 0; i < items.Size(); i++)
{
if (items[i]->IsVideo())
{
playlist = PLAYLIST_VIDEO;
break;
}
}
g_playlistPlayer.ClearPlaylist(playlist);
g_playlistPlayer.Add(playlist, items);
g_playlistPlayer.SetCurrentPlaylist(playlist);
g_playlistPlayer.Play(playOffset);
}
else
{
int playlist = item.IsAudio() ? PLAYLIST_MUSIC : PLAYLIST_VIDEO;
g_playlistPlayer.ClearPlaylist(playlist);
g_playlistPlayer.SetCurrentPlaylist(playlist);
// play media
if (!g_application.PlayMedia(item, playlist))
{
CLog::Log(LOGERROR, "XBMC.PlayMedia could not play media: %s", params[0].c_str());
return false;
}
}
}
else if (execute.Equals("slideShow") || execute.Equals("recursiveslideShow"))
{
if (!params.size())
{
CLog::Log(LOGERROR, "XBMC.SlideShow called with empty parameter");
return -2;
}
// leave RecursiveSlideShow command as-is
unsigned int flags = 0;
if (execute.Equals("RecursiveSlideShow"))
flags |= 1;
// SlideShow(dir[,recursive][,[not]random])
else
{
if ((params.size() > 1 && params[1] == "recursive") || (params.size() > 2 && params[2] == "recursive"))
flags |= 1;
if ((params.size() > 1 && params[1] == "random") || (params.size() > 2 && params[2] == "random"))
flags |= 2;
if ((params.size() > 1 && params[1] == "notrandom") || (params.size() > 2 && params[2] == "notrandom"))
flags |= 4;
}
CGUIMessage msg(GUI_MSG_START_SLIDESHOW, 0, 0, flags);
msg.SetStringParam(params[0]);
CGUIWindow *pWindow = g_windowManager.GetWindow(WINDOW_SLIDESHOW);
if (pWindow) pWindow->OnMessage(msg);
}
else if (execute.Equals("reloadskin"))
{
// Reload the skin
g_application.ReloadSkin();
}
else if (execute.Equals("unloadskin"))
{
g_application.UnloadSkin(true); // we're reloading the skin after this
}
else if (execute.Equals("refreshrss"))
{
g_rssManager.Stop();
g_settings.LoadRSSFeeds();
g_rssManager.Start();
}
else if (execute.Equals("playercontrol"))
{
g_application.ResetScreenSaver();
g_application.WakeUpScreenSaverAndDPMS();
if (!params.size())
{
CLog::Log(LOGERROR, "XBMC.PlayerControl called with empty parameter");
return -3;
}
if (parameter.Equals("play"))
{ // play/pause
// either resume playing, or pause
if (g_application.IsPlaying())
{
if (g_application.GetPlaySpeed() != 1)
g_application.SetPlaySpeed(1);
else
g_application.m_pPlayer->Pause();
}
}
else if (parameter.Equals("stop"))
{
g_application.StopPlaying();
}
else if (parameter.Equals("rewind") || parameter.Equals("forward"))
{
if (g_application.IsPlaying() && !g_application.m_pPlayer->IsPaused())
{
int iPlaySpeed = g_application.GetPlaySpeed();
if (parameter.Equals("rewind") && iPlaySpeed == 1) // Enables Rewinding
iPlaySpeed *= -2;
else if (parameter.Equals("rewind") && iPlaySpeed > 1) //goes down a notch if you're FFing
iPlaySpeed /= 2;
else if (parameter.Equals("forward") && iPlaySpeed < 1) //goes up a notch if you're RWing
{
iPlaySpeed /= 2;
if (iPlaySpeed == -1) iPlaySpeed = 1;
}
else
iPlaySpeed *= 2;
if (iPlaySpeed > 32 || iPlaySpeed < -32)
iPlaySpeed = 1;
g_application.SetPlaySpeed(iPlaySpeed);
}
}
else if (parameter.Equals("next"))
{
g_application.OnAction(CAction(ACTION_NEXT_ITEM));
}
else if (parameter.Equals("previous"))
{
g_application.OnAction(CAction(ACTION_PREV_ITEM));
}
else if (parameter.Equals("bigskipbackward"))
{
if (g_application.IsPlaying())
g_application.m_pPlayer->Seek(false, true);
}
else if (parameter.Equals("bigskipforward"))
{
if (g_application.IsPlaying())
g_application.m_pPlayer->Seek(true, true);
}
else if (parameter.Equals("smallskipbackward"))
{
if (g_application.IsPlaying())
g_application.m_pPlayer->Seek(false, false);
}
else if (parameter.Equals("smallskipforward"))
{
if (g_application.IsPlaying())
g_application.m_pPlayer->Seek(true, false);
}
else if (parameter.Left(14).Equals("seekpercentage"))
{
CStdString offset = "";
float offsetpercent;
if (parameter.size() == 14)
CLog::Log(LOGERROR,"PlayerControl(seekpercentage(n)) called with no argument");
else if (parameter.size() < 17) // arg must be at least "(N)"
CLog::Log(LOGERROR,"PlayerControl(seekpercentage(n)) called with invalid argument: \"%s\"", parameter.Mid(14).c_str());
else
{
// Don't bother checking the argument: an invalid arg will do seek(0)
offset = parameter.Mid(15).TrimRight(")");
offsetpercent = (float) atof(offset.c_str());
if (offsetpercent < 0 || offsetpercent > 100)
CLog::Log(LOGERROR,"PlayerControl(seekpercentage(n)) argument, %f, must be 0-100", offsetpercent);
else if (g_application.IsPlaying())
g_application.SeekPercentage(offsetpercent);
}
}
else if( parameter.Equals("showvideomenu") )
{
if( g_application.IsPlaying() && g_application.m_pPlayer )
g_application.m_pPlayer->OnAction(CAction(ACTION_SHOW_VIDEOMENU));
}
else if( parameter.Equals("record") )
{
if( g_application.IsPlaying() && g_application.m_pPlayer && g_application.m_pPlayer->CanRecord())
g_application.m_pPlayer->Record(!g_application.m_pPlayer->IsRecording());
}
else if (parameter.Left(9).Equals("partymode"))
{
CStdString strXspPath = "";
//empty param=music, "music"=music, "video"=video, else xsp path
PartyModeContext context = PARTYMODECONTEXT_MUSIC;
if (parameter.size() > 9)
{
if (parameter.Mid(10).Equals("video)"))
context = PARTYMODECONTEXT_VIDEO;
else if (!parameter.Mid(10).Equals("music)"))
{
strXspPath = parameter.Mid(10).TrimRight(")");
context = PARTYMODECONTEXT_UNKNOWN;
}
}
if (g_partyModeManager.IsEnabled())
g_partyModeManager.Disable();
else
g_partyModeManager.Enable(context, strXspPath);
}
else if (parameter.Equals("random") ||
parameter.Equals("randomoff") ||
parameter.Equals("randomon"))
{
// get current playlist
int iPlaylist = g_playlistPlayer.GetCurrentPlaylist();
// reverse the current setting
bool shuffled = g_playlistPlayer.IsShuffled(iPlaylist);
if ((shuffled && parameter.Equals("randomon")) || (!shuffled && parameter.Equals("randomoff")))
return 0;
// check to see if we should notify the user
bool notify = (params.size() == 2 && params[1].Equals("notify"));
g_playlistPlayer.SetShuffle(iPlaylist, !shuffled, notify);
// save settings for now playing windows
switch (iPlaylist)
{
case PLAYLIST_MUSIC:
g_settings.m_bMyMusicPlaylistShuffle = g_playlistPlayer.IsShuffled(iPlaylist);
g_settings.Save();
break;
case PLAYLIST_VIDEO:
g_settings.m_bMyVideoPlaylistShuffle = g_playlistPlayer.IsShuffled(iPlaylist);
g_settings.Save();
}
// send message
CGUIMessage msg(GUI_MSG_PLAYLISTPLAYER_RANDOM, 0, 0, iPlaylist, g_playlistPlayer.IsShuffled(iPlaylist));
g_windowManager.SendThreadMessage(msg);
}
else if (parameter.Left(6).Equals("repeat"))
{
// get current playlist
int iPlaylist = g_playlistPlayer.GetCurrentPlaylist();
PLAYLIST::REPEAT_STATE previous_state = g_playlistPlayer.GetRepeat(iPlaylist);
PLAYLIST::REPEAT_STATE state;
if (parameter.Equals("repeatall"))
state = PLAYLIST::REPEAT_ALL;
else if (parameter.Equals("repeatone"))
state = PLAYLIST::REPEAT_ONE;
else if (parameter.Equals("repeatoff"))
state = PLAYLIST::REPEAT_NONE;
else if (previous_state == PLAYLIST::REPEAT_NONE)
state = PLAYLIST::REPEAT_ALL;
else if (previous_state == PLAYLIST::REPEAT_ALL)
state = PLAYLIST::REPEAT_ONE;
else
state = PLAYLIST::REPEAT_NONE;
if (state == previous_state)
return 0;
// check to see if we should notify the user
bool notify = (params.size() == 2 && params[1].Equals("notify"));
g_playlistPlayer.SetRepeat(iPlaylist, state, notify);
// save settings for now playing windows
switch (iPlaylist)
{
case PLAYLIST_MUSIC:
g_settings.m_bMyMusicPlaylistRepeat = (state == PLAYLIST::REPEAT_ALL);
g_settings.Save();
break;
case PLAYLIST_VIDEO:
g_settings.m_bMyVideoPlaylistRepeat = (state == PLAYLIST::REPEAT_ALL);
g_settings.Save();
}
// send messages so now playing window can get updated
CGUIMessage msg(GUI_MSG_PLAYLISTPLAYER_REPEAT, 0, 0, iPlaylist, (int)state);
g_windowManager.SendThreadMessage(msg);
}
}
else if (execute.Equals("playwith"))
{
g_application.m_eForcedNextPlayer = CPlayerCoreFactory::GetPlayerCore(parameter);
g_application.OnAction(CAction(ACTION_PLAYER_PLAY));
}
else if (execute.Equals("mute"))
{
g_application.ToggleMute();
}
else if (execute.Equals("setvolume"))
{
int oldVolume = g_application.GetVolume();
int volume = atoi(parameter.c_str());
g_application.SetVolume((float)volume);
if(oldVolume != volume)
{
if(params.size() > 1 && params[1].Equals("showVolumeBar"))
{
CApplicationMessenger::Get().ShowVolumeBar(oldVolume < volume);
}
}
}
else if (execute.Equals("playlist.playoffset"))
{
// playlist.playoffset(offset)
// playlist.playoffset(music|video,offset)
CStdString strPos = parameter;
if (params.size() > 1)
{
// ignore any other parameters if present
CStdString strPlaylist = params[0];
strPos = params[1];
int iPlaylist = PLAYLIST_NONE;
if (strPlaylist.Equals("music"))
iPlaylist = PLAYLIST_MUSIC;
else if (strPlaylist.Equals("video"))
iPlaylist = PLAYLIST_VIDEO;
// unknown playlist
if (iPlaylist == PLAYLIST_NONE)
{
CLog::Log(LOGERROR,"Playlist.PlayOffset called with unknown playlist: %s", strPlaylist.c_str());
return false;
}
// user wants to play the 'other' playlist
if (iPlaylist != g_playlistPlayer.GetCurrentPlaylist())
{
g_application.StopPlaying();
g_playlistPlayer.Reset();
g_playlistPlayer.SetCurrentPlaylist(iPlaylist);
}
}
// play the desired offset
int pos = atol(strPos.c_str());
// playlist is already playing
if (g_application.IsPlaying())
g_playlistPlayer.PlayNext(pos);
// we start playing the 'other' playlist so we need to use play to initialize the player state
else
g_playlistPlayer.Play(pos);
}
else if (execute.Equals("playlist.clear"))
{
g_playlistPlayer.Clear();
}
#ifdef HAS_DVD_DRIVE
else if (execute.Equals("ejecttray"))
{
g_mediaManager.ToggleTray();
}
#endif
else if( execute.Equals("alarmclock") && params.size() > 1 )
{
// format is alarmclock(name,command[,seconds,true]);
float seconds = 0;
if (params.size() > 2)
{
if (params[2].Find(':') == -1)
seconds = static_cast<float>(atoi(params[2].c_str())*60);
else
seconds = (float)StringUtils::TimeStringToSeconds(params[2]);
}
else
{ // check if shutdown is specified in particular, and get the time for it
CStdString strHeading;
if (parameter.CompareNoCase("shutdowntimer") == 0)
strHeading = g_localizeStrings.Get(20145);
else
strHeading = g_localizeStrings.Get(13209);
CStdString strTime;
if( CGUIDialogNumeric::ShowAndGetNumber(strTime, strHeading) )
seconds = static_cast<float>(atoi(strTime.c_str())*60);
else
return false;
}
bool silent = false;
bool loop = false;
for (unsigned int i = 3; i < params.size() ; i++)
{
// check "true" for backward comp
if (params[i].CompareNoCase("true") == 0 || params[i].CompareNoCase("silent") == 0)
silent = true;
else if (params[i].CompareNoCase("loop") == 0)
loop = true;
}
if( g_alarmClock.IsRunning() )
g_alarmClock.Stop(params[0],silent);
g_alarmClock.Start(params[0], seconds, params[1], silent, loop);
}
else if (execute.Equals("notification"))
{
if (params.size() < 2)
return -1;
if (params.size() == 4)
CGUIDialogKaiToast::QueueNotification(params[3],params[0],params[1],atoi(params[2].c_str()));
else if (params.size() == 3)
CGUIDialogKaiToast::QueueNotification("",params[0],params[1],atoi(params[2].c_str()));
else
CGUIDialogKaiToast::QueueNotification(params[0],params[1]);
}
else if (execute.Equals("cancelalarm"))
{
bool silent = false;
if (params.size() > 1 && params[1].CompareNoCase("true") == 0)
silent = true;
g_alarmClock.Stop(params[0],silent);
}
else if (execute.Equals("playdvd"))
{
#ifdef HAS_DVD_DRIVE
bool restart = false;
if (params.size() > 0 && params[0].CompareNoCase("restart") == 0)
restart = true;
CAutorun::PlayDisc(g_mediaManager.GetDiscPath(), true, restart);
#endif
}
else if (execute.Equals("ripcd"))
{
#ifdef HAS_CDDA_RIPPER
CCDDARipper::GetInstance().RipCD();
#endif
}
else if (execute.Equals("skin.togglesetting"))
{
int setting = g_settings.TranslateSkinBool(parameter);
g_settings.SetSkinBool(setting, !g_settings.GetSkinBool(setting));
g_settings.Save();
}
else if (execute.Equals("skin.setbool") && params.size())
{
if (params.size() > 1)
{
int string = g_settings.TranslateSkinBool(params[0]);
g_settings.SetSkinBool(string, params[1].CompareNoCase("true") == 0);
g_settings.Save();
return 0;
}
// default is to set it to true
int setting = g_settings.TranslateSkinBool(params[0]);
g_settings.SetSkinBool(setting, true);
g_settings.Save();
}
else if (execute.Equals("skin.reset"))
{
g_settings.ResetSkinSetting(parameter);
g_settings.Save();
}
else if (execute.Equals("skin.resetsettings"))
{
g_settings.ResetSkinSettings();
g_settings.Save();
}
else if (execute.Equals("skin.theme"))
{
// enumerate themes
vector<CStdString> vecTheme;
CUtil::GetSkinThemes(vecTheme);
int iTheme = -1;
// find current theme
if (!g_guiSettings.GetString("lookandfeel.skintheme").Equals("SKINDEFAULT"))
{
for (unsigned int i=0;i<vecTheme.size();++i)
{
CStdString strTmpTheme(g_guiSettings.GetString("lookandfeel.skintheme"));
URIUtils::RemoveExtension(strTmpTheme);
if (vecTheme[i].Equals(strTmpTheme))
{
iTheme=i;
break;
}
}
}
int iParam = atoi(parameter.c_str());
if (iParam == 0 || iParam == 1)
iTheme++;
else if (iParam == -1)
iTheme--;
if (iTheme > (int)vecTheme.size()-1)
iTheme = -1;
if (iTheme < -1)
iTheme = vecTheme.size()-1;
CStdString strSkinTheme = "SKINDEFAULT";
if (iTheme != -1 && iTheme < (int)vecTheme.size())
strSkinTheme = vecTheme[iTheme];
g_guiSettings.SetString("lookandfeel.skintheme", strSkinTheme);
// also set the default color theme
CStdString colorTheme(URIUtils::ReplaceExtension(strSkinTheme, ".xml"));
if (colorTheme.Equals("Textures.xml"))
colorTheme = "defaults.xml";
g_guiSettings.SetString("lookandfeel.skincolors", colorTheme);
g_application.ReloadSkin();
}
else if (execute.Equals("skin.setstring") || execute.Equals("skin.setimage") || execute.Equals("skin.setfile") ||
execute.Equals("skin.setpath") || execute.Equals("skin.setnumeric") || execute.Equals("skin.setlargeimage"))
{
// break the parameter up if necessary
int string = 0;
if (params.size() > 1)
{
string = g_settings.TranslateSkinString(params[0]);
if (execute.Equals("skin.setstring"))
{
g_settings.SetSkinString(string, params[1]);
g_settings.Save();
return 0;
}
}
else
string = g_settings.TranslateSkinString(params[0]);
CStdString value = g_settings.GetSkinString(string);
VECSOURCES localShares;
g_mediaManager.GetLocalDrives(localShares);
if (execute.Equals("skin.setstring"))
{
if (CGUIKeyboardFactory::ShowAndGetInput(value, g_localizeStrings.Get(1029), true))
g_settings.SetSkinString(string, value);
}
else if (execute.Equals("skin.setnumeric"))
{
if (CGUIDialogNumeric::ShowAndGetNumber(value, g_localizeStrings.Get(611)))
g_settings.SetSkinString(string, value);
}
else if (execute.Equals("skin.setimage"))
{
if (CGUIDialogFileBrowser::ShowAndGetImage(localShares, g_localizeStrings.Get(1030), value))
g_settings.SetSkinString(string, value);
}
else if (execute.Equals("skin.setlargeimage"))
{
VECSOURCES *shares = g_settings.GetSourcesFromType("pictures");
if (!shares) shares = &localShares;
if (CGUIDialogFileBrowser::ShowAndGetImage(*shares, g_localizeStrings.Get(1030), value))
g_settings.SetSkinString(string, value);
}
else if (execute.Equals("skin.setfile"))
{
// Note. can only browse one addon type from here
// if browsing for addons, required param[1] is addontype string, with optional param[2]
// as contenttype string see IAddon.h & ADDON::TranslateXX
CStdString strMask = (params.size() > 1) ? params[1] : "";
strMask.ToLower();
ADDON::TYPE type;
if ((type = TranslateType(strMask)) != ADDON_UNKNOWN)
{
CURL url;
url.SetProtocol("addons");
url.SetHostName("enabled");
url.SetFileName(strMask+"/");
localShares.clear();
CStdString content = (params.size() > 2) ? params[2] : "";
content.ToLower();
url.SetPassword(content);
CStdString strMask;
if (type == ADDON_SCRIPT)
strMask = ".py";
CStdString replace;
if (CGUIDialogFileBrowser::ShowAndGetFile(url.Get(), strMask, TranslateType(type, true), replace, true, true, true))
{
if (replace.Mid(0,9).Equals("addons://"))
g_settings.SetSkinString(string, URIUtils::GetFileName(replace));
else
g_settings.SetSkinString(string, replace);
}
}
else
{
if (params.size() > 2)
{
value = params[2];
URIUtils::AddSlashAtEnd(value);
bool bIsSource;
if (CUtil::GetMatchingSource(value,localShares,bIsSource) < 0) // path is outside shares - add it as a separate one
{
CMediaSource share;
share.strName = g_localizeStrings.Get(13278);
share.strPath = value;
localShares.push_back(share);
}
}
if (CGUIDialogFileBrowser::ShowAndGetFile(localShares, strMask, g_localizeStrings.Get(1033), value))
g_settings.SetSkinString(string, value);
}
}
else // execute.Equals("skin.setpath"))
{
g_mediaManager.GetNetworkLocations(localShares);
if (params.size() > 1)
{
value = params[1];
URIUtils::AddSlashAtEnd(value);
bool bIsSource;
if (CUtil::GetMatchingSource(value,localShares,bIsSource) < 0) // path is outside shares - add it as a separate one
{
CMediaSource share;
share.strName = g_localizeStrings.Get(13278);
share.strPath = value;
localShares.push_back(share);
}
}
if (CGUIDialogFileBrowser::ShowAndGetDirectory(localShares, g_localizeStrings.Get(1031), value))
g_settings.SetSkinString(string, value);
}
g_settings.Save();
}
else if (execute.Equals("skin.setaddon") && params.size() > 1)
{
int string = g_settings.TranslateSkinString(params[0]);
vector<ADDON::TYPE> types;
for (unsigned int i = 1 ; i < params.size() ; i++)
{
ADDON::TYPE type = TranslateType(params[i]);
if (type != ADDON_UNKNOWN)
types.push_back(type);
}
CStdString result;
if (types.size() > 0 && CGUIWindowAddonBrowser::SelectAddonID(types, result, true) == 1)
{
g_settings.SetSkinString(string, result);
g_settings.Save();
}
}
else if (execute.Equals("dialog.close") && params.size())
{
bool bForce = false;
if (params.size() > 1 && params[1].CompareNoCase("true") == 0)
bForce = true;
if (params[0].CompareNoCase("all") == 0)
{
g_windowManager.CloseDialogs(bForce);
}
else
{
int id = CButtonTranslator::TranslateWindow(params[0]);
CGUIWindow *window = (CGUIWindow *)g_windowManager.GetWindow(id);
if (window && window->IsDialog())
((CGUIDialog *)window)->Close(bForce);
}
}
else if (execute.Equals("system.logoff"))
{
// there was a commit from cptspiff here which was reverted
// for keeping the behaviour from Eden in Frodo - see
// git rev 9ee5f0047b
if (g_windowManager.GetActiveWindow() == WINDOW_LOGIN_SCREEN)
return -1;
g_application.StopPlaying();
if (g_application.IsMusicScanning())
g_application.StopMusicScan();
if (g_application.IsVideoScanning())
g_application.StopVideoScan();
ADDON::CAddonMgr::Get().StopServices(true);
g_application.getNetwork().NetworkMessage(CNetwork::SERVICES_DOWN,1);
g_settings.LoadMasterForLogin();
g_passwordManager.bMasterUser = false;
g_windowManager.ActivateWindow(WINDOW_LOGIN_SCREEN);
if (!g_application.StartEventServer()) // event server could be needed in some situations
CGUIDialogKaiToast::QueueNotification("DefaultIconWarning.png", g_localizeStrings.Get(33102), g_localizeStrings.Get(33100));
}
else if (execute.Equals("pagedown"))
{
int id = atoi(parameter.c_str());
CGUIMessage message(GUI_MSG_PAGE_DOWN, g_windowManager.GetFocusedWindow(), id);
g_windowManager.SendMessage(message);
}
else if (execute.Equals("pageup"))
{
int id = atoi(parameter.c_str());
CGUIMessage message(GUI_MSG_PAGE_UP, g_windowManager.GetFocusedWindow(), id);
g_windowManager.SendMessage(message);
}
else if (execute.Equals("updatelibrary") && params.size())
{
if (params[0].Equals("music"))
{
if (g_application.IsMusicScanning())
g_application.StopMusicScan();
else
g_application.StartMusicScan(params.size() > 1 ? params[1] : "");
}
if (params[0].Equals("video"))
{
if (g_application.IsVideoScanning())
g_application.StopVideoScan();
else
g_application.StartVideoScan(params.size() > 1 ? params[1] : "");
}
}
else if (execute.Equals("cleanlibrary"))
{
if (!params.size() || params[0].Equals("video"))
{
if (!g_application.IsVideoScanning())
g_application.StartVideoCleanup();
else
CLog::Log(LOGERROR, "XBMC.CleanLibrary is not possible while scanning or cleaning");
}
else if (params[0].Equals("music"))
{
if (!g_application.IsMusicScanning())
{
CMusicDatabase musicdatabase;
musicdatabase.Open();
musicdatabase.Cleanup();
musicdatabase.Close();
}
else
CLog::Log(LOGERROR, "XBMC.CleanLibrary is not possible while scanning for media info");
}
}
else if (execute.Equals("exportlibrary"))
{
int iHeading = 647;
if (params[0].Equals("music"))
iHeading = 20196;
CStdString path;
VECSOURCES shares;
g_mediaManager.GetLocalDrives(shares);
bool singleFile;
bool thumbs=false;
bool actorThumbs=false;
bool overwrite=false;
bool cancelled=false;
if (params.size() > 1)
singleFile = params[1].Equals("true");
else
singleFile = CGUIDialogYesNo::ShowAndGetInput(iHeading,20426,20427,-1,20428,20429,cancelled);
if (cancelled)
return -1;
if (singleFile)
{
if (params.size() > 2)
thumbs = params[2].Equals("true");
else
thumbs = CGUIDialogYesNo::ShowAndGetInput(iHeading,20430,-1,-1,cancelled);
}
if (cancelled)
return -1;
if (thumbs && params[0].Equals("video"))
{
if (params.size() > 4)
actorThumbs = params[4].Equals("true");
else
actorThumbs = CGUIDialogYesNo::ShowAndGetInput(iHeading,20436,-1,-1,cancelled);
}
if (cancelled)
return -1;
if (singleFile)
{
if (params.size() > 3)
overwrite = params[3].Equals("true");
else
overwrite = CGUIDialogYesNo::ShowAndGetInput(iHeading,20431,-1,-1,cancelled);
}
if (cancelled)
return -1;
if (params.size() > 2)
path=params[2];
if (singleFile || !path.IsEmpty() ||
CGUIDialogFileBrowser::ShowAndGetDirectory(shares,
g_localizeStrings.Get(661), path, true))
{
if (params[0].Equals("video"))
{
CVideoDatabase videodatabase;
videodatabase.Open();
videodatabase.ExportToXML(path, singleFile, thumbs, actorThumbs, overwrite);
videodatabase.Close();
}
else
{
if (URIUtils::HasSlashAtEnd(path))
URIUtils::AddFileToFolder(path, "musicdb.xml", path);
CMusicDatabase musicdatabase;
musicdatabase.Open();
musicdatabase.ExportToXML(path, singleFile, thumbs, overwrite);
musicdatabase.Close();
}
}
}
else if (execute.Equals("lastfm.love"))
{
CLastFmManager::GetInstance()->Love(parameter.Equals("false") ? false : true);
}
else if (execute.Equals("lastfm.ban"))
{
CLastFmManager::GetInstance()->Ban(parameter.Equals("false") ? false : true);
}
else if (execute.Equals("control.move") && params.size() > 1)
{
CGUIMessage message(GUI_MSG_MOVE_OFFSET, g_windowManager.GetFocusedWindow(), atoi(params[0].c_str()), atoi(params[1].c_str()));
g_windowManager.SendMessage(message);
}
else if (execute.Equals("container.refresh"))
{ // NOTE: These messages require a media window, thus they're sent to the current activewindow.
// This shouldn't stop a dialog intercepting it though.
CGUIMessage message(GUI_MSG_NOTIFY_ALL, g_windowManager.GetActiveWindow(), 0, GUI_MSG_UPDATE, 1); // 1 to reset the history
message.SetStringParam(parameter);
g_windowManager.SendMessage(message);
}
else if (execute.Equals("container.update") && params.size())
{
CGUIMessage message(GUI_MSG_NOTIFY_ALL, g_windowManager.GetActiveWindow(), 0, GUI_MSG_UPDATE, 0);
message.SetStringParam(params[0]);
if (params.size() > 1 && params[1].CompareNoCase("replace") == 0)
message.SetParam2(1); // reset the history
g_windowManager.SendMessage(message);
}
else if (execute.Equals("container.nextviewmode"))
{
CGUIMessage message(GUI_MSG_CHANGE_VIEW_MODE, g_windowManager.GetActiveWindow(), 0, 0, 1);
g_windowManager.SendMessage(message);
}
else if (execute.Equals("container.previousviewmode"))
{
CGUIMessage message(GUI_MSG_CHANGE_VIEW_MODE, g_windowManager.GetActiveWindow(), 0, 0, -1);
g_windowManager.SendMessage(message);
}
else if (execute.Equals("container.setviewmode"))
{
CGUIMessage message(GUI_MSG_CHANGE_VIEW_MODE, g_windowManager.GetActiveWindow(), 0, atoi(parameter.c_str()));
g_windowManager.SendMessage(message);
}
else if (execute.Equals("container.nextsortmethod"))
{
CGUIMessage message(GUI_MSG_CHANGE_SORT_METHOD, g_windowManager.GetActiveWindow(), 0, 0, 1);
g_windowManager.SendMessage(message);
}
else if (execute.Equals("container.previoussortmethod"))
{
CGUIMessage message(GUI_MSG_CHANGE_SORT_METHOD, g_windowManager.GetActiveWindow(), 0, 0, -1);
g_windowManager.SendMessage(message);
}
else if (execute.Equals("container.setsortmethod"))
{
CGUIMessage message(GUI_MSG_CHANGE_SORT_METHOD, g_windowManager.GetActiveWindow(), 0, atoi(parameter.c_str()));
g_windowManager.SendMessage(message);
}
else if (execute.Equals("container.sortdirection"))
{
CGUIMessage message(GUI_MSG_CHANGE_SORT_DIRECTION, g_windowManager.GetActiveWindow(), 0, 0);
g_windowManager.SendMessage(message);
}
else if (execute.Equals("control.message") && params.size() >= 2)
{
int controlID = atoi(params[0].c_str());
int windowID = (params.size() == 3) ? CButtonTranslator::TranslateWindow(params[2]) : g_windowManager.GetActiveWindow();
if (params[1] == "moveup")
g_windowManager.SendMessage(GUI_MSG_MOVE_OFFSET, windowID, controlID, 1);
else if (params[1] == "movedown")
g_windowManager.SendMessage(GUI_MSG_MOVE_OFFSET, windowID, controlID, -1);
else if (params[1] == "pageup")
g_windowManager.SendMessage(GUI_MSG_PAGE_UP, windowID, controlID);
else if (params[1] == "pagedown")
g_windowManager.SendMessage(GUI_MSG_PAGE_DOWN, windowID, controlID);
else if (params[1] == "click")
g_windowManager.SendMessage(GUI_MSG_CLICKED, controlID, windowID);
}
else if (execute.Equals("sendclick") && params.size())
{
if (params.size() == 2)
{
// have a window - convert it
int windowID = CButtonTranslator::TranslateWindow(params[0]);
CGUIMessage message(GUI_MSG_CLICKED, atoi(params[1].c_str()), windowID);
g_windowManager.SendMessage(message);
}
else
{ // single param - assume you meant the active window
CGUIMessage message(GUI_MSG_CLICKED, atoi(params[0].c_str()), g_windowManager.GetActiveWindow());
g_windowManager.SendMessage(message);
}
}
else if (execute.Equals("action") && params.size())
{
// try translating the action from our ButtonTranslator
int actionID;
if (CButtonTranslator::TranslateActionString(params[0].c_str(), actionID))
{
int windowID = params.size() == 2 ? CButtonTranslator::TranslateWindow(params[1]) : WINDOW_INVALID;
CApplicationMessenger::Get().SendAction(CAction(actionID), windowID);
}
}
else if (execute.Equals("setproperty") && params.size() >= 2)
{
CGUIWindow *window = g_windowManager.GetWindow(params.size() > 2 ? CButtonTranslator::TranslateWindow(params[2]) : g_windowManager.GetFocusedWindow());
if (window)
window->SetProperty(params[0],params[1]);
}
else if (execute.Equals("clearproperty") && params.size())
{
CGUIWindow *window = g_windowManager.GetWindow(params.size() > 1 ? CButtonTranslator::TranslateWindow(params[1]) : g_windowManager.GetFocusedWindow());
if (window)
window->SetProperty(params[0],"");
}
else if (execute.Equals("wakeonlan"))
{
g_application.getNetwork().WakeOnLan((char*)params[0].c_str());
}
else if (execute.Equals("addon.default.opensettings") && params.size() == 1)
{
AddonPtr addon;
ADDON::TYPE type = TranslateType(params[0]);
if (CAddonMgr::Get().GetDefault(type, addon))
{
CGUIDialogAddonSettings::ShowAndGetInput(addon);
if (type == ADDON_VIZ)
g_windowManager.SendMessage(GUI_MSG_VISUALISATION_RELOAD, 0, 0);
}
}
else if (execute.Equals("addon.default.set") && params.size() == 1)
{
CStdString addonID;
TYPE type = TranslateType(params[0]);
bool allowNone = false;
if (type == ADDON_VIZ)
allowNone = true;
if (type != ADDON_UNKNOWN &&
CGUIWindowAddonBrowser::SelectAddonID(type,addonID,allowNone))
{
CAddonMgr::Get().SetDefault(type,addonID);
if (type == ADDON_VIZ)
g_windowManager.SendMessage(GUI_MSG_VISUALISATION_RELOAD, 0, 0);
}
}
else if (execute.Equals("addon.opensettings") && params.size() == 1)
{
AddonPtr addon;
if (CAddonMgr::Get().GetAddon(params[0], addon))
CGUIDialogAddonSettings::ShowAndGetInput(addon);
}
else if (execute.Equals("updateaddonrepos"))
{
CAddonInstaller::Get().UpdateRepos(true);
}
else if (execute.Equals("updatelocaladdons"))
{
CAddonMgr::Get().FindAddons();
}
else if (execute.Equals("toggledpms"))
{
g_application.ToggleDPMS(true);
}
#if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
else if (execute.Equals("lirc.stop"))
{
g_RemoteControl.Disconnect();
g_RemoteControl.setUsed(false);
}
else if (execute.Equals("lirc.start"))
{
g_RemoteControl.setUsed(true);
g_RemoteControl.Initialize();
}
else if (execute.Equals("lirc.send"))
{
CStdString command;
for (int i = 0; i < (int)params.size(); i++)
{
command += params[i];
if (i < (int)params.size() - 1)
command += ' ';
}
g_RemoteControl.AddSendCommand(command);
}
#endif
#ifdef HAS_LCD
else if (execute.Equals("lcd.suspend"))
{
g_lcd->Suspend();
}
else if (execute.Equals("lcd.resume"))
{
g_lcd->Resume();
}
#endif
else if (execute.Equals("weather.locationset"))
{
int loc = atoi(params[0]);
CGUIMessage msg(GUI_MSG_ITEM_SELECT, 0, 0, loc);
g_windowManager.SendMessage(msg, WINDOW_WEATHER);
}
else if (execute.Equals("weather.locationnext"))
{
CGUIMessage msg(GUI_MSG_MOVE_OFFSET, 0, 0, 1);
g_windowManager.SendMessage(msg, WINDOW_WEATHER);
}
else if (execute.Equals("weather.locationprevious"))
{
CGUIMessage msg(GUI_MSG_MOVE_OFFSET, 0, 0, -1);
g_windowManager.SendMessage(msg, WINDOW_WEATHER);
}
else if (execute.Equals("weather.refresh"))
{
CGUIMessage msg(GUI_MSG_MOVE_OFFSET, 0, 0, 0);
g_windowManager.SendMessage(msg, WINDOW_WEATHER);
}
else if (execute.Equals("videolibrary.search"))
{
CGUIMessage msg(GUI_MSG_SEARCH, 0, 0, 0);
g_windowManager.SendMessage(msg, WINDOW_VIDEO_NAV);
}
else if (execute.Equals("toggledebug"))
{
bool debug = g_guiSettings.GetBool("debug.showloginfo");
g_guiSettings.SetBool("debug.showloginfo", !debug);
g_advancedSettings.SetDebugMode(!debug);
}
else if (execute.Equals("startpvrmanager"))
{
g_application.StartPVRManager();
}
else if (execute.Equals("stoppvrmanager"))
{
g_application.StopPVRManager();
}
else if (execute.Equals("setsizemanual"))
{
if (!params.size())
{
CLog::Log(LOGERROR, "SetSizeManual called with empty parameter");
return -2;
}
CGUIMessage msg(GUI_MSG_SETTING_SLIDSHOWSIZE, 0, 0, 0);
msg.SetStringParam(params[0]);
CGUIWindow *pWindow = g_windowManager.GetWindow(WINDOW_SLIDESHOW);
if (pWindow) pWindow->OnMessage(msg);
g_renderManager.SetSizeManual(params[0]); //set video size.
}
else if (execute.Equals("updatetwitter"))
{
if (!params.size())
{
CLog::Log(LOGERROR, "UpdateTwitter called with empty parameter");
return -2;
}
g_infoManager.SetTwitterInfo(params[0]);
}
else
return -1;
return 0;
}
|
inn1983/teropi
|
xbmc/interfaces/Builtins.cpp
|
C++
|
gpl-2.0
| 59,879
|
/*
Author: The Happy Bit
Author URI: http://thehappybit.com
License: GNU General Public License version 3.0
License URI: http://www.gnu.org/licenses/gpl-3.0.html
Version: 1.0
*/
#sc-form { }
#sc-form h3 { font-size: 14px; display: block; color: #333; font-weight: normal; font-style: normal; text-transform: uppercase; }
#sc-container { margin: 15px 0 10px; border: 1px solid #ccc; }
.sc-row { padding: 8px 10px; background-color: #fff; clear: both; }
.left-col { float: left; width: 130px; margin-right: 10px; }
.right-col { }
.sc-row label { line-height: 18px; }
.sc-row input[type="text"], .sc-row textarea { padding: 5px 10px; }
.sc-row input[type="checkbox"] { }
.sc-row.border { border-bottom: 1px solid #e6e6e6; }
.sc-footer-row { }
#cancel { float: left;
/* background: #cf2417 !important; color: #fff !important; border-color: #b51e13 !important; */
}
#insert { float: right; background: #78a539 !important; color: #fff !important; border-color: #668c31 !important; }
#insert:hover, #cancel:hover { border: 1px solid rgba(0,0,0,.8) !important; }
.clear { display: block; clear: both; }
|
successdt/chamsoctruocvasausinh
|
wp-content/themes/metropolis/config/shortcodes/shortcode_style.css
|
CSS
|
gpl-2.0
| 1,108
|
#ifndef _GLOBVAR_H
#define _GLOBVAR_H
#include <windows.h>
#include "global.h"
#include "boe.newgraph.h"
extern RECT bottom_buttons[7];
extern RECT town_buttons[10];
extern RECT combat_buttons[9];
extern RECT world_screen;
extern RECT item_screen_button_rects[9];
extern RECT border_rect[4];
extern RECT medium_buttons[4];
extern RECT startup_top;
extern RECT item_buttons[8][6]; // name, use, give, drip, info, sell/id
extern RECT pc_buttons[6][5]; // name, hp, sp, info, trade
extern pending_special_type special_queue[20];
extern Boolean end_scenario ;
extern short refer_priest[62];
extern short mage_need_select[62];
extern short priest_need_select[62];
extern Boolean item_area_button_active[8][6];
extern Boolean pc_area_button_active[6][5];
extern short item_bottom_button_active[9];
extern RECT pc_help_button,pc_area_rect,item_area_rect;
extern short current_terrain_type, num_out_moves;
extern short door_pc,store_drop_item;
extern short current_switch;
extern out_wandering_type store_wandering_special;
extern long dummy;
extern short store_shop_type;
extern short debug_ok;
extern short store_selling_values[8];
extern char *dir_string[8];
extern char get_new_terrain();
extern creature_start_type save_monster_type;
extern short wand_loc_count;
extern short monst_place_count; // 1 - standard place 2 - place last
extern item_record_type start_items[6];
extern RECT shopping_rects[8][7];
extern unsigned char out[96][96];
extern unsigned char out_e[96][96];
extern unsigned char misc_i[64][64],sfx[64][64];
/* Mac stuff globals */
extern HWND text_sbar, item_sbar, shop_sbar;
extern RECT sbar_rect;
extern RECT shop_sbar_rect;
extern RECT item_sbar_rect;
extern int dialog_answer;
extern Boolean All_Done, dialog_not_toast;
extern Boolean in_startup_mode ;
//extern Boolean play_sounds;
extern Boolean diff_depth_ok ,spell_forced ,startup_loaded ;
extern Boolean save_maps ,party_in_memory ,in_scen_debug ;
extern Boolean window_in_front ;
extern Boolean belt_present ;
extern Boolean game_run_before ;
extern Boolean give_intro_hint ;
extern short on_spell_menu[2][62];
extern short on_monst_menu[256];
extern short current_cursor;
extern HCURSOR arrow_curs[3][3], sword_curs, key_curs, target_curs,talk_curs,look_curs;
extern party_record_type party;
extern outdoor_record_type outdoors[2][2];
extern current_town_type c_town;
extern big_tr_type t_d;
extern stored_items_list t_i;
extern setup_save_type setup_save;
extern location monster_targs[T_M];
extern short combat_posing_monster, current_working_monster; // 0-5 PC 100 + x - monster x
extern Boolean fast_bang ;
extern short spec_item_array[60];
extern short overall_mode,current_spell_range;
extern Boolean first_update ,anim_onscreen ,frills_on ,sys_7_avail,suppress_stat_screen ;
extern short stat_window,store_modifier;
extern Boolean monsters_going, boom_anim_active;
extern short give_delays;
extern Boolean modeless_exists[18];
extern short modeless_key[18];
extern HWND modeless_dialogs[18];
extern short town_size[3];
extern short which_item_page[6]; // Remembers which of the 2 item pages pc looked at
extern short ulx, uly;
extern short display_mode; // 0 - center 1- ul 2 - ur 3 - dl 4 - dr 5 - small win
extern short current_ground,stat_screen_mode;
extern long anim_ticks;
// Spell casting globals
extern short store_mage, store_priest;
extern short store_mage_lev, store_priest_lev;
extern short store_spell_target,pc_casting;
extern short pc_last_cast[2][6];
extern int num_targets_left;
extern location spell_targets[8];
extern long store_mouse;
/* Combat globals */
extern short which_combat_type,town_type;
extern location center;
extern unsigned char combat_terrain[64][64];
extern location pc_pos[6];
extern short current_pc;
extern short combat_active_pc;
extern effect_pat_type current_pat;
extern short monst_target[T_M]; // 0-5 target that pc 6 - no target 100 + x - target monster x
extern short spell_caster, missile_firer,current_monst_tactic;
extern short store_current_pc;
extern stored_items_list stored_items[3];
extern stored_outdoor_maps_type o_maps;
// Special stuff booleans
extern Boolean web,crate,barrel,fire_barrier,force_barrier,quickfire,force_wall,fire_wall,antimagic,scloud,ice_wall,blade_wall;
extern Boolean sleep_field;
extern long last_anim_time;
/* Windoze stuff globals */
extern Boolean cursor_shown ;
extern short store_pc_being_created;
extern HWND mainPtr;
extern HWND force_dlog;
extern HFONT font,fantasy_font,small_bold_font,italic_font,underline_font,bold_font,tiny_font;
extern HBITMAP bmap;
extern HDC main_dc,main_dc2,main_dc3;
extern HINSTANCE store_hInstance;
extern HACCEL accel;
extern BOOL event_handled;
extern scenario_data_type scenario;
extern talking_record_type talking;
extern char scen_strs2[110][256];
extern stored_town_maps_type town_maps;
extern char szWinName[12];
extern char szAppName[14];
extern char file_path_name[256];
extern Boolean block_erase ;
/* dynamically allocated */
extern piles_of_stuff_dumping_type *data_store;
extern piles_of_stuff_dumping_type2 *data_store2;
extern piles_of_stuff_dumping_type3 *data_store3;
extern piles_of_stuff_dumping_type4 *data_store4;
extern piles_of_stuff_dumping_type5 *data_store5;
extern scen_item_data_type *scen_item_list;
extern scen_header_type *scen_headers;
/* end of dynamically allocated */
extern char create_line[60];
extern short spell_being_cast;
extern short missile_inv_slot, ammo_inv_slot;
extern short force_wall_position; // 10 -> no force wall
extern Boolean processing_fields ;
extern short futzing;
extern unsigned char store_sum_monst;
extern short store_sum_monst_cost;
extern location out_start_loc;
extern short hit_chance[51];
extern short abil_range[40];
extern short abil_odds[40];
extern short s_cost[2][62] ;
extern short mage_range[80];
extern short priest_range[62];
extern short monst_mage_spell[55];
extern short monst_cleric_spell[55];
extern short monst_mage_cost[27];
extern short monst_mage_area_effect[27];
extern short monst_priest_cost[26];
extern short monst_priest_area_effect[26];
extern char *d_string[8];
extern short pc_marked_damage[6];
extern short monst_marked_damage[T_M];
extern location hor_vert_place[14];
extern location diag_place[14];
extern unsigned char beasts[5];
extern unsigned char m1[20];
extern unsigned char m2[16];
extern unsigned char m3[16];
extern short mage_caster_array[7][18];
extern short mage_emer_spells[7][4];
extern short priest_caster_array[7][10];
extern short priest_emer_spells[7][4];
extern effect_pat_type null_pat;
extern effect_pat_type single;
extern effect_pat_type t;
extern effect_pat_type small_square;
extern effect_pat_type square;
extern effect_pat_type open_square;
extern effect_pat_type radius2;
extern effect_pat_type radius3;
extern effect_pat_type field[8];
extern short last_attacked[6],pc_dir[6],pc_parry[6],pc_moves[6];
extern Boolean center_on_monst;
extern short sign_mode,person_graphic,store_person_graphic,store_sign_mode;
extern long num_talk_entries;
extern short store_tip_page_on;
extern short store_pre_talk_mode,store_personality,store_personality_graphic,shop_identify_cost;
extern HBITMAP talk_gworld;
extern Boolean talk_end_forced;
extern char old_str1[256];
extern char old_str2[256];
extern char one_back1[256];
extern char one_back2[256];
extern RECT talk_area_rect, word_place_rect,talk_help_rect;
/**/
extern char title_string[50];
extern unsigned char store_monst_type;
extern short store_m_num;
extern RECT dummy_rect;
extern short strnum1,strnum2,oldstrnum1,oldstrnum2;
extern short store_talk_face_pic,cur_town_talk_loaded;
extern short store_shop_items[30];
extern short store_shop_costs[30];
extern short store_shop_min,store_shop_max,store_pre_shop_mode,store_cost_mult;
extern char store_store_name[256];
extern RECT bottom_help_rects[4];
extern RECT shop_frame;
extern RECT shop_done_rect; /**/
extern char *heal_types[9];
extern short heal_costs[9];
extern long cost_mult[7];
extern short cur_display_mode;
extern short terrain_pic[256];
extern short store_scen_page_on,store_num_scen;
#define ND 15
#define NI 500
#define NL 100
#define NUM_DLOG_B 53
extern char text_long_str[10][256];
extern char text_short_str[140][35];
extern char labels[NL][25];
extern Boolean label_taken[NL];
extern HWND edit_box, talk_edit_box;
extern HWND store_edit_parent; // kludgy
extern HDC dlg_force_dc; // save HDCs when dealing with dlogs
extern short store_free_slot,store_dlog_num;
extern HWND store_parent;
extern short available_dlog_buttons[NUM_DLOG_B];
extern short button_type[150];
extern char *button_strs[150];
extern short button_left_adj[150];
extern char button_def_key[150];
extern short button_ul_x[15];
extern short button_ul_y[15];
extern short button_width[15];
extern short button_height[15];
extern DLGPROC d_proc;
extern WNDPROC edit_proc;
extern WNDPROC old_edit_proc;
//#define NUM_SOUNDS 100
extern HGLOBAL sound_handles[NUM_SOUNDS];
extern char * snds[NUM_SOUNDS];
extern short last_played;
extern short store_last_sound_played;
//extern bool always_asynch[100];
//extern Boolean load_when_play[100];
extern short can_ignore[100];
extern short num_devs;
extern Boolean sounds_fucked ;
extern long intro_music_start_time;
extern HWND the_dialog;
extern HBITMAP spec_scen_g;
extern Boolean loaded_yet , got_nagged ,ae_loading ;
extern Boolean cur_scen_is_win ;
extern void print_write_position ();
extern char last_load_file[63];
extern char szFileName [128];
extern char szTitleName [128];
extern OPENFILENAME ofn;
extern OFSTRUCT save_dir,save_dir2;
extern SCROLLINFO lpsi;
extern MSG msg;
extern BITMAP bitmap_info;
// Trying this to fix bug. Hope it works.
extern tiny_tr_type tiny_t;
extern ave_tr_type ave_t;
extern outdoor_record_type dummy_out;////
extern town_record_type dummy_town;
extern short jl;
extern HBITMAP bg_bitmap[14];
extern HBRUSH checker_brush;
extern HBITMAP checker_bitmap,bw_bitmap;
extern HBITMAP startup_button_orig,startup_button_g,anim_mess ;
extern Boolean done_fancy_startup_once ;
extern short terrain_there[9][9];
extern RECT win_from_rects[6];
extern RECT win_to_rects[6];
// 0 - title 1 - button 2 - credits 3 - base button
extern RECT startup_from[4];
extern RECT trim_rects[8];
extern RECT top_left_rec;
extern char combat_graphics[5];
extern short debug_nums[6];
extern short remember_tiny_text; // Remembers what's in the tiny text-bar, to prevent redrawing.
extern char light_area[13][13];
extern char unexplored_area[13][13];
// Declare the graphics
extern HBITMAP mixed_gworld, pc_stats_gworld, item_stats_gworld, text_area_gworld;
extern HBITMAP terrain_screen_gworld,text_bar_gworld,orig_text_bar_gworld,buttons_gworld;
extern HBITMAP items_gworld,tiny_obj_gworld,fields_gworld;
extern HBITMAP dlg_buttons_gworld,missiles_gworld,dlogpics_gworld,small_temp_gworld;
extern HBITMAP talking_portraits_gworld, frills_gworld, ter_anim_gworld,monsters_gworld[10], terrains_gworld[6];
extern HBITMAP displayed_picture;
extern HBITMAP dialog_pattern_gworld,pattern_gworld,status_pattern_gworld;
// Startup graphics, will die when play starts
extern HBITMAP startup_gworld;
extern HRGN clip_region;
extern HBRUSH gbrush;
extern HPEN gpen;
extern Boolean has_run_anim ;
extern RECT main_win_rect;
extern RECT main_win2_source_rect;
extern RECT main_win2_rect ;
extern RECT tiny_world_1_source_rect,tiny_world_1_rect;
extern RECT share_mess_source_rect,
share_mess_rect;
extern RECT start_buttons_source_rect,
start_buttons_rect; /**/
// Variables to store trim. Makes game faster, but wastes 15K. We'll see how it works...
extern char out_trim[96][96];
extern char town_trim[64][64];
// Array to store which spots have been seen. Time-saver for drawing fields
extern char spot_seen[9][9];
extern short startup_anim_pos;
extern Boolean supressing_some_spaces ;
extern location ok_space[4];
extern char combat_string[100];
extern BOOL pal_ok ;
extern Boolean syscolors_stored ;
extern int elements[5];
extern COLORREF store_element_colors[5];
extern short dlog_pat_placed;
extern short current_pattern;
extern RECT boat_rects[4]; /**/
extern Boolean gave_no_g_error ;
extern unsigned char m_pic_sheet[200];
extern unsigned char m_pic_index[200];
extern unsigned char m_pic_index_x[200];
extern unsigned char m_pic_index_y[200];
extern short mage_spell_pos,priest_spell_pos,skill_pos;
extern pc_record_type *store_pc;
extern creature_data_type *store_m;
extern short store_trait_mode,store_item_pc,store_pc_num;
extern item_record_type store_i;
extern Boolean full_roster ;
extern location source_locs[6];
// Displaying string vars
extern short store_str1a;
extern short store_str1b;
extern short store_str2a;
extern short store_str2b;
extern short store_which_string_dlog;
extern short store_page_on,store_num_i;
extern short store_str_label_1,store_str_label_2,store_str_label_1b,store_str_label_2b;
// Misc dialog vars
extern short store_display_mode,store_displayed_item,position,cur_entry,num_entries,store_help_mode;
extern creature_data_type hold_m;
////
extern Boolean equippable[26];
extern short num_hands_to_use[26];
extern short num_that_can_equip[26];
// For following, if an item of type n is equipped, no other items of type n can be equipped,
// if n > 0
extern short excluding_types[26];
extern short selected,item_max;
extern short first_item_shown,store_get_mode,current_getting_pc,store_pcnum,total_items_gettable; // these 5 used for get items dialog
extern short item_array[130]; // NUM_TOWN_ITEMS + a bit
extern short answer_given;
extern char *store_str;
extern short store_dnum;
extern HWND test_dlog3;
extern HWND store_focus;
extern short being_created;
extern short procinst_exists[18];
extern char terrain_blocked[256];
extern short short_can_see();
extern Boolean combat_pt_in_light();
extern location obs_sec;
extern location which_party_sec;
extern location light_locs[40];
extern short num_lights;
extern char d_s[60];
extern short charm_odds[20];
extern creature_start_type null_start_type;
extern short monsters_faces[190];
extern HRGN oval_region,dark_mask_region,temp_rect_rgn;
extern short skill_cost[20];
extern short skill_g_cost[20];
extern short skill_bonus[21];
extern short spell_level[62];
extern short spell_cost[2][62];
extern const char *mage_s_name[];
extern char *priest_s_name[];
extern char *alch_names[];
extern char *alch_names_short[];
extern short spell_w_cast[2][62];
// 0 - everywhere 1 - combat only 2 - town only 3 - town & outdoor only 4 - town & combat only 5 - outdoor only
extern Boolean get_mage[30];
extern Boolean get_priest[30];
extern short combat_percent[20];
extern short town_spell,who_cast,which_pc_displayed;
extern Boolean spell_button_active[90];
extern char talk_edit_string[40];
extern char c_line[60];
// Variables for spell selection
extern short store_situation,store_last_target_darkened,on_which_spell_page;
extern short store_last_cast_mage ,store_last_cast_priest ;
extern short buttons_on[38];
// buttons_on determines which buttons can be hit when on the second spell page
extern short spell_index[38];
// Says which buttons hit which spells on second spell page, 90 means no button
extern Boolean can_choose_caster;
// Variables for spending xp
extern Boolean talk_done ;
extern long val_for_text;
extern Boolean keep_change ;
extern short store_skills[20],store_h,store_sp,i,store_skp,which_skill;
extern long store_g;
extern short store_train_mode,store_train_pc;
extern HBITMAP pcs_gworld;
// Dialog vars
extern short store_mage_store ;
extern short store_priest_store ;
extern short store_store_target;
extern short store_graphic_pc_num ;
extern short store_graphic_mode ;
extern short store_pc_graphic;
extern pc_array adven;
extern Boolean can_draw_pcs ;
extern short store_item_spell_level;
extern Boolean special_in_progress ;
extern item_record_type null_item;
extern short spec_str_offset[3];
extern short current_pc_picked_in_spec_enc ; // pc that's been selected, -1 if none
extern location store_special_loc;
extern short boom_gr[8] ;
extern short skill_max[20];
extern short abil_chart[200];
extern RECT startup_button[6];
extern short buf_pointer , lines_to_print, num_added_since_stop ;
extern char store_string[256];
extern char store_string2[256];
extern short start_print_point;
extern short mark_where_printing_long;
extern Boolean printing_long ;
extern char c_str[256];
extern Boolean save_mess_given ;
extern RECT status_panel_clip_rect,item_panel_clip_rect;
extern RECT item_buttons_from[7]; /**/
extern short store_mode;
extern Boolean string_added ;
extern short store_text_x , store_text_y ;
extern short current_item_button[6];
extern short pc_button_state[6];
extern char *m_mage_sp[];
extern char *m_priest_sp[];
// extra devices for maps
extern HBRUSH hbrush[6];
extern HPEN hpen[6];
extern RECT store_map_window_rect;
extern Boolean need_map_full_refresh ,forcing_map_button_redraw ;
extern HBITMAP map_gworld;
extern HBRUSH bg[14];
extern HBRUSH map_brush[25];
extern HBITMAP map_bitmap[25];
extern unsigned char map_pats[256];// 250
extern unsigned char anim_map_pats[18];
extern location town_map_adj ;
extern short town_force,store_min,store_max,store_shop;
extern location town_force_loc;
extern Boolean shop_button_active[12];
extern RECT map_title_rect; /**/
extern RECT map_bar_rect;
extern unsigned char map_graphic_placed[8][64]; // keeps track of what's been filled on map
extern Boolean kludge_force_full_refresh ;
extern word_rect_type preset_words[9];
extern word_rect_type store_words[50];
//Timer Special happened ?
extern BOOL timed_special_happened;
extern BOOL ghost_mode;
extern unsigned char queue_position;
#endif
|
mboeh/blades-ng
|
cpp/globvar.h
|
C
|
gpl-2.0
| 18,353
|
/***************************************************************************/
/* ____Demonstrates passing a stream to another process____ */
/* Process 0 initializes a random number stream and prints a few random */
/* numbers. It then passes this stream to process 1, which recieves it */
/* and prints a few random numbers from this stream. */
/***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h> /* MPI header file */
#define SIMPLE_SPRNG /* simple interface */
#include "sprng.h" /* SPRNG header file */
#define SEED 985456376
main(int argc, char *argv[])
{
double rn;
int i, myid, len, nprocs;
MPI_Status status;
char *packed;
/************************** MPI calls ************************************/
MPI_Init(&argc, &argv); /* Initialize MPI */
MPI_Comm_rank(MPI_COMM_WORLD, &myid); /* find process id */
MPI_Comm_size(MPI_COMM_WORLD, &nprocs); /* find number of processes */
if(nprocs < 2)
{
fprintf(stderr,"ERROR: At least 2 processes required\n");
MPI_Finalize();
exit(1);
}
if (myid==0) /*********** process 0 sends stream to process 1 ***********/
{
init_sprng(SEED,SPRNG_DEFAULT); /*initialize stream */
printf("Process %d: Print information about stream:\n",myid);
print_sprng();
printf("Process %d: Print 2 random numbers in [0,1):\n", myid);
for (i=0;i<2;i++)
{
rn = sprng(); /* generate double precision random number */
printf("Process %d: %f\n", myid, rn);
}
len = pack_sprng(&packed); /* pack stream into an array */
/* inform process 1 how many bytes process 0 will send. */
MPI_Send(&len, 1, MPI_INT, 1, 0, MPI_COMM_WORLD);
MPI_Send(packed, len, MPI_BYTE, 1, 0, MPI_COMM_WORLD); /* send stream */
free(packed); /* free storage for array */
printf(" Process 0 sends stream to process 1\n");
}
else if(myid == 1) /****** process 1 receives stream from process 0 *****/
{
init_sprng(SEED,SPRNG_DEFAULT); /*initialize stream */
MPI_Recv(&len, 1, MPI_INT, 0, MPI_ANY_TAG,
MPI_COMM_WORLD, &status); /* receive buffer size required */
if ((packed = (char *) malloc(len)) == NULL) /* allocate array */
{
fprintf(stderr,"ERROR: process %d: Cannot allocate memory\n", myid);
MPI_Finalize();
exit(1);
}
MPI_Recv(packed, len, MPI_BYTE, 0, MPI_ANY_TAG,
MPI_COMM_WORLD, &status); /* receive packed stream */
unpack_sprng(packed); /* unpack stream */
printf(" Process 1 has received the packed stream\n");
printf("Process %d: Print information about stream:\n",myid);
print_sprng();
free(packed); /* free array of packed stream */
printf(" Process 1 prints 2 numbers from received stream:\n");
for (i=0;i<2;i++)
{
rn = sprng(); /* generate double precision random number */
printf("Process %d: %f\n", myid, rn);
}
}
MPI_Finalize(); /* terminate MPI */
}
|
eliask/sprng
|
DOCS/www/examples/message-simple_mpi.c
|
C
|
gpl-2.0
| 3,374
|
/*
* algif_hash: User-space interface for hash algorithms
*
* This file provides the user-space API for hash algorithms.
*
* Copyright (c) 2010 Herbert Xu <herbert@gondor.apana.org.au>
*
* 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 <crypto/hash.h>
#include <crypto/sha.h>
#include <crypto/if_alg.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/net.h>
#include <net/sock.h>
struct hash_ctx {
struct af_alg_sgl sgl;
u8 *result;
struct af_alg_completion completion;
unsigned int len;
bool more;
struct ahash_request req;
};
static int hash_sendmsg(struct kiocb *unused, struct socket *sock,
struct msghdr *msg, size_t ignored)
{
int limit = ALG_MAX_PAGES * PAGE_SIZE;
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct hash_ctx *ctx = ask->private;
unsigned long iovlen;
struct iovec *iov;
long copied = 0;
int err;
if (limit > sk->sk_sndbuf)
limit = sk->sk_sndbuf;
lock_sock(sk);
if (!ctx->more) {
err = crypto_ahash_init(&ctx->req);
if (err)
goto unlock;
}
ctx->more = 0;
for (iov = msg->msg_iov, iovlen = msg->msg_iovlen; iovlen > 0;
iovlen--, iov++) {
unsigned long seglen = iov->iov_len;
char __user *from = iov->iov_base;
while (seglen) {
int len = min_t(unsigned long, seglen, limit);
int newlen;
newlen = af_alg_make_sg(&ctx->sgl, from, len, 0);
if (newlen < 0) {
err = copied ? 0 : newlen;
goto unlock;
}
#ifdef CONFIG_CRYPTO_HW
ahash_request_set_crypt(&ctx->req, ctx->sgl.sg, ctx->result, newlen);
if (crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req)) < SHA384_DIGEST_SIZE)
len = SHA1_BLOCK_SIZE;
else
len = SHA512_BLOCK_SIZE;
if (newlen%len) {
err = copy_from_user(ctx->req.result, &from[newlen - newlen%len],
newlen%len);
if (err)
goto unlock;
}
#else
ahash_request_set_crypt(&ctx->req, ctx->sgl.sg, NULL, newlen);
#endif
err = af_alg_wait_for_completion(
crypto_ahash_update(&ctx->req),
&ctx->completion);
af_alg_free_sg(&ctx->sgl);
if (err)
goto unlock;
seglen -= newlen;
from += newlen;
copied += newlen;
}
}
err = 0;
ctx->more = msg->msg_flags & MSG_MORE;
if (!ctx->more) {
ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0);
err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req),
&ctx->completion);
}
unlock:
release_sock(sk);
return err ?: copied;
}
static ssize_t hash_sendpage(struct socket *sock, struct page *page,
int offset, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct hash_ctx *ctx = ask->private;
int err;
if (flags & MSG_SENDPAGE_NOTLAST)
flags |= MSG_MORE;
lock_sock(sk);
sg_init_table(ctx->sgl.sg, 1);
sg_set_page(ctx->sgl.sg, page, size, offset);
ahash_request_set_crypt(&ctx->req, ctx->sgl.sg, ctx->result, size);
if (!(flags & MSG_MORE)) {
if (ctx->more)
err = crypto_ahash_finup(&ctx->req);
else
err = crypto_ahash_digest(&ctx->req);
} else {
if (!ctx->more) {
err = crypto_ahash_init(&ctx->req);
if (err)
goto unlock;
}
err = crypto_ahash_update(&ctx->req);
}
err = af_alg_wait_for_completion(err, &ctx->completion);
if (err)
goto unlock;
ctx->more = flags & MSG_MORE;
unlock:
release_sock(sk);
return err ?: size;
}
static int hash_recvmsg(struct kiocb *unused, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct hash_ctx *ctx = ask->private;
unsigned ds = crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req));
int err;
if (len > ds)
len = ds;
else if (len < ds)
msg->msg_flags |= MSG_TRUNC;
lock_sock(sk);
if (ctx->more) {
ctx->more = 0;
ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0);
err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req),
&ctx->completion);
if (err)
goto unlock;
}
err = memcpy_toiovec(msg->msg_iov, ctx->result, len);
unlock:
release_sock(sk);
return err ?: len;
}
static int hash_accept(struct socket *sock, struct socket *newsock, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct hash_ctx *ctx = ask->private;
struct ahash_request *req = &ctx->req;
char state[crypto_ahash_statesize(crypto_ahash_reqtfm(req))];
struct sock *sk2;
struct alg_sock *ask2;
struct hash_ctx *ctx2;
int err;
err = crypto_ahash_export(req, state);
if (err)
return err;
err = af_alg_accept(ask->parent, newsock);
if (err)
return err;
sk2 = newsock->sk;
ask2 = alg_sk(sk2);
ctx2 = ask2->private;
ctx2->more = 1;
err = crypto_ahash_import(&ctx2->req, state);
if (err) {
sock_orphan(sk2);
sock_put(sk2);
}
return err;
}
static struct proto_ops algif_hash_ops = {
.family = PF_ALG,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.getname = sock_no_getname,
.ioctl = sock_no_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.getsockopt = sock_no_getsockopt,
.mmap = sock_no_mmap,
.bind = sock_no_bind,
.setsockopt = sock_no_setsockopt,
.poll = sock_no_poll,
.release = af_alg_release,
.sendmsg = hash_sendmsg,
.sendpage = hash_sendpage,
.recvmsg = hash_recvmsg,
.accept = hash_accept,
};
static void *hash_bind(const char *name, u32 type, u32 mask)
{
return crypto_alloc_ahash(name, type, mask);
}
static void hash_release(void *private)
{
crypto_free_ahash(private);
}
static int hash_setkey(void *private, const u8 *key, unsigned int keylen)
{
return crypto_ahash_setkey(private, key, keylen);
}
static void hash_sock_destruct(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct hash_ctx *ctx = ask->private;
#ifdef CONFIG_CRYPTO_HW
sock_kfree_s(sk, ctx->result, SHA512_BLOCK_SIZE);
#else
sock_kfree_s(sk, ctx->result,
crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req)));
#endif
sock_kfree_s(sk, ctx, ctx->len);
af_alg_release_parent(sk);
}
static int hash_accept_parent(void *private, struct sock *sk)
{
struct hash_ctx *ctx;
struct alg_sock *ask = alg_sk(sk);
unsigned len = sizeof(*ctx) + crypto_ahash_reqsize(private);
unsigned ds = crypto_ahash_digestsize(private);
ctx = sock_kmalloc(sk, len, GFP_KERNEL);
if (!ctx)
return -ENOMEM;
#ifdef CONFIG_CRYPTO_HW
ds = SHA512_BLOCK_SIZE;
#endif
ctx->result = sock_kmalloc(sk, ds, GFP_KERNEL);
if (!ctx->result) {
sock_kfree_s(sk, ctx, len);
return -ENOMEM;
}
memset(ctx->result, 0, ds);
ctx->len = len;
ctx->more = 0;
af_alg_init_completion(&ctx->completion);
ask->private = ctx;
ahash_request_set_tfm(&ctx->req, private);
ahash_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG,
af_alg_complete, &ctx->completion);
sk->sk_destruct = hash_sock_destruct;
return 0;
}
static const struct af_alg_type algif_type_hash = {
.bind = hash_bind,
.release = hash_release,
.setkey = hash_setkey,
.accept = hash_accept_parent,
.ops = &algif_hash_ops,
.name = "hash",
.owner = THIS_MODULE
};
static int __init algif_hash_init(void)
{
return af_alg_register_type(&algif_type_hash);
}
static void __exit algif_hash_exit(void)
{
int err = af_alg_unregister_type(&algif_type_hash);
BUG_ON(err);
}
module_init(algif_hash_init);
module_exit(algif_hash_exit);
MODULE_LICENSE("GPL");
|
zsoltm/linux-sunxi-exp
|
crypto/algif_hash.c
|
C
|
gpl-2.0
| 7,558
|
/**
* @file
* Normalize.css is intended to be used as an alternative to CSS resets.
*
* This file is a slight fork of these original sources:
* - normalize.css v2.1.2 | MIT License | git.io/normalize
* - normalize.scss v2.1.2 | MIT/GPLv2 License | bit.ly/normalize-with-compass
*
* It's suggested that you read the normalize.scss file and customise it to meet
* your needs, rather then including the file in your project and overriding the
* defaults later in your CSS.
* @see http://nicolasgallagher.com/about-normalize-css/
*
* Also: @see http://meiert.com/en/blog/20080419/reset-style-sheets-are-bad/
* @see http://snook.ca/archives/html_and_css/no_css_reset/
*/
/**
* HTML5 display definitions
*/
/* Correct `block` display not defined in IE 8/9. */
article,
aside,
details,
figcaption,
figure,
footer,
header,
main,
nav,
section,
summary {
display: block;
}
/* Correct `inline-block` display not defined in IE 8/9. */
audio,
canvas,
video {
display: inline-block;
*display: inline;
*zoom: 1;
}
/**
* Prevent modern browsers from displaying `audio` without controls.
* Remove excess height in iOS 5 devices.
*/
audio:not([controls]) {
display: none;
height: 0;
}
/* Address styling not present in IE 8/9. */
[hidden] {
display: none;
}
/**
* Base
*
* Instead of relying on the fonts that are available on a user's computer, you
* can use web fonts which, like images, are resources downloaded to the user's
* browser. Because of the bandwidth and rendering resources required, web fonts
* should be used with care.
*
* Numerous resources for web fonts can be found on Google. Here are a few
* websites where you can find Open Source fonts to download:
* - http://www.fontsquirrel.com/fontface
* - http://www.theleagueofmoveabletype.com
*
* In order to use these fonts, you will need to convert them into formats
* suitable for web fonts. We recommend the free-to-use Font Squirrel's
* Font-Face Generator:
* http://www.fontsquirrel.com/fontface/generator
*
* The following is an example @font-face declaration. This font can then be
* used in any ruleset using a property like this: font-family: Example, serif;
*/
/*
@font-face {
font-family: 'Example';
src: url('../fonts/example.eot');
src: url('../fonts/example.eot?iefix') format('eot'),
url('../fonts/example.woff') format('woff'),
url('../fonts/example.ttf') format('truetype'),
url('../fonts/example.svg#webfontOkOndcij') format('svg');
font-weight: normal;
font-style: normal;
}
*/
/**
* 1. Set default font family to sans-serif.
* 2. Prevent iOS text size adjust after orientation change, without disabling
* user zoom.
* 3. Correct text resizing oddly in IE 6/7 when body `font-size` is set using
* `em` units.
*/
html {
font-family: Verdana, Tahoma, "DejaVu Sans", sans-serif; /* 1 */
/* Delete all but one of the following font-size declarations: */
/* Use a 12px base font size. 16px x 75% = 12px */
font-size: 75%; /* 3 */
/* Use a 14px base font size. 16px x .875 = 14px */
font-size: 87.5%; /* 3 */
/* Use a 16px base font size. */
font-size: 100%; /* 3 */
-ms-text-size-adjust: 100%; /* 2 */
-webkit-text-size-adjust: 100%; /* 2 */
/* Establish a vertical rhythm. */
line-height: 1.5em;
}
/* Address `font-family` inconsistency between `textarea` and other form elements. */
button,
input,
select,
textarea {
/**
* The following font family declarations are available on most computers.
*
* A user's web browser will look at the comma-separated list and will
* attempt to use each font in turn until it finds one that is available
* on the user's computer. The final "generic" font (sans-serif, serif or
* monospace) hints at what type of font to use if the web browser doesn't
* find any of the fonts in the list.
*
* font-family: "Times New Roman", Times, Georgia, "DejaVu Serif", serif;
* font-family: Times, "Times New Roman", Georgia, "DejaVu Serif", serif;
* font-family: Georgia, "Times New Roman", "DejaVu Serif", serif;
*
* font-family: Verdana, Tahoma, "DejaVu Sans", sans-serif;
* font-family: Tahoma, Verdana, "DejaVu Sans", sans-serif;
* font-family: Helvetica, Arial, "Nimbus Sans L", sans-serif;
* font-family: Arial, Helvetica, "Nimbus Sans L", sans-serif;
*
* font-family: "Courier New", "DejaVu Sans Mono", monospace;
*/
font-family: Verdana, Tahoma, "DejaVu Sans", sans-serif;
}
/* Remove default margin. */
body {
margin: 0;
padding: 0;
}
/**
* Links
*
* The order of link states are based on Eric Meyer's article:
* http://meyerweb.com/eric/thoughts/2007/06/11/who-ordered-the-link-states
*/
a:link {
}
a:visited {
}
a:hover,
a:focus {
}
a:active {
}
/* Address `outline` inconsistency between Chrome and other browsers. */
a:focus {
outline: thin dotted;
}
/* Improve readability when focused and also mouse hovered in all browsers. */
a:active,
a:hover {
outline: 0;
}
/**
* Typography
*
* To achieve a pleasant vertical rhythm, we use Compass' Vertical Rhythm mixins
* so that the line height of our base font becomes the basic unit of vertical
* measurement. We use multiples of that unit to set the top and bottom margins
* for our block level elements and to set the line heights of any fonts.
* For more information, see http://24ways.org/2006/compose-to-a-vertical-rhythm
*/
/* Set 1 unit of vertical rhythm on the top and bottom margin. */
p,
pre {
margin: 1.5em 0;
}
blockquote {
/* Also indent the quote on both sides. */
margin: 1.5em 30px;
}
/**
* Address variable `h1` font-size and margin within `section` and `article`
* contexts in Firefox 4+, Safari 5, and Chrome.
*/
h1 {
/* Set the font-size and line-height while keeping a proper vertical rhythm. */
font-size: 2em;
line-height: 1.5em; /* 3rem / 2em = 1.5em */
/* Set 1 unit of vertical rhythm on the top and bottom margins. */
margin-top: 0.75em; /* 1.5rem / 2em = .75em */
margin-bottom: 0.75em;
}
h2 {
font-size: 1.5em;
line-height: 2em; /* 3rem / 1.5em = 2em */
margin-top: 1em; /* 1.5rem / 1.5em = 1em */
margin-bottom: 1em;
}
h3 {
font-size: 1.17em;
line-height: 1.28205em; /* 1.5rem / 1.17em = 1.28205em */
margin-top: 1.28205em;
margin-bottom: 1.28205em;
}
h4 {
font-size: 1em;
line-height: 1.5em; /* 1.5rem / 1em = 1.5em */
margin-top: 1.5em;
margin-bottom: 1.5em;
}
h5 {
font-size: 0.83em;
line-height: 1.80723em; /* 1.5rem / 0.83em = 1.80723em */
margin-top: 1.80723em;
margin-bottom: 1.80723em;
}
h6 {
font-size: 0.67em;
line-height: 2.23881em; /* 1.5rem / 0.67em = 2.23881em */
margin-top: 2.23881em;
margin-bottom: 2.23881em;
}
/* Address styling not present in IE 8/9, Safari 5, and Chrome. */
abbr[title] {
border-bottom: 1px dotted;
}
/* Address style set to `bolder` in Firefox 4+, Safari 5, and Chrome. */
b,
strong {
font-weight: bold;
}
/* Address styling not present in Safari 5 and Chrome. */
dfn {
font-style: italic;
}
/* Address differences between Firefox and other browsers. */
hr {
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
height: 0;
border: 1px solid #666;
padding-bottom: -1px;
margin: 1.5em 0;
}
/* Address styling not present in IE 8/9. */
mark {
background: #ff0;
color: #000;
}
/* Correct font family set oddly in Safari 5 and Chrome. */
code,
kbd,
pre,
samp,
tt,
var {
font-family: "Courier New", "DejaVu Sans Mono", monospace, sans-serif;
_font-family: 'courier new', monospace;
font-size: 1em;
line-height: 1.5em;
}
/* Improve readability of pre-formatted text in all browsers. */
pre {
white-space: pre;
white-space: pre-wrap;
word-wrap: break-word;
}
/* Set consistent quote types. */
q {
quotes: "\201C" "\201D" "\2018" "\2019";
}
/* Address inconsistent and variable font size in all browsers. */
small {
font-size: 80%;
}
/* Prevent `sub` and `sup` affecting `line-height` in all browsers. */
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
/**
* Lists
*/
dl,
menu,
ol,
ul {
/* Address margins set differently in IE 6/7. */
margin: 1.5em 0;
}
ol ol,
ol ul,
ul ol,
ul ul {
/* Turn off margins on nested lists. */
margin: 0;
}
dd {
margin: 0 0 0 30px; /* LTR */
}
/* Address paddings set differently in IE 6/7. */
menu,
ol,
ul {
padding: 0 0 0 30px; /* LTR */
}
/* Correct list images handled incorrectly in IE 7. */
nav ul,
nav ol {
list-style: none;
list-style-image: none;
}
/**
* Embedded content and figures
*
* @todo Look into adding responsive embedded video.
*/
img {
/* Remove border when inside `a` element in IE 8/9. */
border: 0;
/* Improve image quality when scaled in IE 7. */
-ms-interpolation-mode: bicubic;
/* Suppress the space beneath the baseline */
/* vertical-align: bottom; */
/* Responsive images */
max-width: 100%;
/* height: auto; */
/* Correct IE 8 not scaling image height when resized. */
width: auto;
}
/* Correct overflow displayed oddly in IE 9. */
svg:not(:root) {
overflow: hidden;
}
/* Address margin not present in IE 8/9 and Safari 5. */
figure {
margin: 0;
}
/**
* Forms
*/
/* Correct margin displayed oddly in IE 6/7. */
form {
margin: 0;
}
/* Define consistent border, margin, and padding. */
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.5em 0.625em 1em;
}
/**
* 1. Correct `color` not being inherited in IE 8/9.
* 2. Remove padding so people aren't caught out if they zero out fieldsets.
* 3. Correct alignment displayed oddly in IE 6/7.
*/
legend {
border: 0; /* 1 */
padding: 0; /* 2 */
*margin-left: -7px; /* 3 */ /* LTR */
}
/**
* 1. Correct font family not being inherited in all browsers.
* 2. Correct font size not being inherited in all browsers.
* 3. Address margins set differently in Firefox 4+, Safari 5, and Chrome.
* 4. Improve appearance and consistency with IE 6/7.
* 5. Keep form elements constrained in their containers.
*/
button,
input,
select,
textarea {
font-family: inherit; /* 1 */
font-size: 100%; /* 2 */
margin: 0; /* 3 */
vertical-align: baseline; /* 4 */
*vertical-align: middle; /* 4 */
max-width: 100%; /* 5 */
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box; /* 5 */
}
/**
* Address Firefox 4+ setting `line-height` on `input` using `!important` in
* the UA stylesheet.
*/
button,
input {
line-height: normal;
}
/**
* Address inconsistent `text-transform` inheritance for `button` and `select`.
* All other form control elements do not inherit `text-transform` values.
* Correct `button` style inheritance in Chrome, Safari 5+, and IE 8+.
* Correct `select` style inheritance in Firefox 4+ and Opera.
*/
button,
select {
text-transform: none;
}
/**
* 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
* and `video` controls.
* 2. Correct inability to style clickable `input` types in iOS.
* 3. Improve usability and consistency of cursor style between image-type
* `input` and others.
* 4. Remove inner spacing in IE 7 without affecting normal text inputs.
* Known issue: inner spacing remains in IE 6.
*/
button,
html input[type="button"], /* 1 */
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button; /* 2 */
cursor: pointer; /* 3 */
*overflow: visible; /* 4 */
}
/**
* Re-set default cursor for disabled elements.
*/
button[disabled],
html input[disabled] {
cursor: default;
}
/**
* 1. Address box sizing set to `content-box` in IE 8/9.
* 2. Remove excess padding in IE 8/9.
* 3. Remove excess padding in IE 7.
* Known issue: excess padding remains in IE 6.
*/
input[type="checkbox"],
input[type="radio"] {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
*height: 13px; /* 3 */
*width: 13px; /* 3 */
}
/**
* 1. Address `appearance` set to `searchfield` in Safari 5 and Chrome.
* 2. Address `box-sizing` set to `border-box` in Safari 5 and Chrome
* (include `-moz` to future-proof).
*/
input[type="search"] {
-webkit-appearance: textfield; /* 1 */
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box; /* 2 */
}
/**
* Remove inner padding and search cancel button in Safari 5 and Chrome
* on OS X.
*/
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/* Remove inner padding and border in Firefox 4+. */
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}
/**
* 1. Remove default vertical scrollbar in IE 8/9.
* 2. Improve readability and alignment in all browsers.
*/
textarea {
overflow: auto; /* 1 */
vertical-align: top; /* 2 */
}
/* Drupal-style form labels. */
label {
display: block;
font-weight: bold;
}
/**
* Tables
*/
table {
/* Remove most spacing between table cells. */
border-collapse: collapse;
border-spacing: 0;
/* Prevent cramped-looking tables */
/* width: 100%; */
/* Add vertical rhythm margins. */
margin-top: 1.5em;
margin-bottom: 1.5em;
}
|
scottshipman/ffvcoop
|
sites/all/themes/ffvcoop/css/normalize.css
|
CSS
|
gpl-2.0
| 13,263
|
<?php
use mvc\interfaces\controllerActionInterface;
use mvc\controller\controllerClass;
//use mvc\config\myConfigClass as config;
use mvc\config\myConfigClass as config;
use mvc\request\requestClass as request;
use mvc\session\sessionClass as session;
use mvc\routing\routingClass as routing;
use mvc\i18n\i18nClass as i18n;
/**
* Description esta cumple una funcion es para el eliminado en masa
*
* @author Leydy Lucia Castillo Mosquera <leydylucia@hotmail.com>
* @category usuario
*/
class deleteSelectActionClass extends controllerClass implements controllerActionInterface {
public function execute() {
try {/* se grago el and resquest etc.. */
if (request::getInstance()->isMethod('POST') and request::getInstance()->hasPost('chk')) {
$idsToDelete = request::getInstance()->getPost('chk'); /* el chk es para escojer varios dator por medio del cheklist */
foreach ($idsToDelete as $id) {
$ids = array(
usuarioTableClass::ID => $id
);
usuarioTableClass::delete($ids, true);
}
/* session para mensaje */
session::getInstance()->setSuccess('los Elementos seleccionas fueron eliminados con exito');
// session::getInstance()->setSucces('los Elementos seleccionas fueron eliminados con exito');
routing::getInstance()->redirect('default', 'index');
} else {
routing::getInstance()->redirect('default', 'index');
}
} catch (PDOException $exc) {
session::getInstance()->setFlash('exc', $exc);
routing::getInstance()->forward('shfSecurity', 'exception');
}
}
}
|
leydylucia/proyectPorcicola-leyMar
|
controller/default/deleteSelectActionClass.php
|
PHP
|
gpl-2.0
| 1,671
|
/*
* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.List;
import java.util.ArrayList;
import jdk.test.lib.*;
import static jdk.test.lib.Asserts.*;
/* @test TestMetaspacePerfCounters
* @bug 8014659
* @requires vm.gc=="null"
* @library /testlibrary
* @summary Tests that performance counters for metaspace and compressed class
* space exists and works.
* @modules java.base/jdk.internal.misc
* java.compiler
* java.management
* jdk.jvmstat/sun.jvmstat.monitor
* @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-UseCompressedOops -XX:-UseCompressedClassPointers -XX:+UsePerfData -XX:+UseSerialGC TestMetaspacePerfCounters
* @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-UseCompressedOops -XX:-UseCompressedClassPointers -XX:+UsePerfData -XX:+UseParallelGC -XX:+UseParallelOldGC TestMetaspacePerfCounters
* @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-UseCompressedOops -XX:-UseCompressedClassPointers -XX:+UsePerfData -XX:+UseG1GC TestMetaspacePerfCounters
*
* @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UseCompressedOops -XX:+UseCompressedClassPointers -XX:+UsePerfData -XX:+UseSerialGC TestMetaspacePerfCounters
* @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UseCompressedOops -XX:+UseCompressedClassPointers -XX:+UsePerfData -XX:+UseParallelGC -XX:+UseParallelOldGC TestMetaspacePerfCounters
* @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UseCompressedOops -XX:+UseCompressedClassPointers -XX:+UsePerfData -XX:+UseG1GC TestMetaspacePerfCounters
*/
public class TestMetaspacePerfCounters {
public static Class fooClass = null;
private static final String[] counterNames = {"minCapacity", "maxCapacity", "capacity", "used"};
public static void main(String[] args) throws Exception {
String metaspace = "sun.gc.metaspace";
String ccs = "sun.gc.compressedclassspace";
checkPerfCounters(metaspace);
if (isUsingCompressedClassPointers()) {
checkPerfCounters(ccs);
checkUsedIncreasesWhenLoadingClass(ccs);
} else {
checkEmptyPerfCounters(ccs);
checkUsedIncreasesWhenLoadingClass(metaspace);
}
}
private static void checkPerfCounters(String ns) throws Exception {
long minCapacity = getMinCapacity(ns);
long maxCapacity = getMaxCapacity(ns);
long capacity = getCapacity(ns);
long used = getUsed(ns);
assertGTE(minCapacity, 0L);
assertGTE(used, minCapacity);
assertGTE(capacity, used);
assertGTE(maxCapacity, capacity);
}
private static void checkEmptyPerfCounters(String ns) throws Exception {
for (PerfCounter counter : countersInNamespace(ns)) {
String msg = "Expected " + counter.getName() + " to equal 0";
assertEQ(counter.longValue(), 0L, msg);
}
}
private static void checkUsedIncreasesWhenLoadingClass(String ns) throws Exception {
// Need to ensure that used is up to date and that all unreachable
// classes are unloaded before doing this check.
System.gc();
long before = getUsed(ns);
fooClass = compileAndLoad("Foo", "public class Foo { }");
System.gc();
long after = getUsed(ns);
assertGT(after, before);
}
private static List<PerfCounter> countersInNamespace(String ns) throws Exception {
List<PerfCounter> counters = new ArrayList<>();
for (String name : counterNames) {
counters.add(PerfCounters.findByName(ns + "." + name));
}
return counters;
}
private static Class<?> compileAndLoad(String name, String source) throws Exception {
byte[] byteCode = InMemoryJavaCompiler.compile(name, source);
return ByteCodeLoader.load(name, byteCode);
}
private static boolean isUsingCompressedClassPointers() {
return Platform.is64bit() && InputArguments.contains("-XX:+UseCompressedClassPointers");
}
private static long getMinCapacity(String ns) throws Exception {
return PerfCounters.findByName(ns + ".minCapacity").longValue();
}
private static long getCapacity(String ns) throws Exception {
return PerfCounters.findByName(ns + ".capacity").longValue();
}
private static long getMaxCapacity(String ns) throws Exception {
return PerfCounters.findByName(ns + ".maxCapacity").longValue();
}
private static long getUsed(String ns) throws Exception {
return PerfCounters.findByName(ns + ".used").longValue();
}
}
|
FauxFaux/jdk9-hotspot
|
test/gc/metaspace/TestMetaspacePerfCounters.java
|
Java
|
gpl-2.0
| 5,623
|
/* datepicker */
.ui-helper-hidden {
display: none
}
.ui-helper-hidden-accessible {
position: absolute !important;
clip: rect(1px 1px 1px 1px);
clip: rect(1px, 1px, 1px, 1px)
}
.ui-helper-reset {
margin: 0;
padding: 0;
border: 0;
outline: 0;
line-height: 1.3;
text-decoration: none;
font-size: 100%;
list-style: none
}
.ui-helper-clearfix:after, .ui-helper-clearfix:before {
content: "";
display: table
}
.ui-helper-clearfix:after {
clear: both
}
.ui-helper-clearfix {
zoom: 1
}
.ui-helper-zfix {
width: 100%;
height: 100%;
top: 0;
left: 0;
position: absolute;
opacity: 0;
filter: Alpha(Opacity=0)
}
.ui-state-disabled {
cursor: default !important
}
.ui-icon {
display: block;
text-indent: -99999px;
overflow: hidden;
background-repeat: no-repeat
}
.ui-widget-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%
}
.ui-accordion {
width: 100%
}
.ui-accordion .ui-accordion-header {
cursor: pointer;
position: relative;
margin-top: 1px;
zoom: 1
}
.ui-accordion .ui-accordion-li-fix {
display: inline
}
.ui-accordion .ui-accordion-header-active {
border-bottom: 0 !important
}
.ui-accordion .ui-accordion-header a {
display: block;
font-size: 1em;
padding: .5em .5em .5em .7em
}
.ui-accordion-icons .ui-accordion-header a {
padding-left: 2.2em
}
.ui-accordion .ui-accordion-header .ui-icon {
position: absolute;
left: .5em;
top: 50%;
margin-top: -8px
}
.ui-accordion .ui-accordion-content {
padding: 1em 2.2em;
border-top: 0;
margin-top: -2px;
position: relative;
top: 1px;
margin-bottom: 2px;
overflow: auto;
display: none;
zoom: 1
}
.ui-accordion .ui-accordion-content-active {
display: block
}
.ui-autocomplete {
position: absolute;
cursor: default
}
* html .ui-autocomplete {
width: 1px
}
.ui-menu {
list-style: none;
padding: 2px;
margin: 0;
display: block;
float: left
}
.ui-menu .ui-menu {
margin-top: -3px
}
.ui-menu .ui-menu-item {
margin: 0;
padding: 0;
zoom: 1;
float: left;
clear: left;
width: 100%
}
.ui-menu .ui-menu-item a {
text-decoration: none;
display: block;
padding: .2em .4em;
line-height: 1.5;
zoom: 1
}
.ui-menu .ui-menu-item a.ui-state-active, .ui-menu .ui-menu-item a.ui-state-hover {
font-weight: 400;
margin: -1px
}
.ui-button {
display: inline-block;
position: relative;
padding: 0;
margin-right: .1em;
text-decoration: none !important;
cursor: pointer;
text-align: center;
zoom: 1;
overflow: visible
}
.ui-button-icon-only {
width: 2.2em
}
button.ui-button-icon-only {
width: 2.4em
}
.ui-button-icons-only {
width: 3.4em
}
button.ui-button-icons-only {
width: 3.7em
}
.ui-button .ui-button-text {
display: block;
line-height: 1.4
}
.ui-button-text-only .ui-button-text {
padding: .4em 1em
}
.ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text {
padding: .4em;
text-indent: -9999999px
}
.ui-button-text-icon-primary .ui-button-text, .ui-button-text-icons .ui-button-text {
padding: .4em 1em .4em 2.1em
}
.ui-button-text-icon-secondary .ui-button-text, .ui-button-text-icons .ui-button-text {
padding: .4em 2.1em .4em 1em
}
.ui-button-text-icons .ui-button-text {
padding-left: 2.1em;
padding-right: 2.1em
}
input.ui-button {
padding: .4em 1em
}
.ui-button-icon-only .ui-icon, .ui-button-icons-only .ui-icon, .ui-button-text-icon-primary .ui-icon, .ui-button-text-icon-secondary .ui-icon, .ui-button-text-icons .ui-icon {
position: absolute;
top: 50%;
margin-top: -8px
}
.ui-button-icon-only .ui-icon {
left: 50%;
margin-left: -8px
}
.ui-button-icons-only .ui-button-icon-primary, .ui-button-text-icon-primary .ui-button-icon-primary, .ui-button-text-icons .ui-button-icon-primary {
left: .5em
}
.ui-button-icons-only .ui-button-icon-secondary, .ui-button-text-icon-secondary .ui-button-icon-secondary, .ui-button-text-icons .ui-button-icon-secondary {
right: .5em
}
.ui-buttonset {
margin-right: 7px
}
.ui-buttonset .ui-button {
margin-left: 0;
margin-right: -.3em
}
button.ui-button::-moz-focus-inner {
border: 0;
padding: 0
}
.ui-datepicker {
width: 17em;
padding: .2em .2em 0;
display: none
}
.ui-datepicker .ui-datepicker-header {
position: relative;
padding: .2em 0
}
.ui-datepicker .ui-datepicker-next, .ui-datepicker .ui-datepicker-prev {
position: absolute;
top: 2px;
width: 1.8em;
height: 1.8em
}
.ui-datepicker .ui-datepicker-next-hover, .ui-datepicker .ui-datepicker-prev-hover {
top: 1px
}
.ui-datepicker .ui-datepicker-prev {
left: 2px
}
.ui-datepicker .ui-datepicker-next {
right: 2px
}
.ui-datepicker .ui-datepicker-prev-hover {
left: 1px
}
.ui-datepicker .ui-datepicker-next-hover {
right: 1px
}
.ui-datepicker .ui-datepicker-next span, .ui-datepicker .ui-datepicker-prev span {
display: block;
position: absolute;
left: 50%;
margin-left: -8px;
top: 50%;
margin-top: -8px
}
.ui-datepicker .ui-datepicker-title {
margin: 0 2.3em;
line-height: 1.8em;
text-align: center
}
.ui-datepicker .ui-datepicker-title select {
font-size: 1em;
margin: 1px 0
}
.ui-datepicker select.ui-datepicker-month-year {
width: 100%
}
.ui-datepicker select.ui-datepicker-month, .ui-datepicker select.ui-datepicker-year {
width: 49%
}
.ui-datepicker table {
width: 100%;
font-size: .9em;
border-collapse: collapse;
margin: 0 0 .4em
}
.ui-datepicker th {
padding: .7em .3em;
text-align: center;
font-weight: 700;
border: 0
}
.ui-datepicker td {
border: 0;
padding: 1px
}
.ui-datepicker td a, .ui-datepicker td span {
display: block;
padding: .2em;
text-align: right;
text-decoration: none
}
.ui-datepicker .ui-datepicker-buttonpane {
background-image: none;
margin: .7em 0 0;
padding: 0 .2em;
border-left: 0;
border-right: 0;
border-bottom: 0
}
.ui-datepicker .ui-datepicker-buttonpane button {
float: right;
margin: .5em .2em .4em;
cursor: pointer;
padding: .2em .6em .3em;
width: auto;
overflow: visible
}
.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current {
float: left
}
.ui-datepicker.ui-datepicker-multi {
width: auto
}
.ui-datepicker-multi .ui-datepicker-group {
float: left
}
.ui-datepicker-multi .ui-datepicker-group table {
width: 95%;
margin: 0 auto .4em
}
.ui-datepicker-multi-2 .ui-datepicker-group {
width: 50%
}
.ui-datepicker-multi-3 .ui-datepicker-group {
width: 33.3%
}
.ui-datepicker-multi-4 .ui-datepicker-group {
width: 25%
}
.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header, .ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header {
border-left-width: 0
}
.ui-datepicker-multi .ui-datepicker-buttonpane {
clear: left
}
.ui-datepicker-row-break {
clear: both;
width: 100%;
font-size: 0
}
.ui-datepicker-rtl {
direction: rtl
}
.ui-datepicker-rtl .ui-datepicker-prev {
right: 2px;
left: auto
}
.ui-datepicker-rtl .ui-datepicker-next {
left: 2px;
right: auto
}
.ui-datepicker-rtl .ui-datepicker-prev:hover {
right: 1px;
left: auto
}
.ui-datepicker-rtl .ui-datepicker-next:hover {
left: 1px;
right: auto
}
.ui-datepicker-rtl .ui-datepicker-buttonpane {
clear: right
}
.ui-datepicker-rtl .ui-datepicker-buttonpane button {
float: left
}
.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current, .ui-datepicker-rtl .ui-datepicker-group {
float: right
}
.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header, .ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header {
border-right-width: 0;
border-left-width: 1px
}
.ui-datepicker-cover {
display: none;
display: block;
position: absolute;
z-index: -1;
filter: mask();
top: -4px;
left: -4px;
width: 200px;
height: 200px
}
.ui-dialog {
position: absolute;
padding: .2em;
width: 300px;
overflow: hidden
}
.ui-dialog .ui-dialog-titlebar {
padding: .4em 1em;
position: relative
}
.ui-dialog .ui-dialog-title {
float: left;
margin: .1em 16px .1em 0
}
.ui-dialog .ui-dialog-titlebar-close {
position: absolute;
right: .3em;
top: 50%;
width: 19px;
margin: -10px 0 0 0;
padding: 1px;
height: 18px
}
.ui-dialog .ui-dialog-titlebar-close span {
display: block;
margin: 1px
}
.ui-dialog .ui-dialog-titlebar-close:focus, .ui-dialog .ui-dialog-titlebar-close:hover {
padding: 0
}
.ui-dialog .ui-dialog-content {
position: relative;
border: 0;
padding: .5em 1em;
background: 0 0;
overflow: auto;
zoom: 1
}
.ui-dialog .ui-dialog-buttonpane {
text-align: left;
border-width: 1px 0 0;
background-image: none;
margin: .5em 0 0;
padding: .3em 1em .5em .4em
}
.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset {
float: right
}
.ui-dialog .ui-dialog-buttonpane button {
margin: .5em .4em .5em 0;
cursor: pointer
}
.ui-dialog .ui-resizable-se {
width: 14px;
height: 14px;
right: 3px;
bottom: 3px
}
.ui-draggable .ui-dialog-titlebar {
cursor: move
}
.ui-progressbar {
height: 2em;
text-align: left;
overflow: hidden
}
.ui-progressbar .ui-progressbar-value {
margin: -1px;
height: 100%
}
.ui-resizable {
position: relative
}
.ui-resizable-handle {
position: absolute;
font-size: .1px;
z-index: 99999;
display: block
}
.ui-resizable-autohide .ui-resizable-handle, .ui-resizable-disabled .ui-resizable-handle {
display: none
}
.ui-resizable-n {
cursor: n-resize;
height: 7px;
width: 100%;
top: -5px;
left: 0
}
.ui-resizable-s {
cursor: s-resize;
height: 7px;
width: 100%;
bottom: -5px;
left: 0
}
.ui-resizable-e {
cursor: e-resize;
width: 7px;
right: -5px;
top: 0;
height: 100%
}
.ui-resizable-w {
cursor: w-resize;
width: 7px;
left: -5px;
top: 0;
height: 100%
}
.ui-resizable-se {
cursor: se-resize;
width: 12px;
height: 12px;
right: 1px;
bottom: 1px
}
.ui-resizable-sw {
cursor: sw-resize;
width: 9px;
height: 9px;
left: -5px;
bottom: -5px
}
.ui-resizable-nw {
cursor: nw-resize;
width: 9px;
height: 9px;
left: -5px;
top: -5px
}
.ui-resizable-ne {
cursor: ne-resize;
width: 9px;
height: 9px;
right: -5px;
top: -5px
}
.ui-selectable-helper {
position: absolute;
z-index: 100;
border: 1px dotted #000
}
.ui-slider {
position: relative;
text-align: left
}
.ui-slider .ui-slider-handle {
position: absolute;
z-index: 2;
width: 1.2em;
height: 1.2em;
cursor: default
}
.ui-slider .ui-slider-range {
position: absolute;
z-index: 1;
font-size: .7em;
display: block;
border: 0;
background-position: 0 0
}
.ui-slider-horizontal {
height: .8em
}
.ui-slider-horizontal .ui-slider-handle {
top: -.3em;
margin-left: -.6em
}
.ui-slider-horizontal .ui-slider-range {
top: 0;
height: 100%
}
.ui-slider-horizontal .ui-slider-range-min {
left: 0
}
.ui-slider-horizontal .ui-slider-range-max {
right: 0
}
.ui-slider-vertical {
width: .8em;
height: 100px
}
.ui-slider-vertical .ui-slider-handle {
left: -.3em;
margin-left: 0;
margin-bottom: -.6em
}
.ui-slider-vertical .ui-slider-range {
left: 0;
width: 100%
}
.ui-slider-vertical .ui-slider-range-min {
bottom: 0
}
.ui-slider-vertical .ui-slider-range-max {
top: 0
}
.ui-tabs {
position: relative;
padding: .2em;
zoom: 1
}
.ui-tabs .ui-tabs-nav {
margin: 0;
padding: .2em .2em 0
}
.ui-tabs .ui-tabs-nav li {
list-style: none;
float: left;
position: relative;
top: 1px;
margin: 0 .2em 1px 0;
border-bottom: 0 !important;
padding: 0;
white-space: nowrap
}
.ui-tabs .ui-tabs-nav li a {
float: left;
padding: .5em 1em;
text-decoration: none
}
.ui-tabs .ui-tabs-nav li.ui-tabs-selected {
margin-bottom: 0;
padding-bottom: 1px
}
.ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-state-processing a, .ui-tabs .ui-tabs-nav li.ui-tabs-selected a {
cursor: text
}
.ui-tabs .ui-tabs-nav li a, .ui-tabs.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-selected a {
cursor: pointer
}
.ui-tabs .ui-tabs-panel {
display: block;
border-width: 0;
padding: 1em 1.4em;
background: 0 0
}
.ui-tabs .ui-tabs-hide {
display: none !important
}
.ui-widget {
font-family: Verdana, Arial, sans-serif;
font-size: 12px
}
.ui-widget .ui-widget {
font-size: 1em
}
.ui-widget button, .ui-widget input, .ui-widget select, .ui-widget textarea {
font-family: Verdana, Arial, sans-serif;
font-size: 1em
}
.ui-widget-content {
border: 1px solid #aaa;
background: #fff url(../images/ui-bg_flat_75_ffffff_40x100.png) 50% 50% repeat-x;
color: #222
}
.ui-widget-content a {
color: #222
}
.ui-widget-header {
border: 1px solid #aaa;
background: #ccc url(../images/ui-bg_highlight-soft_75_cccccc_1x100.png) 50% 50% repeat-x;
color: #222;
font-weight: 700
}
.ui-widget-header a {
color: #222
}
.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default {
border: 1px solid #d3d3d3;
background: #e6e6e6 url(../images/ui-bg_glass_75_e6e6e6_1x400.png) 50% 50% repeat-x;
font-weight: 400;
color: #555
}
.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited {
color: #555;
text-decoration: none
}
.ui-state-focus, .ui-state-hover, .ui-widget-content .ui-state-focus, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-focus, .ui-widget-header .ui-state-hover {
border: 1px solid #999;
background: #dadada url(../images/ui-bg_glass_75_dadada_1x400.png) 50% 50% repeat-x;
font-weight: 400;
color: #212121
}
.ui-state-hover a, .ui-state-hover a:hover {
color: #212121;
text-decoration: none
}
.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active {
border: 1px solid #aaa;
background: #fff url(../images/ui-bg_glass_65_ffffff_1x400.png) 50% 50% repeat-x;
font-weight: 400;
color: #212121
}
.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited {
color: #212121;
text-decoration: none
}
.ui-widget :active {
outline: 0
}
.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight {
border: 1px solid #fcefa1;
background: #fbf9ee url(../images/ui-bg_glass_55_fbf9ee_1x400.png) 50% 50% repeat-x;
color: #363636
}
.ui-state-highlight a, .ui-widget-content .ui-state-highlight a, .ui-widget-header .ui-state-highlight a {
color: #363636
}
.ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error {
border: 1px solid #cd0a0a;
background: #fef1ec url(../images/ui-bg_glass_95_fef1ec_1x400.png) 50% 50% repeat-x;
color: #cd0a0a
}
.ui-state-error a, .ui-state-error-text, .ui-widget-content .ui-state-error a, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error a, .ui-widget-header .ui-state-error-text {
color: #cd0a0a
}
.ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary {
font-weight: 700
}
.ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary {
opacity: .7;
filter: Alpha(Opacity=70);
font-weight: 400
}
.ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled {
opacity: .35;
filter: Alpha(Opacity=35);
background-image: none
}
.ui-icon {
width: 16px;
height: 16px;
background-image: url(../images/ui-icons_454545_256x240.png)
}
.ui-state-active .ui-icon, .ui-state-default .ui-icon, .ui-state-error .ui-icon, .ui-state-error-text .ui-icon, .ui-state-focus .ui-icon, .ui-state-highlight .ui-icon, .ui-state-hover .ui-icon, .ui-widget-content .ui-icon, .ui-widget-header .ui-icon {
background-image: url(../images/ui-icons_454545_256x240.png)
}
.ui-icon-carat-1-n {
background-position: 0 0
}
.ui-icon-carat-1-ne {
background-position: -16px 0
}
.ui-icon-carat-1-e {
background-position: -32px 0
}
.ui-icon-carat-1-se {
background-position: -48px 0
}
.ui-icon-carat-1-s {
background-position: -64px 0
}
.ui-icon-carat-1-sw {
background-position: -80px 0
}
.ui-icon-carat-1-w {
background-position: -96px 0
}
.ui-icon-carat-1-nw {
background-position: -112px 0
}
.ui-icon-carat-2-n-s {
background-position: -128px 0
}
.ui-icon-carat-2-e-w {
background-position: -144px 0
}
.ui-icon-triangle-1-n {
background-position: 0 -16px
}
.ui-icon-triangle-1-ne {
background-position: -16px -16px
}
.ui-icon-triangle-1-e {
background-position: -32px -16px
}
.ui-icon-triangle-1-se {
background-position: -48px -16px
}
.ui-icon-triangle-1-s {
background-position: -64px -16px
}
.ui-icon-triangle-1-sw {
background-position: -80px -16px
}
.ui-icon-triangle-1-w {
background-position: -96px -16px
}
.ui-icon-triangle-1-nw {
background-position: -112px -16px
}
.ui-icon-triangle-2-n-s {
background-position: -128px -16px
}
.ui-icon-triangle-2-e-w {
background-position: -144px -16px
}
.ui-icon-arrow-1-n {
background-position: 0 -32px
}
.ui-icon-arrow-1-ne {
background-position: -16px -32px
}
.ui-icon-arrow-1-e {
background-position: -32px -32px
}
.ui-icon-arrow-1-se {
background-position: -48px -32px
}
.ui-icon-arrow-1-s {
background-position: -64px -32px
}
.ui-icon-arrow-1-sw {
background-position: -80px -32px
}
.ui-icon-arrow-1-w {
background-position: -96px -32px
}
.ui-icon-arrow-1-nw {
background-position: -112px -32px
}
.ui-icon-arrow-2-n-s {
background-position: -128px -32px
}
.ui-icon-arrow-2-ne-sw {
background-position: -144px -32px
}
.ui-icon-arrow-2-e-w {
background-position: -160px -32px
}
.ui-icon-arrow-2-se-nw {
background-position: -176px -32px
}
.ui-icon-arrowstop-1-n {
background-position: -192px -32px
}
.ui-icon-arrowstop-1-e {
background-position: -208px -32px
}
.ui-icon-arrowstop-1-s {
background-position: -224px -32px
}
.ui-icon-arrowstop-1-w {
background-position: -240px -32px
}
.ui-icon-arrowthick-1-n {
background-position: 0 -48px
}
.ui-icon-arrowthick-1-ne {
background-position: -16px -48px
}
.ui-icon-arrowthick-1-e {
background-position: -32px -48px
}
.ui-icon-arrowthick-1-se {
background-position: -48px -48px
}
.ui-icon-arrowthick-1-s {
background-position: -64px -48px
}
.ui-icon-arrowthick-1-sw {
background-position: -80px -48px
}
.ui-icon-arrowthick-1-w {
background-position: -96px -48px
}
.ui-icon-arrowthick-1-nw {
background-position: -112px -48px
}
.ui-icon-arrowthick-2-n-s {
background-position: -128px -48px
}
.ui-icon-arrowthick-2-ne-sw {
background-position: -144px -48px
}
.ui-icon-arrowthick-2-e-w {
background-position: -160px -48px
}
.ui-icon-arrowthick-2-se-nw {
background-position: -176px -48px
}
.ui-icon-arrowthickstop-1-n {
background-position: -192px -48px
}
.ui-icon-arrowthickstop-1-e {
background-position: -208px -48px
}
.ui-icon-arrowthickstop-1-s {
background-position: -224px -48px
}
.ui-icon-arrowthickstop-1-w {
background-position: -240px -48px
}
.ui-icon-arrowreturnthick-1-w {
background-position: 0 -64px
}
.ui-icon-arrowreturnthick-1-n {
background-position: -16px -64px
}
.ui-icon-arrowreturnthick-1-e {
background-position: -32px -64px
}
.ui-icon-arrowreturnthick-1-s {
background-position: -48px -64px
}
.ui-icon-arrowreturn-1-w {
background-position: -64px -64px
}
.ui-icon-arrowreturn-1-n {
background-position: -80px -64px
}
.ui-icon-arrowreturn-1-e {
background-position: -96px -64px
}
.ui-icon-arrowreturn-1-s {
background-position: -112px -64px
}
.ui-icon-arrowrefresh-1-w {
background-position: -128px -64px
}
.ui-icon-arrowrefresh-1-n {
background-position: -144px -64px
}
.ui-icon-arrowrefresh-1-e {
background-position: -160px -64px
}
.ui-icon-arrowrefresh-1-s {
background-position: -176px -64px
}
.ui-icon-arrow-4 {
background-position: 0 -80px
}
.ui-icon-arrow-4-diag {
background-position: -16px -80px
}
.ui-icon-extlink {
background-position: -32px -80px
}
.ui-icon-newwin {
background-position: -48px -80px
}
.ui-icon-refresh {
background-position: -64px -80px
}
.ui-icon-shuffle {
background-position: -80px -80px
}
.ui-icon-transfer-e-w {
background-position: -96px -80px
}
.ui-icon-transferthick-e-w {
background-position: -112px -80px
}
.ui-icon-folder-collapsed {
background-position: 0 -96px
}
.ui-icon-folder-open {
background-position: -16px -96px
}
.ui-icon-document {
background-position: -32px -96px
}
.ui-icon-document-b {
background-position: -48px -96px
}
.ui-icon-note {
background-position: -64px -96px
}
.ui-icon-mail-closed {
background-position: -80px -96px
}
.ui-icon-mail-open {
background-position: -96px -96px
}
.ui-icon-suitcase {
background-position: -112px -96px
}
.ui-icon-comment {
background-position: -128px -96px
}
.ui-icon-person {
background-position: -144px -96px
}
.ui-icon-print {
background-position: -160px -96px
}
.ui-icon-trash {
background-position: -176px -96px
}
.ui-icon-locked {
background-position: -192px -96px
}
.ui-icon-unlocked {
background-position: -208px -96px
}
.ui-icon-bookmark {
background-position: -224px -96px
}
.ui-icon-tag {
background-position: -240px -96px
}
.ui-icon-home {
background-position: 0 -112px
}
.ui-icon-flag {
background-position: -16px -112px
}
.ui-icon-calendar {
background-position: -32px -112px
}
.ui-icon-cart {
background-position: -48px -112px
}
.ui-icon-pencil {
background-position: -64px -112px
}
.ui-icon-clock {
background-position: -80px -112px
}
.ui-icon-disk {
background-position: -96px -112px
}
.ui-icon-calculator {
background-position: -112px -112px
}
.ui-icon-zoomin {
background-position: -128px -112px
}
.ui-icon-zoomout {
background-position: -144px -112px
}
.ui-icon-search {
background-position: -160px -112px
}
.ui-icon-wrench {
background-position: -176px -112px
}
.ui-icon-gear {
background-position: -192px -112px
}
.ui-icon-heart {
background-position: -208px -112px
}
.ui-icon-star {
background-position: -224px -112px
}
.ui-icon-link {
background-position: -240px -112px
}
.ui-icon-cancel {
background-position: 0 -128px
}
.ui-icon-plus {
background-position: -16px -128px
}
.ui-icon-plusthick {
background-position: -32px -128px
}
.ui-icon-minus {
background-position: -48px -128px
}
.ui-icon-minusthick {
background-position: -64px -128px
}
.ui-icon-close {
background-position: -80px -128px
}
.ui-icon-closethick {
background-position: -96px -128px
}
.ui-icon-key {
background-position: -112px -128px
}
.ui-icon-lightbulb {
background-position: -128px -128px
}
.ui-icon-scissors {
background-position: -144px -128px
}
.ui-icon-clipboard {
background-position: -160px -128px
}
.ui-icon-copy {
background-position: -176px -128px
}
.ui-icon-contact {
background-position: -192px -128px
}
.ui-icon-image {
background-position: -208px -128px
}
.ui-icon-video {
background-position: -224px -128px
}
.ui-icon-script {
background-position: -240px -128px
}
.ui-icon-alert {
background-position: 0 -144px
}
.ui-icon-info {
background-position: -16px -144px
}
.ui-icon-notice {
background-position: -32px -144px
}
.ui-icon-help {
background-position: -48px -144px
}
.ui-icon-check {
background-position: -64px -144px
}
.ui-icon-bullet {
background-position: -80px -144px
}
.ui-icon-radio-off {
background-position: -96px -144px
}
.ui-icon-radio-on {
background-position: -112px -144px
}
.ui-icon-pin-w {
background-position: -128px -144px
}
.ui-icon-pin-s {
background-position: -144px -144px
}
.ui-icon-play {
background-position: 0 -160px
}
.ui-icon-pause {
background-position: -16px -160px
}
.ui-icon-seek-next {
background-position: -32px -160px
}
.ui-icon-seek-prev {
background-position: -48px -160px
}
.ui-icon-seek-end {
background-position: -64px -160px
}
.ui-icon-seek-first, .ui-icon-seek-start {
background-position: -80px -160px
}
.ui-icon-stop {
background-position: -96px -160px
}
.ui-icon-eject {
background-position: -112px -160px
}
.ui-icon-volume-off {
background-position: -128px -160px
}
.ui-icon-volume-on {
background-position: -144px -160px
}
.ui-icon-power {
background-position: 0 -176px
}
.ui-icon-signal-diag {
background-position: -16px -176px
}
.ui-icon-signal {
background-position: -32px -176px
}
.ui-icon-battery-0 {
background-position: -48px -176px
}
.ui-icon-battery-1 {
background-position: -64px -176px
}
.ui-icon-battery-2 {
background-position: -80px -176px
}
.ui-icon-battery-3 {
background-position: -96px -176px
}
.ui-icon-circle-plus {
background-position: 0 -192px
}
.ui-icon-circle-minus {
background-position: -16px -192px
}
.ui-icon-circle-close {
background-position: -32px -192px
}
.ui-icon-circle-triangle-e {
background-position: -48px -192px
}
.ui-icon-circle-triangle-s {
background-position: -64px -192px
}
.ui-icon-circle-triangle-w {
background-position: -80px -192px
}
.ui-icon-circle-triangle-n {
background-position: -96px -192px
}
.ui-icon-circle-arrow-e {
background-position: -112px -192px
}
.ui-icon-circle-arrow-s {
background-position: -128px -192px
}
.ui-icon-circle-arrow-w {
background-position: -144px -192px
}
.ui-icon-circle-arrow-n {
background-position: -160px -192px
}
.ui-icon-circle-zoomin {
background-position: -176px -192px
}
.ui-icon-circle-zoomout {
background-position: -192px -192px
}
.ui-icon-circle-check {
background-position: -208px -192px
}
.ui-icon-circlesmall-plus {
background-position: 0 -208px
}
.ui-icon-circlesmall-minus {
background-position: -16px -208px
}
.ui-icon-circlesmall-close {
background-position: -32px -208px
}
.ui-icon-squaresmall-plus {
background-position: -48px -208px
}
.ui-icon-squaresmall-minus {
background-position: -64px -208px
}
.ui-icon-squaresmall-close {
background-position: -80px -208px
}
.ui-icon-grip-dotted-vertical {
background-position: 0 -224px
}
.ui-icon-grip-dotted-horizontal {
background-position: -16px -224px
}
.ui-icon-grip-solid-vertical {
background-position: -32px -224px
}
.ui-icon-grip-solid-horizontal {
background-position: -48px -224px
}
.ui-icon-gripsmall-diagonal-se {
background-position: -64px -224px
}
.ui-icon-grip-diagonal-se {
background-position: -80px -224px
}
.ui-corner-all, .ui-corner-left, .ui-corner-tl, .ui-corner-top {
-moz-border-radius-topleft: 4px;
-webkit-border-top-left-radius: 4px;
-khtml-border-top-left-radius: 4px;
border-top-left-radius: 4px
}
.ui-corner-all, .ui-corner-right, .ui-corner-top, .ui-corner-tr {
-moz-border-radius-topright: 4px;
-webkit-border-top-right-radius: 4px;
-khtml-border-top-right-radius: 4px;
border-top-right-radius: 4px
}
.ui-corner-all, .ui-corner-bl, .ui-corner-bottom, .ui-corner-left {
-moz-border-radius-bottomleft: 4px;
-webkit-border-bottom-left-radius: 4px;
-khtml-border-bottom-left-radius: 4px;
border-bottom-left-radius: 4px
}
.ui-corner-all, .ui-corner-bottom, .ui-corner-br, .ui-corner-right {
-moz-border-radius-bottomright: 4px;
-webkit-border-bottom-right-radius: 4px;
-khtml-border-bottom-right-radius: 4px;
border-bottom-right-radius: 4px
}
.ui-widget-overlay {
background: #aaa url(../images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x;
opacity: .3;
filter: Alpha(Opacity=30)
}
.ui-widget-shadow {
margin: -8px 0 0 -8px;
padding: 8px;
background: #aaa url(../images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x;
opacity: .3;
filter: Alpha(Opacity=30);
-moz-border-radius: 8px;
-khtml-border-radius: 8px;
-webkit-border-radius: 8px;
border-radius: 8px
}
/* end datepicker */
.tp_donate_setting_wrapper a.nav-tab:focus {
box-shadow: none;
}
.tp_donate_wrapper_content table th {
text-align: left;
min-width: 300px;
max-width: 300px;
}
.tp_donate_wrapper_content table p {
margin: 2px;
font-weight: normal;
}
.tp_donate_wrapper_content table select,
.tp_donate_wrapper_content table input[ type="text" ] {
width: auto;
min-width: 250px;
}
#checkout h3 a {
font-size: 12px;
font-weight: 600;
padding: 0px 12px;
}
#checkout h3 a.active {
border-bottom: 1px solid #f1f1f1;
background: #f1f1f1;
color: #000;
}
/* WP POST TABLE */
.column-donate_date,
.column-donate_total,
.column-donate_payment_method,
.column-donate_status {
width: 10%;
}
/* END WP POST TABLE */
/**
* metabox
*/
.donate_metabox_setting {
position: relative;
float: left;
width: 20%;
margin: 0;
background-color: #fafafa;
border: 1px solid #eee;
box-sizing: border-box;
}
.donate_metabox_setting:after {
content: "";
display: block;
width: 100%;
height: 9999em;
position: absolute;
bottom: -9999em;
left: 0;
background-color: #fafafa;
border-right: 1px solid #eee;
}
.donate_metabox_setting li {
margin: 0;
}
.donate_metabox_setting li a {
text-decoration: none;
padding: 12px;
display: block;
border-bottom: 1px solid #eee;
}
.donate_metabox_setting li a:focus {
box-shadow: none;
}
.donate_metabox_setting_section {
margin-bottom: 15px;
}
.donate_metabox_setting_section .form-group {
border-bottom: 1px solid #eee;
}
.form-group .description {
display: block;
}
.donate_metabox_setting_container {
width: 80%;
float: left;
box-sizing: border-box;
}
#donate_setting_section .inside {
overflow: hidden;
margin: 0;
padding: 0;
}
.donate_metabox_setting_section .donate_metabox {
border-bottom: 1px solid #dedede;
}
.donate_metabox_setting_section label {
float: left;
width: 150px;
font-size: 12px;
font-weight: 400;
line-height: 24px;
margin-left: -150px;
}
.donate_metabox_setting_section th {
text-align: left;
width: 30%;
}
.donate_metabox_setting_section p {
padding: 5px 5px 5px 165px;
}
.donate_metabox_setting_container .tool_box {
overflow: hidden;
}
.donate_metabox_setting_section textarea {
width: 100%;
}
#donate_donate_info_section .inside {
margin: 0;
padding: 0;
}
.donate_items {
border-collapse: collapse;
width: 100%;
}
.donate_items * {
color: #999;
}
.donate_items thead th {
background-color: #f8f8f8;
font-weight: 400;
font-size: 13px;
}
.donate_items th,
.donate_items tr {
border-bottom: 1px solid #f8f8f8;
}
.donate_items td {
border: none;
}
.donate_items .campaign {
text-align: left;
border-right: 1px solid #f8f8f8;
}
.donate_items .action {
width: 1%;
border-left: 1px solid #f8f8f8;
}
.donate_items .action a {
text-decoration: none;
display: inline-block;
padding: 5px;
border-radius: 50%;
}
.donate_items .action a i {
font-size: 9px;
}
.donate_items .amount {
text-align: center;;
}
.donate_items .total,
.donate_items .donor {
text-align: right;
border-right: 1px solid #f8f8f8;
color: #666;
}
.donate_items tbody *,
.donate_items tfoot * {
color: #666;
font-size: 12px;
}
.donate_items .thumb {
width: 1%;
}
.addition {
width: 100%;
}
.donate_items tfoot .amount ins {
color: #000;
font-weight: 600;
}
/**
* donor metabox
*/
#donate_donor_info_section th,
#donate_donor_info_section td,
#donate_donate_info_section th,
#donate_donate_info_section td {
padding: 12px;
}
.column-start,
.column-end,
.column-funded {
text-align: center !important;
}
#donate_donate_info_section label {
padding: 5px 10px !important;
}
#thimpress_donate_type {
width: 200px;
}
/**
* donate status
*/
#donate_action label {
font-weight: 600;
}
.donate-status {
display: inline-block;
padding: 5px;
border-radius: 3px;
font-size: 10px;
font-weight: 600;
color: #fff;
min-width: 55px;
text-align: center;
}
.donate-status.donate-cancelled {
background-color: #634A4A;
}
.donate-status.donate-pending {
background-color: rgba(255, 47, 0, 0.82);
}
.donate-status.donate-processing {
background-color: rgb(255, 235, 0);
}
.donate-status.donate-completed {
background-color: rgba(31, 241, 28, 0.82);
}
.donate-status.donate-refunded {
background-color: #d47f3c;
}
/* donate notes */
#donate_note label {
display: block;
margin: 0 0 5px 0;
font-weight: 600;
}
#donate_note textarea {
width: 100%;
}
#action-status {
display: inline-block;
margin-right: 5px;
}
#action-status a {
margin-right: 5px;
padding: 0 7px;
}
.donate_action.column-donate_action a.edit-donate {
padding: 0 7px;
margin-left: -5px;
}
|
ThimPressWP/FundPress
|
assets/css/admin/admin.css
|
CSS
|
gpl-2.0
| 33,814
|
<?php
/*
+---------------------------------------------------------------------------+
| Revive Adserver |
| http://www.revive-adserver.com |
| |
| Copyright: See the COPYRIGHT.txt file. |
| License: GPLv2 or later, see the LICENSE.txt file. |
+---------------------------------------------------------------------------+
*/
require_once MAX_PATH . '/etc/changes/migration_tables_core_546.php';
require_once MAX_PATH . '/lib/OA/DB/Sql.php';
require_once MAX_PATH . '/etc/changes/tests/unit/MigrationTest.php';
require_once MAX_PATH . '/lib/OA/Dal/DataGenerator.php';
require_once(MAX_PATH. '/lib/OA/Upgrade/Configuration.php');
/**
* Test for migration class #546 that check that the old preferences
* stored on the table 'preference' are migrated to the table 'preferences'
*
* @package changes
* @subpackage TestSuite
* @author Miguel Correa <miguel.correa@openx.org>
*/
class Migration_546Test extends MigrationTest
{
/**
* Test for migration class
*
*/
function testMigrateStatus()
{
$prefix = $this->getPrefix();
$this->initDatabase(544, array('preference', 'preferences', 'account_preference_assoc', 'preference_advertiser', 'preference_publisher', 'agency', 'application_variable', 'accounts'));
$tblPreference = $this->oDbh->quoteIdentifier($prefix.'preference', true);
$tblAgency = $this->oDbh->quoteIdentifier($prefix.'agency', true);
$tblApplicationVariable = $this->oDbh->quoteIdentifier($prefix.'application_variable', true);
$tblAccounts = $this->oDbh->quoteIdentifier($prefix.'accounts', true);
$aExistingTablesInicio = $this->oDbh->manager->listTables();
$this->oDbh->exec("INSERT INTO {$tblPreference} (agencyid, config_version, my_header, my_footer, my_logo, language, name, company_name,
override_gd_imageformat, begin_of_week, percentage_decimals, type_sql_allow, type_url_allow,
type_web_allow, type_html_allow, type_txt_allow, banner_html_auto, admin, admin_pw, admin_fullname,
admin_email, warn_admin, warn_agency, warn_client, warn_limit, admin_email_headers, admin_novice,
default_banner_weight, default_campaign_weight, default_banner_url, default_banner_destination,
client_welcome, client_welcome_msg, publisher_welcome, publisher_welcome_msg, content_gzip_compression,
userlog_email, gui_show_campaign_info, gui_show_campaign_preview, gui_campaign_anonymous, gui_show_banner_info,
gui_show_banner_preview, gui_show_banner_html, gui_show_matching, gui_show_parents, gui_hide_inactive,
gui_link_compact_limit, gui_header_background_color, gui_header_foreground_color, gui_header_active_tab_color,
gui_header_text_color, gui_invocation_3rdparty_default, qmail_patch, updates_enabled, updates_cache,
updates_timestamp, updates_last_seen, allow_invocation_plain, allow_invocation_plain_nocookies, allow_invocation_js,
allow_invocation_frame, allow_invocation_xmlrpc, allow_invocation_local, allow_invocation_interstitial,
allow_invocation_popup, allow_invocation_clickonly, auto_clean_tables, auto_clean_tables_interval, auto_clean_userlog,
auto_clean_userlog_interval, auto_clean_tables_vacuum, autotarget_factor, maintenance_timestamp, compact_stats,
statslastday, statslasthour, default_tracker_status, default_tracker_type, default_tracker_linkcampaigns,
publisher_agreement, publisher_agreement_text, publisher_payment_modes, publisher_currencies, publisher_categories,
publisher_help_files, publisher_default_tax_id, publisher_default_approved, more_reports, gui_column_id, gui_column_requests,
gui_column_impressions, gui_column_clicks, gui_column_ctr, gui_column_conversions, gui_column_conversions_pending,
gui_column_sr_views, gui_column_sr_clicks, gui_column_revenue, gui_column_cost, gui_column_bv, gui_column_num_items,
gui_column_revcpc, gui_column_costcpc, gui_column_technology_cost, gui_column_income, gui_column_income_margin,
gui_column_profit, gui_column_margin, gui_column_erpm, gui_column_erpc, gui_column_erps, gui_column_eipm,
gui_column_eipc, gui_column_eips, gui_column_ecpm, gui_column_ecpc, gui_column_ecps, gui_column_epps,
maintenance_cron_timestamp, warn_limit_days) VALUES (0, 0.000, NULL, NULL, NULL, 'english', NULL, 'mysite.com', NULL, 1, 2, 't', 't', 'f', 't', 't', 't', 'admin', 'bdcf5fc18e4f01990300ed0d0a306428', 'Your Name', 'miguel.correa@openx.org', 't', 't', 't', 100, NULL, 't', 1, 1, NULL, NULL, 't', NULL, 't', NULL, 'f', 't', 't', 'f', 'f', 't', 't', 'f', 't', 'f', 'f', 50, NULL, NULL, NULL, NULL, '', 'f', 't', NULL, 0, NULL, 'f', 't', 't', 'f', 'f', 't', 't', 't', 't', 'f', 5, 'f', 5, 't', -1, 0, 't', '2008-05-02', 0, 1, 1, 'f', 'f', NULL, NULL, NULL, NULL, NULL, 'f', 'f', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1)");
$this->oDbh->exec("INSERT INTO {$tblAgency} (agencyid, name, contact, email, logout_url, active, updated, account_id) VALUES (1, 'Default manager', NULL, '', NULL, 1, '2008-05-16 11:01:56', 2)");
$this->oDbh->exec("INSERT INTO {$tblApplicationVariable} (name, value) VALUES ('tables_core', '544')");
$this->oDbh->exec("INSERT INTO {$tblApplicationVariable} (name, value) VALUES ('oa_version', '2.5.46-dev')");
$this->oDbh->exec("INSERT INTO {$tblApplicationVariable} (name, value) VALUES ('platform_hash', '70fb56249cb15a78d4ed6aa81d068e74e07b8cc3')");
$this->oDbh->exec("INSERT INTO {$tblApplicationVariable} (name, value) VALUES ('sync_last_run', '2008-05-16 11:01:45')");
$this->oDbh->exec("INSERT INTO {$tblApplicationVariable} (name, value) VALUES ('sync_cache', 'b:0;')");
$this->oDbh->exec("INSERT INTO {$tblApplicationVariable} (name, value) VALUES ('sync_timestamp', '1210932105')");
$this->oDbh->exec("INSERT INTO {$tblAccounts} (account_id, account_type, account_name) VALUES (1, 'ADMIN', 'Administrator account')");
$this->oDbh->exec("INSERT INTO {$tblAccounts} (account_id, account_type, account_name) VALUES (2, 'MANAGER', 'Default manager')");
$this->oDbh->exec("INSERT INTO {$tblAccounts} (account_id, account_type, account_name) VALUES (3, 'TRAFFICKER', 'localhost')");
$migration = new Migration_546();
$migration->init($this->oDbh, MAX_PATH.'/var/DB_Upgrade.test.log');
$migration->migratePreferences();
$tblPreferences = $this->oDbh->quoteIdentifier($prefix.'preferences', true);
$aResults = $this->oDbh->queryAll("SELECT * FROM ".$tblPreferences);
$aExpected = array(array (
'preference_id' => '1',
'preference_name' => 'auto_alter_html_banners_for_click_tracking',
'account_type' => 'ADVERTISER'
),
array (
'preference_id' => '2',
'preference_name' => 'ui_week_start_day',
'account_type' => ''
),
array (
'preference_id' => '3',
'preference_name' => 'ui_percentage_decimals',
'account_type' => ''
),
array (
'preference_id' => '4',
'preference_name' => 'warn_email_admin',
'account_type' => 'ADMIN'
),
array (
'preference_id' => '5',
'preference_name' => 'warn_email_admin_impression_limit',
'account_type' => 'ADMIN'
),
array (
'preference_id' => '6',
'preference_name' => 'warn_email_admin_day_limit',
'account_type' => 'ADMIN'
),
array (
'preference_id' => '7',
'preference_name' => 'warn_email_manager',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '8',
'preference_name' => 'warn_email_manager_impression_limit',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '9',
'preference_name' => 'warn_email_manager_day_limit',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '10',
'preference_name' => 'warn_email_advertiser',
'account_type' => 'ADVERTISER'
),
array (
'preference_id' => '11',
'preference_name' => 'warn_email_advertiser_impression_limit',
'account_type' => 'ADVERTISER'
),
array (
'preference_id' => '12',
'preference_name' => 'warn_email_advertiser_day_limit',
'account_type' => 'ADVERTISER'
),
array (
'preference_id' => '13',
'preference_name' => 'ui_novice_user',
'account_type' => ''
),
array (
'preference_id' => '14',
'preference_name' => 'default_banner_weight',
'account_type' => 'ADVERTISER'
),
array (
'preference_id' => '15',
'preference_name' => 'default_campaign_weight',
'account_type' => 'ADVERTISER'
),
array (
'preference_id' => '16',
'preference_name' => 'default_banner_image_url',
'account_type' => 'TRAFFICKER'
),
array (
'preference_id' => '17',
'preference_name' => 'default_banner_destination_url',
'account_type' => 'TRAFFICKER'
),
array ('preference_id' => '18',
'preference_name' => 'ui_show_campaign_info',
'account_type' => 'ADVERTISER'
),
array('preference_id' => '19',
'preference_name' => 'ui_show_campaign_preview',
'account_type' => 'ADVERTISER'
),
array('preference_id' => '20',
'preference_name' => 'ui_show_banner_info',
'account_type' => 'ADVERTISER'
),
array ('preference_id' => '21',
'preference_name' => 'ui_show_banner_preview',
'account_type' => 'ADVERTISER'
),
array (
'preference_id' => '22',
'preference_name' => 'ui_show_banner_html',
'account_type' => 'ADVERTISER'
),
array (
'preference_id' => '23',
'preference_name' => 'ui_show_matching_banners',
'account_type' => 'TRAFFICKER'
),
array (
'preference_id' => '24',
'preference_name' => 'ui_show_matching_banners_parents',
'account_type' => 'TRAFFICKER'
),
array (
'preference_id' => '25',
'preference_name' => 'ui_hide_inactive',
'account_type' => ''
),
array (
'preference_id' => '26',
'preference_name' => 'tracker_default_status',
'account_type' => 'ADVERTISER'
),
array (
'preference_id' => '27',
'preference_name' => 'tracker_default_type',
'account_type' => 'ADVERTISER'
),
array (
'preference_id' => '28',
'preference_name' => 'tracker_link_campaigns',
'account_type' => 'ADVERTISER'
),
array (
'preference_id' => '29',
'preference_name' => 'ui_column_id',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '30',
'preference_name' => 'ui_column_id_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '31',
'preference_name' => 'ui_column_id_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '32',
'preference_name' => 'ui_column_requests',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '33',
'preference_name' => 'ui_column_requests_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '34',
'preference_name' => 'ui_column_requests_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '35',
'preference_name' => 'ui_column_impressions',
'account_type' => 'MANAGER',
),
array (
'preference_id' => '36',
'preference_name' => 'ui_column_impressions_label',
'account_type' => 'MANAGER',
),
array (
'preference_id' => '37',
'preference_name' => 'ui_column_impressions_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '38',
'preference_name' => 'ui_column_clicks',
'account_type' => 'MANAGER',
),
array (
'preference_id' => '39',
'preference_name' => 'ui_column_clicks_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '40',
'preference_name' => 'ui_column_clicks_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '41',
'preference_name' => 'ui_column_ctr',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '42',
'preference_name' => 'ui_column_ctr_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '43',
'preference_name' => 'ui_column_ctr_rank',
'account_type' => 'MANAGER',
),
array (
'preference_id' => '44',
'preference_name' => 'ui_column_conversions',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '45',
'preference_name' => 'ui_column_conversions_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '46',
'preference_name' => 'ui_column_conversions_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '47',
'preference_name' => 'ui_column_conversions_pending',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '48',
'preference_name' => 'ui_column_conversions_pending_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '49',
'preference_name' => 'ui_column_conversions_pending_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '50',
'preference_name' => 'ui_column_sr_views',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '51',
'preference_name' => 'ui_column_sr_views_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '52',
'preference_name' => 'ui_column_sr_views_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '53',
'preference_name' => 'ui_column_sr_clicks',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '54',
'preference_name' => 'ui_column_sr_clicks_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '55',
'preference_name' => 'ui_column_sr_clicks_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '56',
'preference_name' => 'ui_column_revenue',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '57',
'preference_name' => 'ui_column_revenue_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '58',
'preference_name' => 'ui_column_revenue_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '59',
'preference_name' => 'ui_column_cost',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '60',
'preference_name' => 'ui_column_cost_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '61',
'preference_name' => 'ui_column_cost_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '62',
'preference_name' => 'ui_column_bv',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '63',
'preference_name' => 'ui_column_bv_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '64',
'preference_name' => 'ui_column_bv_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '65',
'preference_name' => 'ui_column_num_items',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '66',
'preference_name' => 'ui_column_num_items_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '67',
'preference_name' => 'ui_column_num_items_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '68',
'preference_name' => 'ui_column_revcpc',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '69',
'preference_name' => 'ui_column_revcpc_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '70',
'preference_name' => 'ui_column_revcpc_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '71',
'preference_name' => 'ui_column_costcpc',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '72',
'preference_name' => 'ui_column_costcpc_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '73',
'preference_name' => 'ui_column_costcpc_rank',
'account_type' => 'MANAGER',
),
array (
'preference_id' => '74',
'preference_name' => 'ui_column_technology_cost',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '75',
'preference_name' => 'ui_column_technology_cost_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '76',
'preference_name' => 'ui_column_technology_cost_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '77',
'preference_name' => 'ui_column_income',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '78',
'preference_name' => 'ui_column_income_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '79',
'preference_name' => 'ui_column_income_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '80',
'preference_name' => 'ui_column_income_margin',
'account_type' => 'MANAGER',
),
array (
'preference_id' => '81',
'preference_name' => 'ui_column_income_margin_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '82',
'preference_name' => 'ui_column_income_margin_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '83',
'preference_name' => 'ui_column_profit',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '84',
'preference_name' => 'ui_column_profit_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '85',
'preference_name' => 'ui_column_profit_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '86',
'preference_name' => 'ui_column_margin',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '87',
'preference_name' => 'ui_column_margin_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '88',
'preference_name' => 'ui_column_margin_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '89',
'preference_name' => 'ui_column_erpm',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '90',
'preference_name' => 'ui_column_erpm_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '91',
'preference_name' => 'ui_column_erpm_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '92',
'preference_name' => 'ui_column_erpc',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '93',
'preference_name' => 'ui_column_erpc_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '94',
'preference_name' => 'ui_column_erpc_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '95',
'preference_name' => 'ui_column_erps',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '96',
'preference_name' => 'ui_column_erps_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '97',
'preference_name' => 'ui_column_erps_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '98',
'preference_name' => 'ui_column_eipm',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '99',
'preference_name' => 'ui_column_eipm_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '100',
'preference_name' => 'ui_column_eipm_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '101',
'preference_name' => 'ui_column_eipc',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '102',
'preference_name' => 'ui_column_eipc_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '103',
'preference_name' => 'ui_column_eipc_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '104',
'preference_name' => 'ui_column_eips',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '105',
'preference_name' => 'ui_column_eips_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '106',
'preference_name' => 'ui_column_eips_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '107',
'preference_name' => 'ui_column_ecpm',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '108',
'preference_name' => 'ui_column_ecpm_label',
'account_type' => 'MANAGER',
),
array (
'preference_id' => '109',
'preference_name' => 'ui_column_ecpm_rank',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '110',
'preference_name' => 'ui_column_ecpc',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '111',
'preference_name' => 'ui_column_ecpc_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '112',
'preference_name' => 'ui_column_ecpc_rank',
'account_type' => 'MANAGER',
),
array (
'preference_id' => '113',
'preference_name' => 'ui_column_ecps',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '114',
'preference_name' => 'ui_column_ecps_label',
'account_type' => 'MANAGER'
),
array (
'preference_id' => '115',
'preference_name' => 'ui_column_ecps_rank',
'account_type' => 'MANAGER'
)
);
$this->assertEqual($aResults, $aExpected);
}
}
|
adqio/revive-adserver
|
etc/changes/tests/unit/migration_tables_core_546.mig.test.php
|
PHP
|
gpl-2.0
| 36,826
|
<?php
namespace DreadLabs\Vantomas\Controller\Semantics;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use DreadLabs\Vantomas\Page\PageType;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
/**
* LinkedDataController
*
* @author Thomas Juhnke <typo3@van-tomas.de>
*/
class LinkedDataController extends ActionController
{
public function initializeAction()
{
$this->request->setFormat('jsonld');
}
/**
* @return string
*/
public function generateAction()
{
$contentObject = $this->configurationManager->getContentObject();
if ((int) $contentObject->data['doktype'] !== PageType::BLOG_ARTICLE) {
$this->getTypoScriptFrontendController()->pageNotFoundAndExit(
'Page not found.'
);
}
$this->view->assign('settings', $this->settings);
$this->view->assign('data', $contentObject->data);
}
/**
* @return TypoScriptFrontendController
*/
private function getTypoScriptFrontendController()
{
return $GLOBALS['TSFE'];
}
}
|
dreadwarrior/vantomas
|
web/typo3conf/ext/vantomas/Classes/Controller/Semantics/LinkedDataController.php
|
PHP
|
gpl-2.0
| 1,528
|
<?php
/**
*
* ?? - 控制器
*
* @package NiPHP
* @category user\controller
* @author 失眠小枕头 [levisun.mail@gmail.com]
* @copyright Copyright (c) 2013, 失眠小枕头, All rights reserved.
* @link www.NiPHP.com
* @since 2017/09/13
*/
namespace app\member\controller;
class Index
{
public function index()
{
return '<style type="text/css">*{ padding: 0; margin: 0; } .think_default_text{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:)</h1><p> ThinkPHP V5.1<br/><span style="font-size:30px">十年磨一剑 - 为API开发设计的高性能框架</span></p></div><script type="text/javascript" src="http://tajs.qq.com/stats?sId=9347272" charset="UTF-8"></script><script type="text/javascript" src="http://ad.topthink.com/Public/static/client.js"></script><thinkad id="ad_bd568ce7058a1091"></thinkad>';
}
public function hello($name = 'ThinkPHP5')
{
return 'hello,' . $name;
}
}
|
levisun/NiPHPTP5.1
|
application/member/controller/Index.php
|
PHP
|
gpl-2.0
| 1,276
|
<?php
if (!function_exists('import_custom_meta_box')){
function import_custom_meta_box($edit_post) {
?>
<div id="postcustomstuff">
<table id="list-table">
<tbody class="list:meta" id="the-list">
<?php if (!empty(PMXI_Plugin::$session->data['pmxi_import']['options']['custom_name'])): foreach (PMXI_Plugin::$session->data['pmxi_import']['options']['custom_name'] as $i => $name): ?>
<tr>
<td class="left">
<label class="screen-reader-text">Key</label>
<input type="text" value="<?php echo esc_attr($name) ?>" name="custom_name[]" size="20">
<div class="submit"><input type="submit" class="delete deletemeta" value="Delete"></div>
</td>
<td>
<label class="screen-reader-text">Value</label>
<textarea name="custom_value[]" rows="2" cols="30" class="widefat"><?php echo esc_html(PMXI_Plugin::$session->data['pmxi_import']['options']['custom_value'][$i]) ?></textarea>
</td>
</tr>
<?php endforeach; endif; ?>
</tbody>
</table>
<?php meta_form(); ?>
</div>
<p><?php _e('Custom fields can be used to add extra metadata to a post that you can <a href="http://codex.wordpress.org/Using_Custom_Fields" target="_blank">use in your theme</a>.'); ?></p>
<?php
}
}
|
willford1/slycollections
|
wp-content/plugins/wp-all-import/helpers/import_custom_meta_box.php
|
PHP
|
gpl-2.0
| 1,317
|
<?
// WinChatty Server
// Copyright (c) 2013 Brian Luft
//
// 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.
require_once '../../../include/Global.php';
$pg = nsc_connectToDatabase();
session_start();
$clientId = '';
if (isset($_SESSION['clientId']))
$clientId = $_SESSION['clientId'];
if (isset($_REQUEST['clientId']))
{
$_SESSION['clientId'] = $_REQUEST['clientId'];
header('Location: https://winchatty.com/v2/notifications/ui/login');
die();
}
$error = false;
if (isset($_POST['action']))
{
$username = strtolower($_POST['username']);
$password = $_POST['password'];
try
{
ChattyParser()->isModerator($username, $password);
}
catch (Exception $ex)
{
$error = 'Invalid username or password.';
}
if ($error === false)
{
if (!empty($clientId))
{
$clientUser = nsc_selectValueOrFalse($pg, 'SELECT username FROM notify_client WHERE id = $1', array($clientId));
if ($clientUser === false)
die('Invalid client ID.');
nsc_execute($pg, 'UPDATE notify_client SET username = $1 WHERE id = $2', array($username, $clientId));
}
$_SESSION['username'] = strtolower($username);
header('Location: https://winchatty.com/v2/notifications/ui/configure');
die();
}
}
?>
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta name="viewport" content="width=420, user-scalable=no">
<title>WinChatty Notifications</title>
<link rel="stylesheet" href="style.css">
<body>
<h1>WinChatty Notifications</h1>
<p>
Please log in using your Shacknews credentials.
</p>
<form method="POST" action="login">
<input type="hidden" name="action" value="login">
<p>
Username:<br>
<input type="text" name="username" class="text">
</p>
<p>
Password:<br>
<input type="password" name="password" class="text">
</p>
<p>
<input type="submit" value="Log in" class="button">
</p>
<? if ($error !== false) { ?>
<p style="background: red; padding: 10px;">
<?=$error?>
</p>
<? } ?>
</form>
</body>
</html>
|
electroly/winchatty-server
|
v2/notifications/ui/login.php
|
PHP
|
gpl-2.0
| 3,236
|
/*
* Copyright (C) 2013 Alexander Krause <alexander.krause@ed-solutions.de>
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <errno.h>
#include <limits.h>
#include <time.h>
#include "sdisp.h"
#include "sdisp-private.h"
void _sdisp_print_debug(sdisp_t *ctx, const char *txt) {
if (ctx->debug) {
if ((ctx == NULL) || (ctx->type_name==NULL)) {
printf("[NULL] %s\n",txt);
} else {
printf("[%s] %s\n",ctx->type_name,txt);
}
}
}
|
erazor83/libsdisp
|
src/sdisp-private.c
|
C
|
gpl-2.0
| 486
|
<article>
<h2>404 — Page not found</h2>
<p>You probably didn't want what you were looking for anyway.</p>
<a href="https://placekitten.com/" target="_blank"><img src="https://placekitten.com/g/<?php echo rand(480, 800); ?>/<?php echo rand(270, 450); ?>" alt=""/></a>
</article>
|
SecretImbecile/pressandforget
|
part-404.php
|
PHP
|
gpl-2.0
| 287
|
/*
* Copyright (C) 2005-2012 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef MANGOS_SPELLAURAS_H
#define MANGOS_SPELLAURAS_H
#include "SpellAuraDefines.h"
#include "DBCEnums.h"
#include "DBCStores.h"
#include "ObjectGuid.h"
#include "ObjectHandler.h"
enum AuraRemoveMode
{
AURA_REMOVE_BY_DEFAULT,
AURA_REMOVE_BY_STACK, // at replace by similar aura
AURA_REMOVE_BY_CANCEL,
AURA_REMOVE_BY_DISPEL,
AURA_REMOVE_BY_DEATH,
AURA_REMOVE_BY_DELETE, // use for speedup and prevent unexpected effects at player logout/pet unsummon (must be used _only_ after save), delete.
AURA_REMOVE_BY_SHIELD_BREAK, // when absorb shield is removed by damage, heal absorb debuf
AURA_REMOVE_BY_EXPIRE, // at duration end
};
enum AuraClassType
{
AURA_CLASS_AURA,
AURA_CLASS_SINGLE_ENEMY_AURA,
AURA_CLASS_AREA_AURA,
AURA_CLASS_PERSISTENT_AREA_AURA,
};
struct Modifier
{
AuraType m_auraname;
int32 m_amount;
int32 m_miscvalue;
uint32 periodictime;
int32 m_baseamount;
};
class Unit;
struct SpellEntry;
struct ProcTriggerSpell;
// forward decl
class Aura;
typedef std::map<SpellEffectIndex,Aura> AuraStorage;
// internal helper
struct ReapplyAffectedPassiveAurasHelper;
class MANGOS_DLL_SPEC SpellAuraHolder
{
public:
SpellAuraHolder (SpellEntry const* spellproto, Unit *target, WorldObject *caster, Item *castItem);
Aura* CreateAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolderPtr holder, Unit *target, Unit *caster = NULL, Item* castItem = NULL);
Aura* CreateAura(AuraClassType type, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolderPtr holder, Unit *target, Unit *caster = NULL, Item* castItem = NULL);
void RemoveAura(SpellEffectIndex index);
void ApplyAuraModifiers(bool apply, bool real = false);
void _AddSpellAuraHolder();
void _RemoveSpellAuraHolder();
void BuildUpdatePacket(WorldPacket& data) const;
void SendAuraUpdate(bool remove) const;
void HandleSpellSpecificBoosts(bool apply);
void HandleSpellSpecificBoostsForward(bool apply);
void CleanupTriggeredSpells();
void setDiminishGroup(DiminishingGroup group) { m_AuraDRGroup = group; }
DiminishingGroup getDiminishGroup() const { return m_AuraDRGroup; }
uint32 GetStackAmount() const { return m_stackAmount; }
void SetStackAmount(uint32 stackAmount);
bool ModStackAmount(int32 num); // return true if last charge dropped
Aura* GetAuraByEffectIndex(SpellEffectIndex index);
Aura const* GetAura(SpellEffectIndex index) const;
uint32 GetId() const { return m_spellProto->Id; }
SpellEntry const* GetSpellProto() const { return m_spellProto; }
ObjectGuid const& GetCasterGuid() const { return m_casterGuid; }
void SetCasterGuid(ObjectGuid guid) { m_casterGuid = guid; }
ObjectGuid const& GetCastItemGuid() const { return m_castItemGuid; }
Unit* GetCaster() const;
Unit* GetTarget() const { return m_target; }
void SetTarget(Unit* target) { m_target = target; }
ObjectGuid const& GetAffectiveCasterGuid() const { return m_originalCasterGuid ? m_originalCasterGuid : m_casterGuid; }
Unit* GetAffectiveCaster() const;
void SetAffectiveCasterGuid(ObjectGuid guid);
bool IsPermanent() const { return m_permanent; }
void SetPermanent(bool permanent) { m_permanent = permanent; }
bool IsPassive() const { return m_isPassive; }
bool IsDeathPersistent() const { return m_isDeathPersist; }
bool IsPersistent() const;
bool IsPositive() const;
bool IsAreaAura() const; // if one from auras of holder applied as area aura
bool IsWeaponBuffCoexistableWith() const;
bool IsNeedVisibleSlot(Unit const* caster) const;
bool IsRemovedOnShapeLost() const { return m_isRemovedOnShapeLost; }
bool IsInUse() const { return (m_in_use > 0);}
bool IsDeleted() const { return m_deleted;}
bool IsEmptyHolder() const;
void SetDeleted() { m_deleted = true; }
void SetInUse(bool state)
{
if (state)
++m_in_use;
else
{
if (m_in_use > 0)
--m_in_use;
}
}
void UpdateHolder(uint32 diff) { SetInUse(true); Update(diff); SetInUse(false); }
void Update(uint32 diff);
void RefreshHolder();
bool IsSingleTarget() const { return m_isSingleTarget; }
void SetIsSingleTarget(bool val) { m_isSingleTarget = val; }
void UnregisterSingleCastHolder();
int32 GetAuraMaxDuration() const { return m_maxDuration; }
void SetAuraMaxDuration(int32 duration);
int32 GetAuraDuration() const { return m_duration; }
void SetAuraDuration(int32 duration) { m_duration = duration; }
uint8 GetAuraSlot() const { return m_auraSlot; }
void SetAuraSlot(uint8 slot) { m_auraSlot = slot; }
uint8 GetAuraFlags() const { return m_auraFlags; }
void SetAuraFlags(uint8 flags) { m_auraFlags = flags; }
uint8 GetAuraLevel() const { return m_auraLevel; }
void SetAuraLevel(uint8 level) { m_auraLevel = level; }
uint32 GetAuraCharges() const { return m_procCharges; }
void SetAuraCharges(uint32 charges, bool update = true)
{
if (m_procCharges == charges)
return;
m_procCharges = charges;
if (update)
SendAuraUpdate(false);
}
bool DropAuraCharge() // return true if last charge dropped
{
if (m_procCharges == 0)
return false;
m_procCharges--;
SendAuraUpdate(false);
return m_procCharges == 0;
}
time_t GetAuraApplyTime() const { return m_applyTime; }
void SetVisibleAura(bool remove);
void SetRemoveMode(AuraRemoveMode mode) { m_removeMode = mode; }
void SetLoadedState(ObjectGuid const& casterGUID, ObjectGuid const& itemGUID, uint32 stackAmount, uint32 charges, int32 maxduration, int32 duration)
{
m_casterGuid = casterGUID;
m_castItemGuid = itemGUID;
m_procCharges = charges;
m_stackAmount = stackAmount;
SetAuraMaxDuration(maxduration);
SetAuraDuration(duration);
}
bool HasMechanic(uint32 mechanic) const;
bool HasMechanicMask(uint32 mechanicMask) const;
void CleanupsBeforeDelete();
~SpellAuraHolder();
private:
void AddAura(Aura aura, SpellEffectIndex index);
SpellEntry const* m_spellProto;
Unit* m_target;
ObjectGuid m_casterGuid;
ObjectGuid m_castItemGuid; // it is NOT safe to keep a pointer to the item because it may get deleted
ObjectGuid m_originalCasterGuid; // real source of auras cast, used for set cast source in area auras with "exclusive target"
time_t m_applyTime;
uint8 m_auraSlot; // Aura slot on unit (for show in client)
uint8 m_auraFlags; // Aura info flag (for send data to client)
uint8 m_auraLevel; // Aura level (store caster level for correct show level dep amount)
uint32 m_procCharges; // Aura charges (0 for infinite)
uint32 m_stackAmount; // Aura stack amount
int32 m_maxDuration; // Max aura duration
int32 m_duration; // Current time
int32 m_timeCla; // Timer for power per sec calculation
AuraRemoveMode m_removeMode:8; // Store info for know remove aura reason
DiminishingGroup m_AuraDRGroup:8; // Diminishing
AuraStorage m_aurasStorage; // Auras storage
bool m_permanent:1;
bool m_isPassive:1;
bool m_isDeathPersist:1;
bool m_isRemovedOnShapeLost:1;
bool m_isSingleTarget:1; // true if it's a single target spell and registered at caster - can change at spell steal for example
bool m_deleted:1;
int32 m_in_use; // > 0 while in SpellAuraHolder::ApplyModifiers call/SpellAuraHolder::Update/etc
};
typedef void(Aura::*pAuraHandler)(bool Apply, bool Real);
// Real == true at aura add/remove
// Real == false at aura mod unapply/reapply; when adding/removing dependent aura/item/stat mods
//
// Code in aura handler can be guarded by if (Real) check if it should execution only at real add/remove of aura
//
// MAIN RULE: Code MUST NOT be guarded by if (Real) check if it modifies any stats
// (percent auras, stats mods, etc)
// Second rule: Code must be guarded by if (Real) check if it modifies object state (start/stop attack, send packets to client, etc)
//
// Other case choice: each code line moved under if (Real) check is mangos speedup,
// each setting object update field code line moved under if (Real) check is significant mangos speedup, and less server->client data sends
// each packet sending code moved under if (Real) check is _large_ mangos speedup, and lot less server->client data sends
class MANGOS_DLL_SPEC Aura
{
friend class SpellAuraHolder;
friend struct ReapplyAffectedPassiveAurasHelper;
public:
//aura handlers
void HandleNULL(bool, bool)
{
// NOT IMPLEMENTED
}
void HandleUnused(bool, bool)
{
// NOT USED BY ANY SPELL OR USELESS
}
void HandleNoImmediateEffect(bool, bool)
{
// aura not have immediate effect at add/remove and handled by ID in other code place
}
void HandleBindSight(bool Apply, bool Real);
void HandleModPossess(bool Apply, bool Real);
void HandlePeriodicDamage(bool Apply, bool Real);
void HandleAuraDummy(bool Apply, bool Real);
void HandleAuraPeriodicDummy(bool apply, bool Real);
void HandleModConfuse(bool Apply, bool Real);
void HandleModCharm(bool Apply, bool Real);
void HandleModFear(bool Apply, bool Real);
void HandlePeriodicHeal(bool Apply, bool Real);
void HandleModAttackSpeed(bool Apply, bool Real);
void HandleModMeleeRangedSpeedPct(bool apply, bool Real);
void HandleModCombatSpeedPct(bool apply, bool Real);
void HandleModThreat(bool Apply, bool Real);
void HandleModTaunt(bool Apply, bool Real);
void HandleFeignDeath(bool Apply, bool Real);
void HandleAuraModDisarm(bool Apply, bool Real);
void HandleAuraModStalked(bool Apply, bool Real);
void HandleAuraWaterWalk(bool Apply, bool Real);
void HandleAuraFeatherFall(bool Apply, bool Real);
void HandleAuraHover(bool Apply, bool Real);
void HandleAddModifier(bool Apply, bool Real);
void HandleAuraModStun(bool Apply, bool Real);
void HandleModDamageDone(bool Apply, bool Real);
void HandleAuraUntrackable(bool Apply, bool Real);
void HandleAuraEmpathy(bool Apply, bool Real);
void HandleModOffhandDamagePercent(bool apply, bool Real);
void HandleAuraModRangedAttackPower(bool Apply, bool Real);
void HandleAuraModIncreaseEnergyPercent(bool Apply, bool Real);
void HandleAuraModIncreaseHealthPercent(bool Apply, bool Real);
void HandleAuraModRegenInterrupt(bool Apply, bool Real);
void HandleModMeleeSpeedPct(bool Apply, bool Real);
void HandlePeriodicTriggerSpell(bool Apply, bool Real);
void HandlePeriodicTriggerSpellWithValue(bool apply, bool Real);
void HandlePeriodicEnergize(bool Apply, bool Real);
void HandleAuraModResistanceExclusive(bool Apply, bool Real);
void HandleAuraSafeFall(bool Apply, bool Real);
void HandleAuraModPetTalentsPoints(bool Apply, bool Real);
void HandleModStealth(bool Apply, bool Real);
void HandleInvisibility(bool Apply, bool Real);
void HandleInvisibilityDetect(bool Apply, bool Real);
void HandleAuraModTotalHealthPercentRegen(bool Apply, bool Real);
void HandleAuraModTotalManaPercentRegen(bool Apply, bool Real);
void HandleAuraModResistance(bool Apply, bool Real);
void HandleAuraModRoot(bool Apply, bool Real);
void HandleAuraModSilence(bool Apply, bool Real);
void HandleAuraModReflectSpells(bool Apply, bool Real);
void HandleAuraModStat(bool Apply, bool Real);
void HandleDetectAmore(bool Apply, bool Real);
void HandleAuraFakeInebriation(bool Apply, bool Real);
void HandleAuraModIncreaseSpeed(bool Apply, bool Real);
void HandleAuraModIncreaseMountedSpeed(bool Apply, bool Real);
void HandleAuraModIncreaseFlightSpeed(bool Apply, bool Real);
void HandleAuraModDecreaseSpeed(bool Apply, bool Real);
void HandleAuraModUseNormalSpeed(bool Apply, bool Real);
void HandleAuraModIncreaseHealth(bool Apply, bool Real);
void HandleAuraModIncreaseEnergy(bool Apply, bool Real);
void HandleAuraModShapeshift(bool Apply, bool Real);
void HandleAuraModEffectImmunity(bool Apply, bool Real);
void HandleAuraModStateImmunity(bool Apply, bool Real);
void HandleAuraModSchoolImmunity(bool Apply, bool Real);
void HandleAuraModDmgImmunity(bool Apply, bool Real);
void HandleAuraModDispelImmunity(bool Apply, bool Real);
void HandleAuraProcTriggerSpell(bool Apply, bool Real);
void HandleAuraTrackCreatures(bool Apply, bool Real);
void HandleAuraTrackResources(bool Apply, bool Real);
void HandleAuraModParryPercent(bool Apply, bool Real);
void HandleAuraModDodgePercent(bool Apply, bool Real);
void HandleAuraModBlockPercent(bool Apply, bool Real);
void HandleAuraModCritPercent(bool Apply, bool Real);
void HandlePeriodicLeech(bool Apply, bool Real);
void HandleModHitChance(bool Apply, bool Real);
void HandleModSpellHitChance(bool Apply, bool Real);
void HandleAuraModScale(bool Apply, bool Real);
void HandlePeriodicManaLeech(bool Apply, bool Real);
void HandlePeriodicHealthFunnel(bool apply, bool Real);
void HandleModCastingSpeed(bool Apply, bool Real);
void HandleAuraMounted(bool Apply, bool Real);
void HandleWaterBreathing(bool Apply, bool Real);
void HandleModBaseResistance(bool Apply, bool Real);
void HandleModRegen(bool Apply, bool Real);
void HandleModPowerRegen(bool Apply, bool Real);
void HandleModPowerRegenPCT(bool Apply, bool Real);
void HandleChannelDeathItem(bool Apply, bool Real);
void HandleDamagePercentTaken(bool Apply, bool Real);
void HandlePeriodicDamagePCT(bool Apply, bool Real);
void HandleAuraModAttackPower(bool Apply, bool Real);
void HandleAuraTransform(bool Apply, bool Real);
void HandleModSpellCritChance(bool Apply, bool Real);
void HandleAuraModIncreaseSwimSpeed(bool Apply, bool Real);
void HandleModPowerCostPCT(bool Apply, bool Real);
void HandleModPowerCost(bool Apply, bool Real);
void HandleFarSight(bool Apply, bool Real);
void HandleModPossessPet(bool Apply, bool Real);
void HandleModMechanicImmunity(bool Apply, bool Real);
void HandleModMechanicImmunityMask(bool Apply, bool Real);
void HandleAuraModSkill(bool Apply, bool Real);
void HandleModDamagePercentDone(bool Apply, bool Real);
void HandleModPercentStat(bool Apply, bool Real);
void HandleModResistancePercent(bool Apply, bool Real);
void HandleAuraModBaseResistancePCT(bool Apply, bool Real);
void HandleModShieldBlockPCT(bool Apply, bool Real);
void HandleAuraTrackStealthed(bool Apply, bool Real);
void HandleModShieldBlock(bool Apply, bool Real);
void HandleForceReaction(bool Apply, bool Real);
void HandleAuraModRangedHaste(bool Apply, bool Real);
void HandleRangedAmmoHaste(bool Apply, bool Real);
void HandleModHealingDone(bool Apply, bool Real);
void HandleModTotalPercentStat(bool Apply, bool Real);
void HandleAuraModTotalThreat(bool Apply, bool Real);
void HandleModUnattackable(bool Apply, bool Real);
void HandleAuraModPacify(bool Apply, bool Real);
void HandleAuraGhost(bool Apply, bool Real);
void HandleAuraAllowFlight(bool Apply, bool Real);
void HandleModRating(bool apply, bool Real);
void HandleModRatingFromStat(bool apply, bool Real);
void HandleModTargetResistance(bool apply, bool Real);
void HandleAuraModAttackPowerPercent(bool apply, bool Real);
void HandleAuraModRangedAttackPowerPercent(bool apply, bool Real);
void HandleAuraModRangedAttackPowerOfStatPercent(bool apply, bool Real);
void HandleAuraModAttackPowerOfStatPercent(bool apply, bool Real);
void HandleAuraModAttackPowerOfArmor(bool apply, bool Real);
void HandleSpiritOfRedemption(bool apply, bool Real);
void HandleAuraAoECharm(bool apply, bool Real);
void HandleModManaRegen(bool apply, bool Real);
void HandleComprehendLanguage(bool apply, bool Real);
void HandleShieldBlockValue(bool apply, bool Real);
void HandleModSpellCritChanceShool(bool apply, bool Real);
void HandleAuraRetainComboPoints(bool apply, bool Real);
void HandleModSpellDamagePercentFromStat(bool apply, bool Real);
void HandleModSpellHealingPercentFromStat(bool apply, bool Real);
void HandleAuraModDispelResist(bool apply, bool Real);
void HandleAuraControlVehicle(bool apply, bool Real);
void HandleModSpellDamagePercentFromAttackPower(bool apply, bool Real);
void HandleModSpellHealingPercentFromAttackPower(bool apply, bool Real);
void HandleAuraModPacifyAndSilence(bool Apply, bool Real);
void HandleAuraModIncreaseMaxHealth(bool apply, bool Real);
void HandleAuraModExpertise(bool apply, bool Real);
void HandleForceMoveForward(bool apply, bool Real);
void HandleAuraModResistenceOfStatPercent(bool apply, bool Real);
void HandleAuraPowerBurn(bool apply, bool Real);
void HandleSchoolAbsorb(bool apply, bool Real);
void HandlePreventFleeing(bool apply, bool Real);
void HandleManaShield(bool apply, bool Real);
void HandleArenaPreparation(bool apply, bool Real);
void HandleAuraMirrorImage(bool apply, bool Real);
void HandleAuraConvertRune(bool apply, bool Real);
void HandleAuraIncreaseBaseHealthPercent(bool Apply, bool Real);
void HandleNoReagentUseAura(bool Apply, bool Real);
void HandlePhase(bool Apply, bool Real);
void HandleModTargetArmorPct(bool Apply, bool Real);
void HandleAuraModAllCritChance(bool Apply, bool Real);
void HandleAuraLinked(bool Apply, bool Real);
void HandleAuraOpenStable(bool apply, bool Real);
void HandleAuraAddMechanicAbilities(bool apply, bool Real);
void HandleAuraSetVehicle(bool apply, bool Real);
void HandleAuraFactionChange(bool apply, bool real);
void HandleAuraStopNaturalManaRegen(bool apply, bool Real);
virtual ~Aura();
void SetModifier(AuraType t, int32 a, uint32 pt, int32 miscValue);
Modifier* GetModifier() { return &m_modifier; }
Modifier const* GetModifier() const { return &m_modifier; }
int32 GetMiscValue() const { return m_spellAuraHolder->GetSpellProto()->EffectMiscValue[m_effIndex]; }
int32 GetMiscBValue() const { return m_spellAuraHolder->GetSpellProto()->EffectMiscValueB[m_effIndex]; }
SpellEntry const* GetSpellProto() const { return ( GetHolder() ? GetHolder()->GetSpellProto() : NULL); }
uint32 GetId() const { return ( (GetHolder() && GetHolder()->GetSpellProto()) ? GetHolder()->GetSpellProto()->Id : 0 ); }
ObjectGuid const& GetCastItemGuid() const;
ObjectGuid const& GetCasterGuid() const;
Unit* GetCaster() const { return ( GetHolder() ? GetHolder()->GetCaster() : NULL); }
Unit* GetTarget() const { return ( GetHolder() ? GetHolder()->GetTarget() : NULL); }
ObjectGuid const& GetAffectiveCasterGuid() const;
Unit* GetAffectiveCaster() const { return ( GetHolder() ? GetHolder()->GetAffectiveCaster() : NULL); }
SpellEffectIndex GetEffIndex() const{ return m_effIndex; }
int32 GetBasePoints() const { return m_currentBasePoints; }
int32 GetAuraMaxDuration() const { return GetHolder()->GetAuraMaxDuration(); }
int32 GetAuraDuration() const { return GetHolder()->GetAuraDuration(); }
time_t GetAuraApplyTime() const { return m_applyTime; }
uint32 GetAuraTicks() const { return m_periodicTick; }
uint32 GetAuraMaxTicks() const
{
int32 maxDuration = GetAuraMaxDuration();
return maxDuration > 0 && m_modifier.periodictime > 0 ? maxDuration / m_modifier.periodictime : 0;
}
void SetAuraPeriodicTimer(int32 timer) { SetInUse(true); m_modifier.periodictime = timer; SetInUse(false);}
uint32 GetStackAmount() const { return GetHolder()->GetStackAmount(); }
void SetLoadedState(int32 damage, uint32 periodicTime)
{
m_modifier.m_amount = damage;
m_modifier.periodictime = periodicTime;
if (uint32 maxticks = GetAuraMaxTicks())
m_periodicTick = maxticks - GetAuraDuration() / m_modifier.periodictime;
}
bool IsPositive() const { return m_positive; }
bool IsPersistent() const { return m_isPersistent; }
bool IsAreaAura() const { return m_isAreaAura; }
bool IsPeriodic() const { return m_isPeriodic; }
bool IsInUse() const { return (m_in_use > 0); }
bool IsStacking() const { return m_stacking;}
void SetInUse(bool state)
{
if (state)
++m_in_use;
else
{
if (m_in_use > 0)
--m_in_use;
}
}
void ApplyModifier(bool apply, bool Real = false);
void UpdateAura(uint32 diff);
void SetRemoveMode(AuraRemoveMode mode) { m_removeMode = mode; }
bool IsDeleted() const { return m_deleted;}
void SetDeleted() { m_deleted = true;}
Unit* GetTriggerTarget() const;
uint32 CalculateCrowdControlBreakDamage();
bool IsAffectedByCrowdControlEffect(uint32 damage);
// add/remove SPELL_AURA_MOD_SHAPESHIFT (36) linked auras
void HandleShapeshiftBoosts(bool apply);
void TriggerSpell();
void TriggerSpellWithValue();
ClassFamilyMask const& GetAuraSpellClassMask() const;
bool isAffectedOnSpell(SpellEntry const *spell) const;
bool CanProcFrom(SpellEntry const *spell, uint32 procFlag, uint32 EventProcEx, uint32 procEx, bool active, bool useClassMask) const;
//SpellAuraHolder const* GetHolder() const { return m_spellHolder; }
SpellAuraHolderPtr GetHolder() { return m_spellAuraHolder; }
SpellAuraHolderPtr const GetHolder() const { return m_spellAuraHolder; }
AuraClassType const GetAuraClassType() const { return m_classType; }
bool IsLastAuraOnHolder();
bool HasMechanic(uint32 mechanic) const;
protected:
Aura(AuraClassType type,SpellEntry const* spellproto, SpellEffectIndex eff, int32 *currentBasePoints, SpellAuraHolderPtr holder, Unit *target, Unit *caster = NULL, Item* castItem = NULL);
void AreaAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32 *currentBasePoints, SpellAuraHolderPtr holder, Unit *target, Unit *caster = NULL, Item* castItem = NULL);
void PersistentAreaAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32 *currentBasePoints, SpellAuraHolderPtr holder, Unit *target, Unit *caster = NULL, Item* castItem = NULL);
void SingleEnemyTargetAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32 *currentBasePoints, SpellAuraHolderPtr holder, Unit *target, Unit *caster = NULL, Item* castItem = NULL);
// must be called only from Aura::UpdateAura
void Update(uint32 diff);
void AreaAuraUpdate(uint32 diff);
void PersistentAreaAuraUpdate(uint32 diff);
// must be called only from Aura*::Update
void PeriodicTick();
void PeriodicDummyTick();
void PeriodicCheck();
bool IsCritFromAbilityAura(Unit* caster, uint32& damage);
void ReapplyAffectedPassiveAuras();
Modifier m_modifier;
time_t m_applyTime;
int32 m_currentBasePoints; // cache SpellEntry::CalculateSimpleValue and use for set custom base points
int32 m_periodicTimer; // Timer for periodic auras
uint32 m_periodicTick; // Tick count pass (including current if use in tick code) from aura apply, used for some tick count dependent aura effects
AuraRemoveMode m_removeMode:8; // Store info for know remove aura reason
SpellEffectIndex m_effIndex :8; // Aura effect index in spell
bool m_deleted:1;
bool m_positive:1;
bool m_isPeriodic:1;
bool m_isAreaAura:1;
bool m_isPersistent:1;
bool m_stacking:1; // Aura is not overwritten, but effects are not cumulative with similar effects
int32 m_in_use; // > 0 while in Aura::ApplyModifier call/Aura::Update/etc
bool IsEffectStacking();
SpellAuraHolderPtr const m_spellAuraHolder;
AuraClassType const m_classType;
ObjectGuid m_castersTargetGuid;
private:
void ReapplyAffectedPassiveAuras(Unit* target, bool owner_mode);
float m_radius;
AreaAuraType m_areaAuraType;
};
MANGOS_DLL_SPEC SpellAuraHolderPtr CreateSpellAuraHolder(SpellEntry const* spellproto, Unit *target, WorldObject *caster, Item *castItem = NULL);
#endif
|
Remix99/MaNGOS
|
src/game/SpellAuras.h
|
C
|
gpl-2.0
| 27,566
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.