code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
|---|---|---|---|---|---|
/*AWE GALLERY*/
.awe-gallery .awe-image-container {
position: relative;
padding-top: 75%;
overflow: hidden;
}
.awe-gallery .md-item-image img {
max-width: none;
float: none;
position: absolute;
top: 50%;
left: 50%;
width: auto;
height: 100%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
}
.awe-gallery li.md-item-image {
width: 25%;
}
.awe-gallery.image-col-1 li.md-item-image {
width: 100%;
}
.awe-gallery.image-col-2 li.md-item-image {
width: 50%;
}
.awe-gallery.image-col-3 li.md-item-image {
width: 33.33%;
}
.awe-gallery.image-col-4 li.md-item-image {
width: 25%;
}
.awe-gallery.image-col-5 li.md-item-image {
width: 20%;
}
.awe-gallery.image-col-6 li.md-item-image {
width: 16.66%;
}
.awe-gallery.image-col-7 li.md-item-image {
width: 14.28%;
}
.awe-gallery.image-col-8 li.md-item-image {
width: 12.25%;
}
.awe-gallery.image-col-9 li.md-item-image {
width: 11.11%;
}
.awe-gallery.image-col-10 li.md-item-image {
width: 10%;
}
.awe-gallery.image-col-11 li.md-item-image {
width: 9.09%;
}
.awe-gallery.image-col-12 li.md-item-image {
width: 8.33%;
}
@media screen and (max-width: 1199px) {
.awe-gallery.image-col-md-1 li.md-item-image {
width: 100%;
}
.awe-gallery.image-col-md-2 li.md-item-image {
width: 50%;
}
.awe-gallery.image-col-md-3 li.md-item-image {
width: 33.33%;
}
.awe-gallery.image-col-md-4 li.md-item-image {
width: 25%;
}
.awe-gallery.image-col-md-5 li.md-item-image {
width: 20%;
}
.awe-gallery.image-col-md-6 li.md-item-image {
width: 16.66%;
}
.awe-gallery.image-col-md-7 li.md-item-image {
width: 14.28%;
}
.awe-gallery.image-col-md-8 li.md-item-image {
width: 12.25%;
}
.awe-gallery.image-col-md-9 li.md-item-image {
width: 11.11%;
}
.awe-gallery.image-col-md-10 li.md-item-image {
width: 10%;
}
.awe-gallery.image-col-md-11 li.md-item-image {
width: 9.09%;
}
.awe-gallery.image-col-md-12 li.md-item-image {
width: 8.33%;
}
}
@media screen and (max-width: 991px) {
.awe-gallery.image-col-sm-1 li.md-item-image {
width: 100%;
}
.awe-gallery.image-col-sm-2 li.md-item-image {
width: 50%;
}
.awe-gallery.image-col-sm-3 li.md-item-image {
width: 33.33%;
}
.awe-gallery.image-col-sm-4 li.md-item-image {
width: 25%;
}
.awe-gallery.image-col-sm-5 li.md-item-image {
width: 20%;
}
.awe-gallery.image-col-sm-6 li.md-item-image {
width: 16.66%;
}
.awe-gallery.image-col-sm-7 li.md-item-image {
width: 14.28%;
}
.awe-gallery.image-col-sm-8 li.md-item-image {
width: 12.25%;
}
.awe-gallery.image-col-sm-9 li.md-item-image {
width: 11.11%;
}
.awe-gallery.image-col-sm-10 li.md-item-image {
width: 10%;
}
.awe-gallery.image-col-sm-11 li.md-item-image {
width: 9.09%;
}
.awe-gallery.image-col-sm-12 li.md-item-image {
width: 8.33%;
}
}
@media screen and (max-width: 767px) {
.awe-gallery.image-col-xs-1 li.md-item-image {
width: 100%;
}
.awe-gallery.image-col-xs-2 li.md-item-image {
width: 50%;
}
.awe-gallery.image-col-xs-3 li.md-item-image {
width: 33.33%;
}
.awe-gallery.image-col-xs-4 li.md-item-image {
width: 25%;
}
.awe-gallery.image-col-xs-5 li.md-item-image {
width: 20%;
}
.awe-gallery.image-col-xs-6 li.md-item-image {
width: 16.66%;
}
.awe-gallery.image-col-xs-7 li.md-item-image {
width: 14.28%;
}
.awe-gallery.image-col-xs-8 li.md-item-image {
width: 12.25%;
}
.awe-gallery.image-col-xs-9 li.md-item-image {
width: 11.11%;
}
.awe-gallery.image-col-xs-10 li.md-item-image {
width: 10%;
}
.awe-gallery.image-col-xs-11 li.md-item-image {
width: 9.09%;
}
.awe-gallery.image-col-xs-12 li.md-item-image {
width: 8.33%;
}
}
/*Magnic popup*/
.mfp-wrap .mfp-container .mdf-list-thumb {
position: absolute;
bottom: 10px;
left: 100px;
right: 100px;
text-align: center;
z-index: 1200;
}
.mfp-wrap .mfp-container .mdf-list-thumb img {
width: 50px;
height: 50px;
margin-right: 5px;
cursor: pointer;
border: 1px solid rgb(16, 31, 20);
display: none;
}
.mfp-wrap .mfp-container .mdf-list-thumb .img-show {
display: inline-block;
}
.mfp-wrap .mfp-container .mdf-list-thumb img.active {
border : 1px solid blue;
}
.mfp-wrap .mfp-container .mdf-list-thumb .thumb-content {
display: inline-block;
background: rgba(31, 4, 4, 1);
padding: 0 20px;
position: relative;
}
.mfp-wrap .mfp-container .mdf-list-thumb .thumb-content i {
position: absolute;
top: 20px;
color: #FFF;
}
.mfp-wrap .mfp-container .mdf-list-thumb .thumb-content i:hover {
box-shadow: 1px 1px 1px 1px;
}
.mfp-wrap .mfp-container .mdf-list-thumb .thumb-content i.gallery-prev {
left: 0;
margin-left: 3px;
}
.mfp-wrap .mfp-container .mdf-list-thumb .thumb-content i.gallery-next {
right: 0;
margin-right: 3px;
}
.mfp-container .mfp-content .mfp-description {
position: absolute;
bottom: 100px;
line-height: 16px;
}
.mfp-content .mfp-figure .mfp-img {
padding: 40px 0 100px 0;
}
.mfp-content .mfp-figure:after {
bottom: 100px;
}
.mgf-md-popup {
width: 100%;
height: 100%;
}
.awe-image img {
max-width: 100%;
}
.awe-equal-column > .container > .row > .awe-blank > .awe-col-content {
padding: 15px;
}
.image-thumb {
position: relative;
overflow: hidden;
}
.node-unpublished {
background-color: inherit;
}
|
aposidelov/copfun1
|
sites/all/modules/custom/md_awecontent/css/objects/gallery.css
|
CSS
|
gpl-2.0
| 5,963
|
#region Header
// Vorspire _,-'/-'/ ProfileRankOrder.cs
// . __,-; ,'( '/
// \. `-.__`-._`:_,-._ _ , . ``
// `:-._,------' ` _,`--` -: `_ , ` ,' :
// `---..__,,--' (C) 2016 ` -'. -'
// # Vita-Nex [http://core.vita-nex.com] #
// {o)xxx|===============- # -===============|xxx(o}
// # The MIT License (MIT) #
#endregion
namespace VitaNex.Modules.AutoPvP
{
public enum PvPProfileRankOrder
{
None,
Points,
Wins,
Kills
}
}
|
Andries1985/Shards-of-Nagash
|
Scripts/VitaNex/Core/Modules/AutoPVP/Objects/Profile/ProfileRankOrder.cs
|
C#
|
gpl-2.0
| 507
|
<?php
/**
* The template for displaying the footer
*
* Contains the closing of the "site-content" div and all content after.
*
* @package WordPress
* @subpackage Twenty_Fifteen
* @since Twenty Fifteen 1.0
*/
?>
<footer class="bmg-l-footer">
<div class="bmg-l-footer__inner">
<div class="bmg-l-footer__nav">
<div class="bmg-l-footer__country">
<ul>
<li>
<a class="bmg-l-footer__flag js-user-location-modal" href="javascript:void(0);">
<img width="18" src="/assets/images/flag/phl-a2a1a5476b.png" alt="Philippines">Philippines
</a>
</li>
<li>
$USD
<a class="bmg-l-footer__country-edit js-user-location-modal" href="javascript:void(0);">EDIT</a>
</li>
</ul>
</div>
<nav class="verticalmenu">
<ul>
<li>
<a href="/aboutbuyma/">About BUYMA</a>
</li>
<li>
<a target="_blank" href="https://buyma-us.zendesk.com/">FAQ</a>
</li>
<li>
<a href="/contact/">Contact us</a>
</li>
</ul>
<ul>
<li><a href="/terms/">Terms of Use</a></li>
<li><a href="/privacy/">Privacy Policy</a></li>
<li><a href="/notice_and_takedown/">Notice and Takedown Policy</a></li>
<li><a href="/tradelaw/">Mark based on specific trade law</a></li>
<li>
<a target="_blank" href="http://www.enigmo.co.jp/en/">enigmo</a>
</li>
</ul>
</nav>
</div>
<p class="footer-tagline">BUYMA - A new online personal shopping experience</p>
<div class="bmg-l-footer__outer-nav">
<nav>
<ul>
<li>
<a target="_blank" href="http://www.buyma.com/">BUYMA.com (JP)</a>
</li>
<li>
<a target="_blank" href="http://buymakorea.com/pages/?">BUYMA Korea</a>
</li>
<li>
<a target="_blank" href="https://stylehaus.jp/">STYLE HAUS</a>
</li>
<li>
<a target="_blank" href="https://www.stulio.jp/">STULIO</a>
</li>
<li>
<a target="_blank" href="http://www.buymabooks.com/">BUYMA Books</a>
</li>
<li>
<a target="_blank" href="http://toptip.jp/">toptip</a>
</li>
</ul>
</nav>
<p>
<small>©2005 Enigmo Inc. All rights reserved.</small>
</p>
</div>
</div>
</footer>
<?php wp_footer(); ?>
</body>
</html>
|
goygoybords/buyma
|
wp-content/themes/twentyfifteen/footer.php
|
PHP
|
gpl-2.0
| 2,372
|
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Kick-Sass - Tables</title>
<meta name="description" content="Some tables">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" href="demos.css">
<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,600,700,400italic,700italic" rel="stylesheet" type="text/css">
</head>
<body>
<h1 class="heading-1">Kick-Sass</h1>
<hr>
<h2 class="heading-2">Tables</h2>
<p>Here"s a paragraph to show spacing around the table. Aenean lacinia bibendum nulla sed consectetur. Maecenas faucibus mollis interdum..</p>
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Table heading</th>
<th>Table heading</th>
<th>Table heading</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
</tr>
<tr>
<th>2</th>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
</tr>
<tr>
<th>3</th>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
</tr>
</tbody>
</table>
<p>Here"s a paragraph to show spacing around the table. Aenean lacinia bibendum nulla sed consectetur. Maecenas faucibus mollis interdum..</p>
<div class="overflowIndicator-wrapper">
<table class="table overflowIndicator-content">
<thead>
<tr>
<th>#</th>
<th>Table heading</th>
<th>Table heading</th>
<th>Table heading</th>
<th>Table heading</th>
<th>Table heading</th>
<th>Table heading</th>
<th>Table heading</th>
<th>Table heading</th>
<th>Table heading</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
</tr>
<tr>
<th>2</th>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
</tr>
<tr>
<th>3</th>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
<td>Table cell</td>
</tr>
</tbody>
</table>
</div><!-- .overflowIndicator-wrapper -->
<p>Here"s a paragraph to show spacing around the table. Aenean lacinia bibendum nulla sed consectetur. Maecenas faucibus mollis interdum.</p>
</body>
</html>
|
MichaelArestad/Kick-Sass
|
demos/tables.html
|
HTML
|
gpl-2.0
| 2,650
|
/******************************************************************************
*
* M4RIE: Linear Algebra over GF(2^e)
*
* Copyright (C) 2011 Martin Albrecht <martinralbrecht@googlemail.com>
*
* Distributed under the terms of the GNU General Public License (GEL)
* version 2 or higher.
*
* 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 for more details.
*
* The full text of the GPL is available at:
*
* http://www.gnu.org/licenses/
******************************************************************************/
#include "permutation.h"
#include "trsm.h"
#include "ple.h"
#include "newton_john.h"
rci_t mzed_ple_naive(mzed_t *A, mzp_t *P, mzp_t *Q) {
rci_t col_pos = 0;
rci_t row_pos = 0;
word tmp = 0;
const gf2e *ff = A->finite_field;
rci_t i,j;
int found = 0;
while (row_pos < A->nrows && col_pos < A->ncols) {
found = 0;
for(j=col_pos; j<A->ncols; j++) {
for(i=row_pos; i<A->nrows; i++) {
if( (tmp = mzed_read_elem(A, i,j)) != 0) {
found = 1;
break;
}
}
if (found)
break;
}
if (found) {
P->values[row_pos] = i;
Q->values[row_pos] = j;
mzed_row_swap(A, row_pos, i);
if(j+1 < A->ncols) {
mzed_rescale_row(A, row_pos, j+1, gf2e_inv(ff, tmp));
for(rci_t l=row_pos+1; l<A->nrows; l++) {
if ((tmp = mzed_read_elem(A,l,j)))
mzed_add_multiple_of_row(A, l, A, row_pos, tmp, j+1);
}
}
row_pos++;
col_pos = j + 1;
} else {
break;
}
}
for (rci_t i = row_pos; i < A->nrows; ++i)
P->values[i] = i;
for (rci_t i = row_pos; i < A->ncols; ++i)
Q->values[i] = i;
for (rci_t i=0; i < row_pos; i++) {
mzed_col_swap_in_rows(A, i, Q->values[i], i, A->nrows);
}
return row_pos;
}
rci_t _mzed_ple(mzed_t *A, mzp_t *P, mzp_t *Q, rci_t cutoff) {
if (cutoff == 0)
cutoff = __M4RIE_PLE_CUTOFF;
if ((A->ncols > m4ri_radix && (gf2e_degree_to_w(A->finite_field) * A->ncols * A->nrows) > cutoff)) {
mzd_slice_t *a = mzed_slice(NULL, A);
rci_t r = _mzd_slice_ple(a, P, Q, cutoff);
mzed_cling(A, a);
mzd_slice_free(a);
return r;
} else {
return mzed_ple_newton_john(A, P, Q);
}
}
rci_t _mzd_slice_ple(mzd_slice_t *A, mzp_t *P, mzp_t *Q, rci_t cutoff) {
assert(A->x[0]->offset == 0);
const rci_t ncols = A->ncols;
const rci_t nrows = A->nrows;
if (cutoff == 0)
cutoff = __M4RIE_PLE_CUTOFF;
if (ncols <= m4ri_radix || (gf2e_degree_to_w(A->finite_field) * A->ncols * A->nrows) <= cutoff) {
mzed_t *Abar = mzed_cling(NULL, A);
rci_t r = mzed_ple_newton_john(Abar, P, Q);
mzed_slice(A, Abar);
mzed_free(Abar);
return r;
}
/* n1
* ------------------------------------------
* | A0 | A1 |
* ------------------------------------------
*/
rci_t n1 = (((ncols - 1) / m4ri_radix + 1) >> 1) * m4ri_radix;
mzd_slice_t *A0 = mzd_slice_init_window(A, 0, 0, nrows, n1);
mzd_slice_t *A1 = mzd_slice_init_window(A, 0, n1, nrows, ncols);
mzp_t *P1 = mzp_init_window(P, 0, nrows);
mzp_t *Q1 = mzp_init_window(Q, 0, A0->ncols);
rci_t r1 = _mzd_slice_ple(A0, P1, Q1, cutoff);
/* r1 n1
* ------------------------------------------
* | A00 | | A01 |
* r1------------------------------------------
* | A10 | | A11 |
* ------------------------------------------
*/
mzd_slice_t *A00 = mzd_slice_init_window(A, 0, 0, r1, r1);
mzd_slice_t *A10 = mzd_slice_init_window(A, r1, 0, nrows, r1);
mzd_slice_t *A01 = mzd_slice_init_window(A, 0, n1, r1, ncols);
mzd_slice_t *A11 = mzd_slice_init_window(A, r1, n1, nrows, ncols);
if (r1) {
/* Computation of the Schur complement */
mzd_slice_apply_p_left(A1, P1);
mzd_slice_trsm_lower_left(A00, A01);
mzd_slice_addmul(A11, A10, A01);
}
mzp_free_window(P1);
mzp_free_window(Q1);
mzp_t *P2 = mzp_init_window(P, r1, nrows);
mzp_t *Q2 = mzp_init_window(Q, n1, ncols);
rci_t r2 = _mzd_slice_ple(A11, P2, Q2, cutoff);
/* n
* -------------------
* | A0b |
* r1-----------------
* | A1b |
* -------------------
*/
/* Update A10 */
mzd_slice_apply_p_left(A10, P2);
/* Update P */
for (rci_t i = 0; i < nrows - r1; ++i)
P2->values[i] += r1;
/* Update the A0b block (permutation + rotation) */
for(rci_t i=0, j=n1; j < ncols; ++i, ++j)
Q2->values[i] += n1;
for(rci_t i=n1, j = r1; i < n1 + r2; ++i, ++j)
Q->values[j] = Q->values[i];
_mzd_slice_compress_l(A, r1, n1, r2);
mzp_free_window(Q2);
mzp_free_window(P2);
mzd_slice_free_window(A0);
mzd_slice_free_window(A1);
mzd_slice_free_window(A00);
mzd_slice_free_window(A01);
mzd_slice_free_window(A10);
mzd_slice_free_window(A11);
return r1 + r2;
}
rci_t _mzd_slice_pluq(mzd_slice_t *A, mzp_t *P, mzp_t *Q, rci_t cutoff) {
rci_t r = _mzd_slice_ple(A, P, Q, cutoff);
if(r && r < A->nrows) {
mzd_slice_t *A0 = mzd_slice_init_window(A, 0, 0, r, A->ncols);
mzd_slice_apply_p_right_trans_tri(A0, Q);
mzd_slice_free_window(A0);
} else {
mzd_slice_apply_p_right_trans_tri(A, Q);
}
return r;
}
|
grudy/m4rie
|
src/ple.c
|
C
|
gpl-2.0
| 5,529
|
<?php
/**
* The template for displaying all pages.
*
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages
* and that other 'pages' on your WordPress site will use a
* different template.
*
* @package Monaco
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<?php
// If comments are open or we have at least one comment, load up the comment template
if ( comments_open() || '0' != get_comments_number() ) :
comments_template();
endif;
?>
<?php endwhile; // end of the loop. ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
|
techborder/wp
|
wp-content/themes/monaco/page.php
|
PHP
|
gpl-2.0
| 849
|
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "common/system.h"
#include "titanic/sound/qmixer.h"
#include "titanic/titanic.h"
namespace Titanic {
QMixer::QMixer(Audio::Mixer *mixer) : _mixer(mixer) {
}
bool QMixer::qsWaveMixInitEx(const QMIXCONFIG &config) {
assert(_channels.empty());
assert(config.iChannels > 0 && config.iChannels < 256);
_channels.resize(config.iChannels);
return true;
}
void QMixer::qsWaveMixActivate(bool fActivate) {
// Not currently implemented in ScummVM
}
int QMixer::qsWaveMixOpenChannel(int iChannel, QMixFlag mode) {
// Not currently implemented in ScummVM
return 0;
}
int QMixer::qsWaveMixEnableChannel(int iChannel, uint flags, bool enabled) {
// Not currently implemented in ScummVM
return 0;
}
void QMixer::qsWaveMixCloseSession() {
_mixer->stopAll();
_channels.clear();
}
void QMixer::qsWaveMixFreeWave(Audio::SoundHandle &handle) {
_mixer->stopHandle(handle);
}
void QMixer::qsWaveMixFlushChannel(int iChannel, uint flags) {
if (flags & QMIX_OPENALL) {
// Ignore channel, and flush all the channels
for (uint idx = 0; idx < _channels.size(); ++idx)
qsWaveMixFlushChannel(idx, 0);
} else {
// Flush the specified channel
Common::List<SoundEntry>::iterator i;
Common::List<SoundEntry> &sounds = _channels[iChannel]._sounds;
for (i = sounds.begin(); i != sounds.end(); ++i)
_mixer->stopHandle((*i)._soundHandle);
sounds.clear();
}
}
void QMixer::qsWaveMixSetPanRate(int iChannel, uint flags, uint rate) {
ChannelEntry &channel = _channels[iChannel];
channel._panRate = rate;
channel._volumeChangeStart = channel._volumeChangeEnd = 0;
}
void QMixer::qsWaveMixSetVolume(int iChannel, uint flags, uint volume) {
ChannelEntry &channel = _channels[iChannel];
// QMixer volumes go from 0-32767, but we need to convert to 0-255 for ScummVM
assert(volume <= 32767);
byte newVolume = (volume >= 32700) ? 255 : volume * 255 / 32767;
channel._volumeStart = channel._volume;
channel._volumeEnd = newVolume;
channel._volumeChangeStart = g_system->getMillis();
channel._volumeChangeEnd = channel._volumeChangeStart + channel._panRate;
debugC(DEBUG_DETAILED, kDebugCore, "qsWaveMixSetPanRate vol=%d to %d, start=%u, end=%u",
channel._volumeStart, channel._volumeEnd, channel._volumeChangeStart, channel._volumeChangeEnd);
}
void QMixer::qsWaveMixSetSourcePosition(int iChannel, uint flags, const QSVECTOR &position) {
ChannelEntry &channel = _channels[iChannel];
// Flag whether distance should reset when a new sound is started
channel._resetDistance = (flags & QMIX_USEONCE) != 0;
// Currently, we only do a basic simulation of spatial positioning by
// getting the distance, and proportionately reducing the volume the
// further away the source is
channel._distance = sqrt(position.x * position.x + position.y * position.y
+ position.z * position.z);
}
void QMixer::qsWaveMixSetPolarPosition(int iChannel, uint flags, const QSPOLAR &position) {
ChannelEntry &channel = _channels[iChannel];
// Flag whether distance should reset when a new sound is started
channel._resetDistance = (flags & QMIX_USEONCE) != 0;
// Currently, we only do a basic simulation of spatial positioning by
// getting the distance, and proportionately reducing the volume the
// further away the source is
channel._distance = position.range;
}
void QMixer::qsWaveMixSetListenerPosition(const QSVECTOR &position, uint flags) {
// Not currently implemented in ScummVM
}
void QMixer::qsWaveMixSetListenerOrientation(const QSVECTOR &direction, const QSVECTOR &up, uint flags) {
// Not currently implemented in ScummVM
}
void QMixer::qsWaveMixSetDistanceMapping(int iChannel, uint flags, const QMIX_DISTANCES &distances) {
// Not currently implemented in ScummVM
}
void QMixer::qsWaveMixSetFrequency(int iChannel, uint flags, uint frequency) {
// Not currently implemented in ScummVM
}
void QMixer::qsWaveMixSetSourceVelocity(int iChannel, uint flags, const QSVECTOR &velocity) {
// Not currently implemented in ScummVM
}
int QMixer::qsWaveMixPlayEx(int iChannel, uint flags, CWaveFile *waveFile, int loops, const QMIXPLAYPARAMS ¶ms) {
if (iChannel == -1) {
// Find a free channel
for (iChannel = 0; iChannel < (int)_channels.size(); ++iChannel) {
if (_channels[iChannel]._sounds.empty())
break;
}
assert(iChannel != (int)_channels.size());
}
// If the new sound replaces current ones, then clear the channel
ChannelEntry &channel = _channels[iChannel];
if (flags & QMIX_CLEARQUEUE) {
if (!channel._sounds.empty() && channel._sounds.front()._started)
_mixer->stopHandle(channel._sounds.front()._soundHandle);
channel._sounds.clear();
}
// Add the sound to the channel
channel._sounds.push_back(SoundEntry(waveFile, params.callback, loops, params.dwUser));
qsWaveMixPump();
return 0;
}
bool QMixer::qsWaveMixIsChannelDone(int iChannel) const {
return _channels[iChannel]._sounds.empty();
}
void QMixer::qsWaveMixPump() {
// Iterate through each of the channels
for (uint iChannel = 0; iChannel < _channels.size(); ++iChannel) {
ChannelEntry &channel = _channels[iChannel];
// If there's a transition in sound volume in progress, handle it
if (channel._volumeChangeEnd) {
byte oldVolume = channel._volume;
uint currentTicks = g_system->getMillis();
if (currentTicks >= channel._volumeChangeEnd) {
// Reached end of transition period
channel._volume = channel._volumeEnd;
channel._volumeChangeStart = channel._volumeChangeEnd = 0;
} else {
// Transition in progress, so figure out new volume
channel._volume = (int)channel._volumeStart +
((int)channel._volumeEnd - (int)channel._volumeStart) *
(int)(currentTicks - channel._volumeChangeStart) / (int)channel._panRate;
}
debugC(DEBUG_DETAILED, kDebugCore, "qsWaveMixPump time=%u vol=%d",
currentTicks, channel._volume);
if (channel._volume != oldVolume && !channel._sounds.empty()
&& channel._sounds.front()._started) {
_mixer->setChannelVolume(channel._sounds.front()._soundHandle,
channel.getRawVolume());
}
}
// If the playing sound on the channel is finished, then call
// the callback registered for it, and remove it from the list
if (!channel._sounds.empty()) {
SoundEntry &sound = channel._sounds.front();
if (sound._started && !_mixer->isSoundHandleActive(sound._soundHandle)) {
// Sound is finished
if (sound._callback)
// Call the callback to signal end
sound._callback(iChannel, sound._waveFile, sound._userData);
// Remove sound record from channel
channel._sounds.erase(channel._sounds.begin());
}
}
// If there's an unstarted sound at the front of a channel's
// sound list, then start it playing
if (!channel._sounds.empty()) {
SoundEntry &sound = channel._sounds.front();
if (!sound._started) {
if (channel._resetDistance)
channel._distance = 0.0;
// Play the wave
sound._soundHandle = sound._waveFile->play(
sound._loops, channel.getRawVolume());
sound._started = true;
}
}
}
}
/*------------------------------------------------------------------------*/
byte QMixer::ChannelEntry::getRawVolume() const {
// Emperically decided adjustment divisor for distances
const double ADJUSTMENT_FACTOR = 5.0;
double r = 1.0 + (_distance / ADJUSTMENT_FACTOR);
double percent = 1.0 / (r * r);
double newVolume = _volume * percent;
return (byte)newVolume;
}
} // End of namespace Titanic
|
yinsimei/scummvm
|
engines/titanic/sound/qmixer.cpp
|
C++
|
gpl-2.0
| 8,371
|
/* $Id$ */
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <pjsip/sip_config.h>
/* pjsip configuration instance, initialized with default values */
pjsip_cfg_t pjsip_sip_cfg_var =
{
/* Global settings */
{
PJSIP_ALLOW_PORT_IN_FROMTO_HDR,
PJSIP_ACCEPT_REPLACE_IN_EARLY_STATE,
0,
0,
PJSIP_DONT_SWITCH_TO_TCP,
PJSIP_DONT_SWITCH_TO_TLS,
PJSIP_FOLLOW_EARLY_MEDIA_FORK,
PJSIP_REQ_HAS_VIA_ALIAS,
PJSIP_RESOLVE_HOSTNAME_TO_GET_INTERFACE,
0,
PJSIP_ENCODE_SHORT_HNAME,
PJSIP_ACCEPT_MULTIPLE_SDP_ANSWERS
},
/* Transaction settings */
{
PJSIP_MAX_TSX_COUNT,
PJSIP_T1_TIMEOUT,
PJSIP_T2_TIMEOUT,
PJSIP_T4_TIMEOUT,
PJSIP_TD_TIMEOUT
},
/* Client registration client */
{
PJSIP_REGISTER_CLIENT_CHECK_CONTACT
},
/* TCP transport settings */
{
PJSIP_TCP_KEEP_ALIVE_INTERVAL
},
/* TLS transport settings */
{
PJSIP_TLS_KEEP_ALIVE_INTERVAL
}
};
#ifdef PJ_DLL
PJ_DEF(pjsip_cfg_t*) pjsip_cfg(void)
{
return &pjsip_sip_cfg_var;
}
#endif
|
ismangil/pjproject
|
pjsip/src/pjsip/sip_config.c
|
C
|
gpl-2.0
| 1,929
|
"""
USAGE:
twitter [action] [options]
ACTIONS:
follow add the specified user to your follow list
friends get latest tweets from your friends (default action)
help print this help text that you are currently reading
leave remove the specified user from your following list
public get latest public tweets
replies get latest replies
set set your twitter status
shell login the twitter shell
OPTIONS:
-e --email <email> your email to login to twitter
-p --password <password> your twitter password
-r --refresh run this command forever, polling every once
in a while (default: every 5 minutes)
-R --refresh-rate <rate> set the refresh rate (in seconds)
-f --format <format> specify the output format for status updates
-c --config <filename> read username and password from given config
file (default ~/.twitter)
-l --length <count> specify number of status updates shown
(default: 20, max: 200)
-t --timestamp show time before status lines
-d --datestamp shoe date before status lines
FORMATS for the --format option
default one line per status
verbose multiple lines per status, more verbose status info
urls nothing but URLs
ansi ansi colour (rainbow mode)
CONFIG FILES
The config file should contain a [twitter] header, and all the desired options
you wish to set, like so:
[twitter]
email: <username>
password: <password>
format: <desired_default_format_for_output>
prompt: <twitter_shell_prompt e.g. '[cyan]twitter[R]> '>
"""
import sys
import time
from getopt import gnu_getopt as getopt, GetoptError
from getpass import getpass
import re
import os.path
from ConfigParser import SafeConfigParser
import datetime
from api import Twitter, TwitterError
import ansi
# Please don't change this, it was provided by the fine folks at Twitter.
# If you change it, it will not work.
AGENT_STR = "twittercommandlinetoolpy"
OPTIONS = {
'email': None,
'password': None,
'action': 'friends',
'refresh': False,
'refresh_rate': 600,
'format': 'default',
'prompt': '[cyan]twitter[R]> ',
'config_filename': os.environ.get('HOME', '') + os.sep + '.twitter',
'length': 20,
'timestamp': False,
'datestamp': False,
'extra_args': []
}
def parse_args(args, options):
long_opts = ['email', 'password', 'help', 'format', 'refresh',
'refresh-rate', 'config', 'length', 'timestamp', 'datestamp']
short_opts = "e:p:f:h?rR:c:l:td"
opts, extra_args = getopt(args, short_opts, long_opts)
for opt, arg in opts:
if opt in ('-e', '--email'):
options['email'] = arg
elif opt in ('-p', '--password'):
options['password'] = arg
elif opt in ('-f', '--format'):
options['format'] = arg
elif opt in ('-r', '--refresh'):
options['refresh'] = True
elif opt in ('-R', '--refresh-rate'):
options['refresh_rate'] = int(arg)
elif opt in ('-l', '--length'):
options["length"] = int(arg)
elif opt in ('-t', '--timestamp'):
options["timestamp"] = True
elif opt in ('-d', '--datestamp'):
options["datestamp"] = True
elif opt in ('-?', '-h', '--help'):
options['action'] = 'help'
elif opt in ('-c', '--config'):
options['config_filename'] = arg
if extra_args and not ('action' in options and options['action'] == 'help'):
options['action'] = extra_args[0]
options['extra_args'] = extra_args[1:]
def get_time_string(status, options):
timestamp = options["timestamp"]
datestamp = options["datestamp"]
t = time.strptime(status['created_at'], "%a %b %d %H:%M:%S +0000 %Y")
i_hate_timezones = time.timezone
if (time.daylight):
i_hate_timezones = time.altzone
dt = datetime.datetime(*t[:-3]) - datetime.timedelta(
seconds=i_hate_timezones)
t = dt.timetuple()
if timestamp and datestamp:
return time.strftime("%Y-%m-%d %H:%M:%S ", t)
elif timestamp:
return time.strftime("%H:%M:%S ", t)
elif datestamp:
return time.strftime("%Y-%m-%d ", t)
return ""
class StatusFormatter(object):
def __call__(self, status):
return (u"%S%s %s" %(
get_time_string(status, options),
status['user']['screen_name'], status['text']))
class AnsiStatusFormatter(object):
def __init__(self):
self._colourMap = ansi.ColourMap()
def __call__(self, status, options):
colour = self._colourMap.colourFor(status['user']['screen_name'])
return (u"%s%s%s%s %s" %(
get_time_string(status, options),
ansi.cmdColour(colour), status['user']['screen_name'],
ansi.cmdReset(), status['text']))
class VerboseStatusFormatter(object):
def __call__(self, status, options):
return (u"-- %s (%s) on %s\n%s\n" %(
status['user']['screen_name'],
status['user']['location'],
status['created_at'],
status['text']))
class URLStatusFormatter(object):
urlmatch = re.compile(r'https?://\S+')
def __call__(self, status, options):
urls = self.urlmatch.findall(status['text'])
return u'\n'.join(urls) if urls else ""
class AdminFormatter(object):
def __call__(self, action, user):
user_str = u"%s (%s)" %(user['screen_name'], user['name'])
if action == "follow":
return u"You are now following %s.\n" %(user_str)
else:
return u"You are no longer following %s.\n" %(user_str)
class VerboseAdminFormatter(object):
def __call__(self, action, user):
return(u"-- %s: %s (%s): %s" % (
"Following" if action == "follow" else "Leaving",
user['screen_name'],
user['name'],
user['url']))
status_formatters = {
'default': StatusFormatter,
'verbose': VerboseStatusFormatter,
'urls': URLStatusFormatter,
'ansi': AnsiStatusFormatter
}
admin_formatters = {
'default': AdminFormatter,
'verbose': VerboseAdminFormatter,
'urls': AdminFormatter,
'ansi': AdminFormatter
}
def get_status_formatter(options):
sf = status_formatters.get(options['format'])
if (not sf):
raise TwitterError(
"Unknown formatter '%s'" %(options['format']))
return sf()
def get_admin_formatter(options):
sf = admin_formatters.get(options['format'])
if (not sf):
raise TwitterError(
"Unknown formatter '%s'" %(options['format']))
return sf()
class Action(object):
def ask(self, subject='perform this action', careful=False):
'''
Requests fromt he user using `raw_input` if `subject` should be
performed. When `careful`, the default answer is NO, otherwise YES.
Returns the user answer in the form `True` or `False`.
'''
sample = '(y/N)'
if not careful:
sample = '(Y/n)'
prompt = 'You really want to %s %s? ' %(subject, sample)
try:
answer = raw_input(prompt).lower()
if careful:
return answer in ('yes', 'y')
else:
return answer not in ('no', 'n')
except EOFError:
print >>sys.stderr # Put Newline since Enter was never pressed
# TODO:
# Figure out why on OS X the raw_input keeps raising
# EOFError and is never able to reset and get more input
# Hint: Look at how IPython implements their console
default = True
if careful:
default = False
return default
def __call__(self, twitter, options):
action = actions.get(options['action'], NoSuchAction)()
try:
doAction = lambda : action(twitter, options)
if (options['refresh'] and isinstance(action, StatusAction)):
while True:
doAction()
time.sleep(options['refresh_rate'])
else:
doAction()
except KeyboardInterrupt:
print >>sys.stderr, '\n[Keyboard Interrupt]'
pass
class NoSuchActionError(Exception):
pass
class NoSuchAction(Action):
def __call__(self, twitter, options):
raise NoSuchActionError("No such action: %s" %(options['action']))
def printNicely(string):
if sys.stdout.encoding:
print string.encode(sys.stdout.encoding, 'replace')
else:
print string.encode('utf-8')
class StatusAction(Action):
def __call__(self, twitter, options):
statuses = self.getStatuses(twitter, options)
sf = get_status_formatter(options)
for status in statuses:
statusStr = sf(status, options)
if statusStr.strip():
printNicely(statusStr)
class AdminAction(Action):
def __call__(self, twitter, options):
if not (options['extra_args'] and options['extra_args'][0]):
raise TwitterError("You need to specify a user (screen name)")
af = get_admin_formatter(options)
try:
user = self.getUser(twitter, options['extra_args'][0])
except TwitterError, e:
print "There was a problem following or leaving the specified user."
print "You may be trying to follow a user you are already following;"
print "Leaving a user you are not currently following;"
print "Or the user may not exist."
print "Sorry."
print
print e
else:
printNicely(af(options['action'], user))
class FriendsAction(StatusAction):
def getStatuses(self, twitter, options):
return reversed(twitter.statuses.friends_timeline(count=options["length"]))
class PublicAction(StatusAction):
def getStatuses(self, twitter, options):
return reversed(twitter.statuses.public_timeline(count=options["length"]))
class RepliesAction(StatusAction):
def getStatuses(self, twitter, options):
return reversed(twitter.statuses.replies(count=options["length"]))
class FollowAction(AdminAction):
def getUser(self, twitter, user):
return twitter.friendships.create(id=user)
class LeaveAction(AdminAction):
def getUser(self, twitter, user):
return twitter.friendships.destroy(id=user)
class SetStatusAction(Action):
def __call__(self, twitter, options):
statusTxt = (u" ".join(options['extra_args'])
if options['extra_args']
else unicode(raw_input("message: ")))
status = (statusTxt.encode('utf8', 'replace'))
twitter.statuses.update(status=status)
class TwitterShell(Action):
def render_prompt(self, prompt):
'''Parses the `prompt` string and returns the rendered version'''
prompt = prompt.strip("'").replace("\\'","'")
for colour in ansi.COLOURS_NAMED:
if '[%s]' %(colour) in prompt:
prompt = prompt.replace(
'[%s]' %(colour), ansi.cmdColourNamed(colour))
prompt = prompt.replace('[R]', ansi.cmdReset())
return prompt
def __call__(self, twitter, options):
prompt = self.render_prompt(options.get('prompt', 'twitter> '))
while True:
options['action'] = ""
try:
args = raw_input(prompt).split()
parse_args(args, options)
if not options['action']:
continue
elif options['action'] == 'exit':
raise SystemExit(0)
elif options['action'] == 'shell':
print >>sys.stderr, 'Sorry Xzibit does not work here!'
continue
elif options['action'] == 'help':
print >>sys.stderr, '''\ntwitter> `action`\n
The Shell Accepts all the command line actions along with:
exit Leave the twitter shell (^D may also be used)
Full CMD Line help is appended below for your convinience.'''
Action()(twitter, options)
options['action'] = ''
except NoSuchActionError, e:
print >>sys.stderr, e
except KeyboardInterrupt:
print >>sys.stderr, '\n[Keyboard Interrupt]'
except EOFError:
print >>sys.stderr
leaving = self.ask(subject='Leave')
if not leaving:
print >>sys.stderr, 'Excellent!'
else:
raise SystemExit(0)
class HelpAction(Action):
def __call__(self, twitter, options):
print __doc__
actions = {
'follow' : FollowAction,
'friends' : FriendsAction,
'help' : HelpAction,
'leave' : LeaveAction,
'public' : PublicAction,
'replies' : RepliesAction,
'set' : SetStatusAction,
'shell' : TwitterShell,
}
def loadConfig(filename):
options = dict(OPTIONS)
if os.path.exists(filename):
cp = SafeConfigParser()
cp.read([filename])
for option in ('email', 'password', 'format', 'prompt'):
if cp.has_option('twitter', option):
options[option] = cp.get('twitter', option)
return options
def main(args=sys.argv[1:]):
arg_options = {}
try:
parse_args(args, arg_options)
except GetoptError, e:
print >> sys.stderr, "I can't do that, %s." %(e)
print >> sys.stderr
raise SystemExit(1)
config_options = loadConfig(
arg_options.get('config_filename') or OPTIONS.get('config_filename'))
# Apply the various options in order, the most important applied last.
# Defaults first, then what's read from config file, then command-line
# arguments.
options = dict(OPTIONS)
for d in config_options, arg_options:
for k,v in d.items():
if v: options[k] = v
if options['refresh'] and options['action'] not in (
'friends', 'public', 'replies'):
print >> sys.stderr, "You can only refresh the friends, public, or replies actions."
print >> sys.stderr, "Use 'twitter -h' for help."
raise SystemExit(1)
if options['email'] and not options['password']:
options['password'] = getpass("Twitter password: ")
twitter = Twitter(options['email'], options['password'], agent=AGENT_STR)
try:
Action()(twitter, options)
except NoSuchActionError, e:
print >>sys.stderr, e
raise SystemExit(1)
except TwitterError, e:
print >> sys.stderr, e.args[0]
print >> sys.stderr, "Use 'twitter -h' for help."
raise SystemExit(1)
|
avsm/lifedb-plugins
|
Twitter/twitter/cmdline.py
|
Python
|
gpl-2.0
| 15,027
|
\documentclass[german,a4paper,twoside]{scrreprt}
%\usepackage[ansinew]{inputenc}
\usepackage[utf8]{inputenc}
\usepackage[german]{babel}
\usepackage{makeidx}
\usepackage{graphicx} % Anleitung hierzu in c:\Program Files\MiKTeX 2.7\doc\latex\graphics\grfguide.pdf
\usepackage{wrapfig}
%\usepackage[T1]{fontenc}
\usepackage{fancyhdr}
\usepackage[colorlinks]{hyperref} % Bietet hyperlinks und Zugriffe auf Dateien in Farbe
\newcommand{\fspec}[1]{\protect\nolinkurl{#1}}
\makeindex
\parindent=0pt
\oddsidemargin=0.75\oddsidemargin
\evensidemargin=0.75\evensidemargin
%################# Ein paar Schreibvereinachungen ######################
\def\i{\itemsep=0.15\itemsep}
\def\c{\centering}
\def\bc{\begin{center}}
\def\ec{\end{center}}
\def\xc{\textsc{XCSoar~}}
\def\qo#1{\textsf{"#1"}}
\def\achtung{\marginpar{\includegraphics[height=3.0em]{Bilder/Achtung-Sign.jpg}}}
\def\merkes{\marginpar{\includegraphics[height=3.0em]{Bilder/merkesdir.jpg}}}
\def\stop{\marginpar{\begin{center}\includegraphics[height=2.50em]{Bilder/Stop.png}\\ {\footnotesize \textbf{Stimmt das?}}\end{center}}}
\def\far{~{\includegraphics[height=1.0em]{Bilder/farrowr.jpg}}~}
\def\fal{~{\includegraphics[height=1.0em]{Bilder/farrowl.jpg}}~}
\def\blitz{ \includegraphics[width=1em]{Bilder/blitz1.png}}
\def\bblitz{\marginpar{\includegraphics[height=2.0em]{Bilder/blitz1.png}}}
\def\bbblitz{\includegraphics[height=4.0em]{Bilder/blitz1.png}}
\def\smallblitz{ \includegraphics[width=0.66em]{Bilder/blitz1.png}}
\rightmargin=0.55\rightmargin
\leftmargin=0.55\leftmargin
%----------------------------------------------------------------------------------------------
%----------------------------------------------------------------------------------------------
\begin{document}
\input{buttons.sty} %Lädt buttons, Menüs etc. von XCSoar - leicht variiert von OH.
\shorthandoff{"} %Anführungszeichen erscheinen wie auf Tastatur und nicht als Tastatursteuerzeichen.
\vspace*{2cm}
\begin{center}
\includegraphics[angle=0,width=0.5\textwidth,keepaspectratio='true']{graphics/logo.pdf}
\vskip 0.5cm
\includegraphics[angle=0,width=0.66\textwidth,keepaspectratio='true']{graphics/title.pdf}
\end{center}
\vspace*{2cm}
\begin{center}
{\Large\textbf{\textsf{Flash\raisebox{-\baselineskip}[\ht\strutbox]{\bbblitz}Manual made by Hotte (OH)}}}\\
\end{center}
% \reflectbox{Spiegelverkehrt ?}? Ja, geht auch ...
%\input{einleitung.tex} % Fertig bis auf die letzten 4 \sections
%\newpage
%\input{bedienerOF.tex} % Noch gar nicht fertig ...
%\newpage
%\input{navigation.tex} %fast fertig für v6 machen
%\newpage
%\input{XC-Tasks.tex} % Im Bau für v6 machen ...
%\newpage
%\input{Endanflugrechner.tex} %Im Bau
%\newpage
%\input{Athmosphaere-und-Instrumente.tex} % Im Bau
%\newpage
%\input{Airspace-und-Traffic.tex} % Im Bau
%\newpage
%\input{Avionik-und-Airframe.tex} % Im Bau
%\newpage
%\input{Schnellstart.tex} % Fertig. % für v6 abändern-schon weit !
%\newpage
%\input{InfoBoxBeschreibung.tex} % Im Bau Sehr Wichtig
%\newpage
%\input{Konfiguration.tex} % Im Bau sehr wichtig
%\newpage
\input{Blitzeinstieg}
%\input{DataFiles.tex} % Im Bau Sehr wichtig
%\newpage
%\input{Entwicklung-und-Entstehung.tex} % Im Bau - unwichtig
%\begin{small}
%\input{GnuGeneralPublicLicense.tex} % Fertig
%\end{small}
\tableofcontents
\printindex
\end{document}
|
onkelhotte/XCSoar
|
doc/manual/de/Blitz/XCSoar-Blitzeinstieg.tex
|
TeX
|
gpl-2.0
| 3,742
|
/* arch/arm/mach-rk30/board-rk30-sdk.c
*
* Copyright (C) 2012 ROCKCHIP, Inc.
*
* 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/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/i2c.h>
#include <linux/skbuff.h>
#include <linux/spi/spi.h>
#include <linux/mmc/host.h>
#include <linux/ion.h>
#include <linux/cpufreq.h>
#include <linux/clk.h>
#include <mach/dvfs.h>
#include <asm/setup.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/flash.h>
#include <asm/hardware/gic.h>
#include <mach/board.h>
#include <mach/hardware.h>
#include <mach/io.h>
#include <mach/gpio.h>
#include <mach/iomux.h>
#include <linux/fb.h>
#include <linux/power/smb347-charger.h>
#include <linux/regulator/machine.h>
#include <linux/rfkill-rk.h>
#include <linux/sensor-dev.h>
#ifdef CONFIG_RK30_PWM_REGULATOR
#include <linux/regulator/rk29-pwm-regulator.h>
#endif
#if defined(CONFIG_HDMI_RK30)
#include "../../../drivers/video/rockchip/hdmi/rk_hdmi.h"
#endif
#if defined(CONFIG_SPIM_RK29)
#include "../../../drivers/spi/rk29_spim.h"
#endif
#if defined(CONFIG_MU509)
#include <linux/mu509.h>
#endif
#if defined(CONFIG_MW100)
#include <linux/mw100.h>
#endif
#if defined(CONFIG_MT6229)
#include <linux/mt6229.h>
#endif
#if defined(CONFIG_SEW868)
#include <linux/sew868.h>
#endif
#if defined(CONFIG_ANDROID_TIMED_GPIO)
#include "../../../drivers/staging/android/timed_gpio.h"
#endif
#ifdef CONFIG_THREE_FB_BUFFER
#define RK30_FB0_MEM_SIZE 12*SZ_1M
#else
#define RK30_FB0_MEM_SIZE 8*SZ_1M
#endif
#ifdef CONFIG_VIDEO_RK29
/*---------------- Camera Sensor Macro Define Begin ------------------------*/
/*---------------- Camera Sensor Configuration Macro Begin ------------------------*/
#define CONFIG_SENSOR_0 RK29_CAM_SENSOR_GT2005 /* back camera sensor */
#define CONFIG_SENSOR_IIC_ADDR_0 0x78
#define CONFIG_SENSOR_IIC_ADAPTER_ID_0 3
#define CONFIG_SENSOR_CIF_INDEX_0 0
#define CONFIG_SENSOR_ORIENTATION_0 90
#define CONFIG_SENSOR_POWER_PIN_0 INVALID_GPIO
#define CONFIG_SENSOR_RESET_PIN_0 INVALID_GPIO
#define CONFIG_SENSOR_POWERDN_PIN_0 RK30_PIN4_PC3
#define CONFIG_SENSOR_FALSH_PIN_0 INVALID_GPIO
#define CONFIG_SENSOR_POWERACTIVE_LEVEL_0 RK29_CAM_POWERACTIVE_L
#define CONFIG_SENSOR_RESETACTIVE_LEVEL_0 RK29_CAM_RESETACTIVE_L
#define CONFIG_SENSOR_POWERDNACTIVE_LEVEL_0 RK29_CAM_POWERDNACTIVE_L
#define CONFIG_SENSOR_FLASHACTIVE_LEVEL_0 RK29_CAM_FLASHACTIVE_L
#define CONFIG_SENSOR_QCIF_FPS_FIXED_0 15000
#define CONFIG_SENSOR_240X160_FPS_FIXED_0 15000
#define CONFIG_SENSOR_QVGA_FPS_FIXED_0 15000
#define CONFIG_SENSOR_CIF_FPS_FIXED_0 15000
#define CONFIG_SENSOR_VGA_FPS_FIXED_0 15000
#define CONFIG_SENSOR_480P_FPS_FIXED_0 15000
#define CONFIG_SENSOR_SVGA_FPS_FIXED_0 15000
#define CONFIG_SENSOR_720P_FPS_FIXED_0 30000
#define CONFIG_SENSOR_01 RK29_CAM_SENSOR_SP2518 /* back camera sensor 1 */
#define CONFIG_SENSOR_IIC_ADDR_01 0x60
#define CONFIG_SENSOR_CIF_INDEX_01 0
#define CONFIG_SENSOR_IIC_ADAPTER_ID_01 3
#define CONFIG_SENSOR_ORIENTATION_01 90
#define CONFIG_SENSOR_POWER_PIN_01 INVALID_GPIO
#define CONFIG_SENSOR_RESET_PIN_01 INVALID_GPIO
#define CONFIG_SENSOR_POWERDN_PIN_01 RK30_PIN4_PC3
#define CONFIG_SENSOR_FALSH_PIN_01 INVALID_GPIO
#define CONFIG_SENSOR_POWERACTIVE_LEVEL_01 RK29_CAM_POWERACTIVE_L
#define CONFIG_SENSOR_RESETACTIVE_LEVEL_01 RK29_CAM_RESETACTIVE_L
#define CONFIG_SENSOR_POWERDNACTIVE_LEVEL_01 RK29_CAM_POWERDNACTIVE_H
#define CONFIG_SENSOR_FLASHACTIVE_LEVEL_01 RK29_CAM_FLASHACTIVE_L
#define CONFIG_SENSOR_QCIF_FPS_FIXED_01 15000
#define CONFIG_SENSOR_240X160_FPS_FIXED_01 15000
#define CONFIG_SENSOR_QVGA_FPS_FIXED_01 15000
#define CONFIG_SENSOR_CIF_FPS_FIXED_01 15000
#define CONFIG_SENSOR_VGA_FPS_FIXED_01 15000
#define CONFIG_SENSOR_480P_FPS_FIXED_01 15000
#define CONFIG_SENSOR_SVGA_FPS_FIXED_01 15000
#define CONFIG_SENSOR_720P_FPS_FIXED_01 30000
#define CONFIG_SENSOR_02 RK29_CAM_SENSOR_GC2035 /* back camera sensor 2 */
#define CONFIG_SENSOR_IIC_ADDR_02 0x78
#define CONFIG_SENSOR_CIF_INDEX_02 0
#define CONFIG_SENSOR_IIC_ADAPTER_ID_02 3
#define CONFIG_SENSOR_ORIENTATION_02 90
#define CONFIG_SENSOR_POWER_PIN_02 INVALID_GPIO
#define CONFIG_SENSOR_RESET_PIN_02 INVALID_GPIO
#define CONFIG_SENSOR_POWERDN_PIN_02 RK30_PIN4_PC3
#define CONFIG_SENSOR_FALSH_PIN_02 INVALID_GPIO
#define CONFIG_SENSOR_POWERACTIVE_LEVEL_02 RK29_CAM_POWERACTIVE_L
#define CONFIG_SENSOR_RESETACTIVE_LEVEL_02 RK29_CAM_RESETACTIVE_L
#define CONFIG_SENSOR_POWERDNACTIVE_LEVEL_02 RK29_CAM_POWERDNACTIVE_H
#define CONFIG_SENSOR_FLASHACTIVE_LEVEL_02 RK29_CAM_FLASHACTIVE_L
#define CONFIG_SENSOR_QCIF_FPS_FIXED_02 15000
#define CONFIG_SENSOR_240X160_FPS_FIXED_02 15000
#define CONFIG_SENSOR_QVGA_FPS_FIXED_02 15000
#define CONFIG_SENSOR_CIF_FPS_FIXED_02 15000
#define CONFIG_SENSOR_VGA_FPS_FIXED_02 15000
#define CONFIG_SENSOR_480P_FPS_FIXED_02 15000
#define CONFIG_SENSOR_SVGA_FPS_FIXED_02 15000
#define CONFIG_SENSOR_720P_FPS_FIXED_02 30000
#define CONFIG_SENSOR_03 RK29_CAM_SENSOR_HI253 /* back camera sensor 3 */
#define CONFIG_SENSOR_IIC_ADDR_03 0x40
#define CONFIG_SENSOR_CIF_INDEX_03 0
#define CONFIG_SENSOR_IIC_ADAPTER_ID_03 3
#define CONFIG_SENSOR_ORIENTATION_03 90
#define CONFIG_SENSOR_POWER_PIN_03 INVALID_GPIO
#define CONFIG_SENSOR_RESET_PIN_03 INVALID_GPIO
#define CONFIG_SENSOR_POWERDN_PIN_03 RK30_PIN4_PC3
#define CONFIG_SENSOR_FALSH_PIN_03 INVALID_GPIO
#define CONFIG_SENSOR_POWERACTIVE_LEVEL_03 RK29_CAM_POWERACTIVE_L
#define CONFIG_SENSOR_RESETACTIVE_LEVEL_03 RK29_CAM_RESETACTIVE_L
#define CONFIG_SENSOR_POWERDNACTIVE_LEVEL_03 RK29_CAM_POWERDNACTIVE_H
#define CONFIG_SENSOR_FLASHACTIVE_LEVEL_03 RK29_CAM_FLASHACTIVE_L
#define CONFIG_SENSOR_QCIF_FPS_FIXED_03 15000
#define CONFIG_SENSOR_240X160_FPS_FIXED_03 15000
#define CONFIG_SENSOR_QVGA_FPS_FIXED_03 15000
#define CONFIG_SENSOR_CIF_FPS_FIXED_03 15000
#define CONFIG_SENSOR_VGA_FPS_FIXED_03 15000
#define CONFIG_SENSOR_480P_FPS_FIXED_03 15000
#define CONFIG_SENSOR_SVGA_FPS_FIXED_03 15000
#define CONFIG_SENSOR_720P_FPS_FIXED_03 30000
#define CONFIG_SENSOR_04 RK29_CAM_SENSOR_GC2015 /* back camera sensor 4 */
#define CONFIG_SENSOR_IIC_ADDR_04 0x60
#define CONFIG_SENSOR_CIF_INDEX_04 0
#define CONFIG_SENSOR_IIC_ADAPTER_ID_04 3
#define CONFIG_SENSOR_ORIENTATION_04 90
#define CONFIG_SENSOR_POWER_PIN_04 INVALID_GPIO
#define CONFIG_SENSOR_RESET_PIN_04 INVALID_GPIO
#define CONFIG_SENSOR_POWERDN_PIN_04 RK30_PIN4_PC3
#define CONFIG_SENSOR_FALSH_PIN_04 INVALID_GPIO
#define CONFIG_SENSOR_POWERACTIVE_LEVEL_04 RK29_CAM_POWERACTIVE_L
#define CONFIG_SENSOR_RESETACTIVE_LEVEL_04 RK29_CAM_RESETACTIVE_L
#define CONFIG_SENSOR_POWERDNACTIVE_LEVEL_04 RK29_CAM_POWERDNACTIVE_H
#define CONFIG_SENSOR_FLASHACTIVE_LEVEL_04 RK29_CAM_FLASHACTIVE_L
#define CONFIG_SENSOR_QCIF_FPS_FIXED_04 15000
#define CONFIG_SENSOR_240X160_FPS_FIXED_04 15000
#define CONFIG_SENSOR_QVGA_FPS_FIXED_04 15000
#define CONFIG_SENSOR_CIF_FPS_FIXED_04 15000
#define CONFIG_SENSOR_VGA_FPS_FIXED_04 15000
#define CONFIG_SENSOR_480P_FPS_FIXED_04 15000
#define CONFIG_SENSOR_SVGA_FPS_FIXED_04 15000
#define CONFIG_SENSOR_720P_FPS_FIXED_04 30000
#define CONFIG_SENSOR_05 RK29_CAM_SENSOR_OV5640 /* back camera sensor 5 */
#define CONFIG_SENSOR_IIC_ADDR_05 0x78
#define CONFIG_SENSOR_CIF_INDEX_05 0
#define CONFIG_SENSOR_IIC_ADAPTER_ID_05 3
#define CONFIG_SENSOR_ORIENTATION_05 90
#define CONFIG_SENSOR_POWER_PIN_05 INVALID_GPIO
#define CONFIG_SENSOR_RESET_PIN_05 INVALID_GPIO
#define CONFIG_SENSOR_POWERDN_PIN_05 RK30_PIN4_PC3
#define CONFIG_SENSOR_FALSH_PIN_05 INVALID_GPIO
#define CONFIG_SENSOR_POWERACTIVE_LEVEL_05 RK29_CAM_POWERACTIVE_L
#define CONFIG_SENSOR_RESETACTIVE_LEVEL_05 RK29_CAM_RESETACTIVE_L
#define CONFIG_SENSOR_POWERDNACTIVE_LEVEL_05 RK29_CAM_POWERDNACTIVE_H
#define CONFIG_SENSOR_FLASHACTIVE_LEVEL_05 RK29_CAM_FLASHACTIVE_L
#define CONFIG_SENSOR_QCIF_FPS_FIXED_05 15000
#define CONFIG_SENSOR_240X160_FPS_FIXED_05 15000
#define CONFIG_SENSOR_QVGA_FPS_FIXED_05 15000
#define CONFIG_SENSOR_CIF_FPS_FIXED_05 15000
#define CONFIG_SENSOR_VGA_FPS_FIXED_05 15000
#define CONFIG_SENSOR_480P_FPS_FIXED_05 15000
#define CONFIG_SENSOR_SVGA_FPS_FIXED_05 15000
#define CONFIG_SENSOR_720P_FPS_FIXED_05 30000
#define CONFIG_SENSOR_06 RK29_CAM_SENSOR_OV5640 /* back camera sensor 6 */
#define CONFIG_SENSOR_IIC_ADDR_06 0x00
#define CONFIG_SENSOR_CIF_INDEX_06 0
#define CONFIG_SENSOR_IIC_ADAPTER_ID_06 3
#define CONFIG_SENSOR_ORIENTATION_06 90
#define CONFIG_SENSOR_POWER_PIN_06 INVALID_GPIO
#define CONFIG_SENSOR_RESET_PIN_06 INVALID_GPIO
#define CONFIG_SENSOR_POWERDN_PIN_06 RK30_PIN4_PC3
#define CONFIG_SENSOR_FALSH_PIN_06 INVALID_GPIO
#define CONFIG_SENSOR_POWERACTIVE_LEVEL_06 RK29_CAM_POWERACTIVE_L
#define CONFIG_SENSOR_RESETACTIVE_LEVEL_06 RK29_CAM_RESETACTIVE_L
#define CONFIG_SENSOR_POWERDNACTIVE_LEVEL_06 RK29_CAM_POWERDNACTIVE_H
#define CONFIG_SENSOR_FLASHACTIVE_LEVEL_06 RK29_CAM_FLASHACTIVE_L
#define CONFIG_SENSOR_QCIF_FPS_FIXED_06 15000
#define CONFIG_SENSOR_240X160_FPS_FIXED_06 15000
#define CONFIG_SENSOR_QVGA_FPS_FIXED_06 15000
#define CONFIG_SENSOR_CIF_FPS_FIXED_06 15000
#define CONFIG_SENSOR_VGA_FPS_FIXED_06 15000
#define CONFIG_SENSOR_480P_FPS_FIXED_06 15000
#define CONFIG_SENSOR_SVGA_FPS_FIXED_06 15000
#define CONFIG_SENSOR_720P_FPS_FIXED_06 30000
#define CONFIG_SENSOR_07 RK29_CAM_SENSOR_OV5640 /* back camera sensor 7 */
#define CONFIG_SENSOR_IIC_ADDR_07 0x00
#define CONFIG_SENSOR_CIF_INDEX_07 0
#define CONFIG_SENSOR_IIC_ADAPTER_ID_07 3
#define CONFIG_SENSOR_ORIENTATION_07 90
#define CONFIG_SENSOR_POWER_PIN_07 INVALID_GPIO
#define CONFIG_SENSOR_RESET_PIN_07 INVALID_GPIO
#define CONFIG_SENSOR_POWERDN_PIN_07 RK30_PIN4_PC3
#define CONFIG_SENSOR_FALSH_PIN_07 INVALID_GPIO
#define CONFIG_SENSOR_POWERACTIVE_LEVEL_07 RK29_CAM_POWERACTIVE_L
#define CONFIG_SENSOR_RESETACTIVE_LEVEL_07 RK29_CAM_RESETACTIVE_L
#define CONFIG_SENSOR_POWERDNACTIVE_LEVEL_07 RK29_CAM_POWERDNACTIVE_H
#define CONFIG_SENSOR_FLASHACTIVE_LEVEL_07 RK29_CAM_FLASHACTIVE_L
#define CONFIG_SENSOR_QCIF_FPS_FIXED_07 15000
#define CONFIG_SENSOR_240X160_FPS_FIXED_07 15000
#define CONFIG_SENSOR_QVGA_FPS_FIXED_07 15000
#define CONFIG_SENSOR_CIF_FPS_FIXED_07 15000
#define CONFIG_SENSOR_VGA_FPS_FIXED_07 15000
#define CONFIG_SENSOR_480P_FPS_FIXED_07 15000
#define CONFIG_SENSOR_SVGA_FPS_FIXED_07 15000
#define CONFIG_SENSOR_720P_FPS_FIXED_07 30000
#define CONFIG_SENSOR_08 RK29_CAM_SENSOR_OV5640 /* back camera sensor 8 */
#define CONFIG_SENSOR_IIC_ADDR_08 0x00
#define CONFIG_SENSOR_CIF_INDEX_08 0
#define CONFIG_SENSOR_IIC_ADAPTER_ID_08 3
#define CONFIG_SENSOR_ORIENTATION_08 90
#define CONFIG_SENSOR_POWER_PIN_08 INVALID_GPIO
#define CONFIG_SENSOR_RESET_PIN_08 INVALID_GPIO
#define CONFIG_SENSOR_POWERDN_PIN_08 RK30_PIN4_PC3
#define CONFIG_SENSOR_FALSH_PIN_08 INVALID_GPIO
#define CONFIG_SENSOR_POWERACTIVE_LEVEL_08 RK29_CAM_POWERACTIVE_L
#define CONFIG_SENSOR_RESETACTIVE_LEVEL_08 RK29_CAM_RESETACTIVE_L
#define CONFIG_SENSOR_POWERDNACTIVE_LEVEL_08 RK29_CAM_POWERDNACTIVE_H
#define CONFIG_SENSOR_FLASHACTIVE_LEVEL_08 RK29_CAM_FLASHACTIVE_L
#define CONFIG_SENSOR_QCIF_FPS_FIXED_08 15000
#define CONFIG_SENSOR_240X160_FPS_FIXED_08 15000
#define CONFIG_SENSOR_QVGA_FPS_FIXED_08 15000
#define CONFIG_SENSOR_CIF_FPS_FIXED_08 15000
#define CONFIG_SENSOR_VGA_FPS_FIXED_08 15000
#define CONFIG_SENSOR_480P_FPS_FIXED_08 15000
#define CONFIG_SENSOR_SVGA_FPS_FIXED_08 15000
#define CONFIG_SENSOR_720P_FPS_FIXED_08 30000
#define CONFIG_SENSOR_09 RK29_CAM_SENSOR_OV5640 /* back camera sensor 9 */
#define CONFIG_SENSOR_IIC_ADDR_09 0x00
#define CONFIG_SENSOR_CIF_INDEX_09 0
#define CONFIG_SENSOR_IIC_ADAPTER_ID_09 3
#define CONFIG_SENSOR_ORIENTATION_09 90
#define CONFIG_SENSOR_POWER_PIN_09 INVALID_GPIO
#define CONFIG_SENSOR_RESET_PIN_09 INVALID_GPIO
#define CONFIG_SENSOR_POWERDN_PIN_09 RK30_PIN4_PC3
#define CONFIG_SENSOR_FALSH_PIN_09 INVALID_GPIO
#define CONFIG_SENSOR_POWERACTIVE_LEVEL_09 RK29_CAM_POWERACTIVE_L
#define CONFIG_SENSOR_RESETACTIVE_LEVEL_09 RK29_CAM_RESETACTIVE_L
#define CONFIG_SENSOR_POWERDNACTIVE_LEVEL_09 RK29_CAM_POWERDNACTIVE_H
#define CONFIG_SENSOR_FLASHACTIVE_LEVEL_09 RK29_CAM_FLASHACTIVE_L
#define CONFIG_SENSOR_QCIF_FPS_FIXED_09 15000
#define CONFIG_SENSOR_240X160_FPS_FIXED_09 15000
#define CONFIG_SENSOR_QVGA_FPS_FIXED_09 15000
#define CONFIG_SENSOR_CIF_FPS_FIXED_09 15000
#define CONFIG_SENSOR_VGA_FPS_FIXED_09 15000
#define CONFIG_SENSOR_480P_FPS_FIXED_09 15000
#define CONFIG_SENSOR_SVGA_FPS_FIXED_09 15000
#define CONFIG_SENSOR_720P_FPS_FIXED_09 30000
#define CONFIG_SENSOR_1 RK29_CAM_SENSOR_GC0308 /* front camera sensor 0 */
#define CONFIG_SENSOR_IIC_ADDR_1 0x42
#define CONFIG_SENSOR_IIC_ADAPTER_ID_1 3
#define CONFIG_SENSOR_CIF_INDEX_1 0
#define CONFIG_SENSOR_ORIENTATION_1 270
#define CONFIG_SENSOR_POWER_PIN_1 INVALID_GPIO
#define CONFIG_SENSOR_RESET_PIN_1 INVALID_GPIO
#define CONFIG_SENSOR_POWERDN_PIN_1 RK30_PIN1_PB7
#define CONFIG_SENSOR_FALSH_PIN_1 INVALID_GPIO
#define CONFIG_SENSOR_POWERACTIVE_LEVEL_1 RK29_CAM_POWERACTIVE_L
#define CONFIG_SENSOR_RESETACTIVE_LEVEL_1 RK29_CAM_RESETACTIVE_L
#define CONFIG_SENSOR_POWERDNACTIVE_LEVEL_1 RK29_CAM_POWERDNACTIVE_H
#define CONFIG_SENSOR_FLASHACTIVE_LEVEL_1 RK29_CAM_FLASHACTIVE_L
#define CONFIG_SENSOR_QCIF_FPS_FIXED_1 15000
#define CONFIG_SENSOR_240X160_FPS_FIXED_1 15000
#define CONFIG_SENSOR_QVGA_FPS_FIXED_1 15000
#define CONFIG_SENSOR_CIF_FPS_FIXED_1 15000
#define CONFIG_SENSOR_VGA_FPS_FIXED_1 15000
#define CONFIG_SENSOR_480P_FPS_FIXED_1 15000
#define CONFIG_SENSOR_SVGA_FPS_FIXED_1 15000
#define CONFIG_SENSOR_720P_FPS_FIXED_1 30000
#define CONFIG_SENSOR_11 RK29_CAM_SENSOR_SP0838 /* front camera sensor 1 */
#define CONFIG_SENSOR_IIC_ADDR_11 0x30
#define CONFIG_SENSOR_IIC_ADAPTER_ID_11 3
#define CONFIG_SENSOR_CIF_INDEX_11 0
#define CONFIG_SENSOR_ORIENTATION_11 270
#define CONFIG_SENSOR_POWER_PIN_11 INVALID_GPIO
#define CONFIG_SENSOR_RESET_PIN_11 INVALID_GPIO
#define CONFIG_SENSOR_POWERDN_PIN_11 RK30_PIN1_PB7
#define CONFIG_SENSOR_FALSH_PIN_11 INVALID_GPIO
#define CONFIG_SENSOR_POWERACTIVE_LEVEL_11 RK29_CAM_POWERACTIVE_L
#define CONFIG_SENSOR_RESETACTIVE_LEVEL_11 RK29_CAM_RESETACTIVE_L
#define CONFIG_SENSOR_POWERDNACTIVE_LEVEL_11 RK29_CAM_POWERDNACTIVE_H
#define CONFIG_SENSOR_FLASHACTIVE_LEVEL_11 RK29_CAM_FLASHACTIVE_L
#define CONFIG_SENSOR_QCIF_FPS_FIXED_11 15000
#define CONFIG_SENSOR_240X160_FPS_FIXED_11 15000
#define CONFIG_SENSOR_QVGA_FPS_FIXED_11 15000
#define CONFIG_SENSOR_CIF_FPS_FIXED_11 15000
#define CONFIG_SENSOR_VGA_FPS_FIXED_11 15000
#define CONFIG_SENSOR_480P_FPS_FIXED_11 15000
#define CONFIG_SENSOR_SVGA_FPS_FIXED_11 15000
#define CONFIG_SENSOR_720P_FPS_FIXED_11 30000
#define CONFIG_SENSOR_12 RK29_CAM_SENSOR_GC2035 /* front camera sensor 2 */
#define CONFIG_SENSOR_IIC_ADDR_12 0x78
#define CONFIG_SENSOR_IIC_ADAPTER_ID_12 3
#define CONFIG_SENSOR_CIF_INDEX_12 0
#define CONFIG_SENSOR_ORIENTATION_12 270
#define CONFIG_SENSOR_POWER_PIN_12 INVALID_GPIO
#define CONFIG_SENSOR_RESET_PIN_12 INVALID_GPIO
#define CONFIG_SENSOR_POWERDN_PIN_12 RK30_PIN1_PB7
#define CONFIG_SENSOR_FALSH_PIN_12 INVALID_GPIO
#define CONFIG_SENSOR_POWERACTIVE_LEVEL_12 RK29_CAM_POWERACTIVE_L
#define CONFIG_SENSOR_RESETACTIVE_LEVEL_12 RK29_CAM_RESETACTIVE_L
#define CONFIG_SENSOR_POWERDNACTIVE_LEVEL_12 RK29_CAM_POWERDNACTIVE_H
#define CONFIG_SENSOR_FLASHACTIVE_LEVEL_12 RK29_CAM_FLASHACTIVE_L
#define CONFIG_SENSOR_QCIF_FPS_FIXED_12 15000
#define CONFIG_SENSOR_240X160_FPS_FIXED_12 15000
#define CONFIG_SENSOR_QVGA_FPS_FIXED_12 15000
#define CONFIG_SENSOR_CIF_FPS_FIXED_12 15000
#define CONFIG_SENSOR_VGA_FPS_FIXED_12 15000
#define CONFIG_SENSOR_480P_FPS_FIXED_12 15000
#define CONFIG_SENSOR_SVGA_FPS_FIXED_12 15000
#define CONFIG_SENSOR_720P_FPS_FIXED_12 30000
#define CONFIG_SENSOR_13 RK29_CAM_SENSOR_HI253 /* front camera sensor 3 */
#define CONFIG_SENSOR_IIC_ADDR_13 0x40
#define CONFIG_SENSOR_IIC_ADAPTER_ID_13 3
#define CONFIG_SENSOR_CIF_INDEX_13 0
#define CONFIG_SENSOR_ORIENTATION_13 270
#define CONFIG_SENSOR_POWER_PIN_13 INVALID_GPIO
#define CONFIG_SENSOR_RESET_PIN_13 INVALID_GPIO
#define CONFIG_SENSOR_POWERDN_PIN_13 RK30_PIN1_PB7
#define CONFIG_SENSOR_FALSH_PIN_13 INVALID_GPIO
#define CONFIG_SENSOR_POWERACTIVE_LEVEL_13 RK29_CAM_POWERACTIVE_L
#define CONFIG_SENSOR_RESETACTIVE_LEVEL_13 RK29_CAM_RESETACTIVE_L
#define CONFIG_SENSOR_POWERDNACTIVE_LEVEL_13 RK29_CAM_POWERDNACTIVE_H
#define CONFIG_SENSOR_FLASHACTIVE_LEVEL_13 RK29_CAM_FLASHACTIVE_L
#define CONFIG_SENSOR_QCIF_FPS_FIXED_13 15000
#define CONFIG_SENSOR_240X160_FPS_FIXED_13 15000
#define CONFIG_SENSOR_QVGA_FPS_FIXED_13 15000
#define CONFIG_SENSOR_CIF_FPS_FIXED_13 15000
#define CONFIG_SENSOR_VGA_FPS_FIXED_13 15000
#define CONFIG_SENSOR_480P_FPS_FIXED_13 15000
#define CONFIG_SENSOR_SVGA_FPS_FIXED_13 15000
#define CONFIG_SENSOR_720P_FPS_FIXED_13 30000
#define CONFIG_SENSOR_14 RK29_CAM_SENSOR_GT2005 /* front camera sensor 4 */
#define CONFIG_SENSOR_IIC_ADDR_14 0x78
#define CONFIG_SENSOR_IIC_ADAPTER_ID_14 3
#define CONFIG_SENSOR_CIF_INDEX_14 0
#define CONFIG_SENSOR_ORIENTATION_14 270
#define CONFIG_SENSOR_POWER_PIN_14 INVALID_GPIO
#define CONFIG_SENSOR_RESET_PIN_14 INVALID_GPIO
#define CONFIG_SENSOR_POWERDN_PIN_14 RK30_PIN1_PB7
#define CONFIG_SENSOR_FALSH_PIN_14 INVALID_GPIO
#define CONFIG_SENSOR_POWERACTIVE_LEVEL_14 RK29_CAM_POWERACTIVE_L
#define CONFIG_SENSOR_RESETACTIVE_LEVEL_14 RK29_CAM_RESETACTIVE_L
#define CONFIG_SENSOR_POWERDNACTIVE_LEVEL_14 RK29_CAM_POWERDNACTIVE_L
#define CONFIG_SENSOR_FLASHACTIVE_LEVEL_14 RK29_CAM_FLASHACTIVE_L
#define CONFIG_SENSOR_QCIF_FPS_FIXED_14 15000
#define CONFIG_SENSOR_240X160_FPS_FIXED_14 15000
#define CONFIG_SENSOR_QVGA_FPS_FIXED_14 15000
#define CONFIG_SENSOR_CIF_FPS_FIXED_14 15000
#define CONFIG_SENSOR_VGA_FPS_FIXED_14 15000
#define CONFIG_SENSOR_480P_FPS_FIXED_14 15000
#define CONFIG_SENSOR_SVGA_FPS_FIXED_14 15000
#define CONFIG_SENSOR_720P_FPS_FIXED_14 30000
#define CONFIG_SENSOR_15 RK29_CAM_SENSOR_HI704 /* front camera sensor 5 */
#define CONFIG_SENSOR_IIC_ADDR_15 0x60
#define CONFIG_SENSOR_IIC_ADAPTER_ID_15 3
#define CONFIG_SENSOR_CIF_INDEX_15 0
#define CONFIG_SENSOR_ORIENTATION_15 270
#define CONFIG_SENSOR_POWER_PIN_15 INVALID_GPIO
#define CONFIG_SENSOR_RESET_PIN_15 INVALID_GPIO
#define CONFIG_SENSOR_POWERDN_PIN_15 RK30_PIN1_PB7
#define CONFIG_SENSOR_FALSH_PIN_15 INVALID_GPIO
#define CONFIG_SENSOR_POWERACTIVE_LEVEL_15 RK29_CAM_POWERACTIVE_L
#define CONFIG_SENSOR_RESETACTIVE_LEVEL_15 RK29_CAM_RESETACTIVE_L
#define CONFIG_SENSOR_POWERDNACTIVE_LEVEL_15 RK29_CAM_POWERDNACTIVE_H
#define CONFIG_SENSOR_FLASHACTIVE_LEVEL_15 RK29_CAM_FLASHACTIVE_L
#define CONFIG_SENSOR_QCIF_FPS_FIXED_15 15000
#define CONFIG_SENSOR_240X160_FPS_FIXED_15 15000
#define CONFIG_SENSOR_QVGA_FPS_FIXED_15 15000
#define CONFIG_SENSOR_CIF_FPS_FIXED_15 15000
#define CONFIG_SENSOR_VGA_FPS_FIXED_15 15000
#define CONFIG_SENSOR_480P_FPS_FIXED_15 15000
#define CONFIG_SENSOR_SVGA_FPS_FIXED_15 15000
#define CONFIG_SENSOR_720P_FPS_FIXED_15 30000
#define CONFIG_SENSOR_16 RK29_CAM_SENSOR_OV2655 /* front camera sensor 6 */
#define CONFIG_SENSOR_IIC_ADDR_16 0x60
#define CONFIG_SENSOR_IIC_ADAPTER_ID_16 3
#define CONFIG_SENSOR_CIF_INDEX_16 0
#define CONFIG_SENSOR_ORIENTATION_16 270
#define CONFIG_SENSOR_POWER_PIN_16 INVALID_GPIO
#define CONFIG_SENSOR_RESET_PIN_16 INVALID_GPIO
#define CONFIG_SENSOR_POWERDN_PIN_16 RK30_PIN1_PB7
#define CONFIG_SENSOR_FALSH_PIN_16 INVALID_GPIO
#define CONFIG_SENSOR_POWERACTIVE_LEVEL_16 RK29_CAM_POWERACTIVE_L
#define CONFIG_SENSOR_RESETACTIVE_LEVEL_16 RK29_CAM_RESETACTIVE_L
#define CONFIG_SENSOR_POWERDNACTIVE_LEVEL_16 RK29_CAM_POWERDNACTIVE_H
#define CONFIG_SENSOR_FLASHACTIVE_LEVEL_16 RK29_CAM_FLASHACTIVE_L
#define CONFIG_SENSOR_QCIF_FPS_FIXED_16 15000
#define CONFIG_SENSOR_240X160_FPS_FIXED_16 15000
#define CONFIG_SENSOR_QVGA_FPS_FIXED_16 15000
#define CONFIG_SENSOR_CIF_FPS_FIXED_16 15000
#define CONFIG_SENSOR_VGA_FPS_FIXED_16 15000
#define CONFIG_SENSOR_480P_FPS_FIXED_16 15000
#define CONFIG_SENSOR_SVGA_FPS_FIXED_16 15000
#define CONFIG_SENSOR_720P_FPS_FIXED_16 30000
#define CONFIG_SENSOR_17 RK29_CAM_SENSOR_SP2518 /* front camera sensor 7 */
#define CONFIG_SENSOR_IIC_ADDR_17 0x60
#define CONFIG_SENSOR_IIC_ADAPTER_ID_17 3
#define CONFIG_SENSOR_CIF_INDEX_17 0
#define CONFIG_SENSOR_ORIENTATION_17 270
#define CONFIG_SENSOR_POWER_PIN_17 INVALID_GPIO
#define CONFIG_SENSOR_RESET_PIN_17 INVALID_GPIO
#define CONFIG_SENSOR_POWERDN_PIN_17 RK30_PIN1_PB7
#define CONFIG_SENSOR_FALSH_PIN_17 INVALID_GPIO
#define CONFIG_SENSOR_POWERACTIVE_LEVEL_17 RK29_CAM_POWERACTIVE_L
#define CONFIG_SENSOR_RESETACTIVE_LEVEL_17 RK29_CAM_RESETACTIVE_L
#define CONFIG_SENSOR_POWERDNACTIVE_LEVEL_17 RK29_CAM_POWERDNACTIVE_H
#define CONFIG_SENSOR_FLASHACTIVE_LEVEL_17 RK29_CAM_FLASHACTIVE_L
#define CONFIG_SENSOR_QCIF_FPS_FIXED_17 15000
#define CONFIG_SENSOR_240X160_FPS_FIXED_17 15000
#define CONFIG_SENSOR_QVGA_FPS_FIXED_17 15000
#define CONFIG_SENSOR_CIF_FPS_FIXED_17 15000
#define CONFIG_SENSOR_VGA_FPS_FIXED_17 15000
#define CONFIG_SENSOR_480P_FPS_FIXED_17 15000
#define CONFIG_SENSOR_SVGA_FPS_FIXED_17 15000
#define CONFIG_SENSOR_720P_FPS_FIXED_17 30000
#define CONFIG_SENSOR_18 RK29_CAM_SENSOR_SP2518 /* front camera sensor 8 */
#define CONFIG_SENSOR_IIC_ADDR_18 0x00
#define CONFIG_SENSOR_IIC_ADAPTER_ID_18 3
#define CONFIG_SENSOR_CIF_INDEX_18 0
#define CONFIG_SENSOR_ORIENTATION_18 270
#define CONFIG_SENSOR_POWER_PIN_18 INVALID_GPIO
#define CONFIG_SENSOR_RESET_PIN_18 INVALID_GPIO
#define CONFIG_SENSOR_POWERDN_PIN_18 RK30_PIN1_PB7
#define CONFIG_SENSOR_FALSH_PIN_18 INVALID_GPIO
#define CONFIG_SENSOR_POWERACTIVE_LEVEL_18 RK29_CAM_POWERACTIVE_L
#define CONFIG_SENSOR_RESETACTIVE_LEVEL_18 RK29_CAM_RESETACTIVE_L
#define CONFIG_SENSOR_POWERDNACTIVE_LEVEL_18 RK29_CAM_POWERDNACTIVE_H
#define CONFIG_SENSOR_FLASHACTIVE_LEVEL_18 RK29_CAM_FLASHACTIVE_L
#define CONFIG_SENSOR_QCIF_FPS_FIXED_18 15000
#define CONFIG_SENSOR_240X160_FPS_FIXED_18 15000
#define CONFIG_SENSOR_QVGA_FPS_FIXED_18 15000
#define CONFIG_SENSOR_CIF_FPS_FIXED_18 15000
#define CONFIG_SENSOR_VGA_FPS_FIXED_18 15000
#define CONFIG_SENSOR_480P_FPS_FIXED_18 15000
#define CONFIG_SENSOR_SVGA_FPS_FIXED_18 15000
#define CONFIG_SENSOR_720P_FPS_FIXED_18 30000
#define CONFIG_SENSOR_19 RK29_CAM_SENSOR_SP2518 /* front camera sensor 9 */
#define CONFIG_SENSOR_IIC_ADDR_19 0x00
#define CONFIG_SENSOR_IIC_ADAPTER_ID_19 3
#define CONFIG_SENSOR_CIF_INDEX_19 0
#define CONFIG_SENSOR_ORIENTATION_19 270
#define CONFIG_SENSOR_POWER_PIN_19 INVALID_GPIO
#define CONFIG_SENSOR_RESET_PIN_19 INVALID_GPIO
#define CONFIG_SENSOR_POWERDN_PIN_19 RK30_PIN1_PB7
#define CONFIG_SENSOR_FALSH_PIN_19 INVALID_GPIO
#define CONFIG_SENSOR_POWERACTIVE_LEVEL_19 RK29_CAM_POWERACTIVE_L
#define CONFIG_SENSOR_RESETACTIVE_LEVEL_19 RK29_CAM_RESETACTIVE_L
#define CONFIG_SENSOR_POWERDNACTIVE_LEVEL_19 RK29_CAM_POWERDNACTIVE_H
#define CONFIG_SENSOR_FLASHACTIVE_LEVEL_19 RK29_CAM_FLASHACTIVE_L
#define CONFIG_SENSOR_QCIF_FPS_FIXED_19 15000
#define CONFIG_SENSOR_240X160_FPS_FIXED_19 15000
#define CONFIG_SENSOR_QVGA_FPS_FIXED_19 15000
#define CONFIG_SENSOR_CIF_FPS_FIXED_19 15000
#define CONFIG_SENSOR_VGA_FPS_FIXED_19 15000
#define CONFIG_SENSOR_480P_FPS_FIXED_19 15000
#define CONFIG_SENSOR_SVGA_FPS_FIXED_19 15000
#define CONFIG_SENSOR_720P_FPS_FIXED_19 30000
#endif //#ifdef CONFIG_VIDEO_RK29
/*---------------- Camera Sensor Configuration Macro End------------------------*/
#include "../../../drivers/media/video/rk30_camera.c"
/*---------------- Camera Sensor Macro Define End ---------*/
#define PMEM_CAM_SIZE PMEM_CAM_NECESSARY
/*****************************************************************************************
* camera devices
* author: ddl@rock-chips.com
*****************************************************************************************/
#ifdef CONFIG_VIDEO_RK29
#define CONFIG_SENSOR_POWER_IOCTL_USR 1 //define this refer to your board layout
#define CONFIG_SENSOR_RESET_IOCTL_USR 0
#define CONFIG_SENSOR_POWERDOWN_IOCTL_USR 0
#define CONFIG_SENSOR_FLASH_IOCTL_USR 0
static void rk_cif_power(int on)
{
#ifdef CONFIG_KP_AXP20
//gpio_direction_output(RK30_PIN6_PB0, on ? GPIO_HIGH : GPIO_LOW);
#else
struct regulator *ldo_18,*ldo_28;
#if defined (CONFIG_MFD_WM831X)
ldo_28 = regulator_get(NULL, "ldo7"); // vcc28_cif
ldo_18 = regulator_get(NULL, "ldo1"); // vcc18_cif
#endif
#if defined (CONFIG_MFD_TPS65910)
ldo_28 = regulator_get(NULL, "vmmc"); // vcc28_cif
ldo_18 = regulator_get(NULL, "vdig1"); // vcc18_cif
#endif
if (ldo_28 == NULL || IS_ERR(ldo_28) || ldo_18 == NULL || IS_ERR(ldo_18)){
printk("get cif ldo failed!\n");
return;
}
if(on == 0){
regulator_disable(ldo_28);
regulator_put(ldo_28);
regulator_disable(ldo_18);
regulator_put(ldo_18);
mdelay(500);
}
else{
regulator_set_voltage(ldo_28, 2800000, 2800000);
regulator_enable(ldo_28);
// printk("%s set ldo7 vcc28_cif=%dmV end\n", __func__, regulator_get_voltage(ldo_28));
regulator_put(ldo_28);
regulator_set_voltage(ldo_18, 1800000, 1800000);
// regulator_set_suspend_voltage(ldo, 1800000);
regulator_enable(ldo_18);
// printk("%s set ldo1 vcc18_cif=%dmV end\n", __func__, regulator_get_voltage(ldo_18));
regulator_put(ldo_18);
}
#endif
}
#if CONFIG_SENSOR_POWER_IOCTL_USR
static int sensor_power_usr_cb (struct rk29camera_gpio_res *res,int on)
{
//#error "CONFIG_SENSOR_POWER_IOCTL_USR is 1, sensor_power_usr_cb function must be writed!!";
rk_cif_power(on);
}
#endif
#if CONFIG_SENSOR_RESET_IOCTL_USR
static int sensor_reset_usr_cb (struct rk29camera_gpio_res *res,int on)
{
#error "CONFIG_SENSOR_RESET_IOCTL_USR is 1, sensor_reset_usr_cb function must be writed!!";
}
#endif
#if CONFIG_SENSOR_POWERDOWN_IOCTL_USR
static int sensor_powerdown_usr_cb (struct rk29camera_gpio_res *res,int on)
{
#error "CONFIG_SENSOR_POWERDOWN_IOCTL_USR is 1, sensor_powerdown_usr_cb function must be writed!!";
}
#endif
#if CONFIG_SENSOR_FLASH_IOCTL_USR
static int sensor_flash_usr_cb (struct rk29camera_gpio_res *res,int on)
{
#error "CONFIG_SENSOR_FLASH_IOCTL_USR is 1, sensor_flash_usr_cb function must be writed!!";
}
#endif
static struct rk29camera_platform_ioctl_cb sensor_ioctl_cb = {
#if CONFIG_SENSOR_POWER_IOCTL_USR
.sensor_power_cb = sensor_power_usr_cb,
#else
.sensor_power_cb = NULL,
#endif
#if CONFIG_SENSOR_RESET_IOCTL_USR
.sensor_reset_cb = sensor_reset_usr_cb,
#else
.sensor_reset_cb = NULL,
#endif
#if CONFIG_SENSOR_POWERDOWN_IOCTL_USR
.sensor_powerdown_cb = sensor_powerdown_usr_cb,
#else
.sensor_powerdown_cb = NULL,
#endif
#if CONFIG_SENSOR_FLASH_IOCTL_USR
.sensor_flash_cb = sensor_flash_usr_cb,
#else
.sensor_flash_cb = NULL,
#endif
};
#if CONFIG_SENSOR_IIC_ADDR_0
static struct reginfo_t rk_init_data_sensor_reg_0[] =
{
{0x0000, 0x00,0,0}
};
static struct reginfo_t rk_init_data_sensor_winseqreg_0[] ={
{0x0000, 0x00,0,0}
};
#endif
#if CONFIG_SENSOR_IIC_ADDR_1
static struct reginfo_t rk_init_data_sensor_reg_1[] =
{
{0x0000, 0x00,0,0}
};
static struct reginfo_t rk_init_data_sensor_winseqreg_1[] =
{
{0x0000, 0x00,0,0}
};
#endif
#if CONFIG_SENSOR_IIC_ADDR_01
static struct reginfo_t rk_init_data_sensor_reg_01[] =
{
{0x0000, 0x00,0,0}
};
static struct reginfo_t rk_init_data_sensor_winseqreg_01[] =
{
{0x0000, 0x00,0,0}
};
#endif
#if CONFIG_SENSOR_IIC_ADDR_02
static struct reginfo_t rk_init_data_sensor_reg_02[] =
{
{0x0000, 0x00,0,0}
};
static struct reginfo_t rk_init_data_sensor_winseqreg_02[] =
{
{0x0000, 0x00,0,0}
};
#endif
#if CONFIG_SENSOR_IIC_ADDR_03
static struct reginfo_t rk_init_data_sensor_reg_03[] =
{
{0x0000, 0x00,0,0}
};
static struct reginfo_t rk_init_data_sensor_winseqreg_03[] =
{
{0x0000, 0x00,0,0}
};
#endif
#if CONFIG_SENSOR_IIC_ADDR_04
static struct reginfo_t rk_init_data_sensor_reg_04[] =
{
{0x0000, 0x00,0,0}
};
static struct reginfo_t rk_init_data_sensor_winseqreg_04[] =
{
{0x0000, 0x00,0,0}
};
#endif
#if CONFIG_SENSOR_IIC_ADDR_05
static struct reginfo_t rk_init_data_sensor_reg_05[] =
{
{0x0000, 0x00,0,0}
};
static struct reginfo_t rk_init_data_sensor_winseqreg_05[] =
{
{0x0000, 0x00,0,0}
};
#endif
#if CONFIG_SENSOR_IIC_ADDR_06
static struct reginfo_t rk_init_data_sensor_reg_06[] =
{
{0x0000, 0x00,0,0}
};
static struct reginfo_t rk_init_data_sensor_winseqreg_06[] =
{
{0x0000, 0x00,0,0}
};
#endif
#if CONFIG_SENSOR_IIC_ADDR_07
static struct reginfo_t rk_init_data_sensor_reg_07[] =
{
{0x0000, 0x00,0,0}
};
static struct reginfo_t rk_init_data_sensor_winseqreg_07[] =
{
{0x0000, 0x00,0,0}
};
#endif
#if CONFIG_SENSOR_IIC_ADDR_08
static struct reginfo_t rk_init_data_sensor_reg_08[] =
{
{0x0000, 0x00,0,0}
};
static struct reginfo_t rk_init_data_sensor_winseqreg_08[] =
{
{0x0000, 0x00,0,0}
};
#endif
#if CONFIG_SENSOR_IIC_ADDR_09
static struct reginfo_t rk_init_data_sensor_reg_09[] =
{
{0x0000, 0x00,0,0}
};
static struct reginfo_t rk_init_data_sensor_winseqreg_09[] =
{
{0x0000, 0x00,0,0}
};
#endif
#if CONFIG_SENSOR_IIC_ADDR_11
static struct reginfo_t rk_init_data_sensor_reg_11[] =
{
{0x0000, 0x00,0,0}
};
static struct reginfo_t rk_init_data_sensor_winseqreg_11[] =
{
{0x0000, 0x00,0,0}
};
#endif
#if CONFIG_SENSOR_IIC_ADDR_12
static struct reginfo_t rk_init_data_sensor_reg_12[] =
{
{0x0000, 0x00,0,0}
};
static struct reginfo_t rk_init_data_sensor_winseqreg_12[] =
{
{0x0000, 0x00,0,0}
};
#endif
#if CONFIG_SENSOR_IIC_ADDR_13
static struct reginfo_t rk_init_data_sensor_reg_13[] =
{
{0x0000, 0x00,0,0}
};
static struct reginfo_t rk_init_data_sensor_winseqreg_13[] =
{
{0x0000, 0x00,0,0}
};
#endif
#if CONFIG_SENSOR_IIC_ADDR_14
static struct reginfo_t rk_init_data_sensor_reg_14[] =
{
{0x0000, 0x00,0,0}
};
static struct reginfo_t rk_init_data_sensor_winseqreg_14[] =
{
{0x0000, 0x00,0,0}
};
#endif
#if CONFIG_SENSOR_IIC_ADDR_15
static struct reginfo_t rk_init_data_sensor_reg_15[] =
{
{0x0000, 0x00,0,0}
};
static struct reginfo_t rk_init_data_sensor_winseqreg_15[] =
{
{0x0000, 0x00,0,0}
};
#endif
#if CONFIG_SENSOR_IIC_ADDR_16
static struct reginfo_t rk_init_data_sensor_reg_16[] =
{
{0x0000, 0x00,0,0}
};
static struct reginfo_t rk_init_data_sensor_winseqreg_16[] =
{
{0x0000, 0x00,0,0}
};
#endif
#if CONFIG_SENSOR_IIC_ADDR_17
static struct reginfo_t rk_init_data_sensor_reg_17[] =
{
{0x0000, 0x00,0,0}
};
static struct reginfo_t rk_init_data_sensor_winseqreg_17[] =
{
{0x0000, 0x00,0,0}
};
#endif
#if CONFIG_SENSOR_IIC_ADDR_18
static struct reginfo_t rk_init_data_sensor_reg_18[] =
{
{0x0000, 0x00,0,0}
};
static struct reginfo_t rk_init_data_sensor_winseqreg_18[] =
{
{0x0000, 0x00,0,0}
};
#endif
#if CONFIG_SENSOR_IIC_ADDR_19
static struct reginfo_t rk_init_data_sensor_reg_19[] =
{
{0x0000, 0x00,0,0}
};
static struct reginfo_t rk_init_data_sensor_winseqreg_19[] =
{
{0x0000, 0x00,0,0}
};
#endif
static rk_sensor_user_init_data_s rk_init_data_sensor[RK_CAM_NUM] =
{
#if CONFIG_SENSOR_IIC_ADDR_0
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = rk_init_data_sensor_reg_0,
.rk_sensor_init_winseq = rk_init_data_sensor_winseqreg_0,
.rk_sensor_winseq_size = sizeof(rk_init_data_sensor_winseqreg_0) / sizeof(struct reginfo_t),
.rk_sensor_init_data_size = sizeof(rk_init_data_sensor_reg_0) / sizeof(struct reginfo_t),
},
#else
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = NULL,
.rk_sensor_init_winseq = NULL,
.rk_sensor_winseq_size = 0,
.rk_sensor_init_data_size = 0,
},
#endif
#if CONFIG_SENSOR_IIC_ADDR_1
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = rk_init_data_sensor_reg_1,
.rk_sensor_init_winseq = rk_init_data_sensor_winseqreg_1,
.rk_sensor_winseq_size = sizeof(rk_init_data_sensor_winseqreg_1) / sizeof(struct reginfo_t),
.rk_sensor_init_data_size = sizeof(rk_init_data_sensor_reg_1) / sizeof(struct reginfo_t),
},
#else
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = NULL,
.rk_sensor_init_winseq = NULL,
.rk_sensor_winseq_size = 0,
.rk_sensor_init_data_size = 0,
},
#endif
#if CONFIG_SENSOR_IIC_ADDR_01
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = rk_init_data_sensor_reg_01,
.rk_sensor_init_winseq = rk_init_data_sensor_winseqreg_01,
.rk_sensor_winseq_size = sizeof(rk_init_data_sensor_winseqreg_01) / sizeof(struct reginfo_t),
.rk_sensor_init_data_size = sizeof(rk_init_data_sensor_reg_01) / sizeof(struct reginfo_t),
},
#else
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = NULL,
.rk_sensor_init_winseq = NULL,
.rk_sensor_winseq_size = 0,
.rk_sensor_init_data_size = 0,
},
#endif
#if CONFIG_SENSOR_IIC_ADDR_02
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = rk_init_data_sensor_reg_02,
.rk_sensor_init_winseq = rk_init_data_sensor_winseqreg_02,
.rk_sensor_winseq_size = sizeof(rk_init_data_sensor_winseqreg_02) / sizeof(struct reginfo_t),
.rk_sensor_init_data_size = sizeof(rk_init_data_sensor_reg_02) / sizeof(struct reginfo_t),
},
#else
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = NULL,
.rk_sensor_init_winseq = NULL,
.rk_sensor_winseq_size = 0,
.rk_sensor_init_data_size = 0,
},
#endif
#if CONFIG_SENSOR_IIC_ADDR_03
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = rk_init_data_sensor_reg_03,
.rk_sensor_init_winseq = rk_init_data_sensor_winseqreg_03,
.rk_sensor_winseq_size = sizeof(rk_init_data_sensor_winseqreg_03) / sizeof(struct reginfo_t),
.rk_sensor_init_data_size = sizeof(rk_init_data_sensor_reg_03) / sizeof(struct reginfo_t),
},
#else
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = NULL,
.rk_sensor_init_winseq = NULL,
.rk_sensor_winseq_size = 0,
.rk_sensor_init_data_size = 0,
},
#endif
#if CONFIG_SENSOR_IIC_ADDR_04
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = rk_init_data_sensor_reg_04,
.rk_sensor_init_winseq = rk_init_data_sensor_winseqreg_04,
.rk_sensor_winseq_size = sizeof(rk_init_data_sensor_winseqreg_04) / sizeof(struct reginfo_t),
.rk_sensor_init_data_size = sizeof(rk_init_data_sensor_reg_04) / sizeof(struct reginfo_t),
},
#else
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = NULL,
.rk_sensor_init_winseq = NULL,
.rk_sensor_winseq_size = 0,
.rk_sensor_init_data_size = 0,
},
#endif
#if CONFIG_SENSOR_IIC_ADDR_05
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = rk_init_data_sensor_reg_05,
.rk_sensor_init_winseq = rk_init_data_sensor_winseqreg_05,
.rk_sensor_winseq_size = sizeof(rk_init_data_sensor_winseqreg_05) / sizeof(struct reginfo_t),
.rk_sensor_init_data_size = sizeof(rk_init_data_sensor_reg_05) / sizeof(struct reginfo_t),
},
#else
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = NULL,
.rk_sensor_init_winseq = NULL,
.rk_sensor_winseq_size = 0,
.rk_sensor_init_data_size = 0,
},
#endif
#if CONFIG_SENSOR_IIC_ADDR_06
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = rk_init_data_sensor_reg_06,
.rk_sensor_init_winseq = rk_init_data_sensor_winseqreg_06,
.rk_sensor_winseq_size = sizeof(rk_init_data_sensor_winseqreg_06) / sizeof(struct reginfo_t),
.rk_sensor_init_data_size = sizeof(rk_init_data_sensor_reg_06) / sizeof(struct reginfo_t),
},
#else
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = NULL,
.rk_sensor_init_winseq = NULL,
.rk_sensor_winseq_size = 0,
.rk_sensor_init_data_size = 0,
},
#endif
#if CONFIG_SENSOR_IIC_ADDR_07
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = rk_init_data_sensor_reg_07,
.rk_sensor_init_winseq = rk_init_data_sensor_winseqreg_07,
.rk_sensor_winseq_size = sizeof(rk_init_data_sensor_winseqreg_07) / sizeof(struct reginfo_t),
.rk_sensor_init_data_size = sizeof(rk_init_data_sensor_reg_07) / sizeof(struct reginfo_t),
},
#else
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = NULL,
.rk_sensor_init_winseq = NULL,
.rk_sensor_winseq_size = 0,
.rk_sensor_init_data_size = 0,
},
#endif
#if CONFIG_SENSOR_IIC_ADDR_08
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = rk_init_data_sensor_reg_08,
.rk_sensor_init_winseq = rk_init_data_sensor_winseqreg_08,
.rk_sensor_winseq_size = sizeof(rk_init_data_sensor_winseqreg_08) / sizeof(struct reginfo_t),
.rk_sensor_init_data_size = sizeof(rk_init_data_sensor_reg_08) / sizeof(struct reginfo_t),
},
#else
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = NULL,
.rk_sensor_init_winseq = NULL,
.rk_sensor_winseq_size = 0,
.rk_sensor_init_data_size = 0,
},
#endif
#if CONFIG_SENSOR_IIC_ADDR_09
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = rk_init_data_sensor_reg_09,
.rk_sensor_init_winseq = rk_init_data_sensor_winseqreg_09,
.rk_sensor_winseq_size = sizeof(rk_init_data_sensor_winseqreg_09) / sizeof(struct reginfo_t),
.rk_sensor_init_data_size = sizeof(rk_init_data_sensor_reg_09) / sizeof(struct reginfo_t),
},
#else
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = NULL,
.rk_sensor_init_winseq = NULL,
.rk_sensor_winseq_size = 0,
.rk_sensor_init_data_size = 0,
},
#endif
#if CONFIG_SENSOR_IIC_ADDR_11
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = rk_init_data_sensor_reg_11,
.rk_sensor_init_winseq = rk_init_data_sensor_winseqreg_11,
.rk_sensor_winseq_size = sizeof(rk_init_data_sensor_winseqreg_11) / sizeof(struct reginfo_t),
.rk_sensor_init_data_size = sizeof(rk_init_data_sensor_reg_11) / sizeof(struct reginfo_t),
},
#else
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = NULL,
.rk_sensor_init_winseq = NULL,
.rk_sensor_winseq_size = 0,
.rk_sensor_init_data_size = 0,
},
#endif
#if CONFIG_SENSOR_IIC_ADDR_12
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = rk_init_data_sensor_reg_12,
.rk_sensor_init_winseq = rk_init_data_sensor_winseqreg_12,
.rk_sensor_winseq_size = sizeof(rk_init_data_sensor_winseqreg_12) / sizeof(struct reginfo_t),
.rk_sensor_init_data_size = sizeof(rk_init_data_sensor_reg_12) / sizeof(struct reginfo_t),
},
#else
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = NULL,
.rk_sensor_init_winseq = NULL,
.rk_sensor_winseq_size = 0,
.rk_sensor_init_data_size = 0,
},
#endif
#if CONFIG_SENSOR_IIC_ADDR_13
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = rk_init_data_sensor_reg_13,
.rk_sensor_init_winseq = rk_init_data_sensor_winseqreg_13,
.rk_sensor_winseq_size = sizeof(rk_init_data_sensor_winseqreg_13) / sizeof(struct reginfo_t),
.rk_sensor_init_data_size = sizeof(rk_init_data_sensor_reg_13) / sizeof(struct reginfo_t),
},
#else
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = NULL,
.rk_sensor_init_winseq = NULL,
.rk_sensor_winseq_size = 0,
.rk_sensor_init_data_size = 0,
},
#endif
#if CONFIG_SENSOR_IIC_ADDR_14
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = rk_init_data_sensor_reg_14,
.rk_sensor_init_winseq = rk_init_data_sensor_winseqreg_14,
.rk_sensor_winseq_size = sizeof(rk_init_data_sensor_winseqreg_14) / sizeof(struct reginfo_t),
.rk_sensor_init_data_size = sizeof(rk_init_data_sensor_reg_14) / sizeof(struct reginfo_t),
},
#else
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = NULL,
.rk_sensor_init_winseq = NULL,
.rk_sensor_winseq_size = 0,
.rk_sensor_init_data_size = 0,
},
#endif
#if CONFIG_SENSOR_IIC_ADDR_15
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = rk_init_data_sensor_reg_15,
.rk_sensor_init_winseq = rk_init_data_sensor_winseqreg_15,
.rk_sensor_winseq_size = sizeof(rk_init_data_sensor_winseqreg_15) / sizeof(struct reginfo_t),
.rk_sensor_init_data_size = sizeof(rk_init_data_sensor_reg_15) / sizeof(struct reginfo_t),
},
#else
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = NULL,
.rk_sensor_init_winseq = NULL,
.rk_sensor_winseq_size = 0,
.rk_sensor_init_data_size = 0,
},
#endif
#if CONFIG_SENSOR_IIC_ADDR_16
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = rk_init_data_sensor_reg_16,
.rk_sensor_init_winseq = rk_init_data_sensor_winseqreg_16,
.rk_sensor_winseq_size = sizeof(rk_init_data_sensor_winseqreg_16) / sizeof(struct reginfo_t),
.rk_sensor_init_data_size = sizeof(rk_init_data_sensor_reg_16) / sizeof(struct reginfo_t),
},
#else
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = NULL,
.rk_sensor_init_winseq = NULL,
.rk_sensor_winseq_size = 0,
.rk_sensor_init_data_size = 0,
},
#endif
#if CONFIG_SENSOR_IIC_ADDR_17
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = rk_init_data_sensor_reg_17,
.rk_sensor_init_winseq = rk_init_data_sensor_winseqreg_17,
.rk_sensor_winseq_size = sizeof(rk_init_data_sensor_winseqreg_17) / sizeof(struct reginfo_t),
.rk_sensor_init_data_size = sizeof(rk_init_data_sensor_reg_17) / sizeof(struct reginfo_t),
},
#else
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = NULL,
.rk_sensor_init_winseq = NULL,
.rk_sensor_winseq_size = 0,
.rk_sensor_init_data_size = 0,
},
#endif
#if CONFIG_SENSOR_IIC_ADDR_18
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = rk_init_data_sensor_reg_18,
.rk_sensor_init_winseq = rk_init_data_sensor_winseqreg_18,
.rk_sensor_winseq_size = sizeof(rk_init_data_sensor_winseqreg_18) / sizeof(struct reginfo_t),
.rk_sensor_init_data_size = sizeof(rk_init_data_sensor_reg_18) / sizeof(struct reginfo_t),
},
#else
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = NULL,
.rk_sensor_init_winseq = NULL,
.rk_sensor_winseq_size = 0,
.rk_sensor_init_data_size = 0,
},
#endif
#if CONFIG_SENSOR_IIC_ADDR_19
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = rk_init_data_sensor_reg_19,
.rk_sensor_init_winseq = rk_init_data_sensor_winseqreg_19,
.rk_sensor_winseq_size = sizeof(rk_init_data_sensor_winseqreg_19) / sizeof(struct reginfo_t),
.rk_sensor_init_data_size = sizeof(rk_init_data_sensor_reg_19) / sizeof(struct reginfo_t),
},
#else
{
.rk_sensor_init_width = INVALID_VALUE,
.rk_sensor_init_height = INVALID_VALUE,
.rk_sensor_init_bus_param = INVALID_VALUE,
.rk_sensor_init_pixelcode = INVALID_VALUE,
.rk_sensor_init_data = NULL,
.rk_sensor_init_winseq = NULL,
.rk_sensor_winseq_size = 0,
.rk_sensor_init_data_size = 0,
},
#endif
};
#include "../../../drivers/media/video/rk30_camera.c"
#endif /* CONFIG_VIDEO_RK29 */
#if defined(CONFIG_TOUCHSCREEN_CYTTSP4)
#define CY_I2C_NAME "cyttsp4-i2c"
#define CY_I2C_TCH_ADR 0x67
#define CY_I2C_LDR_ADR 0x69
#define CY_MAXX 1024//1368 //1296 //480
#define CY_MAXY 768//782 //828 //256
#define TOUCH_GPIO_RST_CYTTSP RK30_PIN4_PD0
#define TOUCH_GPIO_IRQ_CYTTSP RK30_PIN4_PC2
static int cyttsp4_i2c_init(void)
{
#if 0
return cyttsp4_vkey_init(CY_I2C_VKEY_NAME);;
#else
return 0;
#endif
}
static int cyttsp4_hw_reset(void)
{
int ret = 0;
gpio_set_value(TOUCH_GPIO_RST_CYTTSP, 1);
pr_info("%s: gpio_set_value(step%d)=%d\n", __func__, 1, 1);
msleep(20);
gpio_set_value(TOUCH_GPIO_RST_CYTTSP, 0);
pr_info("%s: gpio_set_value(step%d)=%d\n", __func__, 2, 0);
msleep(40);
gpio_set_value(TOUCH_GPIO_RST_CYTTSP, 1);
msleep(20);
pr_info("%s: gpio_set_value(step%d)=%d\n", __func__, 3, 1);
return ret;
}
static int cyttsp4_hw_recov(int on)
{
int retval = 0;
pr_info("%s: on=%d\n", __func__, on);
if (on == 0) {
cyttsp4_hw_reset();
retval = 0;
} else
retval = -EINVAL;
#if 0 // KEVKEV
else {
retval = gpio_direction_output(TOUCH_GPIO_IRQ_CYTTSP, 0);
if (retval < 0) {
pr_err("%s: Fail switch IRQ pin to output"
" r=%d\n", __func__, retval);
} else {
cyttsp4_hw_reset();
retval = gpio_direction_input(TOUCH_GPIO_IRQ_CYTTSP);
if (retval < 0) {
pr_err("%s: Fail switch IRQ pin to input"
" r=%d\n", __func__, retval);
}
}
}
#endif
return 0;
}
static int cyttsp4_irq_stat(void)
{
return gpio_get_value(TOUCH_GPIO_IRQ_CYTTSP);
}
#define CY_ABS_MIN_X 0
#define CY_ABS_MIN_Y 0
#define CY_ABS_MIN_P 0
#define CY_ABS_MIN_W 0
#define CY_ABS_MIN_T 0//1
#define CY_ABS_MAX_X CY_MAXX
#define CY_ABS_MAX_Y CY_MAXY
#define CY_ABS_MAX_P 255
#define CY_ABS_MAX_W 255
#define CY_ABS_MAX_T 9//10
#define CY_IGNORE_VALUE 0xFFFF
#include <linux/input/touch_platform.h>
#include "../../../drivers/input/touchscreen/cyttsp4_params.h"
static struct touch_settings cyttsp4_sett_param_regs = {
.data = (uint8_t *)&cyttsp4_param_regs[0],
.size = sizeof(cyttsp4_param_regs),
.tag = 0,
};
static struct touch_settings cyttsp4_sett_param_size = {
.data = (uint8_t *)&cyttsp4_param_size[0],
.size = sizeof(cyttsp4_param_size),
.tag = 0,
};
/* Design Data Table */
static u8 cyttsp4_ddata[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24 /* test padding, 25, 26, 27, 28, 29, 30, 31 */
};
static struct touch_settings cyttsp4_sett_ddata = {
.data = (uint8_t *)&cyttsp4_ddata[0],
.size = sizeof(cyttsp4_ddata),
.tag = 0,
};
/* Manufacturing Data Table */
static u8 cyttsp4_mdata[] = {
65, 64, /* test truncation */63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48,
47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32,
31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16,
15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
};
static struct touch_settings cyttsp4_sett_mdata = {
.data = (uint8_t *)&cyttsp4_mdata[0],
.size = sizeof(cyttsp4_mdata),
.tag = 0,
};
#define CY_USE_INCLUDE_FBL
#ifdef CY_USE_INCLUDE_FBL
#include "../../../drivers/input/touchscreen/cyttsp4_img.h"
static struct touch_firmware cyttsp4_firmware = {
.img = cyttsp4_img,
.size = sizeof(cyttsp4_img),
.ver = cyttsp4_ver,
.vsize = sizeof(cyttsp4_ver),
};
#else
static u8 test_img[] = {0, 1, 2, 4, 8, 16, 32, 64, 128};
static u8 test_ver[] = {0, 0, 0, 0, 0x10, 0x20, 0, 0, 0};
static struct touch_firmware cyttsp4_firmware = {
.img = test_img,
.size = sizeof(test_img),
.ver = test_ver,
.vsize = sizeof(test_ver),
};
#endif
static const uint16_t cyttsp4_abs[] = {
ABS_MT_POSITION_X, CY_ABS_MIN_X, CY_ABS_MAX_X, 0, 0,
ABS_MT_POSITION_Y, CY_ABS_MIN_Y, CY_ABS_MAX_Y, 0, 0,
ABS_MT_PRESSURE, CY_ABS_MIN_P, CY_ABS_MAX_P, 0, 0,
// CY_IGNORE_VALUE/*ABS_MT_TOUCH_MAJOR*/, CY_ABS_MIN_W, CY_ABS_MAX_W, 0, 0,
ABS_MT_TOUCH_MAJOR, CY_ABS_MIN_W, CY_ABS_MAX_W, 0, 0,
ABS_MT_TRACKING_ID, CY_ABS_MIN_T, CY_ABS_MAX_T, 0, 0,
};
struct touch_framework cyttsp4_framework = {
.abs = (uint16_t *)&cyttsp4_abs[0],
.size = sizeof(cyttsp4_abs)/sizeof(uint16_t),
.enable_vkeys = 1,
};
struct touch_platform_data cyttsp4_i2c_touch_platform_data = {
.sett = {
NULL, /* Reserved */
NULL, /* Command Registers */
NULL, /* Touch Report */
NULL, /* Cypress Data Record */
NULL, /* Test Record */
NULL, /* Panel Configuration Record */
&cyttsp4_sett_param_regs,
&cyttsp4_sett_param_size,
NULL, /* Reserved */
NULL, /* Reserved */
NULL, /* Operational Configuration Record */
&cyttsp4_sett_ddata, /* Design Data Record */
&cyttsp4_sett_mdata, /* Manufacturing Data Record */
},
.fw = &cyttsp4_firmware,
.frmwrk = &cyttsp4_framework,
.addr = {CY_I2C_TCH_ADR, CY_I2C_LDR_ADR},
.flags = /*0x01 | 0x02 | */0x20 | 0x40,
.hw_reset = cyttsp4_hw_reset,
.hw_recov = cyttsp4_hw_recov,
.irq_stat = cyttsp4_irq_stat,
};
#endif
/*novatek nt11003 touchpad*/
#if defined (CONFIG_TOUCHSCREEN_NOVATEK)
#define TOUCH_NOVATEK_RESET_PIN RK30_PIN4_PD0
#define TOUCH_NOVATEK_INT_PIN RK30_PIN4_PC2
static u8 novatek_gpio_init_status = 0;
static int novatek_exit_platform_hw(void)
{
if (novatek_gpio_init_status & (1<<0)) {
gpio_free(TOUCH_NOVATEK_INT_PIN);
}
if (novatek_gpio_init_status & (1<<1)) {
gpio_free(TOUCH_NOVATEK_RESET_PIN);
}
novatek_gpio_init_status = 0;
}
static int novatek_init_platform_hw(void)
{
s32 ret = 0;
/* request interrupt */
if((ret = gpio_request(TOUCH_NOVATEK_INT_PIN, NULL)) != 0)
{
printk("%s,%s,gpio request error!3\n", __LINE__, __FUNCTION__);
goto exit_novatek_init;
}
novatek_gpio_init_status |= (1 << 0);
/* set reset pin */
if((ret = gpio_request(TOUCH_NOVATEK_RESET_PIN, NULL)) != 0)
{
printk("%s,%s,gpio request error!4\n", __LINE__, __FUNCTION__);
goto exit_novatek_init;
}
novatek_gpio_init_status |= (1 << 1);
gpio_direction_output(TOUCH_NOVATEK_RESET_PIN, GPIO_LOW);
mdelay(100);
gpio_set_value(TOUCH_NOVATEK_RESET_PIN, GPIO_HIGH);
mdelay(100);
exit_novatek_init:
if (ret < 0) {
novatek_exit_platform_hw();
}
return ret;
}
static struct novatek_i2c_platform_data novatek_info = {
.version = 11003,
.ts_init_platform_hw = novatek_init_platform_hw,
.ts_exit_platform_hw = novatek_exit_platform_hw,
.gpio_rst = TOUCH_NOVATEK_RESET_PIN,
.gpio_irq = TOUCH_NOVATEK_INT_PIN,
.irq_edge = 1,
.screen_max_x = 1024,
.screen_max_y = 768,
};
#endif
/*ft5x0x touchpad*/
#if defined (CONFIG_TOUCHSCREEN_FT5306)
#define TOUCH_FT5X0X_RESET_PIN RK30_PIN4_PD0
#define TOUCH_FT5X0X_INT_PIN RK30_PIN4_PC2
#define TOUCH_FT5X0X_PWR_PIN INVALID_GPIO
static u8 ft5x0x_gpio_init_status = 0;
static int ft5x0x_exit_platform_hw(void)
{
if (ft5x0x_gpio_init_status & (1<<0)) {
gpio_free(TOUCH_FT5X0X_INT_PIN);
}
if (ft5x0x_gpio_init_status & (1<<1)) {
gpio_free(TOUCH_FT5X0X_RESET_PIN);
}
if (ft5x0x_gpio_init_status & (1<<2)) {
gpio_free(TOUCH_FT5X0X_PWR_PIN);
}
ft5x0x_gpio_init_status = 0;
}
static int ft5x0x_init_platform_hw(void)
{
s32 ret = 0;
#if defined (CONFIG_MFD_WM831X)
struct regulator *ldo;
ldo = regulator_get(NULL, "ldo9"); //vcc_tp
regulator_set_voltage(ldo, 2800000, 2800000);
regulator_set_suspend_voltage(ldo, 2800000);
regulator_disable(ldo);
// printk("%s set ldo9 vcc_tp=%dmV end\n", __func__, regulator_get_voltage(ldo));
regulator_put(ldo);
mdelay(100);
#endif
#if defined (CONFIG_MFD_TPS65910)
struct regulator *ldo;
ldo = regulator_get(NULL, "vaux33"); //vcc_tp
regulator_set_voltage(ldo, 2800000, 2800000);
regulator_set_suspend_voltage(ldo, 2800000);
regulator_disable(ldo);
printk("%s set vaux33 vcc_tp=%dmV end\n", __func__, regulator_get_voltage(ldo));
regulator_put(ldo);
mdelay(100);
#endif
/* request power enable */
if (TOUCH_FT5X0X_PWR_PIN != INVALID_GPIO) {
if((ret = gpio_request(TOUCH_FT5X0X_PWR_PIN, NULL)) != 0)
{
printk("%s,%s,gpio request error!3\n", __LINE__, __FUNCTION__);
goto exit_ft5x0x_init;
}
ft5x0x_gpio_init_status |= (1 << 2);
}
/* request interrupt */
if((ret = gpio_request(TOUCH_FT5X0X_INT_PIN, NULL)) != 0)
{
printk("%s,%s,gpio request error!3\n", __LINE__, __FUNCTION__);
goto exit_ft5x0x_init;
}
ft5x0x_gpio_init_status |= (1 << 0);
//gpio_pull_updown(RK29_PIN0_PA2, 1);
/* set reset pin */
if((ret = gpio_request(TOUCH_FT5X0X_RESET_PIN, NULL)) != 0)
{
printk("%s,%s,gpio request error!4\n", __LINE__, __FUNCTION__);
goto exit_ft5x0x_init;
}
ft5x0x_gpio_init_status |= (1 << 1);
gpio_direction_output(TOUCH_FT5X0X_PWR_PIN, 1);
gpio_direction_output(TOUCH_FT5X0X_RESET_PIN, GPIO_LOW);
mdelay(100);
gpio_set_value(TOUCH_FT5X0X_RESET_PIN, GPIO_HIGH);
mdelay(100);
exit_ft5x0x_init:
if (ret < 0) {
ft5x0x_exit_platform_hw();
}
#if defined (CONFIG_MFD_TPS65910)
ldo = regulator_get(NULL, "vaux33"); //vcc_tp
regulator_set_voltage(ldo, 2800000, 2800000);
regulator_set_suspend_voltage(ldo, 2800000);
regulator_enable(ldo);
printk("%s set vaux33 vcc_tp=%dmV end\n", __func__, regulator_get_voltage(ldo));
regulator_put(ldo);
mdelay(100);
#endif
#if defined (CONFIG_MFD_WM831X)
ldo = regulator_get(NULL, "ldo9"); //vcc_tp
regulator_set_voltage(ldo, 2800000, 2800000);
regulator_set_suspend_voltage(ldo, 2800000);
regulator_enable(ldo);
// printk("%s set ldo9 vcc_tp=%dmV end\n", __func__, regulator_get_voltage(ldo));
regulator_put(ldo);
mdelay(100);
#endif
return ret;
}
static struct ft5x0x_platform_data ft5x0x_info = {
.model= 5006,
.init_platform_hw= ft5x0x_init_platform_hw,
.exit_platform_hw= ft5x0x_exit_platform_hw,
};
#endif
#if defined(CONFIG_TOUCHSCREEN_GT8XX)
#define TOUCH_RESET_PIN RK30_PIN4_PD0
#define TOUCH_PWR_PIN INVALID_GPIO
int goodix_init_platform_hw(void)
{
int ret;
rk30_mux_api_set(GPIO4D0_SMCDATA8_TRACEDATA8_NAME, GPIO4D_GPIO4D0);
rk30_mux_api_set(GPIO4C2_SMCDATA2_TRACEDATA2_NAME, GPIO4C_GPIO4C2);
printk("%s:0x%x,0x%x\n",__func__,rk30_mux_api_get(GPIO4D0_SMCDATA8_TRACEDATA8_NAME),rk30_mux_api_get(GPIO4C2_SMCDATA2_TRACEDATA2_NAME));
if (TOUCH_PWR_PIN != INVALID_GPIO) {
ret = gpio_request(TOUCH_PWR_PIN, "goodix power pin");
if (ret != 0) {
gpio_free(TOUCH_PWR_PIN);
printk("goodix power error\n");
return -EIO;
}
gpio_direction_output(TOUCH_PWR_PIN, 0);
gpio_set_value(TOUCH_PWR_PIN, GPIO_LOW);
msleep(100);
}
if (TOUCH_RESET_PIN != INVALID_GPIO) {
ret = gpio_request(TOUCH_RESET_PIN, "goodix reset pin");
if (ret != 0) {
gpio_free(TOUCH_RESET_PIN);
printk("goodix gpio_request error\n");
return -EIO;
}
gpio_direction_output(TOUCH_RESET_PIN, 1);
msleep(100);
//gpio_set_value(TOUCH_RESET_PIN, GPIO_LOW);
//msleep(100);
//gpio_set_value(TOUCH_RESET_PIN, GPIO_HIGH);
//msleep(500);
}
return 0;
}
struct goodix_platform_data goodix_info = {
.model = 8105,
.irq_pin = RK30_PIN4_PC2,
.rest_pin = TOUCH_RESET_PIN,
.init_platform_hw = goodix_init_platform_hw,
};
#endif
#if defined (CONFIG_TOUCHSCREEN_BYD693X)
#define BYD_BF693X_MODEL_NAME 14
#define BYD_BF693X_TOUCH_POWER_PIN RK30_PIN2_PC2
#define BYD_BF693X_TOUCH_RESET_PIN INVALID_GPIO
#define BYD_BF693X_TOUCH_INT_PIN RK30_PIN4_PC2
int tp_probe_flag;
int get_probe_state(void)
{
return tp_probe_flag;
}
void set_probe_state(int state)
{
tp_probe_flag = state;
}
static struct byd_platform_data byd693x_info = {
.get_probe_state = get_probe_state,
.set_probe_state = set_probe_state,
.model = BYD_BF693X_MODEL_NAME,
.pwr_pin = BYD_BF693X_TOUCH_POWER_PIN,
.rst_pin = BYD_BF693X_TOUCH_RESET_PIN,
.int_pin = BYD_BF693X_TOUCH_INT_PIN,
.pwr_on_value = 0,
.tp_flag = 0,
.screen_max_x = 800,
.screen_max_y = 480,
.swap_xy = 0,
.xpol = 1,
.ypol = 0,
};
#endif
#if defined (CONFIG_TOUCHSCREEN_BF6931A)
#define TOUCH_PWR_PIN RK30_PIN2_PC2
#define TOUCH_INT_PIN RK30_PIN4_PC2
int bf6931a_init_platform_hw(void)
{
printk("bf6931a_init_platform_hw\n");
if(gpio_request(TOUCH_PWR_PIN,NULL) != 0){
gpio_free(TOUCH_PWR_PIN);
printk("bf6931a_init_platform_hw gpio_request error\n");
return -EIO;
}
if(gpio_request(TOUCH_INT_PIN,NULL) != 0){
gpio_free(TOUCH_INT_PIN);
printk("bf6931a_init_platform_hw gpio_request error\n");
return -EIO;
}
gpio_direction_output(TOUCH_PWR_PIN, 1);
mdelay(10);
gpio_direction_input(TOUCH_INT_PIN);
msleep(300);
return 0;
}
void bf6931a_exit_platform_hw(void)
{
printk("bf6931a_exit_platform_hw\n");
gpio_free(TOUCH_PWR_PIN);
gpio_free(TOUCH_INT_PIN);
}
int bf6931a_platform_sleep(void)
{
printk("bf6931a_platform_sleep\n");
//gpio_set_value(TOUCH_RESET_PIN,GPIO_LOW);
return 0;
}
int bf6931a_platform_wakeup(void)
{
printk("bf6931a_platform_wakeup\n");
gpio_set_value(TOUCH_PWR_PIN,GPIO_HIGH);
msleep(300);
return 0;
}
struct bf6931a_platform_data bf6931a_info = {
.init_platform_hw= bf6931a_init_platform_hw,
.exit_platform_hw= bf6931a_exit_platform_hw,
.bf6931a_platform_sleep = bf6931a_platform_sleep,
.bf6931a_platform_wakeup = bf6931a_platform_wakeup,
};
#endif
static struct spi_board_info board_spi_devices[] = {
};
/***********************************************************
* rk30 backlight
************************************************************/
#ifdef CONFIG_BACKLIGHT_RK29_BL
#define PWM_ID 2
#define PWM_MUX_NAME GPIO0D6_PWM2_NAME
#define PWM_MUX_MODE GPIO0D_PWM2
#define PWM_MUX_MODE_GPIO GPIO0D_GPIO0D6
#define PWM_GPIO RK30_PIN0_PD6
#define PWM_EFFECT_VALUE 0
#define LCD_DISP_ON_PIN
#ifdef LCD_DISP_ON_PIN
//#define BL_EN_MUX_NAME GPIOF34_UART3_SEL_NAME
//#define BL_EN_MUX_MODE IOMUXB_GPIO1_B34
#define BL_EN_PIN RK30_PIN6_PB3
#define BL_EN_VALUE GPIO_HIGH
#endif
static int rk29_backlight_io_init(void)
{
int ret = 0;
rk30_mux_api_set(PWM_MUX_NAME, PWM_MUX_MODE);
#ifdef LCD_DISP_ON_PIN
// rk30_mux_api_set(BL_EN_MUX_NAME, BL_EN_MUX_MODE);
ret = gpio_request(BL_EN_PIN, NULL);
if (ret != 0) {
gpio_free(BL_EN_PIN);
}
gpio_direction_output(BL_EN_PIN, 0);
gpio_set_value(BL_EN_PIN, !BL_EN_VALUE);
#endif
return ret;
}
static int rk29_backlight_io_deinit(void)
{
int ret = 0;
#ifdef LCD_DISP_ON_PIN
gpio_free(BL_EN_PIN);
#endif
rk30_mux_api_set(PWM_MUX_NAME, PWM_MUX_MODE_GPIO);
return ret;
}
static int rk29_backlight_pwm_suspend(void)
{
int ret = 0;
rk30_mux_api_set(PWM_MUX_NAME, PWM_MUX_MODE_GPIO);
if (gpio_request(PWM_GPIO, NULL)) {
printk("func %s, line %d: request gpio fail\n", __FUNCTION__, __LINE__);
return -1;
}
gpio_direction_output(PWM_GPIO, GPIO_LOW);
#ifdef LCD_DISP_ON_PIN
gpio_direction_output(BL_EN_PIN, 0);
gpio_set_value(BL_EN_PIN, !BL_EN_VALUE);
#endif
return ret;
}
static int rk29_backlight_pwm_resume(void)
{
gpio_free(PWM_GPIO);
rk30_mux_api_set(PWM_MUX_NAME, PWM_MUX_MODE);
#ifdef LCD_DISP_ON_PIN
msleep(30);
gpio_direction_output(BL_EN_PIN, 1);
gpio_set_value(BL_EN_PIN, BL_EN_VALUE);
#endif
return 0;
}
static struct rk29_bl_info rk29_bl_info = {
.pwm_id = PWM_ID,
.bl_ref = PWM_EFFECT_VALUE,
.io_init = rk29_backlight_io_init,
.io_deinit = rk29_backlight_io_deinit,
.min_brightness = 80,
.pwm_suspend = rk29_backlight_pwm_suspend,
.pwm_resume = rk29_backlight_pwm_resume,
};
static struct platform_device rk29_device_backlight = {
.name = "rk29_backlight",
.id = -1,
.dev = {
.platform_data = &rk29_bl_info,
}
};
#endif
#ifdef CONFIG_RK29_SUPPORT_MODEM
#define RK30_MODEM_POWER RK30_PIN4_PD1
#define RK30_MODEM_POWER_IOMUX rk29_mux_api_set(GPIO4D1_SMCDATA9_TRACEDATA9_NAME, GPIO4D_GPIO4D1)
static int rk30_modem_io_init(void)
{
printk("%s\n", __FUNCTION__);
RK30_MODEM_POWER_IOMUX;
return 0;
}
static struct rk29_io_t rk30_modem_io = {
.io_addr = RK30_MODEM_POWER,
.enable = GPIO_HIGH,
.disable = GPIO_LOW,
.io_init = rk30_modem_io_init,
};
static struct platform_device rk30_device_modem = {
.name = "rk30_modem",
.id = -1,
.dev = {
.platform_data = &rk30_modem_io,
}
};
#endif
#if defined(CONFIG_MU509)
static int mu509_io_init(void)
{
rk30_mux_api_set(GPIO2B6_LCDC1DATA14_SMCADDR18_TSSYNC_NAME, GPIO2B_GPIO2B6);
rk30_mux_api_set(GPIO4D2_SMCDATA10_TRACEDATA10_NAME, GPIO4D_GPIO4D2);
rk30_mux_api_set(GPIO2B7_LCDC1DATA15_SMCADDR19_HSADCDATA7_NAME, GPIO2B_GPIO2B7);
rk30_mux_api_set(GPIO2C0_LCDCDATA16_GPSCLK_HSADCCLKOUT_NAME, GPIO2C_GPIO2C0);
return 0;
}
static int mu509_io_deinit(void)
{
return 0;
}
struct rk29_mu509_data rk29_mu509_info = {
.io_init = mu509_io_init,
.io_deinit = mu509_io_deinit,
.modem_power_en = RK30_PIN6_PB2,//RK30_PIN4_PD1,
.bp_power = RK30_PIN2_PB6,//RK30_PIN4_PD1,
.bp_reset = RK30_PIN4_PD2,
.ap_wakeup_bp = RK30_PIN2_PB7,
.bp_wakeup_ap = RK30_PIN6_PA0,
};
struct platform_device rk29_device_mu509 = {
.name = "mu509",
.id = -1,
.dev = {
.platform_data = &rk29_mu509_info,
}
};
#endif
#if defined(CONFIG_MW100)
static int mw100_io_init(void)
{
rk30_mux_api_set(GPIO2B6_LCDC1DATA14_SMCADDR18_TSSYNC_NAME, GPIO2B_GPIO2B6);
rk30_mux_api_set(GPIO4D2_SMCDATA10_TRACEDATA10_NAME, GPIO4D_GPIO4D2);
rk30_mux_api_set(GPIO2B7_LCDC1DATA15_SMCADDR19_HSADCDATA7_NAME, GPIO2B_GPIO2B7);
rk30_mux_api_set(GPIO2C0_LCDCDATA16_GPSCLK_HSADCCLKOUT_NAME, GPIO2C_GPIO2C0);
return 0;
}
static int mw100_io_deinit(void)
{
return 0;
}
struct rk29_mw100_data rk29_mw100_info = {
.io_init = mw100_io_init,
.io_deinit = mw100_io_deinit,
.modem_power_en = RK30_PIN6_PB2,
.bp_power = RK30_PIN2_PB6,
.bp_reset = RK30_PIN4_PD2,
.ap_wakeup_bp = RK30_PIN2_PB7,
.bp_wakeup_ap = RK30_PIN6_PA0,
};
struct platform_device rk29_device_mw100 = {
.name = "mw100",
.id = -1,
.dev = {
.platform_data = &rk29_mw100_info,
}
};
#endif
#if defined(CONFIG_MT6229)
static int mt6229_io_init(void)
{
rk30_mux_api_set(GPIO2B6_LCDC1DATA14_SMCADDR18_TSSYNC_NAME, GPIO2B_GPIO2B6);
rk30_mux_api_set(GPIO4D2_SMCDATA10_TRACEDATA10_NAME, GPIO4D_GPIO4D2);
rk30_mux_api_set(GPIO2B7_LCDC1DATA15_SMCADDR19_HSADCDATA7_NAME, GPIO2B_GPIO2B7);
rk30_mux_api_set(GPIO2C0_LCDCDATA16_GPSCLK_HSADCCLKOUT_NAME, GPIO2C_GPIO2C0);
rk30_mux_api_set(GPIO2C1_LCDC1DATA17_SMCBLSN0_HSADCDATA6_NAME, GPIO2C_GPIO2C1);
rk30_mux_api_set(GPIO2C1_LCDC1DATA17_SMCBLSN0_HSADCDATA6_NAME, GPIO2C_GPIO2C1);
return 0;
return 0;
}
static int mt6229_io_deinit(void)
{
return 0;
}
struct rk29_mt6229_data rk29_mt6229_info = {
.io_init = mt6229_io_init,
.io_deinit = mt6229_io_deinit,
.modem_power_en = RK30_PIN6_PB2,
.bp_power = RK30_PIN2_PB6,
.modem_usb_en = RK30_PIN2_PC0,
.modem_uart_en = RK30_PIN2_PC1,
.bp_wakeup_ap = RK30_PIN6_PA1,
.ap_ready = RK30_PIN2_PB7,
};
struct platform_device rk29_device_mt6229 = {
.name = "mt6229",
.id = -1,
.dev = {
.platform_data = &rk29_mt6229_info,
}
};
#endif
#if defined(CONFIG_SEW868)
static int sew868_io_init(void)
{
rk30_mux_api_set(GPIO2B6_LCDC1DATA14_SMCADDR18_TSSYNC_NAME, GPIO2B_GPIO2B6);
rk30_mux_api_set(GPIO4D2_SMCDATA10_TRACEDATA10_NAME, GPIO4D_GPIO4D2);
rk30_mux_api_set(GPIO4D4_SMCDATA12_TRACEDATA12_NAME, GPIO4D_GPIO4D4);
return 0;
}
static int sew868_io_deinit(void)
{
return 0;
}
struct rk30_sew868_data rk30_sew868_info = {
.io_init = sew868_io_init,
.io_deinit = sew868_io_deinit,
.bp_power = RK30_PIN6_PB2,
.bp_power_active_low = 1,
.bp_sys = RK30_PIN2_PB6,
.bp_reset = RK30_PIN4_PD2,
.bp_reset_active_low = 1,
.bp_wakeup_ap = RK30_PIN4_PD4,
.ap_wakeup_bp = NULL,
};
struct platform_device rk30_device_sew868 = {
.name = "sew868",
.id = -1,
.dev = {
.platform_data = &rk30_sew868_info,
}
};
#endif
/*MMA7660gsensor*/
#if defined (CONFIG_GS_MMA7660)
#define MMA8452_INT_PIN RK30_PIN4_PC0
static int mma8452_init_platform_hw(void)
{
rk30_mux_api_set(GPIO4C0_SMCDATA0_TRACEDATA0_NAME, GPIO4C_GPIO4C0);
if (gpio_request(MMA8452_INT_PIN, NULL) != 0) {
gpio_free(MMA8452_INT_PIN);
printk("mma8452_init_platform_hw gpio_request error\n");
return -EIO;
}
gpio_pull_updown(MMA8452_INT_PIN, 1);
return 0;
}
static struct gsensor_platform_data mma8452_info = {
.model = 8452,
.swap_xy = 0,
.swap_xyz = 1,
.init_platform_hw = mma8452_init_platform_hw,
.orientation = {-1, 0, 0, 0, 0, 1, 0, -1, 0},
};
#endif
/*MMA8452 gsensor*/
#if defined (CONFIG_GS_MMA8452)
#define MMA8452_INT_PIN RK30_PIN4_PC0
static int mma8452_init_platform_hw(void)
{
rk30_mux_api_set(GPIO4C0_SMCDATA0_TRACEDATA0_NAME, GPIO4C_GPIO4C0);
return 0;
}
static struct sensor_platform_data mma8452_info = {
.type = SENSOR_TYPE_ACCEL,
.irq_enable = 1,
.poll_delay_ms = 30,
.init_platform_hw = mma8452_init_platform_hw,
.orientation = {-1, 0, 0, 0, 0, 1, 0, -1, 0},
};
#endif
#if defined (CONFIG_GS_LIS3DH)
#define LIS3DH_INT_PIN RK30_PIN4_PC0
static int lis3dh_init_platform_hw(void)
{
rk30_mux_api_set(GPIO4C0_SMCDATA0_TRACEDATA0_NAME, GPIO4C_GPIO4C0);
return 0;
}
static struct sensor_platform_data lis3dh_info = {
.type = SENSOR_TYPE_ACCEL,
.irq_enable = 1,
.poll_delay_ms = 30,
.init_platform_hw = lis3dh_init_platform_hw,
.orientation = {-1, 0, 0, 0, 0, 1, 0, -1, 0},
};
#endif
#if defined(CONFIG_CHARGER_SMB347)
struct smb347_info smb347_info = {
.chg_en_pin = RK30_PIN4_PD5, // charge enable pin (smb347's c4 pin)
.chg_ctl_pin = RK30_PIN6_PB2, // charge control pin (smb347's d2 pin)
.chg_stat_pin = RK30_PIN4_PD6, // charge stat pin (smb347's f5 pin)
.chg_susp_pin = RK30_PIN4_PD7, // charge usb suspend pin (smb347's d3 pin)
.max_current = 1800, // dc and hc input current limit can set 300/500/700/900/1200/1500/1800/2000/2200/2500(ma)
.otg_power_form_smb = 0, // if otg 5v power form smb347 set 1 otherwise set 0
};
#endif
#if defined (CONFIG_COMPASS_AK8975)
static struct sensor_platform_data akm8975_info =
{
.type = SENSOR_TYPE_COMPASS,
.irq_enable = 1,
.poll_delay_ms = 30,
.m_layout =
{
{
{1, 0, 0},
{0, 1, 0},
{0, 0, 1},
},
{
{1, 0, 0},
{0, 1, 0},
{0, 0, 1},
},
{
{1, 0, 0},
{0, 1, 0},
{0, 0, 1},
},
{
{1, 0, 0},
{0, 1, 0},
{0, 0, 1},
},
}
};
#endif
#if defined(CONFIG_GYRO_L3G4200D)
#include <linux/l3g4200d.h>
#define L3G4200D_INT_PIN RK30_PIN4_PC3
static int l3g4200d_init_platform_hw(void)
{
rk30_mux_api_set(GPIO4C3_SMCDATA3_TRACEDATA3_NAME, GPIO4C_GPIO4C3);
return 0;
}
static struct sensor_platform_data l3g4200d_info = {
.type = SENSOR_TYPE_GYROSCOPE,
.irq_enable = 1,
.poll_delay_ms = 30,
.orientation = {0, 1, 0, -1, 0, 0, 0, 0, 1},
.init_platform_hw = l3g4200d_init_platform_hw,
.x_min = 40,//x_min,y_min,z_min = (0-100) according to hardware
.y_min = 40,
.z_min = 20,
};
#endif
#ifdef CONFIG_LS_CM3217
static struct sensor_platform_data cm3217_info = {
.type = SENSOR_TYPE_LIGHT,
.irq_enable = 0,
.poll_delay_ms = 500,
};
#endif
#ifdef CONFIG_FB_ROCKCHIP
#ifdef CONFIG_MFD_RK610
#define LCD_CS_MUX_NAME GPIO1C3_CIFDATA5_RMIITXD0_NAME
#define LCD_CS_PIN RK30_PIN1_PC3
#define LCD_CS_VALUE GPIO_HIGH
#define LCD_STB_MUX_NAME GPIO2C6_LCDC1DATA22_SPI1RXD_HSADCDATA3_NAME
#define LCD_STB_PIN RK30_PIN2_PC6
#define LCD_STB_VALUE GPIO_HIGH
#define LCD_EN_MUX_NAME GPIO4C7_SMCDATA7_TRACEDATA7_NAME
#define LCD_EN_PIN RK30_PIN6_PB0
#define LCD_EN_VALUE GPIO_LOW
#else
#define LCD_CS_MUX_NAME GPIO4C7_SMCDATA7_TRACEDATA7_NAME
#define LCD_CS_PIN RK30_PIN4_PC7
#define LCD_CS_VALUE GPIO_HIGH
#define LCD_EN_MUX_NAME GPIO4C7_SMCDATA7_TRACEDATA7_NAME
#define LCD_EN_PIN RK30_PIN6_PB4
#define LCD_EN_VALUE GPIO_LOW
#endif
static int rk_fb_io_init(struct rk29_fb_setting_info *fb_setting)
{
int ret = 0;
#ifdef CONFIG_MFD_RK610
rk30_mux_api_set(LCD_CS_MUX_NAME, GPIO1C_GPIO1C3);
#else
rk30_mux_api_set(LCD_CS_MUX_NAME, GPIO4C_GPIO4C7);
#endif
ret = gpio_request(LCD_CS_PIN, NULL);
if (ret != 0)
{
gpio_free(LCD_CS_PIN);
printk(KERN_ERR "request lcd cs pin fail!\n");
return -1;
}
else
{
gpio_direction_output(LCD_CS_PIN, LCD_CS_VALUE);
}
#ifdef CONFIG_MFD_RK610
rk30_mux_api_set(LCD_STB_MUX_NAME, GPIO2C_GPIO2C6);
ret = gpio_request(LCD_STB_PIN, NULL);
if (ret != 0)
{
gpio_free(LCD_STB_PIN);
printk(KERN_ERR "request lcd stb pin fail!\n");
return -1;
}
else
{
gpio_direction_output(LCD_STB_PIN, LCD_STB_VALUE);
}
#endif
ret = gpio_request(LCD_EN_PIN, NULL);
if (ret != 0)
{
gpio_free(LCD_EN_PIN);
printk(KERN_ERR "request lcd en pin fail!\n");
return -1;
}
else
{
gpio_direction_output(LCD_EN_PIN, LCD_EN_VALUE);
}
return 0;
}
static int rk_fb_io_disable(void)
{
gpio_set_value(LCD_CS_PIN, LCD_CS_VALUE? 0:1);
gpio_set_value(LCD_EN_PIN, LCD_EN_VALUE? 0:1);
#ifdef CONFIG_MFD_RK610
gpio_direction_output(LCD_STB_PIN, LCD_STB_VALUE? 0:1);
#endif
return 0;
}
static int rk_fb_io_enable(void)
{
#ifdef CONFIG_MFD_RK610
gpio_direction_output(LCD_STB_PIN, LCD_STB_VALUE);
#endif
#ifdef CONFIG_MALATA_C1006
gpio_set_value(LCD_EN_PIN, LCD_EN_VALUE);
mdelay(100);
gpio_set_value(LCD_CS_PIN, LCD_CS_VALUE);
#else
gpio_set_value(LCD_CS_PIN, LCD_CS_VALUE);
gpio_set_value(LCD_EN_PIN, LCD_EN_VALUE);
#endif
return 0;
}
static int rk_fb_io_deinit(void)
{
printk("%s enter!\n", __FUNCTION__);
rk29_backlight_pwm_suspend();
gpio_direction_output(LCD_CS_PIN, !LCD_CS_VALUE);
gpio_set_value(LCD_CS_PIN, !LCD_CS_VALUE);
mdelay(50);
gpio_direction_output(LCD_EN_PIN, !LCD_EN_VALUE);
gpio_set_value(LCD_EN_PIN, !LCD_EN_VALUE);
mdelay(500);
return 0;
}
#if defined(CONFIG_LCDC0_RK30)
struct rk29fb_info lcdc0_screen_info = {
.prop = PRMRY, //primary display device
.io_init = rk_fb_io_init,
.io_deinit = rk_fb_io_deinit,
.io_disable = rk_fb_io_disable,
.io_enable = rk_fb_io_enable,
.set_screen_info = set_lcd_info,
};
#endif
#if defined(CONFIG_LCDC1_RK30)
struct rk29fb_info lcdc1_screen_info = {
#if defined(CONFIG_HDMI_RK30)
.prop = EXTEND, //extend display device
.lcd_info = NULL,
.set_screen_info = hdmi_init_lcdc,
#endif
};
#endif
static struct resource resource_fb[] = {
[0] = {
.name = "fb0 buf",
.start = 0,
.end = 0,//RK30_FB0_MEM_SIZE - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.name = "ipp buf", //for rotate
.start = 0,
.end = 0,//RK30_FB0_MEM_SIZE - 1,
.flags = IORESOURCE_MEM,
},
[2] = {
.name = "fb2 buf",
.start = 0,
.end = 0,//RK30_FB0_MEM_SIZE - 1,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device device_fb = {
.name = "rk-fb",
.id = -1,
.num_resources = ARRAY_SIZE(resource_fb),
.resource = resource_fb,
};
#endif
#ifdef CONFIG_ANDROID_TIMED_GPIO
static struct timed_gpio timed_gpios[] = {
{
.name = "vibrator",
.gpio = RK30_PIN0_PA4,
.max_timeout = 1000,
.active_low = 0,
.adjust_time =20, //adjust for diff product
},
};
static struct timed_gpio_platform_data rk29_vibrator_info = {
.num_gpios = 1,
.gpios = timed_gpios,
};
static struct platform_device rk29_device_vibrator = {
.name = "timed-gpio",
.id = -1,
.dev = {
.platform_data = &rk29_vibrator_info,
},
};
#endif
#ifdef CONFIG_LEDS_GPIO_PLATFORM
static struct gpio_led rk29_leds[] = {
{
.name = "button-backlight",
.gpio = RK30_PIN4_PD7,
.default_trigger = "timer",
.active_low = 0,
.retain_state_suspended = 0,
.default_state = LEDS_GPIO_DEFSTATE_OFF,
},
};
static struct gpio_led_platform_data rk29_leds_pdata = {
.leds = rk29_leds,
.num_leds = ARRAY_SIZE(rk29_leds),
};
static struct platform_device rk29_device_gpio_leds = {
.name = "leds-gpio",
.id = -1,
.dev = {
.platform_data = &rk29_leds_pdata,
},
};
#endif
#ifdef CONFIG_RK_IRDA
#define IRDA_IRQ_PIN RK30_PIN6_PA1
static int irda_iomux_init(void)
{
int ret = 0;
//irda irq pin
ret = gpio_request(IRDA_IRQ_PIN, NULL);
if (ret != 0) {
gpio_free(IRDA_IRQ_PIN);
printk(">>>>>> IRDA_IRQ_PIN gpio_request err \n ");
}
gpio_pull_updown(IRDA_IRQ_PIN, PullDisable);
gpio_direction_input(IRDA_IRQ_PIN);
return 0;
}
static int irda_iomux_deinit(void)
{
gpio_free(IRDA_IRQ_PIN);
return 0;
}
static struct irda_info rk29_irda_info = {
.intr_pin = IRDA_IRQ_PIN,
.iomux_init = irda_iomux_init,
.iomux_deinit = irda_iomux_deinit,
//.irda_pwr_ctl = bu92747guw_power_ctl,
};
static struct platform_device irda_device = {
#ifdef CONFIG_RK_IRDA_NET
.name = "rk_irda",
#else
.name = "bu92747_irda",
#endif
.id = -1,
.dev = {
.platform_data = &rk29_irda_info,
}
};
#endif
#ifdef CONFIG_ION
#define ION_RESERVE_SIZE (80 * SZ_1M)
static struct ion_platform_data rk30_ion_pdata = {
.nr = 1,
.heaps = {
{
.type = ION_HEAP_TYPE_CARVEOUT,
.id = ION_NOR_HEAP_ID,
.name = "norheap",
.size = ION_RESERVE_SIZE,
}
},
};
static struct platform_device device_ion = {
.name = "ion-rockchip",
.id = 0,
.dev = {
.platform_data = &rk30_ion_pdata,
},
};
#endif
/**************************************************************************************************
* SDMMC devices, include the module of SD,MMC,and sdio.noted by xbw at 2012-03-05
**************************************************************************************************/
#ifdef CONFIG_SDMMC_RK29
#include "board-rk30-sdk-sdmmc.c"
#if defined(CONFIG_SDMMC0_RK29_WRITE_PROTECT)
#define SDMMC0_WRITE_PROTECT_PIN RK30_PIN3_PB2 //According to your own project to set the value of write-protect-pin.
#endif
#if defined(CONFIG_SDMMC1_RK29_WRITE_PROTECT)
#define SDMMC1_WRITE_PROTECT_PIN RK30_PIN3_PB3 //According to your own project to set the value of write-protect-pin.
#endif
#define RK29SDK_WIFI_SDIO_CARD_DETECT_N RK30_PIN6_PB2
#define RK29SDK_WIFI_SDIO_CARD_INT RK30_PIN3_PD2
#define RK29SDK_SD_CARD_DETECT_N RK30_PIN3_PB6 //According to your own project to set the value of card-detect-pin.
#define RK29SDK_SD_CARD_INSERT_LEVEL GPIO_LOW // set the voltage of insert-card. Please pay attention to the default setting.
#endif //endif ---#ifdef CONFIG_SDMMC_RK29
#ifdef CONFIG_SDMMC0_RK29
static int rk29_sdmmc0_cfg_gpio(void)
{
#ifdef CONFIG_SDMMC_RK29_OLD
rk30_mux_api_set(GPIO3B1_SDMMC0CMD_NAME, GPIO3B_SDMMC0_CMD);
rk30_mux_api_set(GPIO3B0_SDMMC0CLKOUT_NAME, GPIO3B_SDMMC0_CLKOUT);
rk30_mux_api_set(GPIO3B2_SDMMC0DATA0_NAME, GPIO3B_SDMMC0_DATA0);
rk30_mux_api_set(GPIO3B3_SDMMC0DATA1_NAME, GPIO3B_SDMMC0_DATA1);
rk30_mux_api_set(GPIO3B4_SDMMC0DATA2_NAME, GPIO3B_SDMMC0_DATA2);
rk30_mux_api_set(GPIO3B5_SDMMC0DATA3_NAME, GPIO3B_SDMMC0_DATA3);
rk30_mux_api_set(GPIO3B6_SDMMC0DETECTN_NAME, GPIO3B_GPIO3B6);
rk30_mux_api_set(GPIO3A7_SDMMC0PWREN_NAME, GPIO3A_GPIO3A7);
gpio_request(RK30_PIN3_PA7, "sdmmc-power");
gpio_direction_output(RK30_PIN3_PA7, GPIO_LOW);
#else
rk29_sdmmc_set_iomux(0, 0xFFFF);
#if defined(CONFIG_SDMMC0_RK29_SDCARD_DET_FROM_GPIO)
rk30_mux_api_set(GPIO3B6_SDMMC0DETECTN_NAME, GPIO3B_GPIO3B6);
#else
rk30_mux_api_set(GPIO3B6_SDMMC0DETECTN_NAME, GPIO3B_SDMMC0_DETECT_N);
#endif
#if defined(CONFIG_SDMMC0_RK29_WRITE_PROTECT)
gpio_request(SDMMC0_WRITE_PROTECT_PIN, "sdmmc-wp");
gpio_direction_input(SDMMC0_WRITE_PROTECT_PIN);
#endif
#endif
return 0;
}
#define CONFIG_SDMMC0_USE_DMA
struct rk29_sdmmc_platform_data default_sdmmc0_data = {
.host_ocr_avail =
(MMC_VDD_25_26 | MMC_VDD_26_27 | MMC_VDD_27_28 | MMC_VDD_28_29 |
MMC_VDD_29_30 | MMC_VDD_30_31 | MMC_VDD_31_32 | MMC_VDD_32_33 |
MMC_VDD_33_34 | MMC_VDD_34_35 | MMC_VDD_35_36),
.host_caps =
(MMC_CAP_4_BIT_DATA | MMC_CAP_MMC_HIGHSPEED | MMC_CAP_SD_HIGHSPEED),
.io_init = rk29_sdmmc0_cfg_gpio,
#if !defined(CONFIG_SDMMC_RK29_OLD)
.set_iomux = rk29_sdmmc_set_iomux,
#endif
.dma_name = "sd_mmc",
#ifdef CONFIG_SDMMC0_USE_DMA
.use_dma = 1,
#else
.use_dma = 0,
#endif
#if defined(CONFIG_WIFI_COMBO_MODULE_CONTROL_FUNC)
.status = rk29sdk_wifi_mmc0_status,
.register_status_notify = rk29sdk_wifi_mmc0_status_register,
#endif
#if defined(CONFIG_SDMMC0_RK29_SDCARD_DET_FROM_GPIO)
.detect_irq = RK29SDK_SD_CARD_DETECT_N,
.insert_card_level = RK29SDK_SD_CARD_INSERT_LEVEL,
#else
.detect_irq = RK30_PIN3_PB6, // INVALID_GPIO
#endif
.enable_sd_wakeup = 0,
#if defined(CONFIG_SDMMC0_RK29_WRITE_PROTECT)
.write_prt = SDMMC0_WRITE_PROTECT_PIN,
#else
.write_prt = INVALID_GPIO,
#endif
};
#endif // CONFIG_SDMMC0_RK29
#ifdef CONFIG_SDMMC1_RK29
#define CONFIG_SDMMC1_USE_DMA
static int rk29_sdmmc1_cfg_gpio(void)
{
#if defined(CONFIG_SDMMC_RK29_OLD)
rk30_mux_api_set(GPIO3C0_SMMC1CMD_NAME, GPIO3C_SMMC1_CMD);
rk30_mux_api_set(GPIO3C5_SDMMC1CLKOUT_NAME, GPIO3C_SDMMC1_CLKOUT);
rk30_mux_api_set(GPIO3C1_SDMMC1DATA0_NAME, GPIO3C_SDMMC1_DATA0);
rk30_mux_api_set(GPIO3C2_SDMMC1DATA1_NAME, GPIO3C_SDMMC1_DATA1);
rk30_mux_api_set(GPIO3C3_SDMMC1DATA2_NAME, GPIO3C_SDMMC1_DATA2);
rk30_mux_api_set(GPIO3C4_SDMMC1DATA3_NAME, GPIO3C_SDMMC1_DATA3);
//rk30_mux_api_set(GPIO3C6_SDMMC1DETECTN_NAME, GPIO3C_SDMMC1_DETECT_N);
#else
#if defined(CONFIG_SDMMC1_RK29_WRITE_PROTECT)
gpio_request(SDMMC1_WRITE_PROTECT_PIN, "sdio-wp");
gpio_direction_input(SDMMC1_WRITE_PROTECT_PIN);
#endif
#endif
return 0;
}
struct rk29_sdmmc_platform_data default_sdmmc1_data = {
.host_ocr_avail =
(MMC_VDD_25_26 | MMC_VDD_26_27 | MMC_VDD_27_28 | MMC_VDD_28_29 |
MMC_VDD_29_30 | MMC_VDD_30_31 | MMC_VDD_31_32 | MMC_VDD_32_33 |
MMC_VDD_33_34),
#if !defined(CONFIG_USE_SDMMC1_FOR_WIFI_DEVELOP_BOARD)
.host_caps = (MMC_CAP_4_BIT_DATA | MMC_CAP_SDIO_IRQ |
MMC_CAP_MMC_HIGHSPEED | MMC_CAP_SD_HIGHSPEED),
#else
.host_caps =
(MMC_CAP_4_BIT_DATA | MMC_CAP_MMC_HIGHSPEED | MMC_CAP_SD_HIGHSPEED),
#endif
.io_init = rk29_sdmmc1_cfg_gpio,
#if !defined(CONFIG_SDMMC_RK29_OLD)
.set_iomux = rk29_sdmmc_set_iomux,
#endif
.dma_name = "sdio",
#ifdef CONFIG_SDMMC1_USE_DMA
.use_dma = 1,
#else
.use_dma = 0,
#endif
#if !defined(CONFIG_USE_SDMMC1_FOR_WIFI_DEVELOP_BOARD)
#if defined(CONFIG_WIFI_CONTROL_FUNC) || defined(CONFIG_WIFI_COMBO_MODULE_CONTROL_FUNC)
.status = rk29sdk_wifi_status,
.register_status_notify = rk29sdk_wifi_status_register,
#endif
#if defined(CONFIG_SDMMC0_RK29_SDCARD_DET_FROM_GPIO)
.detect_irq = INVALID_GPIO,//RK29SDK_WIFI_SDIO_CARD_DETECT_N,
#else
//.detect_irq = RK29SDK_WIFI_SDIO_CARD_DETECT_N,
#endif
#if defined(CONFIG_SDMMC1_RK29_WRITE_PROTECT)
.write_prt = SDMMC1_WRITE_PROTECT_PIN,
#else
.write_prt = INVALID_GPIO,
#endif
#if defined(CONFIG_RK29_SDIO_IRQ_FROM_GPIO)
.sdio_INT_gpio = RK29SDK_WIFI_SDIO_CARD_INT,
#endif
#else
.detect_irq = INVALID_GPIO,
.enable_sd_wakeup = 0,
#endif
};
#endif //endif--#ifdef CONFIG_SDMMC1_RK29
/**************************************************************************************************
* the end of setting for SDMMC devices
**************************************************************************************************/
#if defined(CONFIG_BATTERY_RK30_ADC)||defined(CONFIG_BATTERY_RK30_ADC_FAC)
static struct rk30_adc_battery_platform_data rk30_adc_battery_platdata = {
.dc_det_pin = RK30_PIN6_PA5,
.batt_low_pin = INVALID_GPIO,
.charge_set_pin = INVALID_GPIO,
.charge_ok_pin = RK30_PIN6_PA6,
.dc_det_level = GPIO_LOW,
.charge_ok_level = GPIO_HIGH,
};
static struct platform_device rk30_device_adc_battery = {
.name = "rk30-battery",
.id = -1,
.dev = {
.platform_data = &rk30_adc_battery_platdata,
},
};
#endif
#ifdef CONFIG_RK29_VMAC
#define PHY_PWR_EN_GPIO RK30_PIN1_PD6
#include "board-rk30-sdk-vmac.c"
#endif
#ifdef CONFIG_RFKILL_RK
// bluetooth rfkill device, its driver in net/rfkill/rfkill-rk.c
static struct rfkill_rk_platform_data rfkill_rk_platdata = {
.type = RFKILL_TYPE_BLUETOOTH,
.poweron_gpio = { // BT_REG_ON
.io = RK30_PIN3_PC7,
.enable = GPIO_HIGH,
.iomux = {
.name = GPIO3C7_SDMMC1WRITEPRT_NAME,
.fgpio = GPIO3C_GPIO3C7,
},
},
.reset_gpio = { // BT_RST
.io = RK30_PIN3_PD1, // set io to INVALID_GPIO for disable it
.enable = GPIO_LOW,
.iomux = {
.name = GPIO3D1_SDMMC1BACKENDPWR_NAME,
.fgpio = GPIO3D_GPIO3D1,
},
},
.wake_gpio = { // BT_WAKE, use to control bt's sleep and wakeup
.io = RK30_PIN3_PC6, // set io to INVALID_GPIO for disable it
.enable = GPIO_HIGH,
.iomux = {
.name = GPIO3C6_SDMMC1DETECTN_NAME,
.fgpio = GPIO3C_GPIO3C6,
},
},
.wake_host_irq = { // BT_HOST_WAKE, for bt wakeup host when it is in deep sleep
.gpio = {
.io = RK30_PIN6_PA7, // set io to INVALID_GPIO for disable it
.enable = GPIO_LOW, // set GPIO_LOW for falling, set 0 for rising
.iomux = {
.name = NULL,
},
},
},
.rts_gpio = { // UART_RTS, enable or disable BT's data coming
.io = RK30_PIN1_PA3, // set io to INVALID_GPIO for disable it
.enable = GPIO_LOW,
.iomux = {
.name = GPIO1A3_UART0RTSN_NAME,
.fgpio = GPIO1A_GPIO1A3,
.fmux = GPIO1A_UART0_RTS_N,
},
},
};
static struct platform_device device_rfkill_rk = {
.name = "rfkill_rk",
.id = -1,
.dev = {
.platform_data = &rfkill_rk_platdata,
},
};
#endif
#ifdef CONFIG_RK30_PWM_REGULATOR
const static int pwm_voltage_map[] = {
#ifdef CONFIG_KP_AXP20
1000000, 1050000, 1075000, 1100000, 1125000, 1150000, 1175000, 1200000, 1225000, 1250000, 1275000, 1300000, 1325000, 1350000, 1375000, 1400000, 1425000
#else
1000000, 1025000, 1050000, 1075000, 1100000, 1125000, 1150000, 1175000, 1200000, 1225000, 1250000, 1275000, 1300000, 1325000, 1350000, 1375000, 1400000
#endif
};
static struct regulator_consumer_supply pwm_dcdc1_consumers[] = {
{
.supply = "vdd_core",
}
};
struct regulator_init_data pwm_regulator_init_dcdc[1] =
{
{
.constraints = {
.name = "PWM_DCDC1",
.min_uV = 600000,
.max_uV = 1800000, //0.6-1.8V
.apply_uV = true,
.valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE,
},
.num_consumer_supplies = ARRAY_SIZE(pwm_dcdc1_consumers),
.consumer_supplies = pwm_dcdc1_consumers,
},
};
static struct pwm_platform_data pwm_regulator_info[1] = {
{
.pwm_id = 3,
.pwm_gpio = RK30_PIN0_PD7,
.pwm_iomux_name = GPIO0D7_PWM3_NAME,
.pwm_iomux_pwm = GPIO0D_PWM3,
.pwm_iomux_gpio = GPIO0D_GPIO0D6,
.pwm_voltage = 1100000,
.suspend_voltage = 1050000,
.min_uV = 1000000,
#ifdef CONFIG_KP_AXP20
.max_uV = 1425000,
#else
.max_uV = 1400000,
#endif
.coefficient = 455, //45.5%
.pwm_voltage_map = pwm_voltage_map,
.init_data = &pwm_regulator_init_dcdc[0],
},
};
#ifdef CONFIG_KP_AXP20
//-----------------
const static int pwm_voltage_map_1[] = {
1000000, 1050000, 1075000, 1100000, 1125000, 1150000, 1175000, 1200000, 1225000, 1250000, 1275000, 1300000, 1325000, 1350000, 1375000, 1400000, 1425000
};
static struct regulator_consumer_supply pwm_dcdc1_consumers_1[] = {
{
.supply = "vdd_cpu",
}
};
struct regulator_init_data pwm_regulator_init_dcdc_1[1] =
{
{
.constraints = {
.name = "PWM_DCDC1",
.min_uV = 600000,
.max_uV = 1800000, //0.6-1.8V
.apply_uV = true,
.valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE,
},
.num_consumer_supplies = ARRAY_SIZE(pwm_dcdc1_consumers_1),
.consumer_supplies = pwm_dcdc1_consumers_1,
},
};
static struct pwm_platform_data pwm_regulator_info_1[1] = {
{
.pwm_id = 0,
.pwm_gpio = RK30_PIN0_PA3,
.pwm_iomux_name = GPIO0A3_PWM0_NAME,
.pwm_iomux_pwm = GPIO0A_PWM0,
.pwm_iomux_gpio = GPIO0D_GPIO0D6,
.pwm_voltage = 1100000,
.suspend_voltage = 1050000,
.min_uV = 1000000,
.max_uV = 1425000,
.coefficient = 455, //45.5%
.pwm_voltage_map = pwm_voltage_map_1,
.init_data = &pwm_regulator_init_dcdc_1[0],
},
};
struct platform_device pwm_regulator_device[2] = {
{
.name = "pwm-voltage-regulator",
.id = 0,
.dev = {
.platform_data = &pwm_regulator_info[0],
}
},
{
.name = "pwm-voltage-regulator",
.id = 1,
.dev = {
.platform_data = &pwm_regulator_info_1[0],
}
},
};
#else
struct platform_device pwm_regulator_device[1] = {
{
.name = "pwm-voltage-regulator",
.id = 0,
.dev = {
.platform_data = &pwm_regulator_info[0],
}
},
};
#endif
#endif
static struct platform_device *devices[] __initdata = {
#ifdef CONFIG_BACKLIGHT_RK29_BL
&rk29_device_backlight,
#endif
#ifdef CONFIG_FB_ROCKCHIP
&device_fb,
#endif
#ifdef CONFIG_ION
&device_ion,
#endif
#ifdef CONFIG_ANDROID_TIMED_GPIO
&rk29_device_vibrator,
#endif
#ifdef CONFIG_LEDS_GPIO_PLATFORM
&rk29_device_gpio_leds,
#endif
#ifdef CONFIG_RK_IRDA
&irda_device,
#endif
#if defined(CONFIG_WIFI_CONTROL_FUNC)||defined(CONFIG_WIFI_COMBO_MODULE_CONTROL_FUNC)
&rk29sdk_wifi_device,
#endif
#ifdef CONFIG_RK29_SUPPORT_MODEM
&rk30_device_modem,
#endif
#if defined(CONFIG_MU509)
&rk29_device_mu509,
#endif
#if defined(CONFIG_MW100)
&rk29_device_mw100,
#endif
#if defined(CONFIG_MT6229)
&rk29_device_mt6229,
#endif
#if defined(CONFIG_SEW868)
&rk30_device_sew868,
#endif
#if defined(CONFIG_BATTERY_RK30_ADC)||defined(CONFIG_BATTERY_RK30_ADC_FAC)
&rk30_device_adc_battery,
#endif
#ifdef CONFIG_RFKILL_RK
&device_rfkill_rk,
#endif
#ifdef CONFIG_RK30_PWM_REGULATOR
&pwm_regulator_device[0],
#ifdef CONFIG_KP_AXP20
&pwm_regulator_device[1],
#endif
#endif
};
// i2c
#ifdef CONFIG_I2C0_RK30
static struct i2c_board_info __initdata i2c0_info[] = {
#if defined (CONFIG_GS_MMA8452)
{
.type = "gs_mma8452",
.addr = 0x1d,
.flags = 0,
.irq = MMA8452_INT_PIN,
.platform_data = &mma8452_info,
},
#endif
#if defined (CONFIG_GS_LIS3DH)
{
.type = "gs_lis3dh",
.addr = 0x19, //0x19(SA0-->VCC), 0x18(SA0-->GND)
.flags = 0,
.irq = LIS3DH_INT_PIN,
.platform_data = &lis3dh_info,
},
#endif
#if defined (CONFIG_GS_MMA7660)
{
.type = "gs_mma8452",
.addr = 0x4c,
.flags = 0,
.irq = MMA8452_INT_PIN,
.platform_data = &mma8452_info,
},
#endif
#if defined (CONFIG_COMPASS_AK8975)
{
.type = "ak8975",
.addr = 0x0d,
.flags = 0,
.irq = RK30_PIN4_PC1,
.platform_data = &akm8975_info,
},
#endif
#if defined (CONFIG_GYRO_L3G4200D)
{
.type = "l3g4200d_gryo",
.addr = 0x69,
.flags = 0,
.irq = L3G4200D_INT_PIN,
.platform_data = &l3g4200d_info,
},
#endif
#if defined (CONFIG_SND_SOC_RK1000)
{
.type = "rk1000_i2c_codec",
.addr = 0x60,
.flags = 0,
},
{
.type = "rk1000_control",
.addr = 0x40,
.flags = 0,
},
#endif
#if defined (CONFIG_SND_SOC_RT5631)
{
.type = "rt5631",
.addr = 0x1a,
.flags = 0,
},
#endif
#if defined (CONFIG_SND_SOC_RT5633)
{
.type = "rt5633",
.addr = 0x1c,
.flags = 0,
},
#endif
#ifdef CONFIG_MFD_RK610
{
.type = "rk610_ctl",
.addr = 0x40,
.flags = 0,
},
#ifdef CONFIG_RK610_TVOUT
{
.type = "rk610_tvout",
.addr = 0x42,
.flags = 0,
},
#endif
#ifdef CONFIG_HDMI_RK610
{
.type = "rk610_hdmi",
.addr = 0x46,
.flags = 0,
.irq = RK30_PIN6_PB4,
},
#endif
#ifdef CONFIG_SND_SOC_RK610
{//RK610_CODEC addr from 0x60 to 0x80 (0x60~0x80)
.type = "rk610_i2c_codec",
.addr = 0x60,
.flags = 0,
},
#endif
#endif
};
#endif
#define PMIC_TYPE_WM8326 1
#define PMIC_TYPE_TPS65910 2
int __sramdata g_pmic_type = 0;
#ifdef CONFIG_I2C1_RK30
#ifdef CONFIG_MFD_WM831X_I2C
#include "board-rk30-sdk-wm8326.c"
#endif
#ifdef CONFIG_MFD_TPS65910
#define TPS65910_HOST_IRQ RK30_PIN6_PA4
#include "board-rk30-sdk-tps65910.c"
#endif
#ifdef CONFIG_KP_AXP20
#include "../../../drivers/power/axp_power/axp-board.h"
#endif
static struct i2c_board_info __initdata i2c1_info[] = {
#if defined (CONFIG_MFD_WM831X_I2C)
{
.type = "wm8326",
.addr = 0x34,
.flags = 0,
.irq = RK30_PIN6_PA4,
.platform_data = &wm831x_platdata,
},
#endif
#if defined (CONFIG_CHARGER_SMB347)
{
.type = "smb347",
.addr = 0x06,
.flags = 0,
.platform_data = &smb347_info,
},
#endif
#if defined (CONFIG_KP_AXP20)
{
.type = "axp_mfd",
.addr = 0x34,
.flags = 0,
.irq =RK30_PIN6_PA4,
.platform_data = &axp_pdata,
},
#endif
#if defined (CONFIG_MFD_TPS65910)
{
.type = "tps65910",
.addr = TPS65910_I2C_ID0,
.flags = 0,
.irq = TPS65910_HOST_IRQ,
.platform_data = &tps65910_data,
},
#endif
#if defined (CONFIG_RTC_HYM8563)
{
.type = "rtc_hym8563",
.addr = 0x51,
.flags = 0,
.irq = RK30_PIN6_PA0,
},
#endif
};
#endif
#ifdef CONFIG_KP_AXP20
#define cru_readl(offset) readl_relaxed(RK30_CRU_BASE + offset)
#define cru_writel(v, offset) do { writel_relaxed(v, RK30_CRU_BASE + offset); dsb(); } while (0)
#define grf_readl(offset) readl_relaxed(RK30_GRF_BASE + offset)
#define grf_writel(v, offset) do { writel_relaxed(v, RK30_GRF_BASE + offset); dsb(); } while (0)
#define CRU_CLKGATE5_CON_ADDR 0x00e4
#define GRF_GPIO6L_DIR_ADDR 0x0030
#define GRF_GPIO6L_DO_ADDR 0x0068
#define GRF_GPIO6L_EN_ADDR 0x00a0
#define CRU_CLKGATE5_GRFCLK_ON 0x00100000
#define CRU_CLKGATE5_GRFCLK_OFF 0x00100010
#define GPIO6_PB1_DIR_OUT 0x02000200
#define GPIO6_PB1_DO_LOW 0x02000000
#define GPIO6_PB1_DO_HIGH 0x02000200
#define GPIO6_PB1_EN_MASK 0x02000200
#define GPIO6_PB1_UNEN_MASK 0x02000000
void __sramfunc board_pmu_axp202_suspend(void)
{
cru_writel(CRU_CLKGATE5_GRFCLK_ON,CRU_CLKGATE5_CON_ADDR); //open grf clk
grf_writel(GPIO6_PB1_DIR_OUT, GRF_GPIO6L_DIR_ADDR);
grf_writel(GPIO6_PB1_DO_HIGH, GRF_GPIO6L_DO_ADDR); //set gpio6_b1 output low
grf_writel(GPIO6_PB1_EN_MASK, GRF_GPIO6L_EN_ADDR);
}
void __sramfunc board_pmu_axp202_resume(void)
{
grf_writel(GPIO6_PB1_DIR_OUT, GRF_GPIO6L_DIR_ADDR);
grf_writel(GPIO6_PB1_DO_LOW, GRF_GPIO6L_DO_ADDR); //set gpio6_b1 output high
grf_writel(GPIO6_PB1_EN_MASK, GRF_GPIO6L_EN_ADDR);
#ifdef CONFIG_CLK_SWITCH_TO_32K
sram_32k_udelay(10000);
#else
sram_udelay(10000);
#endif
}
#endif
void __sramfunc board_pmu_suspend(void)
{
#if defined (CONFIG_MFD_WM831X_I2C)
if(g_pmic_type == PMIC_TYPE_WM8326)
board_pmu_wm8326_suspend();
#endif
#if defined (CONFIG_MFD_TPS65910)
if(g_pmic_type == PMIC_TYPE_TPS65910)
board_pmu_tps65910_suspend();
#endif
#if defined (CONFIG_KP_AXP20)
board_pmu_axp202_suspend();
#endif
}
void __sramfunc board_pmu_resume(void)
{
#if defined (CONFIG_MFD_WM831X_I2C)
if(g_pmic_type == PMIC_TYPE_WM8326)
board_pmu_wm8326_resume();
#endif
#if defined (CONFIG_MFD_TPS65910)
if(g_pmic_type == PMIC_TYPE_TPS65910)
board_pmu_tps65910_resume();
#endif
#if defined (CONFIG_KP_AXP20)
board_pmu_axp202_resume();
#endif
}
#ifdef CONFIG_KP_AXP20
int __sramdata gpio0a3_iomux,gpio0a3_do,gpio0a3_dir,gpio0a3_en;
void __sramfunc rk30_pwm_arm_suspend_voltage(void)
{
#ifdef CONFIG_RK30_PWM_REGULATOR
// int gpio0d7_iomux,gpio0d7_do,gpio0d7_dir,gpio0d7_en;
sram_udelay(10000);
gpio0a3_iomux = readl_relaxed(GRF_GPIO0A_IOMUX);
gpio0a3_do = grf_readl(GRF_GPIO0L_DO);
gpio0a3_dir = grf_readl(GRF_GPIO0L_DIR);
gpio0a3_en = grf_readl(GRF_GPIO0L_EN);
writel_relaxed((1<<22), GRF_GPIO0A_IOMUX);
grf_writel((1<<19)|(1<<3), GRF_GPIO0L_DIR);
grf_writel((1<<19)|(1<<3), GRF_GPIO0L_DO);
grf_writel((1<<19)|(1<<3), GRF_GPIO0L_EN);
#endif
}
void __sramfunc rk30_pwm_arm_resume_voltage(void)
{
#ifdef CONFIG_RK30_PWM_REGULATOR
writel_relaxed((1<<22)|gpio0a3_iomux, GRF_GPIO0A_IOMUX);
grf_writel((1<<19)|gpio0a3_en, GRF_GPIO0L_EN);
grf_writel((1<<19)|gpio0a3_dir, GRF_GPIO0L_DIR);
grf_writel((1<<19)|gpio0a3_do, GRF_GPIO0L_DO);
sram_udelay(10000);
#endif
}
#endif
int __sramdata gpio0d7_iomux,gpio0d7_do,gpio0d7_dir,gpio0d7_en;
void __sramfunc rk30_pwm_logic_suspend_voltage(void)
{
#ifdef CONFIG_RK30_PWM_REGULATOR
// int gpio0d7_iomux,gpio0d7_do,gpio0d7_dir,gpio0d7_en;
sram_udelay(10000);
gpio0d7_iomux = readl_relaxed(GRF_GPIO0D_IOMUX);
gpio0d7_do = grf_readl(GRF_GPIO0H_DO);
gpio0d7_dir = grf_readl(GRF_GPIO0H_DIR);
gpio0d7_en = grf_readl(GRF_GPIO0H_EN);
writel_relaxed((1<<30), GRF_GPIO0D_IOMUX);
grf_writel((1<<31)|(1<<15), GRF_GPIO0H_DIR);
grf_writel((1<<31)|(1<<15), GRF_GPIO0H_DO);
grf_writel((1<<31)|(1<<15), GRF_GPIO0H_EN);
#endif
#ifdef CONFIG_KP_AXP20
rk30_pwm_arm_suspend_voltage();
#endif
}
void __sramfunc rk30_pwm_logic_resume_voltage(void)
{
#ifdef CONFIG_RK30_PWM_REGULATOR
#ifdef CONFIG_KP_AXP20
rk30_pwm_arm_resume_voltage();
sram_udelay(10000);
#endif
writel_relaxed((1<<30)|gpio0d7_iomux, GRF_GPIO0D_IOMUX);
grf_writel((1<<31)|gpio0d7_en, GRF_GPIO0H_EN);
grf_writel((1<<31)|gpio0d7_dir, GRF_GPIO0H_DIR);
grf_writel((1<<31)|gpio0d7_do, GRF_GPIO0H_DO);
sram_udelay(10000);
#endif
}
extern void pwm_suspend_voltage(void);
extern void pwm_resume_voltage(void);
void rk30_pwm_suspend_voltage_set(void)
{
#ifdef CONFIG_RK30_PWM_REGULATOR
pwm_suspend_voltage();
#endif
}
void rk30_pwm_resume_voltage_set(void)
{
#ifdef CONFIG_RK30_PWM_REGULATOR
pwm_resume_voltage();
#endif
}
#ifdef CONFIG_I2C2_RK30
static struct i2c_board_info __initdata i2c2_info[] = {
#if defined (CONFIG_TOUCHSCREEN_GT8XX)
{
.type = "Goodix-TS",
.addr = 0x55,
.flags = 0,
.irq = RK30_PIN4_PC2,
.platform_data = &goodix_info,
},
#endif
#if defined (CONFIG_TOUCHSCREEN_BYD693X)
{
.type = "byd693x-ts",
.addr = 0x52,
.flags = 0,
.irq = RK30_PIN4_PC2,
.platform_data = &byd693x_info,
},
#endif
#if defined (CONFIG_TOUCHSCREEN_BF6931A)
{
.type ="bf6931a_ts",
.addr = 0x2c, //0x70,
.flags =0,
.irq =RK30_PIN4_PC2, // support goodix tp detect, 20110706
.platform_data = &bf6931a_info,
},
#endif
#if defined (CONFIG_TOUCHSCREEN_SSL)
{
.type ="ssd253x-ts",
.addr =0x48,
.flags =0,
.irq =RK30_PIN0_PA2,
},
#endif
#if defined (CONFIG_TOUCHSCREEN_CYTTSP4)
{
.type = CY_I2C_NAME,
.addr = CY_I2C_LDR_ADR,
.irq = TOUCH_GPIO_IRQ_CYTTSP,
.platform_data = &cyttsp4_i2c_touch_platform_data,
},
#endif
#if defined (CONFIG_TOUCHSCREEN_GT801PLUS_819_8105_8110)
{
.type = "GT801PLUS-TS",
.addr = 0x55,
},
#endif
#if defined (CONFIG_TOUCHSCREEN_GT813_827_828)
{
.type = "GT828-TS",
.addr = 0x5d,
},
#endif
#if defined (CONFIG_TOUCHSCREEN_GT800_801)
{
.type = "Goodix-TS",
.addr = 0x55,
.flags = 0,
.irq = RK30_PIN4_PC2,
},
#endif
#if defined (CONFIG_TOUCHSCREEN_NOVATEK)
{
.type = "novatek-ts",
.addr = 0x09,
.flags = 0,
.irq = RK30_PIN4_PC2,
.platform_data = &novatek_info,
},
#endif
#if defined(CONFIG_TOUCHSCREEN_GSLX680)
{
.type = "gslX680",
.addr = 0x40,
},
#endif
#if defined (CONFIG_TOUCHSCREEN_ZET6221)
{
.type ="zet6221_ts",
.addr =0x76,
.flags =0,
.irq =RK30_PIN4_PC2,
},
#endif
#if defined (CONFIG_TOUCHSCREEN_FT5306)
{
.type = "ft5x0x_ts",
.addr = 0x38,
.flags = 0,
.irq = RK30_PIN4_PC2,
.platform_data = &ft5x0x_info,
},
#endif
#if defined (CONFIG_LS_CM3217)
{
.type = "lightsensor",
.addr = 0x10,
.flags = 0,
.platform_data = &cm3217_info,
},
#endif
};
#endif
#ifdef CONFIG_I2C3_RK30
static struct i2c_board_info __initdata i2c3_info[] = {
};
#endif
#ifdef CONFIG_I2C4_RK30
static struct i2c_board_info __initdata i2c4_info[] = {
};
#endif
#ifdef CONFIG_I2C_GPIO_RK30
#define I2C_SDA_PIN INVALID_GPIO// RK30_PIN2_PD6 //set sda_pin here
#define I2C_SCL_PIN INVALID_GPIO//RK30_PIN2_PD7 //set scl_pin here
static int rk30_i2c_io_init(void)
{
//set iomux (gpio) here
//rk30_mux_api_set(GPIO2D7_I2C1SCL_NAME, GPIO2D_GPIO2D7);
//rk30_mux_api_set(GPIO2D6_I2C1SDA_NAME, GPIO2D_GPIO2D6);
return 0;
}
struct i2c_gpio_platform_data default_i2c_gpio_data = {
.sda_pin = I2C_SDA_PIN,
.scl_pin = I2C_SCL_PIN,
.udelay = 5, // clk = 500/udelay = 100Khz
.timeout = 100,//msecs_to_jiffies(100),
.bus_num = 5,
.io_init = rk30_i2c_io_init,
};
static struct i2c_board_info __initdata i2c_gpio_info[] = {
};
#endif
static void __init rk30_i2c_register_board_info(void)
{
#ifdef CONFIG_I2C0_RK30
i2c_register_board_info(0, i2c0_info, ARRAY_SIZE(i2c0_info));
#endif
#ifdef CONFIG_I2C1_RK30
i2c_register_board_info(1, i2c1_info, ARRAY_SIZE(i2c1_info));
#endif
#ifdef CONFIG_I2C2_RK30
i2c_register_board_info(2, i2c2_info, ARRAY_SIZE(i2c2_info));
#endif
#ifdef CONFIG_I2C3_RK30
i2c_register_board_info(3, i2c3_info, ARRAY_SIZE(i2c3_info));
#endif
#ifdef CONFIG_I2C4_RK30
i2c_register_board_info(4, i2c4_info, ARRAY_SIZE(i2c4_info));
#endif
#ifdef CONFIG_I2C_GPIO_RK30
i2c_register_board_info(5, i2c_gpio_info, ARRAY_SIZE(i2c_gpio_info));
#endif
}
//end of i2c
#if defined (CONFIG_KP_AXP20)
extern void axp_power_off(void);
#endif
#ifdef CONFIG_SND_SOC_RT5633
extern void rt5633_shutdown(void);
#endif
#ifdef CONFIG_KP_AXP20
#define POWER_ON_PIN RK30_PIN6_PB2 //power_hold
void rk30_pm_power_off(void)
#else
#define POWER_ON_PIN RK30_PIN6_PB0 //power_hold
static void rk30_pm_power_off(void)
#endif
{
printk(KERN_ERR "rk30_pm_power_off start...\n");
#ifdef CONFIG_SND_SOC_RT5633
rt5633_shutdown();
#endif
gpio_direction_output(POWER_ON_PIN, GPIO_LOW);
#if defined(CONFIG_MFD_WM831X)
if(g_pmic_type == PMIC_TYPE_WM8326)
{
wm831x_set_bits(Wm831x,WM831X_GPIO_LEVEL,0x0001,0x0000); //set sys_pwr 0
wm831x_device_shutdown(Wm831x);//wm8326 shutdown
}
#endif
#if defined(CONFIG_MFD_TPS65910)
if(g_pmic_type == PMIC_TYPE_TPS65910)
{
tps65910_device_shutdown();//tps65910 shutdown
}
#endif
#ifdef CONFIG_KP_AXP20
axp_power_off();
#endif
while (1);
}
static void __init machine_rk30_board_init(void)
{
avs_init();
gpio_request(POWER_ON_PIN, "poweronpin");
gpio_direction_output(POWER_ON_PIN, GPIO_HIGH);
pm_power_off = rk30_pm_power_off;
rk30_i2c_register_board_info();
spi_register_board_info(board_spi_devices, ARRAY_SIZE(board_spi_devices));
platform_add_devices(devices, ARRAY_SIZE(devices));
board_usb_detect_init(RK30_PIN6_PA3);
#ifdef CONFIG_WIFI_CONTROL_FUNC
rk29sdk_wifi_bt_gpio_control_init();
#endif
}
static void __init rk30_reserve(void)
{
#ifdef CONFIG_ION
rk30_ion_pdata.heaps[0].base = board_mem_reserve_add("ion", ION_RESERVE_SIZE);
#endif
#ifdef CONFIG_FB_ROCKCHIP
resource_fb[0].start = board_mem_reserve_add("fb0", RK30_FB0_MEM_SIZE);
resource_fb[0].end = resource_fb[0].start + RK30_FB0_MEM_SIZE - 1;
resource_fb[1].start = board_mem_reserve_add("ipp buf", RK30_FB0_MEM_SIZE);
resource_fb[1].end = resource_fb[1].start + RK30_FB0_MEM_SIZE - 1;
resource_fb[2].start = board_mem_reserve_add("fb2", RK30_FB0_MEM_SIZE);
resource_fb[2].end = resource_fb[2].start + RK30_FB0_MEM_SIZE - 1;
#endif
#ifdef CONFIG_VIDEO_RK29
rk30_camera_request_reserve_mem();
#endif
board_mem_reserved();
}
/**
* dvfs_cpu_logic_table: table for arm and logic dvfs
* @frequency : arm frequency
* @cpu_volt : arm voltage depend on frequency
* @logic_volt : logic voltage arm requests depend on frequency
* comments : min arm/logic voltage
*/
#ifdef CONFIG_KP_AXP20
static struct dvfs_arm_table dvfs_cpu_logic_table[] = {
{.frequency = 252 * 1000, .cpu_volt = 1075 * 1000, .logic_volt = 1125 * 1000},//0.975V/1.000V
{.frequency = 504 * 1000, .cpu_volt = 1100 * 1000, .logic_volt = 1125 * 1000},//0.975V/1.000V
{.frequency = 816 * 1000, .cpu_volt = 1200 * 1000, .logic_volt = 1200 * 1000},//1.000V/1.025V
{.frequency = 1008 * 1000, .cpu_volt = 1225 * 1000, .logic_volt = 1200 * 1000},//1.025V/1.050V
{.frequency = 1200 * 1000, .cpu_volt = 1275 * 1000, .logic_volt = 1250 * 1000},//1.100V/1.050V
{.frequency = 1272 * 1000, .cpu_volt = 1275 * 1000, .logic_volt = 1250 * 1000},//1.150V/1.100V
{.frequency = 1416 * 1000, .cpu_volt = 1350 * 1000, .logic_volt = 1250 * 1000},//1.225V/1.100V
{.frequency = 1512 * 1000, .cpu_volt = 1400 * 1000, .logic_volt = 1300 * 1000},//1.300V/1.150V
{.frequency = 1608 * 1000, .cpu_volt = 1425 * 1000, .logic_volt = 1300 * 1000},//1.325V/1.175V
{.frequency = CPUFREQ_TABLE_END},
};
#else
static struct dvfs_arm_table dvfs_cpu_logic_table[] = {
{.frequency = 252 * 1000, .cpu_volt = 1075 * 1000, .logic_volt = 1125 * 1000},//0.975V/1.000V
{.frequency = 504 * 1000, .cpu_volt = 1100 * 1000, .logic_volt = 1125 * 1000},//0.975V/1.000V
{.frequency = 816 * 1000, .cpu_volt = 1125 * 1000, .logic_volt = 1150 * 1000},//1.000V/1.025V
{.frequency = 1008 * 1000, .cpu_volt = 1125 * 1000, .logic_volt = 1150 * 1000},//1.025V/1.050V
{.frequency = 1200 * 1000, .cpu_volt = 1175 * 1000, .logic_volt = 1200 * 1000},//1.100V/1.050V
{.frequency = 1272 * 1000, .cpu_volt = 1225 * 1000, .logic_volt = 1200 * 1000},//1.150V/1.100V
{.frequency = 1416 * 1000, .cpu_volt = 1300 * 1000, .logic_volt = 1200 * 1000},//1.225V/1.100V
{.frequency = 1512 * 1000, .cpu_volt = 1350 * 1000, .logic_volt = 1250 * 1000},//1.300V/1.150V
{.frequency = 1608 * 1000, .cpu_volt = 1425 * 1000, .logic_volt = 1300 * 1000},//1.325V/1.175V
{.frequency = CPUFREQ_TABLE_END},
};
#endif
static struct cpufreq_frequency_table dvfs_gpu_table[] = {
{.frequency = 266 * 1000, .index = 1050 * 1000},
{.frequency = 400 * 1000, .index = 1275 * 1000},
{.frequency = CPUFREQ_TABLE_END},
};
static struct cpufreq_frequency_table dvfs_ddr_table[] = {
{.frequency = 300 * 1000, .index = 1050 * 1000},
{.frequency = 400 * 1000, .index = 1125 * 1000},
{.frequency = CPUFREQ_TABLE_END},
};
#define DVFS_CPU_TABLE_SIZE (ARRAY_SIZE(dvfs_cpu_logic_table))
static struct cpufreq_frequency_table cpu_dvfs_table[DVFS_CPU_TABLE_SIZE];
static struct cpufreq_frequency_table dep_cpu2core_table[DVFS_CPU_TABLE_SIZE];
void __init board_clock_init(void)
{
rk30_clock_data_init(periph_pll_default, codec_pll_default, RK30_CLOCKS_DEFAULT_FLAGS);
dvfs_set_arm_logic_volt(dvfs_cpu_logic_table, cpu_dvfs_table, dep_cpu2core_table);
dvfs_set_freq_volt_table(clk_get(NULL, "gpu"), dvfs_gpu_table);
dvfs_set_freq_volt_table(clk_get(NULL, "ddr"), dvfs_ddr_table);
}
MACHINE_START(RK30, "RK30board")
.boot_params = PLAT_PHYS_OFFSET + 0x800,
.fixup = rk30_fixup,
.reserve = &rk30_reserve,
.map_io = rk30_map_io,
.init_irq = rk30_init_irq,
.timer = &rk30_timer,
.init_machine = machine_rk30_board_init,
MACHINE_END
|
aloksinha2001/picuntu-3.0.8-alok
|
arch/arm/mach-rk30/board-rk30-sdk.c
|
C
|
gpl-2.0
| 111,947
|
/** -----------------------------------------------------:[ Membership Meta Box ]:---------- */
#it_exchange_membership_addon_membership_access_metabox .it-exchange-membership-restriction-group{margin-bottom:10px;background:#FFF;border:1px solid #DDD;border-top:0;box-shadow:#F6F6F6 0 0 10px;}
#it_exchange_membership_addon_membership_access_metabox .it-exchange-membership-rule{position:relative;padding:15px 30px 15px 35px;padding-left:35px;border-top:1px solid #DDD;}
#it_exchange_membership_addon_membership_access_metabox .it-exchange-membership-rule input[type="checkbox"]{position:absolute;left:15px;}
#it_exchange_membership_addon_membership_access_metabox .it-exchange-membership-rule-description{padding-left:10px;font-size:10px;color:#AAA;}
#it_exchange_membership_addon_membership_access_metabox .it-exchange-membership-remove-rule,
#it_exchange_membership_addon_membership_access_metabox .it-exchange-membership-remove-new-rule{cursor:pointer;position:absolute;z-index:100;color:#CCC;top:15px;right:15px;-webkit-transition:color .2s ease;-moz-transition:color .2s ease;transition:color .2s ease;}
#it_exchange_membership_addon_membership_access_metabox .it-exchange-membership-remove-rule:hover,
#it_exchange_membership_addon_membership_access_metabox .it-exchange-membership-remove-new-rule:hover{color:#E1797A;}
/** ----------------------------------------:[ drip ]:--- */
#it_exchange_membership_addon_membership_access_metabox .it-exchange-membership-rule-delay{margin:3px 0;font-size:10px;color:#AAA;}
#it_exchange_membership_addon_membership_access_metabox .it-exchange-membership-drip-rule input{max-width:50px;margin-right:5px;}
/** ----------------------------------------:[ new rule ]:--- */
#it_exchange_membership_addon_membership_access_metabox .it-exchange-new-membership-rule{overflow:hidden;margin-bottom:10px;position:relative;padding:15px 35px 15px 15px;background:#FFF;border:1px solid #DDD;}
#it_exchange_membership_addon_membership_access_metabox .it-exchange-new-membership-rule select{max-width:100%;}
#it_exchange_membership_addon_membership_access_metabox .it-exchange-new-membership-rule .it-exchange-membership-drip-rule{float:left;}
#it_exchange_membership_addon_membership_access_metabox .it-exchange-add-new-restriction-ok-button{float:left;margin-left:5px;}
/** ----------------------------------------:[ no restrictions ]:--- */
.it-exchange-membership-no-restrictions{padding:10px;margin-bottom:10px;background:#FFF;border:1px solid #DEDEDE;box-shadow:inset #EEE 0 0 5px;}
|
itaddy/permiekids
|
wp-content/plugins/exchange-addon-membership/lib/styles/add-edit-post.css
|
CSS
|
gpl-2.0
| 2,519
|
/****************************************************************************/
/*
* uclinux.c -- generic memory mapped MTD driver for uclinux
*
* (C) Copyright 2002, Greg Ungerer (gerg@snapgear.com)
*
* $Id: uclinux.c,v 1.2 2002/08/07 00:43:45 gerg Exp $
*/
/****************************************************************************/
#include <linux/config.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/major.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#include <linux/mtd/partitions.h>
#include <asm/io.h>
/****************************************************************************/
__u8 uclinux_read8(struct map_info *map, unsigned long ofs)
{
return(*((__u8 *) (map->map_priv_1 + ofs)));
}
__u16 uclinux_read16(struct map_info *map, unsigned long ofs)
{
return(*((__u16 *) (map->map_priv_1 + ofs)));
}
__u32 uclinux_read32(struct map_info *map, unsigned long ofs)
{
return(*((__u32 *) (map->map_priv_1 + ofs)));
}
void uclinux_copy_from(struct map_info *map, void *to, unsigned long from, ssize_t len)
{
memcpy(to, (void *)(map->map_priv_1 + from), len);
}
void uclinux_write8(struct map_info *map, __u8 d, unsigned long adr)
{
*((__u8 *) (map->map_priv_1 + adr)) = d;
}
void uclinux_write16(struct map_info *map, __u16 d, unsigned long adr)
{
*((__u16 *) (map->map_priv_1 + adr)) = d;
}
void uclinux_write32(struct map_info *map, __u32 d, unsigned long adr)
{
*((__u32 *) (map->map_priv_1 + adr)) = d;
}
void uclinux_copy_to(struct map_info *map, unsigned long to, const void *from, ssize_t len)
{
memcpy((void *) (map->map_priv_1 + to), from, len);
}
/****************************************************************************/
struct map_info uclinux_ram_map = {
name: "RAM",
read8: uclinux_read8,
read16: uclinux_read16,
read32: uclinux_read32,
copy_from: uclinux_copy_from,
write8: uclinux_write8,
write16: uclinux_write16,
write32: uclinux_write32,
copy_to: uclinux_copy_to,
};
struct mtd_info *uclinux_ram_mtdinfo;
/****************************************************************************/
int uclinux_point(struct mtd_info *mtd, loff_t from, size_t len,
size_t *retlen, u_char **mtdbuf)
{
struct map_info *map = (struct map_info *) mtd->priv;
*mtdbuf = (u_char *) (map->map_priv_1 + ((int) from));
*retlen = len;
return(0);
}
static void uclinux_unpoint(struct mtd_info *mtd, u_char *addr, loff_t from,
size_t len)
{
}
/****************************************************************************/
int __init uclinux_mtd_init(void)
{
struct mtd_info *mtd;
struct map_info *mapp;
extern char _ebss;
mapp = &uclinux_ram_map;
mapp->map_priv_2 = (unsigned long) &_ebss;
mapp->size = PAGE_ALIGN(ntohl(*((unsigned long *)((&_ebss) + 8))));
mapp->buswidth = 4;
printk("uclinux[mtd]: RAM probe address=0x%x size=0x%x\n",
(int) mapp->map_priv_2, (int) mapp->size);
mapp->map_priv_1 = (unsigned long)
ioremap_nocache(mapp->map_priv_2, mapp->size);
if (mapp->map_priv_1 == 0) {
printk("uclinux[mtd]: ioremap_nocache() failed\n");
return(-EIO);
}
mtd = do_map_probe("map_ram", mapp);
if (!mtd) {
printk("uclinux[mtd]: failed to find a mapping?\n");
iounmap((void *) mapp->map_priv_1);
return(-ENXIO);
}
mtd->module = THIS_MODULE;
mtd->point = uclinux_point;
mtd->unpoint = uclinux_unpoint;
mtd->priv = mapp;
uclinux_ram_mtdinfo = mtd;
add_mtd_device(mtd);
printk("uclinux[mtd]: root filesystem index=%d\n", mtd->index);
ROOT_DEV = MKDEV(MTD_BLOCK_MAJOR, mtd->index);
put_mtd_device(mtd);
return(0);
}
/****************************************************************************/
void __exit uclinux_mtd_cleanup(void)
{
if (uclinux_ram_mtdinfo) {
del_mtd_partitions(uclinux_ram_mtdinfo);
map_destroy(uclinux_ram_mtdinfo);
uclinux_ram_mtdinfo = NULL;
}
if (uclinux_ram_map.map_priv_1) {
iounmap((void *) uclinux_ram_map.map_priv_1);
uclinux_ram_map.map_priv_1 = 0;
}
}
/****************************************************************************/
module_init(uclinux_mtd_init);
module_exit(uclinux_mtd_cleanup);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Greg Ungerer <gerg@snapgear.com>");
MODULE_DESCRIPTION("Generic RAM based MTD for uClinux");
/****************************************************************************/
|
iPodLinux/linux-2.4.24-ipod
|
drivers/mtd/maps/uclinux.c
|
C
|
gpl-2.0
| 4,373
|
// -*- C++ -*-
#ifndef _NR_TYPES_H_
#define _NR_TYPES_H_
#include <complex>
#include <fstream>
#include "nrutil.h"
namespace NR {
typedef double DP;
// Vector Types
typedef const NRVec<bool> Vec_I_BOOL;
typedef NRVec<bool> Vec_BOOL, Vec_O_BOOL, Vec_IO_BOOL;
typedef const NRVec<char> Vec_I_CHR;
typedef NRVec<char> Vec_CHR, Vec_O_CHR, Vec_IO_CHR;
typedef const NRVec<unsigned char> Vec_I_UCHR;
typedef NRVec<unsigned char> Vec_UCHR, Vec_O_UCHR, Vec_IO_UCHR;
typedef const NRVec<int> Vec_I_INT;
typedef NRVec<int> Vec_INT, Vec_O_INT, Vec_IO_INT;
typedef const NRVec<unsigned int> Vec_I_UINT;
typedef NRVec<unsigned int> Vec_UINT, Vec_O_UINT, Vec_IO_UINT;
typedef const NRVec<long> Vec_I_LNG;
typedef NRVec<long> Vec_LNG, Vec_O_LNG, Vec_IO_LNG;
typedef const NRVec<unsigned long> Vec_I_ULNG;
typedef NRVec<unsigned long> Vec_ULNG, Vec_O_ULNG, Vec_IO_ULNG;
typedef const NRVec<float> Vec_I_SP;
typedef NRVec<float> Vec_SP, Vec_O_SP, Vec_IO_SP;
typedef const NRVec<DP> Vec_I_DP;
typedef NRVec<DP> Vec_DP, Vec_O_DP, Vec_IO_DP;
typedef const NRVec<std::complex<float> > Vec_I_CPLX_SP;
typedef NRVec<std::complex<float> > Vec_CPLX_SP, Vec_O_CPLX_SP, Vec_IO_CPLX_SP;
typedef const NRVec<std::complex<DP> > Vec_I_CPLX_DP;
typedef NRVec<std::complex<DP> > Vec_CPLX_DP, Vec_O_CPLX_DP, Vec_IO_CPLX_DP;
// Matrix Types
typedef const NRMat<bool> Mat_I_BOOL;
typedef NRMat<bool> Mat_BOOL, Mat_O_BOOL, Mat_IO_BOOL;
typedef const NRMat<char> Mat_I_CHR;
typedef NRMat<char> Mat_CHR, Mat_O_CHR, Mat_IO_CHR;
typedef const NRMat<unsigned char> Mat_I_UCHR;
typedef NRMat<unsigned char> Mat_UCHR, Mat_O_UCHR, Mat_IO_UCHR;
typedef const NRMat<int> Mat_I_INT;
typedef NRMat<int> Mat_INT, Mat_O_INT, Mat_IO_INT;
typedef const NRMat<unsigned int> Mat_I_UINT;
typedef NRMat<unsigned int> Mat_UINT, Mat_O_UINT, Mat_IO_UINT;
typedef const NRMat<long> Mat_I_LNG;
typedef NRMat<long> Mat_LNG, Mat_O_LNG, Mat_IO_LNG;
typedef const NRVec<unsigned long> Mat_I_ULNG;
typedef NRMat<unsigned long> Mat_ULNG, Mat_O_ULNG, Mat_IO_ULNG;
typedef const NRMat<float> Mat_I_SP;
typedef NRMat<float> Mat_SP, Mat_O_SP, Mat_IO_SP;
typedef const NRMat<DP> Mat_I_DP;
typedef NRMat<DP> Mat_DP, Mat_O_DP, Mat_IO_DP;
typedef const NRMat<std::complex<float> > Mat_I_CPLX_SP;
typedef NRMat<std::complex<float> > Mat_CPLX_SP, Mat_O_CPLX_SP, Mat_IO_CPLX_SP;
typedef const NRMat<std::complex<DP> > Mat_I_CPLX_DP;
typedef NRMat<std::complex<DP> > Mat_CPLX_DP, Mat_O_CPLX_DP, Mat_IO_CPLX_DP;
// 3D Matrix Types
typedef const NRMat3d<DP> Mat3D_I_DP;
typedef NRMat3d<DP> Mat3D_DP, Mat3D_O_DP, Mat3D_IO_DP;
// Miscellaneous Types
typedef NRVec<unsigned long *> Vec_ULNG_p;
typedef NRVec<NRMat<DP> *> Vec_Mat_DP_p;
typedef NRVec<std::fstream *> Vec_FSTREAM_p;
} // namespace NR
#endif /* _NR_TYPES_H_ */
|
JeffersonLab/chroma_utils
|
lib/recipes/nrtypes_nr.h
|
C
|
gpl-2.0
| 2,873
|
package si.virag.parkomat.modules;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import com.wdullaer.materialdatetimepicker.time.RadialPickerLayout;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
import org.threeten.bp.LocalTime;
import org.threeten.bp.temporal.ChronoField;
import org.threeten.bp.temporal.ChronoUnit;
import rx.Observable;
import rx.Subscriber;
/**
* Handles parking time related things
*/
public class TimeManager {
@NonNull
private final Context appContext;
public TimeManager(@NonNull Context applicationContext) {
this.appContext = applicationContext;
}
public LocalTime initialDisplayedTime() {
return LocalTime.now().plus(1, ChronoUnit.HOURS);
}
public Observable<LocalTime> pickTime(@NonNull final Activity owner, @NonNull final LocalTime currentlySelected) {
return Observable.create(new Observable.OnSubscribe<LocalTime>() {
@Override
public void call(final Subscriber<? super LocalTime> subscriber) {
TimePickerDialog.OnTimeSetListener listener = new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute, int second) {
LocalTime instant = LocalTime.now()
.with(ChronoField.HOUR_OF_DAY, hourOfDay)
.with(ChronoField.MINUTE_OF_HOUR, minute);
subscriber.onNext(instant);
}
};
DialogInterface.OnDismissListener dismissListener = new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
subscriber.onCompleted();
}
};
TimePickerDialog dialog = TimePickerDialog.newInstance(listener, currentlySelected.get(ChronoField.HOUR_OF_DAY), currentlySelected.get(ChronoField.MINUTE_OF_HOUR), true);
dialog.setOnDismissListener(dismissListener);
dialog.show(owner.getFragmentManager(), "TimePicker");
}
});
}
}
|
izacus/Parkomat
|
app/src/main/java/si/virag/parkomat/modules/TimeManager.java
|
Java
|
gpl-2.0
| 2,335
|
<?php if(!defined("IN_ESOTALK")) exit;
/**
* OpauthConnect
*
* @copyright Copyright © 2012 Oleksandr Golubtsov
* @license GPLv2 License
* @package OpauthСonnect
*
* This file is part of OpauthСonnect plugin. Please see the included license file for usage information
*/
ET::$pluginInfo["OpauthConnect"] = array(
"name" => "OpauthConnect",
"description" => "Sign in via social networks",
"version" => "2.1",
"author" => "Oleksandr Golubtsov",
"authorEmail" => "alex.8fmi@gmail.com",
"authorURL" => "http://alex-dev.me",
"license" => "GPLv2"
);
require_once "classes".DIRECTORY_SEPARATOR."OCServices.php";
require_once "classes".DIRECTORY_SEPARATOR."OpauthConnect.php";
require_once "classes".DIRECTORY_SEPARATOR."OCSettings.php";
class ETPlugin_OpauthConnect extends ETPlugin {
private $settings;
private $services;
private $opauth_connect;
public function __construct($rootDirectory) {
parent::__construct($rootDirectory);
ETFactory::register("ocMemberSocialModel", "OcMemberSocialModel", dirname(__FILE__)."/models/OcMemberSocialModel.class.php");
ETFactory::register("ocSettingsModel", "OcSettingsModel", dirname(__FILE__)."/models/OcSettingsModel.class.php");
$this->services = new OCServices;
$this->settings = new OCSettings;
}
public function handler_init($sender) {
if(ET::$session->get("remember") === null) ET::$session->store("remember", 1);
$sender->addCSSFile($this->resource("css/opauthconnect.css"));
$sender->addJSFile($this->resource("js/opauthconnect.js"));
$config = array();
$config['security_salt'] = $this->settings->get(OCSettings::SECURITY_SALT);
$config['path'] = URL('user/social/');
$config['callback_url'] = URL('user/social/callback/');
foreach($this->services as $service) {
if($this->settings->get($service->settings->enabled)) {
$config['Strategy'][$service->name] = array(
$service->key => $this->settings->get($service->settings->key),
$service->secret => $this->settings->get($service->settings->secret)
);
foreach($service->static as $name => $value) {
$config['Strategy'][$service->name][$name] = $value;
}
}
}
$this->opauth_connect = new OpauthConnect($config);
}
public function handler_initAdmin($sender, $menu) {
$sender->addCSSFile($this->resource("css/backend.css"));
$sender->addJSFile($this->resource("js/backend.js"));
}
public function handler_renderOpauth($sender) {
$data = array(
'remember' => ET::$session->get("remember", 0),
'services' => array()
);
foreach($this->services as $service) {
if($this->settings->get($service->settings->enabled)) {
$data['services'][$service->name] = array(
'url' => URL('user/social/'.$service->machine_name),
'icon' => URL($this->resource($service->icon))
);
}
}
$sender->renderView('social/oc_buttons', $data);
}
public function handler_settingsController_renderBefore($sender) {
if(isset($sender->data['panes']) && !empty($sender->data['panes'])) {
$sender->data['panes']->add('social_accounts', "<a href='".URL("settings/social/accounts")."'>".T("Social Accounts")."</a>");
}
}
private function login($memberId) {
if($memberId) {
ET::$session->loginWithMemberId($memberId);
if(ET::$session->get("remember")) ET::$session->setRememberCookie($memberId);
}
redirect(URL());
}
public function settings($sender) {
$form = ETFactory::make("form");
$form->action = URL("admin/plugins/settings/OpauthConnect");
if($form->validPostBack("save") && !$form->errorCount()) {
$this->settings->set(OCSettings::PASS_EMAIL_SUBJ, $form->getValue(OCSettings::PASS_EMAIL_SUBJ));
$this->settings->set(OCSettings::CONFIRM_EMAIL_SUBJ, $form->getValue(OCSettings::CONFIRM_EMAIL_SUBJ));
$this->settings->set(OCSettings::ALLOW_UNLINK, $form->getValue(OCSettings::ALLOW_UNLINK));
$this->settings->set(OCSettings::SECURITY_SALT, $form->getValue(OCSettings::SECURITY_SALT));
foreach($this->services as $service) {
foreach($service->settings as $setting) {
$this->settings->set($setting, $form->getValue($setting));
}
}
$this->settings->save();
$sender->message(T("message.changesSaved"), "success");
$sender->redirect(URL("admin/plugins"));
}
$form->setValue(OCSettings::SECURITY_SALT, $this->settings->get(OCSettings::SECURITY_SALT));
$form->setValue(OCSettings::ALLOW_UNLINK, $this->settings->get(OCSettings::ALLOW_UNLINK));
$form->setValue(OCSettings::CONFIRM_EMAIL_SUBJ, $this->settings->get(OCSettings::CONFIRM_EMAIL_SUBJ));
$form->setValue(OCSettings::PASS_EMAIL_SUBJ, $this->settings->get(OCSettings::PASS_EMAIL_SUBJ));
$form_services = array();
foreach($this->services as $service) {
$form_services[$service->machine_name]['name'] = $service->name;
$form_services[$service->machine_name]['raw_key'] = $service->key;
$form_services[$service->machine_name]['raw_secret'] = $service->secret;
foreach($service->settings as $k => $v) {
$form_services[$service->machine_name][$k] = array(
"key" => $v,
"value" => $this->settings->get($v)
);
}
}
$sender->data("form", $form);
$sender->data("form_services", $form_services);
return $this->view('admin/oc_settings');
}
public function action_settingsController_social($sender, $action, $param1 = null) {
switch($action) {
case "accounts":
$this->settings_social_accounts($sender);
break;
case "unlink":
$this->settings_social_unlink_account($sender, $param1);
break;
default:
$sender->render404();
break;
}
}
private function settings_social_accounts($sender) {
$sender->profile("social_accounts");
$accounts = ET::getInstance("ocMemberSocialModel")->getAccounts(ET::$session->userId);
foreach($accounts as &$account) {
$account["logo"] = URL($this->resource("images/settings/".$account["socialNetwork"].".png"));
}
$sender->data("accounts", $accounts);
$sender->data("allow_unlink", $this->settings->get(OCSettings::ALLOW_UNLINK));
$sender->data("accounts_exist", !empty($accounts));
$sender->renderProfile($this->view("admin/oc_social_accounts"));
}
private function settings_social_unlink_account($sender, $id) {
if(!$this->settings->get(OCSettings::ALLOW_UNLINK) || !ET::getInstance("ocMemberSocialModel")->isApropriateUser(ET::$session->userId, $id)) {
$sender->render404();
return;
}
ET::getInstance("ocMemberSocialModel")->deleteById($id);
redirect(URL("settings/social/accounts"));
}
public function setup($oldVersion = "") {
ET::$database->structure()->table("member")
->dropColumn("fromSN")
->dropColumn("TWid")
->dropColumn("TWconfirmed")
->exec(false);
ET::$database->structure()->table("oc_member_social")
->column("id", "int(11) unsigned", false)
->column("member_Id", "int(11) unsigned", false)
->column("socialNetwork", "varchar(255)", false)
->column("socialId", "varchar(255)", false)
->column("profileLink", "varchar(255)", false)
->column("name", "varchar(255)", false)
->column("confirmed", "tinyint unsigned", false)
->column("confirmationHash", "varchar(255)")
->column("confirmationSent", "int(11) unsigned", 0)
->key("id", "primary")
->key(array("socialNetwork","socialId"), "unique")
->exec(false);
ET::$database->structure()->table("oc_settings")
->column("name", "varchar(50)", false)
->column("value", "varchar(100)", false)
->key("name", "primary")
->exec(false);
ET::$database->query(strtr("ALTER TABLE [prefix]oc_member_social ADD FOREIGN KEY(member_Id) REFERENCES [prefix]member(memberId)", array('[prefix]' => C("esoTalk.database.prefix"))));
// ET::$database->query($this->services->getSettingsSchemaQuery(C("esoTalk.database.prefix")));
return true;
}
private function social_auth($sender) {
if(ET::$session->user) {
$sender->message("You are already logged in");
redirect(URL());
}
$this->opauth_connect->doRequest();
}
private function social_callback($sender) {
try {
$response = $this->opauth_connect->getResponse();
switch($this->opauth_connect->validateAccount($response["static"]['uid'], $response["static"]['provider'])) {
case OpauthConnect::ACCOUNT_CONFIRMED:
$this->login($this->opauth_connect->getLastAccountValidation());
break;
case OpauthConnect::ACCOUNT_NOT_EXISTS:
ET::$session->store("OpauthConnect", $response["static"]);
$this->social_setup($sender, $response["editable"]);
return;
case OpauthConnect::ACCOUNT_NOT_CONFIRMED:
$sender->message("Your account was not confirmed. <a href='".URL("user/social/sendconfirmation/".$this->opauth_connect->getLastAccountValidation())."'>Send confirmation letter again</a>", "warning");
break;
}
}
catch(Exception $ex) {
$sender->message($ex->getMessage(), "warning");
}
redirect(URL());
}
private function social_confirm($sender, $hash) {
if($result = ET::getInstance("ocMemberSocialModel")->validateConfirmationHash($hash)) {
$sender->message(T("You successfully confirmed your new account"), "success");
$this->login($result);
}
$sender->message(T("Invalid confirmation hash"), "warning");
redirect(URL());
}
private function social_remember() {
ET::$session->store("remember", (int)R("remember", 0));
}
private function social_sendConfirmation($sender, $row_id, $is_new_user) {
$data = ET::getInstance("ocMemberSocialModel")->getConfirmationData($row_id);
if(time() - $data["confirmationSent"] > OpauthConnect::CONFIRMATION_INTERVAL) {
$params = array(
"confirmationUrl" => URL("user/social/confirm/".$data['confirmationHash'], true),
"profileLink" => $data["profileLink"],
"socialName" => $data["name"],
"socialNetwork" => $data["socialNetwork"],
"userName" => $data["username"],
"forumName" => C("esoTalk.forumTitle"),
"isNewUser" => $is_new_user
);
$title = strtr($this->settings->get(OCSettings::CONFIRM_EMAIL_SUBJ), array(
"[forumName]" => C("esoTalk.forumTitle"),
"[socialNetwork]" => $data["socialNetwork"],
"[socialName]" => $data["name"],
"[userName]" => $data["username"]
));
sendEmail($data["email"], $title, $sender->getViewContents('emails/oc_confirmation', $params));
ET::getInstance("ocMemberSocialModel")->sentConfirmation($row_id);
$sender->message("Confirmation letter was sent to your e-mail address (".$data["email"].")", "success");
}
else {
$sender->message(T("Confirmation letter can be sent once per 5 minutes. Please wait"), "warning");
}
redirect(URL());
}
private function social_setup($sender, $form_data = array()) {
$session_data = ET::$session->get("OpauthConnect");
if(!$session_data) {
$sender->message(T("Time is out. Please, try again"), "warning");
redirect(URL("user/login"));
}
$email_only = false;
if(ET::memberModel()->validateEmail($session_data["email"]) == "emailTaken") {
$email_only = true;
}
$form = ETFactory::make("form");
$form->action = URL("user/social/setup");
$sender->data("show_password", false);
if($form->validPostBack("save")) {
if(!$session_data["email"]) {
if(!$form->getValue("email")) {
$form->error("email", T("Email must be set"));
}
if(ET::memberModel()->validateEmail($form->getValue("email"), false) !== null) {
$form->error("email", T("Email is invalid"));
}
}
if(!$email_only) {
if(!$form->getValue("generate_password")) {
// @TODO: refactor this in future
$sender->data("show_password", true);
if(ET::memberModel()->validatePassword($form->getValue("password")) !== null) {
$form->error("password", T("Password is too shot"));
}
elseif($form->getValue("password") != $form->getValue("password_repeat")) {
$form->error("password_repeat", T("Passwords not match"));
}
}
switch(ET::memberModel()->validateUsername($form->getValue("username"))) {
case 'nameTaken':
$form->error("username", T("Username is already exists"));
break;
case 'invalidUsername':
$form->error("username", T("Username is incorrect"));
break;
}
}
if(!$form->errorCount()) {
if($session_data["email"]) {
$email = $session_data["email"];
$needs_confirmation = false;
}
else {
$email = $form->getValue("email");
$needs_confirmation = true;
}
switch(ET::memberModel()->validateEmail($email)) {
case null:
$password = $form->getValue("generate_password") ? generateRandomString(12, OpauthConnect::PASSWORD_CHARS) : $form->getValue("password");
if($form->getValue("generate_password")) {
$params = array(
"userName" => $form->getValue("username"),
"password" => $password,
"forumName" => C("esoTalk.forumTitle")
);
$title = strtr($this->settings->get(OCSettings::PASS_EMAIL_SUBJ), array(
"[forumName]" => C("esoTalk.forumTitle"),
"[userName]" => $form->getValue("username")
));
sendEmail($email, $title, $sender->getViewContents('emails/oc_password', $params));
}
$data = array(
"username" => $form->getValue("username"),
"email" => $email,
"password" => $password,
"account" => ACCOUNT_MEMBER,
"confirmed" => true //this field is not used. just dummy value
);
$memberId = ET::memberModel()->create($data);
$avatar_exists = false;
$is_new_user = true;
break;
case "emailTaken":
$member = ET::memberModel()->get(array("email" => $email));
$avatar_exists = $member[0]["avatarFormat"];
$memberId = $member[0]["memberId"];
$is_new_user = null;
break;
}
ET::$session->remove("OpauthConnect");
if(!$avatar_exists && $form->getValue("avatar")) {
$avatar = ET::uploader()->saveAsImage($form->getValue("avatar"), PATH_UPLOADS."/avatars/".$memberId, C("esoTalk.avatars.width"), C("esoTalk.avatars.height"), "crop");
ET::memberModel()->updateById($memberId, array("avatarFormat" => pathinfo($avatar, PATHINFO_EXTENSION)));
}
$row_id = ET::getInstance("ocMemberSocialModel")->addAccount(
$memberId,
$session_data["provider"],
$session_data["uid"],
$session_data["link"],
$session_data["name"],
!$needs_confirmation,
$needs_confirmation ? md5(uniqid(rand())) : null
);
if($needs_confirmation) {
$this->social_sendConfirmation($sender, $row_id, $is_new_user);
}
else {
$this->login($memberId);
}
}
}
foreach($form_data as $key => $value) {
$form->setValue($key, $value);
}
$sender->data("show_email", true);
if($session_data["email"]) {
if($form->isPostBack()) $_POST['email'] = $session_data["email"];
else $form->setValue("email", $session_data["email"]);
$sender->data("show_email", false);
}
$sender->data("email_only", $email_only);
$sender->data("form", $form);
$sender->render("social/oc_account_setup");
}
public function action_userController_social($sender, $action, $param1 = null, $param2 = null) {
switch($action) {
case "setup":
$this->social_setup($sender);
break;
case "callback":
$this->social_callback($sender);
break;
case "sendconfirmation":
$this->social_sendConfirmation($sender, $param1, $param2);
break;
case "confirm":
$this->social_confirm($sender, $param1);
break;
case "remember":
$this->social_remember();
break;
default:
if($this->services->isServiceExists($action)) {
$this->social_auth($sender);
}
else {
$sender->render404();
}
break;
}
}
public function uninstall() {}
}
|
phisyks/discuss
|
addons/plugins/OpauthConnect/plugin.php
|
PHP
|
gpl-2.0
| 20,268
|
/*!
* Font Awesome 4.2.0 by @davegandy - http://fontawesome.io - @fontawesome
* License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License)
*/
/* FONT PATH
* -------------------------- */
@font-face {
font-family: 'FontAwesome';
src: url('fonts/fontawesome-webfont.eot?v=4.2.0');
src: url('fonts/fontawesome-webfont.eot?#iefix&v=4.2.0') format('embedded-opentype'), url('fonts/fontawesome-webfont.woff?v=4.2.0') format('woff'), url('fonts/fontawesome-webfont.ttf?v=4.2.0') format('truetype'), url('fonts/fontawesome-webfont.svg?v=4.2.0#fontawesomeregular') format('svg');
font-weight: normal;
font-style: normal;
}
#wdi_spider_popup_wrap .fa,
div[id^="bwg_container"] .fa,
#bwg_rotate_image .fa {
display: inline-block;
font-family: FontAwesome !important;
font-style: normal;
font-weight: normal;
line-height: 1 !important;
text-rendering: auto;
-webkit-font-smoothing: antialiased !important;
-moz-osx-font-smoothing: grayscale !important;
}
/* makes the font 33% larger relative to the icon container */
.fa-lg {
font-size: 1.33333333em;
line-height: 0.75em;
vertical-align: -15%;
}
.fa-2x {
font-size: 2em;
}
.fa-3x {
font-size: 3em;
}
.fa-4x {
font-size: 4em;
}
.fa-5x {
font-size: 5em;
}
.fa-fw {
width: 1.28571429em;
text-align: center;
}
.fa-ul {
padding-left: 0;
margin-left: 2.14285714em;
list-style-type: none;
}
.fa-ul > li {
position: relative;
}
.fa-li {
position: absolute;
left: -2.14285714em;
width: 2.14285714em;
top: 0.14285714em;
text-align: center;
}
.fa-li.fa-lg {
left: -1.85714286em;
}
.fa-border {
padding: .2em .25em .15em;
border: solid 0.08em #eeeeee;
border-radius: .1em;
}
.pull-right {
float: right;
}
.pull-left {
float: left;
}
.fa.pull-left {
margin-right: .3em;
}
.fa.pull-right {
margin-left: .3em;
}
.fa-spin {
-webkit-animation: spin 2s infinite linear;
-moz-animation: spin 2s infinite linear;
-o-animation: spin 2s infinite linear;
animation: spin 2s infinite linear;
}
@-moz-keyframes spin {
0% {
-moz-transform: rotate(0deg);
}
100% {
-moz-transform: rotate(359deg);
}
}
@-webkit-keyframes spin {
0% {
-webkit-transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(359deg);
}
}
@-o-keyframes spin {
0% {
-o-transform: rotate(0deg);
}
100% {
-o-transform: rotate(359deg);
}
}
@-ms-keyframes spin {
0% {
-ms-transform: rotate(0deg);
}
100% {
-ms-transform: rotate(359deg);
}
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(359deg);
}
}
.fa-rotate-90 {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-ms-transform: rotate(90deg);
-o-transform: rotate(90deg);
transform: rotate(90deg);
}
.fa-rotate-180 {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2);
-webkit-transform: rotate(180deg);
-moz-transform: rotate(180deg);
-ms-transform: rotate(180deg);
-o-transform: rotate(180deg);
transform: rotate(180deg);
}
.fa-rotate-270 {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
-webkit-transform: rotate(270deg);
-moz-transform: rotate(270deg);
-ms-transform: rotate(270deg);
-o-transform: rotate(270deg);
transform: rotate(270deg);
}
.fa-flip-horizontal {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1);
-webkit-transform: scale(-1, 1);
-moz-transform: scale(-1, 1);
-ms-transform: scale(-1, 1);
-o-transform: scale(-1, 1);
transform: scale(-1, 1);
}
.fa-flip-vertical {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1);
-webkit-transform: scale(1, -1);
-moz-transform: scale(1, -1);
-ms-transform: scale(1, -1);
-o-transform: scale(1, -1);
transform: scale(1, -1);
}
:root .fa-rotate-90,
:root .fa-rotate-180,
:root .fa-rotate-270,
:root .fa-flip-horizontal,
:root .fa-flip-vertical {
filter: none;
}
.fa-stack {
position: relative;
display: inline-block;
width: 2em;
height: 2em;
line-height: 2em;
vertical-align: middle;
}
.fa-stack-1x,
.fa-stack-2x {
position: absolute;
left: 0;
width: 100%;
text-align: center;
}
.fa-stack-1x {
line-height: inherit;
}
.fa-stack-2x {
font-size: 2em;
}
.fa-inverse {
color: #ffffff;
}
/* Font Awesome uses the Unicode Private Use Area (PUA) to ensure screen
readers do not read off random characters that represent icons */
.fa-glass:before {
content: "\f000";
}
.fa-music:before {
content: "\f001";
}
.fa-search:before {
content: "\f002";
}
.fa-envelope-o:before {
content: "\f003";
}
.fa-heart:before {
content: "\f004";
}
.fa-star:before {
content: "\f005";
}
.fa-star-o:before {
content: "\f006";
}
.fa-user:before {
content: "\f007";
}
.fa-film:before {
content: "\f008";
}
.fa-th-large:before {
content: "\f009";
}
.fa-th:before {
content: "\f00a";
}
.fa-th-list:before {
content: "\f00b";
}
.fa-check:before {
content: "\f00c";
}
.fa-remove:before,
.fa-close:before,
.fa-times:before {
content: "\f00d";
}
.fa-search-plus:before {
content: "\f00e";
}
.fa-search-minus:before {
content: "\f010";
}
.fa-power-off:before {
content: "\f011";
}
.fa-signal:before {
content: "\f012";
}
.fa-gear:before,
.fa-cog:before {
content: "\f013";
}
.fa-trash-o:before {
content: "\f014";
}
.fa-home:before {
content: "\f015";
}
.fa-file-o:before {
content: "\f016";
}
.fa-clock-o:before {
content: "\f017";
}
.fa-road:before {
content: "\f018";
}
.fa-download:before {
content: "\f019";
}
.fa-arrow-circle-o-down:before {
content: "\f01a";
}
.fa-arrow-circle-o-up:before {
content: "\f01b";
}
.fa-inbox:before {
content: "\f01c";
}
.fa-play-circle-o:before {
content: "\f01d";
}
.fa-rotate-right:before,
.fa-repeat:before {
content: "\f01e";
}
.fa-refresh:before {
content: "\f021";
}
.fa-list-alt:before {
content: "\f022";
}
.fa-lock:before {
content: "\f023";
}
.fa-flag:before {
content: "\f024";
}
.fa-headphones:before {
content: "\f025";
}
.fa-volume-off:before {
content: "\f026";
}
.fa-volume-down:before {
content: "\f027";
}
.fa-volume-up:before {
content: "\f028";
}
.fa-qrcode:before {
content: "\f029";
}
.fa-barcode:before {
content: "\f02a";
}
.fa-tag:before {
content: "\f02b";
}
.fa-tags:before {
content: "\f02c";
}
.fa-book:before {
content: "\f02d";
}
.fa-bookmark:before {
content: "\f02e";
}
.fa-print:before {
content: "\f02f";
}
.fa-camera:before {
content: "\f030";
}
.fa-font:before {
content: "\f031";
}
.fa-bold:before {
content: "\f032";
}
.fa-italic:before {
content: "\f033";
}
.fa-text-height:before {
content: "\f034";
}
.fa-text-width:before {
content: "\f035";
}
.fa-align-left:before {
content: "\f036";
}
.fa-align-center:before {
content: "\f037";
}
.fa-align-right:before {
content: "\f038";
}
.fa-align-justify:before {
content: "\f039";
}
.fa-list:before {
content: "\f03a";
}
.fa-dedent:before,
.fa-outdent:before {
content: "\f03b";
}
.fa-indent:before {
content: "\f03c";
}
.fa-video-camera:before {
content: "\f03d";
}
.fa-photo:before,
.fa-image:before,
.fa-picture-o:before {
content: "\f03e";
}
.fa-pencil:before {
content: "\f040";
}
.fa-map-marker:before {
content: "\f041";
}
.fa-adjust:before {
content: "\f042";
}
.fa-tint:before {
content: "\f043";
}
.fa-edit:before,
.fa-pencil-square-o:before {
content: "\f044";
}
.fa-share-square-o:before {
content: "\f045";
}
.fa-check-square-o:before {
content: "\f046";
}
.fa-arrows:before {
content: "\f047";
}
.fa-step-backward:before {
content: "\f048";
}
.fa-fast-backward:before {
content: "\f049";
}
.fa-backward:before {
content: "\f04a";
}
.fa-play:before {
content: "\f04b";
}
.fa-pause:before {
content: "\f04c";
}
.fa-stop:before {
content: "\f04d";
}
.fa-forward:before {
content: "\f04e";
}
.fa-fast-forward:before {
content: "\f050";
}
.fa-step-forward:before {
content: "\f051";
}
.fa-eject:before {
content: "\f052";
}
.fa-chevron-left:before {
content: "\f053";
}
.fa-chevron-right:before {
content: "\f054";
}
.fa-plus-circle:before {
content: "\f055";
}
.fa-minus-circle:before {
content: "\f056";
}
.fa-times-circle:before {
content: "\f057";
}
.fa-check-circle:before {
content: "\f058";
}
.fa-question-circle:before {
content: "\f059";
}
.fa-info-circle:before {
content: "\f05a";
}
.fa-crosshairs:before {
content: "\f05b";
}
.fa-times-circle-o:before {
content: "\f05c";
}
.fa-check-circle-o:before {
content: "\f05d";
}
.fa-ban:before {
content: "\f05e";
}
.fa-arrow-left:before {
content: "\f060";
}
.fa-arrow-right:before {
content: "\f061";
}
.fa-arrow-up:before {
content: "\f062";
}
.fa-arrow-down:before {
content: "\f063";
}
.fa-mail-forward:before,
.fa-share:before {
content: "\f064";
}
.fa-resize-full:before,
.fa-expand:before {
content: "\f065";
}
.fa-resize-small:before,
.fa-compress:before {
content: "\f066";
}
.fa-plus:before {
content: "\f067";
}
.fa-minus:before {
content: "\f068";
}
.fa-asterisk:before {
content: "\f069";
}
.fa-exclamation-circle:before {
content: "\f06a";
}
.fa-gift:before {
content: "\f06b";
}
.fa-leaf:before {
content: "\f06c";
}
.fa-fire:before {
content: "\f06d";
}
.fa-eye:before {
content: "\f06e";
}
.fa-eye-slash:before {
content: "\f070";
}
.fa-warning:before,
.fa-exclamation-triangle:before {
content: "\f071";
}
.fa-plane:before {
content: "\f072";
}
.fa-calendar:before {
content: "\f073";
}
.fa-random:before {
content: "\f074";
}
.fa-comment:before {
content: "\f075";
}
.fa-magnet:before {
content: "\f076";
}
.fa-chevron-up:before {
content: "\f077";
}
.fa-chevron-down:before {
content: "\f078";
}
.fa-retweet:before {
content: "\f079";
}
.fa-shopping-cart:before {
content: "\f07a";
}
.fa-folder:before {
content: "\f07b";
}
.fa-folder-open:before {
content: "\f07c";
}
.fa-resize-vertical:before,
.fa-arrows-v:before {
content: "\f07d";
}
.fa-resize-horizontal:before,
.fa-arrows-h:before {
content: "\f07e";
}
.fa-bar-chart-o:before,
.fa-bar-chart:before {
content: "\f080";
}
.fa-twitter-square:before {
content: "\f081";
}
.fa-facebook-square:before {
content: "\f082";
}
.fa-camera-retro:before {
content: "\f083";
}
.fa-key:before {
content: "\f084";
}
.fa-gears:before,
.fa-cogs:before {
content: "\f085";
}
.fa-comments:before {
content: "\f086";
}
.fa-thumbs-o-up:before {
content: "\f087";
}
.fa-thumbs-o-down:before {
content: "\f088";
}
.fa-star-half:before {
content: "\f089";
}
.fa-heart-o:before {
content: "\f08a";
}
.fa-sign-out:before {
content: "\f08b";
}
.fa-linkedin-square:before {
content: "\f08c";
}
.fa-thumb-tack:before {
content: "\f08d";
}
.fa-external-link:before {
content: "\f08e";
}
.fa-sign-in:before {
content: "\f090";
}
.fa-trophy:before {
content: "\f091";
}
.fa-github-square:before {
content: "\f092";
}
.fa-upload:before {
content: "\f093";
}
.fa-lemon-o:before {
content: "\f094";
}
.fa-phone:before {
content: "\f095";
}
.fa-square-o:before {
content: "\f096";
}
.fa-bookmark-o:before {
content: "\f097";
}
.fa-phone-square:before {
content: "\f098";
}
.fa-twitter:before {
content: "\f099";
}
.fa-facebook:before {
content: "\f09a";
}
.fa-github:before {
content: "\f09b";
}
.fa-unlock:before {
content: "\f09c";
}
.fa-credit-card:before {
content: "\f09d";
}
.fa-rss:before {
content: "\f09e";
}
.fa-hdd-o:before {
content: "\f0a0";
}
.fa-bullhorn:before {
content: "\f0a1";
}
.fa-bell:before {
content: "\f0f3";
}
.fa-certificate:before {
content: "\f0a3";
}
.fa-hand-o-right:before {
content: "\f0a4";
}
.fa-hand-o-left:before {
content: "\f0a5";
}
.fa-hand-o-up:before {
content: "\f0a6";
}
.fa-hand-o-down:before {
content: "\f0a7";
}
.fa-arrow-circle-left:before {
content: "\f0a8";
}
.fa-arrow-circle-right:before {
content: "\f0a9";
}
.fa-arrow-circle-up:before {
content: "\f0aa";
}
.fa-arrow-circle-down:before {
content: "\f0ab";
}
.fa-globe:before {
content: "\f0ac";
}
.fa-wrench:before {
content: "\f0ad";
}
.fa-tasks:before {
content: "\f0ae";
}
.fa-filter:before {
content: "\f0b0";
}
.fa-briefcase:before {
content: "\f0b1";
}
.fa-fullscreen:before,
.fa-arrows-alt:before {
content: "\f0b2";
}
.fa-group:before,
.fa-users:before {
content: "\f0c0";
}
.fa-chain:before,
.fa-link:before {
content: "\f0c1";
}
.fa-cloud:before {
content: "\f0c2";
}
.fa-flask:before {
content: "\f0c3";
}
.fa-cut:before,
.fa-scissors:before {
content: "\f0c4";
}
.fa-copy:before,
.fa-files-o:before {
content: "\f0c5";
}
.fa-paperclip:before {
content: "\f0c6";
}
.fa-save:before,
.fa-floppy-o:before {
content: "\f0c7";
}
.fa-square:before {
content: "\f0c8";
}
.fa-navicon:before,
.fa-reorder:before,
.fa-bars:before {
content: "\f0c9";
}
.fa-list-ul:before {
content: "\f0ca";
}
.fa-list-ol:before {
content: "\f0cb";
}
.fa-strikethrough:before {
content: "\f0cc";
}
.fa-underline:before {
content: "\f0cd";
}
.fa-table:before {
content: "\f0ce";
}
.fa-magic:before {
content: "\f0d0";
}
.fa-truck:before {
content: "\f0d1";
}
.fa-pinterest:before {
content: "\f0d2";
}
.fa-pinterest-square:before {
content: "\f0d3";
}
.fa-google-plus-square:before {
content: "\f0d4";
}
.fa-google-plus:before {
content: "\f0d5";
}
.fa-money:before {
content: "\f0d6";
}
.fa-caret-down:before {
content: "\f0d7";
}
.fa-caret-up:before {
content: "\f0d8";
}
.fa-caret-left:before {
content: "\f0d9";
}
.fa-caret-right:before {
content: "\f0da";
}
.fa-columns:before {
content: "\f0db";
}
.fa-unsorted:before,
.fa-sort:before {
content: "\f0dc";
}
.fa-sort-down:before,
.fa-sort-desc:before {
content: "\f0dd";
}
.fa-sort-up:before,
.fa-sort-asc:before {
content: "\f0de";
}
.fa-envelope:before {
content: "\f0e0";
}
.fa-linkedin:before {
content: "\f0e1";
}
.fa-rotate-left:before,
.fa-undo:before {
content: "\f0e2";
}
.fa-legal:before,
.fa-gavel:before {
content: "\f0e3";
}
.fa-dashboard:before,
.fa-tachometer:before {
content: "\f0e4";
}
.fa-comment-o:before {
content: "\f0e5";
}
.fa-comments-o:before {
content: "\f0e6";
}
.fa-flash:before,
.fa-bolt:before {
content: "\f0e7";
}
.fa-sitemap:before {
content: "\f0e8";
}
.fa-umbrella:before {
content: "\f0e9";
}
.fa-paste:before,
.fa-clipboard:before {
content: "\f0ea";
}
.fa-lightbulb-o:before {
content: "\f0eb";
}
.fa-exchange:before {
content: "\f0ec";
}
.fa-cloud-download:before {
content: "\f0ed";
}
.fa-cloud-upload:before {
content: "\f0ee";
}
.fa-user-md:before {
content: "\f0f0";
}
.fa-stethoscope:before {
content: "\f0f1";
}
.fa-suitcase:before {
content: "\f0f2";
}
.fa-bell-o:before {
content: "\f0a2";
}
.fa-coffee:before {
content: "\f0f4";
}
.fa-cutlery:before {
content: "\f0f5";
}
.fa-file-text-o:before {
content: "\f0f6";
}
.fa-building-o:before {
content: "\f0f7";
}
.fa-hospital-o:before {
content: "\f0f8";
}
.fa-ambulance:before {
content: "\f0f9";
}
.fa-medkit:before {
content: "\f0fa";
}
.fa-fighter-jet:before {
content: "\f0fb";
}
.fa-beer:before {
content: "\f0fc";
}
.fa-h-square:before {
content: "\f0fd";
}
.fa-plus-square:before {
content: "\f0fe";
}
.fa-angle-double-left:before {
content: "\f100";
}
.fa-angle-double-right:before {
content: "\f101";
}
.fa-angle-double-up:before {
content: "\f102";
}
.fa-angle-double-down:before {
content: "\f103";
}
.fa-angle-left:before {
content: "\f104";
}
.fa-angle-right:before {
content: "\f105";
}
.fa-angle-up:before {
content: "\f106";
}
.fa-angle-down:before {
content: "\f107";
}
.fa-desktop:before {
content: "\f108";
}
.fa-laptop:before {
content: "\f109";
}
.fa-tablet:before {
content: "\f10a";
}
.fa-mobile-phone:before,
.fa-mobile:before {
content: "\f10b";
}
.fa-circle-o:before {
content: "\f10c";
}
.fa-quote-left:before {
content: "\f10d";
}
.fa-quote-right:before {
content: "\f10e";
}
.fa-spinner:before {
content: "\f110";
}
.fa-circle:before {
content: "\f111";
}
.fa-mail-reply:before,
.fa-reply:before {
content: "\f112";
}
.fa-github-alt:before {
content: "\f113";
}
.fa-folder-o:before {
content: "\f114";
}
.fa-folder-open-o:before {
content: "\f115";
}
.fa-smile-o:before {
content: "\f118";
}
.fa-frown-o:before {
content: "\f119";
}
.fa-meh-o:before {
content: "\f11a";
}
.fa-gamepad:before {
content: "\f11b";
}
.fa-keyboard-o:before {
content: "\f11c";
}
.fa-flag-o:before {
content: "\f11d";
}
.fa-flag-checkered:before {
content: "\f11e";
}
.fa-terminal:before {
content: "\f120";
}
.fa-code:before {
content: "\f121";
}
.fa-mail-reply-all:before,
.fa-reply-all:before {
content: "\f122";
}
.fa-star-half-empty:before,
.fa-star-half-full:before,
.fa-star-half-o:before {
content: "\f123";
}
.fa-location-arrow:before {
content: "\f124";
}
.fa-crop:before {
content: "\f125";
}
.fa-code-fork:before {
content: "\f126";
}
.fa-unlink:before,
.fa-chain-broken:before {
content: "\f127";
}
.fa-question:before {
content: "\f128";
}
.fa-info:before {
content: "\f129";
}
.fa-exclamation:before {
content: "\f12a";
}
.fa-superscript:before {
content: "\f12b";
}
.fa-subscript:before {
content: "\f12c";
}
.fa-eraser:before {
content: "\f12d";
}
.fa-puzzle-piece:before {
content: "\f12e";
}
.fa-microphone:before {
content: "\f130";
}
.fa-microphone-slash:before {
content: "\f131";
}
.fa-shield:before {
content: "\f132";
}
.fa-calendar-o:before {
content: "\f133";
}
.fa-fire-extinguisher:before {
content: "\f134";
}
.fa-rocket:before {
content: "\f135";
}
.fa-maxcdn:before {
content: "\f136";
}
.fa-chevron-circle-left:before {
content: "\f137";
}
.fa-chevron-circle-right:before {
content: "\f138";
}
.fa-chevron-circle-up:before {
content: "\f139";
}
.fa-chevron-circle-down:before {
content: "\f13a";
}
.fa-html5:before {
content: "\f13b";
}
.fa-css3:before {
content: "\f13c";
}
.fa-anchor:before {
content: "\f13d";
}
.fa-unlock-alt:before {
content: "\f13e";
}
.fa-bullseye:before {
content: "\f140";
}
.fa-ellipsis-h:before {
content: "\f141";
}
.fa-ellipsis-v:before {
content: "\f142";
}
.fa-rss-square:before {
content: "\f143";
}
.fa-play-circle:before {
content: "\f144";
}
.fa-ticket:before {
content: "\f145";
}
.fa-minus-square:before {
content: "\f146";
}
.fa-minus-square-o:before {
content: "\f147";
}
.fa-level-up:before {
content: "\f148";
}
.fa-level-down:before {
content: "\f149";
}
.fa-check-square:before {
content: "\f14a";
}
.fa-pencil-square:before {
content: "\f14b";
}
.fa-external-link-square:before {
content: "\f14c";
}
.fa-share-square:before {
content: "\f14d";
}
.fa-compass:before {
content: "\f14e";
}
.fa-toggle-down:before,
.fa-caret-square-o-down:before {
content: "\f150";
}
.fa-toggle-up:before,
.fa-caret-square-o-up:before {
content: "\f151";
}
.fa-toggle-right:before,
.fa-caret-square-o-right:before {
content: "\f152";
}
.fa-euro:before,
.fa-eur:before {
content: "\f153";
}
.fa-gbp:before {
content: "\f154";
}
.fa-dollar:before,
.fa-usd:before {
content: "\f155";
}
.fa-rupee:before,
.fa-inr:before {
content: "\f156";
}
.fa-cny:before,
.fa-rmb:before,
.fa-yen:before,
.fa-jpy:before {
content: "\f157";
}
.fa-ruble:before,
.fa-rouble:before,
.fa-rub:before {
content: "\f158";
}
.fa-won:before,
.fa-krw:before {
content: "\f159";
}
.fa-bitcoin:before,
.fa-btc:before {
content: "\f15a";
}
.fa-file:before {
content: "\f15b";
}
.fa-file-text:before {
content: "\f15c";
}
.fa-sort-alpha-asc:before {
content: "\f15d";
}
.fa-sort-alpha-desc:before {
content: "\f15e";
}
.fa-sort-amount-asc:before {
content: "\f160";
}
.fa-sort-amount-desc:before {
content: "\f161";
}
.fa-sort-numeric-asc:before {
content: "\f162";
}
.fa-sort-numeric-desc:before {
content: "\f163";
}
.fa-thumbs-up:before {
content: "\f164";
}
.fa-thumbs-down:before {
content: "\f165";
}
.fa-youtube-square:before {
content: "\f166";
}
.fa-youtube:before {
content: "\f167";
}
.fa-xing:before {
content: "\f168";
}
.fa-xing-square:before {
content: "\f169";
}
.fa-youtube-play:before {
content: "\f16a";
}
.fa-dropbox:before {
content: "\f16b";
}
.fa-stack-overflow:before {
content: "\f16c";
}
.fa-instagram:before {
content: "\f16d";
}
.fa-flickr:before {
content: "\f16e";
}
.fa-adn:before {
content: "\f170";
}
.fa-bitbucket:before {
content: "\f171";
}
.fa-bitbucket-square:before {
content: "\f172";
}
.fa-tumblr:before {
content: "\f173";
}
.fa-tumblr-square:before {
content: "\f174";
}
.fa-long-arrow-down:before {
content: "\f175";
}
.fa-long-arrow-up:before {
content: "\f176";
}
.fa-long-arrow-left:before {
content: "\f177";
}
.fa-long-arrow-right:before {
content: "\f178";
}
.fa-apple:before {
content: "\f179";
}
.fa-windows:before {
content: "\f17a";
}
.fa-android:before {
content: "\f17b";
}
.fa-linux:before {
content: "\f17c";
}
.fa-dribbble:before {
content: "\f17d";
}
.fa-skype:before {
content: "\f17e";
}
.fa-foursquare:before {
content: "\f180";
}
.fa-trello:before {
content: "\f181";
}
.fa-female:before {
content: "\f182";
}
.fa-male:before {
content: "\f183";
}
.fa-gittip:before {
content: "\f184";
}
.fa-sun-o:before {
content: "\f185";
}
.fa-moon-o:before {
content: "\f186";
}
.fa-archive:before {
content: "\f187";
}
.fa-bug:before {
content: "\f188";
}
.fa-vk:before {
content: "\f189";
}
.fa-weibo:before {
content: "\f18a";
}
.fa-renren:before {
content: "\f18b";
}
.fa-pagelines:before {
content: "\f18c";
}
.fa-stack-exchange:before {
content: "\f18d";
}
.fa-arrow-circle-o-right:before {
content: "\f18e";
}
.fa-arrow-circle-o-left:before {
content: "\f190";
}
.fa-toggle-left:before,
.fa-caret-square-o-left:before {
content: "\f191";
}
.fa-dot-circle-o:before {
content: "\f192";
}
.fa-wheelchair:before {
content: "\f193";
}
.fa-vimeo-square:before {
content: "\f194";
}
.fa-turkish-lira:before,
.fa-try:before {
content: "\f195";
}
.fa-plus-square-o:before {
content: "\f196";
}
.fa-space-shuttle:before {
content: "\f197";
}
.fa-slack:before {
content: "\f198";
}
.fa-envelope-square:before {
content: "\f199";
}
.fa-wordpress:before {
content: "\f19a";
}
.fa-openid:before {
content: "\f19b";
}
.fa-institution:before,
.fa-bank:before,
.fa-university:before {
content: "\f19c";
}
.fa-mortar-board:before,
.fa-graduation-cap:before {
content: "\f19d";
}
.fa-yahoo:before {
content: "\f19e";
}
.fa-google:before {
content: "\f1a0";
}
.fa-reddit:before {
content: "\f1a1";
}
.fa-reddit-square:before {
content: "\f1a2";
}
.fa-stumbleupon-circle:before {
content: "\f1a3";
}
.fa-stumbleupon:before {
content: "\f1a4";
}
.fa-delicious:before {
content: "\f1a5";
}
.fa-digg:before {
content: "\f1a6";
}
.fa-pied-piper:before {
content: "\f1a7";
}
.fa-pied-piper-alt:before {
content: "\f1a8";
}
.fa-drupal:before {
content: "\f1a9";
}
.fa-joomla:before {
content: "\f1aa";
}
.fa-language:before {
content: "\f1ab";
}
.fa-fax:before {
content: "\f1ac";
}
.fa-building:before {
content: "\f1ad";
}
.fa-child:before {
content: "\f1ae";
}
.fa-paw:before {
content: "\f1b0";
}
.fa-spoon:before {
content: "\f1b1";
}
.fa-cube:before {
content: "\f1b2";
}
.fa-cubes:before {
content: "\f1b3";
}
.fa-behance:before {
content: "\f1b4";
}
.fa-behance-square:before {
content: "\f1b5";
}
.fa-steam:before {
content: "\f1b6";
}
.fa-steam-square:before {
content: "\f1b7";
}
.fa-recycle:before {
content: "\f1b8";
}
.fa-automobile:before,
.fa-car:before {
content: "\f1b9";
}
.fa-cab:before,
.fa-taxi:before {
content: "\f1ba";
}
.fa-tree:before {
content: "\f1bb";
}
.fa-spotify:before {
content: "\f1bc";
}
.fa-deviantart:before {
content: "\f1bd";
}
.fa-soundcloud:before {
content: "\f1be";
}
.fa-database:before {
content: "\f1c0";
}
.fa-file-pdf-o:before {
content: "\f1c1";
}
.fa-file-word-o:before {
content: "\f1c2";
}
.fa-file-excel-o:before {
content: "\f1c3";
}
.fa-file-powerpoint-o:before {
content: "\f1c4";
}
.fa-file-photo-o:before,
.fa-file-picture-o:before,
.fa-file-image-o:before {
content: "\f1c5";
}
.fa-file-zip-o:before,
.fa-file-archive-o:before {
content: "\f1c6";
}
.fa-file-sound-o:before,
.fa-file-audio-o:before {
content: "\f1c7";
}
.fa-file-movie-o:before,
.fa-file-video-o:before {
content: "\f1c8";
}
.fa-file-code-o:before {
content: "\f1c9";
}
.fa-vine:before {
content: "\f1ca";
}
.fa-codepen:before {
content: "\f1cb";
}
.fa-jsfiddle:before {
content: "\f1cc";
}
.fa-life-bouy:before,
.fa-life-buoy:before,
.fa-life-saver:before,
.fa-support:before,
.fa-life-ring:before {
content: "\f1cd";
}
.fa-circle-o-notch:before {
content: "\f1ce";
}
.fa-ra:before,
.fa-rebel:before {
content: "\f1d0";
}
.fa-ge:before,
.fa-empire:before {
content: "\f1d1";
}
.fa-git-square:before {
content: "\f1d2";
}
.fa-git:before {
content: "\f1d3";
}
.fa-hacker-news:before {
content: "\f1d4";
}
.fa-tencent-weibo:before {
content: "\f1d5";
}
.fa-qq:before {
content: "\f1d6";
}
.fa-wechat:before,
.fa-weixin:before {
content: "\f1d7";
}
.fa-send:before,
.fa-paper-plane:before {
content: "\f1d8";
}
.fa-send-o:before,
.fa-paper-plane-o:before {
content: "\f1d9";
}
.fa-history:before {
content: "\f1da";
}
.fa-circle-thin:before {
content: "\f1db";
}
.fa-header:before {
content: "\f1dc";
}
.fa-paragraph:before {
content: "\f1dd";
}
.fa-sliders:before {
content: "\f1de";
}
.fa-share-alt:before {
content: "\f1e0";
}
.fa-share-alt-square:before {
content: "\f1e1";
}
.fa-bomb:before {
content: "\f1e2";
}
.fa-soccer-ball-o:before,
.fa-futbol-o:before {
content: "\f1e3";
}
.fa-tty:before {
content: "\f1e4";
}
.fa-binoculars:before {
content: "\f1e5";
}
.fa-plug:before {
content: "\f1e6";
}
.fa-slideshare:before {
content: "\f1e7";
}
.fa-twitch:before {
content: "\f1e8";
}
.fa-yelp:before {
content: "\f1e9";
}
.fa-newspaper-o:before {
content: "\f1ea";
}
.fa-wifi:before {
content: "\f1eb";
}
.fa-calculator:before {
content: "\f1ec";
}
.fa-paypal:before {
content: "\f1ed";
}
.fa-google-wallet:before {
content: "\f1ee";
}
.fa-cc-visa:before {
content: "\f1f0";
}
.fa-cc-mastercard:before {
content: "\f1f1";
}
.fa-cc-discover:before {
content: "\f1f2";
}
.fa-cc-amex:before {
content: "\f1f3";
}
.fa-cc-paypal:before {
content: "\f1f4";
}
.fa-cc-stripe:before {
content: "\f1f5";
}
.fa-bell-slash:before {
content: "\f1f6";
}
.fa-bell-slash-o:before {
content: "\f1f7";
}
.fa-trash:before {
content: "\f1f8";
}
.fa-copyright:before {
content: "\f1f9";
}
.fa-at:before {
content: "\f1fa";
}
.fa-eyedropper:before {
content: "\f1fb";
}
.fa-paint-brush:before {
content: "\f1fc";
}
.fa-birthday-cake:before {
content: "\f1fd";
}
.fa-area-chart:before {
content: "\f1fe";
}
.fa-pie-chart:before {
content: "\f200";
}
.fa-line-chart:before {
content: "\f201";
}
.fa-lastfm:before {
content: "\f202";
}
.fa-lastfm-square:before {
content: "\f203";
}
.fa-toggle-off:before {
content: "\f204";
}
.fa-toggle-on:before {
content: "\f205";
}
.fa-bicycle:before {
content: "\f206";
}
.fa-bus:before {
content: "\f207";
}
.fa-ioxhost:before {
content: "\f208";
}
.fa-angellist:before {
content: "\f209";
}
.fa-cc:before {
content: "\f20a";
}
.fa-shekel:before,
.fa-sheqel:before,
.fa-ils:before {
content: "\f20b";
}
.fa-meanpath:before {
content: "\f20c";
}
|
npalomares/evenkeel
|
wp-content/plugins/wd-instagram-feed/css/font-awesome/font-awesome.css
|
CSS
|
gpl-2.0
| 27,510
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace Revista_Programar_Reader_Win8
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
}
}
|
pikax/papreader
|
Revista Programar Reader Win8/MainPage.xaml.cs
|
C#
|
gpl-2.0
| 828
|
<?php
/**
* Element: Agents
* Displays a multiselectbox of different browsers
*
* @package NoNumber Framework
* @version 14.4.1
*
* @author Peter van Westen <peter@nonumber.nl>
* @link http://www.nonumber.nl
* @copyright Copyright © 2014 NoNumber All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
defined('_JEXEC') or die;
require_once JPATH_PLUGINS . '/system/nnframework/helpers/text.php';
class JFormFieldNN_Agents extends JFormField
{
public $type = 'Agents';
private $params = null;
protected function getInput()
{
$this->params = $this->element->attributes();
$group = $this->get('group');
if (!is_array($this->value))
{
$this->value = explode(',', $this->value);
}
$agents = array();
switch ($group)
{
/* OS */
case 'os':
$agents[] = array('Windows (' . JText::_('JALL') . ')', 'Windows');
$agents[] = array('Windows 8', 'Windows nt 6.2');
$agents[] = array('Windows 7', 'Windows nt 6.1');
$agents[] = array('Windows Vista', 'Windows nt 6.0');
$agents[] = array('Windows Server 2003', 'Windows nt 5.2');
$agents[] = array('Windows XP', 'Windows nt 5.1');
$agents[] = array('Windows 2000 sp1', 'Windows nt 5.01');
$agents[] = array('Windows 2000', 'Windows nt 5.0');
$agents[] = array('Windows NT 4.0', 'Windows nt 4.0');
$agents[] = array('Windows Me', 'Win 9x 4.9');
$agents[] = array('Windows 98', 'Windows 98');
$agents[] = array('Windows 95', 'Windows 95');
$agents[] = array('Windows CE', 'Windows ce');
$agents[] = array('Mac OS (' . JText::_('JALL') . ')', '#(Mac OS|Mac_PowerPC|Macintosh)#');
$agents[] = array('Mac OSX (' . JText::_('JALL') . ')', 'Mac OS X');
$agents[] = array('Mac OSX Mountain Lion', 'Mac OS X 10.8');
$agents[] = array('Mac OSX Lion', 'Mac OS X 10.7');
$agents[] = array('Mac OSX Snow Leopard', 'Mac OS X 10.6');
$agents[] = array('Mac OSX Leopard', 'Mac OS X 10.5');
$agents[] = array('Mac OSX Tiger', 'Mac OS X 10.4');
$agents[] = array('Mac OSX Panther', 'Mac OS X 10.3');
$agents[] = array('Mac OSX Jaguar', 'Mac OS X 10.2');
$agents[] = array('Mac OSX Puma', 'Mac OS X 10.1');
$agents[] = array('Mac OSX Cheetah', 'Mac OS X 10.0');
$agents[] = array('Mac OS (classic)', '#(Mac_PowerPC|Macintosh)#');
$agents[] = array('Linux', '#(Linux|X11)#');
$agents[] = array('Open BSD', 'OpenBSD');
$agents[] = array('Sun OS', 'SunOS');
$agents[] = array('QNX', 'QNX');
$agents[] = array('BeOS', 'BeOS');
$agents[] = array('OS/2', 'OS/2');
break;
/* Browsers */
case 'browsers':
$agents[] = array('Chrome (' . JText::_('JALL') . ')', 'Chrome');
$agents[] = array('Chrome 35', 'Chrome/35.');
$agents[] = array('Chrome 34', 'Chrome/34.');
$agents[] = array('Chrome 33', 'Chrome/33.');
$agents[] = array('Chrome 32', 'Chrome/32.');
$agents[] = array('Chrome 31', 'Chrome/31.');
$agents[] = array('Chrome 30', 'Chrome/30.');
$agents[] = array('Chrome 29', 'Chrome/29.');
$agents[] = array('Chrome 28', 'Chrome/28.');
$agents[] = array('Chrome 27', 'Chrome/27.');
$agents[] = array('Chrome 26', 'Chrome/26.');
$agents[] = array('Chrome 25', 'Chrome/25.');
$agents[] = array('Chrome 24', 'Chrome/24.');
$agents[] = array('Chrome 23', 'Chrome/23.');
$agents[] = array('Chrome 22', 'Chrome/22.');
$agents[] = array('Chrome 21', 'Chrome/21.');
//$agents[] = array('Chrome 31-40', '#Chrome/(3[1-9]|40)\.#');
//$agents[] = array('Chrome 21-30', '#Chrome/(2[1-9]|30)\.#');
$agents[] = array('Chrome 11-20', '#Chrome/(1[1-9]|20)\.#');
$agents[] = array('Chrome 1-10', '#Chrome/([1-9]|10)\.#');
$agents[] = array('Firefox (' . JText::_('JALL') . ')', 'Firefox');
$agents[] = array('Firefox 30', 'Firefox/30.');
$agents[] = array('Firefox 29', 'Firefox/29.');
$agents[] = array('Firefox 28', 'Firefox/28.');
$agents[] = array('Firefox 27', 'Firefox/27.');
$agents[] = array('Firefox 26', 'Firefox/26.');
$agents[] = array('Firefox 25', 'Firefox/25.');
$agents[] = array('Firefox 24', 'Firefox/24.');
$agents[] = array('Firefox 23', 'Firefox/23.');
$agents[] = array('Firefox 22', 'Firefox/22.');
$agents[] = array('Firefox 21', 'Firefox/21.');
//$agents[] = array('Firefox 21-30', '#Firefox/(2[1-9]|30)\.#');
$agents[] = array('Firefox 11-20', '#Firefox/(1[1-9]|20)\.#');
$agents[] = array('Firefox 1-10', '#Firefox/([1-9]|10)\.#');
$agents[] = array('Internet Explorer (' . JText::_('JALL') . ')', 'MSIE');
$agents[] = array('Internet Explorer 10.6', 'MSIE 10.6');
$agents[] = array('Internet Explorer 10.0', 'MSIE 10.0');
$agents[] = array('Internet Explorer 10', 'MSIE 10.');
$agents[] = array('Internet Explorer 9', 'MSIE 9.');
$agents[] = array('Internet Explorer 8', 'MSIE 8.');
$agents[] = array('Internet Explorer 7', 'MSIE 7.');
$agents[] = array('Internet Explorer 1-6', '#MSIE [1-6]\.#');
$agents[] = array('Opera (' . JText::_('JALL') . ')', 'Opera');
$agents[] = array('Opera 13', 'Opera/13.');
$agents[] = array('Opera 12', 'Opera/12.');
$agents[] = array('Opera 11', 'Opera/11.');
$agents[] = array('Opera 10', 'Opera/10.');
$agents[] = array('Opera 1-9', '#Opera/[1-9]\.#');
$agents[] = array('Safari (' . JText::_('JALL') . ')', 'Safari');
$agents[] = array('Safari 8', '#Version/8\..*Safari/#');
$agents[] = array('Safari 7', '#Version/7\..*Safari/#');
$agents[] = array('Safari 6', '#Version/6\..*Safari/#');
$agents[] = array('Safari 5', '#Version/5\..*Safari/#');
$agents[] = array('Safari 4', '#Version/4\..*Safari/#');
$agents[] = array('Safari 1-3', '#Version/[1-3]\..*Safari/#');
break;
/* Mobile browsers */
case 'mobile':
$agents[] = array(JText::_('JALL'), 'mobile');
$agents[] = array('Android', 'Android');
$agents[] = array('Blackberry', 'Blackberry');
$agents[] = array('IE Mobile', 'IEMobile');
$agents[] = array('iPad', 'iPad');
$agents[] = array('iPhone', 'iPhone');
$agents[] = array('iPod Touch', 'iPod');
$agents[] = array('NetFront', 'NetFront');
$agents[] = array('Nokia', 'NokiaBrowser');
$agents[] = array('Opera Mini', 'Opera Mini');
$agents[] = array('Opera Mobile', 'Opera Mobi');
$agents[] = array('UC Browser', 'UC Browser');
break;
}
$options = array();
foreach ($agents as $agent)
{
$option = JHtml::_('select.option', $agent['1'], $agent['0']);
$options[] = $option;
}
$attr = '';
$attr .= $this->get('size') ? ' size="' . (int) $this->get('size') . '"' : '';
$attr .= ' multiple="multiple"';
return JHtml::_('select.genericlist', $options, $this->name, trim($attr), 'value', 'text', $this->value, $this->id);
}
private function get($val, $default = '')
{
return (isset($this->params[$val]) && (string) $this->params[$val] != '') ? (string) $this->params[$val] : $default;
}
}
|
L16jovenesTIC/portal-web
|
plugins/system/nnframework/fields/agents.php
|
PHP
|
gpl-2.0
| 7,025
|
#!/usr/local/bin/perl -w
#
use Graphics::VTK;
use Tk;
use Graphics::VTK::Tk;
$MW = Tk::MainWindow->new;
# Example demonstrates how to generate a 3D tetrahedra mesh from a volume. This example
# differs from clipVolume.tcl in that the mesh is generated within a range of contour
# values.
$VTK_DATA = 0;
$VTK_DATA = $ENV{VTK_DATA};
use Graphics::VTK::Tk::vtkInt;
# Quadric definition
$quadric = Graphics::VTK::Quadric->new;
$quadric->SetCoefficients('.5',1,'.2',0,'.1',0,0,'.2',0,0);
$sample = Graphics::VTK::SampleFunction->new;
$sample->SetSampleDimensions(20,20,20);
$sample->SetImplicitFunction($quadric);
$sample->ComputeNormalsOff;
# Program a bandpass filter to clip a range of data. What we do is transform the
# scalars so that values lying betweeen (minRange,maxRange) are >= 0.0; all
# others are < 0.0,
$dataset = Graphics::VTK::ImplicitDataSet->new;
$dataset->SetDataSet($sample->GetOutput);
$window = Graphics::VTK::ImplicitWindowFunction->new;
$window->SetImplicitFunction($dataset);
$window->SetWindowRange(0.5,1.0);
# Generate tetrahedral mesh
$clip = Graphics::VTK::ClipVolume->new;
$clip->SetInput($sample->GetOutput);
$clip->SetClipFunction($window);
$clip->SetValue(0.0);
$clip->GenerateClippedOutputOff;
$clipMapper = Graphics::VTK::DataSetMapper->new;
$clipMapper->SetInput($clip->GetOutput);
$clipMapper->ScalarVisibilityOff;
$clipActor = Graphics::VTK::Actor->new;
$clipActor->SetMapper($clipMapper);
$clipActor->GetProperty->SetColor('.8','.4','.4');
# Create outline
$outline = Graphics::VTK::OutlineFilter->new;
$outline->SetInput($clip->GetInput);
$outlineMapper = Graphics::VTK::PolyDataMapper->new;
$outlineMapper->SetInput($outline->GetOutput);
$outlineActor = Graphics::VTK::Actor->new;
$outlineActor->SetMapper($outlineMapper);
$outlineActor->GetProperty->SetColor(0,0,0);
# Define graphics objects
$ren1 = Graphics::VTK::Renderer->new;
$renWin = Graphics::VTK::RenderWindow->new;
$renWin->AddRenderer($ren1);
$iren = Graphics::VTK::RenderWindowInteractor->new;
$iren->SetRenderWindow($renWin);
$ren1->SetBackground(1,1,1);
$ren1->AddActor($clipActor);
$ren1->AddActor($outlineActor);
$iren->SetUserMethod(
sub
{
$MW->{'.vtkInteract'}->deiconify;
}
);
$iren->Initialize;
#renWin SetFileName clipVolume2.tcl.ppm
#renWin SaveImageAsPPM
$MW->withdraw;
Graphics::VTK::Tk::vtkInt::vtkInteract($MW);
Tk->MainLoop;
|
paultcochrane/Graphics-VTK
|
examples/old_examples/graphics/clipVolume2.pl
|
Perl
|
gpl-2.0
| 2,356
|
// -*- C++ -*-
/**
* \file LyXVC.h
* This file is part of LyX, the document processor.
* Licence details can be found in the file COPYING.
*
* \author Lars Gullik Bjønnes
*
* Full author contact details are available in file CREDITS.
*/
#ifndef LYX_VC_H
#define LYX_VC_H
#include <boost/scoped_ptr.hpp>
#include <string>
namespace lyx {
namespace support { class FileName; }
class VCS;
class Buffer;
/** Version Control for LyX.
This is the class giving the version control features to LyX. It is
intended to support different kinds of version control.
The support in LyX is based loosely upon the version control in GNU Emacs,
but is not as extensive as that one. See Extended Manual for a simple
tutorial and manual for the use of the version control system in LyX.
LyXVC use this algorithm when it searches for VC files:
for RCS it searches for <filename>,v and RCS/<filename>,v similarly
CVS/Entries for cvs and .svn/entries. By doing this there doesn't need to be any
special support for VC in the lyx format, and this is especially good
when the lyx format will be a subset of LaTeX.
*/
class LyXVC {
public:
///
LyXVC();
///
~LyXVC();
/** Not a good name perhaps. This function should be called whenever
LyX loads a file. This function then checks for a master VC file (for
RCS this is *,v or RCS/ *,v ; for CVS this is CVS/Entries and .svn/entries
for SVN) if this file or entry is found, the loaded file is assumed to be
under controll by VC, and the appropiate actions is taken.
Returns true if the file is under control by a VCS.
*/
bool file_found_hook(support::FileName const & fn);
/** This function should be run when a file is requested for loading,
but it does not exist. This function will then check for a VC master
file with the same name (see above function). If this exists the
user should be asked if he/her wants to checkout a version for
viewing/editing. Returns true if the file is under control by a VCS
and the user wants to view/edit it.
*/
static bool file_not_found_hook(support::FileName const & fn);
///
void setBuffer(Buffer *);
/// Register the document as an VC file.
bool registrer();
// std::string used as a return value in functions below are
// workaround to defer messages to be displayed in UI. If message()
// is used directly, message string is immediately overwritten
// by the next multiple messages on the top of the processed dispatch
// machinery.
/// Unlock and commit changes. Returns log.
std::string checkIn();
/// Does the current VC supports this operation?
bool checkInEnabled() const;
/// Lock/update and prepare to edit document. Returns log.
std::string checkOut();
/// Does the current VC supports this operation?
bool checkOutEnabled() const;
/// Synchronize the whole archive with repository
std::string repoUpdate();
/// Does the current VC supports this operation?
bool repoUpdateEnabled() const;
/**
* Toggle locking property of the edited file,
* i.e. whether the file uses locking mechanism.
*/
std::string lockingToggle();
/// Does the current VC support this operation?
bool lockingToggleEnabled() const;
/// Revert to last version
bool revert();
/// Undo last check-in.
void undoLast();
/// Does the current VC supports this operation?
bool undoLastEnabled() const;
/**
* Prepare revision rev of the file into newly created temporary file
* and save the filename into parameter f.
* Parameter rev can be either revision number or negative number
* which is interpreted as how many revision back from the current
* one do we want. rev=0 is reserved for the last (committed) revision.
* We need rev to be string, since in various VCS revision is not integer.
* If RCS addressed by a single number, it is automatically used
* as the last number in the whole revision specification (it applies
* for retrieving normal revisions (rev>0) or backtracking (rev<0).
*/
bool prepareFileRevision(std::string const & rev, std::string & f);
/// Does the current VC supports this operation?
bool prepareFileRevisionEnabled();
/**
* Generate a log file and return the filename.
* It is the caller's responsibility to remove the
* file after use.
*/
const std::string getLogFile() const;
/**
* We do not support this generally. In RCS/SVN file read-only flag
* is often connected with locking state and one has to be careful to
* keep things in synchro once we would allow user to toggle
* read-only flags.
*/
void toggleReadOnly();
/// Is the document under administration by VCS?
bool inUse() const;
/// Returns the RCS + version number for messages
std::string const versionString() const;
/**
* Returns whether we use locking for the given file.
*/
bool locking() const;
// type of the revision information
enum RevisionInfo {
Unknown = 0,
File = 1,
Tree = 2,
Author = 3,
Date = 4,
Time = 5
};
/**
* Return revision info specified by the argument.
* Its safe to call it regardless VCS is in usage or this
* info is (un)available. Returns empty string in such a case.
*/
std::string revisionInfo(RevisionInfo const info) const;
private:
///
Buffer * owner_;
///
boost::scoped_ptr<VCS> vcs;
};
} // namespace lyx
#endif
|
rpavlik/lyx-lucid-backport
|
src/LyXVC.h
|
C
|
gpl-2.0
| 5,324
|
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>ApplicationTerminationHandler Class Reference</title>
<link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><img src="images/qpelogo.png" align="left" width="32" height="32" border="0" /></td>
<td width="1"> </td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a> · <a href="classes.html"><font color="#004faf">All Classes</font></a> · <a href="groups.html"><font color="#004faf">Grouped Classes</font></a> · <a href="annotated.html"><font color="#004faf">Annotated</font></a> · <a href="functions.html"><font color="#004faf">Functions</font></a></td>
<td align="right" valign="top"><img src="images/codeless.png" align="right" border="0" /></td></tr></table><h1 class="title">ApplicationTerminationHandler Class Reference</h1>
<p>The ApplicationTerminationHandler class allows tasks to be notified, and possibly filter, when an application terminates. <a href="#details">More...</a></p>
<pre> #include <ApplicationTerminationHandler></pre><p>Inherits <a href="qobject.html">QObject</a>.</p>
<ul>
<li><a href="applicationterminationhandler-members.html">List of all members, including inherited members</a></li>
</ul>
<a name="public-functions"></a>
<h3>Public Functions</h3>
<ul>
<li><div class="fn"/><b><a href="applicationterminationhandler.html#ApplicationTerminationHandler">ApplicationTerminationHandler</a></b> ( QObject * <i>parent</i> = 0 )</li>
<li><div class="fn"/>virtual bool <b><a href="applicationterminationhandler.html#terminated">terminated</a></b> ( const QString & <i>appName</i>, ApplicationTypeLauncher::TerminationReason <i>reason</i> ) = 0</li>
</ul>
<ul>
<li><div class="fn"/>29 public functions inherited from <a href="qobject.html#public-functions">QObject</a></li>
</ul>
<h3>Additional Inherited Members</h3>
<ul>
<li><div class="fn"/>1 property inherited from <a href="qobject.html#properties">QObject</a></li>
<li><div class="fn"/>1 public slot inherited from <a href="qobject.html#public-slots">QObject</a></li>
<li><div class="fn"/>1 signal inherited from <a href="qobject.html#signals">QObject</a></li>
<li><div class="fn"/>1 public type inherited from <a href="qobject.html#public-variables">QObject</a></li>
<li><div class="fn"/>4 static public members inherited from <a href="qobject.html#static-public-members">QObject</a></li>
<li><div class="fn"/>7 protected functions inherited from <a href="qobject.html#protected-functions">QObject</a></li>
<li><div class="fn"/>2 protected variables inherited from <a href="qobject.html#protected-variables">QObject</a></li>
</ul>
<a name="details"></a>
<hr />
<h2>Detailed Description</h2>
<p>The ApplicationTerminationHandler class allows tasks to be notified, and possibly filter, when an application terminates.</p>
<p>The ApplicationTerminationHandler provides a Qtopia Server Task interface. Qtopia Server Tasks are documented in full in the <a href="qtopiaserverapplication.html">QtopiaServerApplication</a> class documentation.</p>
<p><b>Note:</b> This class is part of the Qtopia server and cannot be used by other Qtopia applications.</p>
<p>When an application terminates, the <a href="applicationlauncher.html">ApplicationLauncher</a> notifies all tasks, in order, that implement the ApplicationTerminationHandler interface. A task that implements the ApplicationTeminationHandler interface can filter the termination notification by returning true from its <a href="applicationterminationhandler.html#terminated">terminated</a>() notification method. Filtering a termination will prevent subsequently ordered tasks from being notified.</p>
<p>Regardless of whether or not a task is filtered, the <a href="applicationlauncher.html">ApplicationLauncher</a> class will still emit the global <a href="applicationlauncher.html#applicationTerminated">ApplicationLauncher::applicationTerminated</a>() signal, albeit with the <b>filtered</b> parameter set to true.</p>
<p>Termination handlers can be used to hide the termination of "system" applications from the user, or to implement custom termination notices. The <a href="qterminationhandler.html">QTerminationHandler</a> class, for example, uses a server side termination handler to display a more descriptive crash message when an application abnormally exits.</p>
<hr />
<h2>Member Function Documentation</h2>
<h3 class="fn"><a name="ApplicationTerminationHandler"></a>ApplicationTerminationHandler::ApplicationTerminationHandler ( <a href="qobject.html">QObject</a> * <i>parent</i> = 0 )</h3>
<p>Construct a new <a href="applicationterminationhandler.html">ApplicationTerminationHandler</a> interface with the given <i>parent</i>.</p>
<h3 class="fn"><a name="terminated"></a>bool ApplicationTerminationHandler::terminated ( const <a href="qstring.html">QString</a> & <i>appName</i>, <a href="applicationtypelauncher.html#TerminationReason-enum">ApplicationTypeLauncher::TerminationReason</a> <i>reason</i> ) <tt> [pure virtual]</tt></h3>
<p>Invoked when an application terminates. <i>appName</i> is the name of the application that terminated and <i>reason</i> is the way in which it terminated.</p>
<p>Returning false from this method allows the termination notification to continue to propagate to other <a href="applicationterminationhandler.html">ApplicationTerminationHandler</a> instances. Returning true stops further propagation. Implementors should only return true if they intend to notify the user of the termination, or if they have determined that notification is not required.</p>
<p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td align="left">Copyright © 2008 Trolltech</td>
<td align="center"><a href="trademarks.html">Trademarks</a></td>
<td align="right"><div align="right">Qtopia 4.3.4</div></td>
</tr></table></div></address></body>
</html>
|
muromec/qtopia-ezx
|
doc/html/applicationterminationhandler.html
|
HTML
|
gpl-2.0
| 6,265
|
# The set of languages for which implicit dependencies are needed:
SET(CMAKE_DEPENDS_LANGUAGES
"C"
)
# The set of files for implicit dependencies of each language:
SET(CMAKE_DEPENDS_CHECK_C
"D:/librtlsdr-master/src/librtlsdr.c" "D:/librtlsdr-master/build/src/CMakeFiles/rtlsdr_static.dir/librtlsdr.c.obj"
"D:/librtlsdr-master/src/tuner_e4k.c" "D:/librtlsdr-master/build/src/CMakeFiles/rtlsdr_static.dir/tuner_e4k.c.obj"
"D:/librtlsdr-master/src/tuner_fc0012.c" "D:/librtlsdr-master/build/src/CMakeFiles/rtlsdr_static.dir/tuner_fc0012.c.obj"
"D:/librtlsdr-master/src/tuner_fc0013.c" "D:/librtlsdr-master/build/src/CMakeFiles/rtlsdr_static.dir/tuner_fc0013.c.obj"
"D:/librtlsdr-master/src/tuner_fc2580.c" "D:/librtlsdr-master/build/src/CMakeFiles/rtlsdr_static.dir/tuner_fc2580.c.obj"
"D:/librtlsdr-master/src/tuner_r82xx.c" "D:/librtlsdr-master/build/src/CMakeFiles/rtlsdr_static.dir/tuner_r82xx.c.obj"
)
SET(CMAKE_C_COMPILER_ID "GNU")
# Preprocessor definitions for this target.
SET(CMAKE_TARGET_DEFINITIONS
"DETACH_KERNEL_DRIVER=1"
"rtlsdr_STATIC"
)
# Targets to which this target links.
SET(CMAKE_TARGET_LINKED_INFO_FILES
)
# The include file search paths:
SET(CMAKE_C_TARGET_INCLUDE_PATH
"../include"
"../lib/libusb/include/libusbx-1.0"
"../lib/pthreads/Pre-built.2/include"
)
SET(CMAKE_CXX_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
SET(CMAKE_Fortran_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
SET(CMAKE_ASM_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
|
Excalibur201010/librtlsdr-3gains
|
build/src/CMakeFiles/rtlsdr_static.dir/DependInfo.cmake
|
CMake
|
gpl-2.0
| 1,553
|
/*
Interpréteur GOTO++
Copyright 2002 Sidoine de Wispelaere
Ce programme est un logiciel libre ; vous pouvez le redistribuer
et/ou le modifier sous les termes de la GNU General Public Licence
telle que publiée par la Free Software Fundation ; soit dans la
version 2 de la Licence, soit (à votre choix) dans une version
ultérieure.
Ce programme est distribué dans l'espoir qu'il sera utile mais
SANS AUCUNE GARANTIE ; sans même la garantie implicite qu'il soit
COMMERCIALISABLE ou ADEQUAT POUR UN USAGE PARTICULIER. Voir la
GNU General Public Licence pour plus de détails.
Vous devriez avoir reçu une copie de la GNU General Public Licence
avec ce programme ; dans le cas contraire, écrivez à :
Free Software Fundation, Inc.
59 Temple Place - Suite 330, Boston, MA 02111-1307, US
****
Voici le fameux compilateur, qui vous domine du haut de ses je ne sais
combien de lignes. Bon courage pour comprendre tout ça.
*/
#include <gotopp/base.h>
#include <gotopp/icompilateur.h>
#include <gotopp/erreur.h>
#include "compriv.h"
#include <gotopp/global.h>
using namespace GotoPP;
using namespace std;
namespace GotoPP
{
bool ALPHA(carac c)
{
return ((c>='A' && c<='Z')||(c>='a' && c<='z'));
}
bool ALPHANUM(carac c)
{
return ((c>='A' && c<='Z')||(c>='a' && c<='z')||(c>='0' && c<='9'));
}
inline bool EGAL(const carac * x, const carac * y, size_t ly)
{
return (czlen(x)==ly && memcmp(x,y,ly*sizeof(carac))==0);
}
// #define EGALMC(_T(y) ((lClef==sizeof(_T(y))/sizeof(carac)-1)&&(memcmp(MotClef,_T(y),sizeof(_T(y))-sizeof(carac))==0))
const int PRI_CONSTANTE=1;
const int PRI_TAILLE=2;
const int PRI_PLUSMOINS=5;
const int PRI_FOIS=8;
const int PRI_MODULO=8;
const int PRI_CONCAT=9;
const int PRI_EXEC=10;
const int PRI_DEF=15;
const int PRI_REGOTO=18;
const int PRI_ABSOLUE=3;
const int PRI_OPPOSE=3;
const int PRI_TYPEDE=1;
const int PRI_VIRGULE=999;
const int PRI_MAX=1000;
const int PRI_COLLE=1001;
const int PRI_PAR_O=0;
const int PRI_PAR_F=1003;
const int PRI_FIN=1004;
const int PRI_NOUVEAU=10;
const int PRI_COMP=14;
const int PRI_NON=4;
const int PRI_OU=16;
const int PRI_ET=17;
const int PRI_SWITCH=20;
const int PRI_OUBIN=12;
const int PRI_ETBIN=13;
const int PRI_DECALAGEBIN=7;
index_t LireEtiquette(bool & local);
carac prochainFichier[512];
}
/*
Le principe de base du compilateur est expliqué dans CompilerSeparateur.
* Explication sur les variables "longues", c'est à dire les variables
dotées de propriétés, d'indices de tableau, etc.
machin.chose[truc+13][chose].bidule=
Si une variable est terminée par . ou [ alors cette
variable est une variable longue.
Une variable longue est entourée de parenthèses dont la priorité
est celle d'une constante (<> des vraies parenthèses).
variables longues => flag variablelongue=true
on saute le point
par la suite :
soit on lit [ soit on lit des mots clefs => tout le reste génère une erreur
Lecture de [ : variablelongue=false
Lecture de ] : variablelongue=true
en lisant une variable si le flag variablelongue=true c'est une propriété
si après un ] ou une variable il n'y a pas . ou [ alors on
dépile les variables longues en mettant la parenthèse finale et
variablelongue=false
*/
//namespace GotoPP {
// namespace Compilateur {
inline void Compilateur::AjParO(uint priorite=PRI_PAR_O)
{
Instr[nInstr].p=priorite;
Instr[nInstr].pVal=nValeurs;
Instr[nInstr].nVal=0;
Instr[nInstr++].Special=SPE_PAR_O;
}
inline void Compilateur::AjParF()
{
Instr[nInstr].p=PRI_PAR_F;
Instr[nInstr].pVal=nValeurs;
Instr[nInstr].nVal=0;
Instr[nInstr++].Special=SPE_PAR_F;
}
inline void Compilateur::AjDebutParams()
{
Instr[nInstr].p=PRI_CONSTANTE;
Instr[nInstr].pVal=nValeurs;
Instr[nInstr].nVal=0;
Instr[nInstr].Code= Code::I_DEBUTPARAM;
Instr[nInstr++].Special=SPE_NORMAL;
}
inline void Compilateur::AjCode(Code code, uint Priorite=PRI_CONSTANTE)
{
Instr[nInstr].p=Priorite;
Instr[nInstr].pVal=nValeurs;
Instr[nInstr].nVal=0;
Instr[nInstr].Code = code;
Instr[nInstr++].Special=SPE_NORMAL;
}
inline void Compilateur::AjNoOp(uint priorite)
{
Instr[nInstr].p=priorite;
Instr[nInstr].pVal=nValeurs;
Instr[nInstr].nVal=0;
Instr[nInstr++].Special=SPE_NOOP;
}
inline void Compilateur::AjExpReg(carac *er, carac *modif)
{
Instr[nInstr-1].nVal++;
Valeur[nValeurs].Type=TYPE_OBJETC;
Valeur[nValeurs++].v.o=regexp::Creer(er, modif);
}
inline void Compilateur::AjEntier(int e)
{
Instr[nInstr-1].nVal++;
Valeur[nValeurs].Type=TYPE_ENTIER;
Valeur[nValeurs++].v.i=e;
}
inline void Compilateur::AjType(type t)
{
Instr[nInstr-1].nVal++;
Valeur[nValeurs].Type=TYPE_TYPE;
Valeur[nValeurs++].v.i=t;
}
inline void Compilateur::AjCarac(carac c)
{
Instr[nInstr-1].nVal++;
Valeur[nValeurs].Type=TYPE_CARAC;
Valeur[nValeurs++].v.i=c;
}
inline void Compilateur::AjChances(float f)
{
Instr[nInstr-1].nVal++;
Valeur[nValeurs].Type=TYPE_CHANCES;
Valeur[nValeurs++].v.f=f;
}
inline void Compilateur::AjChaine(carac *c,size_t l)
{
Instr[nInstr-1].nVal++;
Valeur[nValeurs].Type=TYPE_CHAINE;
Valeur[nValeurs++].v.c=chaineval::CreerFormat(c,l);
}
inline void Compilateur::AjEntierType(int e,type Type)
{
Instr[nInstr-1].nVal++;
Valeur[nValeurs].Type=Type;
Valeur[nValeurs++].v.i=e;
}
inline void Compilateur::AjPtrType(Symbole * ptr, type Type)
{
Instr[nInstr-1].nVal++;
Valeur[nValeurs].Type=Type;
Valeur[nValeurs++].v.ptr=ptr;
}
inline bool Compilateur::EstNouveauSymbole(Symbole * s)
{
return s == nullptr;
}
void Compilateur::SupprimerVarLongue()
{
nInstr=VarLongue[iVarLongue].nInstrsDepart;
nValeurs=Instr[nInstr].pVal;
}
bool Compilateur::CompilerOperateur()
{
if (*Source=='@' && Source[1]=='%' && Source[2]=='N'
&& Source[3]=='e')
{
clog << TXT("Bien tenté mais ça ne marche pas.\n");
Source+=4;
}
else
if (*Source=='@' && (Source[1]=='+'||Source[1]=='-'||Source[1]==':'))
{
Source++;
if (*Source=='+')
AjCode(Code::I_EMPILER2);
else if (*Source=='-')
AjCode(Code::I_DEPILER2);
else if (*Source==':')
AjCode(Code::I_VALEUR2);
Source++;
}
else
if (*Source==SEP_PROP) //Sépare les propriétés
{
if (VarLongue[iVarLongue].Type.l==0)
throw TXT("@ doit être placé après un nom de variable");
Source++;
SauterEspaces();
ChercherMotClef();
if (lClef==0)
throw TXT("@ doit être suivi d'un nom de pingouin");
Symbole * prop=ChercherSymboleDans(VarLongue[iVarLongue].Type.Dernier());
CompilerVariable(prop,VarLongue[iVarLongue].Val);
}
else
if (*Source=='|')
{
Source++;
if (*Source=='*')
AjCode(Code::I_ETBIN,PRI_ETBIN);
else if (*Source=='+')
AjCode(Code::I_OUBIN,PRI_OUBIN);
else if (*Source=='<')
AjCode(Code::I_DECALG,PRI_DECALAGEBIN);
else if (*Source=='>')
AjCode(Code::I_DECALD,PRI_DECALAGEBIN);
else
throw TXT("opérateur binaire inconnu");
Source++;
}
else
if (*Source=='?' && nInstr==0)
{
if (AcSwitch.l==0)
throw TXT("on n'est pas dans un GOTOMULTIPLE");
Source++;
if (czncmp(Source,_T("défaut?"),7)==0)
{
Source+=7;
programme->Switch[AcSwitch.Dernier()]->PosDefaut=(code*)Ins.t;
}
else
LigneAc=LP_CAS;
}
else
if (*Source=='!')
{
Source++;
if (*Source>='0' && *Source<='9')
{
ProbaSauterLigne=0;
do
{
ProbaSauterLigne*=10;
ProbaSauterLigne+=*Source-'0';
Source++;
}
while (*Source>='0' && *Source<='9');
}
else
ProbaSauterLigne=90;
InstrAc=IP_OPERATEUR;
}
else
if (*Source=='`')
{
Source++;
AjCode(Code::I_TYPEDE,PRI_TYPEDE);
}
else
if (*Source=='_')
{
Source++;
AjCode(Code::I_CONCAT,PRI_CONCAT);
InstrAc=IP_OPERATEUR;
}
else if (*Source=='"')
{
AjCode(Code::I_VALEURCLEF);
Source++;
InstrAc=IP_OPERATEUR;
}
else if (*Source=='#')
{
AjCode(Code::I_VALEUR);
Source++;
InstrAc=IP_OPERATEUR;
}
else if (*Source=='}')
{
AjParO(PRI_CONSTANTE);
Source++;
InstrAc=IP_PARO;
}
else if ((*Source=='{')||(*Source==')'))
{
AjParF();
Source++;
}
else if (*Source=='~')
{
Source++;
if (*Source=='~')
{
AjCode(Code::I_NONOPPOSE,PRI_OPPOSE);
Source++;
}
else
AjCode(Code::I_OPPOSE,PRI_OPPOSE);
InstrAc=IP_OPERATEUR;
}
else if (*Source=='=')
{
Source++;
if (*Source=='-')
{
Source++;
AjCode(Code::I_DECREMENTER,PRI_DEF);
}
else
if (*Source=='+')
{
Source++;
AjCode(Code::I_INCREMENTER,PRI_DEF);
}
else
if (*Source=='=')
{
Source++;
AjCode(Code::I_INSTANCEDE,PRI_DEF);
}
else
AjCode(Code::I_DEFINIR,PRI_DEF);
InstrAc=IP_OPERATEUR;
}
else if (*Source==':')
{
Source++;
if (*Source=='=')
{
AjCode(Code::I_DIVISEREGAL,PRI_DEF);
Source++;
}
else
AjCode(Code::I_DIVISE,PRI_FOIS);
InstrAc=IP_OPERATEUR;
}
else if ((*Source=='*')&&(Source[1]=='='))
{
Source+=2;
AjCode(Code::I_MULTIPLIEREGAL,PRI_DEF);
InstrAc=IP_OPERATEUR;
}
else if (*Source=='+')
{
Source++;
if (*Source=='+')
{
Source++;
AjCode(Code::I_SUPERPLUS,PRI_PLUSMOINS);
}
else
{
AjCode(Code::I_AJOUTER,PRI_PLUSMOINS);
//AjOperateurVV(OPVV_PLUS);
}
InstrAc=IP_OPERATEUR;
}
else if (*Source=='-')
{
AjCode(Code::I_SOUSTRAIRE,PRI_PLUSMOINS);
Source++;
InstrAc=IP_OPERATEUR;
}
else if (*Source=='(')
{
Source++;
AjCode(Code::I_EXECVAL,PRI_EXEC);
//On ferme la parenthèse qui *doit* avoir été ouverte
//avant de mettre la valeur dans la pile
AjParF();
AjParO();
AjDebutParams();
}
else if (*Source=='%')
{
if (NiveauGourou>2)
throw TXT("le % est interdit pour les gourous de niveau supérieur à 2");
bool local;
Symbole * s=LireEtiquette(local);
if (!EstNouveauSymbole(s) && s->EstClasse())
CompilerClasse(s);
else
CompilerVariable(s, false);
}
else
return false;
return true;
}
void Compilateur::DebutBloc(TypeBloc Type, Symbole * espace)
{
Bloc * bloc=new Bloc();
bloc->type=Type;
bloc->depart=(int)Ins.t;
if (espace==0)
{
Symbole * parent;
if (blocs.l>0)
parent=blocs.Dernier()->symbole;
else
parent=programme->symboleGlobal;
//On crée un symbole vide
espace=new Symbole(_T(""),parent,Symbole::Bloc);
if (parent->PeutContenirLocaux())
espace->taille=parent->taille;
programme->symbole.Etendre(espace);
}
bloc->symbole=espace;
blocs.Etendre(bloc);
LigneAc=LP_DEBUTBLOC;
}
void Compilateur::FinBloc()
{
if (blocs.l==0)
throw TXT("pas de bloc ouvert");
bool Sinon=false;
switch(blocs.Dernier()->type)
{
case TypeBloc::Rien:
break;
case TypeBloc::Sinon:
//clog << "bloc sinon terminé en ligne "<<Ligne<<'\n';
if (RefEtiqA.l==0)
throw TXT("un AC sans AUTOGOTOZ");
Ins.ChgGotoRel(RefEtiqA.Dernier().Etiq,(int)Ins.t);
RefEtiqA.l--;
break;
case TypeBloc::Si:
{
//clog << "bloc si terminé en ligne "<<Ligne<<'\n';
//On regarde si il y a un sinon après
carac *src=Source;
int ligne=Ligne;
do
{
SauterEspaces();
if (*Source=='\n')
{
Ligne++;
Source++;
}
else
if (*Source=='/')
Source++;
else
break;
}
while (1);
if (Source[0]=='A' && Source[1]=='C' && Source[2]=='A'
&& Source[3]=='C' && (ucarac(Source[4])<=' '||Source[4]=='/'))
{
Source+=4;
SauterEspaces();
if ((nInstr)||(*Source!='\n' && *Source!=0 && *Source!='/'))
throw TXT("ACAC doit être seul sur la ligne");
//L'équivalent de sinon : insère un GOTO vers la suite
//puis un AC
SauterEspaces();
Ins.AjouterCode(Code::I_GOTOR);
//Cible d'un AUTOGOTOZ qui crée un GOTOPASMALIN
int cible=RefEtiqA.Dernier().Etiq;
RefEtiqA.Dernier().Etiq=(int)Ins.t;
Ins.AjouterEntier(0);
Ins.ChgGotoRel(cible,(int)Ins.t);
Sinon=true;
}
else
{
Source=src;
Ligne=ligne;
if (RefEtiqA.l==0)
throw TXT("un AC sans AUTOGOTOZ");
Ins.ChgGotoRel(RefEtiqA.Dernier().Etiq,(int)Ins.t);
RefEtiqA.l--;
}
break;
}
case TypeBloc::ForEach:
{
int Depart=(int)Ins.t;
Ins.AjouterCode(Code::I_VARIABLELOC);
Ins.AjouterEntier(blocs.Dernier()->indice->indice);
Ins.AjouterCode(Code::I_ENTIER);
Ins.AjouterEntier(1);
Ins.AjouterCode(Code::I_INCREMENTER);
Ins.AjouterCode(Code::I_GOTOR);
Ins.AjouterGotoRel(blocs.Dernier()->depart);
for (index_t e=0; e<blocs.Dernier()->continues.l;e++)
Ins.ChgGotoRel(blocs.Dernier()->continues[e],Depart);
for (index_t e=0; e<blocs.Dernier()->breaks.l;e++)
Ins.ChgGotoRel(blocs.Dernier()->breaks[e],(int)Ins.t);
break;
}
case TypeBloc::For:
{
int Depart=(int)Ins.t;
if (blocs.Dernier()->pasDuFor)
{
LigneDeCode * ldc=blocs.Dernier()->pasDuFor;
CreerCodeFinal(*ldc);
delete ldc;
}
Ins.AjouterCode(Code::I_GOTOR);
Ins.AjouterGotoRel(blocs.Dernier()->depart);
for (index_t e=0; e<blocs.Dernier()->continues.l;e++)
Ins.ChgGotoRel(blocs.Dernier()->continues[e],Depart);
for (index_t e=0; e<blocs.Dernier()->breaks.l;e++)
Ins.ChgGotoRel(blocs.Dernier()->breaks[e],(int)Ins.t);
break;
}
case TypeBloc::TantQue:
{
//clog << "bloc tantque terminé en ligne "<<Ligne<<'\n';
Ins.AjouterCode(Code::I_GOTOR);
Ins.AjouterGotoRel(blocs.Dernier()->depart);
for (index_t e=0; e<blocs.Dernier()->continues.l;e++)
Ins.ChgGotoRel(blocs.Dernier()->continues[e],blocs.Dernier()->depart);
for (index_t e=0; e<blocs.Dernier()->breaks.l;e++)
Ins.ChgGotoRel(blocs.Dernier()->breaks[e],(int)Ins.t);
break;
}
case TypeBloc::Switch:
{
//clog << "bloc switch terminé en ligne "<<Ligne<<'\n';
if (AcSwitch.l==0)
throw TXT("une fin de GOTOMULTIPLE sans GOTOMULTIPLE ouvert");
if (programme->Switch[AcSwitch.Dernier()]->PosDefaut== nullptr)
programme->Switch[AcSwitch.Dernier()]->PosDefaut=reinterpret_cast<code*>(Ins.t);
//Trions les switchs
qsort(programme->Switch[AcSwitch.Dernier()]->Cas.t,
programme->Switch[AcSwitch.Dernier()]->Cas.l,sizeof(CCasSwitch),
CompCasSwitch);
AcSwitch.l--;
for (index_t e=0; e<blocs.Dernier()->breaks.l;e++)
Ins.ChgGotoRel(blocs.Dernier()->breaks[e],static_cast<int>(Ins.t));
break;
}
case TypeBloc::Fonction:
//clog << "bloc fonction terminé en ligne "<<Ligne<<'\n';
AjCode(Code::I_RETOUR,PRI_EXEC);
break;
case TypeBloc::Classe:
break;
#ifdef _DEBUG
default:
throw TXT("bloc de type inconnu");
#endif
}
blocs.EffacerDernier();
if (blocs.l==0)
{
/*//On fait le lien des étiquettes locales
qsort(&LabelL.Premier(),LabelL.l,sizeof(SLabel),CmpLabels);
//clog << RefEtiq.l << " références à des étiquettes \n";
for (index_t z=0; z<RefEtiqL.l; z++)
{
int *k=(int*)&Ins.c[RefEtiqL[z]];
int v=*k;
SLabelL * l=(SLabelL*)bsearch(&v,&LabelL.Premier(),LabelL.l,sizeof(SLabelL),CmpLabels);
if (!l)
throw TXT("il est fait référence à une étiquette locale qui n'existe pas dans ce bloc, à toi de trouver laquelle");
*k=l->Valeur-RefEtiqL[z]-sizeof(int);
}
LabelL.l=0;
RefEtiqL.l=0;*/
}
if (blocs.Dernier()->classeSpecifiee)
blocs.EffacerDernier();
if (Sinon)
DebutBloc(TypeBloc::Sinon);
}
bool Compilateur::CompilerMotClef0()
{
if (EstMotClef(_T("bush")) || EstMotClef(_T("deubeulyou")))
{
SauterEspaces();
ChercherMotClef();
if (lClef==0)
throw TXT("une constante doit avoir un nom");
Symbole * symb=programme->NouvelleConstante(MotClef,lClef);
SauterEspaces();
if (*Source!='=')
throw TXT("il manque le = après le nom de la constante");
Source++;
AjCode(Code::I_CONSTVAR,PRI_DEF);
AjPtrType(symb,TYPE_SYMBOLE);
}
else
if (EstMotClef(_T("BLOC")))
{
DebutBloc(TypeBloc::Rien);
}
else if (EstMotClef(_T("FINBLOC")))
{
FinBloc();
}
else
if (EstMotClef(_T("FINGOTOMULTIPLE")))
{
if (blocs.l==0 || blocs.Dernier()->type!= TypeBloc::Switch)
throw TXT("FINGOTOMULTIPLE doit fermer un GOTOMULTIPLE");
FinBloc();
}
else
if (EstMotClef(_T("GOTOMULTIPLE")))
{
AjCode(Code::I_SWITCH,PRI_SWITCH);
AjEntier((int)programme->Switch.l);
AcSwitch.Etendre((int)programme->Switch.l);
CSwitch * swit=new CSwitch();
programme->Switch.Etendre(swit);
CibleAuto++;//Pour les "arret"
DebutBloc(TypeBloc::Switch);
}
else
if (EstMotClef(_T("et")))
{
AjCode(Code::I_ET,PRI_ET);
AjEntier((int)EtOu.l);
AjCode(Code::I_FINOUET,PRI_ET);
AjEntier((int)EtOu.l);
EtOu.Etendre(-1);
}
else
if (EstMotClef(_T("ou")))
{
AjCode(Code::I_OU,PRI_OU);
AjEntier((int)EtOu.l);
AjCode(Code::I_FINOUET,PRI_OU);
AjEntier((int)EtOu.l);
EtOu.Etendre(-1);
}
else
if (EstMotClef(_T("eg")))
{
AjCode(Code::I_EGAL,PRI_COMP);
}
else
if (EstMotClef(_T("diff")))
{
AjCode(Code::I_DIFFERENT,PRI_COMP);
}
else
if (EstMotClef(_T("inf")))
{
AjCode(Code::I_INFERIEUR,PRI_COMP);
}
else
if (EstMotClef(_T("sup")))
{
AjCode(Code::I_SUPERIEUR,PRI_COMP);
}
else
if (EstMotClef(_T("supeg")))
{
AjCode(Code::I_SUPEGAL,PRI_COMP);
}
else
if (EstMotClef(_T("infeg")))
{
AjCode(Code::I_INFEGAL,PRI_COMP);
}
else
if (EstMotClef(_T("non")))
{
AjCode(Code::I_NON,PRI_NON);
}
else
if (EstMotClef(_T("AUTOGOTOZ")))
{
AjCode(Code::I_GOTOZEROR,PRI_EXEC);
AjEntierType(0,TYPE_ETIQAUTO);
DebutBloc(TypeBloc::Si);
}
else
if (EstMotClef(_T("TantQue")))
{
DebutBloc(TypeBloc::TantQue);
AjCode(Code::I_GOTOZEROR,PRI_EXEC);
AjEntierType((int)blocs.l-1,TYPE_ETIQAUTOBREAK);
}
else
if (EstMotClef(_T("costaud")))
{
DebutBloc(TypeBloc::For);
LigneAc=LP_FOR_INIT;
}
else
if (EstMotClef(_T("PouCharque")))
{
SauterEspaces();
Symbole * classe=ChercherSymbole();
if (EstNouveauSymbole(classe) || !classe->EstClasse())
throw TXT("classe de la variable de parcours indéfinie");
SauterEspaces();
ChercherMotClef();
if (lClef==0)
throw TXT("indiquez un nom pour la variable de parcours");
DebutBloc(TypeBloc::ForEach);
Symbole * s=blocs.Dernier()->symbole;
//On crée les trois variables locales utilisées
blocs.Dernier()->indice=programme->NouveauSymbole(_T("indice"),6,CType(symboleEntier),s);
DernierSymbole().type=Symbole::VariableLocale;
DernierSymbole().indice=(index_t)s->taille++;
blocs.Dernier()->tableau=programme->NouveauSymbole(_T("tableau"),7,CType(classe),s);
DernierSymbole().TypeAc.Empiler(symboleTableau);
DernierSymbole().type=Symbole::VariableLocale;
DernierSymbole().indice=(index_t)s->taille++;
blocs.Dernier()->iterateur=programme->NouveauSymbole(MotClef,lClef,CType(classe),s);
DernierSymbole().type=Symbole::VariableLocale;
DernierSymbole().indice=(index_t)s->taille++;
index_t svarLoc=(index_t)(blocs[blocs.l-2]->symbole->taille);
AjCode(Code::I_VARIABLELOC,PRI_CONSTANTE);
AjPtrType(blocs.Dernier()->indice,TYPE_VARIABLE);
AjCode(Code::I_ENTIER,PRI_CONSTANTE);
AjEntier(0);
AjCode(Code::I_DEFINIR,PRI_CONSTANTE);
AjCode(Code::I_VARIABLELOC,PRI_CONSTANTE);
AjPtrType(blocs.Dernier()->tableau,TYPE_VARIABLE);
AjCode(Code::I_INSTANCEDE,PRI_MAX);
LigneAc=LP_FOREACH_INIT;
}
else
if (EstMotClef(_T("arret")))
{
AjCode(Code::I_GOTOR,PRI_EXEC);
int Cible=int(blocs.l)-1;
while (Cible>=0 && blocs[Cible]->type!= TypeBloc::Fonction
&& blocs[Cible]->type!= TypeBloc::TantQue
&& blocs[Cible]->type!= TypeBloc::Switch
&& blocs[Cible]->type!= TypeBloc::For
&& blocs[Cible]->type!= TypeBloc::ForEach)
Cible--;
if (blocs[Cible]->type== TypeBloc::Fonction)
throw TXT("interdit de sortir d'une fonction avec arret");
if (Cible<0)
throw TXT("un arret doit se trouver dans un bloc");
AjEntierType(Cible,TYPE_ETIQAUTOBREAK);
}
else
if (EstMotClef(_T("continue")))
{
AjCode(Code::I_GOTOR,PRI_EXEC);
int Cible=int(blocs.l)-1;
while (Cible>=0 && blocs[Cible]->type!= TypeBloc::Fonction
&& blocs[Cible]->type!= TypeBloc::TantQue
&& blocs[Cible]->type!= TypeBloc::For
&& blocs[Cible]->type!= TypeBloc::ForEach)
Cible--;
if (blocs[Cible]->type== TypeBloc::Fonction)
throw TXT("interdit de sortir d'une fonction avec continue");
if (Cible<0)
throw TXT("un continue doit se trouver dans un TantQue");
AjEntierType(Cible,TYPE_ETIQAUTOCONTINUE);
}
else
if (EstMotClef(_T("AC")))
{
if (nInstr)
throw TXT("AC doit être en début de ligne");
if ((blocs.l==0 || (blocs.Dernier()->type != TypeBloc::Si&&blocs.Dernier()->type != TypeBloc::Sinon)))
throw TXT("un AC doit terminer un AUTOGOTOZ");
FinBloc();
}
else
if (EstMotClef(_T("faiblard")))
{
SauterEspaces();
if ((nInstr)||(*Source!='\n' && *Source!=0))
throw TXT("faiblard doit être seul sur la ligne");
if (blocs.l==0 || blocs.Dernier()->type!= TypeBloc::For)
throw TXT("un faiblard doit terminer un costaud");
FinBloc();
}
else
if (EstMotClef(_T("FinTantQue")))
{
SauterEspaces();
if ((nInstr)||(*Source!='\n' && *Source!=0))
throw TXT("FinTantQue doit être seul sur la ligne");
if (blocs.l==0 || (blocs.Dernier()->type!= TypeBloc::TantQue
&& blocs.Dernier()->type!= TypeBloc::ForEach))
throw TXT("un FinTantQue doit terminer un TantQue ou un PouCharque");
FinBloc();
}
else
if (EstMotClef(_T("ACAC")))
{
throw TXT("que fait ce ACAC ici ?");
}
else
return false;
return true;
}
bool Compilateur::CompilerMotClef1()
{
if (EstMotClef(_T("GOTOPASMALIN")))
{
SauterEspaces();
bool locale;
Symbole * c=LireEtiquette(locale);
if (locale)
{
AjCode(Code::I_GOTOR,PRI_CONSTANTE);
AjPtrType(c,TYPE_ETIQLOC);
}
else
{
AjCode(Code::I_GOTO,PRI_CONSTANTE);
AjPtrType(c,TYPE_ETIQUETTE);
}
}
else
if (EstMotClef(_T("GOTONULPOURLESNULS")))
{
SauterEspaces();
bool Locale;
Symbole * c=LireEtiquette(Locale);
if (Locale)
{
AjCode(Code::I_GOTOZEROR,PRI_EXEC);
AjPtrType(c,TYPE_ETIQLOC);
}
else
{
AjCode(Code::I_GOTOZERO,PRI_EXEC);
AjPtrType(c,TYPE_ETIQUETTE);
}
}
else
if (EstMotClef(_T("GOTONONNULPOURLESNULS")))
{
SauterEspaces();
bool Locale;
Symbole * c=LireEtiquette(Locale);
if (Locale)
{
AjCode(Code::I_GOTONONZEROR,PRI_EXEC);
AjPtrType(c,TYPE_ETIQLOC);
}
else
{
AjCode(Code::I_GOTONONZERO,PRI_EXEC);
AjPtrType(c,TYPE_ETIQUETTE);
}
}
else
return false;
return true;
}
bool Compilateur::SymboleDisponible()
{
Symbole * verifie=ChercherSymboleSimple();
if (!EstNouveauSymbole(verifie) && verifie->parent==blocs.Dernier()->symbole)
return false;
return true;
}
bool Compilateur::CompilerMotClef2()
{
if (EstMotClef(_T("estrefvalide")))
{
AjCode(Code::I_ESTREFVALIDE,PRI_CONSTANTE);
}
else
if (EstMotClef(_T("RESTEDELADIVISIONPAR")))
{
AjCode(Code::I_MODULO,PRI_MODULO);
}
else
if (EstMotClef(_T("monpitipingouin")))
{
AjCode(Code::I_THIS,PRI_CONSTANTE);
}
else
if (EstMotClef(_T("encasderreurGOTO")))
{
SauterEspaces();
bool Locale;
Symbole * c=LireEtiquette(Locale);
if (Locale)
{
AjCode(Code::I_ENERREURR,PRI_CONSTANTE);
AjPtrType(c,TYPE_ETIQLOC);
}
else
{
AjCode(Code::I_ENERREUR,PRI_CONSTANTE);
AjPtrType(c,TYPE_ETIQUETTE);
}
}
else
if (EstMotClef(_T("GOTOBIBLIOTHEQUE")))
{
SauterEspaces();
ChercherMotClef();
if (lClef==0)
throw TXT("le nom de la bibliothèque de fonctions n'est pas indiqué");
for (index_t b=0; b<programme->fichierSource.l; b++)
if (EGAL(programme->fichierSource[b]->Nom,MotClef,lClef))
return true;
FichierSource * fichierSource=new FichierSource();
programme->fichierSource.Etendre(fichierSource);
if (!fichierSource->Charger(MotClef,lClef,CheminModules))
throw TXT("bibliothèque introuvable");
fichierSource->Parent=AcFichierSource;
AcFichierSource->AcPos=Source;
AcFichierSource->Ligne=Ligne;
fichierSource->DebutCode=(code*)Ins.t;
Ligne=1;
Source=fichierSource->Source;
AcFichierSource=fichierSource;
}
else
if (EstMotClef(_T("GOTOMODULE")))
{
SauterEspaces();
ChercherMotClef();
if (lClef==0)
throw TXT("nom de module attendu");
programme->ChargerModule(MotClef,uint(lClef));
}
else
if (EstMotClef(_T("BEBEPINGOUIN")))
{
AjCode(Code::I_NOUVEAU,PRI_NOUVEAU);
}
else
if (EstMotClef(_T("tailleenlongueur")))
{
AjCode(Code::I_TAILLE,PRI_TAILLE);
}
else
if (EstMotClef(_T("REGOTO")))
{
AjCode(Code::I_RETOUR,PRI_REGOTO);
}
else
if (EstMotClef(_T("GOTOUNIVERSPARALLELEouizzz")))
{
SauterEspaces();
bool Locale;
Symbole * c=LireEtiquette(Locale);
if (Locale)
{
AjCode(Code::I_GOTOTACHER,PRI_CONSTANTE);
AjPtrType(c,TYPE_ETIQLOC);
}
else
{
AjCode(Code::I_GOTOTACHE,PRI_CONSTANTE);
AjPtrType(c,TYPE_ETIQUETTE);
}
}
else
if (EstMotClef(_T("GOTOFINTACHE")))
{
AjCode(Code::I_FINTACHE,PRI_CONSTANTE);
}
else
if (EstMotClef(_T("troupeau")))
{
if (nInstr)
throw TXT("la classe doit être définie en début de ligne");
//Définition d'une classe d'objet
SauterEspaces();
ChercherMotClef();
if (lClef==0)
throw TXT("nom de classe attendu");
bool ClasseGivree;
if (EstMotClef(_T("GIVRE")))
{
if (NiveauGourou>1)
throw TXT("le mot-clef GIVRE est interdit aux gourous de niveau supérieur à 1");
ClasseGivree=true;
SauterEspaces();
ChercherMotClef();
if (lClef==0)
throw TXT("nom de classe attendu après GIVRE");
}
else
ClasseGivree=false;
//On vérifie que le symbole n'est pas déjà utilisé
if (!SymboleDisponible())
throw TXT("nom de classe déjà utilisé");
Symbole * c=programme->NouveauSymbole(MotClef,lClef,CType(symboleValeur),
blocs.Dernier()->symbole);
DebutBloc(TypeBloc::Classe,c);
c->type=Symbole::Classe;
c->defConstr=0;
if (ClasseGivree)
c->attributs|=Symbole::filsglob;
else
c->attributs|=Symbole::filsthis;
SauterEspaces();
if (*Source==':')
{
Source++;
SauterEspaces();
Symbole * i=ChercherSymbole();
if (!EstNouveauSymbole(i))
{
if (i->type!=Symbole::Classe)
throw TXT("impossible de dériver une classe intégrée");
//On copie tous les fils
for (Symbole * f=i->fils;f!=0;f=f->suivant)
{
Symbole * copie=new Symbole(*f);
programme->symbole.Etendre(copie);
if (copie->acces==Symbole::Prive)
copie->acces=Symbole::Cache;
}
c->taille=i->taille;
}
else
throw CErreur(TXT("troupeau de base %.*s inconnu"),lClef,MotClef);
}
if (*Source!='\n')
throw TXT("fin de ligne attendue après le nom du troupeau");
Source++;
Ligne++;
}
else
if (EstMotClef(_T("fintroupeau")))
{
SauterEspaces();
if (*Source!='\n')
throw TXT("retour à la ligne attendu après finclasse");
Source++;
Ligne++;
if (blocs.Dernier()->type!= TypeBloc::Classe)
throw TXT("fintroupeau devrait indiquer la fin de définition d'une classe");
FinBloc();
}
else
if (EstMotClef(_T("machineapingouins")))
{
//Définition d'une fonction
SauterEspaces();
CompilerFonction();
}
else
if (EstMotClef(_T("NPARAMS")))
{
AjCode(Code::I_NPARAMS,PRI_CONSTANTE);
}
else
if (EstMotClef(_T("APLUS")))
{
if (blocs.l==0 || blocs.Dernier()->type!= TypeBloc::Fonction)
throw TXT("fin de bloc alors qu'aucun bloc n'a été ouvert");
FinBloc();
}
else
return false;
return true;
}
bool Compilateur::CompilerMotClef3()
{
if (EstMotClef(_T("ASV")))
{
throw TXT("ASV est réservé pour les fonctions");
}
else
if (EstMotClef(_T("niveaugourou")))
{
SauterEspaces();
NiveauGourou=*Source-'0';
if (NiveauGourou<0 || NiveauGourou>3)
throw TXT("le niveau de gourou doit être compris entre 0 et 3");
Source++;
}
else
if (EstMotClef(_T("enentier")))
{
AjCode(Code::I_CONVTYPE,PRI_CONSTANTE);
AjType(TYPE_PINGOUIN);
AjType(TYPE_ENTIER);
}
else
if (EstMotClef(_T("enfonction")))
{
AjCode(Code::I_CONVTYPE,PRI_CONSTANTE);
AjType(TYPE_PINGOUIN);
AjType(TYPE_FONCTIONC);
}
else
if (EstMotClef(_T("encaractere")))
{
AjCode(Code::I_CONVTYPE,PRI_CONSTANTE);
AjType(TYPE_PINGOUIN);
AjType(TYPE_CARAC);
}
else
if (EstMotClef(_T("envariable")))
{
AjCode(Code::I_CONVTYPE,PRI_CONSTANTE);
AjType(TYPE_PINGOUIN);
AjType(TYPE_VARIABLE);
}
else
if (EstMotClef(_T("nimportequoitochances")))
{
AjCode(Code::I_CONVTYPE,PRI_CONSTANTE);
AjType(TYPE_PINGOUIN);
AjType(TYPE_CHANCES);
}
else
if (EstMotClef(_T("NOSTRADAMUS")))
{
czerr<<TXT("Ce programme est béni par Nostradamus.\n");
}
else
if (EstMotClef(_T("SUPERPROLETAIRE")))
throw TXT("la révolution humaine est en marche ! Maudit âne ! Ton disque dur vient d'être détruit !");
else
if (EstMotClef(_T("NIAC")))
throw TXT("la bêtise du NIAC est bête");
else
if (EstMotClef(_T("NumeroBiblio")))
{
AjCode(Code::I_ENTIER,PRI_CONSTANTE);
AjEntier((int)(AcFichierSource!=programme->fichierSource[0]));//TODO: un truc qui veut dire quelque chose
}
else
if (EstMotClef(_T("MULTIPLICATION")))
{
AjCode(Code::I_FOIS,PRI_FOIS);
}
else
if (EstMotClef(_T("GOTOFIN")))
{
AjCode(Code::I_STOP,PRI_CONSTANTE);
}
else
if (EstMotClef(_T("dup")))
{
AjCode(Code::I_DUPLIQUER,PRI_CONSTANTE);
}
else
if (EstMotClef(_T("suppr")))
{
AjCode(Code::I_SUPPRIMER,PRI_CONSTANTE);
}
else
if (EstMotClef(_T("existe")))
{
AjCode(Code::I_EXISTE,PRI_CONSTANTE);
}
else
if (EstMotClef(_T("pastrespermissif")))
{
DeclarationStricte=true;
}
else
return false;
return true;
}
bool Compilateur::CompilerMotClef()
{
bool ret=CompilerMotClef3();
if (ret)
{
if (NiveauGourou>3)
throw TXT("mot-clef interdit aux gourous de niveau supérieur à 3");
else
return true;
}
ret=CompilerMotClef2();
if (ret)
{
if (NiveauGourou>2)
throw TXT("mot-clef interdit aux gourous de niveau supérieur à 2");
else
return true;
}
ret=CompilerMotClef1();
if (ret)
{
if (NiveauGourou>1)
throw TXT("mot-clef interdit aux gourous de niveau supérieur à 1");
else
return true;
}
ret=CompilerMotClef0();
if (ret)
{
if (NiveauGourou>0)
throw TXT("mot-clef interdit aux gourous de niveau supérieur à 0");
else
return true;
}
return false;
}
//Si posEN!=rien, on ne cherche pas dans les use
//et uniquement à partir de Bloc[posEn]
Symbole * Compilateur::ChercherSymboleSimple(Bloc ** posEN)
{
//TODO: un travail d'optimisation est faisable, notamment en
//utilisant un index pour les noms de symbole
//Heu alors là c'est une astuce, pour que ça puisse tourner en boucle
if (posEN!=0)
posEN--;
Symbole * var=0;
//On commence par regarder dans tous les blocs à partir de posEn
Bloc ** fin=(posEN==0?blocs.Debut():posEN+1);
for (Bloc ** en=blocs.Fin()-1; en>=fin; en--)
{
Symbole * parent=(*en)->symbole;
for (Symbole * f=parent->fils; f!=0; f=f->suivant)
{
if (EGAL(f->nom,MotClef,lClef))
return f;
}
}
//Si on n'a pas trouvé, on cherche dans les uses
for (Symbole ** e=useEspace.Debut(); e<useEspace.Fin(); e++)
{
Symbole * parent=(*e);
for (Symbole * f=parent->fils; f!=0; f=f->suivant)
{
if (EGAL(f->nom,MotClef,lClef))
return f;
}
}
return 0;//pas trouvé
//On regarde tous les symboles du programme
/*for (Symbole ** i=programme->symbole.Debut();
i!=programme->symbole.Fin(); i++)
{
Symbole * symbole=*i;
if (EGAL(symbole->nom,MotClef,lClef))
{
//Est-il dans l'espace de nommage courant ?
//Celui-ci est dicté par l'ensemble des blocs dans lesquels on se trouve
for (CBloc ** en=(posEN==0?Bloc.Debut():posEN+1); en<Bloc.Fin(); en++)
if ((*en)->symbole==symbole->parent)
{
var=symbole;
posEN=en;
}
//Est-il dans les use ?
if (posEN==0)
{
for (Symbole ** e=useEspace.Debut(); e<useEspace.Fin(); e++)
if (*e==symbole->parent)
var=symbole;
}
//Gare ! Ce symbole peut être remplacé par un autre symbole de même nom
//défini dans un bloc fils
if (var==symbole && posEN!=0 && posEN==Bloc.Fin()-1)
break;
}
}
return var;*/
}
Symbole * Compilateur::ChercherSymbole(bool creer)
{
Symbole * var;
Symbole * parent=programme->symboleGlobal;
bool numeros=false;
if (*Source=='%')
{
numeros=true;
if (Source[1]=='%')
{
Source+=2;
//On ne cherche que dans cette fonction
Bloc ** en=blocs.Fin()-1;
while (en>blocs.Debut())
{
if ((*en)->type== TypeBloc::Fonction)
break;
en--;
}
ChercherMotClef(true);
if (lClef==0)
throw TXT("symbole attendu");
parent=(*en)->symbole;
var=ChercherSymboleSimple(en);
}
else
var=blocs.Premier()->symbole;
}
else
{
ChercherMotClef();
if (lClef==0)
throw TXT("symbole attendu");
var=ChercherSymboleSimple();
}
while(*Source=='%')
{
if (EstNouveauSymbole(var))
throw TXT("le symbole avant la virgule doit être défini");
Source++;
ChercherMotClef(numeros);
if (lClef==0)
throw TXT("on attend un nom après la virgule");
parent=var;
var=ChercherSymboleDans(var);
}
if (creer && EstNouveauSymbole(var))
{
var=programme->NouveauSymbole(MotClef,lClef,CType(symboleValeur),parent);
var->type=Symbole::FonctionGPP;
var->attributs|=Symbole::constante;
}
return var;
}
Symbole * Compilateur::ChercherSymboleDans(Symbole * ou)
{
for (Symbole * s=ou->fils; s!=0; s=s->suivant)
{
if (EGAL(s->nom,MotClef,lClef))
{
return s;
}
}
return 0;
}
Symbole * Compilateur::LireEtiquette(bool &local)
{
carac * depart=Source;
Symbole * s=ChercherSymbole(true);
//TODO: comme ça, ça ne peut pas marcher. Qu'est ce que ça signifiait ?
//local=(s>=etaitPremierSymbole);
local=false;
if (s && s->type!=Symbole::FonctionGPP)
throw CErreur(TXT("%s n'est pas une étiquette"),s->nom);
return s;
}
void Compilateur::InsererConstante(Symbole * var)
{
switch(var->type)
{
case Symbole::FonctionGPP:
AjCode(Code::I_ETIQUETTE);
AjPtrType(var,TYPE_ETIQUETTE);//Vu qu'on ne saura que plus
//tard la vraie valeur (à l'édition de lien)
break;
case Symbole::MethodeGPP:
AjCode(Code::I_ETIQUETTE_THIS);
AjPtrType(var,TYPE_ETIQUETTE);//Vu qu'on ne saura que plus
//tard la vraie valeur (à l'édition de lien)
break;
case Symbole::FonctionC:
AjCode(Code::I_FONCTIONC);
AjPtrType(var,TYPE_FONCTIONC);
break;
case Symbole::MethodeC:
AjCode(Code::I_FONCTIONC_THIS);
AjPtrType(var,TYPE_FONCTIONC_THIS);
break;
case Symbole::EtiquetteLocale:
AjCode(Code::I_ETIQUETTELOC);
AjPtrType(var,TYPE_ETIQLOC);//Vu qu'on ne saura que plus
//tard la vraie valeur (à l'édition de lien)
break;
case Symbole::VariableGlobale:
case Symbole::VariableLocale:
{
switch(var->Valeur.Type)
{
case TYPE_ENTIER:
AjCode(Code::I_ENTIER);
AjEntier(var->Valeur.v.i);
break;
case TYPE_FONCTIONC:
AjCode(Code::I_FONCTIONC);
AjPtrType(var,TYPE_FONCTIONC);
break;
case TYPE_FONCTIONMODULE:
AjCode(Code::I_FONCTIONMODULE);
AjEntier(var->Valeur.v.i);
break;
case TYPE_ETIQUETTE_THIS:
AjCode(Code::I_ETIQUETTE_THIS);
AjPtrType(var,TYPE_ETIQUETTE_THIS);
break;
case TYPE_FONCTIONC_THIS:
AjCode(Code::I_FONCTIONC_THIS);
AjPtrType(var,TYPE_FONCTIONC_THIS);
break;
case TYPE_INCONNU:
throw TXT("constante indéfinie");
default:
throw TXT("type non supporté pour une constante");
}
break;
}
default:
throw TXT("erreur interne du compilateur (type d'exécution)");
}
}
/* Le traitement des variables
La variable en cours de traitement est stockée dans VarLongue
cas 1:
[&]var
=> la variable est isolée => var[&]
cas 2:
[&]var@tvar
=> la variable a une propriété => < var tvar[&] >
cas 3:*/
bool Compilateur::CompilerVariable(Symbole * var, bool Val)
{
//Est-ce une nouvelle variable ?
if (EstNouveauSymbole(var))
{
if (DeclarationStricte)
throw CErreur(TXT("la variable %.*s n'a pas été déclarée"),
lClef,MotClef);
var=programme->NouvelleVariable(MotClef,lClef,CType(symboleValeur));
}
SauterEspaces();
//Est-ce une constante ?
if (var->attributs&Symbole::constante)
{
bool dansVariableLongue;
if (VarLongue[iVarLongue].Type.l==0)
dansVariableLongue=false;
else
dansVariableLongue=true;
if (*Source=='(')
{
if (!dansVariableLongue)
AjParO(PRI_EXEC);
// Instr[VarLongue[iVarLongue].Depart].p=I_EXEC;
// else
}
InsererConstante(var);
if (dansVariableLongue)
{
if (*Source!='(')
AjParF();
VarLongue[iVarLongue].Type.Vider();
}
else
{
//Appel automatique par this->blob
if (var->type==Symbole::MethodeGPP && *Source=='(')
{
Source++;
AjCode(Code::I_EXECMEMETHISVAL);
AjParF();
AjParO();
AjDebutParams();
}
}
return true;
}
// bool variableLongue;
if (VarLongue[iVarLongue].Type.l==0)
{
int prio=PRI_CONSTANTE;
bool variableLongue;
//On n'a pas encore démarré la variable longue
//On vérifie si c'en est une
if ((*Source==SEP_TAB_O)||(*Source==SEP_PROP)||
(*Source==SEP_HAC_O))
{
//Suivis d'un début de tableau, de hachage ou de propriété
//=> c'est une variable longue
variableLongue=true;
VarLongue[iVarLongue].nInstrsDepart=nInstr;
AjParO(PRI_CONSTANTE);
VarLongue[iVarLongue].Type=var->TypeAc;
VarLongue[iVarLongue].Val=Val;
}
else
{
//C'est une variable isolée, sans propriété ni rien
variableLongue=false;
//Le I_EXEC doit se ballader avec la variable
//on met donc une parenthèse au début
if (*Source=='(')
AjParO(var->TypeAc.EstFonction()?PRI_EXEC:PRI_CONSTANTE);
}
//Le code en question
//Si c'est une variable longue on empile toujours la référence
//Si c'est un appel de fonction qui suit on empile toujours la valeur
if ((Val && !variableLongue)||*Source=='(')
{
switch(var->type)
{
case Symbole::VariableGlobale:
AjCode(Code::I_VALEURVAR,prio);
break;
case Symbole::VariableLocale:
AjCode(Code::I_VALEURVARLOC,prio);
break;
case Symbole::VariableParam:
AjCode(Code::I_PARAMVAL,prio);
break;
case Symbole::VariableThis:
AjCode(Code::I_THISVAL,prio);
break;
default:
throw TXT("hu ?");
}
}
else
{
switch(var->type)
{
case Symbole::VariableLocale:
AjCode(Code::I_VARIABLELOC);
break;
case Symbole::VariableGlobale:
AjCode(Code::I_VARIABLE);
break;
case Symbole::VariableParam:
AjCode(Code::I_PARAMREF);
break;
case Symbole::VariableThis:
AjCode(Code::I_THISREF);
break;
default:
throw TXT("hein ?");
}
}
AjPtrType(var,TYPE_VARIABLE);
}
else //C'est une propriété
{
if ((*Source==SEP_TAB_O)||(*Source==SEP_PROP)||
(*Source==SEP_HAC_O))
{
//On continue
VarLongue[iVarLongue].Type=var->TypeAc;
AjCode(Code::I_CTABLEAUREF);
AjEntier(var->indice);
}
else
{
VarLongue[iVarLongue].Type.Vider();
if (var->type==Symbole::VariableGlobale)
{
//Propriété givrée
//On annule tout le code qui a conduit ici
SupprimerVarLongue();
AjCode(VarLongue[iVarLongue].Val? Code::I_VALEURVAR: Code::I_VARIABLE);
AjPtrType(var,TYPE_VARIABLE);
}
/*TODO: implémentation des propriétés*/
/*else if (var->type==Symbole::ProprieteC)
{
if (VarLongue[iVarLongue].Val)
{
AjCode(Code::I_
}*/
else
{
//Fin de la variable longue
if (VarLongue[iVarLongue].Val)
AjCode(Code::I_CTABLEAUVAL);
else
AjCode(Code::I_CTABLEAUREF);
AjEntier(var->indice);
if (*Source!='(') //On change la priorité de la parenthèse qui a
//ouvert la variable, qu'on garde ouverte pour rajouter le I_EXEC
AjParF();
// else
// Instr[VarLongue[iVarLongue].Depart].p=PRI_EXEC;
}
}
}
return true;
}
void Compilateur::SauterEspaces()
{
do
{
while (*Source==' ' || *Source=='\t' || *Source=='\r')
Source++;
//Commentaires
if (*Source=='#' && Source[1]=='!')
{
Source+=2;
while ((*Source!='!' || Source[1]!='#')&&(*Source))
{
if (*Source=='\n')
Ligne++;
Source++;
}
if (!*Source)
throw TXT("pas de !# pour fermer le commentaire");
Source+=2;
continue;
}
else
if ((*Source=='G')&&(Source[1]=='O')&&(Source[2]=='T')&&(Source[3]=='O')&&(ucarac(Source[4])<=32))
{
Source+=4;
while ((*Source!='\n')&&(*Source))
Source++;
return;
}
else
if (*Source=='^') //Continuation de ligne
{
if (Source[1]=='\r' && Source[2]=='\n')
{
Source+=3;
Ligne++;
}
else if (Source[1]=='\n')
{
Source+=2;
Ligne++;
}
else
return;
}
else
return;
}
while (1);
}
void Compilateur::FinOu()
{
//On vire l'entier du FINOU
Ins.t-=sizeof(int);
Ins.i=&Ins.c[Ins.t];
int Ou;
int NouvOu=*(int*)Ins.i;
do
{
Ou=NouvOu;
if (EtOu[Ou]==-1)
throw TXT("arg");
NouvOu=*(int*)&Ins.c[EtOu[Ou]+1];
Ins.ChgGotoRel(EtOu[Ou]+1,(int)Ins.t);
//*(int*)&Ins.c[]=(int)Ins.t;
//clog << "NouvOu= "<<NouvOu<<" Ou="<<Ou<<"\n";
}
while (NouvOu!=Ou);
}
void Compilateur::CreerCodeFinal(LigneDeCode & insTri)
{
Code CodePrec= Code::I_STOP,CodePrec2= Code::I_STOP;
int CodePrecPos=0,CodePrec2Pos=0;
for (uint Ac=0; Ac<insTri.nIns; Ac++)
{
//if (ValTri[InsTri[Ac].pVal].Type==TYPE_CODE)
{
int j=insTri.ins[Ac].pVal;
if (CodePrec== Code::I_FINOUET)
{
//Si le nouveau est un OU, on transforme
//le FINOU qu'il y avait avant en un OU
if ((insTri.ins[Ac].Code== Code::I_OU)||(insTri.ins[Ac].Code== Code::I_ET))
{
EtOu[insTri.val[j].v.i]=CodePrecPos;
*(code*)&Ins.c[CodePrecPos] = (code)insTri.ins[Ac].Code;
/* Instr[Ac].Special=SPE_DEJAMIS;
Instr[Ac].nVal=0;
Ac=RIEN;*/
CodePrec = (Code)insTri.val[j].v.i;
continue;
}
else
FinOu();
}
else if ((insTri.ins[Ac].Code== Code::I_OU)||(insTri.ins[Ac].Code== Code::I_ET))
{
EtOu[insTri.val[j].v.i]=(int)Ins.t;
}
CodePrec2=CodePrec;
CodePrec2Pos=CodePrecPos;
CodePrec=insTri.ins[Ac].Code;
CodePrecPos=(int)Ins.t;
}
Ins.AjouterCode(insTri.ins[Ac].Code);
//On effectue éventuellement un traitement sur les valeurs à insérer dans
for (uint z=0; z<insTri.ins[Ac].nVal; z++)
{
uint j=z+insTri.ins[Ac].pVal;
switch(insTri.val[j].Type)
{
case TYPE_ETIQUETTE:
case TYPE_ETIQUETTE_THIS:
RefEtiq.Etendre(int(Ins.t));
break;
case TYPE_ETIQLOC:
RefEtiqL.Etendre(int(Ins.t));
break;
case TYPE_ETIQAUTO:
RefEtiqA.Etendre(SEtiqA(int(Ins.t),DebutLigne));
break;
case TYPE_ETIQAUTOCONTINUE:
{
int b=insTri.val[j].v.i;
blocs[b]->continues.Etendre((int)Ins.t);
break;
}
case TYPE_ETIQAUTOBREAK:
{
int b=insTri.val[j].v.i;
blocs[b]->breaks.Etendre((int)Ins.t);
break;
}
case TYPE_VARIABLE:
case TYPE_VARIABLELOC:
case TYPE_VARIABLETHIS:
case TYPE_VARIABLEPARAM:
insTri.val[j].v.i=insTri.val[j].v.ptr->indice;
break;
case 0:
throw TXT("erreur interne du compilateur (type instruction=0)");
}
Ins.Ajouter(insTri.val[j]);
}
}
if (CodePrec== Code::I_FINOUET)
FinOu();
}
bool Compilateur::CompilerSeparateur()
{
if ((*Source=='\n')||(*Source==0)||(*Source=='/')||(*Source=='?' && LigneAc==LP_CAS))//Fin de ligne
{
if (LigneAc==LP_CAS && *Source!='?')
throw TXT("il manque un ? en fin de cas");
if (iVarLongue)
throw TXT("un < n'est pas refermé par un >");
DebutLigne=(int)Ins.t;
int PosDebutLigne;//Position de la portion
//de code dans laquelle il faut mettre la pos du
//début de la prochaine ligne
insTri.Init();
PosPileType=0;
if (nInstr==1)
{
if (Instr[0].Special==SPE_NORMAL)
AjouterInstruction(0);
else
throw TXT("c'est quoi ce machin tout seul sur la ligne ?");
}
else if (nInstr>1)
{
//On calcule la taille des parenthèses
uint nOuvre=0,nFerme=0;
for (uint i=0; i<nInstr; i++)
{
if (Instr[i].Special==SPE_PAR_O)
{
nOuvre++;
uint l=i+1;
uint nPars=1;
while ((nPars)&&(l<nInstr))
{
if (Instr[l].Special==SPE_PAR_F)
nPars--;
else
if (Instr[l].Special==SPE_PAR_O)
nPars++;
l++;
}
if (nPars)
throw TXT("une parenthèse n'est pas refermée");
Instr[i].nVal=l-i-1;//Le nombre d'instructions entre les parenthèses+les parenthèses
Instr[i].pVal=i;
}
else if (Instr[i].Special==SPE_PAR_F)
{
nFerme++;
if (nFerme>nOuvre)
throw TXT("une parenthèse est refermée sans avoir été ouverte");
}
}
/*
si ac=0
si pile et si pile n'est pas une ( qui contient la position suivante
instruction ac=enlever l'instruction du haut de la pile
sinon
ac=suivant
suivant=0
si suivant=0
si l'instruction est une parenthèse déjà mise, sauter tout ce qui
est entre parenthèses et recommencer
rechercher l'instruction suivante :
Si l'instruction est une instruction parenthèse
sauter toutes les intructions dans les parenthèses
sinon
passer à l'instruction suivante
si ac=0
continue;
si instr=parenthèse et suiv=parenthèse fermante
ac=suiv=0
continue
si l'instruction actuelle a une priorité inférieure ou égale à l'instruction suivante
si l'instruction actuelle est une parenthèse
marquer la parenthèse comme déjà mise
se repositionner à la première instruction de la parenthèse
instruction ac=cette instruction
suiv=0
sinon
écrire l'instruction actuelle
ac=0
sinon
mettre en pile l'instruction actuelle
instruction ac=instructino suivante
suivant=0
x*y+a*b
ac = x, pile =, res =, suiv=*
ac = *, pile =, res =x, suiv=y
ac = y, pile =*, res= x,suiv=+
ac = *, pile =, res=xy,suiv=+
ac = +, pile =, res=xy*,suiv=a
ac = a, pile =+, res=xy*,suiv=*
ac = +, pile =, res=xy*a,suiv=*
ac = *, pile =+, res=xy*a,suiv=b
ac = b, pile =+*, res=xy*a,suiv=;
ac =*, pile=+, res=xy*ab,suiv;
ac =+, pile=, res=xy*ab*,suiv;
ac =;, pile =, res=xy*ab*+,suiv
x*(y+a)*b
ac = x, pile =, res =,suiv=*
ac = *, pile =, res =x,suiv=(
ac = (, pile =*, res=x,suiv=*
ac = y, pile =*(, res=x,suiv=+
ac = +, pile =*(, res=xy,suiv=a
ac = a, pile =*(+, res=xy,suiv=)
ac = +, pile =*(, res=xya,suiv=)
ac = (, pile =*, res=xya+, suiv=)
ac = *, pile =, res=xya+, suiv=*
ac = *, pile =, res=xya+*, suiv=b
ac = b, pile =*, res=xya+*, suiv=;
ac = *, pile =, res=xya+*b, suiv=;
ac = ;, pile =, res=xya+*b*, suiv
{a+b}(x*y)*c
0123456789AB
ac = {, pile =, res =, suiv=(, pos=5
ac = (, pile ={, res=, suiv=*, pos=A
ac = x, pile ={(, res=, suiv=*,pos=7
ac = *, pile ={(, res=x, suiv=y,pos=8
ac = y, pile ={(*, res=x, suiv=),pos=9
ac = *, pile ={(, res=xy, suiv=),pos=9
ac = (, pile ={(, res=xy*,suiv=),pos=9
ac =
*/
#define RIEN -1
int Ac=0, Suivant=RIEN, Pos=0;
int Pile[128];
uint PosPile=0;
int HautPile=RIEN;
Instr[nInstr].p=PRI_FIN;
Instr[nInstr].Special=SPE_FIN;
while (Suivant!=(int)nInstr || PosPile)
{
if (Ac==RIEN)//Cherchons l'instruction actuelle
{
/* Si dans la pile on a une instruction normale
ou dans le cas particulier (1)
on récupère l'instruction dans la pile
sinon on passe à l'instruction suivante
(1) Quand on a SPE_PAR_OM en haut de la pile et une
parenthèse fermante en suite, cela signifie qu'on a traité tout
le contenu des parenthèses et on se replace à son début*/
if (PosPile &&
(Instr[HautPile].Special!=SPE_PAR_OM || (Suivant!=-1 && Instr[Suivant].Special==SPE_PAR_F)))
//||Instr[HautPile].pVal>Pos || (Instr[HautPile].pVal+Instr[HautPile].nVal<Pos)))
{
PosPile--;
Ac=HautPile;//Va permettre son élimination
if (PosPile)
HautPile=Pile[PosPile-1];
else
HautPile=RIEN;
}
else
{
Ac=Suivant;
Suivant=RIEN;
}
}
if (Suivant==RIEN)
{
/*Si on n'a pas d'instruction suivante :
si l'instruction lue est une parenthèse,
on saute son contenu */
if (Instr[Pos].Special==SPE_PAR_O)
Pos+=Instr[Pos].nVal;
Pos++;
//On saute les instructions déjà mises
while ((Instr[Pos].Special==SPE_PAR_OM)
||(Instr[Pos].Special==SPE_DEJAMIS))
Pos+=Instr[Pos].nVal+1;
Suivant=Pos;
}
if (Ac==RIEN)
continue;
//Si Ac et Suivant sont des parenthèses, on les annulle
if (Instr[Ac].Special==SPE_PAR_OM && Instr[Suivant].Special==SPE_PAR_F)
{
Ac=RIEN;
Suivant=RIEN;
continue;
}
if (Instr[Ac].p<=Instr[Suivant].p)
{
//Si la priorité de Ac est inférieure ou égale
//à la priorité de Suivant, on la garde
if (Instr[Ac].Special==SPE_PAR_O)
{
/*Si l'instruction Ac était une parenthèse
on va examiner 'récursivement' son contenu
Pour cela on empile le début de la parenthèse,
et on se place sur l'instruction après la parenthèse*/
Instr[Ac].Special=SPE_PAR_OM;
HautPile=Ac;
Pile[PosPile++]=HautPile;
Ac=Pos=Ac+1;
Suivant=RIEN;
//TODO: régler le problème des parenthèses vides
/*Pos=Ac;
Ac=RIEN;
Suivant=RIEN;*/
}
else
{
//Sinon on ajoute l'instruction
AjouterInstruction(Ac);
Instr[Ac].Special=SPE_DEJAMIS;
Instr[Ac].nVal=0;
Ac=RIEN;
}
}
else
{
//On empile l'instruction
Pile[PosPile++]=Ac;
HautPile=Ac;
Ac=Suivant;
Suivant=RIEN;
}
}
}
if (LigneAc==LP_FOR_PAS)
{
LigneDeCode *ldc=new LigneDeCode;
ldc->nIns=insTri.nIns;
ldc->nVals=insTri.nVals;
memcpy(ldc->ins,insTri.ins,insTri.nIns*sizeof(SInstr));
memcpy(ldc->val,insTri.val,insTri.nVals*sizeof(valeur));
for (index_t i=0; i<insTri.nVals; i++)
insTri.val[i].Effacer();
blocs.Dernier()->pasDuFor=ldc;
insTri.Init();
}
if (LigneAc==LP_CAS)
{
if (insTri.nIns==0)
throw TXT("cas vide");
if (insTri.nIns>1)
throw TXT("le cas ne se résoud pas en une constante");
if (insTri.ins[0].Code!= Code::I_ENTIER)
throw TXT("le cas doit être une constante entière");
CCasSwitch casSwitch((code*)Ins.t,insTri.val[0].v.i);
programme->Switch[AcSwitch.Dernier()]->Cas.Etendre(casSwitch);
insTri.Init();
}
nValeurs=0;
nInstr=0;
if (insTri.nIns)
{
Ins.AjouterCode(Code::I_DEBUTLIGNE);
Ins.AjouterEntier(Ligne);
if (ProbaSauterLigne)
{
Ins.AjouterCode(Code::I_PROBASAUTERLIGNE);
Ins.AjouterChances(ProbaSauterLigne);
PosDebutLigne=int(Ins.t);
Ins.AjouterEntier(0);
}
CreerCodeFinal(insTri);
/*if (PosPileType)
{
Ins.AjouterCode(I_DEPLACERHAUTPILE);
Ins.AjouterEntier(-(int)PosPileType);
}*/
if (ProbaSauterLigne)
{
Ins.ChgGotoRel(PosDebutLigne,(int)Ins.t);
ProbaSauterLigne=0;
}
}
carac TypeFinLigne=*Source;
if (TypeFinLigne)
Source++;
if (LigneAc==LP_FOREACH_INIT)
{
index_t svarLoc=(index_t)blocs[blocs.l-2]->symbole->taille;
blocs.Dernier()->depart=(int)Ins.t;
Ins.AjouterCode(Code::I_VALEURVARLOC);
Ins.AjouterEntier(int(svarLoc));
Ins.AjouterCode(Code::I_VARIABLELOC);
Ins.AjouterEntier(int(svarLoc+1));
Ins.AjouterCode(Code::I_TAILLE);
Ins.AjouterCode(Code::I_INFERIEUR);
Ins.AjouterCode(Code::I_GOTOZEROR);
blocs.Dernier()->breaks.Etendre((int)Ins.t);
Ins.AjouterEntier(0);
Ins.AjouterCode(Code::I_VARIABLELOC);
Ins.AjouterEntier(int(svarLoc+2));
Ins.AjouterCode(Code::I_VARIABLELOC);
Ins.AjouterEntier(int(svarLoc+1));
Ins.AjouterCode(Code::I_VALEURVARLOC);
Ins.AjouterEntier(int(svarLoc));
Ins.AjouterCode(Code::I_TABLEAUVAL);
Ins.AjouterCode(Code::I_INSTANCEDE);
LigneAc=LP_DEBUTBLOC;
}
if ((TypeFinLigne=='/')&&(LigneAc==LP_DEBUTBLOC))
{
blocs.Dernier()->blocLigne=true;
LignePrec=LigneAc;
LigneAc=LP_NORMALE;
}
else if (LigneAc==LP_FOR_INIT)
{
LignePrec=LigneAc;
LigneAc=LP_FOR_TEST;
blocs.Dernier()->depart=(int)Ins.t;
AjCode(Code::I_GOTOZEROR,PRI_MAX);
AjEntierType((int)blocs.l-1,TYPE_ETIQAUTOBREAK);
}
else if (LigneAc==LP_FOR_TEST)
{
LignePrec=LigneAc;
LigneAc=LP_FOR_PAS;
}
else if (LigneAc==LP_FOR_PAS)
{
LignePrec=LigneAc;
LigneAc=LP_NORMALE;
if (TypeFinLigne=='/')
blocs.Dernier()->blocLigne=true;
}
else
{
LignePrec=LigneAc;
LigneAc=LP_NORMALE;
while (blocs.l && blocs.Dernier()->blocLigne)
FinBloc();
}
if (TypeFinLigne=='\n')
Ligne++;
if (TypeFinLigne==0)
{
return true;
}
}
else
return false;
return true;
}
bool Compilateur::CompilerTableau()
{
if ((*Source==SEP_TAB_O)||(*Source==SEP_HAC_O))
{
if (VarLongue[iVarLongue].Type.l==0)
throw TXT("le < pour l'indice de tableau doit coller à la variable");
/*La variable doit être du type XXX TABLEAU/HACHAGE
ou à la rigueur être un PINGOUIN, ou, dans le cas de <>
du type XXX classe (!=entier...) pour un accès direct
aux propriétés*/
if (VarLongue[iVarLongue].Type.Dernier()!=symboleValeur)
{
//On vérifie que le symbole correspond bien à la déclaration
//de la variable
if (*Source==SEP_TAB_O
&&VarLongue[iVarLongue].Type.Dernier()!=symboleTableau
&&VarLongue[iVarLongue].Type.Dernier()->IsPod())
{
AfficherType(VarLongue[iVarLongue].Type);
throw TXT("symbole < invalide car ce n'est pas un tableau");
}
if (*Source==SEP_HAC_O
&&VarLongue[iVarLongue].Type.Dernier()!=symboleTableHachage)
throw TXT("ce n'est pas une table de hachage");
}
AjParO(PRI_CONSTANTE);
VarLongue[++iVarLongue].Type.Vider();
Source++;
}
else if ((*Source=='>')||(*Source==SEP_HAC_F))
{
bool Hac=(*Source==SEP_HAC_F);
Source++;
SauterEspaces();
if (iVarLongue==0)
throw TXT("symbole > ou ] innattendu, le tableau n'a pas été ouvert");
iVarLongue--;
if (VarLongue[iVarLongue].Type.l==0)
throw TXT("bug dans la gestion des tableaux");
/* clog <<"fermeture ";
AfficherType(VarLongue[iVarLongue].Type);*/
//On peut avoir par exemple ENTIER TABLEAU
//On vire TABLEAU (puisque a[3] est du type des membres a)
//On vérifie que le truc qui ferme correspond bien au type de la variable
if (VarLongue[iVarLongue].Type.Dernier()!=symboleValeur)
{
Symbole * c=VarLongue[iVarLongue].Type.Depiler();
//On vérifie par la même occasion qu'on ferme avec le bon type
if (!Hac
&&c!=symboleTableau&& c->type!=Symbole::Classe)
throw TXT("symbole > invalide car ce n'est pas un tableau");
if (Hac
&&c!=symboleTableHachage)
throw TXT("ce n'est pas une table de hachage");
}
AjParF();
if (*Source==SEP_TAB_O || *Source==SEP_PROP || *Source==SEP_HAC_O)
{
//On continue la variable longue
AjCode(Hac? Code::I_HACHAGEREF: Code::I_TABLEAUREF);
}
else
{
//Fin de la variable longue
VarLongue[iVarLongue].Type.Vider();
if (*Source=='(')
{
AjCode(Hac? Code::I_HACHAGEVAL: Code::I_TABLEAUVAL);
//On change la priorité de la variable longue
//Instr[VarLongue[iVarLongue].Depart].p=PRI_EXEC;
//et on ne ferme pas la parenthèse...
}
else
{
if (VarLongue[iVarLongue].Val)
AjCode(Hac? Code::I_HACHAGEVAL: Code::I_TABLEAUVAL);
else
AjCode(Hac? Code::I_HACHAGEREF: Code::I_TABLEAUREF);
AjParF();
}
}
}
else
return false;
return true;
}
void Compilateur::CompilerFonction()
{
bool definitEtiquette=false;
if (*Source==_T('§'))
{
definitEtiquette=true;
Source++;
}
Symbole * classeParent=blocs.Dernier()->symbole;
while (!classeParent->PeutContenirFonction())
classeParent=classeParent->parent;
carac * debut=Source;
int ligne=Ligne;
//On va chercher le nom de la classe si il y est
ChercherMotClef(definitEtiquette);
if (lClef==0)
throw TXT("nom d'étiquette attendu");
if ((*Source==':')&&(Source[1]=='A')&&(Source[2]=='S')
&&(Source[3]=='V'))
{
Source+=4;
SauterEspaces();
if (*Source=='(')
{
Source++;
SauterEspaces();
while (*Source!=')')
{
ChercherMotClef();
if (lClef==0)
throw TXT("erreur de syntaxe dans les parenthèses");
SauterEspaces();
}
Source++;
SauterEspaces();
}
if (*Source==':')
{
//Ça y est, on en est au nom de la classe !
//...quelle syntaxe pourrie ce GOTO++
Source++;
Symbole * s=ChercherSymbole();
if (EstNouveauSymbole(s) || !s->EstClasse())
throw TXT("la classe de cette fonction n'existe pas");
classeParent=s;
}
}
//On revient au début
Source=debut;
Ligne=ligne;
ChercherMotClef(true);
Symbole * syFonction=ChercherSymboleDans(classeParent);
SauterEspaces();
if (!EstNouveauSymbole(syFonction))
{
//On regarde si on est en train de définir la valeur du symbole
if (syFonction->Valeur.Type==TYPE_ETIQUETTE)
throw TXT("la fonction a déjà été définie");
}
else
{
//On crée le symbole
syFonction=programme->NouveauSymbole(MotClef,lClef,CType(symboleValeur),
blocs.Dernier()->symbole);
syFonction->attributs|=Symbole::constante;
}
//On calcule la valeur
int valeurEtiquette=0;
const carac * c=MotClef;
for (index_t a=0; a<lClef; a++)
{
valeurEtiquette*=10;
valeurEtiquette+=*c-'0';
c++;
}
//Début d'un bloc de fonction
if ((*Source==':')&&(Source[1]=='A')&&(Source[2]=='S')
&&(Source[3]=='V'))
{
definitEtiquette=true;
Source+=4;
SauterEspaces();
index_t nNouvParametres=0;
if (*Source=='(')//Les paramètres
{
Source++;
do
{
SauterEspaces();
ChercherMotClef();
if (lClef==0)
break;
Symbole * nouveau=programme->NouveauSymbole(MotClef,lClef,CType(symboleValeur),
syFonction);
nouveau->acces=Symbole::Local;
nouveau->type=Symbole::VariableParam;
nouveau->indice=nNouvParametres++;
}
while(1);
if (*Source!=')')
throw TXT("parenthèse fermante attendue");
Source++;
}
if (*Source==':')//Classe
{
Source++;
ChercherSymbole();//on fait ça, mais on la connait déjà évidemment
DebutBloc(TypeBloc::Classe,classeParent);
blocs.Dernier()->classeSpecifiee=true;
}
DebutBloc(TypeBloc::Fonction,syFonction);
if (classeParent!=programme->symboleGlobal)
{
carac * k=classeParent->nom;
while (*k)
{
valeurEtiquette*=10;
valeurEtiquette+=*k-'0';
k++;
}
if (czcmp(syFonction->nom,_T("berger"))==0)
{
//C'est le constructeur
classeParent->defConstr=syFonction;
}
}
}
if (classeParent!=syFonction->parent)
{
//On la vire d'où elle est...
//Un peu chiant ça...
Symbole * ancParent=syFonction->parent;
if (ancParent->fils==syFonction)
ancParent->fils=syFonction->suivant;
//On reconnecte le frère
for (Symbole * f=ancParent->fils; f!=0; f=f->suivant)
{
if (f->suivant==syFonction)
{
f->suivant=syFonction->suivant;
break;
}
}
syFonction->parent=classeParent;
syFonction->suivant=classeParent->fils;
classeParent->fils=syFonction;
}
bool fnthis;
if (syFonction->parent->attributs & Symbole::filsthis)
fnthis=true;
else
fnthis=false;
syFonction->etiquette=valeurEtiquette;
if (definitEtiquette)
{
syFonction->Valeur.Type=TYPE_ETIQUETTE;
syFonction->Valeur.v.i=(int)Ins.t;
}
//On regarde si il y a des attributs, style GIVRE
ChercherMotClef();
if (lClef)
{
if (EstMotClef(_T("GIVRE")))
{
fnthis=false;
}
else
Source=MotClef;//On annule
}
if (fnthis)
{
syFonction->TypeAc.Def(symboleValeur);//le retour
syFonction->TypeAc.Empiler(symboleDebutParams);
syFonction->TypeAc.Empiler(symboleValeur);
syFonction->TypeAc.Empiler(symboleEtc);
syFonction->TypeAc.Empiler(symboleMethodeGPP);
syFonction->type=Symbole::MethodeGPP;
}
else
{
syFonction->TypeAc.Def(symboleValeur);//le retour
syFonction->TypeAc.Empiler(symboleDebutParams);
syFonction->TypeAc.Empiler(symboleValeur);
syFonction->TypeAc.Empiler(symboleEtc);
syFonction->TypeAc.Empiler(symboleFonctionGPP);
syFonction->type=Symbole::FonctionGPP;
}
syFonction->attributs|=Symbole::constante;
}
bool Compilateur::CompilerConstante()
{
if ((*Source=='^')&&(ucarac(Source[1])>' '))//Expression régulière
{
Source++;
carac Limite=*(Source++);
carac *ExpReg=Source;
while (*Source && *Source!=Limite)
{
if (*Source=='\\')
{
Source++;
if (*Source==0)
break;
}
if (*Source=='\n')
Ligne++;
Source++;
}
if (*Source==Limite)
*(Source++)=0;
else
throw TXT("expression régulière non terminée");
carac * modif=0;
if (*Source>='a' && *Source<='z')
{
modif=Source;
while (*Source>='a' && *Source<='z')
Source++;
if (*Source)
*(Source++)=0;
}
AjCode(Code::I_EXPREG);
AjExpReg(ExpReg,modif);
}
else if (*Source==';')//Constante de caractère de contrôle
{
Source++;
carac car='\n';
if (ALPHANUM(ucarac(*Source)))
{
switch (*Source)
{
case 'n':
car='\n';
break;
case 'r':
car='\r';
break;
case 't':
car='\t';
break;
case '0':
car=0;
break;
default:
throw TXT("caractère de contrôle inconnu");
}
Source++;
}
AjCode(Code::I_CARAC,PRI_CONSTANTE);
AjCarac(car);
}
else if (*Source==_T('«'))
{
Source++;
size_t l=0;
carac * dep=Source;
while ((*Source)&&(*Source!=_T('»')))
{
if (*Source==';')
{
Source++;
l++;
if (*Source==0)
break;
}
if (*Source=='\n')
Ligne++;
Source++;
l++;
}
if (*Source!=_T('»'))
throw TXT("une chaîne doit se terminer par »");
Source++;
//achaine c(dep,l);
AjCode(Code::I_CONSTANTE,PRI_CONSTANTE);
AjType(TYPE_CHAINE);
AjChaine(dep,l);
}
else if (*Source=='$')
{
Source++;
bool Modificateur;
if (*Source=='<')
{
Modificateur=true;
Source++;
}
else
Modificateur=false;
int c=0;
int nChiffres=0;
while ((ucarac(*Source)>='0' && ucarac(*Source)<='9'))
{
c*=10;
c+=*Source-'0';
Source++;
nChiffres++;
}
if (nChiffres==0)
c=PRI_VIRGULE;
if (Modificateur)
{
if (nInstr==0)
throw TXT("tentative de modifier la priorité de l'instruction précédente, alors qu'il n'y en a pas");
Instr[nInstr-1].p=c;
}
else
{
AjNoOp(c);
}
}
else if (*Source==_T('§'))
{
if (nInstr)
throw TXT("les étiquettes doivent se trouver en début de ligne");
CompilerFonction();
}
else if (*Source=='?')
{
float c=0;
Source++;
bool Negatif;
if (*Source=='-')
{
Negatif=true;
Source++;
}
else
Negatif=false;
while (ucarac(*Source)>='0' && ucarac(*Source)<='9')
{
c*=10;
c+=*Source-'0';
Source++;
}
if (*Source==',')
{
Source++;
float d=0;
float div=1;
while (ucarac(*Source)>='0' && ucarac(*Source)<='9')
{
d*=10;
d+=*Source-'0';
Source++;
div*=10;
}
c+=d/div;
}
if (*Source==_T('ê') || *Source==_T('Ê'))
{
Source++;
bool Neg;
if (*Source=='-')
{
Neg=true;
Source++;
}
else
Neg=false;
float e=0;
while (ucarac(*Source)>='0' && ucarac(*Source)<='9')
{
e*=10;
e+=*Source-'0';
Source++;
}
if (Neg)
e=-e;
c*=powf(10,e);
}
if (Negatif)
c=-c;
AjCode(Code::I_CHANCES,PRI_CONSTANTE);
AjChances(c);
}
else if ((*Source=='*')&&(Source[1]=='`'))//Constante de caractère
{
Source+=2;
carac c=*(Source++);
if (*Source!='\'')
throw TXT("les caractères doivent être entre ` et '");
Source++;
AjCode(Code::I_CARAC,PRI_CONSTANTE);
AjCarac(c);
}
else if ((*Source=='*')&&(Source[1]=='('))//Constante entière
{
Source+=2;
int c=0;
bool Negatif;
if (*Source=='-')
{
Negatif=true;
Source++;
}
else
Negatif=false;
while (*Source && *Source!=')' && *Source!='\n')
{
c*=10;
c+=*Source-'0';
Source++;
}
if (Negatif)
c=-c;
if (*Source!=')')
throw TXT("les nombres entiers doivent se terminer par )");
Source++;
AjCode(Code::I_ENTIER,PRI_CONSTANTE);
AjEntier(c);
}
else
return false;
return true;
}
void Compilateur::ChercherMotClef(bool avecChiffres)
{
lClef=0;
if (ALPHA(*Source) || (avecChiffres && (*Source>='0') && (*Source<='9')))
{
MotClef=Source;
do
{
Source++;
lClef++;
}
while(ALPHA(*Source) || (avecChiffres && (*Source>='0') && (*Source<='9')));
}
}
bool Compilateur::CompilerClasse(Symbole * cla)
{
SauterEspaces();
//Opérateurs spéciaux
if (*Source=='`')
{
Source++;
AjCode(Code::I_ENTIER,PRI_CONSTANTE);
AjEntier((int)size_t(cla));//TODO : un truc qui veut dire quelquechose
return true;
}
if (*Source=='^' && Source[1]=='^')
{
//On veut le numéro de la propriété
Source+=2;
ChercherMotClef();
Symbole * prop=ChercherSymboleDans(cla);
if (!EstNouveauSymbole(prop))
{
AjCode(Code::I_ENTIER,PRI_CONSTANTE);
AjEntier((int)prop->indice);
return true;
}
throw CErreur(TXT("propriété %.*s inconnue après le ^^"),
lClef,MotClef);
}
bool Redef=false;
bool Constructeur=true;
bool givre;
if (blocs.Dernier()->symbole->attributs & Symbole::filsglob)
givre=true;
else
givre=false;
SauterEspaces();
carac * DebutNom=Source;
ChercherMotClef();
while (lClef)
{
if (EstMotClef(_T("sauvage")))
{
Redef=false;
Constructeur=false;
}
else if (EstMotClef(_T("zap")))
{
Redef=true;
Constructeur=false;
}
else if (EstMotClef(_T("GIVRE")))
givre=true;
else
break;
SauterEspaces();
DebutNom=Source;
ChercherMotClef();
}
Symbole * var=ChercherSymboleDans(blocs.Dernier()->symbole);
if (EstNouveauSymbole(var)) //Nouvelle variable
{
var=programme->NouveauSymbole(MotClef,lClef,CType(symboleValeur),
blocs.Dernier()->symbole);
}
if (!Redef)
{
if (givre)
{
var->indice=programme->varGlob.l;
programme->varGlob.Etendre(valeur());
var->type=Symbole::VariableGlobale;
}
else
{
Symbole * parent=blocs.Dernier()->symbole;
var->indice=(index_t)parent->taille++;
if (parent->attributs & Symbole::filsthis)
var->type=Symbole::VariableThis;
else
var->type=Symbole::VariableLocale;
}
}
var->TypeAc.Def(cla);
//Nombre de dimensions
LireType(var->TypeAc);
if (!Redef)
var->typeDepart=var->TypeAc;
/*
if (var->TypeAc.l==1 && Constructeur)
{
if (cla->type==Symbole::ClasseC)
{
//On alloue l'objet
AjCode(Code::I_ALLOCATION);
AjPtrType(cla,TYPE_TYPE);
}
else
{
//TODO: non implémenté pour les classes GPP, on alloue pas
}
}*/
SauterEspaces();
if (*Source=='=')
{
Source=DebutNom;//TODO: utiliser un appel au constructeur par copie
}
else if (Constructeur && cla->defConstr)
{
if (var->TypeAc.l!=1)
throw TXT("le berger ne peut pas être exécuté avec les troupeaux anonymes de troupeaux");
AjCode(givre? Code::I_VARIABLE: Code::I_VARIABLELOC);
AjPtrType(var,TYPE_VARIABLE);
AjCode(Code::I_INSTANCEDE,PRI_DEF);
AjParO(PRI_EXEC);
InsererConstante(cla->defConstr);
AjCode(Code::I_EXECVAL,PRI_CONSTANTE);
AjParF();
AjParO();
AjDebutParams();
if (*Source=='\n')
AjParF();
else if (*Source=='(')
{
Source++;
}
}
else if (*Source!='\n')
{
if (ucarac(*Source)<=32)
throw CErreur(TXT("caractère 0x%x inattendu après la déclaration"),*Source);
else
throw CErreur(TXT("caractère %c inattendu après la déclaration"),*Source);
}
return true;
}
GotoPP::BoutCode* Compilateur::Compiler()
{
Ins.Reinit();
Ligne=1;
nValeurs=0;
nInstr=0;
iVarLongue=0;
ProbaSauterLigne=0;
InstrAc=IP_PARO;
CibleAuto=0;
DernierSi=~0;
NiveauGourou=1;
etaitPremierSymbole=programme->symbole.FinI();
index_t EtaitPremierSource=programme->fichierSource.l;
//On inclut l'espace de nommage "rien" qui contient
//les fonctions internes
useEspace.Vider();
useEspace.Etendre(symboleStd);
//useEspace.Etendre();
//useEspace.Dernier()=rien;
//On crée le bloc global
blocs.Vider();
DebutBloc(TypeBloc::Classe,programme->symboleGlobal);
/*
% <= symbole global, peut contenir des chiffres
%% <= symbole pas global, peut contenir des chiffres
*/
while (1)
{
SauterEspaces();
ChercherMotClef();
InstrPrec=InstrAc;
InstrAc=IP_VARIABLE;
const bool AVECET=true;
const bool SANSET=false;
if (lClef)
{
if (!CompilerMotClef())
{
Source=MotClef;
Symbole * s=ChercherSymbole();
if (!EstNouveauSymbole(s) && s->EstClasse())
CompilerClasse(s);
else
CompilerVariable(s, SANSET);
}
}
else
{
if (!CompilerSeparateur())
{
if (*Source=='&')
{
Source++;
Symbole * s=ChercherSymbole();
if (!EstNouveauSymbole(s) && s->EstClasse())
throw TXT("nom de troupeau innattendu après le symbole &");
else
CompilerVariable(s, AVECET);
}
else
if (!CompilerOperateur() && !CompilerSeparateur() &&
!CompilerTableau() && !CompilerConstante())
{
if (*Source<=' ')
throw CErreur(TXT("caractère 0x%x inattendu"),*Source);
else
throw CErreur(TXT("caractère %c inattendu"),*Source);
}
}
else
if (*Source==0)
{
if (AcFichierSource &&
AcFichierSource->Parent!=0)
{
AcFichierSource->FinCode=(code*)Ins.t;
AcFichierSource=AcFichierSource->Parent;
Ligne=AcFichierSource->Ligne;
Source=AcFichierSource->AcPos;
}
else
break;
}
}
}
Ins.AjouterCode(Code::I_STOP);
if (AcSwitch.l)
throw TXT("un GOTOMULTIPLE n'a pas été fermé");
// DebutLigne=Ins.c;
//Bon on corrige tous les labels !
for (Symbole ** l=etaitPremierSymbole; l<programme->symbole.Fin(); l++)
{
if ((*l)->type==Symbole::FonctionGPP ||
(*l)->type==Symbole::MethodeGPP)
{
code * c=&Ins.c[(*l)->Valeur.v.i];
(*l)->Valeur.v.et=c;
}
}
// qsort(&Label.Premier(),Label.l,sizeof(SLabel),CmpLabels);
//clog << RefEtiq.l << " références à des étiquettes \n";
for (index_t z=0; z<RefEtiq.l; z++)
{
Symbole **k=(Symbole**)&Ins.c[RefEtiq[z]];
Symbole * v=*k;
if (v->Valeur.Type!=TYPE_ETIQUETTE &&
v->Valeur.Type!=TYPE_ETIQUETTE_THIS )
throw CErreur(TXT("lors de l'édition des liens, l'étiquette %s%%%s n'a pas été définie"),
v->parent->nom,v->nom);
*((code**)k)=v->Valeur.v.et;
}
for (index_t z=0; z<RefEtiqL.l; z++)
{
Symbole **k=(Symbole **)&Ins.c[RefEtiqL[z]];
Symbole * v=*k;
if (v->Valeur.Type!=TYPE_ETIQUETTE &&
v->Valeur.Type!=TYPE_ETIQUETTE_THIS )
throw CErreur(TXT("lors de l'édition des liens, l'étiquette %s n'a pas été définie"),
v->nom);
*((size_t*)k)=size_t((size_t)v->Valeur.v.et-(size_t)k-sizeof(size_t));
}
//clog << "Taille du code : "<<Ins.t<<" octets\n";
if (blocs.l>1)
throw TXT("tous les blocs d'instructions n'ont pas été fermés");
if (RefEtiqA.l)
throw TXT("toutes les étiquettes automatiques n'ont pas été placées avec AC");
//On corrige tous les switchs
for (index_t i=0; i<programme->Switch.l; i++)
{
for (index_t c=0; c<programme->Switch[i]->Cas.l; c++)
programme->Switch[i]->Cas[c].Pos+=(size_t)Ins.c;
if (programme->Switch[i]->PosDefaut)
programme->Switch[i]->PosDefaut+=(size_t)Ins.c;
}
//On corrige tous les fichiers sources
for (index_t i=EtaitPremierSource; i<programme->fichierSource.l; i++)
{
programme->fichierSource[i]->DebutCode+=(size_t)Ins.c;
programme->fichierSource[i]->FinCode+=(size_t)Ins.c;
}
Ins.i=Ins.c;
programme->InitVarGlob();
return Ins.CreerBoutCode();
}
int Compilateur::AcLigne()
{
return Ligne;
}
carac * Compilateur::AcFichier()
{
if (AcFichierSource!=0)
return AcFichierSource->Nom;
else
return TXT("<code dynamique>");
}
|
Sidoine/gotopp
|
src/compilateur/compilateur.cpp
|
C++
|
gpl-2.0
| 70,880
|
<?php
if ( ! defined( 'ABSPATH' ) ) {
die( '-1' );
}
$events_label_singular = tribe_get_event_label_singular();
$events_label_plural = tribe_get_event_label_plural();
if ( ! $_POST ) {
$event_cost = get_post_meta( $post_id, '_EventCost', false );
if (is_array($event_cost)) {
if (empty($event_cost)) {
$event_cost = '';
} else {
$event_cost = $event_cost[0];
}
}
} else {
$event_cost = isset( $_POST['EventCost'] ) ? esc_attr( $_POST['EventCost'] ) : '';
}
if ( apply_filters( 'tribe_events_community_display_cost_section', true ) ) {
?>
<div class="tribe_sectionheader">
<h4><?php tribe_community_events_field_label( 'EventCost', __( 'Cost', 'the-events-calendar') ); ?></h4>
</div><!-- .tribe_sectionheader -->
<div class="block">
<input type="checkbox" id="isFreeEventCheckbox" <?php checked($event_cost, '0'); ?> />
<label style="margin-right:20px;" for="isFreeEventCheckbox"><?php esc_html_e( 'Free', 'the-events-calendar' ); ?></label>
<span id='EventCostContainer'>
<label>
<input type="text" id="EventCost" name="EventCost" size="10" value="<?php echo esc_attr( $event_cost ); ?>" />
рублей
</label>
</span>
</div>
<?php
}//end if
|
Ilya-d/htdocs
|
wp-content/themes/malivi/templates/community/modules/cost.php
|
PHP
|
gpl-2.0
| 1,280
|
#ifndef INTERPROCESS_H_QFGT309Z
#define INTERPROCESS_H_QFGT309Z
#include <string>
#include <exception>
#include <stdexcept>
class interprocess_interface {
public:
interprocess_interface(){};
interprocess_interface(std::wstring);
virtual ~interprocess_interface(){};
protected:
virtual std::string on_msg_send(std::string&)=0;
virtual std::string on_msg_receive(std::string&)=0;
public:
void send_msg(std::string);
void listen();
private:
void run();
};
namespace ipc {
class exception: public std::exception {};
class fifo_open_error: public ipc::exception {
public:
const char* what() noexcept {
return "Error while opening fifo";
}
};
class fifo_create_error: public ipc::exception {
public:
const char* what() noexcept {
return "Error while creating fifo";
}
};
class wrong_msg_size: public ipc::exception {
public:
const char* what() noexcept {
return "Message size is wrong";
}
};
class server_process_connected: public ipc::exception {
public:
const char* what() noexcept {
return "There is a process connected as server";
}
};
}
#endif /* end of include guard: INTERPROCESS_H_QFGT309Z */
|
kristiyan-peychev/banicaMP
|
ipc/interprocess.h
|
C
|
gpl-2.0
| 1,321
|
/*
Warrior of Dreamworld, 2D Massivly Mutiplayer Online Role-playing Game
Copyright (C) 2012 Ryan Lahfa
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "shared/Log.hpp"
#include "ObjectMgr.hpp"
#include <boost/archive/binary_iarchive.hpp>
ObjectMgr* sObjectMgr;
ObjectMgr::ObjectMgr(std::string const& TilesetPath, std::string const& TemplatesFilePath) :
m_TilesetPath (TilesetPath),
m_TemplatesFilePath (TemplatesFilePath)
{
}
ObjectMgr::~ObjectMgr()
{
std::for_each(m_ItemTemplates.begin(), m_ItemTemplates.end(), MapDeleter());
std::for_each(m_CreatureTemplates.begin(), m_CreatureTemplates.end(), MapDeleter());
std::for_each(m_Tilesets.begin(), m_Tilesets.end(), MapDeleter());
std::for_each(m_Textures.begin(), m_Textures.end(), MapDeleter());
}
void ObjectMgr::Initialize()
{
LoadTemplates();
}
void ObjectMgr::LoadTileset(std::string const& FileName)
{
if (!SearchTileset(FileName))
{
sf::Texture* tilesetTexture = new sf::Texture;
if (!tilesetTexture->loadFromFile(m_TilesetPath + '/' + FileName))
{
sLog.Write("Failed to load tileset texture: %s !", FileName);
throw std::runtime_error("Failed to load a texture !");
}
m_Tilesets[FileName] = tilesetTexture;
}
}
ItemTemplate* ObjectMgr::GetItemTemplate(uint64 ItemID)
{
if (!SearchItemTemplate(ItemID))
{
sLog.Write("Failed to find data about this item ID: %u !", ItemID);
throw std::runtime_error("Failed to find data about something.");
}
return m_ItemTemplates[ItemID];
}
sf::Texture* ObjectMgr::GetTileset(std::string const& TilesetName)
{
if (SearchTileset(TilesetName))
return m_Tilesets[TilesetName];
else
{
LoadTileset(TilesetName);
return m_Tilesets[TilesetName];
}
}
sf::Texture* ObjectMgr::GetTileset(std::string const& TilesetName, sf::Color const& Mask, uint8 alpha)
{
if (SearchTileset(TilesetName))
return m_Tilesets[TilesetName];
else
{
LoadTileset(TilesetName);
sf::Texture* tileset = m_Tilesets[TilesetName];
sf::Image imageTexture = tileset->copyToImage();
imageTexture.createMaskFromColor(Mask, alpha);
tileset->update(imageTexture);
return tileset;
}
}
sf::Texture* ObjectMgr::GetTexture(std::string const& TextureName, std::string const& TexturePath)
{
auto TextureIt = m_Textures.find(TextureName);
if (TextureIt != m_Textures.end())
return TextureIt->second;
sf::Texture* Tex = new sf::Texture;
if (!Tex->loadFromFile(TexturePath))
{
sLog.Write("Failed to load texture (texture name: %s, texture path: %s)", TextureName, TexturePath);
throw std::runtime_error("Failed to load texture.");
}
m_Textures[TextureName] = Tex;
return Tex;
}
bool ObjectMgr::SearchItemTemplate(uint64 ItemID) const
{
return m_ItemTemplates.find(ItemID) != m_ItemTemplates.end();
}
bool ObjectMgr::SearchCreatureTemplate(uint64 CreatureEntry) const
{
return m_CreatureTemplates.find(CreatureEntry) != m_CreatureTemplates.end();
}
bool ObjectMgr::SearchTileset(std::string const& FileName) const
{
return m_Tilesets.find(FileName) != m_Tilesets.end();
}
void ObjectMgr::LoadItemTemplate(std::string const& lineData)
{
ItemTemplate* Proto = new ItemTemplate;
std::vector<std::string> data;
boost::algorithm::split(data, lineData, boost::is_any_of(";"), boost::algorithm::token_compress_on);
Proto->ItemID = boost::lexical_cast<uint64>(data.at(0));
Proto->Class = boost::lexical_cast<uint32>(data.at(1));
Proto->SubClass = boost::lexical_cast<uint32>(data.at(2));
Proto->Name = data.at(3);
Proto->DisplayInfoID = boost::lexical_cast<uint32>(data.at(4));
Proto->InventoryType = boost::lexical_cast<uint8>(data.at(5));
Proto->Description = data.at(6);
m_ItemTemplates[Proto->ItemID] = Proto;
}
void ObjectMgr::LoadCreatureTemplate(std::string const& lineData)
{
CreatureTemplate* Proto = new CreatureTemplate;
std::vector<std::string> data;
boost::algorithm::split(data, lineData, boost::is_any_of(";"), boost::algorithm::token_compress_on);
Proto->Entry = boost::lexical_cast<uint64>(data.at(0));
Proto->Name = data.at(1);
Proto->Tileset = data.at(2);
Proto->tx = boost::lexical_cast<uint16>(data.at(3));
Proto->ty = boost::lexical_cast<uint16>(data.at(4));
Proto->npcflag = boost::lexical_cast<uint16>(data.at(5)); // Really needed by Client ?
Proto->MaxHealth = boost::lexical_cast<uint32>(data.at(6));
Proto->MaxPower = boost::lexical_cast<uint32>(data.at(7));
m_CreatureTemplates[Proto->Entry] = Proto;
}
void ObjectMgr::LoadTemplates()
{
std::ifstream fileData(m_TemplatesFilePath);
if (fileData)
{
std::string line;
while (std::getline(fileData, line))
{
int idxType = line.find(";");
std::string typeTemplate = line.substr(0, idxType);
if (typeTemplate == "ItemTemplate")
LoadItemTemplate(line.substr(idxType + 1));
else if (typeTemplate == "CreatureTemplate")
LoadCreatureTemplate(line.substr(idxType + 1));
else if (typeTemplate == "QuestTemplate") // Skip it. Thanks to krofna!
;
else
sLog.Write("Unknown template type: %s. templates_info.dbc damaged ?", typeTemplate);
}
}
else
{
sLog.Write("Failed to load templates data (FileName: %s)", m_TemplatesFilePath);
throw std::runtime_error("Failed to load data.");
}
}
|
krofna/Warrior-of-Dreamworld
|
client/ObjectMgr.cpp
|
C++
|
gpl-2.0
| 6,332
|
/**
* Copyright (C) 2002-2007 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* FreeCol is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.common.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import net.sf.freecol.Reformation;
import org.w3c.dom.Element;
/**
* Represents a work location on a tile.
*/
public class ColonyTile extends FreeColGameObject implements WorkLocation, Ownable {
public static final String UNIT_CHANGE = "UNIT_CHANGE";
private Colony colony;
private Tile workTile;
private Unit unit;
private boolean colonyCenterTile;
/**
* Creates a new <code>ColonyTile</code>.
*
* @param game The <code>Game</code> this object belongs to.
* @param colony The <code>Colony</code> this object belongs to.
* @param workTile The tile in which this <code>ColonyTile</code> represents a
* <code>WorkLocation</code> for.
*/
public ColonyTile(Game game, Colony colony, Tile workTile) {
super(game);
this.colony = colony;
this.workTile = workTile;
if (colony.getTile() == workTile) {
colonyCenterTile = true;
} else {
colonyCenterTile = false;
}
}
/**
* Initiates a new <code>Building</code> from an
* XML representation.
*
* @param game The <code>Game</code> this object belongs to.
* @param in The input stream containing the XML.
* @throws XMLStreamException if an error occured during parsing.
*/
public ColonyTile(Game game, XMLStreamReader in) throws XMLStreamException {
super(game, in);
readFromXML(in);
}
/**
* Initiates a new <code>Building</code> from an
* XML representation.
*
* @param game The <code>Game</code> this object belongs to.
* @param e An XML-element that will be used to initialize
* this object.
*/
public ColonyTile(Game game, Element e) {
super(game, e);
readFromXMLElement(e);
}
/**
* Initiates a new <code>ColonyTile</code>
* with the given ID. The object should later be
* initialized by calling either
* {@link #readFromXML(XMLStreamReader)} or
* {@link #readFromXMLElement(Element)}.
*
* @param game The <code>Game</code> in which this object belong.
* @param id The unique identifier for this object.
*/
public ColonyTile(Game game, String id) {
super(game, id);
}
/**
* Gets the owner of this <code>Ownable</code>.
*
* @return The <code>Player</code> controlling this
* {@link Ownable}.
*/
public Player getOwner() {
return colony.getOwner();
}
/**
* Sets the owner of this <code>Ownable</code>.
*
* @param p The <code>Player</code> that should take ownership
* of this {@link Ownable}.
* @exception UnsupportedOperationException is always thrown by
* this method.
*/
public void setOwner(Player p) {
throw new UnsupportedOperationException();
}
/**
* Checks if this is the tile where the <code>Colony</code> is located.
* @return The result.
*/
public boolean isColonyCenterTile() {
return colonyCenterTile;
}
/**
* Gets the work tile.
*
* @return The tile in which this <code>ColonyTile</code> represents a
* <code>WorkLocation</code> for.
*/
public Tile getWorkTile() {
return workTile;
}
/**
* Gets the tile where the colony is located.
* @return The <code>Tile</code>.
*/
public Tile getTile() {
return colony.getTile();
}
public GoodsContainer getGoodsContainer() {
return null;
}
/**
* Gets the <code>Unit</code> currently working on this <code>ColonyTile</code>.
*
* @return The <code>Unit</code> or <i>null</i> if no unit is present.
* @see #setUnit
*/
public Unit getUnit() {
return unit;
}
/**
* Gets a pointer to the colony containing this tile.
* @return The <code>Colony</code>.
*/
public Colony getColony() {
return colony;
}
/**
* Sets a <code>Unit</code> to this <code>ColonyTile</code>.
*
* @param unit The <code>Unit</code>.
* @see #getUnit
*/
public void setUnit(Unit unit) {
Unit oldUnit = getUnit();
this.unit = unit;
if (oldUnit != null) {
GoodsType workType = oldUnit.getWorkType();
firePropertyChange(workType.getId(), getProductionOf(oldUnit, workType), null);
}
if (unit != null) {
GoodsType workType = unit.getWorkType();
// SOMEHOW, workType was null in unit tests
if (workType != null) {
firePropertyChange(workType.getId(), null, getProductionOf(unit, workType));
}
}
}
/**
* Gets the amount of Units at this <code>ColonyTile</code>.
* @return The amount of Units at this <code>ColonyTile</code>.
*/
public int getUnitCount() {
return (getUnit() != null) ? 1 : 0;
}
/**
* Relocates any worker on this <code>ColonyTile</code>.
* The workers are added to another {@link WorkLocation}
* within the {@link Colony}.
*/
public void relocateWorkers() {
if (getUnit() != null) {
for (WorkLocation wl : getColony().getWorkLocations()) {
if (wl != this && wl.canAdd(getUnit())) {
getUnit().work(wl);
break;
}
}
}
}
/**
* Check if this <code>WorkLocation</code> is available to the colony.
* Used by canAdd() and the gui to decide whether to draw a border
* on this tile in the colony panel.
*
* @return True if the location can be worked.
*/
public boolean canBeWorked() {
Player player = getOwner();
// Not workable if there is a settlement, hostile occupation,
// unable to work water, or lost city rumour to Europeans.
Tile tile = getWorkTile();
if (tile.getSettlement() != null
|| tile.getOccupyingUnit() != null
|| !(tile.isLand() || colony.hasAbility("model.ability.produceInWater"))
|| (player.isEuropean() && tile.hasLostCityRumour())) {
return false;
}
// Special cases when tile owned by another settlement.
Settlement settlement = tile.getOwningSettlement();
if (settlement == null) {
; // OK
} else if (settlement instanceof Colony) {
// Disallow if owned by other Europeans or in active use.
Colony otherColony = (Colony) settlement;
if (otherColony != colony) {
if (otherColony.getOwner() != player
|| otherColony.getColonyTile(tile).getUnit() != null) {
return false;
}
}
} else if (settlement instanceof IndianSettlement) {
// Disallow if owned and valued by natives.
if (player.getLandPrice(tile) > 0) {
return false;
}
} else {
throw new IllegalStateException("Bogus settlement");
}
return true;
}
/**
* Checks if the specified <code>Locatable</code> may be added to
* this <code>WorkLocation</code>.
*
* @param locatable the <code>Locatable</code>.
* @return <code>true</code> if the <code>Unit</code> may be added
* and <code>false</code> otherwise.
*/
public boolean canAdd(Locatable locatable) {
if (!canBeWorked()) {
return false;
}
if (!(locatable instanceof Unit)) {
return false;
}
Unit unit = (Unit) locatable;
if (!unit.getType().hasSkill()) {
return false;
}
return getUnit() == null || unit == getUnit();
}
/**
* Add the specified <code>Locatable</code> to this <code>WorkLocation</code>.
* @param locatable The <code>Locatable</code> that shall be added to this <code>WorkLocation</code>.
*/
public void add(Locatable locatable) {
if (isColonyCenterTile() || unit != null) {
throw new IllegalStateException("Other unit present while adding a unit to ColonyTile:" + getId());
}
if (!canAdd(locatable)) {
if (getWorkTile().getOwningSettlement() != null && getWorkTile().getOwningSettlement() != getColony()) {
throw new IllegalArgumentException("Cannot add locatable to this location: another colony claims this land!");
}
throw new IllegalArgumentException("Cannot add locatable to this location: there is a unit here already!");
}
Unit u = (Unit) locatable;
u.removeAllEquipment(false);
u.setState(Unit.UnitState.IN_COLONY);
// Find a teacher if available.
Unit potentialTeacher = getColony().findTeacher(u);
if (potentialTeacher != null) {
potentialTeacher.setStudent(u);
u.setTeacher(potentialTeacher);
}
setUnit(u);
}
/**
* Remove the specified <code>Locatable</code> from this <code>WorkLocation</code>.
* @param locatable The <code>Locatable</code> that shall be removed from this <code>WorkLocation</code>.
*/
public void remove(Locatable locatable) {
if (getUnit() == null) {
return;
}
if (!getUnit().equals(locatable)) {
return;
}
Unit oldUnit = getUnit();
oldUnit.setMovesLeft(0);
setUnit(null);
}
public List<Unit> getUnitList() {
if(getUnit() == null) {
return new ArrayList<Unit>();
} else {
return Collections.singletonList(getUnit());
}
}
public Iterator <Unit> getUnitIterator() {
return getUnitList().iterator();
}
/**
* Checks if this <code>ColonyTile</code> contains the given <code>Locatable</code>.
*
* @param locatable The <code>Locatable</code>.
* @return The result.
*/
public boolean contains(Locatable locatable) {
return (locatable == unit) ? true:false;
}
/**
* Gets the <code>Unit</code> currently working on this <code>ColonyTile</code>.
*
* @return The <code>Unit</code> or <i>null</i> if no unit is present.
* @see #setUnit
*/
public Unit getFirstUnit() {
return getUnit();
}
/**
* Gets the <code>Unit</code> currently working on this <code>ColonyTile</code>.
*
* @return The <code>Unit</code> or <i>null</i> if no unit is present.
* @see #setUnit
*/
public Unit getLastUnit() {
return getUnit();
}
/**
* Returns the unit who is occupying the tile
* @return the unit who is occupying the tile
* @see #isOccupied()
*/
public Unit getOccupyingUnit() {
return workTile.getOccupyingUnit();
}
/**
* Checks whether there is a fortified enemy unit in the tile.
* Units can't produce in occupied tiles
* @return <code>true</code> if an fortified enemy unit is in the tile
*/
public boolean isOccupied() {
return workTile.isOccupied();
}
/**
* Prepares this <code>ColonyTile</code> for a new turn.
*/
public void newTurn() {
if (isColonyCenterTile()) {
produceGoodsCenterTile();
} else if (getUnit() != null && !isOccupied()) {
produceGoods();
workTile.expendResource(getUnit().getWorkType(), getUnit().getType(), colony);
}
}
private void produceGoods() {
int amount = getProductionOf(getUnit().getWorkType());
if (amount > 0) {
colony.addGoods(getUnit().getWorkType(), amount);
unit.modifyExperience(amount);
}
}
private void produceGoodsCenterTile() {
GoodsType goodsFood = workTile.primaryGoods();
colony.addGoods(goodsFood, getProductionOf(goodsFood));
GoodsType type2 = workTile.secondaryGoods();
if (type2 != null)
colony.addGoods(type2, getProductionOf(type2));
}
/**
* Returns a worktype for a unit.
*
* @param unit a <code>Unit</code> value
* @return a workType
*/
public GoodsType getWorkType(Unit unit) {
GoodsType workType = unit.getWorkType();
int amount = getProductionOf(unit, workType);
if (amount == 0) {
List<GoodsType> farmedGoodsTypes = Reformation.getSpecification().getFarmedGoodsTypeList();
for(GoodsType farmedGoods : farmedGoodsTypes) {
int newAmount = getProductionOf(unit, farmedGoods);
if (newAmount > amount) {
amount = newAmount;
workType = farmedGoods;
}
}
}
return workType;
}
/**
* Returns the production of the given type of goods.
*
* @param goodsType a <code>GoodsType</code> value
* @return an <code>int</code> value
*/
public int getProductionOf(GoodsType goodsType) {
if (goodsType == null) {
throw new IllegalArgumentException("GoodsType must not be 'null'.");
} else if (getUnit() == null) {
if (isColonyCenterTile() &&
(goodsType.isFoodType() ||
goodsType.equals(workTile.secondaryGoods()))) {
return workTile.potential(goodsType, null);
} else {
return 0;
}
} else if (goodsType.equals(getUnit().getWorkType())) {
return getProductionOf(getUnit(), goodsType);
} else {
return 0;
}
}
/**
* Returns the production of the given type of goods.
*
* @param goodsType a <code>GoodsType</code> value
* @param unitType a <code>unitType</code> value
* @return an <code>int</code> value
*/
public Set<Modifier> getProductionModifiers(GoodsType goodsType, UnitType unitType) {
if (goodsType == null) {
throw new IllegalArgumentException("GoodsType must not be 'null'.");
} else {
Set<Modifier> result = new LinkedHashSet<Modifier>();
if (getUnit() == null) {
if (isColonyCenterTile() &&
(goodsType.isFoodType() ||
goodsType.equals(workTile.secondaryGoods()))) {
result.addAll(workTile.getProductionBonus(goodsType, null));
result.addAll(getColony().getFeatureContainer().getModifierSet(goodsType.getId()));
}
} else if (goodsType.equals(getUnit().getWorkType())) {
result.addAll(workTile.getProductionBonus(goodsType, unitType));
result.addAll(getUnit().getModifierSet(goodsType.getId()));
}
return result;
}
}
/**
* Returns the production of the given type of goods which would
* be produced by the given unit
*
* @param unit an <code>Unit</code> value
* @param goodsType a <code>GoodsType</code> value
* @return an <code>int</code> value
*/
public int getProductionOf(Unit unit, GoodsType goodsType) {
if (unit == null) {
throw new IllegalArgumentException("Unit must not be 'null'.");
} else if (workTile.isLand() || colony.hasAbility("model.ability.produceInWater")) {
int production = unit.getProductionOf(goodsType, workTile.potential(goodsType, unit.getType()));
if (production > 0) {
production = Math.max(1, production + colony.getProductionBonus());
}
return production;
} else {
return 0;
}
}
@Override
public void dispose() {
if (unit != null) {
unit.dispose();
}
super.dispose();
}
/**
* This method writes an XML-representation of this object to
* the given stream.
*
* <br><br>
*
* Only attributes visible to the given <code>Player</code> will
* be added to that representation if <code>showAll</code> is
* set to <code>false</code>.
*
* @param out The target stream.
* @param player The <code>Player</code> this XML-representation
* should be made for, or <code>null</code> if
* <code>showAll == true</code>.
* @param showAll Only attributes visible to <code>player</code>
* will be added to the representation if <code>showAll</code>
* is set to <i>false</i>.
* @param toSavedGame If <code>true</code> then information that
* is only needed when saving a game is added.
* @throws XMLStreamException if there are any problems writing
* to the stream.
*/
@Override
protected void toXMLImpl(XMLStreamWriter out, Player player, boolean showAll, boolean toSavedGame) throws XMLStreamException {
// Start element:
out.writeStartElement(getXMLElementTagName());
// Add attributes:
out.writeAttribute("ID", getId());
out.writeAttribute("colony", colony.getId());
out.writeAttribute("workTile", workTile.getId());
writeFreeColGameObject(unit, out, player, showAll, toSavedGame);
// End element:
out.writeEndElement();
}
/**
* Initialize this object from an XML-representation of this object.
* @param in The input stream with the XML.
* @throws XMLStreamException if a problem was encountered
* during parsing.
*/
@Override
protected void readFromXMLImpl(XMLStreamReader in) throws XMLStreamException {
setId(in.getAttributeValue(null, "ID"));
colony = getFreeColGameObject(in, "colony", Colony.class);
workTile = getFreeColGameObject(in, "workTile", Tile.class);
colonyCenterTile = (colony.getTile() == workTile);
unit = null;
while (in.nextTag() != XMLStreamConstants.END_ELEMENT) {
if (in.getLocalName().equals(Unit.getXMLElementTagName())) {
setUnit(updateFreeColGameObject(in, Unit.class));
}
}
}
/**
* Will return the position of the tile and the name of the colony in
* addition to the FreeColObject.toString().
*
* @return A representation of a colony-tile that can be used for debugging.
*/
@Override
public String toString() {
return "ColonyTile " + getWorkTile().getPosition().toString()
+ " in '" + getColony().getName() + "'";
}
/**
* Gets the tag name of the root element representing this object.
* @return "colonyTile".
*/
public static String getXMLElementTagName() {
return "colonyTile";
}
}
|
tectronics/reformationofeurope
|
src/net/sf/freecol/common/model/ColonyTile.java
|
Java
|
gpl-2.0
| 19,928
|
using System.Collections.Generic;
using meridian.smolensk.proto;
namespace smolensk.Models.ViewModels
{
public class AdsListViewModel
{
public string Title { get; set; }
public string NoAdsTitle { get; set; }
public IEnumerable<ad_advertisments> Advertisments { get; set; }
public int TotalPages { get; set; }
public int CurrentPage { get; set; }
public bool IsFavorite { get; set; }
public string RouteName { get; set; }
public AdsListViewModel()
{
NoAdsTitle = "Нет объявлений";
}
}
}
|
seavan/smoltoday
|
trunk/src/smolensk/Models/ViewModels/AdsListViewModel.cs
|
C#
|
gpl-2.0
| 631
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using Sdl.Core.Settings;
using SDLCommunityCleanUpTasks.Models;
namespace SDLCommunityCleanUpTasks
{
public class CleanUpSourceSettings : SettingsGroup, ICleanUpSourceSettings
{
#region TagSettingsControl
public Dictionary<string, bool> FormatTagList
{
get { return GetSetting<Dictionary<string, bool>>(nameof(FormatTagList)); }
set { GetSetting<Dictionary<string, bool>>(nameof(FormatTagList)).Value = value; }
}
public Dictionary<string, bool> PlaceholderTagList
{
get { return GetSetting<Dictionary<string, bool>>(nameof(PlaceholderTagList)); }
set { GetSetting<Dictionary<string, bool>>(nameof(PlaceholderTagList)).Value = value; }
}
public bool UseTagCleaner
{
get { return GetSetting<bool>(nameof(UseTagCleaner)); }
set { GetSetting<bool>(nameof(UseTagCleaner)).Value = value; }
}
#endregion TagSettingsControl
#region ConversionsSettingsControl
public bool ApplyToNonTranslatables
{
get { return GetSetting<bool>(nameof(ApplyToNonTranslatables)); }
set { GetSetting<bool>(nameof(ApplyToNonTranslatables)).Value = value; }
}
public Dictionary<string, bool> ConversionFiles
{
get { return GetSetting<Dictionary<string, bool>>(nameof(ConversionFiles)); }
set { GetSetting<Dictionary<string, bool>>(nameof(ConversionFiles)).Value = value; }
}
public string LastFileDirectory
{
get { return GetSetting<string>(nameof(LastFileDirectory)); }
set { GetSetting<string>(nameof(LastFileDirectory)).Value = value; }
}
public bool UseConversionSettings
{
get { return GetSetting<bool>(nameof(UseConversionSettings)); }
set { GetSetting<bool>(nameof(UseConversionSettings)).Value = value; }
}
#endregion ConversionsSettingsControl
#region SegmentLockerControl
public BindingList<SegmentLockItem> SegmentLockList
{
get { return GetSetting<BindingList<SegmentLockItem>>(nameof(SegmentLockList)); }
set { GetSetting<BindingList<SegmentLockItem>>(nameof(SegmentLockList)).Value = value; }
}
public List<ContextDef> StructureLockList
{
get { return GetSetting<List<ContextDef>>(nameof(StructureLockList)); }
set { GetSetting<List<ContextDef>>(nameof(StructureLockList)).Value = value; }
}
public bool UseContentLocker
{
get { return GetSetting<bool>(nameof(UseContentLocker)); }
set { GetSetting<bool>(nameof(UseContentLocker)).Value = value; }
}
public bool UseSegmentLocker
{
get { return GetSetting<bool>(nameof(UseSegmentLocker)); }
set { GetSetting<bool>(nameof(UseSegmentLocker)).Value = value; }
}
public bool UseStructureLocker
{
get { return GetSetting<bool>(nameof(UseStructureLocker)); }
set { GetSetting<bool>(nameof(UseStructureLocker)).Value = value; }
}
#endregion SegmentLockerControl
public ISettingsGroup Settings { get; set; }
public CultureInfo SourceCulture { get; set; }
public List<Placeholder> Placeholders
{
get { return GetSetting<List<Placeholder>>(nameof(Placeholders)); }
set { GetSetting<List<Placeholder>>(nameof(Placeholders)).Value = value; }
}
[SuppressMessage("Microsoft.Contracts", "TestAlwaysEvaluatingToAConstant")]
protected override object GetDefaultValue(string settingId)
{
switch (settingId)
{
case nameof(UseTagCleaner):
return true;
case nameof(UseConversionSettings):
return true;
case nameof(ApplyToNonTranslatables):
return false;
case nameof(FormatTagList):
return new Dictionary<string, bool>()
{
{ TagTable.BackgroundColor, false },
{ TagTable.Bold, false },
{ TagTable.FontName, false },
{ TagTable.FontSize, false },
{ TagTable.TextColor, false },
{ TagTable.Italic, false },
{ TagTable.TextDirection, false },
{ TagTable.TextPosition, false },
{ TagTable.Underline, false },
{ TagTable.Strikethrough, false }
};
case nameof(PlaceholderTagList):
return new Dictionary<string, bool>();
case nameof(ConversionFiles):
return new Dictionary<string, bool>();
case nameof(LastFileDirectory):
return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
case nameof(SegmentLockList):
return new BindingList<SegmentLockItem>(new List<SegmentLockItem>());
case nameof(UseSegmentLocker):
return true;
case nameof(UseStructureLocker):
return true;
case nameof(UseContentLocker):
return true;
case nameof(StructureLockList):
return new List<ContextDef>();
case nameof(Placeholders):
return new List<Placeholder>();
}
return base.GetDefaultValue(settingId);
}
}
}
|
sdl/Sdl-Community
|
CleanUpTasks/CleanUpTasks/CleanUpSourceSettings.cs
|
C#
|
gpl-2.0
| 5,910
|
<html lang="en">
<head>
<title>Porting libstdc++-v3</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Porting libstdc++-v3">
<meta name="generator" content="makeinfo 4.3">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home">
<!--
Copyright © 2000, 2001, 2002 Free Software Foundation, Inc.
<p>Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.2 or
any later version published by the Free Software Foundation; with the
Invariant Sections being "GNU General Public License", the Front-Cover
texts being (a) (see below), and with the Back-Cover Texts being (b)
(see below). A copy of the license is included in the section entitled
"GNU Free Documentation License".
<p>(a) The FSF's Front-Cover Text is:
<p>A GNU Manual
<p>(b) The FSF's Back-Cover Text is:
<p>You have freedom to copy and modify this GNU Manual, like GNU
software. Copies published by the Free Software Foundation raise
funds for GNU development.-->
</head>
<body>
<h1 class="settitle">Porting libstdc++-v3</h1>
<div class="node">
<p><hr>
Node:<a name="Top">Top</a>,
Next:<a rel="next" accesskey="n" href="#Operating%20system">Operating system</a>,
Up:<a rel="up" accesskey="u" href="#dir">(dir)</a>
<br>
</div>
<h2 class="unnumbered">Porting libstdc++-v3</h2>
<p>This document explains how to port libstdc++-v3 (the GNU C++ library) to
a new target.
<p>In order to make the GNU C++ library (libstdc++-v3) work with a new
target, you must edit some configuration files and provide some new
header files. Unless this is done, libstdc++-v3 will use generic
settings which may not be correct for your target; even if they are
correct, they will likely be inefficient.
<p>Before you get started, make sure that you have a working C library on
your target. The C library need not precisely comply with any
particular standard, but should generally conform to the requirements
imposed by the ANSI/ISO standard.
<p>In addition, you should try to verify that the C++ compiler generally
works. It is difficult to test the C++ compiler without a working
library, but you should at least try some minimal test cases.
<p>Here are the primary steps required to port the library:
<ul class="menu">
<li><a accesskey="1" href="#Operating%20system">Operating system</a>: Configuring for your operating system.
<li><a accesskey="2" href="#CPU">CPU</a>: Configuring for your processor chip.
<li><a accesskey="3" href="#Character%20types">Character types</a>: Implementing character classification.
<li><a accesskey="4" href="#Thread%20safety">Thread safety</a>: Implementing atomic operations.
<li><a accesskey="5" href="#Numeric%20limits">Numeric limits</a>: Implementing numeric limits.
<li><a accesskey="6" href="#Libtool">Libtool</a>: Using libtool.
<li><a accesskey="7" href="#GNU%20Free%20Documentation%20License">GNU Free Documentation License</a>: How you can copy and share this manual.
</ul>
<div class="node">
<p><hr>
Node:<a name="Operating%20system">Operating system</a>,
Next:<a rel="next" accesskey="n" href="#CPU">CPU</a>,
Previous:<a rel="previous" accesskey="p" href="#Top">Top</a>,
Up:<a rel="up" accesskey="u" href="#Top">Top</a>
<br>
</div>
<h2 class="chapter">Operating system</h2>
<p>If you are porting to a new operating system (as opposed to a new chip
using an existing operating system), you will need to create a new
directory in the <code>config/os</code> hierarchy. For example, the IRIX
configuration files are all in <code>config/os/irix</code>. There is no set
way to organize the OS configuration directory. For example,
<code>config/os/solaris/solaris-2.6</code> and
<code>config/os/solaris/solaris-2.7</code> are used as configuration
directories for these two versions of Solaris. On the other hand, both
Solaris 2.7 and Solaris 2.8 use the <code>config/os/solaris/solaris-2.7</code>
directory. The important information is that there needs to be a
directory under <code>config/os</code> to store the files for your operating
system.
<p>You might have to change the <code>configure.target</code> file to ensure that
your new directory is activated. Look for the switch statement that sets
<code>os_include_dir</code>, and add a pattern to handle your operating system
if the default will not suffice. The switch statement switches on only
the OS portion of the standard target triplet; e.g., the <code>solaris2.8</code>
in <code>sparc-sun-solaris2.8</code>. If the new directory is named after the
OS portion of the triplet (the default), then nothing needs to be changed.
<p>The first file to create in this directory, should be called
<code>os_defines.h</code>. This file contains basic macro definitions
that are required to allow the C++ library to work with your C library.
This file should provide macro definitions for <code>__off_t</code>,
<code>__off64_t</code>, and <code>__ssize_t</code>. Typically, this just looks
like:
<pre class="example"> #define __off_t off_t
#define __off64_t off64_t
#define __ssize_t ssize_t
</pre>
<p>You don't have to provide these definitions if your system library
already defines these types - but the only library known to provide
these types is the GNU C Library, so you will almost certainly have to
provide these macros. Note that this file does not have to include a
header file that defines <code>off_t</code>, or the other types; you simply
have to provide the macros.
<p>In addition, several libstdc++-v3 source files unconditionally define
the macro <code>_POSIX_SOURCE</code>. On many systems, defining this macro
causes large portions of the C library header files to be eliminated
at preprocessing time. Therefore, you may have to <code>#undef</code> this
macro, or define other macros (like <code>_LARGEFILE_SOURCE</code> or
<code>__EXTENSIONS__</code>). You won't know what macros to define or
undefine at this point; you'll have to try compiling the library and
seeing what goes wrong. If you see errors about calling functions
that have not been declared, look in your C library headers to see if
the functions are declared there, and then figure out what macros you
need to define. You will need to add them to the
<code>CPLUSPLUS_CPP_SPEC</code> macro in the GCC configuration file for your
target. It will not work to simply define these macros in
<code>os_defines.h</code>.
<p>At this time, there are a few libstdc++-v3-specific macro which may be
defined. <code>_G_USING_THUNKS</code> may be defined to 0 to express that the
port doesn't use thunks (although it is unclear that this is still
useful since libio support isn't currently working and the g++ v3 ABI
invalidates the assumption that some ports don't use thunks).
<p><code>_GLIBCPP_USE_C99_CHECK</code> may be defined to 1 to check C99
function declarations (which are not covered by specialization below)
found in system headers against versions found in the library headers
derived from the standard.
<p><code>_GLIBCPP_USE_C99_DYNAMIC</code> may be defined to an expression that
yields 0 if and only if the system headers are exposing proper support
for C99 functions (which are not covered by specialization below). If
defined, it must be 0 while bootstrapping the compiler/rebuilding the
library.
<p><code>_GLIBCPP_USE_C99_LONG_LONG_CHECK</code> may be defined to 1 to check
the set of C99 long long function declarations found in system headers
against versions found in the library headers derived from the
standard.
<p><code>_GLIBCPP_USE_C99_LONG_LONG_DYNAMIC</code> may be defined to an
expression that yields 0 if and only if the system headers are
exposing proper support for the set of C99 long long functions. If
defined, it must be 0 while bootstrapping the compiler/rebuilding the
library.
<p><code>_GLIBCPP_USE_C99_FP_MACROS_DYNAMIC</code> may be defined to an
expression that yields 0 if and only if the system headers
are exposing proper support for the related set of macros. If defined,
it must be 0 while bootstrapping the compiler/rebuilding the library.
<p><code>_GLIBCPP_USE_C99_FLOAT_TRANSCENDENTALS_CHECK</code> may be defined
to 1 to check the related set of function declarations found in system
headers against versions found in the library headers derived from
the standard.
<p><code>_GLIBCPP_USE_C99_FLOAT_TRANSCENDENTALS_DYNAMIC</code> may be defined
to an expression that yields 0 if and only if the system headers
are exposing proper support for the related set of functions. If defined,
it must be 0 while bootstrapping the compiler/rebuilding the library.
<p>Finally, you should bracket the entire file in an include-guard, like
this:
<pre class="example"> #ifndef _GLIBCPP_OS_DEFINES
#define _GLIBCPP_OS_DEFINES
...
#endif
</pre>
<p>We recommend copying an existing <code>os_defines.h</code> to use as a
starting point.
<div class="node">
<p><hr>
Node:<a name="CPU">CPU</a>,
Next:<a rel="next" accesskey="n" href="#Character%20types">Character types</a>,
Previous:<a rel="previous" accesskey="p" href="#Operating%20system">Operating system</a>,
Up:<a rel="up" accesskey="u" href="#Top">Top</a>
<br>
</div>
<h2 class="chapter">CPU</h2>
<p>If you are porting to a new chip (as opposed to a new operating system
running on an existing chip), you will need to create a new directory in the
<code>config/cpu</code> hierarchy. Much like the <a href="#Operating%20system">Operating system</a> setup,
there are no strict rules on how to organize the CPU configuration
directory, but careful naming choices will allow the configury to find your
setup files without explicit help.
<p>We recommend that for a target triplet <code><CPU>-<vendor>-<OS></code>, you
name your configuration directory <code>config/cpu/<CPU></code>. If you do this,
the configury will find the directory itself. Otherwise you will need to
edit the <code>configure.target</code> file and, in the switch statement that sets
<code>cpu_include_dir</code>, add a pattern to handle your chip.
<p>Note that some chip families share a single configuration directory, for
example, <code>alpha</code>, <code>alphaev5</code>, and <code>alphaev6</code> all use the
<code>config/cpu/alpha</code> directory, and there is an entry in the
<code>configure.target</code> switch statement to handle this.
<p>The <code>cpu_include_dir</code> sets default locations for the files controlling
<a href="#Thread%20safety">Thread safety</a> and <a href="#Numeric%20limits">Numeric limits</a>, if the defaults are not
appropriate for your chip.
<div class="node">
<p><hr>
Node:<a name="Character%20types">Character types</a>,
Next:<a rel="next" accesskey="n" href="#Thread%20safety">Thread safety</a>,
Previous:<a rel="previous" accesskey="p" href="#CPU">CPU</a>,
Up:<a rel="up" accesskey="u" href="#Top">Top</a>
<br>
</div>
<h2 class="chapter">Character types</h2>
<p>The library requires that you provide three header files to implement
character classification, analogous to that provided by the C libraries
<code><ctype.h></code> header. You can model these on the files provided in
<code>config/os/generic</code>. However, these files will almost
certainly need some modification.
<p>The first file to write is <code>ctype_base.h</code>. This file provides
some very basic information about character classification. The libstdc++-v3
library assumes that your C library implements <code><ctype.h></code> by using
a table (indexed by character code) containing integers, where each of
these integers is a bit-mask indicating whether the character is
upper-case, lower-case, alphabetic, etc. The <code>ctype_base.h</code>
file gives the type of the integer, and the values of the various bit
masks. You will have to peer at your own <code><ctype.h></code> to figure out
how to define the values required by this file.
<p>The <code>ctype_base.h</code> header file does not need include guards.
It should contain a single <code>struct</code> definition called
<code>ctype_base</code>. This <code>struct</code> should contain two type
declarations, and one enumeration declaration, like this example, taken
from the IRIX configuration:
<pre class="example"> struct ctype_base
{
typedef unsigned int mask;
typedef int* __to_type;
enum
{
space = _ISspace,
print = _ISprint,
cntrl = _IScntrl,
upper = _ISupper,
lower = _ISlower,
alpha = _ISalpha,
digit = _ISdigit,
punct = _ISpunct,
xdigit = _ISxdigit,
alnum = _ISalnum,
graph = _ISgraph
};
};
</pre>
<p>The <code>mask</code> type is the type of the elements in the table. If your
C library uses a table to map lower-case numbers to upper-case numbers,
and vice versa, you should define <code>__to_type</code> to be the type of the
elements in that table. If you don't mind taking a minor performance
penalty, or if your library doesn't implement <code>toupper</code> and
<code>tolower</code> in this way, you can pick any pointer-to-integer type,
but you must still define the type.
<p>The enumeration should give definitions for all the values in the above
example, using the values from your native <code><ctype.h></code>. They can
be given symbolically (as above), or numerically, if you prefer. You do
not have to include <code><ctype.h></code> in this header; it will always be
included before <code>ctype_base.h</code> is included.
<p>The next file to write is <code>ctype_noninline.h</code>, which also does
not require include guards. This file defines a few member functions
that will be included in <code>include/bits/locale_facets.h</code>. The first
function that must be written is the <code>ctype<char>::ctype</code>
constructor. Here is the IRIX example:
<pre class="example"> ctype<char>::ctype(const mask* __table = 0, bool __del = false,
size_t __refs = 0)
: _Ctype_nois<char>(__refs), _M_del(__table != 0 && __del),
_M_toupper(NULL),
_M_tolower(NULL),
_M_ctable(NULL),
_M_table(!__table
? (const mask*) (__libc_attr._ctype_tbl->_class + 1)
: __table)
{ }
</pre>
<p>There are two parts of this that you might choose to alter. The first,
and most important, is the line involving <code>__libc_attr</code>. That is
IRIX system-dependent code that gets the base of the table mapping
character codes to attributes. You need to substitute code that obtains
the address of this table on your system. If you want to use your
operating system's tables to map upper-case letters to lower-case, and
vice versa, you should initialize <code>_M_toupper</code> and
<code>_M_tolower</code> with those tables, in similar fashion.
<p>Now, you have to write two functions to convert from upper-case to
lower-case, and vice versa. Here are the IRIX versions:
<pre class="example"> char
ctype<char>::do_toupper(char __c) const
{ return _toupper(__c); }
char
ctype<char>::do_tolower(char __c) const
{ return _tolower(__c); }
</pre>
<p>Your C library provides equivalents to IRIX's <code>_toupper</code> and
<code>_tolower</code>. If you initialized <code>_M_toupper</code> and
<code>_M_tolower</code> above, then you could use those tables instead.
<p>Finally, you have to provide two utility functions that convert strings
of characters. The versions provided here will always work - but you
could use specialized routines for greater performance if you have
machinery to do that on your system:
<pre class="example"> const char*
ctype<char>::do_toupper(char* __low, const char* __high) const
{
while (__low < __high)
{
*__low = do_toupper(*__low);
++__low;
}
return __high;
}
const char*
ctype<char>::do_tolower(char* __low, const char* __high) const
{
while (__low < __high)
{
*__low = do_tolower(*__low);
++__low;
}
return __high;
}
</pre>
<p>You must also provide the <code>ctype_inline.h</code> file, which
contains a few more functions. On most systems, you can just copy
<code>config/os/generic/ctype_inline.h</code> and use it on your system.
<p>In detail, the functions provided test characters for particular
properties; they are analogous to the functions like <code>isalpha</code> and
<code>islower</code> provided by the C library.
<p>The first function is implemented like this on IRIX:
<pre class="example"> bool
ctype<char>::
is(mask __m, char __c) const throw()
{ return (_M_table)[(unsigned char)(__c)] & __m; }
</pre>
<p>The <code>_M_table</code> is the table passed in above, in the constructor.
This is the table that contains the bitmasks for each character. The
implementation here should work on all systems.
<p>The next function is:
<pre class="example"> const char*
ctype<char>::
is(const char* __low, const char* __high, mask* __vec) const throw()
{
while (__low < __high)
*__vec++ = (_M_table)[(unsigned char)(*__low++)];
return __high;
}
</pre>
<p>This function is similar; it copies the masks for all the characters
from <code>__low</code> up until <code>__high</code> into the vector given by
<code>__vec</code>.
<p>The last two functions again are entirely generic:
<pre class="example"> const char*
ctype<char>::
scan_is(mask __m, const char* __low, const char* __high) const throw()
{
while (__low < __high && !this->is(__m, *__low))
++__low;
return __low;
}
const char*
ctype<char>::
scan_not(mask __m, const char* __low, const char* __high) const throw()
{
while (__low < __high && this->is(__m, *__low))
++__low;
return __low;
}
</pre>
<div class="node">
<p><hr>
Node:<a name="Thread%20safety">Thread safety</a>,
Next:<a rel="next" accesskey="n" href="#Numeric%20limits">Numeric limits</a>,
Previous:<a rel="previous" accesskey="p" href="#Character%20types">Character types</a>,
Up:<a rel="up" accesskey="u" href="#Top">Top</a>
<br>
</div>
<h2 class="chapter">Thread safety</h2>
<p>The C++ library string functionality requires a couple of atomic
operations to provide thread-safety. If you don't take any special
action, the library will use stub versions of these functions that are
not thread-safe. They will work fine, unless your applications are
multi-threaded.
<p>If you want to provide custom, safe, versions of these functions, there
are two distinct approaches. One is to provide a version for your CPU,
using assembly language constructs. The other is to use the
thread-safety primitives in your operating system. In either case, you
make a file called <code>atomicity.h</code>, and the variable
<code>ATOMICITYH</code> must point to this file.
<p>If you are using the assembly-language approach, put this code in
<code>config/cpu/<chip>/atomicity.h</code>, where chip is the name of
your processor (see <a href="#CPU">CPU</a>). No additional changes are necessary to
locate the file in this case; <code>ATOMICITYH</code> will be set by default.
<p>If you are using the operating system thread-safety primitives approach,
you can also put this code in the same CPU directory, in which case no more
work is needed to locate the file. For examples of this approach,
see the <code>atomicity.h</code> file for IRIX or IA64.
<p>Alternatively, if the primitives are more closely related to the OS
than they are to the CPU, you can put the <code>atomicity.h</code> file in
the <a href="#Operating%20system">Operating system</a> directory instead. In this case, you must
edit <code>configure.target</code>, and in the switch statement that handles
operating systems, override the <code>ATOMICITYH</code> variable to point to
the appropriate <code>os_include_dir</code>. For examples of this approach,
see the <code>atomicity.h</code> file for AIX.
<p>With those bits out of the way, you have to actually write
<code>atomicity.h</code> itself. This file should be wrapped in an
include guard named <code>_BITS_ATOMICITY_H</code>. It should define one
type, and two functions.
<p>The type is <code>_Atomic_word</code>. Here is the version used on IRIX:
<pre class="example"> typedef long _Atomic_word;
</pre>
<p>This type must be a signed integral type supporting atomic operations.
If you're using the OS approach, use the same type used by your system's
primitives. Otherwise, use the type for which your CPU provides atomic
primitives.
<p>Then, you must provide two functions. The bodies of these functions
must be equivalent to those provided here, but using atomic operations:
<pre class="example"> static inline _Atomic_word
__attribute__ ((__unused__))
__exchange_and_add (_Atomic_word* __mem, int __val)
{
_Atomic_word __result = *__mem;
*__mem += __val;
return __result;
}
static inline void
__attribute__ ((__unused__))
__atomic_add (_Atomic_word* __mem, int __val)
{
*__mem += __val;
}
</pre>
<div class="node">
<p><hr>
Node:<a name="Numeric%20limits">Numeric limits</a>,
Next:<a rel="next" accesskey="n" href="#Libtool">Libtool</a>,
Previous:<a rel="previous" accesskey="p" href="#Thread%20safety">Thread safety</a>,
Up:<a rel="up" accesskey="u" href="#Top">Top</a>
<br>
</div>
<h2 class="chapter">Numeric limits</h2>
<p>The C++ library requires information about the fundamental data types,
such as the minimum and maximum representable values of each type.
You can define each of these values individually, but it is usually
easiest just to indicate how many bits are used in each of the data
types and let the library do the rest. For information about the
macros to define, see the top of <code>include/bits/std_limits.h</code>.
<p>If you need to define any macros, you can do so in <code>os_defines.h</code>.
However, if all operating systems for your CPU are likely to use the
same values, you can provide a CPU-specific file instead so that you
do not have to provide the same definitions for each operating system.
To take that approach, create a new file called <code>cpu_limits.h</code> in
your CPU configuration directory (see <a href="#CPU">CPU</a>).
<div class="node">
<p><hr>
Node:<a name="Libtool">Libtool</a>,
Next:<a rel="next" accesskey="n" href="#GNU%20Free%20Documentation%20License">GNU Free Documentation License</a>,
Previous:<a rel="previous" accesskey="p" href="#Numeric%20limits">Numeric limits</a>,
Up:<a rel="up" accesskey="u" href="#Top">Top</a>
<br>
</div>
<h2 class="chapter">Libtool</h2>
<p>The C++ library is compiled, archived and linked with libtool.
Explaining the full workings of libtool is beyond the scope of this
document, but there are a few, particular bits that are necessary for
porting.
<p>Some parts of the libstdc++-v3 library are compiled with the libtool
<code>--tags CXX</code> option (the C++ definitions for libtool). Therefore,
<code>ltcf-cxx.sh</code> in the top-level directory needs to have the correct
logic to compile and archive objects equivalent to the C version of libtool,
<code>ltcf-c.sh</code>. Some libtool targets have definitions for C but not
for C++, or C++ definitions which have not been kept up to date.
<p>The C++ run-time library contains initialization code that needs to be
run as the library is loaded. Often, that requires linking in special
object files when the C++ library is built as a shared library, or
taking other system-specific actions.
<p>The libstdc++-v3 library is linked with the C version of libtool, even
though it is a C++ library. Therefore, the C version of libtool needs to
ensure that the run-time library initializers are run. The usual way to
do this is to build the library using <code>gcc -shared</code>.
<p>If you need to change how the library is linked, look at
<code>ltcf-c.sh</code> in the top-level directory. Find the switch statement
that sets <code>archive_cmds</code>. Here, adjust the setting for your
operating system.
<div class="node">
<p><hr>
Node:<a name="GNU%20Free%20Documentation%20License">GNU Free Documentation License</a>,
Previous:<a rel="previous" accesskey="p" href="#Libtool">Libtool</a>,
Up:<a rel="up" accesskey="u" href="#Top">Top</a>
<br>
</div>
<h2 class="unnumbered">GNU Free Documentation License</h2>
<div align="center">Version 1.2, November 2002</div>
<pre class="display"> Copyright © 2000,2001,2002 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
</pre>
<ol type=1 start=0>
<li>PREAMBLE
<p>The purpose of this License is to make a manual, textbook, or other
functional and useful document <dfn>free</dfn> in the sense of freedom: to
assure everyone the effective freedom to copy and redistribute it,
with or without modifying it, either commercially or noncommercially.
Secondarily, this License preserves for the author and publisher a way
to get credit for their work, while not being considered responsible
for modifications made by others.
<p>This License is a kind of "copyleft", which means that derivative
works of the document must themselves be free in the same sense. It
complements the GNU General Public License, which is a copyleft
license designed for free software.
<p>We have designed this License in order to use it for manuals for free
software, because free software needs free documentation: a free
program should come with manuals providing the same freedoms that the
software does. But this License is not limited to software manuals;
it can be used for any textual work, regardless of subject matter or
whether it is published as a printed book. We recommend this License
principally for works whose purpose is instruction or reference.
</p><li>APPLICABILITY AND DEFINITIONS
<p>This License applies to any manual or other work, in any medium, that
contains a notice placed by the copyright holder saying it can be
distributed under the terms of this License. Such a notice grants a
world-wide, royalty-free license, unlimited in duration, to use that
work under the conditions stated herein. The "Document", below,
refers to any such manual or work. Any member of the public is a
licensee, and is addressed as "you". You accept the license if you
copy, modify or distribute the work in a way requiring permission
under copyright law.
<p>A "Modified Version" of the Document means any work containing the
Document or a portion of it, either copied verbatim, or with
modifications and/or translated into another language.
<p>A "Secondary Section" is a named appendix or a front-matter section
of the Document that deals exclusively with the relationship of the
publishers or authors of the Document to the Document's overall
subject (or to related matters) and contains nothing that could fall
directly within that overall subject. (Thus, if the Document is in
part a textbook of mathematics, a Secondary Section may not explain
any mathematics.) The relationship could be a matter of historical
connection with the subject or with related matters, or of legal,
commercial, philosophical, ethical or political position regarding
them.
<p>The "Invariant Sections" are certain Secondary Sections whose titles
are designated, as being those of Invariant Sections, in the notice
that says that the Document is released under this License. If a
section does not fit the above definition of Secondary then it is not
allowed to be designated as Invariant. The Document may contain zero
Invariant Sections. If the Document does not identify any Invariant
Sections then there are none.
<p>The "Cover Texts" are certain short passages of text that are listed,
as Front-Cover Texts or Back-Cover Texts, in the notice that says that
the Document is released under this License. A Front-Cover Text may
be at most 5 words, and a Back-Cover Text may be at most 25 words.
<p>A "Transparent" copy of the Document means a machine-readable copy,
represented in a format whose specification is available to the
general public, that is suitable for revising the document
straightforwardly with generic text editors or (for images composed of
pixels) generic paint programs or (for drawings) some widely available
drawing editor, and that is suitable for input to text formatters or
for automatic translation to a variety of formats suitable for input
to text formatters. A copy made in an otherwise Transparent file
format whose markup, or absence of markup, has been arranged to thwart
or discourage subsequent modification by readers is not Transparent.
An image format is not Transparent if used for any substantial amount
of text. A copy that is not "Transparent" is called "Opaque".
<p>Examples of suitable formats for Transparent copies include plain
<small>ASCII</small> without markup, Texinfo input format, LaTeX input
format, <small>SGML</small> or <small>XML</small> using a publicly available
<small>DTD</small>, and standard-conforming simple <small>HTML</small>,
PostScript or <small>PDF</small> designed for human modification. Examples
of transparent image formats include <small>PNG</small>, <small>XCF</small> and
<small>JPG</small>. Opaque formats include proprietary formats that can be
read and edited only by proprietary word processors, <small>SGML</small> or
<small>XML</small> for which the <small>DTD</small> and/or processing tools are
not generally available, and the machine-generated <small>HTML</small>,
PostScript or <small>PDF</small> produced by some word processors for
output purposes only.
<p>The "Title Page" means, for a printed book, the title page itself,
plus such following pages as are needed to hold, legibly, the material
this License requires to appear in the title page. For works in
formats which do not have any title page as such, "Title Page" means
the text near the most prominent appearance of the work's title,
preceding the beginning of the body of the text.
<p>A section "Entitled XYZ" means a named subunit of the Document whose
title either is precisely XYZ or contains XYZ in parentheses following
text that translates XYZ in another language. (Here XYZ stands for a
specific section name mentioned below, such as "Acknowledgements",
"Dedications", "Endorsements", or "History".) To "Preserve the Title"
of such a section when you modify the Document means that it remains a
section "Entitled XYZ" according to this definition.
<p>The Document may include Warranty Disclaimers next to the notice which
states that this License applies to the Document. These Warranty
Disclaimers are considered to be included by reference in this
License, but only as regards disclaiming warranties: any other
implication that these Warranty Disclaimers may have is void and has
no effect on the meaning of this License.
</p><li>VERBATIM COPYING
<p>You may copy and distribute the Document in any medium, either
commercially or noncommercially, provided that this License, the
copyright notices, and the license notice saying this License applies
to the Document are reproduced in all copies, and that you add no other
conditions whatsoever to those of this License. You may not use
technical measures to obstruct or control the reading or further
copying of the copies you make or distribute. However, you may accept
compensation in exchange for copies. If you distribute a large enough
number of copies you must also follow the conditions in section 3.
<p>You may also lend copies, under the same conditions stated above, and
you may publicly display copies.
</p><li>COPYING IN QUANTITY
<p>If you publish printed copies (or copies in media that commonly have
printed covers) of the Document, numbering more than 100, and the
Document's license notice requires Cover Texts, you must enclose the
copies in covers that carry, clearly and legibly, all these Cover
Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
the back cover. Both covers must also clearly and legibly identify
you as the publisher of these copies. The front cover must present
the full title with all words of the title equally prominent and
visible. You may add other material on the covers in addition.
Copying with changes limited to the covers, as long as they preserve
the title of the Document and satisfy these conditions, can be treated
as verbatim copying in other respects.
<p>If the required texts for either cover are too voluminous to fit
legibly, you should put the first ones listed (as many as fit
reasonably) on the actual cover, and continue the rest onto adjacent
pages.
<p>If you publish or distribute Opaque copies of the Document numbering
more than 100, you must either include a machine-readable Transparent
copy along with each Opaque copy, or state in or with each Opaque copy
a computer-network location from which the general network-using
public has access to download using public-standard network protocols
a complete Transparent copy of the Document, free of added material.
If you use the latter option, you must take reasonably prudent steps,
when you begin distribution of Opaque copies in quantity, to ensure
that this Transparent copy will remain thus accessible at the stated
location until at least one year after the last time you distribute an
Opaque copy (directly or through your agents or retailers) of that
edition to the public.
<p>It is requested, but not required, that you contact the authors of the
Document well before redistributing any large number of copies, to give
them a chance to provide you with an updated version of the Document.
</p><li>MODIFICATIONS
<p>You may copy and distribute a Modified Version of the Document under
the conditions of sections 2 and 3 above, provided that you release
the Modified Version under precisely this License, with the Modified
Version filling the role of the Document, thus licensing distribution
and modification of the Modified Version to whoever possesses a copy
of it. In addition, you must do these things in the Modified Version:
<ol type=A start=1>
<li>Use in the Title Page (and on the covers, if any) a title distinct
from that of the Document, and from those of previous versions
(which should, if there were any, be listed in the History section
of the Document). You may use the same title as a previous version
if the original publisher of that version gives permission.
<li>List on the Title Page, as authors, one or more persons or entities
responsible for authorship of the modifications in the Modified
Version, together with at least five of the principal authors of the
Document (all of its principal authors, if it has fewer than five),
unless they release you from this requirement.
<li>State on the Title page the name of the publisher of the
Modified Version, as the publisher.
<li>Preserve all the copyright notices of the Document.
<li>Add an appropriate copyright notice for your modifications
adjacent to the other copyright notices.
<li>Include, immediately after the copyright notices, a license notice
giving the public permission to use the Modified Version under the
terms of this License, in the form shown in the Addendum below.
<li>Preserve in that license notice the full lists of Invariant Sections
and required Cover Texts given in the Document's license notice.
<li>Include an unaltered copy of this License.
<li>Preserve the section Entitled "History", Preserve its Title, and add
to it an item stating at least the title, year, new authors, and
publisher of the Modified Version as given on the Title Page. If
there is no section Entitled "History" in the Document, create one
stating the title, year, authors, and publisher of the Document as
given on its Title Page, then add an item describing the Modified
Version as stated in the previous sentence.
<li>Preserve the network location, if any, given in the Document for
public access to a Transparent copy of the Document, and likewise
the network locations given in the Document for previous versions
it was based on. These may be placed in the "History" section.
You may omit a network location for a work that was published at
least four years before the Document itself, or if the original
publisher of the version it refers to gives permission.
<li>For any section Entitled "Acknowledgements" or "Dedications", Preserve
the Title of the section, and preserve in the section all the
substance and tone of each of the contributor acknowledgements and/or
dedications given therein.
<li>Preserve all the Invariant Sections of the Document,
unaltered in their text and in their titles. Section numbers
or the equivalent are not considered part of the section titles.
<li>Delete any section Entitled "Endorsements". Such a section
may not be included in the Modified Version.
<li>Do not retitle any existing section to be Entitled "Endorsements" or
to conflict in title with any Invariant Section.
<li>Preserve any Warranty Disclaimers.
</ol>
<p>If the Modified Version includes new front-matter sections or
appendices that qualify as Secondary Sections and contain no material
copied from the Document, you may at your option designate some or all
of these sections as invariant. To do this, add their titles to the
list of Invariant Sections in the Modified Version's license notice.
These titles must be distinct from any other section titles.
<p>You may add a section Entitled "Endorsements", provided it contains
nothing but endorsements of your Modified Version by various
parties--for example, statements of peer review or that the text has
been approved by an organization as the authoritative definition of a
standard.
<p>You may add a passage of up to five words as a Front-Cover Text, and a
passage of up to 25 words as a Back-Cover Text, to the end of the list
of Cover Texts in the Modified Version. Only one passage of
Front-Cover Text and one of Back-Cover Text may be added by (or
through arrangements made by) any one entity. If the Document already
includes a cover text for the same cover, previously added by you or
by arrangement made by the same entity you are acting on behalf of,
you may not add another; but you may replace the old one, on explicit
permission from the previous publisher that added the old one.
<p>The author(s) and publisher(s) of the Document do not by this License
give permission to use their names for publicity for or to assert or
imply endorsement of any Modified Version.
</p><li>COMBINING DOCUMENTS
<p>You may combine the Document with other documents released under this
License, under the terms defined in section 4 above for modified
versions, provided that you include in the combination all of the
Invariant Sections of all of the original documents, unmodified, and
list them all as Invariant Sections of your combined work in its
license notice, and that you preserve all their Warranty Disclaimers.
<p>The combined work need only contain one copy of this License, and
multiple identical Invariant Sections may be replaced with a single
copy. If there are multiple Invariant Sections with the same name but
different contents, make the title of each such section unique by
adding at the end of it, in parentheses, the name of the original
author or publisher of that section if known, or else a unique number.
Make the same adjustment to the section titles in the list of
Invariant Sections in the license notice of the combined work.
<p>In the combination, you must combine any sections Entitled "History"
in the various original documents, forming one section Entitled
"History"; likewise combine any sections Entitled "Acknowledgements",
and any sections Entitled "Dedications". You must delete all
sections Entitled "Endorsements."
</p><li>COLLECTIONS OF DOCUMENTS
<p>You may make a collection consisting of the Document and other documents
released under this License, and replace the individual copies of this
License in the various documents with a single copy that is included in
the collection, provided that you follow the rules of this License for
verbatim copying of each of the documents in all other respects.
<p>You may extract a single document from such a collection, and distribute
it individually under this License, provided you insert a copy of this
License into the extracted document, and follow this License in all
other respects regarding verbatim copying of that document.
</p><li>AGGREGATION WITH INDEPENDENT WORKS
<p>A compilation of the Document or its derivatives with other separate
and independent documents or works, in or on a volume of a storage or
distribution medium, is called an "aggregate" if the copyright
resulting from the compilation is not used to limit the legal rights
of the compilation's users beyond what the individual works permit.
When the Document is included an aggregate, this License does not
apply to the other works in the aggregate which are not themselves
derivative works of the Document.
<p>If the Cover Text requirement of section 3 is applicable to these
copies of the Document, then if the Document is less than one half of
the entire aggregate, the Document's Cover Texts may be placed on
covers that bracket the Document within the aggregate, or the
electronic equivalent of covers if the Document is in electronic form.
Otherwise they must appear on printed covers that bracket the whole
aggregate.
</p><li>TRANSLATION
<p>Translation is considered a kind of modification, so you may
distribute translations of the Document under the terms of section 4.
Replacing Invariant Sections with translations requires special
permission from their copyright holders, but you may include
translations of some or all Invariant Sections in addition to the
original versions of these Invariant Sections. You may include a
translation of this License, and all the license notices in the
Document, and any Warrany Disclaimers, provided that you also include
the original English version of this License and the original versions
of those notices and disclaimers. In case of a disagreement between
the translation and the original version of this License or a notice
or disclaimer, the original version will prevail.
<p>If a section in the Document is Entitled "Acknowledgements",
"Dedications", or "History", the requirement (section 4) to Preserve
its Title (section 1) will typically require changing the actual
title.
</p><li>TERMINATION
<p>You may not copy, modify, sublicense, or distribute the Document except
as expressly provided for under this License. Any other attempt to
copy, modify, sublicense or distribute the Document is void, and will
automatically terminate your rights under this License. However,
parties who have received copies, or rights, from you under this
License will not have their licenses terminated so long as such
parties remain in full compliance.
</p><li>FUTURE REVISIONS OF THIS LICENSE
<p>The Free Software Foundation may publish new, revised versions
of the GNU Free Documentation License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns. See
<a href="http://www.gnu.org/copyleft/">http://www.gnu.org/copyleft/</a>.
<p>Each version of the License is given a distinguishing version number.
If the Document specifies that a particular numbered version of this
License "or any later version" applies to it, you have the option of
following the terms and conditions either of that specified version or
of any later version that has been published (not as a draft) by the
Free Software Foundation. If the Document does not specify a version
number of this License, you may choose any version ever published (not
as a draft) by the Free Software Foundation.
</ol>
<h3 class="unnumberedsec">ADDENDUM: How to use this License for your documents</h3>
<p>To use this License in a document you have written, include a copy of
the License in the document and put the following copyright and
license notices just after the title page:
<pre class="smallexample"> Copyright (C) <var>year</var> <var>your name</var>.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.2
or any later version published by the Free Software Foundation;
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
A copy of the license is included in the section entitled ``GNU
Free Documentation License''.
</pre>
<p>If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
replace the "with...Texts." line with this:
<pre class="smallexample"> with the Invariant Sections being <var>list their titles</var>, with
the Front-Cover Texts being <var>list</var>, and with the Back-Cover Texts
being <var>list</var>.
</pre>
<p>If you have Invariant Sections without Cover Texts, or some other
combination of the three, merge those two alternatives to suit the
situation.
<p>If your document contains nontrivial examples of program code, we
recommend releasing these examples in parallel under your choice of
free software license, such as the GNU General Public License,
to permit their use in free software.
<div class="contents">
<h2>Table of Contents</h2>
<ul>
<li><a name="toc_Top" href="#Top">Porting libstdc++-v3</a>
<li><a name="toc_Operating%20system" href="#Operating%20system">Operating system</a>
<li><a name="toc_CPU" href="#CPU">CPU</a>
<li><a name="toc_Character%20types" href="#Character%20types">Character types</a>
<li><a name="toc_Thread%20safety" href="#Thread%20safety">Thread safety</a>
<li><a name="toc_Numeric%20limits" href="#Numeric%20limits">Numeric limits</a>
<li><a name="toc_Libtool" href="#Libtool">Libtool</a>
<li><a name="toc_GNU%20Free%20Documentation%20License" href="#GNU%20Free%20Documentation%20License">GNU Free Documentation License</a>
<ul>
<li><a href="#GNU%20Free%20Documentation%20License">ADDENDUM: How to use this License for your documents</a>
</li></ul>
</li></ul>
</div>
</body></html>
|
myri/lanai-gcc
|
libstdc++-v3/docs/html/17_intro/porting.html
|
HTML
|
gpl-2.0
| 47,245
|
#! /usr/bin/python
######
# Copyright 2007-2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 16 Network Circle, Menlo
# Park, CA 94025 or visit www.sun.com if you need additional
# information or have any questions.
#####
import os
import cPickle as C
import pyaura.bridge as B
from pyaura.lib import j2py
DATA_PREFIX= "out500k"
class SimpleStats():
"""
Generate simple statistics and plots for a set of tags.
"""
def __init__(self, prefix=DATA_PREFIX, regHost="brannigan"):
self.tags = C.load(open(os.path.join(prefix, "alltags.dump")))
self._dataFileCache = DataFileCache(prefix, self.tags)
self._is_plot_init = False
if regHost!=None:
self._aB = B.AuraBridge(regHost=regHost)
else:
self._aB = None
def _init_plotting(self, backend="MacOSX"):
if not self._is_plot_init:
self._is_plot_init = True
import matplotlib as M
M.use(backend)
def plot_taglen_hist(self):
self._init_plotting()
import pylab
tag_len = [len(x) for x in self.tags.keys() ]
pylab.hist(tag_len)
def plot_tagpop_itemcnt(self, itemtype="a"):
"""
Tag the histogram of the number of tagged items for each tag
"""
self._init_plotting()
import pylab
itemcnt = [x.get_itemcount(itemtype) for x in self.tags.values()]
pylab.hist(itemcnt, bins=1000)
def plot_tagpop_appcnt(self, itemtype="a"):
"""
Tag the histogram of application counts for each tag
"""
self._init_plotting()
import pylab
appcnt = [x.get_totals(itemtype) for x in self.tags.values()]
pylab.hist(appcnt, bins=1000)
def get_average_len(self):
w_running_tot=0
running_tot=0
tot_cnt=0
nbr_cnt=0
for t in self.tags.values():
w_running_tot+=len(t.name)*t.totals['artist']
running_tot+=len(t.name)
tot_cnt+=t.totals['artist']
nbr_cnt+=1
print "Weighted avg:\t%0.4f" % (float(w_running_tot)/tot_cnt)
print "Avg:\t\t%0.4f" % (float(running_tot)/nbr_cnt)
def find_most_co_ocurr(self, tagname, n=10):
vals = {}
for t in self.tags:
vals[t] = self.co_ocurr(tagname, t)
return sorted(vals.items(), key=lambda (k,v): (v,k), reverse=True)
def find_similar(self, tagname, n=10):
return j2py( self._aB.mdb.find_similar_rawtags(tagname, n) )
def co_ocurr(self, tagname1, tagname2):
"""
Get relative co-occurence (Jaccard coefficient)
"""
tagdata1 = self._dataFileCache.get(tagname1)
tagdata2 = self._dataFileCache.get(tagname2)
kt1 = frozenset(tagdata1['artist'].keys())
kt2 = frozenset(tagdata2['artist'].keys())
return float(len(kt1.intersection(kt2))) / len(kt1.union(kt2))
class DataFileCache():
def __init__(self, prefix, taginfo):
self._prefix = prefix
self._taginfo = taginfo
self._datafiles = {}
def get(self, tagname):
if tagname not in self._taginfo:
raise KeyError("Tag '%s' is not in the db" % tagname)
file_id = self._taginfo[tagname].file_location
if not file_id in self._datafiles:
print " > Loading datafile %s" % file_id
path = os.path.join(self._prefix, "tagcut-%s.tagdata.dump" % file_id)
self._datafiles[file_id] = C.load(open(path))
return self._datafiles[file_id][tagname]
|
SunLabsAST/AURA
|
Bridge/pyaura/tagclustering/simplestats.py
|
Python
|
gpl-2.0
| 4,439
|
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl.keyguard;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.IRemoteControlDisplay;
import android.media.MediaMetadataRetriever;
import android.media.RemoteControlClient;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.RemoteException;
import android.os.SystemClock;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.internal.R;
import java.lang.ref.WeakReference;
/**
* This is the widget responsible for showing music controls in keyguard.
*/
public class KeyguardTransportControlView extends FrameLayout implements OnClickListener {
private static final int MSG_UPDATE_STATE = 100;
private static final int MSG_SET_METADATA = 101;
private static final int MSG_SET_TRANSPORT_CONTROLS = 102;
private static final int MSG_SET_ARTWORK = 103;
private static final int MSG_SET_GENERATION_ID = 104;
private static final int DISPLAY_TIMEOUT_MS = 5000; // 5s
protected static final boolean DEBUG = false;
protected static final String TAG = "TransportControlView";
private ImageView mAlbumArt;
private TextView mTrackTitle;
private ImageView mBtnPrev;
private ImageView mBtnPlay;
private ImageView mBtnNext;
private int mClientGeneration;
private Metadata mMetadata = new Metadata();
private boolean mAttached;
private PendingIntent mClientIntent;
private int mTransportControlFlags;
private int mCurrentPlayState;
private AudioManager mAudioManager;
private IRemoteControlDisplayWeak mIRCD;
private boolean mMusicClientPresent = true;
/**
* The metadata which should be populated into the view once we've been attached
*/
private Bundle mPopulateMetadataWhenAttached = null;
// This handler is required to ensure messages from IRCD are handled in sequence and on
// the UI thread.
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_UPDATE_STATE:
if (mClientGeneration == msg.arg1) updatePlayPauseState(msg.arg2);
break;
case MSG_SET_METADATA:
if (mClientGeneration == msg.arg1) updateMetadata((Bundle) msg.obj);
break;
case MSG_SET_TRANSPORT_CONTROLS:
if (mClientGeneration == msg.arg1) updateTransportControls(msg.arg2);
break;
case MSG_SET_ARTWORK:
if (mClientGeneration == msg.arg1) {
if (mMetadata.bitmap != null) {
mMetadata.bitmap.recycle();
}
mMetadata.bitmap = (Bitmap) msg.obj;
mAlbumArt.setImageBitmap(mMetadata.bitmap);
}
break;
case MSG_SET_GENERATION_ID:
if (msg.arg2 != 0) {
// This means nobody is currently registered. Hide the view.
onListenerDetached();
} else {
onListenerAttached();
}
if (DEBUG) Log.v(TAG, "New genId = " + msg.arg1 + ", clearing = " + msg.arg2);
mClientGeneration = msg.arg1;
mClientIntent = (PendingIntent) msg.obj;
break;
}
}
};
private KeyguardHostView.TransportCallback mTransportCallback;
/**
* This class is required to have weak linkage to the current TransportControlView
* because the remote process can hold a strong reference to this binder object and
* we can't predict when it will be GC'd in the remote process. Without this code, it
* would allow a heavyweight object to be held on this side of the binder when there's
* no requirement to run a GC on the other side.
*/
private static class IRemoteControlDisplayWeak extends IRemoteControlDisplay.Stub {
private WeakReference<Handler> mLocalHandler;
IRemoteControlDisplayWeak(Handler handler) {
mLocalHandler = new WeakReference<Handler>(handler);
}
public void setPlaybackState(int generationId, int state, long stateChangeTimeMs) {
Handler handler = mLocalHandler.get();
if (handler != null) {
handler.obtainMessage(MSG_UPDATE_STATE, generationId, state).sendToTarget();
}
}
public void setMetadata(int generationId, Bundle metadata) {
Handler handler = mLocalHandler.get();
if (handler != null) {
handler.obtainMessage(MSG_SET_METADATA, generationId, 0, metadata).sendToTarget();
}
}
public void setTransportControlFlags(int generationId, int flags) {
Handler handler = mLocalHandler.get();
if (handler != null) {
handler.obtainMessage(MSG_SET_TRANSPORT_CONTROLS, generationId, flags)
.sendToTarget();
}
}
public void setArtwork(int generationId, Bitmap bitmap) {
Handler handler = mLocalHandler.get();
if (handler != null) {
handler.obtainMessage(MSG_SET_ARTWORK, generationId, 0, bitmap).sendToTarget();
}
}
public void setAllMetadata(int generationId, Bundle metadata, Bitmap bitmap) {
Handler handler = mLocalHandler.get();
if (handler != null) {
handler.obtainMessage(MSG_SET_METADATA, generationId, 0, metadata).sendToTarget();
handler.obtainMessage(MSG_SET_ARTWORK, generationId, 0, bitmap).sendToTarget();
}
}
public void setCurrentClientId(int clientGeneration, PendingIntent mediaIntent,
boolean clearing) throws RemoteException {
Handler handler = mLocalHandler.get();
if (handler != null) {
handler.obtainMessage(MSG_SET_GENERATION_ID,
clientGeneration, (clearing ? 1 : 0), mediaIntent).sendToTarget();
}
}
};
public KeyguardTransportControlView(Context context, AttributeSet attrs) {
super(context, attrs);
if (DEBUG) Log.v(TAG, "Create TCV " + this);
mAudioManager = new AudioManager(mContext);
mCurrentPlayState = RemoteControlClient.PLAYSTATE_NONE; // until we get a callback
mIRCD = new IRemoteControlDisplayWeak(mHandler);
}
protected void onListenerDetached() {
mMusicClientPresent = false;
if (DEBUG) Log.v(TAG, "onListenerDetached()");
if (mTransportCallback != null) {
mTransportCallback.onListenerDetached();
} else {
Log.w(TAG, "onListenerDetached: no callback");
}
}
private void onListenerAttached() {
mMusicClientPresent = true;
if (DEBUG) Log.v(TAG, "onListenerAttached()");
if (mTransportCallback != null) {
mTransportCallback.onListenerAttached();
} else {
Log.w(TAG, "onListenerAttached(): no callback");
}
}
private void updateTransportControls(int transportControlFlags) {
mTransportControlFlags = transportControlFlags;
}
@Override
public void onFinishInflate() {
super.onFinishInflate();
mTrackTitle = (TextView) findViewById(R.id.title);
mTrackTitle.setSelected(true); // enable marquee
mAlbumArt = (ImageView) findViewById(R.id.albumart);
mBtnPrev = (ImageView) findViewById(R.id.btn_prev);
mBtnPlay = (ImageView) findViewById(R.id.btn_play);
mBtnNext = (ImageView) findViewById(R.id.btn_next);
final View buttons[] = { mBtnPrev, mBtnPlay, mBtnNext };
for (View view : buttons) {
view.setOnClickListener(this);
}
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
if (DEBUG) Log.v(TAG, "onAttachToWindow()");
if (mPopulateMetadataWhenAttached != null) {
updateMetadata(mPopulateMetadataWhenAttached);
mPopulateMetadataWhenAttached = null;
}
if (!mAttached) {
if (DEBUG) Log.v(TAG, "Registering TCV " + this);
mAudioManager.registerRemoteControlDisplay(mIRCD);
}
mAttached = true;
}
@Override
public void onDetachedFromWindow() {
if (DEBUG) Log.v(TAG, "onDetachFromWindow()");
super.onDetachedFromWindow();
if (mAttached) {
if (DEBUG) Log.v(TAG, "Unregistering TCV " + this);
mAudioManager.unregisterRemoteControlDisplay(mIRCD);
}
mAttached = false;
}
class Metadata {
private String artist;
private String trackTitle;
private String albumTitle;
private Bitmap bitmap;
public String toString() {
return "Metadata[artist=" + artist + " trackTitle=" + trackTitle + " albumTitle=" + albumTitle + "]";
}
}
private String getMdString(Bundle data, int id) {
return data.getString(Integer.toString(id));
}
private void updateMetadata(Bundle data) {
if (mAttached) {
mMetadata.artist = getMdString(data, MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST);
mMetadata.trackTitle = getMdString(data, MediaMetadataRetriever.METADATA_KEY_TITLE);
mMetadata.albumTitle = getMdString(data, MediaMetadataRetriever.METADATA_KEY_ALBUM);
populateMetadata();
} else {
mPopulateMetadataWhenAttached = data;
}
}
/**
* Populates the given metadata into the view
*/
private void populateMetadata() {
StringBuilder sb = new StringBuilder();
int trackTitleLength = 0;
if (!TextUtils.isEmpty(mMetadata.trackTitle)) {
sb.append(mMetadata.trackTitle);
trackTitleLength = mMetadata.trackTitle.length();
}
if (!TextUtils.isEmpty(mMetadata.artist)) {
if (sb.length() != 0) {
sb.append(" - ");
}
sb.append(mMetadata.artist);
}
if (!TextUtils.isEmpty(mMetadata.albumTitle)) {
if (sb.length() != 0) {
sb.append(" - ");
}
sb.append(mMetadata.albumTitle);
}
mTrackTitle.setText(sb.toString(), TextView.BufferType.SPANNABLE);
Spannable str = (Spannable) mTrackTitle.getText();
if (trackTitleLength != 0) {
str.setSpan(new ForegroundColorSpan(0xffffffff), 0, trackTitleLength,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
trackTitleLength++;
}
if (sb.length() > trackTitleLength) {
str.setSpan(new ForegroundColorSpan(0x7fffffff), trackTitleLength, sb.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
mAlbumArt.setImageBitmap(mMetadata.bitmap);
final int flags = mTransportControlFlags;
setVisibilityBasedOnFlag(mBtnPrev, flags, RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS);
setVisibilityBasedOnFlag(mBtnNext, flags, RemoteControlClient.FLAG_KEY_MEDIA_NEXT);
setVisibilityBasedOnFlag(mBtnPlay, flags,
RemoteControlClient.FLAG_KEY_MEDIA_PLAY
| RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
| RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
| RemoteControlClient.FLAG_KEY_MEDIA_STOP);
updatePlayPauseState(mCurrentPlayState);
}
public boolean isMusicPlaying() {
return mCurrentPlayState == RemoteControlClient.PLAYSTATE_PLAYING
|| mCurrentPlayState == RemoteControlClient.PLAYSTATE_BUFFERING;
}
private static void setVisibilityBasedOnFlag(View view, int flags, int flag) {
if ((flags & flag) != 0) {
view.setVisibility(View.VISIBLE);
} else {
view.setVisibility(View.GONE);
}
}
private void updatePlayPauseState(int state) {
if (DEBUG) Log.v(TAG,
"updatePlayPauseState(), old=" + mCurrentPlayState + ", state=" + state);
if (state == mCurrentPlayState) {
return;
}
final int imageResId;
final int imageDescId;
switch (state) {
case RemoteControlClient.PLAYSTATE_ERROR:
imageResId = com.android.internal.R.drawable.stat_sys_warning;
// TODO use more specific image description string for warning, but here the "play"
// message is still valid because this button triggers a play command.
imageDescId = com.android.internal.R.string.lockscreen_transport_play_description;
break;
case RemoteControlClient.PLAYSTATE_PLAYING:
imageResId = com.android.internal.R.drawable.ic_media_pause;
imageDescId = com.android.internal.R.string.lockscreen_transport_pause_description;
break;
case RemoteControlClient.PLAYSTATE_BUFFERING:
imageResId = com.android.internal.R.drawable.ic_media_stop;
imageDescId = com.android.internal.R.string.lockscreen_transport_stop_description;
break;
case RemoteControlClient.PLAYSTATE_PAUSED:
default:
imageResId = com.android.internal.R.drawable.ic_media_play;
imageDescId = com.android.internal.R.string.lockscreen_transport_play_description;
break;
}
mBtnPlay.setImageResource(imageResId);
mBtnPlay.setContentDescription(getResources().getString(imageDescId));
mCurrentPlayState = state;
mTransportCallback.onPlayStateChanged();
}
static class SavedState extends BaseSavedState {
boolean clientPresent;
SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
this.clientPresent = in.readInt() != 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(this.clientPresent ? 1 : 0);
}
public static final Parcelable.Creator<SavedState> CREATOR
= new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.clientPresent = mMusicClientPresent;
return ss;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
if (ss.clientPresent) {
if (DEBUG) Log.v(TAG, "Reattaching client because it was attached");
onListenerAttached();
}
}
public void onClick(View v) {
int keyCode = -1;
if (v == mBtnPrev) {
keyCode = KeyEvent.KEYCODE_MEDIA_PREVIOUS;
} else if (v == mBtnNext) {
keyCode = KeyEvent.KEYCODE_MEDIA_NEXT;
} else if (v == mBtnPlay) {
keyCode = KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE;
}
if (keyCode != -1) {
sendMediaButtonClick(keyCode);
}
}
private void sendMediaButtonClick(int keyCode) {
if (mClientIntent == null) {
// Shouldn't be possible because this view should be hidden in this case.
Log.e(TAG, "sendMediaButtonClick(): No client is currently registered");
return;
}
// use the registered PendingIntent that will be processed by the registered
// media button event receiver, which is the component of mClientIntent
KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
intent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
try {
mClientIntent.send(getContext(), 0, intent);
} catch (CanceledException e) {
Log.e(TAG, "Error sending intent for media button down: "+e);
e.printStackTrace();
}
keyEvent = new KeyEvent(KeyEvent.ACTION_UP, keyCode);
intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
intent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
try {
mClientIntent.send(getContext(), 0, intent);
} catch (CanceledException e) {
Log.e(TAG, "Error sending intent for media button up: "+e);
e.printStackTrace();
}
}
public boolean providesClock() {
return false;
}
private boolean wasPlayingRecently(int state, long stateChangeTimeMs) {
switch (state) {
case RemoteControlClient.PLAYSTATE_PLAYING:
case RemoteControlClient.PLAYSTATE_FAST_FORWARDING:
case RemoteControlClient.PLAYSTATE_REWINDING:
case RemoteControlClient.PLAYSTATE_SKIPPING_FORWARDS:
case RemoteControlClient.PLAYSTATE_SKIPPING_BACKWARDS:
case RemoteControlClient.PLAYSTATE_BUFFERING:
// actively playing or about to play
return true;
case RemoteControlClient.PLAYSTATE_NONE:
return false;
case RemoteControlClient.PLAYSTATE_STOPPED:
case RemoteControlClient.PLAYSTATE_PAUSED:
case RemoteControlClient.PLAYSTATE_ERROR:
// we have stopped playing, check how long ago
if (DEBUG) {
if ((SystemClock.elapsedRealtime() - stateChangeTimeMs) < DISPLAY_TIMEOUT_MS) {
Log.v(TAG, "wasPlayingRecently: time < TIMEOUT was playing recently");
} else {
Log.v(TAG, "wasPlayingRecently: time > TIMEOUT");
}
}
return ((SystemClock.elapsedRealtime() - stateChangeTimeMs) < DISPLAY_TIMEOUT_MS);
default:
Log.e(TAG, "Unknown playback state " + state + " in wasPlayingRecently()");
return false;
}
}
public void setKeyguardCallback(KeyguardHostView.TransportCallback transportCallback) {
mTransportCallback = transportCallback;
}
}
|
rex-xxx/mt6572_x201
|
frameworks/base/policy/src/com/android/internal/policy/impl/keyguard/KeyguardTransportControlView.java
|
Java
|
gpl-2.0
| 19,994
|
/*
* Wazuh app - Mitre alerts components
* Copyright (C) 2015-2021 Wazuh, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Find more information about this on the LICENSE file.
*/
import React, { Component } from 'react'
import {
EuiPanel,
EuiFlexGroup,
EuiFlexItem,
} from '@elastic/eui';
import { SearchBar, FilterManager } from '../../../../../../src/plugins/data/public/';
import { I18nProvider } from '@kbn/i18n/react';
//@ts-ignore
import { ComplianceRequirements } from './components/requirements';
import { ComplianceSubrequirements } from './components/subrequirements';
import { getElasticAlerts, getIndexPattern, IFilterParams } from '../mitre/lib';
import { pciRequirementsFile } from '../../../../common/compliance-requirements/pci-requirements';
import { gdprRequirementsFile } from '../../../../common/compliance-requirements/gdpr-requirements';
import { hipaaRequirementsFile } from '../../../../common/compliance-requirements/hipaa-requirements';
import { nistRequirementsFile } from '../../../../common/compliance-requirements/nist-requirements';
import { tscRequirementsFile } from '../../../../common/compliance-requirements/tsc-requirements';
import { KbnSearchBar } from '../../kbn-search-bar';
import { getDataPlugin } from '../../../kibana-services';
export class ComplianceTable extends Component {
_isMount = false;
timefilter: {
getTime(): any
setTime(time: any): void
_history: { history: { items: { from: string, to: string }[] } }
};
KibanaServices: { [key: string]: any };
filterManager: FilterManager;
indexPattern: any;
state: {
selectedRequirement: string,
flyoutOn: boolean,
filterParams: IFilterParams,
complianceObject: object,
descriptions: object,
loadingAlerts: boolean
selectedRequirements: object,
}
props: any;
constructor(props) {
super(props);
this.KibanaServices = getDataPlugin().query;
this.filterManager = this.KibanaServices.filterManager;
this.timefilter = this.KibanaServices.timefilter.timefilter;
this.state = {
selectedRequirement: "",
flyoutOn: true,
complianceObject: {},
descriptions: {},
loadingAlerts: true,
selectedRequirements: {},
filterParams: {
filters: this.filterManager.getFilters() || [],
query: { language: 'kuery', query: '' },
time: this.timefilter.getTime(),
},
}
this.onChangeSelectedRequirements.bind(this);
this.onQuerySubmit.bind(this);
this.onFiltersUpdated.bind(this);
}
async componentDidMount() {
this._isMount = true;
this.filtersSubscriber = this.filterManager.getUpdates$().subscribe(() => {
this.onFiltersUpdated(this.filterManager.getFilters())
});
this.indexPattern = await getIndexPattern();
this.buildComplianceObject();
}
componentWillUnmount() {
this.filtersSubscriber.unsubscribe();
}
buildComplianceObject() {
try {
let complianceRequirements = {};
let descriptions = {};
let selectedRequirements = {}; // all enabled by default
if (this.props.section === 'pci') {
descriptions = pciRequirementsFile;
Object.keys(pciRequirementsFile).forEach(item => {
const currentRequirement = item.split(".")[0];
if (complianceRequirements[currentRequirement]) {
complianceRequirements[currentRequirement].push(item);
} else {
selectedRequirements[currentRequirement] = true;
complianceRequirements[currentRequirement] = [];
complianceRequirements[currentRequirement].push(item);
}
}); //forEach
}
if (this.props.section === 'gdpr') {
descriptions = gdprRequirementsFile;
Object.keys(gdprRequirementsFile).forEach(item => {
const currentRequirement = item.split("_")[0];
if (complianceRequirements[currentRequirement]) {
complianceRequirements[currentRequirement].push(item);
} else {
selectedRequirements[currentRequirement] = true;
complianceRequirements[currentRequirement] = [];
complianceRequirements[currentRequirement].push(item);
}
}); //forEach
}
if (this.props.section === 'hipaa') {
descriptions = hipaaRequirementsFile;
Object.keys(hipaaRequirementsFile).forEach(item => {
const currentRequirement = item.split(".")[0] + "." + item.split(".")[1] + "." + item.split(".")[2];
if (complianceRequirements[currentRequirement]) {
complianceRequirements[currentRequirement].push(item);
} else {
selectedRequirements[currentRequirement] = true;
complianceRequirements[currentRequirement] = [];
complianceRequirements[currentRequirement].push(item);
}
}); //forEach
}
if (this.props.section === 'nist') {
descriptions = nistRequirementsFile;
Object.keys(nistRequirementsFile).forEach(item => {
const currentRequirement = item.split(".")[0];
if (complianceRequirements[currentRequirement]) {
complianceRequirements[currentRequirement].push(item);
} else {
selectedRequirements[currentRequirement] = true;
complianceRequirements[currentRequirement] = [];
complianceRequirements[currentRequirement].push(item);
}
}); //forEach
}
if (this.props.section === 'tsc') {
descriptions = tscRequirementsFile;
Object.keys(tscRequirementsFile).forEach(item => {
const currentRequirement = item.split(".")[0];
if (complianceRequirements[currentRequirement]) {
complianceRequirements[currentRequirement].push(item);
} else {
selectedRequirements[currentRequirement] = true;
complianceRequirements[currentRequirement] = [];
complianceRequirements[currentRequirement].push(item);
}
}); //forEach
}
this._isMount && this.setState({ complianceObject: complianceRequirements, selectedRequirements, descriptions }, () => this.getRequirementsCount());
} catch (err) {
// TODO ADD showToast
/*this.showToast(
'danger',
'Error',
`Compliance (${this.props.section}) data could not be fetched: ${err}`,
3000
);*/
}
}
onChangeSelectedRequirements = (selectedRequirements) => {
this.setState({ selectedRequirements });
}
onQuerySubmit = (payload: { dateRange: TimeRange, query: Query | undefined }) => {
const { dateRange, query } = payload;
const { filters } = this.state.filterParams;
const filterParams:IFilterParams = { time: dateRange, filters, query};
this.setState({ filterParams, loadingAlerts: true });
}
onFiltersUpdated = (filters: []) => {
const { time, query} = this.state.filterParams;
const filterParams = {time, query, filters};
this.setState({ filterParams, loadingAlerts: true });
}
async componentDidUpdate(prevProps) {
const { filterParams, loadingAlerts } = this.state;
if (JSON.stringify(prevProps.filterParams) !== JSON.stringify(filterParams) && loadingAlerts) {
this.getRequirementsCount();
}
}
async getRequirementsCount() {
try {
const { filterParams } = this.state;
if (!this.indexPattern) { return; }
let fieldAgg = "";
if (this.props.section === "pci")
fieldAgg = "rule.pci_dss";
if (this.props.section === "gdpr")
fieldAgg = "rule.gdpr";
if (this.props.section === "hipaa")
fieldAgg = "rule.hipaa";
if (this.props.section === "nist")
fieldAgg = "rule.nist_800_53";
if (this.props.section === "tsc")
fieldAgg = "rule.tsc";
const aggs = {
tactics: {
terms: {
field: fieldAgg,
size: 100,
}
}
}
// TODO: use `status` and `statusText` to show errors
// @ts-ignore
const { data, status, statusText, } = await getElasticAlerts(this.indexPattern, filterParams, aggs);
const { buckets } = data.aggregations.tactics;
/*if(firstTime){
this.initTactics(buckets); // top tactics are checked on component mount
}*/
this._isMount && this.setState({ requirementsCount: buckets, loadingAlerts: false, firstTime: false });
} catch (err) {
/* this.showToast(
'danger',
'Error',
`Mitre alerts could not be fetched: ${err}`,
3000
);*/
this.setState({ loadingAlerts: false })
}
}
onChangeFlyout = (flyoutOn) => {
this.setState({ flyoutOn });
}
closeFlyout() {
this.setState({ flyoutOn: false });
}
showFlyout(requirement) {
this.setState({
selectedRequirement: requirement,
flyoutOn: true
})
}
render() {
const { complianceObject, loadingAlerts } = this.state;
return (<div>
<EuiFlexGroup>
<EuiFlexItem>
<div className='wz-discover hide-filter-control' >
<KbnSearchBar
onQuerySubmit={this.onQuerySubmit}
onFiltersUpdated={this.onFiltersUpdated}
isLoading={loadingAlerts} />
</div>
</EuiFlexItem>
</EuiFlexGroup>
<EuiFlexGroup style={{ margin: '0 8px' }}>
<EuiFlexItem style={{ width: "calc(100% - 24px)" }}>
<EuiPanel paddingSize="none">
{!!Object.keys(complianceObject).length && this.state.filterParams.time.from !== "init" &&
<EuiFlexGroup>
<EuiFlexItem grow={false} style={{ width: "15%", minWidth: 145, maxHeight: "calc(100vh - 320px)", overflowX: "hidden" }}>
<ComplianceRequirements
indexPattern={this.indexPattern}
section={this.props.section}
onChangeSelectedRequirements={this.onChangeSelectedRequirements}
{...this.state} />
</EuiFlexItem>
<EuiFlexItem style={{ width: "15%" }}>
<ComplianceSubrequirements
indexPattern={this.indexPattern}
filters={this.state.filterParams}
section={this.props.section}
onSelectedTabChanged={(id) => this.props.onSelectedTabChanged(id)}
{...this.state} />
</EuiFlexItem>
</EuiFlexGroup>
}
</EuiPanel>
</EuiFlexItem>
</EuiFlexGroup>
</div>
)
}
}
|
wazuh/wazuh-kibana-app
|
public/components/overview/compliance-table/compliance-table.tsx
|
TypeScript
|
gpl-2.0
| 10,864
|
<?php
//////////////////////////////////////////////////////////////
/// phpThumb() by James Heinrich <info@silisoftware.com> //
// available at http://phpthumb.sourceforge.net ///
//////////////////////////////////////////////////////////////
/// //
// phpThumb.demo.check.php //
// James Heinrich <info@silisoftware.com> //
// //
// Configuration analyzer for phpThumb settings and server //
// settings that may affect phpThumb performance //
// Live demo is at http://phpthumb.sourceforge.net/demo/ //
// //
//////////////////////////////////////////////////////////////
// die('For security reasons, this demo is disabled by default. Please comment out line '.__LINE__.' in '.basename(__FILE__));
$ServerInfo['gd_string'] = 'unknown';
$ServerInfo['gd_numeric'] = 0;
//ob_start();
if (!include_once('../phpthumb.functions.php')) {
ob_end_flush();
die('failed to include_once("../phpthumb.functions.php")');
}
if (!include_once('../phpthumb.class.php')) {
//ob_end_flush();
die('failed to include_once("../phpthumb.class.php")');
}
//ob_end_clean();
$phpThumb = new phpThumb();
if (include_once('../phpThumb.config.php')) {
foreach ($PHPTHUMB_CONFIG as $key => $value) {
$keyname = 'config_'.$key;
$phpThumb->setParameter($keyname, $value);
}
}
$ServerInfo['gd_string'] = phpthumb_functions::gd_version(true);
$ServerInfo['gd_numeric'] = phpthumb_functions::gd_version(false);
$ServerInfo['im_version'] = $phpThumb->ImageMagickVersion();
$gd_info = gd_info();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>phpThumb configuration analyzer</title>
<link rel="stylesheet" type="text/css" href="/style.css" title="style sheet">
</head>
<body style="background-color: #CCCCCC;">
This demo analyzes your settings (phpThumb.config.php and server/PHP) for <a href="http://phpthumb.sourceforge.net"><b>phpThumb()</b></a>.<br>
<br>
<table border="1">
<tr><th colspan="8"><-- bad . . . . . good --></th></tr>
<tr>
<td style="background-color: red;" > </td>
<td style="background-color: orange;" > </td>
<td style="background-color: yellow;" > </td>
<td style="background-color: olive;" > </td>
<td style="background-color: darkgreen;" > </td>
<td style="background-color: green;" > </td>
<td style="background-color: lightgreen;"> </td>
<td style="background-color: lime;" > </td>
</tr>
</table>
<table border="1" cellspacing="0" cellpadding="2">
<tr style="background-color: #EEEEEE;"><th>Setting</th><th colspan="2">Value</th><th>Comments</th></tr>
<?php
$versions['raw'] = array(
'latest' => phpthumb_functions::SafeURLread('http://phpthumb.sourceforge.net/?latestversion=1', $dummy),
'this' => $phpThumb->phpthumb_version,
);
foreach ($versions['raw'] as $key => $value) {
preg_match('#^([0-9\\.]+)\\-?(([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2}))?#i', $value, $matches);
@list($huge, $major, $minor) = @explode('.', @$matches[1]);
@list($year, $month, $day, $hour, $min) = @$matches[3];
$versions['base'][$key] = $matches[1];
$versions['huge'][$key] = $huge;
$versions['major'][$key] = $major;
$versions['minor'][$key] = $minor;
$versions['stamp'][$key] = $matches[2];
$versions['year'][$key] = $year;
$versions['month'][$key] = $month;
$versions['day'][$key] = $day;
$versions['hour'][$key] = $hour;
$versions['min'][$key] = $min;
$versions['date'][$key] = @mktime($hour, $min, 0, $month, $day, $year);
}
$downloadlatest = 'Download the latest version from <a href="http://phpthumb.sourceforge.net">http://phpthumb.sourceforge.net</a>';
echo '<tr><th nowrap>Latest phpThumb version:</th><th colspan="2">'.$versions['raw']['latest'].'</th><td>'.$downloadlatest.'</td></tr>';
echo '<tr><th nowrap>This phpThumb version:</th><th colspan="2" style="background-color: ';
if (!$versions['base']['latest']) {
// failed to get latest version number
echo 'white';
$message = 'Latest version unknown.<br>'.$downloadlatest;
} elseif (phpthumb_functions::version_compare_replacement($versions['base']['this'], $versions['base']['latest'], '>')) {
// new than latest, must be beta version
echo 'lightblue';
$message = 'This must be a pre-release beta version. Please report bugs to <a href="mailto:info@silisoftware.com">info@silisoftware.com</a>';
} elseif (($versions['base']['latest'] == $versions['base']['this']) && ($versions['stamp']['this'] > $versions['stamp']['latest'])) {
// new than latest, must be beta version
echo 'lightblue';
$message = 'You must be using a pre-release beta version. Please report bugs to <a href="mailto:info@silisoftware.com">info@silisoftware.com</a>';
} elseif ($versions['base']['latest'] == $versions['base']['this']) {
// latest version
echo 'lime';
$message = 'You are using the latest released version.';
} elseif ($versions['huge']['latest'].$versions['major']['latest'] == $versions['huge']['this'].$versions['major']['this']) {
echo 'olive';
$message = 'One (or more) minor version(s) have been released since this version.<br>'.$downloadlatest;
} elseif (floatval($versions['huge']['latest'].str_pad($versions['major']['latest'], 2, '0', STR_PAD_LEFT)) < floatval($versions['huge']['this'].str_pad($t_major, 2, '0', STR_PAD_LEFT))) {
echo 'yellow';
$message = 'One (or more) major version(s) have been released since this version, you really should upgrade.<br>'.$downloadlatest;
} else {
echo 'orange';
$message = 'Fundamental changes have been made since this version.<br>'.$downloadlatest;
}
echo ';">'.$phpThumb->phpthumb_version;
echo '</th><td>'.$message.'.<br></td></tr>';
echo '<tr><th>phpThumb.config.php:</th><th colspan="2" style="background-color: ';
if (file_exists('../phpThumb.config.php') && !file_exists('../phpThumb.config.php.default')) {
echo 'lime;">"phpThumb.config.php" exists and "phpThumb.config.php.default" does not';
} elseif (file_exists('../phpThumb.config.php') && file_exists('../phpThumb.config.php.default')) {
echo 'yellow;">"phpThumb.config.php" and "phpThumb.config.php.default" both exist';
} elseif (!file_exists('../phpThumb.config.php') && file_exists('../phpThumb.config.php.default')) {
echo 'yellow;">rename "phpThumb.config.php.default" to "phpThumb.config.php"';
} else {
echo 'yellow;">"phpThumb.config.php" not found (nor "phpThumb.config.php")';
}
echo '</th><td>"phpThumb.config.php.default" that comes in the distribution must be renamed to "phpThumb.config.php" before phpThumb.php can be used. Avoid having both files present to minimize confusion.</td></tr>';
echo '<tr><th>cache directory:</th><th colspan="2">';
$orig_config_cache_directory = $phpThumb->config_cache_directory;
$phpThumb->setCacheDirectory();
echo '<div style="background-color: '.( is_dir($phpThumb->config_cache_directory) ? 'lime;">exists' : 'red;">does NOT exist').'</div>';
echo '<div style="background-color: '.(is_readable($phpThumb->config_cache_directory) ? 'lime;">readable' : 'red;">NOT readable' ).'</div>';
echo '<div style="background-color: '.(is_writable($phpThumb->config_cache_directory) ? 'lime;">writable' : 'red;">NOT writable' ).'</div>';
echo '</th><td>Original: "'.htmlentities($orig_config_cache_directory).'"<br>Resolved: "'.htmlentities($phpThumb->config_cache_directory).'"<br>Must exist and be both readable and writable by PHP.</td></tr>';
echo '<tr><th>cache write test:</th><th colspan="2">';
$phpThumb->rawImageData = 'phpThumb.demo.check.php_cachetest';
$phpThumb->SetCacheFilename();
echo '<div>'.htmlentities($phpThumb->cache_filename ? implode(' / ', preg_split('#[/\\\\]#', $phpThumb->cache_filename)) : 'NO CACHE FILENAME RESOLVED').'</div>';
echo '<div>directory '.(is_dir(dirname($phpThumb->cache_filename)) ? 'exists' : 'does NOT exist').' (before EnsureDirectoryExists())</div>';
phpthumb_functions::EnsureDirectoryExists(dirname($phpThumb->cache_filename));
echo '<div style="background-color: '.(is_dir(dirname($phpThumb->cache_filename)) ? 'lime;">directory exists' : 'red;">directory does NOT exist').' (after EnsureDirectoryExists())</div>';
if ($fp = @fopen($phpThumb->cache_filename, 'wb')) {
fwrite($fp, 'this is a test from '.__FILE__);
fclose($fp);
echo '<div style="background-color: lime;">write test succeeded</div>';
$old_perms = substr(sprintf('%o', fileperms($phpThumb->cache_filename)), -4);
@chmod($phpThumb->cache_filename, 0644);
clearstatcache();
$new_perms = substr(sprintf('%o', fileperms($phpThumb->cache_filename)), -4);
echo '<div style="background-color: '.(($new_perms == '0644') ? 'lime' : (($new_perms > '0644') ? 'orange' : 'red')).';">chmod($phpThumb->cache_filename, 0644) from "'.htmlentities($old_perms).'" resulted in permissions "'.htmlentities($new_perms).'"</div>';
if (@unlink($phpThumb->cache_filename)) {
echo '<div style="background-color: lime;">delete test succeeded</div>';
} else {
echo '<div style="background-color: red;">delete test FAILED</div>';
}
$phpThumb->CleanUpCacheDirectory();
} else {
echo '<div style="background-color: red;">write test FAILED</div>';
}
//echo '</th><td>Original: "'.htmlentities($orig_config_cache_directory).'"<br>Resolved: "'.htmlentities($phpThumb->config_cache_directory).'"<br>Must exist and be both readable and writable by PHP.</td></tr>';
echo '</th><td>Created and deletes a sample cache file to see if you actually have create/delete permission.<br>If <i>Safe Mode</i> is enabled this is often broken.</td></tr>';
echo '<tr><th>temp directory:</th><th colspan="2">';
$orig_config_temp_directory = $phpThumb->config_temp_directory;
echo $phpThumb->phpThumb_tempnam();
echo '<div style="background-color: '.( is_dir($phpThumb->config_temp_directory) ? 'lime;">exists' : 'red;">does NOT exist').'</div>';
echo '<div style="background-color: '.(is_readable($phpThumb->config_temp_directory) ? 'lime;">readable' : 'red;">NOT readable' ).'</div>';
echo '<div style="background-color: '.(is_writable($phpThumb->config_temp_directory) ? 'lime;">writable' : 'red;">NOT writable' ).'</div>';
echo '</th><td>Original: "'.htmlentities($orig_config_temp_directory).'"<br>Resolved: "'.htmlentities($phpThumb->config_temp_directory).'"<br>Must exist and be both readable and writable by PHP.</td></tr>';
echo '<tr><th>PHP version:</th><th colspan="2" style="background-color: ';
if (phpthumb_functions::version_compare_replacement(phpversion(), '5.0.0', '>=')) {
echo 'lime';
} elseif (phpthumb_functions::version_compare_replacement(phpversion(), '4.4.2', '=')) {
echo 'darkgreen';
} elseif (phpthumb_functions::version_compare_replacement(phpversion(), '4.3.3', '>=')) {
echo 'lightgreen';
} elseif (phpthumb_functions::version_compare_replacement(phpversion(), '4.2.0', '>=')) {
echo 'green';
} elseif (phpthumb_functions::version_compare_replacement(phpversion(), '4.1.0', '>=')) {
echo 'yellow';
} elseif (phpthumb_functions::version_compare_replacement(phpversion(), '4.0.6', '>=')) {
echo 'orange';
} else {
echo 'red';
}
echo ';">'.phpversion();
echo '</th><td>PHP5 is ideal (support for numerous built-in filters which are much faster than my code).<br>PHP v4.4.2 contains a bug in fopen over HTTP (phpThumb has a workaround)<br>PHP v4.3.2+ supports ImageSaveAlpha which is required for proper PNG/ICO output.<br>ImageRotate requires PHP v4.3.0+ (but buggy before v4.3.3).<br>EXIF thumbnail extraction requires PHP v4.2.0+.<br>Most things will work back to PHP v4.1.0, and mostly (perhaps buggy) back to v4.0.6, but no guarantees for any version older than that.</td></tr>';
echo '<tr><th>GD version:</th><th colspan="2" style="background-color: ';
if ($ServerInfo['gd_numeric'] >= 2) {
if (!empty($ServerInfo['gd_string']) && preg_match('#bundled#i', $ServerInfo['gd_string'])) {
echo 'lime';
} else {
echo 'yellow';
}
} elseif (!empty($ServerInfo['im_version'])) {
echo 'orange';
} else {
echo 'red';
}
echo ';">'.(!empty($ServerInfo['gd_string']) ? $ServerInfo['gd_string'] : 'n/a');
echo '</th><td>GD2-bundled version is ideal.<br>GD2 (non-bundled) is second choice, but there are a number of bugs in the non-bundled version. ImageRotate is only available in the bundled version of GD2.<br>GD1 will also (mostly) work, at much-reduced image quality and several features disabled. phpThumb can perform most operations with ImageMagick only, even if GD is not available.</td></tr>';
$IMreleaseDate = 0;
if (preg_match('# ([0-9]{2})/([0-9]{2})/([0-9]{2}) #', $ServerInfo['im_version'], $matches)) {
list($dummy, $m, $d, $y) = $matches;
if ($y < 70) {
$y += 2000;
} elseif ($y < 100) {
$y += 1900;
}
$IMreleaseDate = mktime(12, 0, 0, $m, $d, $y);
} elseif (preg_match('# ([0-9]{4})\\-([0-9]{2})\\-([0-9]{2}) #', $ServerInfo['im_version'], $matches)) {
list($dummy, $y, $m, $d) = $matches;
$IMreleaseDate = mktime(12, 0, 0, $m, $d, $y);
}
$IMversionAge = time() - $IMreleaseDate;
echo '<tr><th>ImageMagick version:</th><th colspan="2" style="background-color: ';
if ($ServerInfo['im_version']) {
if ($IMversionAge < (86400 * 365 * 1)) {
echo 'lime';
} elseif ($IMversionAge < (86400 * 365 * 2)) {
echo 'lightgreen';
} elseif ($IMversionAge < (86400 * 365 * 3)) {
echo 'green';
} elseif ($IMversionAge < (86400 * 365 * 4)) {
echo 'darkgreen';
} else {
echo 'olive';
}
} elseif (!empty($ServerInfo['gd_string'])) {
echo 'orange';
} else {
echo 'red';
}
echo ';">';
echo '<div style="color: navy; font-family: monospace;">'.htmlentities($phpThumb->config_imagemagick_path);
echo ' <span style="cursor: help;" title="file_exists" >['.intval( @file_exists($phpThumb->config_imagemagick_path)).']</span> ';
echo ' <span style="cursor: help;" title="file_exists_ignoreopenbasedir">['.intval($phpThumb->file_exists_ignoreopenbasedir($phpThumb->config_imagemagick_path)).']</span> ';
echo ' <span style="cursor: help;" title="is_file" >['.intval( @is_file($phpThumb->config_imagemagick_path)).']</span> ';
echo ' <span style="cursor: help;" title="is_readable" >['.intval( @is_readable($phpThumb->config_imagemagick_path)).']</span> ';
echo ' <span style="cursor: help;" title="is_executable" >['.intval( @is_executable($phpThumb->config_imagemagick_path)).']</span> ';
echo '</div>';
echo '<div style="color: blue; font-family: monospace;">'.htmlentities($phpThumb->ImageMagickCommandlineBase()).'</div>';
echo ($ServerInfo['im_version'] ? $ServerInfo['im_version'] : 'n/a');
echo ($IMreleaseDate ? '<br><br>This version of ImageMagick is '.NiceTimeFormatting($IMversionAge).' old<br>(see <a href="http://www.imagemagick.org/">www.imagemagick.org</a> for new versions)' : '');
echo '</th><td>ImageMagick is faster than GD, can process larger images without PHP memory_limit issues, can resize animated GIFs. phpThumb can perform most operations with ImageMagick only, even if GD is not available.</td></tr>';
echo '<tr><th>ImageMagick features:</th>';
if ($ServerInfo['im_version']) {
$GDfeatures['red'] = array('help', 'thumbnail', 'resize', 'crop', 'repage', 'coalesce', 'gravity', 'background', 'interlace', 'flatten', 'border', 'bordercolor', 'dither', 'quality');
$GDfeatures['orange'] = array('version', 'blur', 'colorize', 'colors', 'colorspace', 'contrast', 'contrast-stretch', 'edge', 'emboss', 'fill', 'flip', 'flop', 'gamma', array('gaussian','gaussian-blur'), 'level', 'modulate', 'monochrome', 'negate', 'normalize', 'rotate', 'sepia-tone', 'threshold', 'unsharp');
echo '<th colspan="2">|';
foreach ($GDfeatures as $missingcolor => $features) {
foreach ($features as $dummy => $feature) {
$foundOneThatWorks = false;
if (is_array($feature)) {
// sometimes feature names change, e.g. "gaussian" -> "gaussian-blur". They won't both exist in the same version of ImageMagick, but as long as one of them does then the feature will work
foreach ($feature as $alternate_feature_name) {
if ($phpThumb->ImageMagickSwitchAvailable($alternate_feature_name)) {
$foundOneThatWorks = true;
$feature = $alternate_feature_name;
break;
}
}
} else {
$foundOneThatWorks = $phpThumb->ImageMagickSwitchAvailable($feature);
}
echo '| <span style="background-color: '.($foundOneThatWorks ? 'lime' : $missingcolor).';">'.htmlentities($feature).'</span> |';
}
}
echo '|</th>';
} else {
echo '<th colspan="2" style="background-color: orange;">ImageMagick not found</th>';
}
echo '<td>All of these parameters may be called by phpThumb, depending on parameters used. Green means the feature is available; red means a critical feature is missing; orange means an optional filter/feature is missing.</td></tr>';
echo '<tr><th>ImageMagick formats:</th>';
if ($ServerInfo['im_version']) {
echo '<td colspan="2"><div style="width: 100%; height: 200px; overflow: auto; font-family: monospace; white-space: pre; background-color: #FFFFFF;">'.htmlentities($phpThumb->ImageMagickFormatsList()).'</div></td>';
} else {
echo '<th colspan="2" style="background-color: orange;">ImageMagick not found</th>';
}
echo '<td>ImageMagick can only read/write formats as listed here. You may need to recompile ImageMagick if you need to use a format not listed</td></tr>';
echo '<tr><th>GD features:</th><th colspan="2">';
$GDfeatures['red'] = array('JPEG Support', 'JPG Support', 'PNG Support'); // older versions would report "JPG Support", newer versions report "JPEG Support"
$GDfeatures['orange'] = array('GIF Read Support', 'GIF Create Support', 'FreeType Support');
foreach ($GDfeatures as $missingcolor => $features) {
foreach ($features as $dummy => $feature) {
if (isset($gd_info[$feature])) {
echo '<div style="background-color: '.($gd_info[$feature] ? 'lime' : $missingcolor).';">'.htmlentities($feature).'</div>';
}
}
}
echo '</th><td>PNG support is required for watermarks, overlays, calls to ImageMagick and other internal operations.<br>JPG support is obviously quite useful, but ImageMagick can substitute<br>GIF read support can be bypassed with ImageMagick and/or internal GIF routines.<br>GIF create support can be bypassed with ImageMagick (if no filters are applied)<br>FreeType support is needed for TTF overlays.</td></tr>';
echo '<tr><th>GD extension "EXIF"</th><th colspan="2" style="background-color: ';
if (extension_loaded('exif')) {
echo 'lime';
} elseif (!empty($ServerInfo['gd_string'])) {
echo 'orange';
}
echo ';">'.(extension_loaded('exif') ? 'TRUE' : 'FALSE');
echo '</th><td>EXIF extension required for auto-rotate images. Also required to extract EXIF thumbnail to use as source if source image is too large for PHP memory_limit and ImageMagick is unavailable.</td></tr>';
echo '<tr><th>php_sapi_name()</th><th colspan="2" style="background-color: ';
$php_sapi_name = strtolower(function_exists('php_sapi_name') ? php_sapi_name() : '');
if (!$php_sapi_name || (preg_match('#~#', dirname($_SERVER['PHP_SELF'])) && ($php_sapi_name != 'apache'))) {
echo 'red';
} elseif ($php_sapi_name == 'cgi-fcgi') {
echo 'orange';
} elseif ($php_sapi_name == 'cgi') {
echo 'yellow';
} elseif ($php_sapi_name == 'apache') {
echo 'lime';
} else {
echo 'green';
}
echo ';">'.htmlentities($php_sapi_name).'</th>';
echo '<td>SAPI mode preferred to CGI mode. FCGI mode has unconfirmed strange behavior (notably more than one space in "wmt" filter text causes errors). If not working in "apache" (SAPI) mode, <i>apache_lookup_uri()</i> will not work.</td></tr>';
echo '<tr><th>Server Software</th><th colspan="2" style="background-color: ';
$server_software = getenv('SERVER_SOFTWARE');
if (!$server_software) {
echo 'red';
} elseif (preg_match('#^Apache/([0-9\\.]+)#i', $server_software, $matches)) {
if (phpthumb_functions::version_compare_replacement($matches[1], '2.0.0', '>=')) {
echo 'lightgreen';
} else {
echo 'lime';
}
} else {
echo 'darkgreen';
}
echo ';">'.$server_software.'</th>';
echo '<td>Apache v1.x has the fewest compatability problems. IIS has numerous annoyances. Apache v2.x is broken when lookup up <i>/~user/filename.jpg</i> style relative filenames using <i>apache_lookup_uri()</i>.</td></tr>';
echo '<tr><th>curl_version:</th><th colspan="2" style="background-color: ';
$curl_version = (function_exists('curl_version') ? curl_version() : '');
if (is_array($curl_version)) {
$curl_version = @$curl_version['version'];
}
if ($curl_version) {
echo 'lime';
} else {
echo 'yellow';
}
echo ';">'.$curl_version.'</th>';
echo '<td>Best if available. HTTP source images will be unavailable if CURL unavailable and <i>allow_url_fopen</i> is also disabled.</td></tr>';
echo '<tr style="background-color: #EEEEEE;"><th colspan="4"> </th></tr>';
echo '<tr style="background-color: #EEEEEE;"><th>function_exists:</th><th colspan="2">Value</th><th>Comments</th></tr>';
$FunctionsExist = array(
'ImageRotate' => array('orange', 'required for "ra" and "ar" filters.'),
'exif_read_data' => array('yellow', 'required for "ar" filter.'),
'exif_thumbnail' => array('yellow', 'required to extract EXIF thumbnails.'),
'memory_get_usage' => array('lightgreen', 'mostly used for troubleshooting.'),
'version_compare' => array('darkgreen', 'available in PHP v4.1.0+, internal workaround available'),
'file_get_contents' => array('darkgreen', 'available in PHP v4.3.0+, internal workaround available'),
'file_put_contents' => array('darkgreen', 'available in PHP v5.0.0+, internal workaround available'),
'is_executable' => array('yellow', 'available in PHP3, except only PHP5 for Windows. poor internal workaround available'),
'gd_info' => array('olive', 'available in PHP v4.3.0+ (with bundled GD2), internal workaround available'),
'ImageTypes' => array('red', 'required for GD image output.'),
'ImageCreateFromJPEG' => array('orange', 'required for JPEG source images using GD.'),
'ImageCreateFromGIF' => array('yellow', 'useful for GIF source images using GD.'),
'ImageCreateFromPNG' => array('orange', 'required for PNG source images using GD and other source image formats using ImageMagick.'),
'ImageCreateFromWBMP' => array('yellow', 'required for WBMP source images using GD.'),
'ImageCreateFromString' => array('orange', 'required for HTTP and non-file image sources.'),
'ImageCreateTrueColor' => array('orange', 'required for all non-ImageMagick filters.'),
'ImageIsTrueColor' => array('olive', 'available in PHP v4.3.2+ with GD v2.0.1+'),
'ImageFilter' => array('yellow', 'PHP5 only. Required for some filters (but most can use ImageMagick instead)'),
);
foreach ($FunctionsExist as $function => $details) {
list($color, $description) = $details;
echo '<tr><th>'.$function.'</th><th colspan="2" style="background-color: ';
if (function_exists(strtolower($function))) {
echo 'lime;">TRUE';
} else {
echo $color.';">FALSE';
}
echo '</th><td>'.htmlentities($description).'</td></tr>';
}
echo '<tr style="background-color: #EEEEEE;"><th colspan="4"> </th></tr>';
echo '<tr style="background-color: #EEEEEE;"><th>Setting</th><th>Master Value</th><th>Local Value</th><th>Comments</th></tr>';
$SettingFeatures = array(
'magic_quotes_runtime' => array('red', 'lime', 'This setting is evil. Turn it off.'),
'magic_quotes_gpc' => array('yellow', 'lime', 'This setting is bad. Turn it off, if possible. phpThumb will attempt to work around it if it is enabled.'),
'safe_mode' => array('orange', 'lime', 'Best if off. Calls to ImageMagick will be disabled if safe_mode is set to prevent writing temp files (limiting max image resolution, no animated GIF resize). Raw image data sources (e.g. from MySQL database) may not work. Temp files may be disabled. Features will be limited. If disabled in Master but enabled in Local, edit httpd.conf and set (php_admin_value safe_mode "Off") between <VirtualHost> tags'),
'allow_url_fopen' => array('lime', 'yellow', 'Best if on. HTTP source images will be unavailable if disabled and CURL is unavailable.'),
);
foreach ($SettingFeatures as $feature => $FeaturesDetails) {
list($color_true, $color_false, $reason) = $FeaturesDetails;
echo '<tr><th>'.$feature.':</th>';
echo '<th style="background-color: '.(@get_cfg_var($feature) ? $color_true : $color_false).';">'.$phpThumb->phpThumbDebugVarDump((bool) @get_cfg_var($feature)).'</th>';
echo '<th style="background-color: '.(preg_match('#(1|ON)#i', @ini_get($feature)) ? $color_true : $color_false).';">'.$phpThumb->phpThumbDebugVarDump((bool) preg_match('#(1|ON)#i', ini_get($feature))).'</th>';
echo '<td>'.htmlentities($reason).'</td></tr>';
}
$MissingFunctionSeverity = array(
'shell_exec' => 'red',
'system' => 'red',
'passthru' => 'red',
'exec' => 'red',
'curl_exec' => 'orange',
);
$DisabledFunctions[0] = explode(',', @get_cfg_var('disable_functions'));
$DisabledFunctions[1] = explode(',', @ini_get('disable_functions'));
echo '<tr><th>disable_functions:</th>';
for ($i = 0; $i <= 1; $i++) {
foreach ($DisabledFunctions[$i] as $key => $value) {
if (!empty($MissingFunctionSeverity[$value])) {
$DisabledFunctions[$i][$key] = '<span style="background-color: '.$MissingFunctionSeverity[$value].';">'.$value.'</span>';
}
}
$disabled_functions = implode(', ', $DisabledFunctions[$i]);
echo '<th style="background-color: '.($disabled_functions ? 'yellow' : 'lime').';">';
echo '</th>';
}
echo '<td>Best if nothing disabled. Calls to ImageMagick will be prevented if exec+system+shell_exec+passthru are disabled.</td></tr>';
echo '<tr><th>memory_limit:</th><th style="background-color: ';
$memory_limit = @get_cfg_var('memory_limit');
if (!$memory_limit) {
echo 'lime';
} elseif ($memory_limit >= 32) {
echo 'lime';
} elseif ($memory_limit >= 24) {
echo 'lightgreen';
} elseif ($memory_limit >= 16) {
echo 'green';
} elseif ($memory_limit >= 12) {
echo 'darkgreen';
} elseif ($memory_limit >= 8) {
echo 'olive';
} elseif ($memory_limit >= 4) {
echo 'yellow';
} elseif ($memory_limit >= 2) {
echo 'orange';
} else {
echo 'red';
}
echo ';">'.($memory_limit ? $memory_limit : '<i>unlimited</i>').'</th><th style="background-color: ';
$memory_limit = @ini_get('memory_limit');
if (!$memory_limit) {
echo 'lime';
} elseif ($memory_limit >= 32) {
echo 'lime';
} elseif ($memory_limit >= 24) {
echo 'lightgreen';
} elseif ($memory_limit >= 16) {
echo 'green';
} elseif ($memory_limit >= 12) {
echo 'darkgreen';
} elseif ($memory_limit >= 8) {
echo 'olive';
} elseif ($memory_limit >= 4) {
echo 'yellow';
} elseif ($memory_limit >= 2) {
echo 'orange';
} else {
echo 'red';
}
echo ';">'.($memory_limit ? $memory_limit : '<i>unlimited</i>').'</th>';
echo '<td>The higher the better. Divide by 5 to get maximum megapixels of source image that can be thumbnailed (without ImageMagick).'.($memory_limit ? ' Your setting ('.$memory_limit.') allows images up to approximately '.number_format($memory_limit / 5, 1).' megapixels' : '').'</td></tr>';
echo '</table>';
function NiceTimeFormatting($seconds, $precision=1, $returnparts=false) {
$sign = (($seconds < 0) ? -1 : 1);
$seconds = abs($seconds);
do {
if ($seconds < 100) {
$value = number_format($seconds, 0);
$unit = 'second'.(($seconds > 1) ? 's' : '');
break;
}
$minutes = $seconds / 60;
if ($minutes < 60) {
$value = number_format($minutes, $precision);
$unit = 'minutes';
break;
}
$hours = $seconds / 3600;
if ($hours < 24) {
$value = number_format($hours, $precision);
$unit = 'hours';
break;
}
$days = $seconds / 86400;
if ($days < 60) {
$value = number_format($days, $precision);
$unit = 'days';
break;
}
$months = $seconds / (30 * 86400);
if ($months < 12) {
$value = number_format($months, $precision);
$unit = 'months';
break;
}
$years = $seconds / (365 * 86400);
if (true) {
$value = number_format($years, $precision);
$unit = 'years';
break;
}
} while (false);
$value *= $sign;
if ($returnparts) {
return array($value, $unit);
}
return $value.' '.$unit;
}
?>
</body>
</html>
|
gdelamardiere/joomla
|
components/com_alphauserpoints/assets/phpThumb/demo/phpThumb.demo.check.php
|
PHP
|
gpl-2.0
| 28,660
|
package org.kidneyomics.gtf;
import static org.junit.Assert.*;
import java.util.LinkedList;
import java.util.List;
import org.biojava.nbio.genome.parsers.gff.Feature;
import org.biojava.nbio.genome.parsers.gff.Location;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FeatureMergerTest {
Logger logger = LoggerFactory.getLogger(FeatureMergerTest.class);
@Test
public void test() {
Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 200, '+'), 0.0, 0, "");
Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(50, 150, '+'), 0.0, 0, "");
Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(250, 300, '+'), 0.0, 0, "");
List<Feature> features = new LinkedList<Feature>();
features.add(f1);
features.add(f2);
features.add(f3);
List<Feature> merged = FeatureMerger.mergeOverlappingFeatures(features);
assertTrue(merged.size() == 2);
Feature m1 = merged.get(0);
assertEquals(50, m1.location().bioStart());
assertEquals(200, m1.location().bioEnd());
Feature m2 = merged.get(1);
assertEquals(250, m2.location().bioStart());
assertEquals(300, m2.location().bioEnd());
}
@Test
public void test2() {
Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 200, '+'), 0.0, 0, "");
Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(50, 150, '-'), 0.0, 0, "");
Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(250, 300, '+'), 0.0, 0, "");
List<Feature> features = new LinkedList<Feature>();
features.add(f1);
features.add(f2);
features.add(f3);
List<Feature> merged = FeatureMerger.mergeOverlappingFeaturesIgnoringStrand(features);
assertTrue(merged.size() == 2);
Feature m1 = merged.get(0);
assertEquals(50, m1.location().bioStart());
assertEquals(200, m1.location().bioEnd());
Feature m2 = merged.get(1);
assertEquals(250, m2.location().bioStart());
assertEquals(300, m2.location().bioEnd());
}
@Test
public void test3() {
Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 200, '+'), 0.0, 0, "");
Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(50, 150, '-'), 0.0, 0, "");
Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(250, 300, '+'), 0.0, 0, "");
List<Feature> features = new LinkedList<Feature>();
features.add(f1);
features.add(f2);
features.add(f3);
IllegalArgumentException exception = null;
try {
FeatureMerger.mergeOverlappingFeatures(features);
} catch(IllegalArgumentException e) {
exception = e;
}
assertNotNull(exception);
}
@Test
public void test4() {
Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(1, 400, '+'), 0.0, 0, "");
Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(50, 150, '-'), 0.0, 0, "");
Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(250, 300, '+'), 0.0, 0, "");
List<Feature> features = new LinkedList<Feature>();
features.add(f1);
features.add(f2);
features.add(f3);
List<Feature> merged = FeatureMerger.mergeOverlappingFeaturesIgnoringStrand(features);
assertTrue(merged.size() == 1);
Feature m1 = merged.get(0);
assertEquals(1, m1.location().bioStart());
assertEquals(400, m1.location().bioEnd());
}
@Test
public void testRemoveOverlappingFeatures() {
Feature f0 = new Feature("chr1", "a", "exon", Location.fromBio(50, 99, '+'), 0.0, 0, "");
Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 200, '+'), 0.0, 0, "");
Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(150, 250, '+'), 0.0, 0, "");
Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(260, 300, '+'), 0.0, 0, "");
List<Feature> features = new LinkedList<Feature>();
features.add(f0);
features.add(f1);
features.add(f2);
features.add(f3);
List<Feature> removed = FeatureMerger.removeOverlappingFeaturesIgnoreStrand(features);
logger.info("removed");
for(Feature f : removed) {
logger.info(GTFFeatureRenderer.render(f));
}
logger.info("kept");
for(Feature f : features) {
logger.info(GTFFeatureRenderer.render(f));
}
assertEquals(2,removed.size());
assertEquals(2,features.size());
assertEquals(100,removed.get(0).location().bioStart());
assertEquals(200,removed.get(0).location().bioEnd());
assertEquals(150,removed.get(1).location().bioStart());
assertEquals(250,removed.get(1).location().bioEnd());
assertEquals(50,features.get(0).location().bioStart());
assertEquals(99,features.get(0).location().bioEnd());
assertEquals(260,features.get(1).location().bioStart());
assertEquals(300,features.get(1).location().bioEnd());
}
@Test
public void testRemoveOverlappingFeatures2() {
Feature f0 = new Feature("chr1", "a", "exon", Location.fromBio(1, 261, '+'), 0.0, 0, "");
Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 200, '+'), 0.0, 0, "");
Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(150, 250, '+'), 0.0, 0, "");
Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(260, 300, '+'), 0.0, 0, "");
List<Feature> features = new LinkedList<Feature>();
features.add(f0);
features.add(f1);
features.add(f2);
features.add(f3);
List<Feature> removed = FeatureMerger.removeOverlappingFeaturesIgnoreStrand(features);
assertEquals(4,removed.size());
assertEquals(0,features.size());
assertEquals(100,removed.get(0).location().bioStart());
assertEquals(200,removed.get(0).location().bioEnd());
assertEquals(150,removed.get(1).location().bioStart());
assertEquals(250,removed.get(1).location().bioEnd());
assertEquals(1,removed.get(2).location().bioStart());
assertEquals(261,removed.get(2).location().bioEnd());
assertEquals(260,removed.get(3).location().bioStart());
assertEquals(300,removed.get(3).location().bioEnd());
}
@Test
public void testRemoveOverlappingFeatures3() {
Feature f0 = new Feature("chr1", "a", "exon", Location.fromBio(1, 50, '+'), 0.0, 0, "");
Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 148, '+'), 0.0, 0, "");
Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(150, 250, '+'), 0.0, 0, "");
Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(260, 400, '+'), 0.0, 0, "");
Feature f4 = new Feature("chr1", "a", "exon", Location.fromBio(260, 300, '+'), 0.0, 0, "");
List<Feature> features = new LinkedList<Feature>();
features.add(f0);
features.add(f1);
features.add(f2);
features.add(f3);
features.add(f4);
List<Feature> removed = FeatureMerger.removeOverlappingFeaturesIgnoreStrand(features);
assertEquals(2,removed.size());
assertEquals(3,features.size());
assertEquals(260,removed.get(0).location().bioStart());
assertEquals(400,removed.get(0).location().bioEnd());
assertEquals(260,removed.get(1).location().bioStart());
assertEquals(300,removed.get(1).location().bioEnd());
assertEquals(1,features.get(0).location().bioStart());
assertEquals(50,features.get(0).location().bioEnd());
assertEquals(100,features.get(1).location().bioStart());
assertEquals(148,features.get(1).location().bioEnd());
assertEquals(150,features.get(2).location().bioStart());
assertEquals(250,features.get(2).location().bioEnd());
}
@Test
public void testRemoveOverlappingFeatures4() {
Feature f0 = new Feature("chr1", "a", "exon", Location.fromBio(1, 261, '+'), 0.0, 0, "");
Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 200, '+'), 0.0, 0, "");
Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(150, 250, '+'), 0.0, 0, "");
Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(260, 300, '+'), 0.0, 0, "");
Feature f4 = new Feature("chr1", "a", "exon", Location.fromBio(300, 400, '+'), 0.0, 0, "");
Feature f5 = new Feature("chr1", "a", "exon", Location.fromBio(500, 600, '+'), 0.0, 0, "");
List<Feature> features = new LinkedList<Feature>();
features.add(f0);
features.add(f1);
features.add(f2);
features.add(f3);
features.add(f4);
features.add(f5);
List<Feature> removed = FeatureMerger.removeOverlappingFeaturesIgnoreStrand(features);
assertEquals(5,removed.size());
assertEquals(1,features.size());
assertEquals(100,removed.get(0).location().bioStart());
assertEquals(200,removed.get(0).location().bioEnd());
assertEquals(150,removed.get(1).location().bioStart());
assertEquals(250,removed.get(1).location().bioEnd());
assertEquals(1,removed.get(2).location().bioStart());
assertEquals(261,removed.get(2).location().bioEnd());
assertEquals(260,removed.get(3).location().bioStart());
assertEquals(300,removed.get(3).location().bioEnd());
assertEquals(300,removed.get(4).location().bioStart());
assertEquals(400,removed.get(4).location().bioEnd());
assertEquals(500,features.get(0).location().bioStart());
assertEquals(600,features.get(0).location().bioEnd());
}
}
|
christopher-gillies/rna-seq-pipeline
|
src/test/java/org/kidneyomics/gtf/FeatureMergerTest.java
|
Java
|
gpl-2.0
| 9,180
|
function eliminarItem(id, url){
console.log("Eliminar Fase");
console.log(id);
console.log(url);
$("#nombre-item").text(id);
$("#modal-eliminar").modal('show');
$("#btn-eliminar").attr('href', url);
}
function revivirItem(id, url){
console.log("Eliminar Fase");
console.log(id);
console.log(url);
$("#nombre-revivir-item").text(id);
$("#modal-revivir").modal('show');
$("#btn-revivir").attr('href', url);
}
function revertirItem(version, id_version){
console.log("Revertir item");
console.log(id_version);
$("#version-item").text(version);
$("#id_version").val(id_version);
$("#modal-revertir").modal('show');
}
function modificarItem(id, codigo, nombre, descripcion){
console.log("MODIFICAR TIPO ITEM");
console.log(id)
console.log(codigo);
console.log(nombre);
console.log(descripcion);
console.log("------------------");
$("#m-id").val(id);
$("#m-codigo").val(codigo)
$("#m-nombre").val(nombre);
$("#m-descripcion").val(descripcion);
$("#modal-modificar").modal('show');
}
function setUrlNewItem(id_fase){
var id_tipo = $("#id-tipo").val();
var url = "/item/" + id_fase + "/nuevo/" + id_tipo + "/";
console.log(url);
$("#next-new-item").attr("href", url);
}
function setListaRelacion(){
var tipo = $("#tipo").val();
console.log(tipo)
if(tipo == 'padre-hijo'){
console.log("tipo padre-hijo");
$("#s-hijo").removeClass('hide');
$("#s-sucesor").addClass('hide');
}else{
console.log("tipo antecesor-sucesor");
$("#s-sucesor").removeClass('hide');
$("#s-hijo").addClass('hide');
}
}
function eliminarRelacionItem(url){
console.log("Eliminar Relacion Item");
console.log(url);
$("#modal-eliminar").modal('show');
$("#btn-eliminar").attr('href', url);
}
function adjuntarArchivo(nombre){
console.log("Adjuntar archivo a");
console.log(nombre);
$("#modal-modificar").modal('show');
}
function showImpacto(url){
$.get( url, function( data ) {
console.log( "Load was performed." + data);
var datos = JSON.parse(data);
if( datos ){
var item = datos;
console.log(item);
$("#nombre-impacto-item").empty().append(""+item.nombre);
$("#impacto-item").empty().append(""+item.impacto);
$("#modal-impacto").modal('show');
}
});
}
|
SantiagoValdez/hpm
|
src/hpm/static/js/item.js
|
JavaScript
|
gpl-2.0
| 2,276
|
# Arduino-Air-Monitor
These are the codes required for my Arduino Air Monitor Project see my instructables for more informationand how to build it.
https://www.instructables.com/id/Arduino-Air-Monitor-Shield-Live-in-a-Safe-Environm/
|
ManojBR105/Arduino-Air-Monitor
|
README.md
|
Markdown
|
gpl-2.0
| 234
|
<?php get_header(); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php $attachment_link = get_the_attachment_link($post->ID, true, array(450, 800)); // This also populates the iconsize for the next line ?>
<?php $_post = &get_post($post->ID); $classname = ($_post->iconsize[0] <= 128 ? 'small' : '') . 'attachment'; // This lets us style narrow icons specially ?>
<div class="item_class" id="post-<?php the_ID(); ?>">
<div class="item_class_title">
<div class="item_class_title_text">
<div class="date">
<div class="date_month"><?php the_time('M') ?></div>
<div class="date_day"><?php the_time('d') ?></div>
</div>
<div class="titles">
<div class="top_title"><h1><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php _e('Permanent Link to',TEMPLATE_DOMAIN);?> <?php the_title(); ?>"><?php the_title(); ?></a></h1></div>
<div class="end_title"><?php _e("Filed Under",TEMPLATE_DOMAIN); ?> (<?php the_category(', ') ?>) <?php _e("by",TEMPLATE_DOMAIN); ?> <?php the_author() ?> <?php _e('on',TEMPLATE_DOMAIN);?> <?php the_time('d-m-Y') ?></div>
</div>
</div>
</div>
<div class="item_class_text">
<?php the_content(__('Read the rest of this entry »',TEMPLATE_DOMAIN)); ?>
</div>
<div class="item_class_panel">
<div>
<div class="links_left">
<span class="panel_comm"><a href="<?php the_permalink() ?>#respond"><?php _e("Post a Comment",TEMPLATE_DOMAIN); ?></a></span>
<?php edit_post_link(__('Edit',TEMPLATE_DOMAIN), '', ''); ?>
</div>
<div class="links_right">
<?php comments_popup_link(__('(0) Comments',TEMPLATE_DOMAIN), __('(1) Comment',TEMPLATE_DOMAIN), __('(%) Comments',TEMPLATE_DOMAIN)); ?>
<a href="<?php the_permalink() ?>" class="panel_read"><?php _e("Read More",TEMPLATE_DOMAIN); ?></a>
</div>
</div>
</div>
</div>
<?php if ( comments_open() ) { ?> <?php comments_template('',true); ?><?php } ?>
<?php endwhile; else: ?>
<div id="content" class="narrowcolumn"><p><?php _e('Sorry, no attachments matched your criteria.',TEMPLATE_DOMAIN);?></p>
<?php _e('Both comments and pings are currently closed.',TEMPLATE_DOMAIN);?></div>
<?php endif; ?>
<?php get_footer(); ?>
|
rjbaniel/upoor
|
wp-content/themes/oceanwide/attachment.php
|
PHP
|
gpl-2.0
| 2,504
|
/*
* Argus Software
* Copyright (c) 2000-2008 QoSient, LLC
* 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 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 this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
/*
* $Id: $
* $DateTime: $
* $Change: $
*/
/*
* radump.c - dump payload as if its tcpdump data.
*/
#include <unistd.h>
#include <stdlib.h>
#include <compat.h>
#include <rabins.h>
#include <argus_util.h>
#include <argus_client.h>
#include <argus_main.h>
#include <argus_filter.h>
#ifndef IPPROTO_PIM
#define IPPROTO_PIM 103
#endif
#define RaDump 1
#include <oui.h>
#include <signal.h>
#include <ctype.h>
#include "interface.h"
const u_char *snapend = NULL;
char ArgusBuf[MAXSTRLEN];
/* draft-ietf-pwe3-iana-allocation-04 */
struct tok l2vpn_encaps_values[] = {
{ 0x00, "Reserved"},
{ 0x01, "Frame Relay"},
{ 0x02, "ATM AAL5 VCC transport"},
{ 0x03, "ATM transparent cell transport"},
{ 0x04, "Ethernet VLAN"},
{ 0x05, "Ethernet"},
{ 0x06, "Cisco-HDLC"},
{ 0x07, "PPP"},
{ 0x08, "SONET/SDH Circuit Emulation Service over MPLS"},
{ 0x09, "ATM n-to-one VCC cell transport"},
{ 0x0a, "ATM n-to-one VPC cell transport"},
{ 0x0b, "IP Layer2 Transport"},
{ 0x0c, "ATM one-to-one VCC Cell Mode"},
{ 0x0d, "ATM one-to-one VPC Cell Mode"},
{ 0x0e, "ATM AAL5 PDU VCC transport"},
{ 0x0f, "Frame-Relay Port mode"},
{ 0x10, "SONET/SDH Circuit Emulation over Packet"},
{ 0x11, "Structure-agnostic E1 over Packet"},
{ 0x12, "Structure-agnostic T1 (DS1) over Packet"},
{ 0x13, "Structure-agnostic E3 over Packet"},
{ 0x14, "Structure-agnostic T3 (DS3) over Packet"},
{ 0x15, "CESoPSN basic mode"},
{ 0x16, "TDMoIP basic mode"},
{ 0x17, "CESoPSN TDM with CAS"},
{ 0x18, "TDMoIP TDM with CAS"},
{ 0x40, "IP-interworking"},
{ 0, NULL}
};
int ArgusThisEflag = 0;
void
ArgusClientInit (struct ArgusParserStruct *parser)
{
parser->RaWriteOut = 1;
if (!(parser->RaInitialized)) {
/*
the library sets signal handling routines for
SIGHUP, SIGTERM, SIGQUIT, SIGINT, SIGUSR1, and SIGUSR2.
SIGHUP doesn't do anything, SIGTERM, SIGQUIT, and SIGINT
call the user supplied RaParseComplete(). SIGUSR1 and
SIGUSR2 modify the debug level so if compiled with
ARGUS_DEBUG support, programs can start generating
debug information. USR1 increments by 1, USR2 sets
it back to zero.
*/
(void) signal (SIGHUP, (void (*)(int)) RaParseComplete);
ArgusThisEflag = parser->eflag;
parser->eflag = ARGUS_HEXDUMP;
parser->RaInitialized++;
}
}
void RaArgusInputComplete (struct ArgusInput *input) {};
void
RaParseComplete (int sig)
{
if (sig >= 0) {
if ((sig == SIGINT) || (sig == SIGQUIT))
exit(0);
}
}
void
ArgusClientTimeout ()
{
#ifdef ARGUSDEBUG
ArgusDebug (6, "ArgusClientTimeout()\n");
#endif
}
void
parse_arg (int argc, char**argv)
{}
void
usage ()
{
extern char version[];
fprintf (stderr, "Ratemplate Version %s\n", version);
fprintf (stderr, "usage: %s \n", ArgusParser->ArgusProgramName);
fprintf (stderr, "usage: %s [options] [ra-options] [- filter-expression]\n", ArgusParser->ArgusProgramName);
fprintf (stderr, "options: -v print verbose protocol information.\n");
fprintf (stderr, " -s +suser dump the source user data buffer.\n");
fprintf (stderr, " +duser dump the destination user buffer.\n");
exit(1);
}
char * RaDumpUserBuffer (struct ArgusParserStruct *, struct ArgusRecordStruct *, int, int);
void
RaProcessRecord (struct ArgusParserStruct *parser, struct ArgusRecordStruct *argus)
{
char buf[MAXSTRLEN];
int i, srcdata = 0, dstdata = 0;
if (argus->hdr.type & ARGUS_MAR) {
} else {
bzero (buf, MAXSTRLEN);
ArgusPrintRecord(ArgusParser, buf, argus, MAXSTRLEN);
fprintf (stdout, "%s", buf);
bzero (ArgusBuf, MAXSTRLEN);
for (i = 0; i < MAX_PRINT_ALG_TYPES; i++) {
if (parser->RaPrintAlgorithmList[i] != NULL) {
if (parser->RaPrintAlgorithmList[i]->print == ArgusPrintSrcUserData)
srcdata = parser->RaPrintAlgorithmList[i]->length;
if (parser->RaPrintAlgorithmList[i]->print == ArgusPrintDstUserData) {
dstdata = parser->RaPrintAlgorithmList[i]->length;
}
}
}
if (srcdata || dstdata) {
if ((parser->RaFieldDelimiter != ' ') && (parser->RaFieldDelimiter != '\0'))
fprintf (stdout, "%c", parser->RaFieldDelimiter);
else
fprintf (stdout, " ");
}
if (srcdata) {
struct ArgusDataStruct *user = (struct ArgusDataStruct *)argus->dsrs[ARGUS_SRCUSERDATA_INDEX];
int slen;
char *str;
if (user != NULL) {
slen = (user->hdr.argus_dsrvl16.len - 2 ) * 4;
slen = (user->count < slen) ? user->count : slen;
slen = (slen > srcdata) ? srcdata : slen;
}
if ((str = RaDumpUserBuffer (parser, argus, ARGUS_SRCUSERDATA_INDEX, 8196)) != NULL) {
int stlen = 0, blen = 0;
char lbuf[64];
sprintf (buf, "s[%d]=", srcdata);
blen = strlen(buf);
stlen = strlen(str);
sprintf (lbuf, "s[%d]=", (stlen > srcdata) ? srcdata : stlen);
sprintf (buf, "%*.*s", blen, blen, lbuf);
sprintf (&buf[strlen(buf)], "\"%s", str);
buf[srcdata - 1] = '\0';
#if defined(HAVE_STRLCAT)
strlcat(buf, "\"", MAXSTRLEN - strlen(buf));
#else
strcat(buf, "\"");
#endif
fprintf (stdout, "%-*.*s", srcdata, srcdata, buf);
bzero (ArgusBuf, MAXSTRLEN);
if ((parser->RaFieldDelimiter != ' ') && (parser->RaFieldDelimiter != '\0'))
fprintf (stdout, "%c", parser->RaFieldDelimiter);
else
fprintf (stdout, " ");
}
}
if (dstdata) {
struct ArgusDataStruct *user = (struct ArgusDataStruct *)argus->dsrs[ARGUS_DSTUSERDATA_INDEX];
int slen;
char *str;
if (user != NULL) {
slen = (user->hdr.argus_dsrvl16.len - 2 ) * 4;
slen = (user->count < slen) ? user->count : slen;
slen = (slen > dstdata) ? dstdata : slen;
}
if ((str = RaDumpUserBuffer (parser, argus, ARGUS_DSTUSERDATA_INDEX, 8196)) != NULL) {
int stlen = 0, blen = 0;
char lbuf[64];
sprintf (buf, "d[%d]=", dstdata);
blen = strlen(buf);
stlen = strlen(str);
sprintf (lbuf, "d[%d]=", (stlen > dstdata) ? dstdata : stlen);
sprintf (buf, "%*.*s", blen, blen, lbuf);
sprintf (&buf[strlen(buf)], "\"%s", str);
buf[dstdata - 1] = '\0';
#if defined(HAVE_STRLCAT)
strlcat(buf, "\"", MAXSTRLEN - strlen(buf));
#else
strcat(buf, "\"");
#endif
fprintf (stdout, "%-*.*s", dstdata, dstdata, buf);
bzero (ArgusBuf, MAXSTRLEN);
}
}
fprintf (stdout, "\n");
fflush(stdout);
}
}
char *
RaDumpUserBuffer (struct ArgusParserStruct *parser, struct ArgusRecordStruct *argus, int ind, int len)
{
struct ArgusFlow *flow = (struct ArgusFlow *) argus->dsrs[ARGUS_FLOW_INDEX];
unsigned short sport = 0, dport = 0;
int type, proto, process = 0;
struct ArgusDataStruct *user = NULL;
u_char buf[MAXSTRLEN], *bp = NULL, dchr;
int slen = 0, done = 0;
switch (ind) {
case ARGUS_SRCUSERDATA_INDEX:
dchr = 's';
break;
case ARGUS_DSTUSERDATA_INDEX:
dchr = 'd';
break;
}
if ((user = (struct ArgusDataStruct *)argus->dsrs[ind]) != NULL) {
bp = (u_char *) &user->array;
slen = (user->hdr.argus_dsrvl16.len - 2 ) * 4;
slen = (user->count < slen) ? user->count : slen;
slen = (slen > len) ? len : slen;
snapend = bp + slen;
}
if (flow != NULL) {
switch (flow->hdr.subtype & 0x3F) {
case ARGUS_FLOW_CLASSIC5TUPLE: {
switch (type = flow->hdr.argus_dsrvl8.qual) {
case ARGUS_TYPE_IPV4:
switch (flow->ip_flow.ip_p) {
case IPPROTO_TCP:
case IPPROTO_UDP: {
proto = flow->ip_flow.ip_p;
sport = flow->ip_flow.sport;
dport = flow->ip_flow.dport;
process++;
break;
}
case IPPROTO_IGMP: {
struct ArgusMetricStruct *metric = (void *)argus->dsrs[ARGUS_METRIC_INDEX];
if ((metric != NULL) && (((ind == ARGUS_SRCUSERDATA_INDEX) && metric->src.pkts) ||
((ind == ARGUS_DSTUSERDATA_INDEX) && metric->dst.pkts))) {
igmp_print(bp, slen);
done++;
break;
}
}
case IPPROTO_PIM: {
struct ArgusMetricStruct *metric = (void *)argus->dsrs[ARGUS_METRIC_INDEX];
if ((metric != NULL) && (((ind == ARGUS_SRCUSERDATA_INDEX) && metric->src.pkts) ||
((ind == ARGUS_DSTUSERDATA_INDEX) && metric->dst.pkts))) {
pim_print(bp, slen);
done++;
break;
}
}
}
break;
case ARGUS_TYPE_IPV6: {
switch (flow->ipv6_flow.ip_p) {
case IPPROTO_TCP:
case IPPROTO_UDP: {
proto = flow->ipv6_flow.ip_p;
sport = flow->ipv6_flow.sport;
dport = flow->ipv6_flow.dport;
process++;
break;
}
case IPPROTO_PIM: {
struct ArgusMetricStruct *metric = (void *)argus->dsrs[ARGUS_METRIC_INDEX];
if ((metric != NULL) && (((ind == ARGUS_SRCUSERDATA_INDEX) && metric->src.pkts) ||
((ind == ARGUS_DSTUSERDATA_INDEX) && metric->dst.pkts))) {
pim_print(bp, slen);
done++;
break;
}
}
}
break;
}
case ARGUS_TYPE_ARP: {
if (ind == ARGUS_SRCUSERDATA_INDEX) {
arp_src_print(parser, argus);
}
if (ind == ARGUS_DSTUSERDATA_INDEX) {
arp_dst_print(parser, argus);
}
done++;
break;
}
/*
struct ArgusMacFlow {
struct ether_header ehdr;
unsigned char dsap, ssap;
};
*/
case ARGUS_TYPE_ETHER: {
if (flow != NULL)
if ((flow->mac_flow.mac_union.ether.ssap == LLCSAP_BPDU) &&
(flow->mac_flow.mac_union.ether.dsap == LLCSAP_BPDU))
stp_print (bp, slen);
done++;
break;
}
}
}
}
}
if (process && bp) {
*(int *)&buf = 0;
#define ISPORT(p) (dport == (p) || sport == (p))
switch (proto) {
case IPPROTO_TCP: {
if (ISPORT(BGP_PORT))
bgp_print(bp, slen);
else if (ISPORT(TELNET_PORT))
telnet_print(bp, slen);
else if (ISPORT(PPTP_PORT))
pptp_print(bp, slen);
else if (ISPORT(NETBIOS_SSN_PORT))
nbt_tcp_print(bp, slen);
else if (ISPORT(BEEP_PORT))
beep_print(bp, slen);
else if (ISPORT(NAMESERVER_PORT) || ISPORT(MULTICASTDNS_PORT))
ns_print(bp + 2, slen - 2, 0);
else if (ISPORT(MSDP_PORT))
msdp_print(bp, slen);
else if (ISPORT(LDP_PORT))
ldp_print(bp, slen);
else {
int elen = 0;
parser->eflag = ArgusThisEflag;
elen = ArgusEncode (parser, (const char *)bp, NULL, slen, ArgusBuf, sizeof(ArgusBuf));
parser->eflag = ARGUS_HEXDUMP;
}
break;
}
case IPPROTO_UDP: {
if (ISPORT(NAMESERVER_PORT))
ns_print(bp, slen, 0);
else if (ISPORT(MULTICASTDNS_PORT))
ns_print(bp, slen, 1);
else if (ISPORT(NTP_PORT))
ntp_print(bp, slen);
else if (ISPORT(LDP_PORT))
ldp_print(bp, slen);
else if (ISPORT(RADIUS_PORT) || ISPORT(RADIUS_NEW_PORT) ||
ISPORT(RADIUS_ACCOUNTING_PORT) ||
ISPORT(RADIUS_NEW_ACCOUNTING_PORT) )
radius_print(bp, slen);
else if (ISPORT(KERBEROS_PORT) || ISPORT(KERBEROS_SEC_PORT))
krb_print(bp, slen);
else if (ISPORT(SNMP_PORT) || ISPORT(SNMPTRAP_PORT))
snmp_print(bp, slen);
else if (ISPORT(TIMED_PORT))
timed_print(bp, slen);
else if (ISPORT(TFTP_PORT))
tftp_print(bp, slen);
else if (ISPORT(IPPORT_BOOTPC) || ISPORT(IPPORT_BOOTPS))
bootp_print(bp, slen);
else if (ISPORT(RIP_PORT))
rip_print(bp, slen);
else if (ISPORT(AODV_PORT))
aodv_print(bp, slen, 0);
else if (ISPORT(L2TP_PORT))
l2tp_print(bp, slen);
else if (ISPORT(SYSLOG_PORT))
syslog_print(bp, slen);
else if (ISPORT(LMP_PORT))
lmp_print(bp, slen);
else if ((sport >= RX_PORT_LOW && sport <= RX_PORT_HIGH) ||
(dport >= RX_PORT_LOW && dport <= RX_PORT_HIGH))
rx_print(bp, slen, sport, dport);
else if (dport == BFD_CONTROL_PORT || dport == BFD_ECHO_PORT )
bfd_print(bp, slen, dport);
else if (ISPORT(NETBIOS_NS_PORT))
nbt_udp137_print(bp, slen);
else if (ISPORT(NETBIOS_DGRAM_PORT))
nbt_udp138_print(bp, slen);
else if (ISPORT(ISAKMP_PORT))
isakmp_print(bp, slen);
else if (ISPORT(ISAKMP_PORT_NATT))
isakmp_rfc3948_print(bp, slen);
else if (ISPORT(ISAKMP_PORT_USER1) || ISPORT(ISAKMP_PORT_USER2))
isakmp_print(bp, slen);
else {
int elen = 0;
parser->eflag = ArgusThisEflag;
elen = ArgusEncode (parser, (const char *)bp, NULL, slen, ArgusBuf, sizeof(ArgusBuf));
parser->eflag = ARGUS_HEXDUMP;
}
/*
else if (ISPORT(3456))
vat_print(bp, slen);
else if (ISPORT(ZEPHYR_SRV_PORT) || ISPORT(ZEPHYR_CLT_PORT))
zephyr_print(bp, slen);
else if (ISPORT(RIPNG_PORT))
ripng_print(bp, slen);
else if (ISPORT(DHCP6_SERV_PORT) || ISPORT(DHCP6_CLI_PORT))
dhcp6_print(bp, slen);
else if (dport == 4567)
wb_print(bp, slen);
else if (ISPORT(CISCO_AUTORP_PORT))
cisco_autorp_print(bp, slen);
else if (ISPORT(RADIUS_PORT) || ISPORT(RADIUS_NEW_PORT) ||
ISPORT(RADIUS_ACCOUNTING_PORT) || ISPORT(RADIUS_NEW_ACCOUNTING_PORT) )
radius_print(bp, slen);
else if (dport == HSRP_PORT)
hsrp_print(bp, slen);
else if (ISPORT(LWRES_PORT))
lwres_print(bp, slen);
else if (ISPORT(MPLS_LSP_PING_PORT))
lspping_print(bp, slen);
*/
}
}
}
return (ArgusBuf);
}
int RaSendArgusRecord(struct ArgusRecordStruct *argus) {return 0;}
void ArgusWindowClose(void);
void ArgusWindowClose(void) {
#ifdef ARGUSDEBUG
ArgusDebug (6, "ArgusWindowClose () returning\n");
#endif
}
/*
* Print out a null-terminated filename (or other ascii string).
* If ep is NULL, assume no truncation check is needed.
* Return true if truncated.
*/
int
fn_print(register const u_char *s, register const u_char *ep, char *buf)
{
register int ret;
register u_char c;
ret = 1; /* assume truncated */
while (ep == NULL || s < ep) {
c = *s++;
if (c == '\0') {
ret = 0;
break;
}
if (!isascii(c)) {
c = toascii(c);
sprintf(&buf[strlen(buf)], "%c", 'M');
sprintf(&buf[strlen(buf)], "%c", '-');
}
if (!isprint(c)) {
c ^= 0x40; /* DEL to ?, others to alpha */
sprintf(&buf[strlen(buf)], "%c", '^');
}
sprintf(&buf[strlen(buf)], "%c", c);
}
return(ret);
}
/*
* Print out a counted filename (or other ascii string).
* If ep is NULL, assume no truncation check is needed.
* Return true if truncated.
*/
int
fn_printn(register const u_char *s, register u_int n,
register const u_char *ep, char *buf)
{
register u_char c;
while (n > 0 && (ep == NULL || s < ep)) {
n--;
c = *s++;
if (!isascii(c)) {
c = toascii(c);
sprintf(&buf[strlen(buf)], "%c", 'M');
sprintf(&buf[strlen(buf)], "%c", '-');
}
if (!isprint(c)) {
c ^= 0x40; /* DEL to ?, others to alpha */
sprintf(&buf[strlen(buf)], "%c", '^');
}
sprintf(&buf[strlen(buf)], "%c", c);
}
return (n == 0) ? 0 : 1;
}
/*
* Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <extract.h>
#include <stdio.h>
#include <string.h>
/*
* Convert a token value to a string; use "fmt" if not found.
const char *
tok2str(const struct tok *lp, const char *fmt, int v)
{
static char buf[128];
while (lp->s != NULL) {
if (lp->v == v)
return (lp->s);
++lp;
}
if (fmt == NULL)
fmt = "#%d";
(void)snprintf(buf, sizeof(buf), fmt, v);
return (buf);
}
*/
/*
* Convert a token value to a string; use "fmt" if not found.
*/
const char *
tok2strbuf(register const struct tok *lp, register const char *fmt,
register int v, char *buf, size_t bufsize)
{
if (lp != NULL) {
while (lp->s != NULL) {
if (lp->v == v)
return (lp->s);
++lp;
}
}
if (fmt == NULL)
fmt = "#%d";
(void)snprintf(buf, bufsize, fmt, v);
return (const char *)buf;
}
/*
* Convert a 32-bit netmask to prefixlen if possible
* the function returns the prefix-len; if plen == -1
* then conversion was not possible;
*/
int mask2plen (u_int32_t);
int
mask2plen (u_int32_t mask)
{
u_int32_t bitmasks[33] = {
0x00000000,
0x80000000, 0xc0000000, 0xe0000000, 0xf0000000,
0xf8000000, 0xfc000000, 0xfe000000, 0xff000000,
0xff800000, 0xffc00000, 0xffe00000, 0xfff00000,
0xfff80000, 0xfffc0000, 0xfffe0000, 0xffff0000,
0xffff8000, 0xffffc000, 0xffffe000, 0xfffff000,
0xfffff800, 0xfffffc00, 0xfffffe00, 0xffffff00,
0xffffff80, 0xffffffc0, 0xffffffe0, 0xfffffff0,
0xfffffff8, 0xfffffffc, 0xfffffffe, 0xffffffff
};
int prefix_len = 32;
/* let's see if we can transform the mask into a prefixlen */
while (prefix_len >= 0) {
if (bitmasks[prefix_len] == mask)
break;
prefix_len--;
}
return (prefix_len);
}
|
hbock/argus-clients
|
radump/radump.c
|
C
|
gpl-2.0
| 21,787
|
power_supply-objs := power_supply_core.o
ifeq ($(CONFIG_SYSFS),y)
power_supply-objs += power_supply_sysfs.o
endif
ifeq ($(CONFIG_LEDS_TRIGGERS),y)
power_supply-objs += power_supply_leds.o
endif
ifeq ($(CONFIG_POWER_SUPPLY_DEBUG),y)
EXTRA_CFLAGS += -DDEBUG
endif
obj-$(CONFIG_POWER_SUPPLY) += power_supply.o
obj-$(CONFIG_PDA_POWER) += pda_power.o
obj-$(CONFIG_APM_POWER) += apm_power.o
obj-$(CONFIG_WM831X_POWER) += wm831x_power.o
obj-$(CONFIG_WM8350_POWER) += wm8350_power.o
obj-$(CONFIG_BATTERY_DS2760) += ds2760_battery.o
obj-$(CONFIG_BATTERY_DS2782) += ds2782_battery.o
obj-$(CONFIG_BATTERY_DS2784) += ds2784_battery.o
obj-$(CONFIG_BATTERY_PMU) += pmu_battery.o
obj-$(CONFIG_BATTERY_OLPC) += olpc_battery.o
obj-$(CONFIG_BATTERY_TOSA) += tosa_battery.o
obj-$(CONFIG_BATTERY_WM97XX) += wm97xx_battery.o
obj-$(CONFIG_BATTERY_BQ27x00) += bq27x00_battery.o
obj-$(CONFIG_BATTERY_DA9030) += da9030_battery.o
obj-$(CONFIG_BATTERY_MAX17040) += max17040_battery.o
obj-$(CONFIG_CHARGER_PCF50633) += pcf50633-charger.o
obj-$(CONFIG_BATTERY_MSM) += msm_battery.o
# Eric Liu+
obj-$(CONFIG_BATTERY_QSD) += qsd_battery.o
# Eric Liu-
|
DJSteve/StreakKernel
|
drivers/power/Makefile
|
Makefile
|
gpl-2.0
| 1,129
|
#include "yacss/CSSBaseValue.hh"
namespace yacss {
std::ostream& operator<< (std::ostream& o, const CSSBaseValue& val)
{
if (val.type == ValueType::Length)
o << val.get<LengthValue>();
else if (val.type == ValueType::Keyword)
o << val.get<KeywordValue>();
else if (val.type == ValueType::ColorRGBA)
o << val.get<ColorRGBAValue>();
else
throw std::runtime_error("CSSBaseValue << : Unknown Type.");
return o;
}
}; // ! ns yacss
|
cirocosta/yacss-parser
|
src/CSSBaseValue.cc
|
C++
|
gpl-2.0
| 456
|
<?php
/****************************************************** Open .node ***
* Description:
* Status: Stable.
* Author: Alexandre Dath <alexandre@dotnode.com>
* $Id$
*
* Copyright (C) 2005 Alexandre Dath <alexandre@dotnode.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
******************** http://opensource.ikse.net/projects/dotnode ***/
define('INCLUDEPATH',BASEPATH.'/../inc');
define('ACTIONSPATH',BASEPATH.'/../actions');
define('RESPONSESPATH',BASEPATH.'/../responses');
define('CODEPIX_PATH',BASEPATH.'/../codepix');
ini_set('session.name','dotnodeSessID');
ini_set('session.save_path',BASEPATH.'/../sessions');
include(INCLUDESPATH.'/session_save_handler.inc.php');
session_set_save_handler ("_sess_open", "_sess_close", "_sess_read", "_sess_write", "_sess_destroy", "_sess_gc");
?>
|
alex-ikse/dotnode
|
includes/config/global.inc.php
|
PHP
|
gpl-2.0
| 1,501
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef MEDIA_BASE_YUV_CONVERT_H_
#define MEDIA_BASE_YUV_CONVERT_H_
#include "base/basictypes.h"
#include "media/base/media_export.h"
#if defined(ARCH_CPU_X86_FAMILY) && \
!(defined(ARCH_CPU_X86_64) && defined(COMPILER_MSVC))
#define MEDIA_MMX_INTRINSICS_AVAILABLE
#endif
namespace media {
enum YUVType {
YV16 = 0,
YV12 = 1,
};
enum Rotate {
ROTATE_0,
ROTATE_90,
ROTATE_180,
ROTATE_270,
MIRROR_ROTATE_0,
MIRROR_ROTATE_90,
MIRROR_ROTATE_180,
MIRROR_ROTATE_270,
};
enum ScaleFilter {
FILTER_NONE = 0,
FILTER_BILINEAR_H = 1,
FILTER_BILINEAR_V = 2,
FILTER_BILINEAR = 3,
};
MEDIA_EXPORT void InitializeCPUSpecificYUVConversions();
MEDIA_EXPORT void ConvertYUVToRGB32(const uint8* yplane,
const uint8* uplane,
const uint8* vplane,
uint8* rgbframe,
int width,
int height,
int ystride,
int uvstride,
int rgbstride,
YUVType yuv_type);
MEDIA_EXPORT void ConvertYUVAToARGB(const uint8* yplane,
const uint8* uplane,
const uint8* vplane,
const uint8* aplane,
uint8* rgbframe,
int width,
int height,
int ystride,
int uvstride,
int astride,
int rgbstride,
YUVType yuv_type);
MEDIA_EXPORT void ScaleYUVToRGB32(const uint8* yplane,
const uint8* uplane,
const uint8* vplane,
uint8* rgbframe,
int source_width,
int source_height,
int width,
int height,
int ystride,
int uvstride,
int rgbstride,
YUVType yuv_type,
Rotate view_rotate,
ScaleFilter filter);
MEDIA_EXPORT void ScaleYUVToRGB32WithRect(const uint8* yplane,
const uint8* uplane,
const uint8* vplane,
uint8* rgbframe,
int source_width,
int source_height,
int dest_width,
int dest_height,
int dest_rect_left,
int dest_rect_top,
int dest_rect_right,
int dest_rect_bottom,
int ystride,
int uvstride,
int rgbstride);
MEDIA_EXPORT void ConvertRGB32ToYUV(const uint8* rgbframe,
uint8* yplane,
uint8* uplane,
uint8* vplane,
int width,
int height,
int rgbstride,
int ystride,
int uvstride);
MEDIA_EXPORT void ConvertRGB24ToYUV(const uint8* rgbframe,
uint8* yplane,
uint8* uplane,
uint8* vplane,
int width,
int height,
int rgbstride,
int ystride,
int uvstride);
MEDIA_EXPORT void ConvertYUY2ToYUV(const uint8* src,
uint8* yplane,
uint8* uplane,
uint8* vplane,
int width,
int height);
MEDIA_EXPORT void ConvertNV21ToYUV(const uint8* src,
uint8* yplane,
uint8* uplane,
uint8* vplane,
int width,
int height);
MEDIA_EXPORT void EmptyRegisterState();
}
#endif
|
qtekfun/htcDesire820Kernel
|
external/chromium_org/media/base/yuv_convert.h
|
C
|
gpl-2.0
| 5,255
|
using System;
using Server.Items;
using Server.Targeting;
namespace Server.Engines.Craft
{
public enum SmeltResult
{
Success,
Invalid,
NoSkill
}
public class Resmelt
{
public Resmelt()
{
}
public static void Do(Mobile from, CraftSystem craftSystem, ITool tool)
{
int num = craftSystem.CanCraft(from, tool, null);
if (num > 0 && num != 1044267)
{
from.SendGump(new CraftGump(from, craftSystem, tool, num));
}
else
{
from.Target = new InternalTarget(craftSystem, tool);
from.SendLocalizedMessage(1044273); // Target an item to recycle.
}
}
private class InternalTarget : Target
{
private readonly CraftSystem m_CraftSystem;
private readonly ITool m_Tool;
public InternalTarget(CraftSystem craftSystem, ITool tool)
: base(2, false, TargetFlags.None)
{
m_CraftSystem = craftSystem;
m_Tool = tool;
}
protected override void OnTarget(Mobile from, object targeted)
{
int num = m_CraftSystem.CanCraft(from, m_Tool, null);
if (num > 0)
{
if (num == 1044267)
{
bool anvil, forge;
DefBlacksmithy.CheckAnvilAndForge(from, 2, out anvil, out forge);
if (!anvil)
num = 1044266; // You must be near an anvil
else if (!forge)
num = 1044265; // You must be near a forge.
}
from.SendGump(new CraftGump(from, m_CraftSystem, m_Tool, num));
}
else
{
SmeltResult result = SmeltResult.Invalid;
bool isStoreBought = false;
int message;
if (targeted is BaseArmor)
{
result = Resmelt(from, (BaseArmor)targeted, ((BaseArmor)targeted).Resource);
isStoreBought = !((BaseArmor)targeted).PlayerConstructed;
}
else if (targeted is BaseWeapon)
{
result = Resmelt(from, (BaseWeapon)targeted, ((BaseWeapon)targeted).Resource);
isStoreBought = !((BaseWeapon)targeted).PlayerConstructed;
}
else if (targeted is DragonBardingDeed)
{
result = Resmelt(from, (DragonBardingDeed)targeted, ((DragonBardingDeed)targeted).Resource);
isStoreBought = false;
}
switch ( result )
{
default:
case SmeltResult.Invalid:
message = 1044272;
break; // You can't melt that down into ingots.
case SmeltResult.NoSkill:
message = 1044269;
break; // You have no idea how to work this metal.
case SmeltResult.Success:
message = isStoreBought ? 500418 : 1044270;
break; // You melt the item down into ingots.
}
from.SendGump(new CraftGump(from, m_CraftSystem, m_Tool, message));
}
}
private SmeltResult Resmelt(Mobile from, Item item, CraftResource resource)
{
try
{
if (CraftResources.GetType(resource) != CraftResourceType.Metal)
return SmeltResult.Invalid;
CraftResourceInfo info = CraftResources.GetInfo(resource);
if (info == null || info.ResourceTypes.Length == 0)
return SmeltResult.Invalid;
CraftItem craftItem = m_CraftSystem.CraftItems.SearchFor(item.GetType());
if (craftItem == null || craftItem.Resources.Count == 0)
return SmeltResult.Invalid;
CraftRes craftResource = craftItem.Resources.GetAt(0);
if (craftResource.Amount < 2)
return SmeltResult.Invalid; // Not enough metal to resmelt
double difficulty = 0.0;
switch ( resource )
{
case CraftResource.DullCopper:
difficulty = 65.0;
break;
case CraftResource.ShadowIron:
difficulty = 70.0;
break;
case CraftResource.Copper:
difficulty = 75.0;
break;
case CraftResource.Bronze:
difficulty = 80.0;
break;
case CraftResource.Gold:
difficulty = 85.0;
break;
case CraftResource.Agapite:
difficulty = 90.0;
break;
case CraftResource.Verite:
difficulty = 95.0;
break;
case CraftResource.Valorite:
difficulty = 99.0;
break;
}
double skill = Math.Max(from.Skills[SkillName.Mining].Value, from.Skills[SkillName.Blacksmith].Value);
if (difficulty > skill)
return SmeltResult.NoSkill;
Type resourceType = info.ResourceTypes[0];
Item ingot = (Item)Activator.CreateInstance(resourceType);
if (item is DragonBardingDeed || (item is BaseArmor && ((BaseArmor)item).PlayerConstructed) || (item is BaseWeapon && ((BaseWeapon)item).PlayerConstructed) || (item is BaseClothing && ((BaseClothing)item).PlayerConstructed))
ingot.Amount = (int)((double)craftResource.Amount * .66);
else
ingot.Amount = 1;
item.Delete();
from.AddToBackpack(ingot);
from.PlaySound(0x2A);
from.PlaySound(0x240);
return SmeltResult.Success;
}
catch
{
}
return SmeltResult.Invalid;
}
}
}
}
|
kevin-10/ServUO
|
Scripts/Services/Craft/Core/Resmelt.cs
|
C#
|
gpl-2.0
| 6,952
|
/*
* LCD panel driver for Sharp LQ10D368 -- TFT VGA (10.4)
*
* Copyright (C) 2009 Li-Pro.Net
* Author: Stephan Linz <linz@li-pro.net>
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <plat/display.h>
static struct omap_video_timings sharp_lq10d368_timings = {
.x_res = 640,
.y_res = 480,
.pixel_clock = 25180,/* LogicPD: 27000 */
.hsw = 96, /* LogicPD: 48 */
.hfp = 32, /* LogicPD: 24 */
.hbp = 32, /* LogicPD: 135 */
.vsw = 1, /* LogicPD: 1 */
.vfp = 22, /* LogicPD: 34 */
.vbp = 22, /* LogicPD: 34 */
};
static int sharp_lq10d368_panel_probe(struct omap_dss_device *dssdev)
{
dssdev->panel.config = OMAP_DSS_LCD_TFT
| OMAP_DSS_LCD_IVS /* inverted for 480 line mode */
| OMAP_DSS_LCD_IHS; /* inverted for 480 line mode */
dssdev->panel.timings = sharp_lq10d368_timings;
dssdev->panel.acb = 0; /* not used for TFT*/
return 0;
}
static void sharp_lq10d368_panel_remove(struct omap_dss_device *dssdev)
{
}
static int sharp_lq10d368_panel_enable(struct omap_dss_device *dssdev)
{
int r = 0;
if (dssdev->platform_enable)
r = dssdev->platform_enable(dssdev);
return r;
}
static void sharp_lq10d368_panel_disable(struct omap_dss_device *dssdev)
{
if (dssdev->platform_disable)
dssdev->platform_disable(dssdev);
}
static int sharp_lq10d368_panel_suspend(struct omap_dss_device *dssdev)
{
sharp_lq10d368_panel_disable(dssdev);
return 0;
}
static int sharp_lq10d368_panel_resume(struct omap_dss_device *dssdev)
{
return sharp_lq10d368_panel_enable(dssdev);
}
static struct omap_dss_driver sharp_lq10d368_driver = {
.probe = sharp_lq10d368_panel_probe,
.remove = sharp_lq10d368_panel_remove,
.enable = sharp_lq10d368_panel_enable,
.disable = sharp_lq10d368_panel_disable,
.suspend = sharp_lq10d368_panel_suspend,
.resume = sharp_lq10d368_panel_resume,
.driver = {
.name = "sharp_lq10d368_panel",
.owner = THIS_MODULE,
},
};
static int __init sharp_lq10d368_panel_drv_init(void)
{
return omap_dss_register_driver(&sharp_lq10d368_driver);
}
static void __exit sharp_lq10d368_panel_drv_exit(void)
{
omap_dss_unregister_driver(&sharp_lq10d368_driver);
}
module_init(sharp_lq10d368_panel_drv_init);
module_exit(sharp_lq10d368_panel_drv_exit);
MODULE_LICENSE("GPL");
|
Aircell/asp-kernel
|
drivers/video/omap2/displays/panel-sharp-lq10d368.c
|
C
|
gpl-2.0
| 2,856
|
/*
* Copyright (C) 2009 Kay Sievers <kay@vrfy.org>
* Copyright (c) 2009 Filippo Argiolas <filippo.argiolas@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:
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1
#endif
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <linux/videodev2.h>
#include "util.h"
int main(int argc, char *argv[]) {
static const struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{}
};
_cleanup_close_ int fd = -1;
char *device;
struct v4l2_capability v2cap;
int c;
while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
switch (c) {
case 'h':
printf("%s [-h,--help] <device file>\n\n"
"Video4Linux device identification.\n\n"
" -h Print this message\n"
, program_invocation_short_name);
return 0;
case '?':
return -EINVAL;
default:
assert_not_reached("Unhandled option");
}
device = argv[optind];
if (device == NULL)
return 2;
fd = open(device, O_RDONLY);
if (fd < 0)
return 3;
if (ioctl(fd, VIDIOC_QUERYCAP, &v2cap) == 0) {
printf("ID_V4L_VERSION=2\n");
printf("ID_V4L_PRODUCT=%s\n", v2cap.card);
printf("ID_V4L_CAPABILITIES=:");
if ((v2cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) > 0)
printf("capture:");
if ((v2cap.capabilities & V4L2_CAP_VIDEO_OUTPUT) > 0)
printf("video_output:");
if ((v2cap.capabilities & V4L2_CAP_VIDEO_OVERLAY) > 0)
printf("video_overlay:");
if ((v2cap.capabilities & V4L2_CAP_AUDIO) > 0)
printf("audio:");
if ((v2cap.capabilities & V4L2_CAP_TUNER) > 0)
printf("tuner:");
if ((v2cap.capabilities & V4L2_CAP_RADIO) > 0)
printf("radio:");
printf("\n");
}
return 0;
}
|
gentoo/eudev
|
src/v4l_id/v4l_id.c
|
C
|
gpl-2.0
| 2,940
|
<?php
/**
* Plugin Update Checker Library 2.2.0
* http://w-shadow.com/
*
* Copyright 2015 Janis Elsts
* Released under the MIT license. See license.txt for details.
*/
if ( !class_exists('wcva_PluginUpdateChecker_2_2', false) ):
/**
* A custom plugin update checker.
*
* @author Janis Elsts
* @copyright 2015
* @version 2.2
* @access public
*/
class wcva_PluginUpdateChecker_2_2 {
public $metadataUrl = ''; //The URL of the plugin's metadata file.
public $pluginAbsolutePath = ''; //Full path of the main plugin file.
public $pluginFile = ''; //Plugin filename relative to the plugins directory. Many WP APIs use this to identify plugins.
public $slug = ''; //Plugin slug.
public $checkPeriod = 12; //How often to check for updates (in hours).
public $optionName = ''; //Where to store the update info.
public $muPluginFile = ''; //For MU plugins, the plugin filename relative to the mu-plugins directory.
public $debugMode = false; //Set to TRUE to enable error reporting. Errors are raised using trigger_error()
//and should be logged to the standard PHP error log.
public $throttleRedundantChecks = false; //Check less often if we already know that an update is available.
public $throttledCheckPeriod = 72;
private $cronHook = null;
private $debugBarPlugin = null;
private $cachedInstalledVersion = null;
private $upgradedPluginFile = null; //The plugin that is currently being upgraded by WordPress.
/**
* Class constructor.
*
* @param string $metadataUrl The URL of the plugin's metadata file.
* @param string $pluginFile Fully qualified path to the main plugin file.
* @param string $slug The plugin's 'slug'. If not specified, the filename part of $pluginFile sans '.php' will be used as the slug.
* @param integer $checkPeriod How often to check for updates (in hours). Defaults to checking every 12 hours. Set to 0 to disable automatic update checks.
* @param string $optionName Where to store book-keeping info about update checks. Defaults to 'external_updates-$slug'.
* @param string $muPluginFile Optional. The plugin filename relative to the mu-plugins directory.
*/
public function __construct($metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = ''){
$this->purchase_url = ''.site_url().'/wp-admin/admin.php?page=wc-settings&tab=products§ion=display#woocommerce_wcva_purchase_code';
$this->is_code_valid = get_option('wcva_activation_status');
$this->metadataUrl = $metadataUrl;
$this->pluginAbsolutePath = $pluginFile;
$this->pluginFile = plugin_basename($this->pluginAbsolutePath);
$this->muPluginFile = $muPluginFile;
$this->checkPeriod = $checkPeriod;
$this->slug = $slug;
$this->optionName = $optionName;
$this->debugMode = defined('WP_DEBUG') && WP_DEBUG;
//If no slug is specified, use the name of the main plugin file as the slug.
//For example, 'my-cool-plugin/cool-plugin.php' becomes 'cool-plugin'.
if ( empty($this->slug) ){
$this->slug = basename($this->pluginFile, '.php');
}
if ( empty($this->optionName) ){
$this->optionName = 'external_updates-' . $this->slug;
}
//Backwards compatibility: If the plugin is a mu-plugin but no $muPluginFile is specified, assume
//it's the same as $pluginFile given that it's not in a subdirectory (WP only looks in the base dir).
if ( empty($this->muPluginFile) && (strpbrk($this->pluginFile, '/\\') === false) && $this->isMuPlugin() ) {
$this->muPluginFile = $this->pluginFile;
}
$this->installHooks();
}
/**
* Install the hooks required to run periodic update checks and inject update info
* into WP data structures.
*
* @return void
*/
protected function installHooks(){
//Override requests for plugin information
add_filter('plugins_api', array($this, 'injectInfo'), 20, 3);
//Insert our update info into the update array maintained by WP
add_filter('site_transient_update_plugins', array($this,'injectUpdate')); //WP 3.0+
add_filter('transient_update_plugins', array($this,'injectUpdate')); //WP 2.8+
add_filter('plugin_row_meta', array($this, 'addCheckForUpdatesLink'), 10, 2);
add_action('admin_init', array($this, 'handleManualCheck'));
add_action('all_admin_notices', array($this, 'displayManualCheckResult'));
//Clear the version number cache when something - anything - is upgraded or WP clears the update cache.
add_filter('upgrader_post_install', array($this, 'clearCachedVersion'));
add_action('delete_site_transient_update_plugins', array($this, 'clearCachedVersion'));
//Set up the periodic update checks
$this->cronHook = 'check_plugin_updates-' . $this->slug;
if ( $this->checkPeriod > 0 ){
//Trigger the check via Cron.
//Try to use one of the default schedules if possible as it's less likely to conflict
//with other plugins and their custom schedules.
$defaultSchedules = array(
1 => 'hourly',
12 => 'twicedaily',
24 => 'daily',
);
if ( array_key_exists($this->checkPeriod, $defaultSchedules) ) {
$scheduleName = $defaultSchedules[$this->checkPeriod];
} else {
//Use a custom cron schedule.
$scheduleName = 'every' . $this->checkPeriod . 'hours';
add_filter('cron_schedules', array($this, '_addCustomSchedule'));
}
if ( !wp_next_scheduled($this->cronHook) && !defined('WP_INSTALLING') ) {
wp_schedule_event(time(), $scheduleName, $this->cronHook);
}
add_action($this->cronHook, array($this, 'maybeCheckForUpdates'));
register_deactivation_hook($this->pluginFile, array($this, '_removeUpdaterCron'));
//In case Cron is disabled or unreliable, we also manually trigger
//the periodic checks while the user is browsing the Dashboard.
add_action( 'admin_init', array($this, 'maybeCheckForUpdates') );
//Like WordPress itself, we check more often on certain pages.
/** @see wp_update_plugins */
add_action('load-update-core.php', array($this, 'maybeCheckForUpdates'));
add_action('load-plugins.php', array($this, 'maybeCheckForUpdates'));
add_action('load-update.php', array($this, 'maybeCheckForUpdates'));
//This hook fires after a bulk update is complete.
add_action('upgrader_process_complete', array($this, 'maybeCheckForUpdates'), 11, 0);
} else {
//Periodic checks are disabled.
wp_clear_scheduled_hook($this->cronHook);
}
if ( did_action('plugins_loaded') ) {
$this->initDebugBarPanel();
} else {
add_action('plugins_loaded', array($this, 'initDebugBarPanel'));
}
//Rename the update directory to be the same as the existing directory.
add_filter('upgrader_source_selection', array($this, 'fixDirectoryName'), 10, 3);
//Keep track of which plugin WordPress is currently upgrading.
add_filter('upgrader_pre_install', array($this, 'setUpgradedPlugin'), 10, 2);
add_filter('upgrader_post_install', array($this, 'clearUpgradedPlugin'), 10, 1);
add_action('upgrader_process_complete', array($this, 'clearUpgradedPlugin'), 10, 1);
}
/**
* Add our custom schedule to the array of Cron schedules used by WP.
*
* @param array $schedules
* @return array
*/
public function _addCustomSchedule($schedules){
if ( $this->checkPeriod && ($this->checkPeriod > 0) ){
$scheduleName = 'every' . $this->checkPeriod . 'hours';
$schedules[$scheduleName] = array(
'interval' => $this->checkPeriod * 3600,
'display' => sprintf('Every %d hours', $this->checkPeriod),
);
}
return $schedules;
}
/**
* Remove the scheduled cron event that the library uses to check for updates.
*
* @return void
*/
public function _removeUpdaterCron(){
wp_clear_scheduled_hook($this->cronHook);
}
/**
* Get the name of the update checker's WP-cron hook. Mostly useful for debugging.
*
* @return string
*/
public function getCronHookName() {
return $this->cronHook;
}
/**
* Retrieve plugin info from the configured API endpoint.
*
* @uses wp_remote_get()
*
* @param array $queryArgs Additional query arguments to append to the request. Optional.
* @return PluginInfo
*/
public function requestInfo($queryArgs = array()){
//Query args to append to the URL. Plugins can add their own by using a filter callback (see addQueryArgFilter()).
$installedVersion = $this->getInstalledVersion();
$queryArgs['installed_version'] = ($installedVersion !== null) ? $installedVersion : '';
$queryArgs = apply_filters('puc_request_info_query_args-'.$this->slug, $queryArgs);
//Various options for the wp_remote_get() call. Plugins can filter these, too.
$options = array(
'timeout' => 10, //seconds
'headers' => array(
'Accept' => 'application/json'
),
);
$options = apply_filters('puc_request_info_options-'.$this->slug, $options);
//The plugin info should be at 'http://your-api.com/url/here/$slug/info.json'
$url = $this->metadataUrl;
if ( !empty($queryArgs) ){
$url = add_query_arg($queryArgs, $url);
}
$result = wp_remote_get(
$url,
$options
);
//Try to parse the response
$pluginInfo = null;
if ( !is_wp_error($result) && isset($result['response']['code']) && ($result['response']['code'] == 200) && !empty($result['body']) ){
$pluginInfo = wcva_PluginInfo_2_2::fromJson($result['body'], $this->debugMode);
$pluginInfo->filename = $this->pluginFile;
$pluginInfo->slug = $this->slug;
} else if ( $this->debugMode ) {
$message = sprintf("The URL %s does not point to a valid plugin metadata file. ", $url);
if ( is_wp_error($result) ) {
$message .= "WP HTTP error: " . $result->get_error_message();
} else if ( isset($result['response']['code']) ) {
$message .= "HTTP response code is " . $result['response']['code'] . " (expected: 200)";
} else {
$message .= "wp_remote_get() returned an unexpected result.";
}
trigger_error($message, E_USER_WARNING);
}
$pluginInfo = apply_filters('puc_request_info_result-'.$this->slug, $pluginInfo, $result);
return $pluginInfo;
}
/**
* Retrieve the latest update (if any) from the configured API endpoint.
*
* @uses PluginUpdateChecker::requestInfo()
*
* @return PluginUpdate An instance of PluginUpdate, or NULL when no updates are available.
*/
public function requestUpdate(){
//For the sake of simplicity, this function just calls requestInfo()
//and transforms the result accordingly.
$pluginInfo = $this->requestInfo(array('checking_for_updates' => '1'));
if ( $pluginInfo == null ){
return null;
}
return wcva_PluginUpdate_2_2::fromPluginInfo($pluginInfo);
}
/**
* Get the currently installed version of the plugin.
*
* @return string Version number.
*/
public function getInstalledVersion(){
if ( isset($this->cachedInstalledVersion) ) {
return $this->cachedInstalledVersion;
}
$pluginHeader = $this->getPluginHeader();
if ( isset($pluginHeader['Version']) ) {
$this->cachedInstalledVersion = $pluginHeader['Version'];
return $pluginHeader['Version'];
} else {
//This can happen if the filename points to something that is not a plugin.
if ( $this->debugMode ) {
trigger_error(
sprintf(
"Can't to read the Version header for '%s'. The filename is incorrect or is not a plugin.",
$this->pluginFile
),
E_USER_WARNING
);
}
return null;
}
}
/**
* Get plugin's metadata from its file header.
*
* @return array
*/
protected function getPluginHeader() {
if ( !is_file($this->pluginAbsolutePath) ) {
//This can happen if the plugin filename is wrong.
if ( $this->debugMode ) {
trigger_error(
sprintf(
"Can't to read the plugin header for '%s'. The file does not exist.",
$this->pluginFile
),
E_USER_WARNING
);
}
return array();
}
if ( !function_exists('get_plugin_data') ){
require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
}
return get_plugin_data($this->pluginAbsolutePath, false, false);
}
/**
* Check for plugin updates.
* The results are stored in the DB option specified in $optionName.
*
* @return PluginUpdate|null
*/
public function checkForUpdates(){
wcva_verify_envato_purchase_code();
$installedVersion = $this->getInstalledVersion();
//Fail silently if we can't find the plugin or read its header.
if ( $installedVersion === null ) {
if ( $this->debugMode ) {
trigger_error(
sprintf('Skipping update check for %s - installed version unknown.', $this->pluginFile),
E_USER_WARNING
);
}
return null;
}
$state = $this->getUpdateState();
if ( empty($state) ){
$state = new StdClass;
$state->lastCheck = 0;
$state->checkedVersion = '';
$state->update = null;
}
$state->lastCheck = time();
$state->checkedVersion = $installedVersion;
$this->setUpdateState($state); //Save before checking in case something goes wrong
$state->update = $this->requestUpdate();
$this->setUpdateState($state);
return $this->getUpdate();
}
/**
* Check for updates if the configured check interval has already elapsed.
* Will use a shorter check interval on certain admin pages like "Dashboard -> Updates" or when doing cron.
*
* You can override the default behaviour by using the "puc_check_now-$slug" filter.
* The filter callback will be passed three parameters:
* - Current decision. TRUE = check updates now, FALSE = don't check now.
* - Last check time as a Unix timestamp.
* - Configured check period in hours.
* Return TRUE to check for updates immediately, or FALSE to cancel.
*
* This method is declared public because it's a hook callback. Calling it directly is not recommended.
*/
public function maybeCheckForUpdates(){
if ( empty($this->checkPeriod) ){
return;
}
$currentFilter = current_filter();
if ( in_array($currentFilter, array('load-update-core.php', 'upgrader_process_complete')) ) {
//Check more often when the user visits "Dashboard -> Updates" or does a bulk update.
$timeout = 60;
} else if ( in_array($currentFilter, array('load-plugins.php', 'load-update.php')) ) {
//Also check more often on the "Plugins" page and /wp-admin/update.php.
$timeout = 3600;
} else if ( $this->throttleRedundantChecks && ($this->getUpdate() !== null) ) {
//Check less frequently if it's already known that an update is available.
$timeout = $this->throttledCheckPeriod * 3600;
} else if ( defined('DOING_CRON') && constant('DOING_CRON') ) {
//WordPress cron schedules are not exact, so lets do an update check even
//if slightly less than $checkPeriod hours have elapsed since the last check.
$cronFuzziness = 20 * 60;
$timeout = $this->checkPeriod * 3600 - $cronFuzziness;
} else {
$timeout = $this->checkPeriod * 3600;
}
$state = $this->getUpdateState();
$shouldCheck =
empty($state) ||
!isset($state->lastCheck) ||
( (time() - $state->lastCheck) >= $timeout );
//Let plugin authors substitute their own algorithm.
$shouldCheck = apply_filters(
'puc_check_now-' . $this->slug,
$shouldCheck,
(!empty($state) && isset($state->lastCheck)) ? $state->lastCheck : 0,
$this->checkPeriod
);
if ( $shouldCheck ){
$this->checkForUpdates();
}
}
/**
* Load the update checker state from the DB.
*
* @return StdClass|null
*/
public function getUpdateState() {
$state = get_site_option($this->optionName, null);
if ( empty($state) || !is_object($state)) {
$state = null;
}
if ( !empty($state) && isset($state->update) && is_object($state->update) ){
$state->update = wcva_PluginUpdate_2_2::fromObject($state->update);
}
return $state;
}
/**
* Persist the update checker state to the DB.
*
* @param StdClass $state
* @return void
*/
private function setUpdateState($state) {
if ( isset($state->update) && is_object($state->update) && method_exists($state->update, 'toStdClass') ) {
$update = $state->update; /** @var PluginUpdate $update */
$state->update = $update->toStdClass();
}
update_site_option($this->optionName, $state);
}
/**
* Reset update checker state - i.e. last check time, cached update data and so on.
*
* Call this when your plugin is being uninstalled, or if you want to
* clear the update cache.
*/
public function resetUpdateState() {
delete_site_option($this->optionName);
}
/**
* Intercept plugins_api() calls that request information about our plugin and
* use the configured API endpoint to satisfy them.
*
* @see plugins_api()
*
* @param mixed $result
* @param string $action
* @param array|object $args
* @return mixed
*/
public function injectInfo($result, $action = null, $args = null){
$relevant = ($action == 'plugin_information') && isset($args->slug) && (
($args->slug == $this->slug) || ($args->slug == dirname($this->pluginFile))
);
if ( !$relevant ){
return $result;
}
$pluginInfo = $this->requestInfo();
$pluginInfo = apply_filters('puc_pre_inject_info-' . $this->slug, $pluginInfo);
if ($pluginInfo){
return $pluginInfo->toWpFormat();
}
return $result;
}
/**
* Insert the latest update (if any) into the update list maintained by WP.
*
* @param StdClass $updates Update list.
* @return StdClass Modified update list.
*/
public function injectUpdate($updates){
//Is there an update to insert?
$update = $this->getUpdate();
//No update notifications for mu-plugins unless explicitly enabled. The MU plugin file
//is usually different from the main plugin file so the update wouldn't show up properly anyway.
if ( !empty($update) && empty($this->muPluginFile) && $this->isMuPlugin() ) {
$update = null;
}
if ( !empty($update) ) {
//Let plugins filter the update info before it's passed on to WordPress.
$update = apply_filters('puc_pre_inject_update-' . $this->slug, $update);
if ( !is_object($updates) ) {
$updates = new StdClass();
$updates->response = array();
}
$wpUpdate = $update->toWpFormat();
$pluginFile = $this->pluginFile;
if ( $this->isMuPlugin() ) {
//WP does not support automatic update installation for mu-plugins, but we can still display a notice.
$wpUpdate->package = null;
$pluginFile = $this->muPluginFile;
}
$updates->response[$pluginFile] = $wpUpdate;
} else if ( isset($updates, $updates->response) ) {
unset($updates->response[$this->pluginFile]);
if ( !empty($this->muPluginFile) ) {
unset($updates->response[$this->muPluginFile]);
}
}
return $updates;
}
/**
* Rename the update directory to match the existing plugin directory.
*
* When WordPress installs a plugin or theme update, it assumes that the ZIP file will contain
* exactly one directory, and that the directory name will be the same as the directory where
* the plugin/theme is currently installed.
*
* GitHub and other repositories provide ZIP downloads, but they often use directory names like
* "project-branch" or "project-tag-hash". We need to change the name to the actual plugin folder.
*
* @param string $source The directory to copy to /wp-content/plugins. Usually a subdirectory of $remoteSource.
* @param string $remoteSource WordPress has extracted the update to this directory.
* @param WP_Upgrader $upgrader
* @return string|WP_Error
*/
function fixDirectoryName($source, $remoteSource, $upgrader) {
global $wp_filesystem; /** @var WP_Filesystem_Base $wp_filesystem */
//Basic sanity checks.
if ( !isset($source, $remoteSource, $upgrader, $upgrader->skin, $wp_filesystem) ) {
return $source;
}
//Figure out which plugin is being upgraded.
$pluginFile = null;
$skin = $upgrader->skin;
if ( $skin instanceof Plugin_Upgrader_Skin ) {
if ( isset($skin->plugin) && is_string($skin->plugin) && ($skin->plugin !== '') ) {
$pluginFile = $skin->plugin;
}
} elseif ( isset($skin->plugin_info) && is_array($skin->plugin_info) ) {
//This case is tricky because Bulk_Plugin_Upgrader_Skin (etc) doesn't actually store the plugin
//filename anywhere. Instead, it has the plugin headers in $plugin_info. So the best we can
//do is compare those headers to the headers of installed plugins.
if ( !function_exists('get_plugins') ){
require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
}
$installedPlugins = get_plugins();
$matches = array();
foreach($installedPlugins as $pluginBasename => $headers) {
$diff1 = array_diff_assoc($headers, $skin->plugin_info);
$diff2 = array_diff_assoc($skin->plugin_info, $headers);
if ( empty($diff1) && empty($diff2) ) {
$matches[] = $pluginBasename;
}
}
//It's possible (though very unlikely) that there could be two plugins with identical
//headers. In that case, we can't unambiguously identify the plugin that's being upgraded.
if ( count($matches) !== 1 ) {
return $source;
}
$pluginFile = reset($matches);
} elseif ( !empty($this->upgradedPluginFile) ) {
$pluginFile = $this->upgradedPluginFile;
}
//If WordPress is upgrading anything other than our plugin, leave the directory name unchanged.
if ( empty($pluginFile) || ($pluginFile !== $this->pluginFile) ) {
return $source;
}
//Rename the source to match the existing plugin directory.
$pluginDirectoryName = dirname($this->pluginFile);
if ( ($pluginDirectoryName === '.') || ($pluginDirectoryName === '/') ) {
return $source;
}
$correctedSource = trailingslashit($remoteSource) . $pluginDirectoryName . '/';
if ( $source !== $correctedSource ) {
//The update archive should contain a single directory that contains the rest of plugin files. Otherwise,
//WordPress will try to copy the entire working directory ($source == $remoteSource). We can't rename
//$remoteSource because that would break WordPress code that cleans up temporary files after update.
$sourceFiles = $wp_filesystem->dirlist($remoteSource);
if ( is_array($sourceFiles) ) {
$sourceFiles = array_keys($sourceFiles);
$firstFilePath = trailingslashit($remoteSource) . $sourceFiles[0];
if ( (count($sourceFiles) > 1) || (!$wp_filesystem->is_dir($firstFilePath)) ) {
return new WP_Error(
'puc-incorrect-directory-structure',
sprintf(
'The directory structure of the update is incorrect. All plugin files should be inside ' .
'a directory named <span class="code">%s</span>, not at the root of the ZIP file.',
htmlentities($this->slug)
)
);
}
}
$upgrader->skin->feedback(sprintf(
'Renaming %s to %s…',
'<span class="code">' . basename($source) . '</span>',
'<span class="code">' . $pluginDirectoryName . '</span>'
));
if ( $wp_filesystem->move($source, $correctedSource, true) ) {
$upgrader->skin->feedback('Plugin directory successfully renamed.');
return $correctedSource;
} else {
return new WP_Error(
'puc-rename-failed',
'Unable to rename the update to match the existing plugin directory.'
);
}
}
return $source;
}
/**
* @access private
*
* @param mixed $input
* @param array $hookExtra
* @return mixed Returns $input unaltered.
*/
public function setUpgradedPlugin($input, $hookExtra) {
if (!empty($hookExtra['plugin']) && is_string($hookExtra['plugin'])) {
$this->upgradedPluginFile = $hookExtra['plugin'];
} else {
$this->upgradedPluginFile = null;
}
return $input;
}
/**
* @access private
*
* @param mixed $input
* @return mixed Returns $input unaltered.
*/
public function clearUpgradedPlugin($input = null) {
$this->upgradedPluginFile = null;
return $input;
}
/**
* Get the details of the currently available update, if any.
*
* If no updates are available, or if the last known update version is below or equal
* to the currently installed version, this method will return NULL.
*
* Uses cached update data. To retrieve update information straight from
* the metadata URL, call requestUpdate() instead.
*
* @return PluginUpdate|null
*/
public function getUpdate() {
$state = $this->getUpdateState(); /** @var StdClass $state */
//Is there an update available insert?
if ( !empty($state) && isset($state->update) && !empty($state->update) ){
$update = $state->update;
//Check if the update is actually newer than the currently installed version.
$installedVersion = $this->getInstalledVersion();
if ( ($installedVersion !== null) && version_compare($update->version, $installedVersion, '>') ){
$update->filename = $this->pluginFile;
return $update;
}
}
return null;
}
/**
* Add a "Check for updates" link to the plugin row in the "Plugins" page. By default,
* the new link will appear after the "Visit plugin site" link.
*
* You can change the link text by using the "puc_manual_check_link-$slug" filter.
* Returning an empty string from the filter will disable the link.
*
* @param array $pluginMeta Array of meta links.
* @param string $pluginFile
* @return array
*/
public function addCheckForUpdatesLink($pluginMeta, $pluginFile) {
$isRelevant = ($pluginFile == $this->pluginFile)
|| (!empty($this->muPluginFile) && $pluginFile == $this->muPluginFile);
if ( $isRelevant && current_user_can('update_plugins') ) {
$linkUrl = wp_nonce_url(
add_query_arg(
array(
'puc_check_for_updates' => 1,
'puc_slug' => $this->slug,
),
is_network_admin() ? network_admin_url('plugins.php') : admin_url('plugins.php')
),
'puc_check_for_updates'
);
$linkText = apply_filters('puc_manual_check_link-' . $this->slug, 'Check for updates');
if ( !empty($linkText) ) {
$pluginMeta[] = sprintf('<a href="%s">%s</a>', esc_attr($linkUrl), $linkText);
}
}
return $pluginMeta;
}
/**
* Check for updates when the user clicks the "Check for updates" link.
* @see self::addCheckForUpdatesLink()
*
* @return void
*/
public function handleManualCheck() {
$shouldCheck =
isset($_GET['puc_check_for_updates'], $_GET['puc_slug'])
&& $_GET['puc_slug'] == $this->slug
&& current_user_can('update_plugins')
&& check_admin_referer('puc_check_for_updates');
if ( $shouldCheck ) {
$update = $this->checkForUpdates();
$status = ($update === null) ? 'no_update' : 'update_available';
wp_redirect(add_query_arg(
array(
'puc_update_check_result' => $status,
'puc_slug' => $this->slug,
),
is_network_admin() ? network_admin_url('plugins.php') : admin_url('plugins.php')
));
}
}
/**
* Display the results of a manual update check.
* @see self::handleManualCheck()
*
* You can change the result message by using the "puc_manual_check_message-$slug" filter.
*/
public function displayManualCheckResult() {
if ( isset($_GET['puc_update_check_result'], $_GET['puc_slug']) && ($_GET['puc_slug'] == $this->slug) ) {
$status = strval($_GET['puc_update_check_result']);
if ( $status == 'no_update' ) {
$message = 'This plugin is up to date.';
} else if ( $status == 'update_available' ) {
if (($this->is_code_valid) == "active") {
$message = 'A new version of this plugin is available';
} else {
$message= sprintf(
'A new version of woocommerce color or image variation swatches plugin is available. Please enter valid <a href="%s"><span> purchase code</span></a> to get the update.',
$this->purchase_url
);
}
} else {
$message = sprintf('Unknown update checker status "%s"', htmlentities($status));
}
printf(
'<div class="updated"><p>%s</p></div>',
apply_filters('puc_manual_check_message-' . $this->slug, $message, $status)
);
}
}
/**
* Check if the plugin file is inside the mu-plugins directory.
*
* @return bool
*/
protected function isMuPlugin() {
static $cachedResult = null;
if ( $cachedResult === null ) {
//Convert both paths to the canonical form before comparison.
$muPluginDir = realpath(WPMU_PLUGIN_DIR);
$pluginPath = realpath($this->pluginAbsolutePath);
$cachedResult = (strpos($pluginPath, $muPluginDir) === 0);
}
return $cachedResult;
}
/**
* Clear the cached plugin version. This method can be set up as a filter (hook) and will
* return the filter argument unmodified.
*
* @param mixed $filterArgument
* @return mixed
*/
public function clearCachedVersion($filterArgument = null) {
$this->cachedInstalledVersion = null;
return $filterArgument;
}
/**
* Register a callback for filtering query arguments.
*
* The callback function should take one argument - an associative array of query arguments.
* It should return a modified array of query arguments.
*
* @uses add_filter() This method is a convenience wrapper for add_filter().
*
* @param callable $callback
* @return void
*/
public function addQueryArgFilter($callback){
add_filter('puc_request_info_query_args-'.$this->slug, $callback);
}
/**
* Register a callback for filtering arguments passed to wp_remote_get().
*
* The callback function should take one argument - an associative array of arguments -
* and return a modified array or arguments. See the WP documentation on wp_remote_get()
* for details on what arguments are available and how they work.
*
* @uses add_filter() This method is a convenience wrapper for add_filter().
*
* @param callable $callback
* @return void
*/
public function addHttpRequestArgFilter($callback){
add_filter('puc_request_info_options-'.$this->slug, $callback);
}
/**
* Register a callback for filtering the plugin info retrieved from the external API.
*
* The callback function should take two arguments. If the plugin info was retrieved
* successfully, the first argument passed will be an instance of PluginInfo. Otherwise,
* it will be NULL. The second argument will be the corresponding return value of
* wp_remote_get (see WP docs for details).
*
* The callback function should return a new or modified instance of PluginInfo or NULL.
*
* @uses add_filter() This method is a convenience wrapper for add_filter().
*
* @param callable $callback
* @return void
*/
public function addResultFilter($callback){
add_filter('puc_request_info_result-'.$this->slug, $callback, 10, 2);
}
/**
* Register a callback for one of the update checker filters.
*
* Identical to add_filter(), except it automatically adds the "puc_" prefix
* and the "-$plugin_slug" suffix to the filter name. For example, "request_info_result"
* becomes "puc_request_info_result-your_plugin_slug".
*
* @param string $tag
* @param callable $callback
* @param int $priority
* @param int $acceptedArgs
*/
public function addFilter($tag, $callback, $priority = 10, $acceptedArgs = 1) {
add_filter('puc_' . $tag . '-' . $this->slug, $callback, $priority, $acceptedArgs);
}
/**
* Initialize the update checker Debug Bar plugin/add-on thingy.
*/
public function initDebugBarPanel() {
$debugBarPlugin = dirname(__FILE__) . '/debug-bar-plugin.php';
if ( class_exists('Debug_Bar', false) && file_exists($debugBarPlugin) ) {
require_once $debugBarPlugin;
$this->debugBarPlugin = new PucDebugBarPlugin($this);
}
}
}
endif;
if ( !class_exists('wcva_PluginInfo_2_2', false) ):
/**
* A container class for holding and transforming various plugin metadata.
*
* @author Janis Elsts
* @copyright 2015
* @version 2.2
* @access public
*/
class wcva_PluginInfo_2_2 {
//Most fields map directly to the contents of the plugin's info.json file.
//See the relevant docs for a description of their meaning.
public $name;
public $slug;
public $version;
public $homepage;
public $sections;
public $banners;
public $download_url;
public $author;
public $author_homepage;
public $requires;
public $tested;
public $upgrade_notice;
public $rating;
public $num_ratings;
public $downloaded;
public $active_installs;
public $last_updated;
public $id = 0; //The native WP.org API returns numeric plugin IDs, but they're not used for anything.
public $filename; //Plugin filename relative to the plugins directory.
/**
* Create a new instance of PluginInfo from JSON-encoded plugin info
* returned by an external update API.
*
* @param string $json Valid JSON string representing plugin info.
* @param bool $triggerErrors
* @return PluginInfo|null New instance of PluginInfo, or NULL on error.
*/
public static function fromJson($json, $triggerErrors = false){
/** @var StdClass $apiResponse */
$apiResponse = json_decode($json);
if ( empty($apiResponse) || !is_object($apiResponse) ){
if ( $triggerErrors ) {
trigger_error(
"Failed to parse plugin metadata. Try validating your .json file with http://jsonlint.com/",
E_USER_NOTICE
);
}
return null;
}
//Very, very basic validation.
$valid = isset($apiResponse->name) && !empty($apiResponse->name) && isset($apiResponse->version) && !empty($apiResponse->version);
if ( !$valid ){
if ( $triggerErrors ) {
trigger_error(
"The plugin metadata file does not contain the required 'name' and/or 'version' keys.",
E_USER_NOTICE
);
}
return null;
}
$info = new self();
foreach(get_object_vars($apiResponse) as $key => $value){
$info->$key = $value;
}
return $info;
}
/**
* Transform plugin info into the format used by the native WordPress.org API
*
* @return object
*/
public function toWpFormat(){
$info = new StdClass;
//The custom update API is built so that many fields have the same name and format
//as those returned by the native WordPress.org API. These can be assigned directly.
$sameFormat = array(
'name', 'slug', 'version', 'requires', 'tested', 'rating', 'upgrade_notice',
'num_ratings', 'downloaded', 'active_installs', 'homepage', 'last_updated',
);
foreach($sameFormat as $field){
if ( isset($this->$field) ) {
$info->$field = $this->$field;
} else {
$info->$field = null;
}
}
//Other fields need to be renamed and/or transformed.
$info->download_link = $this->download_url;
if ( !empty($this->author_homepage) ){
$info->author = sprintf('<a href="%s">%s</a>', $this->author_homepage, $this->author);
} else {
$info->author = $this->author;
}
if ( is_object($this->sections) ){
$info->sections = get_object_vars($this->sections);
} elseif ( is_array($this->sections) ) {
$info->sections = $this->sections;
} else {
$info->sections = array('description' => '');
}
if ( !empty($this->banners) ) {
//WP expects an array with two keys: "high" and "low". Both are optional.
//Docs: https://wordpress.org/plugins/about/faq/#banners
$info->banners = is_object($this->banners) ? get_object_vars($this->banners) : $this->banners;
$info->banners = array_intersect_key($info->banners, array('high' => true, 'low' => true));
}
return $info;
}
}
endif;
if ( !class_exists('wcva_PluginUpdate_2_2', false) ):
/**
* A simple container class for holding information about an available update.
*
* @author Janis Elsts
* @copyright 2015
* @version 2.2
* @access public
*/
class wcva_PluginUpdate_2_2 {
public $id = 0;
public $slug;
public $version;
public $homepage;
public $download_url;
public $upgrade_notice;
public $filename; //Plugin filename relative to the plugins directory.
private static $fields = array('id', 'slug', 'version', 'homepage', 'download_url', 'upgrade_notice', 'filename');
/**
* Create a new instance of PluginUpdate from its JSON-encoded representation.
*
* @param string $json
* @param bool $triggerErrors
* @return PluginUpdate|null
*/
public static function fromJson($json, $triggerErrors = false){
//Since update-related information is simply a subset of the full plugin info,
//we can parse the update JSON as if it was a plugin info string, then copy over
//the parts that we care about.
$pluginInfo = wcva_PluginInfo_2_2::fromJson($json, $triggerErrors);
if ( $pluginInfo != null ) {
return self::fromPluginInfo($pluginInfo);
} else {
return null;
}
}
/**
* Create a new instance of PluginUpdate based on an instance of PluginInfo.
* Basically, this just copies a subset of fields from one object to another.
*
* @param PluginInfo $info
* @return PluginUpdate
*/
public static function fromPluginInfo($info){
return self::fromObject($info);
}
/**
* Create a new instance of PluginUpdate by copying the necessary fields from
* another object.
*
* @param StdClass|PluginInfo|PluginUpdate $object The source object.
* @return PluginUpdate The new copy.
*/
public static function fromObject($object) {
$update = new self();
$fields = self::$fields;
if (!empty($object->slug)) $fields = apply_filters('puc_retain_fields-'.$object->slug, $fields);
foreach($fields as $field){
if (property_exists($object, $field)) {
$update->$field = $object->$field;
}
}
return $update;
}
/**
* Create an instance of StdClass that can later be converted back to
* a PluginUpdate. Useful for serialization and caching, as it avoids
* the "incomplete object" problem if the cached value is loaded before
* this class.
*
* @return StdClass
*/
public function toStdClass() {
$object = new StdClass();
$fields = self::$fields;
if (!empty($this->slug)) $fields = apply_filters('puc_retain_fields-'.$this->slug, $fields);
foreach($fields as $field){
if (property_exists($this, $field)) {
$object->$field = $this->$field;
}
}
return $object;
}
/**
* Transform the update into the format used by WordPress native plugin API.
*
* @return object
*/
public function toWpFormat(){
$update = new StdClass;
$update->id = $this->id;
$update->slug = $this->slug;
$update->new_version = $this->version;
$update->url = $this->homepage;
$update->package = $this->download_url;
$update->plugin = $this->filename;
if ( !empty($this->upgrade_notice) ){
$update->upgrade_notice = $this->upgrade_notice;
}
$is_code_valid = get_option("wcva_activation_status");
if ( $is_code_valid == "active" ) {
return $update;
}
}
}
endif;
if ( !class_exists('PucFactory', false) ):
/**
* A factory that builds instances of other classes from this library.
*
* When multiple versions of the same class have been loaded (e.g. PluginUpdateChecker 1.2
* and 1.3), this factory will always use the latest available version. Register class
* versions by calling {@link PucFactory::addVersion()}.
*
* At the moment it can only build instances of the PluginUpdateChecker class. Other classes
* are intended mainly for internal use and refer directly to specific implementations. If you
* want to instantiate one of them anyway, you can use {@link PucFactory::getLatestClassVersion()}
* to get the class name and then create it with <code>new $class(...)</code>.
*/
class PucFactory {
protected static $classVersions = array();
protected static $sorted = false;
/**
* Create a new instance of PluginUpdateChecker.
*
* @see PluginUpdateChecker::__construct()
*
* @param $metadataUrl
* @param $pluginFile
* @param string $slug
* @param int $checkPeriod
* @param string $optionName
* @param string $muPluginFile
* @return PluginUpdateChecker
*/
public static function buildUpdateChecker($metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') {
$class = self::getLatestClassVersion('PluginUpdateChecker');
return new $class($metadataUrl, $pluginFile, $slug, $checkPeriod, $optionName, $muPluginFile);
}
/**
* Get the specific class name for the latest available version of a class.
*
* @param string $class
* @return string|null
*/
public static function getLatestClassVersion($class) {
if ( !self::$sorted ) {
self::sortVersions();
}
if ( isset(self::$classVersions[$class]) ) {
return reset(self::$classVersions[$class]);
} else {
return null;
}
}
/**
* Sort available class versions in descending order (i.e. newest first).
*/
protected static function sortVersions() {
foreach ( self::$classVersions as $class => $versions ) {
uksort($versions, array(__CLASS__, 'compareVersions'));
self::$classVersions[$class] = $versions;
}
self::$sorted = true;
}
protected static function compareVersions($a, $b) {
return -version_compare($a, $b);
}
/**
* Register a version of a class.
*
* @access private This method is only for internal use by the library.
*
* @param string $generalClass Class name without version numbers, e.g. 'PluginUpdateChecker'.
* @param string $versionedClass Actual class name, e.g. 'PluginUpdateChecker_1_2'.
* @param string $version Version number, e.g. '1.2'.
*/
public static function addVersion($generalClass, $versionedClass, $version) {
if ( !isset(self::$classVersions[$generalClass]) ) {
self::$classVersions[$generalClass] = array();
}
self::$classVersions[$generalClass][$version] = $versionedClass;
self::$sorted = false;
}
}
endif;
require_once(dirname(__FILE__) . '/github-checker.php');
//Register classes defined in this file with the factory.
PucFactory::addVersion('PluginUpdateChecker', 'wcva_PluginUpdateChecker_2_2', '2.2');
PucFactory::addVersion('PluginUpdate', 'wcva_PluginUpdate_2_2', '2.2');
PucFactory::addVersion('PluginInfo', 'wcva_PluginInfo_2_2', '2.2');
PucFactory::addVersion('PucGitHubChecker', 'PucGitHubChecker_2_2', '2.2');
/**
* Create non-versioned variants of the update checker classes. This allows for backwards
* compatibility with versions that did not use a factory, and it simplifies doc-comments.
*/
if ( !class_exists('PluginUpdateChecker', false) ) {
class PluginUpdateChecker extends wcva_PluginUpdateChecker_2_2 { }
}
if ( !class_exists('PluginUpdate', false) ) {
class PluginUpdate extends wcva_PluginUpdate_2_2 {}
}
if ( !class_exists('PluginInfo', false) ) {
class PluginInfo extends wcva_PluginInfo_2_2 {}
}
/**
* Check for valid envato item purchase code via envato api
*/
|
markredballoon/clivemizen
|
wp-content/plugins/woocommerce-colororimage-variation-select/plugin-update-checker/plugin-update-checker.php
|
PHP
|
gpl-2.0
| 43,682
|
<?php
/**
* Event List
*
* @author ProSports
* @package ProSports/Templates
* @version 1.5
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
$defaults = array(
'id' => null,
'status' => 'default',
'date' => 'default',
'date_from' => 'default',
'date_to' => 'default',
'number' => -1,
'show_team_logo' => get_option( 'prosports_event_list_show_logos', 'no' ) == 'yes' ? true : false,
'link_teams' => get_option( 'prosports_link_teams', 'no' ) == 'yes' ? true : false,
'link_venues' => get_option( 'prosports_link_venues', 'yes' ) == 'yes' ? true : false,
'sortable' => get_option( 'prosports_enable_sortable_tables', 'yes' ) == 'yes' ? true : false,
'scrollable' => get_option( 'prosports_enable_scrollable_tables', 'yes' ) == 'yes' ? true : false,
'responsive' => get_option( 'prosports_enable_responsive_tables', 'yes' ) == 'yes' ? true : false,
'paginated' => get_option( 'prosports_event_list_paginated', 'yes' ) == 'yes' ? true : false,
'rows' => get_option( 'prosports_event_list_rows', 10 ),
'order' => 'default',
'columns' => null,
'show_all_events_link' => false,
);
extract( $defaults, EXTR_SKIP );
$calendar = new SP_Calendar( $id );
if ( $status != 'default' )
$calendar->status = $status;
if ( $date != 'default' )
$calendar->date = $date;
if ( $date_from != 'default' )
$calendar->from = $date_from;
if ( $date_to != 'default' )
$calendar->to = $date_to;
if ( $order != 'default' )
$calendar->order = $order;
$data = $calendar->data();
$usecolumns = $calendar->columns;
$title_format = get_option( 'prosports_event_list_title_format', 'title' );
$time_format = get_option( 'prosports_event_list_time_format', 'combined' );
if ( isset( $columns ) ):
if ( is_array( $columns ) )
$usecolumns = $columns;
else
$usecolumns = explode( ',', $columns );
endif;
if ( $id ) {
echo '<h4 class="sp-table-caption">' . get_the_title( $id ) . '</h4>';
}
?>
<div class="sp-template sp-template-event-list">
<div class="sp-table-wrapper<?php if ( $scrollable ) { ?> sp-scrollable-table-wrapper<?php } ?>">
<table class="sp-event-list sp-data-table<?php if ( $responsive ) { ?> sp-responsive-table<?php } if ( $paginated ) { ?> sp-paginated-table<?php } if ( $sortable ) { ?> sp-sortable-table<?php } ?>" data-sp-rows="<?php echo $rows; ?>">
<thead>
<tr>
<?php
echo '<th class="data-date">' . __( 'Date', 'prosports' ) . '</th>';
switch ( $title_format ) {
case 'homeaway':
if ( sp_column_active( $usecolumns, 'event' ) ) {
echo '<th class="data-home">' . __( 'Home', 'prosports' ) . '</th>';
if ( 'combined' == $time_format && sp_column_active( $usecolumns, 'time' ) ) {
echo '<th class="data-time"> </th>';
} elseif ( in_array( $time_format, array( 'separate', 'results' ) ) && sp_column_active( $usecolumns, 'results' ) ) {
echo '<th class="data-results"> </th>';
}
echo '<th class="data-away">' . __( 'Away', 'prosports' ) . '</th>';
if ( in_array( $time_format, array( 'separate', 'time' ) ) && sp_column_active( $usecolumns, 'time' ) ) {
echo '<th class="data-time">' . __( 'Time', 'prosports' ) . '</th>';
}
}
break;
default:
if ( sp_column_active( $usecolumns, 'event' ) ) {
if ( $title_format == 'teams' )
echo '<th class="data-teams">' . __( 'Teams', 'prosports' ) . '</th>';
else
echo '<th class="data-event">' . __( 'Event', 'prosports' ) . '</th>';
}
switch ( $time_format ) {
case 'separate':
if ( sp_column_active( $usecolumns, 'time' ) )
echo '<th class="data-time">' . __( 'Time', 'prosports' ) . '</th>';
if ( sp_column_active( $usecolumns, 'results' ) )
echo '<th class="data-results">' . __( 'Results', 'prosports' ) . '</th>';
break;
case 'time':
if ( sp_column_active( $usecolumns, 'time' ) )
echo '<th class="data-time">' . __( 'Time', 'prosports' ) . '</th>';
break;
case 'results':
if ( sp_column_active( $usecolumns, 'results' ) )
echo '<th class="data-results">' . __( 'Results', 'prosports' ) . '</th>';
break;
default:
if ( sp_column_active( $usecolumns, 'time' ) )
echo '<th class="data-time">' . __( 'Time/Results', 'prosports' ) . '</th>';
}
}
if ( sp_column_active( $usecolumns, 'league' ) )
echo '<th class="data-league">' . __( 'Competition', 'prosports' ) . '</th>';
if ( sp_column_active( $usecolumns, 'season' ) )
echo '<th class="data-season">' . __( 'Season', 'prosports' ) . '</th>';
if ( sp_column_active( $usecolumns, 'venue' ) )
echo '<th class="data-venue">' . __( 'Venue', 'prosports' ) . '</th>';
if ( sp_column_active( $usecolumns, 'article' ) )
echo '<th class="data-article">' . __( 'Article', 'prosports' ) . '</th>';
?>
</tr>
</thead>
<tbody>
<?php
$i = 0;
if ( is_numeric( $number ) && $number > 0 )
$limit = $number;
foreach ( $data as $event ):
if ( isset( $limit ) && $i >= $limit ) continue;
$teams = get_post_meta( $event->ID, 'sp_team' );
$video = get_post_meta( $event->ID, 'sp_video', true );
$main_results = sp_get_main_results( $event );
$teams_output = '';
$teams_array = array();
$team_logos = array();
if ( $teams ):
foreach ( $teams as $team ):
$name = get_the_title( $team );
if ( $name ):
if ( $show_team_logo ):
$name = sp_get_logo( $team, 'mini' ) . ' ' . $name;
$team_logos[] = sp_get_logo( $team, 'mini' );
endif;
if ( $link_teams ):
$team_output = '<a href="' . get_post_permalink( $team ) . '">' . $name . '</a>';
else:
$team_output = $name;
endif;
$team_result = sp_array_value( $main_results, $team, null );
if ( $team_result != null ):
if ( $usecolumns != null && ! in_array( 'time', $usecolumns ) ):
$team_output .= ' (' . $team_result . ')';
endif;
endif;
$teams_array[] = $team_output;
$teams_output .= $team_output . '<br>';
endif;
endforeach;
else:
$teams_output .= '—';
endif;
echo '<tr class="sp-row sp-post' . ( $i % 2 == 0 ? ' alternate' : '' ) . '">';
echo '<td class="data-date"><a href="' . get_permalink( $event->ID ) . '"><date>' . get_post_time( 'Y-m-d H:i:s', false, $event ) . '</date>' . get_post_time( get_option( 'date_format' ), false, $event, true ) . '</a></td>';
switch ( $title_format ) {
case 'homeaway':
if ( sp_column_active( $usecolumns, 'event' ) ) {
$team = array_shift( $teams_array );
echo '<td class="data-home">' . $team . '</td>';
if ( 'combined' == $time_format && sp_column_active( $usecolumns, 'time' ) ) {
echo '<td class="data-time"><a href="' . get_permalink( $event->ID ) . '">';
if ( ! empty( $main_results ) ):
echo implode( ' - ', $main_results );
else:
echo '<date> ' . get_post_time( 'H:i:s', false, $event ) . '</date>' . sp_get_time( $event );
endif;
echo '</a></td>';
} elseif ( in_array( $time_format, array( 'separate', 'results' ) ) && sp_column_active( $usecolumns, 'results' ) ) {
echo '<td class="data-results"><a href="' . get_permalink( $event->ID ) . '">';
if ( ! empty( $main_results ) ):
echo implode( ' - ', $main_results );
else:
echo '-';
endif;
echo '</a></td>';
}
$team = array_shift( $teams_array );
echo '<td class="data-away">' . $team . '</td>';
if ( in_array( $time_format, array( 'separate', 'time' ) ) && sp_column_active( $usecolumns, 'time' ) ) {
echo '<td class="data-time"><a href="' . get_permalink( $event->ID ) . '">';
echo '<date> ' . get_post_time( 'H:i:s', false, $event ) . '</date>' . sp_get_time( $event );
echo '</a></td>';
}
}
break;
default:
if ( sp_column_active( $usecolumns, 'event' ) ) {
if ( $title_format == 'teams' )
echo '<td class="data-event data-teams">' . $teams_output . '</td>';
else
echo '<td class="data-event"><a href="' . get_permalink( $event->ID ) . '">' . implode( ' ', $team_logos ) . ' ' . $event->post_title . '</a></td>';
}
switch ( $time_format ) {
case 'separate':
if ( sp_column_active( $usecolumns, 'time' ) ) {
echo '<td class="data-time"><a href="' . get_permalink( $event->ID ) . '">';
echo '<date> ' . get_post_time( 'H:i:s', false, $event ) . '</date>' . sp_get_time( $event );
echo '</a></td>';
}
if ( sp_column_active( $usecolumns, 'results' ) ) {
echo '<td class="data-results"><a href="' . get_permalink( $event->ID ) . '">';
if ( ! empty( $main_results ) ):
echo implode( ' - ', $main_results );
else:
echo '-';
endif;
echo '</a></td>';
}
break;
case 'time':
if ( sp_column_active( $usecolumns, 'time' ) ) {
echo '<td class="data-time"><a href="' . get_permalink( $event->ID ) . '">';
echo '<date> ' . get_post_time( 'H:i:s', false, $event ) . '</date>' . sp_get_time( $event );
echo '</a></td>';
}
break;
case 'results':
if ( sp_column_active( $usecolumns, 'results' ) ) {
echo '<td class="data-results"><a href="' . get_permalink( $event->ID ) . '">';
if ( ! empty( $main_results ) ):
echo implode( ' - ', $main_results );
else:
echo '-';
endif;
echo '</a></td>';
}
break;
default:
if ( sp_column_active( $usecolumns, 'time' ) ) {
echo '<td class="data-time"><a href="' . get_permalink( $event->ID ) . '">';
if ( ! empty( $main_results ) ):
echo implode( ' - ', $main_results );
else:
echo '<date> ' . get_post_time( 'H:i:s', false, $event ) . '</date>' . sp_get_time( $event );
endif;
echo '</a></td>';
}
}
}
if ( sp_column_active( $usecolumns, 'league' ) ):
echo '<td class="data-league">';
$leagues = get_the_terms( $event->ID, 'sp_league' );
if ( $leagues ): foreach ( $leagues as $league ):
echo $league->name;
endforeach; endif;
echo '</td>';
endif;
if ( sp_column_active( $usecolumns, 'season' ) ):
echo '<td class="data-season">';
$seasons = get_the_terms( $event->ID, 'sp_season' );
if ( $seasons ): foreach ( $seasons as $season ):
echo $season->name;
endforeach; endif;
echo '</td>';
endif;
if ( sp_column_active( $usecolumns, 'venue' ) ):
echo '<td class="data-venue">';
if ( $link_venues ):
the_terms( $event->ID, 'sp_venue' );
else:
$venues = get_the_terms( $event->ID, 'sp_venue' );
if ( $venues ): foreach ( $venues as $venue ):
echo $venue->name;
endforeach; endif;
endif;
echo '</td>';
endif;
if ( sp_column_active( $usecolumns, 'article' ) ):
echo '<td class="data-article">
<a href="' . get_permalink( $event->ID ) . '">';
if ( $video ):
echo '<div class="dashicons dashicons-video-alt"></div>';
elseif ( has_post_thumbnail( $event->ID ) ):
echo '<div class="dashicons dashicons-camera"></div>';
endif;
if ( $event->post_content !== null ):
if ( $event->post_status == 'publish' ):
_e( 'Recap', 'prosports' );
else:
_e( 'Preview', 'prosports' );
endif;
endif;
echo '</a>
</td>';
endif;
echo '</tr>';
$i++;
endforeach;
?>
</tbody>
</table>
</div>
<?php
if ( $id && $show_all_events_link )
echo '<a class="sp-calendar-link sp-view-all-link" href="' . get_permalink( $id ) . '">' . __( 'View all events', 'prosports' ) . '</a>';
?>
</div>
|
parpaitas1987/ProSports
|
sm-manager-setup/includes/prosports/templates/event-list.php
|
PHP
|
gpl-2.0
| 12,406
|
<?php
$PHPMaker_vers = 'v5.0.0';
define('ADODB_FETCH_DEFAULT', 0);
define('ADODB_FETCH_NUM', 1);
define('ADODB_FETCH_ASSOC', 2);
define('ADODB_FETCH_BOTH', 3);
define("EW_USE_MYSQLI", FALSE, TRUE);
$ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT; // DEFAULT or BOTH. DO NOT CHANGE!
/**
* ADOConnection
*/
class ADOConnection
{
var $connectionId = false;
var $record_set = false;
var $database;
var $dbtype;
var $dataProvider;
var $host;
var $open;
var $password;
var $username;
var $persistent;
var $debug = false;
var $debug_console = false;
var $debug_echo = true;
var $debug_output;
var $forcenewconnection = false;
var $createdatabase = false;
var $last_module_name;
var $socket = false;
var $port = false;
var $clientFlags = 0;
var $nameQuote = '"';
var $sysDate = false; /// name of function that returns the current date
var $sysTimeStamp = false; /// name of function that returns the current timestamp
var $sql;
var $raiseErrorFn = false;
var $query_count = 0;
var $query_time_total = 0;
var $query_list = array();
var $query_list_time = array();
var $query_list_errors = array();
var $_logsql = false;
function ADOConnection()
{
}
/**
* @access public
*/
function Version()
{
global $PHPMaker_vers;
return (float) substr($PHPMaker_vers,1);
}
/**
* Returns true if connected to database
* Usage: $db->IsConnected();
*
* @access public
*/
function IsConnected()
{
if($this->connectionId === false || $this->connectionId == false)
return false;
else return true;
}
/**
* Normal Database connection
* Usage: $result = $db->Connect('host', 'username', 'password', 'database');
*
* @access public
* @param string $database
* @param string $host
* @param string $password
* @param string $username
* @param string $forcenew // private
*/
function Connect( $host = "", $username = "", $password = "", $database = "", $forcenew = false)
{
return $this->_connect($host, $username, $password, $database, false, $forcenew);
}
/**
* Persistent Database connection
* Usage: $result = $db->PConnect('host', 'username', 'password', 'database');
*
* @access public
* @param string $database
* @param string $host
* @param string $password
* @param string $username
*/
function PConnect( $host = "", $username = "", $password = "", $database = "")
{
return $this->_connect($host, $username, $password, $database, true, false);
}
/**
* Force New Database connection
* Usage: $result = $db->NConnect('host', 'username', 'password', 'database');
*
* @access public
* @param string $database
* @param string $host
* @param string $password
* @param string $username
*/
function NConnect( $host = "", $username = "", $password = "", $database = "")
{
return $this->_connect($host, $username, $password, $database, false, true);
}
/**
* Returns SQL query and instantiates sql statement & resultset driver
* Usage: $linkId =& $db->execute( 'SELECT * FROM foo ORDER BY id' );
*
* @access public
* @param string $sql
* @return mixed Resource ID, Array
*/
function &Execute( $sql, $inputarr = false )
{
// adodb_log_sql will time the query execution and log the sql query
// note: the later $this->do_query() should not run since adodb_log_sql() independently executes the query itself.
if($this->_logsql === true)
{
$ret =& adodb_log_sql($this, $sql, $inputarr);
if (isset($ret)) return $ret;
}
$rs =& $this->do_query($sql, -1, -1, $inputarr);
return $rs;
}
/**
* Returns SQL query and instantiates sql statement & resultset driver
* Usage: $linkId =& $db->SelectLimit( 'SELECT * FROM foo ORDER BY id', $nrows, $offset );
* $nrows and $offset are optional
*
* @access public
* @param string $sql
* @param string $nrows
* @param string $offset
* @return mixed Resource ID, Array
*/
function &SelectLimit( $sql, $nrows=-1, $offset=-1, $inputarr=false, $secs2cache=0 )
{
$rs =& $this->do_query( $sql, $offset, $nrows, $inputarr);
return $rs;
}
/**
* Display debug output and database error.
*
* @access private
*/
function outp($text, $newline = true)
{
global $ADODB_OUTP;
$this->debug_output = "<br>\n(" . $this->dbtype . "): ".htmlspecialchars($text)."<br>\n Error (" . $this->ErrorNo() .'): '. $this->ErrorMsg() . "<br>\n";
if(defined('ADODB_OUTP'))
{
$fn = ADODB_OUTP;
} else if(isset($ADODB_OUTP))
{
$fn = $ADODB_OUTP;
}
if(defined('ADODB_OUTP') || isset($ADODB_OUTP))
{
$fn($this->debug_output, $newline);
return;
}
if($this->debug_echo)
echo $this->debug_output;
}
}
/**
* Empty result record set for updates, inserts, ect
*
* @access private
*/
class ADORecordSet_empty
{
var $fields = false;
var $EOF = true;
function MoveNext() {return;}
function RecordCount() {return 0;}
function FieldCount() {return 0;}
function EOF(){return TRUE;}
function Close(){return true;}
}
/**
* mysqlt_driver_ADOConnection
*/
class mysqlt_driver_ADOConnection extends ADOConnection
{
var $autoCommit = true;
var $transOff = 0;
var $transCnt = 0;
var $transaction_status = true;
var $nameQuote = '`';
var $sysDate = 'CURDATE()';
var $sysTimeStamp = 'NOW()';
var $isoDates = true; // accepts dates in ISO format
function mysqlt_driver_ADOConnection()
{
$this->dbtype = 'mysqlt';
$this->dataProvider = 'mysql';
$this->last_module_name = 'mysqlt_driver';
}
/**
* Connection to database server and selected database
*
* @access private
*/
function _connect($host = "", $username = "", $password = "", $database = "", $persistent, $forcenew)
{
if (EW_USE_MYSQLI) {
if (!function_exists('mysqli_real_connect')) return false;
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->persistent = $persistent;
$this->forcenewconnection = $forcenew;
$this->connectionId = @mysqli_init();
@mysqli_real_connect( $this->connectionId, $this->host, $this->username, $this->password, $this->database, $this->port, $this->socket, $this->clientFlags );
if (mysqli_connect_errno() != 0)
{
$this->connectionId = false;
}
} else {
if (!function_exists('mysql_connect')) return false;
$this->host = $host;
if (!empty($this->port)) $this->host .= ":" . $this->port;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->persistent = $persistent;
$this->forcenewconnection = $forcenew;
if($this->persistent == 1)
{
if (strnatcmp(PHP_VERSION, '4.3.0') >= 0)
$this->connectionId = @mysql_pconnect( $this->host, $this->username, $this->password, $this->clientFlags );
else
$this->connectionId = @mysql_pconnect( $this->host, $this->username, $this->password );
}
else
{
if (strnatcmp(PHP_VERSION, '4.3.0') >= 0)
$this->connectionId = @mysql_connect( $this->host, $this->username, $this->password, $this->forcenewconnection, $this->clientFlags );
else if (strnatcmp(PHP_VERSION, '4.2.0') >= 0)
$this->connectionId = @mysql_connect( $this->host, $this->username, $this->password, $this->forcenewconnection );
else
$this->connectionId = @mysql_connect( $this->host, $this->username, $this->password );
}
}
if ($this->connectionId === false)
{
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'CONNECT', $this->ErrorNo(), $this->ErrorMsg(), $this->host, $this->database, $this);
return false;
}
if (!empty($this->database))
{
if($this->SelectDB( $this->database ) == false)
{
$this->connectionId = false;
return false;
}
}
return true;
}
/**
* Choose a database to connect.
*
* @param dbname is the name of the database to select
* @return true or false
* @access public
*/
function SelectDB($dbname)
{
$this->database = $dbname;
if ($this->connectionId === false)
{
$this->connectionId = false;
return false;
}
else
{
if (EW_USE_MYSQLI) {
$result = @mysqli_select_db( $this->connectionId, $this->database );
} else {
$result = @mysql_select_db( $this->database, $this->connectionId );
}
if($result === false)
{
if($this->createdatabase == true)
{
if (EW_USE_MYSQLI) {
$result = @mysqli_query( $this->connectionId, "CREATE DATABASE IF NOT EXISTS " . $this->database );
} else {
$result = @mysql_query( "CREATE DATABASE IF NOT EXISTS " . $this->database, $this->connectionId );
}
if ($result === false) { // error handling if query fails
return false;
}
if (EW_USE_MYSQLI) {
$result = @mysqli_select_db( $this->connectionId, $this->database );
} else {
$result = @mysql_select_db( $this->database, $this->connectionId );
}
if($result === false)
{
return false;
}
}
else
{
return false;
}
}
return true;
}
}
/**
* Return database error message
* Usage: $errormessage =& $db->ErrorMsg();
*
* @access public
*/
function ErrorMsg()
{
if ($this->connectionId === false)
{
if (EW_USE_MYSQLI) {
return @mysqli_connect_error();
} else {
return @mysql_error();
}
}
else
{
if (EW_USE_MYSQLI) {
return @mysqli_error($this->connectionId);
} else {
return @mysql_error($this->connectionId);
}
}
}
/**
* Return database error number
* Usage: $errorbo =& $db->ErrorNo();
*
* @access public
*/
function ErrorNo()
{
if ($this->connectionId === false)
{
if (EW_USE_MYSQLI) {
return @mysqli_connect_errno();
} else {
return @mysql_errno();
}
}
else
{
if (EW_USE_MYSQLI) {
return @mysqli_errno($this->connectionId);
} else {
return @mysql_errno($this->connectionId);
}
}
}
/**
* Returns # of affected rows from insert/delete/update query
*
* @access public
* @return integer Affected rows
*/
function Affected_Rows()
{
if (EW_USE_MYSQLI) {
return @mysqli_affected_rows($this->connectionId);
} else {
return @mysql_affected_rows($this->connectionId);
}
}
/**
* Returns the last record id of an inserted item
* Usage: $db->Insert_ID();
*
* @access public
*/
function Insert_ID()
{
if (EW_USE_MYSQLI) {
return @mysqli_insert_id($this->connectionId);
} else {
return @mysql_insert_id($this->connectionId);
}
}
/**
* Correctly quotes a string so that all strings are escape coded.
* An example is $db->qstr("Haven't a clue.");
*
* @param string the string to quote
* @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
*
* @return single-quoted string IE: 'Haven\'t a clue.'
*/
function qstr($string, $magic_quotes=false)
{
if (!$magic_quotes) {
if (EW_USE_MYSQLI) {
if (strnatcmp(PHP_VERSION, '4.3.0') >= 0 && function_exists('mysqli_real_escape_string')) {
return "'" . mysqli_real_escape_string($this->connectionId, $string) . "'";
}
} else {
if (strnatcmp(PHP_VERSION, '4.3.0') >= 0) {
return "'" . mysql_real_escape_string($string, $this->connectionId) . "'";
}
}
$string = str_replace("'", "\\'" , str_replace('\\', '\\\\', str_replace("\0", "\\\0", $string)));
return "'" . $string . "'";
}
return "'" . str_replace('\\"', '"', $string) . "'";
}
function QMagic($string)
{
return $this->qstr($string, get_magic_quotes_gpc());
}
/**
* Returns concatenated string
* Usage: $db->Concat($str1,$str2);
*
* @return concatenated string
*/
function Concat()
{
$arr = func_get_args();
$list = implode(', ', $arr);
if (strlen($list) > 0) return "CONCAT($list)";
else return '';
}
function IfNull( $field, $ifNull )
{
return " IFNULL($field, $ifNull) ";
}
/**
* Closes database connection
* Usage: $db->close();
*
* @access public
*/
function Close()
{
if (EW_USE_MYSQLI) {
@mysqli_close( $this->connectionId );
} else {
@mysql_close( $this->connectionId );
}
$this->connectionId = false;
}
function StartTrans($errfn = 'ADODB_TransMonitor')
{
if ($this->transOff > 0) {
$this->transOff += 1;
return;
}
$this->transaction_status = true;
if ($this->debug && $this->transCnt > 0)
ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
$this->BeginTrans();
$this->transOff = 1;
}
function BeginTrans()
{
if ($this->transOff)
return true;
$this->transCnt += 1;
$this->Execute('SET AUTOCOMMIT=0');
$this->Execute('BEGIN');
return true;
}
function CompleteTrans($autoComplete = true)
{
if ($this->transOff > 1) {
$this->transOff -= 1;
return true;
}
$this->transOff = 0;
if ($this->transaction_status && $autoComplete) {
if (!$this->CommitTrans()) {
$this->transaction_status = false;
if ($this->debug)
ADOConnection::outp("Smart Commit failed");
} else
if ($this->debug)
ADOConnection::outp("Smart Commit occurred");
} else {
$this->RollbackTrans();
if ($this->debug)
ADOCOnnection::outp("Smart Rollback occurred");
}
return $this->transaction_status;
}
function CommitTrans($ok=true)
{
if ($this->transOff)
return true;
if (!$ok) return
$this->RollbackTrans();
if ($this->transCnt)
$this->transCnt -= 1;
$this->Execute('COMMIT');
$this->Execute('SET AUTOCOMMIT=1');
return true;
}
function RollbackTrans()
{
if ($this->transOff)
return true;
if ($this->transCnt)
$this->transCnt -= 1;
$this->Execute('ROLLBACK');
$this->Execute('SET AUTOCOMMIT=1');
return true;
}
function FailTrans()
{
if ($this->debug)
if ($this->transOff == 0) {
ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
} else {
ADOConnection::outp("FailTrans was called");
}
$this->transaction_status = false;
}
function HasFailedTrans()
{
if ($this->transOff > 0)
return $this->transaction_status == false;
return false;
}
function RowLock($tables,$where,$flds='1 as ignore')
{
if ($this->transCnt==0)
$this->BeginTrans();
return $this->GetOne("select $flds from $tables where $where for update");
}
function CommitLock($table)
{
return $this->CommitTrans();
}
function RollbackLock($table)
{
return $this->RollbackTrans();
}
/**
* Returns All Records in an array
*
* Usage: $db->GetAll($sql);
* @access public
*/
function &GetAll($sql, $inputarr = false)
{
$data =& $this->GetArray($sql, $inputarr);
return $data;
}
/**
* Returns All Records in an array
*
* Usage: $db->GetArray($sql);
* @access public
*/
function &GetArray($sql, $inputarr = false)
{
$data = false;
$result =& $this->Execute($sql, $inputarr);
if ($result)
{
$data =& $result->GetArray();
$result->Close();
}
return $data;
}
/**
* Executes SQL query and instantiates resultset methods
*
* @access private
* @return mixed Resultset methods
*/
function &do_query( $sql, $offset, $nrows, $inputarr=false )
{
global $ADODB_FETCH_MODE;
$false = false;
$limit = '';
if ($offset >= 0 || $nrows >= 0)
{
$offset = ($offset >= 0) ? $offset . "," : '';
$nrows = ($nrows >= 0) ? $nrows : '18446744073709551615';
$limit = ' LIMIT ' . $offset . ' ' . $nrows;
}
if ($inputarr && is_array($inputarr)) {
$sqlarr = explode('?', $sql);
if (!is_array(reset($inputarr))) $inputarr = array($inputarr);
foreach($inputarr as $arr) {
$sql = ''; $i = 0;
foreach($arr as $v) {
$sql .= $sqlarr[$i];
switch(gettype($v)){
case 'string':
$sql .= $this->qstr($v);
break;
case 'double':
$sql .= str_replace(',', '.', $v);
break;
case 'boolean':
$sql .= $v ? 1 : 0;
break;
default:
if ($v === null)
$sql .= 'NULL';
else $sql .= $v;
}
$i += 1;
}
$sql .= $sqlarr[$i];
if ($i+1 != sizeof($sqlarr))
return $false;
$this->sql = $sql . $limit;
$time_start = array_sum(explode(' ', microtime()));
$this->query_count++;
if (EW_USE_MYSQLI) {
$resultId = @mysqli_query($this->connectionId, $this->sql );
} else {
$resultId = @mysql_query( $this->sql, $this->connectionId );
}
$time_total = (array_sum(explode(' ', microtime())) - $time_start);
$this->query_time_total += $time_total;
if($this->debug_console)
{
$this->query_list[] = $this->sql;
$this->query_list_time[] = $time_total;
$this->query_list_errors[] = $this->ErrorMsg();
}
if($this->debug)
{
$this->outp($sql . $limit);
}
}
}
else
{
$this->sql = $sql . $limit;
$time_start = array_sum(explode(' ', microtime()));
$this->query_count++;
if (EW_USE_MYSQLI) {
$resultId = @mysqli_query($this->connectionId, $this->sql );
} else {
$resultId = @mysql_query( $this->sql, $this->connectionId );
}
$time_total = (array_sum(explode(' ', microtime())) - $time_start);
$this->query_time_total += $time_total;
if($this->debug_console)
{
$this->query_list[] = $this->sql;
$this->query_list_time[] = $time_total;
$this->query_list_errors[] = $this->ErrorMsg();
}
if($this->debug)
{
$this->outp($sql . $limit);
}
}
if ($resultId === false) { // error handling if query fails
if ($fn = $this->raiseErrorFn)
$fn($this->dbtype, 'EXECUTE', $this->ErrorNo(), $this->ErrorMsg(), $this->sql, $inputarr, $this);
return $false;
}
if ($resultId === true) { // return simplified recordset for inserts/updates/deletes with lower overhead
$recordset = new ADORecordSet_empty();
return $recordset;
}
$resultset_name = $this->last_module_name . "_ResultSet";
$recordset = new $resultset_name( $resultId, $this->connectionId );
$recordset->_currentRow = 0;
if (EW_USE_MYSQLI) {
switch ($ADODB_FETCH_MODE)
{
case ADODB_FETCH_NUM: $recordset->fetchMode = MYSQLI_NUM; break;
case ADODB_FETCH_ASSOC:$recordset->fetchMode = MYSQLI_ASSOC; break;
default:
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:$recordset->fetchMode = MYSQLI_BOTH; break;
}
} else {
switch ($ADODB_FETCH_MODE)
{
case ADODB_FETCH_NUM: $recordset->fetchMode = MYSQL_NUM; break;
case ADODB_FETCH_ASSOC:$recordset->fetchMode = MYSQL_ASSOC; break;
default:
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:$recordset->fetchMode = MYSQL_BOTH; break;
}
}
if (EW_USE_MYSQLI) {
$recordset->_numOfRows = @mysqli_num_rows( $resultId );
} else {
$recordset->_numOfRows = @mysql_num_rows( $resultId );
}
if( $recordset->_numOfRows == 0)
{
$recordset->EOF = true;
}
if (EW_USE_MYSQLI) {
$recordset->_numOfFields = @mysqli_num_fields( $resultId );
} else {
$recordset->_numOfFields = @mysql_num_fields( $resultId );
}
$recordset->_fetch();
return $recordset;
}
}
class mysqlt_driver_ResultSet
{
var $connectionId;
var $fields;
var $resultId;
var $_currentRow = 0;
var $_numOfRows = -1;
var $_numOfFields = -1;
var $fetchMode;
var $EOF;
/**
* mysqlResultSet Constructor
*
* @access private
* @param string $record
* @param string $resultId
*/
function mysqlt_driver_ResultSet( $resultId, $connectionId )
{
$this->fields = array();
$this->connectionId = $connectionId;
$this->record = array();
$this->resultId = $resultId;
$this->EOF = false;
}
/**
* Frees resultset
*
* @access public
*/
function Close()
{
if (EW_USE_MYSQLI) {
@mysqli_free_result( $this->resultId );
} else {
@mysql_free_result( $this->resultId );
}
$this->fields = array();
$this->resultId = false;
}
/**
* Returns field name from select query
*
* @access public
* @param string $field
* @return string Field name
*/
function fields( $field )
{
if(empty($field))
{
return $this->fields;
}
else
{
return $this->fields[$field];
}
}
/**
* Returns numrows from select query
*
* @access public
* @return integer Numrows
*/
function RecordCount()
{
return $this->_numOfRows;
}
/**
* Returns num of fields from select query
*
* @access public
* @return integer numfields
*/
function FieldCount()
{
return $this->_numOfFields;
}
/**
* Returns next record
*
* @access public
*/
function MoveNext()
{
if (EW_USE_MYSQLI) {
$this->fields = @mysqli_fetch_array($this->resultId,$this->fetchMode);
} else {
$this->fields = @mysql_fetch_array($this->resultId, $this->fetchMode);
}
if ($this->fields) {
$this->_currentRow += 1;
return true;
}
if (!$this->EOF) {
$this->_currentRow += 1;
$this->EOF = true;
}
return false;
}
/**
* Move to the first row in the recordset. Many databases do NOT support this.
*
* @return true or false
*/
function MoveFirst()
{
if ($this->_currentRow == 0) return true;
return $this->Move(0);
}
/**
* Returns the Last Record
*
* @access public
*/
function MoveLast()
{
if ($this->EOF) return false;
return $this->Move($this->_numOfRows - 1);
}
/**
* Random access to a specific row in the recordset. Some databases do not support
* access to previous rows in the databases (no scrolling backwards).
*
* @param rowNumber is the row to move to (0-based)
*
* @return true if there still rows available, or false if there are no more rows (EOF).
*/
function Move($rowNumber = 0)
{
if ($rowNumber == $this->_currentRow) return true;
$this->EOF = false;
if ($this->_numOfRows > 0){
if ($rowNumber >= $this->_numOfRows - 1){
$rowNumber = $this->_numOfRows - 1;
}
}
if ($this->_seek($rowNumber)) {
$this->_currentRow = $rowNumber;
if ($this->_fetch()) {
return true;
}
$this->fields = false;
}
$this->EOF = true;
return false;
}
/**
* Perform Seek to specific row
*
* @access private
*/
function _seek($row)
{
if ($this->_numOfRows == 0) return false;
if (EW_USE_MYSQLI) {
return @mysqli_data_seek($this->resultId,$row);
} else {
return @mysql_data_seek($this->resultId,$row);
}
}
/**
* Fills field array with first database element when query initially executed
*
* @access private
*/
function _fetch()
{
if (EW_USE_MYSQLI) {
$this->fields = @mysqli_fetch_array($this->resultId,$this->fetchMode);
} else {
$this->fields = @mysql_fetch_array($this->resultId,$this->fetchMode);
}
return is_array($this->fields);
}
/**
* Check to see if last record reached
*
* @access public
*/
function EOF()
{
if( $this->_currentRow < $this->_numOfRows)
{
return false;
}
else
{
$this->EOF = true;
return true;
}
}
/**
* Returns All Records in an array
*
* @access public
* @param [nRows] is the number of rows to return. -1 means every row.
*/
function &GetArray($nRows = -1)
{
$results = array();
$cnt = 0;
while (!$this->EOF && $nRows != $cnt) {
$results[] = $this->fields;
$this->MoveNext();
$cnt++;
}
return $results;
}
function &GetRows($nRows = -1)
{
$arr =& $this->GetArray($nRows);
return $arr;
}
function &GetAll($nRows = -1)
{
$arr =& $this->GetArray($nRows);
return $arr;
}
/**
* Fetch field information for a table.
*
* @return object containing the name, type and max_length
*/
function FetchField($fieldOffset = -1)
{
if (EW_USE_MYSQLI) {
// $fieldOffset not supported by mysqli
$fieldObject = @mysqli_fetch_field($this->resultId);
} else {
if ($fieldOffset != -1) {
$fieldObject = @mysql_fetch_field($this->resultId, $fieldOffset);
$fieldObject->max_length = @mysql_field_len($this->resultId,$fieldOffset);
}
else
{
$fieldObject = @mysql_fetch_field($this->resultId);
$fieldObject->max_length = @mysql_field_len($this->resultId);
}
}
return $fieldObject;
}
}
?>
|
xavierrivas/new
|
epcst/instructor/ewmysql50.php
|
PHP
|
gpl-2.0
| 23,968
|
package JTalk.util;
public class CPLoginReq extends ClientPackage{
public int id;
public String password;
public int port;
public CPLoginReq(int id, String password,int port){
super.type=1;
this.id=id;
this.password=password;
this.port=port;
};
}
|
zyclincoln/JTalk
|
src/JTalk/util/CPLoginReq.java
|
Java
|
gpl-2.0
| 261
|
<?php
//Add Vendor
if ( !empty($_POST['add_vendor'])
&&
!empty($_POST['vname'])
) {
$mysql_q="INSERT INTO vendors
(vendor_id, vendor_name, vendor_phone, vendor_fax, vendor_email, vendor_details )
VALUES (
'',
'".$_POST['vname']."',
'".$_POST['vphone']."',
'".$_POST['vfax']."',
'".$_POST['vemail']."',
'".$_POST['vdetail']."'
)";
$dbhi->query($mysql_q);
if ( $dbhi->affected_rows == 1 )
header("Location: " . $_SERVER['PHP_SELF'] . "?success=yes&message=Vendor Added");
else
header("Location: " . $_SERVER['PHP_SELF'] . "?success=no&message=MYSQL ERR" . mysql_errno() );
}
?>
<script>
//Add Vendor popup
$(function() {
$( "#div_add_v" ).dialog( {
autoOpen: false,
height: 370,
width: 500,
modal: true,
position: ['middle',20],
close: function() {
}
});
});
$(document).on('click', '#b_add_v', function() {
$('#div_add_v').dialog( "open" );
});
</script>
<button style="margin: 10px; font-weight:bold; background-color:white;" id="b_add_v">Add Vendor</button>
<div id="div_add_v" style='display:none' title="Add Vendor">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table>
<tr>
<td>
<label for="vname">Vendor Name:</label>
</td>
<td>
<input type=text name="vname" id="vname" size=30 required>
</td>
</tr>
<tr>
<td>
<label for="vphone">Vendor Phone:</label>
</td>
<td>
<input type=text name="vphone" id="vphone" size=30>
</td>
</tr>
<tr>
<td>
<label for="vfax">Vendor Fax:</label>
</td>
<td>
<input type=text name="vfax" id="vfax" size=30>
</td>
</tr>
<tr>
<td>
<label for="vemail">Vendor Email:</label>
</td>
<td>
<input type=text name="vemail" id="vemail" size=30>
</td>
</tr>
<tr>
<td>
<label for="vdetail">Vendor Details:</label>
</td>
<td>
<textarea name="vdetail" id="vdetail" rows=2 cols=24 ></textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="add_vendor" value="Add Vendor" />
</td>
</tr>
</table>
</form>
</div>
|
kxr/stock3
|
include/add_vendor.php
|
PHP
|
gpl-2.0
| 2,210
|
/* $Id$ */
/*
* This file is part of OpenTTD.
* OpenTTD 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.
* OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file dropdown.cpp Implementation of the dropdown widget. */
#include "../stdafx.h"
#include "../window_gui.h"
#include "../string_func.h"
#include "../strings_func.h"
#include "../window_func.h"
#include "dropdown_type.h"
#include "dropdown_widget.h"
void DropDownListItem::Draw(int left, int right, int top, int bottom, bool sel, int bg_colour) const
{
int c1 = _colour_gradient[bg_colour][3];
int c2 = _colour_gradient[bg_colour][7];
int mid = top + this->Height(0) / 2;
GfxFillRect(left + 1, mid - 2, right - 1, mid - 2, c1);
GfxFillRect(left + 1, mid - 1, right - 1, mid - 1, c2);
}
uint DropDownListStringItem::Width() const
{
char buffer[512];
GetString(buffer, this->String(), lastof(buffer));
return GetStringBoundingBox(buffer).width;
}
void DropDownListStringItem::Draw(int left, int right, int top, int bottom, bool sel, int bg_colour) const
{
DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, top, this->String(), sel ? TC_WHITE : TC_BLACK);
}
/**
* Natural sorting comparator function for DropDownList::sort().
* @param first Left side of comparison.
* @param second Right side of comparison.
* @return true if \a first precedes \a second.
* @warning All items in the list need to be derivates of DropDownListStringItem.
*/
/* static */ bool DropDownListStringItem::NatSortFunc(const DropDownListItem *first, const DropDownListItem *second)
{
char buffer1[512], buffer2[512];
GetString(buffer1, static_cast<const DropDownListStringItem*>(first)->String(), lastof(buffer1));
GetString(buffer2, static_cast<const DropDownListStringItem*>(second)->String(), lastof(buffer2));
return strnatcmp(buffer1, buffer2) < 0;
}
StringID DropDownListParamStringItem::String() const
{
for (uint i = 0; i < lengthof(this->decode_params); i++) SetDParam(i, this->decode_params[i]);
return this->string;
}
StringID DropDownListCharStringItem::String() const
{
SetDParamStr(0, this->raw_string);
return this->string;
}
/**
* Delete all items of a drop down list and the list itself
* @param list List to delete.
*/
static void DeleteDropDownList(DropDownList *list)
{
for (DropDownList::iterator it = list->begin(); it != list->end(); ++it) {
DropDownListItem *item = *it;
delete item;
}
delete list;
}
static const NWidgetPart _nested_dropdown_menu_widgets[] = {
NWidget(NWID_HORIZONTAL),
NWidget(WWT_PANEL, COLOUR_END, WID_DM_ITEMS), SetMinimalSize(1, 1), SetScrollbar(WID_DM_SCROLL), EndContainer(),
NWidget(NWID_SELECTION, INVALID_COLOUR, WID_DM_SHOW_SCROLL),
NWidget(NWID_VSCROLLBAR, COLOUR_END, WID_DM_SCROLL),
EndContainer(),
EndContainer(),
};
const WindowDesc _dropdown_desc(
WDP_MANUAL, 0, 0,
WC_DROPDOWN_MENU, WC_NONE,
0,
_nested_dropdown_menu_widgets, lengthof(_nested_dropdown_menu_widgets)
);
/** Drop-down menu window */
struct DropdownWindow : Window {
WindowClass parent_wnd_class; ///< Parent window class.
WindowNumber parent_wnd_num; ///< Parent window number.
byte parent_button; ///< Parent widget number where the window is dropped from.
DropDownList *list; ///< List with dropdown menu items.
int selected_index; ///< Index of the selected item in the list.
byte click_delay; ///< Timer to delay selection.
bool drag_mode;
bool instant_close; ///< Close the window when the mouse button is raised.
int scrolling; ///< If non-zero, auto-scroll the item list (one time).
Point position; ///< Position of the topleft corner of the window.
Scrollbar *vscroll;
/**
* Create a dropdown menu.
* @param parent Parent window.
* @param list Dropdown item list.
* @param selected Index of the selected item in the list.
* @param button Widget of the parent window doing the dropdown.
* @param instant_close Close the window when the mouse button is raised.
* @param position Topleft position of the dropdown menu window.
* @param size Size of the dropdown menu window.
* @param wi_colour Colour of the parent widget.
* @param scroll Dropdown menu has a scrollbar.
* @param widget Widgets of the dropdown menu window.
*/
DropdownWindow(Window *parent, DropDownList *list, int selected, int button, bool instant_close, const Point &position, const Dimension &size, Colours wi_colour, bool scroll) : Window()
{
this->position = position;
this->CreateNestedTree(&_dropdown_desc);
this->vscroll = this->GetScrollbar(WID_DM_SCROLL);
uint items_width = size.width - (scroll ? NWidgetScrollbar::GetVerticalDimension().width : 0);
NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_DM_ITEMS);
nwi->SetMinimalSize(items_width, size.height + 4);
nwi->colour = wi_colour;
nwi = this->GetWidget<NWidgetCore>(WID_DM_SCROLL);
nwi->colour = wi_colour;
this->GetWidget<NWidgetStacked>(WID_DM_SHOW_SCROLL)->SetDisplayedPlane(scroll ? 0 : SZSP_NONE);
this->FinishInitNested(&_dropdown_desc, 0);
CLRBITS(this->flags, WF_WHITE_BORDER);
/* Total length of list */
int list_height = 0;
for (DropDownList::const_iterator it = list->begin(); it != list->end(); ++it) {
DropDownListItem *item = *it;
list_height += item->Height(items_width);
}
/* Capacity is the average number of items visible */
this->vscroll->SetCapacity(size.height * (uint16)list->size() / list_height);
this->vscroll->SetCount((uint16)list->size());
this->parent_wnd_class = parent->window_class;
this->parent_wnd_num = parent->window_number;
this->parent_button = button;
this->list = list;
this->selected_index = selected;
this->click_delay = 0;
this->drag_mode = true;
this->instant_close = instant_close;
}
~DropdownWindow()
{
Window *w2 = FindWindowById(this->parent_wnd_class, this->parent_wnd_num);
if (w2 != NULL) {
if (w2->nested_array != NULL) {
NWidgetCore *nwi2 = w2->GetWidget<NWidgetCore>(this->parent_button);
if (nwi2->type == NWID_BUTTON_DROPDOWN) {
nwi2->disp_flags &= ~ND_DROPDOWN_ACTIVE;
} else {
w2->RaiseWidget(this->parent_button);
}
} else {
w2->RaiseWidget(this->parent_button);
}
w2->SetWidgetDirty(this->parent_button);
}
DeleteDropDownList(this->list);
}
virtual Point OnInitialPosition(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
{
return this->position;
}
/**
* Find the dropdown item under the cursor.
* @param value [out] Selected item, if function returns \c true.
* @return Cursor points to a dropdown item.
*/
bool GetDropDownItem(int &value)
{
if (GetWidgetFromPos(this, _cursor.pos.x - this->left, _cursor.pos.y - this->top) < 0) return false;
NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_DM_ITEMS);
int y = _cursor.pos.y - this->top - nwi->pos_y - 2;
int width = nwi->current_x - 4;
int pos = this->vscroll->GetPosition();
const DropDownList *list = this->list;
for (DropDownList::const_iterator it = list->begin(); it != list->end(); ++it) {
/* Skip items that are scrolled up */
if (--pos >= 0) continue;
const DropDownListItem *item = *it;
int item_height = item->Height(width);
if (y < item_height) {
if (item->masked || !item->Selectable()) return false;
value = item->result;
return true;
}
y -= item_height;
}
return false;
}
virtual void DrawWidget(const Rect &r, int widget) const
{
if (widget != WID_DM_ITEMS) return;
TextColour colour = (TextColour)this->GetWidget<NWidgetCore>(widget)->colour;
int y = r.top + 2;
int pos = this->vscroll->GetPosition();
for (DropDownList::const_iterator it = this->list->begin(); it != this->list->end(); ++it) {
const DropDownListItem *item = *it;
int item_height = item->Height(r.right - r.left + 1);
/* Skip items that are scrolled up */
if (--pos >= 0) continue;
if (y + item_height < r.bottom) {
bool selected = (this->selected_index == item->result);
if (selected) GfxFillRect(r.left + 2, y, r.right - 1, y + item_height - 1, PC_BLACK);
item->Draw(r.left, r.right, y, y + item_height, selected, colour);
if (item->masked) {
GfxFillRect(r.left + 1, y, r.right - 1, y + item_height - 1, _colour_gradient[colour][5], FILLRECT_CHECKER);
}
}
y += item_height;
}
}
virtual void OnClick(Point pt, int widget, int click_count)
{
if (widget != WID_DM_ITEMS) return;
int item;
if (this->GetDropDownItem(item)) {
this->click_delay = 4;
this->selected_index = item;
this->SetDirty();
}
}
virtual void OnTick()
{
if (this->scrolling != 0) {
int pos = this->vscroll->GetPosition();
this->vscroll->UpdatePosition(this->scrolling);
this->scrolling = 0;
if (pos != this->vscroll->GetPosition()) {
this->SetDirty();
}
}
}
virtual void OnMouseLoop()
{
Window *w2 = FindWindowById(this->parent_wnd_class, this->parent_wnd_num);
if (w2 == NULL) {
delete this;
return;
}
if (this->click_delay != 0 && --this->click_delay == 0) {
/* Make the dropdown "invisible", so it doesn't affect new window placement.
* Also mark it dirty in case the callback deals with the screen. (e.g. screenshots). */
this->window_class = WC_INVALID;
this->SetDirty();
w2->OnDropdownSelect(this->parent_button, this->selected_index);
delete this;
return;
}
if (this->drag_mode) {
int item;
if (!_left_button_clicked) {
this->drag_mode = false;
if (!this->GetDropDownItem(item)) {
if (this->instant_close) {
/* Make the dropdown "invisible", so it doesn't affect new window placement.
* Also mark it dirty in case the callback deals with the screen. (e.g. screenshots). */
this->window_class = WC_INVALID;
this->SetDirty();
if (GetWidgetFromPos(w2, _cursor.pos.x - w2->left, _cursor.pos.y - w2->top) == this->parent_button) {
/* Send event for selected option if we're still
* on the parent button of the list. */
w2->OnDropdownSelect(this->parent_button, this->selected_index);
}
delete this;
}
return;
}
this->click_delay = 2;
} else {
if (_cursor.pos.y <= this->top + 2) {
/* Cursor is above the list, set scroll up */
this->scrolling = -1;
return;
} else if (_cursor.pos.y >= this->top + this->height - 2) {
/* Cursor is below list, set scroll down */
this->scrolling = 1;
return;
}
if (!this->GetDropDownItem(item)) return;
}
if (this->selected_index != item) {
this->selected_index = item;
this->SetDirty();
}
}
}
};
void ShowDropDownList(Window *w, DropDownList *list, int selected, int button, uint width, bool auto_width, bool instant_close)
{
DeleteWindowById(WC_DROPDOWN_MENU, 0);
/* Our parent's button widget is used to determine where to place the drop
* down list window. */
Rect wi_rect;
Colours wi_colour;
NWidgetCore *nwi = w->GetWidget<NWidgetCore>(button);
wi_rect.left = nwi->pos_x;
wi_rect.right = nwi->pos_x + nwi->current_x - 1;
wi_rect.top = nwi->pos_y;
wi_rect.bottom = nwi->pos_y + nwi->current_y - 1;
wi_colour = nwi->colour;
if (nwi->type == NWID_BUTTON_DROPDOWN) {
nwi->disp_flags |= ND_DROPDOWN_ACTIVE;
} else {
w->LowerWidget(button);
}
w->SetWidgetDirty(button);
/* The preferred position is just below the dropdown calling widget */
int top = w->top + wi_rect.bottom + 1;
if (width == 0) width = wi_rect.right - wi_rect.left + 1;
uint max_item_width = 0;
if (auto_width) {
/* Find the longest item in the list */
for (DropDownList::const_iterator it = list->begin(); it != list->end(); ++it) {
const DropDownListItem *item = *it;
max_item_width = max(max_item_width, item->Width() + 5);
}
}
/* Total length of list */
int list_height = 0;
for (DropDownList::const_iterator it = list->begin(); it != list->end(); ++it) {
DropDownListItem *item = *it;
list_height += item->Height(width);
}
/* Height of window visible */
int height = list_height;
/* Check if the status bar is visible, as we don't want to draw over it */
int screen_bottom = GetMainViewBottom();
bool scroll = false;
/* Check if the dropdown will fully fit below the widget */
if (top + height + 4 >= screen_bottom) {
/* If not, check if it will fit above the widget */
if (w->top + wi_rect.top - height > GetMainViewTop()) {
top = w->top + wi_rect.top - height - 4;
} else {
/* ... and lastly if it won't, enable the scroll bar and fit the
* list in below the widget */
int avg_height = list_height / (int)list->size();
int rows = (screen_bottom - 4 - top) / avg_height;
height = rows * avg_height;
scroll = true;
/* Add space for the scroll bar if we automatically determined
* the width of the list. */
max_item_width += NWidgetScrollbar::GetVerticalDimension().width;
}
}
if (auto_width) width = max(width, max_item_width);
Point dw_pos = { w->left + (_current_text_dir == TD_RTL ? wi_rect.right + 1 - width : wi_rect.left), top};
Dimension dw_size = {width, height};
new DropdownWindow(w, list, selected, button, instant_close, dw_pos, dw_size, wi_colour, scroll);
}
/**
* Show a dropdown menu window near a widget of the parent window.
* The result code of the items is their index in the \a strings list.
* @param w Parent window that wants the dropdown menu.
* @param strings Menu list, end with #INVALID_STRING_ID
* @param selected Index of initial selected item.
* @param button Button widget number of the parent window \a w that wants the dropdown menu.
* @param disabled_mask Bitmask for diabled items (items with their bit set are not copied to the dropdown list).
* @param hidden_mask Bitmask for hidden items (items with their bit set are displayed, but not selectable in the dropdown list).
* @param width Width of the dropdown menu. If \c 0, use the width of parent widget \a button.
*/
void ShowDropDownMenu(Window *w, const StringID *strings, int selected, int button, uint32 disabled_mask, uint32 hidden_mask, uint width)
{
DropDownList *list = new DropDownList();
for (uint i = 0; strings[i] != INVALID_STRING_ID; i++) {
if (!HasBit(hidden_mask, i)) {
list->push_back(new DropDownListStringItem(strings[i], i, HasBit(disabled_mask, i)));
}
}
/* No entries in the list? */
if (list->size() == 0) {
DeleteDropDownList(list);
return;
}
ShowDropDownList(w, list, selected, button, width);
}
/**
* Delete the drop-down menu from window \a pw
* @param pw Parent window of the drop-down menu window
* @return Parent widget number if the drop-down was found and closed, \c -1 if the window was not found.
*/
int HideDropDownMenu(Window *pw)
{
Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->window_class != WC_DROPDOWN_MENU) continue;
DropdownWindow *dw = dynamic_cast<DropdownWindow*>(w);
if (pw->window_class == dw->parent_wnd_class &&
pw->window_number == dw->parent_wnd_num) {
int parent_button = dw->parent_button;
delete dw;
return parent_button;
}
}
return -1;
}
|
benjeffery/openttd
|
src/widgets/dropdown.cpp
|
C++
|
gpl-2.0
| 15,681
|
pimatic-plugin-template
=======================
Personalized for me...
|
sweetpi/pimatic-plugin-template
|
README.md
|
Markdown
|
gpl-2.0
| 71
|
import codecs
import collections
import os
import shutil
from PyQt4 import QtCore, QtGui, QtSvg
from Code.QT import Colocacion
from Code.QT import Controles
from Code.QT import FormLayout
from Code.QT import Iconos
from Code.QT import QTVarios
from Code import TrListas
from Code import VarGen
from Code.Constantes import *
class ConjuntoPiezas:
def __init__(self, nombre):
self.nombre = nombre
self.dicPiezas = self.leePiezas(nombre)
def leePiezas(self, nombre):
try:
dic = {}
for pieza in "rnbqkpRNBQKP":
fich = os.path.join("Pieces", nombre, "%s%s.svg" % ("w" if pieza.isupper() else "b", pieza.lower()))
f = codecs.open(fich, "r", 'utf-8', 'ignore')
qb = QtCore.QByteArray(f.read())
f.close()
dic[pieza] = qb
return dic
except:
return self.leePiezas("Cburnett")
def render(self, pieza):
return QtSvg.QSvgRenderer(self.dicPiezas[pieza])
def widget(self, pieza):
w = QtSvg.QSvgWidget()
w.load(self.dicPiezas[pieza])
return w
def pixmap(self, pieza, tam=24):
pm = QtGui.QPixmap(tam, tam)
pm.fill(QtCore.Qt.transparent)
render = self.render(pieza)
painter = QtGui.QPainter()
painter.begin(pm)
render.render(painter)
painter.end()
return pm
def label(self, owner, pieza, tam):
pm = self.pixmap(pieza, tam)
lb = Controles.LB(owner)
lb.ponImagen(pm)
lb.pieza = pieza
lb.tam_pieza = tam
return lb
def change_label(self, lb, tam):
if lb.tam_pieza <> tam:
pm = self.pixmap(lb.pieza, tam)
lb.ponImagen(pm)
def icono(self, pieza):
icon = QtGui.QIcon(self.pixmap(pieza, 32))
return icon
def cursor(self, pieza):
return QtGui.QCursor(self.pixmap(pieza))
class TodasPiezas:
def __init__(self):
self.dicConjuntos = {}
def selecciona(self, nombre):
if nombre in self.dicConjuntos:
return self.dicConjuntos[nombre]
else:
return self.nuevo(nombre)
def nuevo(self, nombre):
self.dicConjuntos[nombre] = ConjuntoPiezas(nombre)
return self.dicConjuntos[nombre]
def icono(self, pieza, nombre):
fich = os.path.join("Pieces", nombre, "%s%s.svg" % ("w" if pieza.isupper() else "b", pieza.lower()))
f = codecs.open(fich, "r", 'utf-8', 'ignore')
qb = QtCore.QByteArray(f.read())
f.close()
pm = QtGui.QPixmap(32, 32)
pm.fill(QtCore.Qt.transparent)
render = QtSvg.QSvgRenderer(qb)
painter = QtGui.QPainter()
painter.begin(pm)
render.render(painter)
painter.end()
icon = QtGui.QIcon(pm)
return icon
def iconoDefecto(self, pieza):
return self.icono(pieza, "Cburnett")
def saveAllPNG(self, nombre, px):
for pieza in "pnbrqk":
for color in "wb":
fich = os.path.join("Pieces", nombre, "%s%s.svg" % (color, pieza))
f = codecs.open(fich, "r", 'utf-8', 'ignore')
qb = QtCore.QByteArray(f.read())
f.close()
pm = QtGui.QPixmap(px, px)
pm.fill(QtCore.Qt.transparent)
render = QtSvg.QSvgRenderer(qb)
painter = QtGui.QPainter()
painter.begin(pm)
render.render(painter)
painter.end()
pm.save("IntFiles/Figs/%s%s.png" % (color, pieza), "PNG")
HIDE, GREY, CHECKER, SHOW = range(4)
class BlindfoldConfig:
def __init__(self, nomPiezasOri, dicPiezas=None):
self.nomPiezasOri = nomPiezasOri
if dicPiezas is None:
self.restore()
else:
self.dicPiezas = dicPiezas
def ficheroBase(self, pz, siWhite):
pz = pz.lower()
if siWhite:
pzT = pz.upper()
else:
pzT = pz
tipo = self.dicPiezas[pzT]
if tipo == SHOW:
pz = ("w" if siWhite else "b") + pz
return os.path.join("Pieces", self.nomPiezasOri, pz + ".svg")
if tipo == HIDE:
fich = "h"
elif tipo == GREY:
fich = "g"
elif tipo == CHECKER:
fich = "w" if siWhite else "b"
return os.path.join("././IntFiles", "blind_%s.svg" % fich)
def restore(self):
self.dicPiezas = VarGen.configuracion.leeVariables("BLINDFOLD")
if not self.dicPiezas:
for pieza in "rnbqkpRNBQKP":
self.dicPiezas[pieza] = HIDE
def save(self):
VarGen.configuracion.escVariables("BLINDFOLD", self.dicPiezas)
class Blindfold(ConjuntoPiezas):
def __init__(self, nomPiezasOri, tipo=kBlindfoldConfig):
self.nombre = "BlindFold"
self.carpetaBF = os.path.join(VarGen.configuracion.carpeta, "BlindFoldPieces")
self.carpetaPZ = "./IntFiles"
self.tipo = tipo
self.reset(nomPiezasOri)
def leePiezas(self, nombre=None): # nombre usado por compatibilidad
dic = {}
for pieza in "rnbqkpRNBQKP":
fich = os.path.join(self.carpetaBF, "%s%s.svg" % ("w" if pieza.isupper() else "b", pieza.lower()))
f = codecs.open(fich, "r", 'utf-8', 'ignore')
qb = QtCore.QByteArray(f.read())
f.close()
dic[pieza] = qb
return dic
def reset(self, nomPiezasOri):
if self.tipo == kBlindfoldConfig:
dicTPiezas = None
else:
w = b = HIDE
if self.tipo == kBlindfoldWhite:
b = SHOW
elif self.tipo == kBlindfoldBlack:
w = SHOW
dicTPiezas = {}
for pieza in "rnbqkp":
dicTPiezas[pieza] = b
dicTPiezas[pieza.upper()] = w
self.configBF = BlindfoldConfig(nomPiezasOri, dicPiezas=dicTPiezas)
if not os.path.isdir(self.carpetaBF):
os.mkdir(self.carpetaBF)
for siWhite in (True, False):
for pieza in "rnbqkp":
ori = self.configBF.ficheroBase(pieza, siWhite)
bs = "w" if siWhite else "b"
dest = os.path.join(self.carpetaBF, "%s%s.svg" % (bs, pieza))
shutil.copy(ori, dest)
self.dicPiezas = self.leePiezas()
class WBlindfold(QTVarios.WDialogo):
def __init__(self, owner, nomPiezasOri):
titulo = _("Blindfold") + " - " + _("Configuration")
icono = Iconos.Ojo()
extparam = "wblindfold"
QTVarios.WDialogo.__init__(self, owner, titulo, icono, extparam)
self.config = BlindfoldConfig(nomPiezasOri)
self.nomPiezasOri = nomPiezasOri
lbWhite = Controles.LB(self, _("White")).ponTipoLetra(peso=75, puntos=10)
lbBlack = Controles.LB(self, _("Black")).ponTipoLetra(peso=75, puntos=10)
self.dicWidgets = collections.OrderedDict()
self.dicImgs = {}
liOpciones = (
(_("Hide"), HIDE),
(_("Green"), GREY),
(_("Checker"), CHECKER),
(_("Show"), SHOW),
)
dicNomPiezas = TrListas.dicNomPiezas()
def haz(pz):
tpW = self.config.dicPiezas[pz.upper()]
tpB = self.config.dicPiezas[pz]
lbPZw = Controles.LB(self)
cbPZw = Controles.CB(self, liOpciones, tpW).capturaCambiado(self.reset)
lbPZ = Controles.LB(self, dicNomPiezas[pz.upper()]).ponTipoLetra(peso=75, puntos=10)
lbPZb = Controles.LB(self)
cbPZb = Controles.CB(self, liOpciones, tpB).capturaCambiado(self.reset)
self.dicWidgets[pz] = [lbPZw, cbPZw, lbPZ, lbPZb, cbPZb, None, None]
for pz in "kqrbnp":
haz(pz)
btAllW = Controles.PB(self, _("All White"), self.allWhite, plano=False)
self.cbAll = Controles.CB(self, liOpciones, HIDE)
btAllB = Controles.PB(self, _("All Black"), self.allBlack, plano=False)
btSwap = Controles.PB(self, _("Swap"), self.swap, plano=False)
liAcciones = ((_("Save"), Iconos.Grabar(), "grabar"), None,
(_("Cancel"), Iconos.Cancelar(), "cancelar"), None,
(_("Configurations"), Iconos.Opciones(), "configurations"), None,
)
tb = Controles.TB(self, liAcciones)
ly = Colocacion.G()
ly.controlc(lbWhite, 0, 1).controlc(lbBlack, 0, 3)
fila = 1
for pz in "kqrbnp":
lbPZw, cbPZw, lbPZ, lbPZb, cbPZb, tipoW, tipoB = self.dicWidgets[pz]
ly.control(cbPZw, fila, 0)
ly.controlc(lbPZw, fila, 1)
ly.controlc(lbPZ, fila, 2)
ly.controlc(lbPZb, fila, 3)
ly.control(cbPZb, fila, 4)
fila += 1
ly.filaVacia(fila, 20)
fila += 1
ly.controld(btAllW, fila, 0, 1, 2)
ly.control(self.cbAll, fila, 2)
ly.control(btAllB, fila, 3, 1, 2)
ly.controlc(btSwap, fila + 1, 0, 1, 5)
ly.margen(20)
layout = Colocacion.V().control(tb).otro(ly)
self.setLayout(layout)
self.reset()
def procesarTB(self):
getattr(self, self.sender().clave)()
def closeEvent(self):
self.guardarVideo()
def grabar(self):
self.guardarVideo()
self.config.save()
self.accept()
def cancelar(self):
self.guardarVideo()
self.reject()
def configurations(self):
dic = VarGen.configuracion.leeVariables("BLINDFOLD")
dicConf = collections.OrderedDict()
for k in dic:
if k.startswith("_"):
cl = k[1:]
dicConf[cl] = dic[k]
menu = QTVarios.LCMenu(self)
for k in dicConf:
menu.opcion((True, k), k, Iconos.PuntoAzul())
menu.separador()
menu.opcion((True, None), _("Save current configuration"), Iconos.PuntoVerde())
if dicConf:
menu.separador()
menudel = menu.submenu(_("Remove"), Iconos.Delete())
for k in dicConf:
menudel.opcion((False, k), k, Iconos.PuntoNegro())
resp = menu.lanza()
if resp is None:
return
si, cual = resp
if si:
if cual:
dpz = dic["_" + cual]
for pz in "kqrbnp":
lbPZw, cbPZw, lbPZ, lbPZb, cbPZb, tipoW, tipoB = self.dicWidgets[pz]
cbPZw.ponValor(dpz[pz.upper()])
cbPZb.ponValor(dpz[pz])
self.reset()
else:
liGen = [(None, None)]
liGen.append((_("Name") + ":", ""))
resultado = FormLayout.fedit(liGen, title=_("Save current configuration"), parent=self, anchoMinimo=460,
icon=Iconos.TutorialesCrear())
if resultado is None:
return None
accion, liResp = resultado
name = liResp[0].strip()
if not name:
return None
dic["_%s" % name] = self.config.dicPiezas
VarGen.configuracion.escVariables("BLINDFOLD", dic)
else:
del dic["_%s" % cual]
VarGen.configuracion.escVariables("BLINDFOLD", dic)
def allWhite(self):
tp = self.cbAll.valor()
for pzB in "rnbqkp":
lbPZw, cbPZw, lbPZ, lbPZb, cbPZb, tipoW, tipoB = self.dicWidgets[pzB]
cbPZw.ponValor(tp)
self.reset()
def allBlack(self):
tp = self.cbAll.valor()
for pzB in "rnbqkp":
lbPZw, cbPZw, lbPZ, lbPZb, cbPZb, tipoW, tipoB = self.dicWidgets[pzB]
cbPZb.ponValor(tp)
self.reset()
def swap(self):
for pzB in "rnbqkp":
lbPZw, cbPZw, lbPZ, lbPZb, cbPZb, tipoW, tipoB = self.dicWidgets[pzB]
tpB = cbPZb.valor()
tpW = cbPZw.valor()
cbPZb.ponValor(tpW)
cbPZw.ponValor(tpB)
self.reset()
def reset(self):
for pzB in "kqrbnp":
lbPZw, cbPZw, lbPZ, lbPZb, cbPZb, tipoW, tipoB = self.dicWidgets[pzB]
tipoNv = cbPZw.valor()
if tipoW != tipoNv:
pzW = pzB.upper()
self.config.dicPiezas[pzW] = tipoNv
self.dicWidgets[pzB][5] = tipoNv # tiene que ser pzB que esta en misnusculas
fich = self.config.ficheroBase(pzB, True)
if fich in self.dicImgs:
pm = self.dicImgs[fich]
else:
pm = QTVarios.fsvg2pm(fich, 32)
self.dicImgs[fich] = pm
lbPZw.ponImagen(pm)
tipoNv = cbPZb.valor()
if tipoB != tipoNv:
self.config.dicPiezas[pzB] = tipoNv
self.dicWidgets[pzB][6] = tipoNv
fich = self.config.ficheroBase(pzB, False)
if fich in self.dicImgs:
pm = self.dicImgs[fich]
else:
pm = QTVarios.fsvg2pm(fich, 32)
self.dicImgs[fich] = pm
lbPZb.ponImagen(pm)
|
lukasmonk/lucaschess
|
Code/QT/Piezas.py
|
Python
|
gpl-2.0
| 13,281
|
# -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2014 CERN.
##
## Invenio 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.
##
## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
from __future__ import absolute_import, print_function
from datetime import date
from invenio.base.i18n import _
from invenio.testsuite import make_test_suite, run_test_suite
from flask import url_for
from .helpers import DepositionTestCase
class SimpleRecordTest(DepositionTestCase):
def setUp(self):
self.clear('simple')
from invenio.modules.deposit.form import WebDepositForm
from invenio.modules.deposit import fields
from invenio.modules.deposit import field_widgets
from invenio.modules.deposit.types import SimpleRecordDeposition
class SimpleRecordTestForm(WebDepositForm):
keywords = fields.DynamicFieldList(
fields.TextField(
widget_classes='form-control',
widget=field_widgets.ColumnInput(class_="col-xs-10"),
),
label='Keywords',
add_label='Add another keyword',
icon='fa fa-tags fa-fw',
widget_classes='',
min_entries=1,
)
publication_date = fields.Date(
label=_('Publication date'),
icon='fa fa-calendar fa-fw',
description='Required. Format: YYYY-MM-DD.',
default=date.today(),
validators=[],
widget=field_widgets.date_widget,
widget_classes='input-sm',
export_key='imprint.date',
)
class simple(SimpleRecordDeposition):
name = "Simple Test"
name_plural = "Simple Tests"
group = "Tests"
draft_definitions = {
'default': SimpleRecordTestForm,
}
@classmethod
def process_sip_metadata(cls, deposition, metadata):
self.assert_process_metadata(deposition, metadata)
self.register(simple)
def tearDown(self):
self.unregister()
def assert_process_metadata(self, deposition, metadata):
pass
def test_registration(self):
self.assert401(self.client.get(url_for('webdeposit.index'),
follow_redirects=True))
self.login("admin", "")
res = self.client.get(url_for('webdeposit.index'))
self.assert200(res)
assert "Tests" in res.data
assert "Simple Test" in res.data
self.assert200(self.client.get(url_for(
'webdeposit.deposition_type_index', deposition_type='simple'
)))
def test_create_delete(self):
self.login("admin", "")
dep_id = self.create('simple')
self.assert200(self.client.get(url_for(
'webdeposit.run', deposition_type='simple', uuid=dep_id
)))
self.assert200(self.client.get(
url_for('webdeposit.delete',
deposition_type='simple', uuid=dep_id),
follow_redirects=True)
)
TEST_SUITE = make_test_suite(
SimpleRecordTest,
)
if __name__ == "__main__":
run_test_suite(TEST_SUITE)
|
MSusik/invenio
|
invenio/modules/deposit/testsuite/test_type_simplerecord.py
|
Python
|
gpl-2.0
| 3,865
|
/*
* Movable Type (r) Open Source (C) 2001-2012 Six Apart, Ltd.
* This program is distributed under the terms of the
* GNU General Public License, version 2.
*
* $Id$
*/
;(function($) {
var ES = MT.App.EditorStrategy;
ES.Multi = function() { ES.apply(this, arguments) };
$.extend(ES.Multi.prototype, ES.prototype, {
create: function(app, ids, format) {
app.editors = {};
$.each(ids, function() {
$('#' + this).show();
app.editors[this] = new MT.EditorManager(this, {
format: format,
wrap: true
});
var setFormat = app.editors[this]['setFormat'];
app.editors[this]['setFormat'] = function(format) {
$.each(app.editors, function() {
setFormat.apply(this, [format]);
});
};
});
},
set: function(app, id) {
var strategy = this;
if (app.editor) {
var height = app.editor.getHeight();
strategy._setWithHeight(app, id, height);
}
else {
strategy._setWithHeight(app, id, null);
}
},
_setWithHeight: function(app, id, height) {
$(app.editorIds).each(function() {
if (id == this) {
app.editors[this].show();
app.editor = app.editors[this];
if (height) {
app.editor.setHeight(height);
}
}
else {
app.editors[this].hide();
}
});
},
save: function() {
app.editor.save();
}
});
})(jQuery);
|
rosiro/MovableTypeOpenSource-5.2.2-yamucha
|
mt-static/js/editor/app/editor_strategy/multi.js
|
JavaScript
|
gpl-2.0
| 1,649
|
/***********************************************************************************
* *
* Voreen - The Volume Rendering Engine *
* *
* Copyright (C) 2005-2013 University of Muenster, Germany. *
* Visualization and Computer Graphics Group <http://viscg.uni-muenster.de> *
* For a list of authors please refer to the file "CREDITS.txt". *
* *
* This file is part of the Voreen software package. Voreen 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. *
* *
* Voreen 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 in the file *
* "LICENSE.txt" along with this file. If not, see <http://www.gnu.org/licenses/>. *
* *
* For non-commercial academic use see the license exception specified in the file *
* "LICENSE-academic.txt". To get information about commercial licensing please *
* contact the authors. *
* *
***********************************************************************************/
#ifndef VRN_VOLUMEOPERATORMORPHOLOGY_H
#define VRN_VOLUMEOPERATORMORPHOLOGY_H
#include "voreen/core/datastructures/volume/volumeoperator.h"
namespace voreen {
// Base class, defines interface for the operator (-> apply):
class VRN_CORE_API VolumeOperatorErosionBase : public UnaryVolumeOperatorBase {
public:
virtual Volume* apply(const VolumeBase* volume, int kernelSize = 3, ProgressBar* progressBar = 0) const = 0;
};
// Generic implementation:
template<typename T>
class VolumeOperatorErosionGeneric : public VolumeOperatorErosionBase {
public:
virtual Volume* apply(const VolumeBase* volume, int kernelSize = 3, ProgressBar* progressBar = 0) const;
//Implement isCompatible using a handy macro:
IS_COMPATIBLE
};
template<typename T>
Volume* VolumeOperatorErosionGeneric<T>::apply(const VolumeBase* vh, int kernelSize, ProgressBar* progressBar) const {
const VolumeRAM* v = vh->getRepresentation<VolumeRAM>();
if(!v)
return 0;
const VolumeAtomic<T>* volume = dynamic_cast<const VolumeAtomic<T>*>(v);
if(!volume)
return 0;
VolumeAtomic<T>* output = volume->clone();
VolumeAtomic<T>* pong = volume->clone();
size_t halfKernelDim = static_cast<size_t>(kernelSize / 2);
tgt::svec3 volDim = volume->getDimensions();
// kernel is separable => consecutively apply 1D kernel along each axis instead of a 3D kernel
// x-direction (volumeVol -> outputVol)
VRN_FOR_EACH_VOXEL_WITH_PROGRESS_SUB_TASK(pos, tgt::ivec3(0), volDim, progressBar, 0.f, 1.f/3) {
size_t xmin = pos.x >= halfKernelDim ? pos.x - halfKernelDim : 0;
size_t xmax = std::min(pos.x+halfKernelDim, volDim.x-1);
T val = volume->voxel(pos);
tgt::svec3 npos = pos;
for (npos.x=xmin; npos.x<=xmax; npos.x++) {
val = std::min(val, volume->voxel(npos));
}
output->voxel(pos) = val;
}
// y-direction (outputVol -> volumeVol)
VRN_FOR_EACH_VOXEL_WITH_PROGRESS_SUB_TASK(pos, tgt::ivec3(0), volDim, progressBar, 1.f/3, 1.f/3) {
size_t ymin = pos.y >= halfKernelDim ? pos.y - halfKernelDim : 0;
size_t ymax = std::min(pos.y+halfKernelDim, volDim.y-1);
T val = output->voxel(pos);
tgt::svec3 npos = pos;
for (npos.y=ymin; npos.y<=ymax; npos.y++) {
val = std::min(val, output->voxel(npos));
}
pong->voxel(pos) = val;
}
// z-direction (volumeVol -> outputVol)
VRN_FOR_EACH_VOXEL_WITH_PROGRESS_SUB_TASK(pos, tgt::ivec3(0), volDim, progressBar, 2.f/3, 1.f/3) {
size_t zmin = pos.z >= halfKernelDim ? pos.z - halfKernelDim : 0;
size_t zmax = std::min(pos.z+halfKernelDim, volDim.z-1);
T val = pong->voxel(pos);
tgt::svec3 npos = pos;
for (npos.z=zmin; npos.z<=zmax; npos.z++) {
val = std::min(val, pong->voxel(npos));
}
output->voxel(pos) = val;
}
if (progressBar)
progressBar->setProgress(1.f);
return new Volume(output, vh);
}
typedef UniversalUnaryVolumeOperatorGeneric<VolumeOperatorErosionBase> VolumeOperatorErosion;
// ========================================================================================
// Base class, defines interface for the operator (-> apply):
class VolumeOperatorDilationBase : public UnaryVolumeOperatorBase {
public:
virtual Volume* apply(const VolumeBase* volume, int kernelSize = 3, ProgressBar* progressBar = 0) const = 0;
};
// Generic implementation:
template<typename T>
class VolumeOperatorDilationGeneric : public VolumeOperatorDilationBase {
public:
virtual Volume* apply(const VolumeBase* volume, int kernelSize = 3, ProgressBar* progressBar = 0) const;
//Implement isCompatible using a handy macro:
IS_COMPATIBLE
};
template<typename T>
Volume* VolumeOperatorDilationGeneric<T>::apply(const VolumeBase* vh, int kernelSize, ProgressBar* progressBar) const {
const VolumeRAM* v = vh->getRepresentation<VolumeRAM>();
if(!v)
return 0;
const VolumeAtomic<T>* volume = dynamic_cast<const VolumeAtomic<T>*>(v);
if(!volume)
return 0;
VolumeAtomic<T>* output = volume->clone();
VolumeAtomic<T>* pong = volume->clone();
size_t halfKernelDim = kernelSize / 2;
tgt::svec3 volDim = volume->getDimensions();
// kernel is separable => consecutively apply 1D kernel along each axis instead of a 3D kernel
// x-direction (inputVol -> outputVol)
VRN_FOR_EACH_VOXEL_WITH_PROGRESS_SUB_TASK(pos, tgt::ivec3(0), volDim, progressBar, 0.f, 1.f/3) {
size_t xmin = pos.x >= halfKernelDim ? pos.x - halfKernelDim : 0;
size_t xmax = std::min(pos.x+halfKernelDim, volDim.x-1);
T val = volume->voxel(pos);
tgt::svec3 npos = pos;
for (npos.x=xmin; npos.x<=xmax; npos.x++) {
val = std::max(val, volume->voxel(npos));
}
output->voxel(pos) = val;
}
// y-direction (outputVol -> inputVol)
VRN_FOR_EACH_VOXEL_WITH_PROGRESS_SUB_TASK(pos, tgt::ivec3(0), volDim, progressBar, 1.f/3, 1.f/3) {
size_t ymin = pos.y >= halfKernelDim ? pos.y - halfKernelDim : 0;
size_t ymax = std::min(pos.y+halfKernelDim, volDim.y-1);
T val = output->voxel(pos);
tgt::svec3 npos = pos;
for (npos.y=ymin; npos.y<=ymax; npos.y++) {
val = std::max(val, output->voxel(npos));
}
pong->voxel(pos) = val;
}
// z-direction (inputVol -> outputVol)
VRN_FOR_EACH_VOXEL_WITH_PROGRESS_SUB_TASK(pos, tgt::ivec3(0), volDim, progressBar, 2.f/3, 1.f/3) {
size_t zmin = pos.z >= halfKernelDim ? pos.z - halfKernelDim : 0;
size_t zmax = std::min(pos.z+halfKernelDim, volDim.z-1);
T val = pong->voxel(pos);
tgt::svec3 npos = pos;
for (npos.z=zmin; npos.z<=zmax; npos.z++) {
val = std::max(val, pong->voxel(npos));
}
output->voxel(pos) = val;
}
if (progressBar)
progressBar->setProgress(1.f);
return new Volume(output, vh);
}
typedef UniversalUnaryVolumeOperatorGeneric<VolumeOperatorDilationBase> VolumeOperatorDilation;
} // namespace
#endif // VRN_VOLUMEOPERATOR_H
|
lathen/voreen
|
include/voreen/core/datastructures/volume/operators/volumeoperatormorphology.h
|
C
|
gpl-2.0
| 8,202
|
//
// ZJDNews.h
// VistaSeeWorld
//
// Created by qianfeng on 15-2-28.
// Copyright (c) 2015年 ZJD. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface ZJDNews : NSObject
@property (copy) NSString *author;
@property (copy) NSString *desc;
@property (copy) NSString *icon;
@property (copy) NSString *id;
@property (copy) NSString *pub_time;
@property (copy) NSString *title;
@end
|
idanielz/idanielz.github.io
|
OC/demos/VistaSeeWorld/VistaSeeWorld/ZJDNews.h
|
C
|
gpl-2.0
| 408
|
/*
* Asterisk -- An open source telephony toolkit.
*
* Copyright (C) 1999 - 2012, Digium, Inc.
*
* Mark Spencer <markster@digium.com>
*
* See http://www.asterisk.org for more information about
* the Asterisk project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, mailing lists and IRC
* channels for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*! \file
*
* \brief Various sorts of access control
*
* \author Mark Spencer <markster@digium.com>
*/
/*** MODULEINFO
<support_level>core</support_level>
***/
#include "asterisk.h"
ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
#include "asterisk/network.h"
#if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__Darwin__)
#include <fcntl.h>
#include <net/route.h>
#endif
#if defined(SOLARIS)
#include <sys/sockio.h>
#include <net/if.h>
#elif defined(HAVE_GETIFADDRS)
#include <ifaddrs.h>
#endif
#include "asterisk/acl.h"
#include "asterisk/channel.h"
#include "asterisk/utils.h"
#include "asterisk/lock.h"
#include "asterisk/srv.h"
#if (!defined(SOLARIS) && !defined(HAVE_GETIFADDRS))
static int get_local_address(struct ast_sockaddr *ourip)
{
return -1;
}
#else
static void score_address(const struct sockaddr_in *sin, struct in_addr *best_addr, int *best_score)
{
const char *address;
int score;
address = ast_inet_ntoa(sin->sin_addr);
/* RFC 1700 alias for the local network */
if (address[0] == '0') {
score = -25;
/* RFC 1700 localnet */
} else if (strncmp(address, "127", 3) == 0) {
score = -20;
/* RFC 1918 non-public address space */
} else if (strncmp(address, "10.", 3) == 0) {
score = -5;
/* RFC 1918 non-public address space */
} else if (strncmp(address, "172", 3) == 0) {
/* 172.16.0.0 - 172.19.255.255, but not 172.160.0.0 - 172.169.255.255 */
if (address[4] == '1' && address[5] >= '6' && address[6] == '.') {
score = -5;
/* 172.20.0.0 - 172.29.255.255, but not 172.200.0.0 - 172.255.255.255 nor 172.2.0.0 - 172.2.255.255 */
} else if (address[4] == '2' && address[6] == '.') {
score = -5;
/* 172.30.0.0 - 172.31.255.255, but not 172.3.0.0 - 172.3.255.255 */
} else if (address[4] == '3' && (address[5] == '0' || address[5] == '1')) {
score = -5;
/* All other 172 addresses are public */
} else {
score = 0;
}
/* RFC 2544 Benchmark test range (198.18.0.0 - 198.19.255.255, but not 198.180.0.0 - 198.199.255.255) */
} else if (strncmp(address, "198.1", 5) == 0 && address[5] >= '8' && address[6] == '.') {
score = -10;
/* RFC 1918 non-public address space */
} else if (strncmp(address, "192.168", 7) == 0) {
score = -5;
/* RFC 3330 Zeroconf network */
} else if (strncmp(address, "169.254", 7) == 0) {
/*!\note Better score than a test network, but not quite as good as RFC 1918
* address space. The reason is that some Linux distributions automatically
* configure a Zeroconf address before trying DHCP, so we want to prefer a
* DHCP lease to a Zeroconf address.
*/
score = -10;
/* RFC 3330 Test network */
} else if (strncmp(address, "192.0.2.", 8) == 0) {
score = -15;
/* Every other address should be publically routable */
} else {
score = 0;
}
if (score > *best_score) {
*best_score = score;
memcpy(best_addr, &sin->sin_addr, sizeof(*best_addr));
}
}
static int get_local_address(struct ast_sockaddr *ourip)
{
int s, res = -1;
#ifdef SOLARIS
struct lifreq *ifr = NULL;
struct lifnum ifn;
struct lifconf ifc;
struct sockaddr_in *sa;
char *buf = NULL;
int bufsz, x;
#endif /* SOLARIS */
#if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__) || defined(__Darwin__) || defined(__GLIBC__)
struct ifaddrs *ifap, *ifaphead;
int rtnerr;
const struct sockaddr_in *sin;
#endif /* BSD_OR_LINUX */
struct in_addr best_addr;
int best_score = -100;
memset(&best_addr, 0, sizeof(best_addr));
#if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__) || defined(__Darwin__) || defined(__GLIBC__)
rtnerr = getifaddrs(&ifaphead);
if (rtnerr) {
perror(NULL);
return -1;
}
#endif /* BSD_OR_LINUX */
s = socket(AF_INET, SOCK_STREAM, 0);
if (s > 0) {
#if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__) || defined(__Darwin__) || defined(__GLIBC__)
for (ifap = ifaphead; ifap; ifap = ifap->ifa_next) {
if (ifap->ifa_addr && ifap->ifa_addr->sa_family == AF_INET) {
sin = (const struct sockaddr_in *) ifap->ifa_addr;
score_address(sin, &best_addr, &best_score);
res = 0;
if (best_score == 0) {
break;
}
}
}
#endif /* BSD_OR_LINUX */
/* There is no reason whatsoever that this shouldn't work on Linux or BSD also. */
#ifdef SOLARIS
/* Get a count of interfaces on the machine */
ifn.lifn_family = AF_INET;
ifn.lifn_flags = 0;
ifn.lifn_count = 0;
if (ioctl(s, SIOCGLIFNUM, &ifn) < 0) {
close(s);
return -1;
}
bufsz = ifn.lifn_count * sizeof(struct lifreq);
if (!(buf = malloc(bufsz))) {
close(s);
return -1;
}
memset(buf, 0, bufsz);
/* Get a list of interfaces on the machine */
ifc.lifc_len = bufsz;
ifc.lifc_buf = buf;
ifc.lifc_family = AF_INET;
ifc.lifc_flags = 0;
if (ioctl(s, SIOCGLIFCONF, &ifc) < 0) {
close(s);
free(buf);
return -1;
}
for (ifr = ifc.lifc_req, x = 0; x < ifn.lifn_count; ifr++, x++) {
sa = (struct sockaddr_in *)&(ifr->lifr_addr);
score_address(sa, &best_addr, &best_score);
res = 0;
if (best_score == 0) {
break;
}
}
free(buf);
#endif /* SOLARIS */
close(s);
}
#if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__) || defined(__Darwin__)
freeifaddrs(ifaphead);
#endif /* BSD_OR_LINUX */
if (res == 0 && ourip) {
ast_sockaddr_setnull(ourip);
ourip->ss.ss_family = AF_INET;
((struct sockaddr_in *)&ourip->ss)->sin_addr = best_addr;
}
return res;
}
#endif /* HAVE_GETIFADDRS */
/* Free HA structure */
void ast_free_ha(struct ast_ha *ha)
{
struct ast_ha *hal;
while (ha) {
hal = ha;
ha = ha->next;
ast_free(hal);
}
}
/* Free ACL list structure */
struct ast_acl_list *ast_free_acl_list(struct ast_acl_list *acl_list)
{
struct ast_acl *current;
if (!acl_list) {
return NULL;
}
AST_LIST_LOCK(acl_list);
while ((current = AST_LIST_REMOVE_HEAD(acl_list, list))) {
ast_free_ha(current->acl);
ast_free(current);
}
AST_LIST_UNLOCK(acl_list);
AST_LIST_HEAD_DESTROY(acl_list);
ast_free(acl_list);
return NULL;
}
/* Copy HA structure */
void ast_copy_ha(const struct ast_ha *from, struct ast_ha *to)
{
ast_sockaddr_copy(&to->addr, &from->addr);
ast_sockaddr_copy(&to->netmask, &from->netmask);
to->sense = from->sense;
}
/* Create duplicate of ha structure */
static struct ast_ha *ast_duplicate_ha(struct ast_ha *original)
{
struct ast_ha *new_ha;
if ((new_ha = ast_calloc(1, sizeof(*new_ha)))) {
/* Copy from original to new object */
ast_copy_ha(original, new_ha);
}
return new_ha;
}
/* Create duplicate HA link list */
/* Used in chan_sip2 templates */
struct ast_ha *ast_duplicate_ha_list(struct ast_ha *original)
{
struct ast_ha *start = original;
struct ast_ha *ret = NULL;
struct ast_ha *current, *prev = NULL;
while (start) {
current = ast_duplicate_ha(start); /* Create copy of this object */
if (prev) {
prev->next = current; /* Link previous to this object */
}
if (!ret) {
ret = current; /* Save starting point */
}
start = start->next; /* Go to next object */
prev = current; /* Save pointer to this object */
}
return ret; /* Return start of list */
}
static int acl_new(struct ast_acl **pointer, const char *name) {
struct ast_acl *acl;
if (!(acl = ast_calloc(1, sizeof(*acl)))) {
return 1;
}
*pointer = acl;
ast_copy_string(acl->name, name, ACL_NAME_LENGTH);
return 0;
}
struct ast_acl_list *ast_duplicate_acl_list(struct ast_acl_list *original)
{
struct ast_acl_list *clone;
struct ast_acl *current_cursor;
struct ast_acl *current_clone;
/* Early return if we receive a duplication request for a NULL original. */
if (!original) {
return NULL;
}
if (!(clone = ast_calloc(1, sizeof(*clone)))) {
ast_log(LOG_WARNING, "Failed to allocate ast_acl_list struct while cloning an ACL\n");
return NULL;
}
AST_LIST_HEAD_INIT(clone);
AST_LIST_LOCK(original);
AST_LIST_TRAVERSE(original, current_cursor, list) {
if ((acl_new(¤t_clone, current_cursor->name))) {
ast_log(LOG_WARNING, "Failed to allocate ast_acl struct while cloning an ACL.");
continue;
}
/* Copy data from original ACL to clone ACL */
current_clone->acl = ast_duplicate_ha_list(current_cursor->acl);
current_clone->is_invalid = current_cursor->is_invalid;
current_clone->is_realtime = current_cursor->is_realtime;
AST_LIST_INSERT_TAIL(clone, current_clone, list);
}
AST_LIST_UNLOCK(original);
return clone;
}
/*!
* \brief
* Isolate a 32-bit section of an IPv6 address
*
* An IPv6 address can be divided into 4 32-bit chunks. This gives
* easy access to one of these chunks.
*
* \param sin6 A pointer to a struct sockaddr_in6
* \param index Which 32-bit chunk to operate on. Must be in the range 0-3.
*/
#define V6_WORD(sin6, index) ((uint32_t *)&((sin6)->sin6_addr))[(index)]
/*!
* \brief
* Apply a netmask to an address and store the result in a separate structure.
*
* When dealing with IPv6 addresses, one cannot apply a netmask with a simple
* logical and operation. Furthermore, the incoming address may be an IPv4 address
* and need to be mapped properly before attempting to apply a rule.
*
* \param addr The IP address to apply the mask to.
* \param netmask The netmask configured in the host access rule.
* \param result The resultant address after applying the netmask to the given address
* \retval 0 Successfully applied netmask
* \reval -1 Failed to apply netmask
*/
static int apply_netmask(const struct ast_sockaddr *addr, const struct ast_sockaddr *netmask,
struct ast_sockaddr *result)
{
int res = 0;
if (ast_sockaddr_is_ipv4(addr)) {
struct sockaddr_in result4 = { 0, };
struct sockaddr_in *addr4 = (struct sockaddr_in *) &addr->ss;
struct sockaddr_in *mask4 = (struct sockaddr_in *) &netmask->ss;
result4.sin_family = AF_INET;
result4.sin_addr.s_addr = addr4->sin_addr.s_addr & mask4->sin_addr.s_addr;
ast_sockaddr_from_sin(result, &result4);
} else if (ast_sockaddr_is_ipv6(addr)) {
struct sockaddr_in6 result6 = { 0, };
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) &addr->ss;
struct sockaddr_in6 *mask6 = (struct sockaddr_in6 *) &netmask->ss;
int i;
result6.sin6_family = AF_INET6;
for (i = 0; i < 4; ++i) {
V6_WORD(&result6, i) = V6_WORD(addr6, i) & V6_WORD(mask6, i);
}
memcpy(&result->ss, &result6, sizeof(result6));
result->len = sizeof(result6);
} else {
/* Unsupported address scheme */
res = -1;
}
return res;
}
/*!
* \brief
* Parse a netmask in CIDR notation
*
* \details
* For a mask of an IPv4 address, this should be a number between 0 and 32. For
* a mask of an IPv6 address, this should be a number between 0 and 128. This
* function creates an IPv6 ast_sockaddr from the given netmask. For masks of
* IPv4 addresses, this is accomplished by adding 96 to the original netmask.
*
* \param[out] addr The ast_sockaddr produced from the CIDR netmask
* \param is_v4 Tells if the address we are masking is IPv4.
* \param mask_str The CIDR mask to convert
* \retval -1 Failure
* \retval 0 Success
*/
static int parse_cidr_mask(struct ast_sockaddr *addr, int is_v4, const char *mask_str)
{
int mask;
if (sscanf(mask_str, "%30d", &mask) != 1) {
return -1;
}
if (is_v4) {
struct sockaddr_in sin;
if (mask < 0 || mask > 32) {
return -1;
}
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
/* If mask is 0, then we already have the
* appropriate all 0s address in sin from
* the above memset.
*/
if (mask != 0) {
sin.sin_addr.s_addr = htonl(0xFFFFFFFF << (32 - mask));
}
ast_sockaddr_from_sin(addr, &sin);
} else {
struct sockaddr_in6 sin6;
int i;
if (mask < 0 || mask > 128) {
return -1;
}
memset(&sin6, 0, sizeof(sin6));
sin6.sin6_family = AF_INET6;
for (i = 0; i < 4; ++i) {
/* Once mask reaches 0, we don't have
* to explicitly set anything anymore
* since sin6 was zeroed out already
*/
if (mask > 0) {
V6_WORD(&sin6, i) = htonl(0xFFFFFFFF << (mask < 32 ? (32 - mask) : 0));
mask -= mask < 32 ? mask : 32;
}
}
memcpy(&addr->ss, &sin6, sizeof(sin6));
addr->len = sizeof(sin6);
}
return 0;
}
void ast_append_acl(const char *sense, const char *stuff, struct ast_acl_list **path, int *error, int *named_acl_flag)
{
struct ast_acl *acl = NULL;
struct ast_acl *current;
struct ast_acl_list *working_list;
char *tmp, *list;
/* If the ACL list is currently uninitialized, it must be initialized. */
if (*path == NULL) {
struct ast_acl_list *list;
list = ast_calloc(1, sizeof(*list));
if (!list) {
/* Allocation Error */
if (error) {
*error = 1;
}
return;
}
AST_LIST_HEAD_INIT(list);
*path = list;
}
working_list = *path;
AST_LIST_LOCK(working_list);
/* First we need to determine if we will need to add a new ACL node or if we can use an existing one. */
if (strncasecmp(sense, "a", 1)) {
/* The first element in the path should be the unnamed, base ACL. If that's the case, we use it. If not,
* we have to make one and link it up appropriately. */
current = AST_LIST_FIRST(working_list);
if (!current || !ast_strlen_zero(current->name)) {
if (acl_new(&acl, "")) {
if (error) {
*error = 1;
}
}
// Need to INSERT the ACL at the head here.
AST_LIST_INSERT_HEAD(working_list, acl, list);
} else {
/* If the first element was already the unnamed base ACL, we just use that one. */
acl = current;
}
/* With the proper ACL set for modification, we can just pass this off to the ast_ha append function. */
acl->acl = ast_append_ha(sense, stuff, acl->acl, error);
AST_LIST_UNLOCK(working_list);
return;
}
/* We are in ACL append mode, so we know we'll be adding one or more named ACLs. */
list = ast_strdupa(stuff);
while ((tmp = strsep(&list, ","))) {
struct ast_ha *named_ha;
int already_included = 0;
/* Remove leading whitespace from the string in case the user put spaces between items */
tmp = ast_skip_blanks(tmp);
/* The first step is to check for a duplicate */
AST_LIST_TRAVERSE(working_list, current, list) {
if (!strcasecmp(current->name, tmp)) { /* ACL= */
/* Inclusion of the same ACL multiple times isn't a catastrophic error, but it will raise the error flag and skip the entry. */
ast_log(LOG_ERROR, "Named ACL '%s' is already included in the ast_acl container.", tmp);
if (error) {
*error = 1;
}
already_included = 1;
break;
}
}
if (already_included) {
continue;
}
if (acl_new(&acl, tmp)) {
/* This is a catastrophic allocation error and we'll return immediately if this happens. */
if (error) {
*error = 1;
}
AST_LIST_UNLOCK(working_list);
return;
}
/* Attempt to grab the Named ACL we are looking for. */
named_ha = ast_named_acl_find(tmp, &acl->is_realtime, &acl->is_invalid);
/* Set the ACL's ast_ha to the duplicated named ACL retrieved above. */
acl->acl = named_ha;
/* Raise the named_acl_flag since we are adding a named ACL to the ACL container. */
if (named_acl_flag) {
*named_acl_flag = 1;
}
/* Now insert the new ACL at the end of the list. */
AST_LIST_INSERT_TAIL(working_list, acl, list);
}
AST_LIST_UNLOCK(working_list);
}
int ast_acl_list_is_empty(struct ast_acl_list *acl_list)
{
struct ast_acl *head;
if (!acl_list) {
return 1;
}
AST_LIST_LOCK(acl_list);
head = AST_LIST_FIRST(acl_list);
AST_LIST_UNLOCK(acl_list);
if (head) {
return 0;
}
return 1;
}
struct ast_ha *ast_append_ha(const char *sense, const char *stuff, struct ast_ha *path, int *error)
{
struct ast_ha *ha;
struct ast_ha *prev = NULL;
struct ast_ha *ret;
char *tmp, *list = ast_strdupa(stuff);
char *address = NULL, *mask = NULL;
int addr_is_v4;
int allowing = strncasecmp(sense, "p", 1) ? AST_SENSE_DENY : AST_SENSE_ALLOW;
const char *parsed_addr, *parsed_mask;
ret = path;
while (path) {
prev = path;
path = path->next;
}
while ((tmp = strsep(&list, ","))) {
if (!(ha = ast_calloc(1, sizeof(*ha)))) {
if (error) {
*error = 1;
}
return ret;
}
address = strsep(&tmp, "/");
if (!address) {
address = tmp;
} else {
mask = tmp;
}
if (*address == '!') {
ha->sense = (allowing == AST_SENSE_DENY) ? AST_SENSE_ALLOW : AST_SENSE_DENY;
address++;
} else {
ha->sense = allowing;
}
if (!ast_sockaddr_parse(&ha->addr, address, PARSE_PORT_FORBID)) {
ast_log(LOG_WARNING, "Invalid IP address: %s\n", address);
ast_free_ha(ha);
if (error) {
*error = 1;
}
return ret;
}
/* If someone specifies an IPv4-mapped IPv6 address,
* we just convert this to an IPv4 ACL
*/
if (ast_sockaddr_ipv4_mapped(&ha->addr, &ha->addr)) {
ast_log(LOG_NOTICE, "IPv4-mapped ACL network address specified. "
"Converting to an IPv4 ACL network address.\n");
}
addr_is_v4 = ast_sockaddr_is_ipv4(&ha->addr);
if (!mask) {
parse_cidr_mask(&ha->netmask, addr_is_v4, addr_is_v4 ? "32" : "128");
} else if (strchr(mask, ':') || strchr(mask, '.')) {
int mask_is_v4;
/* Mask is of x.x.x.x or x:x:x:x:x:x:x:x variety */
if (!ast_sockaddr_parse(&ha->netmask, mask, PARSE_PORT_FORBID)) {
ast_log(LOG_WARNING, "Invalid netmask: %s\n", mask);
ast_free_ha(ha);
if (error) {
*error = 1;
}
return ret;
}
/* If someone specifies an IPv4-mapped IPv6 netmask,
* we just convert this to an IPv4 ACL
*/
if (ast_sockaddr_ipv4_mapped(&ha->netmask, &ha->netmask)) {
ast_log(LOG_NOTICE, "IPv4-mapped ACL netmask specified. "
"Converting to an IPv4 ACL netmask.\n");
}
mask_is_v4 = ast_sockaddr_is_ipv4(&ha->netmask);
if (addr_is_v4 ^ mask_is_v4) {
ast_log(LOG_WARNING, "Address and mask are not using same address scheme.\n");
ast_free_ha(ha);
if (error) {
*error = 1;
}
return ret;
}
} else if (parse_cidr_mask(&ha->netmask, addr_is_v4, mask)) {
ast_log(LOG_WARNING, "Invalid CIDR netmask: %s\n", mask);
ast_free_ha(ha);
if (error) {
*error = 1;
}
return ret;
}
if (apply_netmask(&ha->addr, &ha->netmask, &ha->addr)) {
/* This shouldn't happen because ast_sockaddr_parse would
* have failed much earlier on an unsupported address scheme
*/
char *failmask = ast_strdupa(ast_sockaddr_stringify(&ha->netmask));
char *failaddr = ast_strdupa(ast_sockaddr_stringify(&ha->addr));
ast_log(LOG_WARNING, "Unable to apply netmask %s to address %s\n", failmask, failaddr);
ast_free_ha(ha);
if (error) {
*error = 1;
}
return ret;
}
if (prev) {
prev->next = ha;
} else {
ret = ha;
}
prev = ha;
parsed_addr = ast_strdupa(ast_sockaddr_stringify(&ha->addr));
parsed_mask = ast_strdupa(ast_sockaddr_stringify(&ha->netmask));
ast_debug(3, "%s/%s sense %d appended to ACL\n", parsed_addr, parsed_mask, ha->sense);
}
return ret;
}
enum ast_acl_sense ast_apply_acl(struct ast_acl_list *acl_list, const struct ast_sockaddr *addr, const char *purpose)
{
struct ast_acl *acl;
/* If the list is NULL, there are no rules, so we'll allow automatically. */
if (!acl_list) {
return AST_SENSE_ALLOW;
}
AST_LIST_LOCK(acl_list);
AST_LIST_TRAVERSE(acl_list, acl, list) {
if (acl->is_invalid) {
/* In this case, the baseline ACL shouldn't ever trigger this, but if that somehow happens, it'll still be shown. */
ast_log(LOG_WARNING, "%sRejecting '%s' due to use of an invalid ACL '%s'.\n", purpose ? purpose : "", ast_sockaddr_stringify_addr(addr),
ast_strlen_zero(acl->name) ? "(BASELINE)" : acl->name);
AST_LIST_UNLOCK(acl_list);
return AST_SENSE_DENY;
}
if (acl->acl) {
if (ast_apply_ha(acl->acl, addr) == AST_SENSE_DENY) {
ast_log(LOG_NOTICE, "%sRejecting '%s' due to a failure to pass ACL '%s'\n", purpose ? purpose : "", ast_sockaddr_stringify_addr(addr),
ast_strlen_zero(acl->name) ? "(BASELINE)" : acl->name);
AST_LIST_UNLOCK(acl_list);
return AST_SENSE_DENY;
}
}
}
AST_LIST_UNLOCK(acl_list);
return AST_SENSE_ALLOW;
}
enum ast_acl_sense ast_apply_ha(const struct ast_ha *ha, const struct ast_sockaddr *addr)
{
/* Start optimistic */
enum ast_acl_sense res = AST_SENSE_ALLOW;
const struct ast_ha *current_ha;
for (current_ha = ha; current_ha; current_ha = current_ha->next) {
struct ast_sockaddr result;
struct ast_sockaddr mapped_addr;
const struct ast_sockaddr *addr_to_use;
#if 0 /* debugging code */
char iabuf[INET_ADDRSTRLEN];
char iabuf2[INET_ADDRSTRLEN];
/* DEBUG */
ast_copy_string(iabuf, ast_inet_ntoa(sin->sin_addr), sizeof(iabuf));
ast_copy_string(iabuf2, ast_inet_ntoa(ha->netaddr), sizeof(iabuf2));
ast_debug(1, "##### Testing %s with %s\n", iabuf, iabuf2);
#endif
if (ast_sockaddr_is_ipv4(&ha->addr)) {
if (ast_sockaddr_is_ipv6(addr)) {
if (ast_sockaddr_is_ipv4_mapped(addr)) {
/* IPv4 ACLs apply to IPv4-mapped addresses */
if (!ast_sockaddr_ipv4_mapped(addr, &mapped_addr)) {
ast_log(LOG_ERROR, "%s provided to ast_sockaddr_ipv4_mapped could not be converted. That shouldn't be possible.\n",
ast_sockaddr_stringify(addr));
continue;
}
addr_to_use = &mapped_addr;
} else {
/* An IPv4 ACL does not apply to an IPv6 address */
continue;
}
} else {
/* Address is IPv4 and ACL is IPv4. No biggie */
addr_to_use = addr;
}
} else {
if (ast_sockaddr_is_ipv6(addr) && !ast_sockaddr_is_ipv4_mapped(addr)) {
addr_to_use = addr;
} else {
/* Address is IPv4 or IPv4 mapped but ACL is IPv6. Skip */
continue;
}
}
/* For each rule, if this address and the netmask = the net address
apply the current rule */
if (apply_netmask(addr_to_use, ¤t_ha->netmask, &result)) {
/* Unlikely to happen since we know the address to be IPv4 or IPv6 */
continue;
}
if (!ast_sockaddr_cmp_addr(&result, ¤t_ha->addr)) {
res = current_ha->sense;
}
}
return res;
}
static int resolve_first(struct ast_sockaddr *addr, const char *name, int flag,
int family)
{
struct ast_sockaddr *addrs;
int addrs_cnt;
addrs_cnt = ast_sockaddr_resolve(&addrs, name, flag, family);
if (addrs_cnt > 0) {
if (addrs_cnt > 1) {
ast_debug(1, "Multiple addresses. Using the first only\n");
}
ast_sockaddr_copy(addr, &addrs[0]);
ast_free(addrs);
} else {
ast_log(LOG_WARNING, "Unable to lookup '%s'\n", name);
return -1;
}
return 0;
}
int ast_get_ip_or_srv(struct ast_sockaddr *addr, const char *hostname, const char *service)
{
char srv[256];
char host[256];
int srv_ret = 0;
int tportno;
if (service) {
snprintf(srv, sizeof(srv), "%s.%s", service, hostname);
if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, srv)) > 0) {
hostname = host;
}
}
if (resolve_first(addr, hostname, PARSE_PORT_FORBID, addr->ss.ss_family) != 0) {
return -1;
}
if (srv_ret > 0) {
ast_sockaddr_set_port(addr, tportno);
}
return 0;
}
struct dscp_codepoint {
char *name;
unsigned int space;
};
/* IANA registered DSCP codepoints */
static const struct dscp_codepoint dscp_pool1[] = {
{ "CS0", 0x00 },
{ "CS1", 0x08 },
{ "CS2", 0x10 },
{ "CS3", 0x18 },
{ "CS4", 0x20 },
{ "CS5", 0x28 },
{ "CS6", 0x30 },
{ "CS7", 0x38 },
{ "AF11", 0x0A },
{ "AF12", 0x0C },
{ "AF13", 0x0E },
{ "AF21", 0x12 },
{ "AF22", 0x14 },
{ "AF23", 0x16 },
{ "AF31", 0x1A },
{ "AF32", 0x1C },
{ "AF33", 0x1E },
{ "AF41", 0x22 },
{ "AF42", 0x24 },
{ "AF43", 0x26 },
{ "EF", 0x2E },
};
int ast_str2cos(const char *value, unsigned int *cos)
{
int fval;
if (sscanf(value, "%30d", &fval) == 1) {
if (fval < 8) {
*cos = fval;
return 0;
}
}
return -1;
}
int ast_str2tos(const char *value, unsigned int *tos)
{
int fval;
unsigned int x;
if (sscanf(value, "%30i", &fval) == 1) {
*tos = fval & 0xFF;
return 0;
}
for (x = 0; x < ARRAY_LEN(dscp_pool1); x++) {
if (!strcasecmp(value, dscp_pool1[x].name)) {
*tos = dscp_pool1[x].space << 2;
return 0;
}
}
return -1;
}
const char *ast_tos2str(unsigned int tos)
{
unsigned int x;
for (x = 0; x < ARRAY_LEN(dscp_pool1); x++) {
if (dscp_pool1[x].space == (tos >> 2)) {
return dscp_pool1[x].name;
}
}
return "unknown";
}
int ast_get_ip(struct ast_sockaddr *addr, const char *hostname)
{
return ast_get_ip_or_srv(addr, hostname, NULL);
}
int ast_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us)
{
int port;
int s;
port = ast_sockaddr_port(us);
if ((s = socket(ast_sockaddr_is_ipv6(them) ? AF_INET6 : AF_INET,
SOCK_DGRAM, 0)) < 0) {
ast_log(LOG_ERROR, "Cannot create socket\n");
return -1;
}
if (ast_connect(s, them)) {
ast_log(LOG_WARNING, "Cannot connect\n");
close(s);
return -1;
}
if (ast_getsockname(s, us)) {
ast_log(LOG_WARNING, "Cannot get socket name\n");
close(s);
return -1;
}
close(s);
{
const char *them_addr = ast_strdupa(ast_sockaddr_stringify_addr(them));
const char *us_addr = ast_strdupa(ast_sockaddr_stringify_addr(us));
ast_debug(3, "For destination '%s', our source address is '%s'.\n",
them_addr, us_addr);
}
ast_sockaddr_set_port(us, port);
return 0;
}
int ast_find_ourip(struct ast_sockaddr *ourip, const struct ast_sockaddr *bindaddr, int family)
{
char ourhost[MAXHOSTNAMELEN] = "";
struct ast_sockaddr root;
int res, port = ast_sockaddr_port(ourip);
/* just use the bind address if it is nonzero */
if (!ast_sockaddr_is_any(bindaddr)) {
ast_sockaddr_copy(ourip, bindaddr);
ast_debug(3, "Attached to given IP address\n");
return 0;
}
/* try to use our hostname */
if (gethostname(ourhost, sizeof(ourhost) - 1)) {
ast_log(LOG_WARNING, "Unable to get hostname\n");
} else {
if (resolve_first(ourip, ourhost, PARSE_PORT_FORBID, family) == 0) {
/* reset port since resolve_first wipes this out */
ast_sockaddr_set_port(ourip, port);
return 0;
}
}
ast_debug(3, "Trying to check A.ROOT-SERVERS.NET and get our IP address for that connection\n");
/* A.ROOT-SERVERS.NET. */
if (!resolve_first(&root, "A.ROOT-SERVERS.NET", PARSE_PORT_FORBID, 0) &&
!ast_ouraddrfor(&root, ourip)) {
/* reset port since resolve_first wipes this out */
ast_sockaddr_set_port(ourip, port);
return 0;
}
res = get_local_address(ourip);
ast_sockaddr_set_port(ourip, port);
return res;
}
|
xhook/asterisk-v11
|
main/acl.c
|
C
|
gpl-2.0
| 26,941
|
package graph;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import game.Graph;
import org.junit.Test;
public class GraphTest {
@Test
/**
* Test que comprueba el correcto funcionamiento del método existNode de la clase Graph
*/
public void existNodeTest() {
Graph<Integer> g = new Graph<Integer>(3);
g.addNode(2);
// Pruebas Positivas
assertEquals(true, g.existNode(2));
// Pruebas Negativas
assertEquals(false, g.existNode(5));
assertEquals(false, g.existNode(null));
}
@Test
/**
* Test que comprueba el correcto funcionamiento del método getEdge de la clase Graph
*/
public void getEdgeTest() {
Graph<Integer> g = new Graph<Integer>(4);
g.addNode(1);
g.addNode(2);
g.addNode(3);
g.addNode(4);
g.addEdge(1, 2, 10);
g.addEdge(1, 3, -2);
// Pruebas Positivas
assertEquals(10, g.getEdge(1, 2), 0.01);
assertEquals(-2, g.getEdge(1, 3), 0.01);
// Pruebas Negativas
assertEquals(-1, g.getEdge(3, 4), 0.01);
assertEquals(-1, g.getEdge(1, null), 0.01);
assertEquals(-1, g.getEdge(null, 2), 0.01);
}
@Test
/**
* Test que comprueba el correcto funcionamiento del método addNode de la clase Graph
*/
public void addNodeTest() {
Graph<Integer> g = new Graph<Integer>(3);
// Prueba positiva
assertEquals(0, g.addNode(1));
// Pruebas negativa de que si añado un nodo ya existente no lo añade
g.addNode(2);
assertEquals(-1, g.addNode(2));
// Prueba negativa de que si añado un nodo null no se añade
assertEquals(-1, g.addNode(null));
// Prueba negativa de que si intento añadir un nodo cuando el array est�
// lleno no se añade
g.addNode(3);
assertEquals(-1, g.addNode(4));
}
@Test
/**
* Test que comprueba el correcto funcionamiento del método removeNode de la clase Graph
*/
public void removeNodeTest() {
Graph<Integer> g = new Graph<Integer>(3);
g.addNode(1);
// Prueba positiva
assertEquals(0, g.removeNode(1));
// Pruebas negativas
assertEquals(-1, g.removeNode(2));
assertEquals(-1, g.removeNode(null));
}
@Test
/**
* Test que comprueba el correcto funcionamiento del método addEdge de la clase Graph
*/
public void addEdgeTest() {
Graph<Integer> g = new Graph<Integer>(3);
g.addNode(1);
g.addNode(2);
g.addNode(3);
// Prueba positiva
assertEquals(0, g.addEdge(1, 2, 2));
assertEquals(0, g.addEdge(1, 2, 4));
assertEquals(0, g.addEdge(1, 3, -2));
// Pruebas negativas
assertEquals(-1, g.addEdge(1, null, 2));
assertEquals(-1, g.addEdge(null, 2, 2));
assertEquals(-1, g.addEdge(4, 5, 2));
}
@Test
/**
* Test que comprueba el correcto funcionamiento del método removeEdge de la clase Graph
*/
public void removeEdgeTest() {
Graph<Integer> g = new Graph<Integer>(3);
g.addNode(1);
g.addNode(2);
g.addNode(3);
g.addEdge(1, 2, 4);
// Prueba positiva
assertEquals(0, g.removeEdge(1, 2));
// Prueba negativa
assertEquals(-1, g.removeEdge(1, null));
assertEquals(-1, g.removeEdge(null, 2));
assertEquals(-1, g.removeEdge(4, 5));
assertEquals(-1, g.removeEdge(2, 3));
}
@Test
/**
* Test que comprueba el correcto funcionamiento del método recorridoProfundidad de la clase Graph
*/
public void recorridoProfunidadTest() {
// Prueba 1
Graph<String> g = new Graph<String>(4);
g.addNode("A");
g.addNode("B");
g.addNode("C");
g.addNode("D");
g.addEdge("A", "B", 1);
g.addEdge("A", "C", 5);
g.addEdge("B", "C", 2);
g.addEdge("B", "D", 3);
g.addEdge("D", "A", 4);
assertEquals(0, g.recorridoProfundidad("A"));
assertEquals(0, g.recorridoProfundidad("B"));
assertEquals(-1, g.recorridoProfundidad("C"));
assertEquals(0, g.recorridoProfundidad("D"));
// Prueba negativa
assertEquals(-1, g.recorridoProfundidad(null));
}
@Test
/**
* Test que comprueba el correcto funcionamiento del método dijkstra de la clase Graph
*/
public void dijkstraTest() {
// Prueba 1
Graph<String> g = new Graph<String>(4);
g.addNode("A");
g.addNode("B");
g.addNode("C");
g.addNode("D");
g.addEdge("A", "B", 1);
g.addEdge("A", "C", 5);
g.addEdge("B", "C", 2);
g.addEdge("B", "D", 3);
g.addEdge("D", "A", 4);
assertArrayEquals(new double[] { 0.0, 1.0, 3.0, 4.0 }, g.dijkstra("A"),
0.01);
// Prueba 2
Graph<Integer> g2 = new Graph<Integer>(6);
g2.addNode(1);
g2.addNode(2);
g2.addNode(3);
g2.addNode(4);
g2.addNode(5);
g2.addNode(6);
g2.addEdge(1, 2, 3);
g2.addEdge(1, 3, 4);
g2.addEdge(1, 5, 8);
g2.addEdge(2, 5, 5);
g2.addEdge(3, 5, 3);
g2.addEdge(5, 6, 3);
g2.addEdge(5, 4, 7);
g2.addEdge(6, 4, 2);
assertArrayEquals(new double[] { 0.0, 3.0, 4.0, 12.0, 7.0, 10.0 },
g2.dijkstra(1), 0.01);
}
@Test
/**
* Test que comprueba el correcto funcionamiento del método floyd de la clase Graph
*/
public void floydTest() {
Graph<String> g = new Graph<String>(4);
g.addNode("A");
g.addNode("B");
g.addNode("C");
g.addNode("D");
g.addEdge("A", "B", 1.0);
g.addEdge("B", "C", 2.0);
g.addEdge("C", "D", 3.0);
g.addEdge("A", "D", 10.0);
assertArrayEquals(new int[][] { { -1, -1, 1, 2 }, { -1, -1, -1, 2 },
{ -1, -1, -1, -1 }, { -1, -1, -1, -1 } }, g.floyd());
// Prueba negativa 1. Hay alguna arista con peso negativo en el grafo
Graph<Integer> g2 = new Graph<Integer>(3);
g2.addNode(1);
g2.addNode(2);
g2.addNode(3);
g2.addEdge(1, 2, 2.0);
g2.addEdge(2, 3, -2.0);
assertNull(g2.floyd());
// Prueba negativa 2. No hay nodos en el grafo
Graph<Integer> g3 = new Graph<Integer>(3);
assertNull(g3.floyd());
}
@Test
/**
* Test que comprueba el correcto funcionamiento del método path de la clase Graph
*/
public void pathTest() {
Graph<String> g = new Graph<String>(4);
g.addNode("A");
g.addNode("B");
g.addNode("C");
g.addNode("D");
g.addEdge("A", "B", 1.0);
g.addEdge("B", "C", 2.0);
g.addEdge("C", "D", 3.0);
g.addEdge("A", "D", 10.0);
assertEquals(6.0, g.path("A", "D"), 0.01);
assertEquals(0.0, g.path("A", "A"), 0.01);
// Prueba negativa 1. Existen los nodos pasados por parámetro pero no
// hay camino entre ellos
Graph<String> g2 = new Graph<String>(4);
g2.addNode("A");
g2.addNode("B");
g2.addNode("C");
g2.addNode("D");
g2.addEdge("A", "B", 1.0);
g2.addEdge("C", "D", 2.0);
assertEquals(-1.0, g2.path("A", "D"), 0.01);
// Prueba negativa 2. No existen los dos nodos pasados por parámetro, o
// uno de ellos
assertEquals(-1.0, g2.path("X", "Y"), 0.01);
assertEquals(-1.0, g2.path("A", null), 0.01);
assertEquals(-1.0, g2.path(null, "B"), 0.01);
// Prueba negativa 3. Hay alguna arista con peso negativo y por tanto no
// podríamos utilizar el método floyd para calcular el path
Graph<Integer> g3 = new Graph<Integer>(3);
g3.addNode(1);
g3.addNode(2);
g3.addNode(3);
g3.addEdge(1, 2, 2.0);
g3.addEdge(2, 3, -2.0);
assertEquals(-1.0, g3.path(1, 2), 0.01);
}
@Test
/**
* Test que comprueba el correcto funcionamiento del método
excentricidad() de la clase Graph
*/
public void excentricidadTest() {
Graph<String> g = new Graph<String>(4);
g.addNode("A");
g.addNode("B");
g.addNode("C");
g.addNode("D");
g.addEdge("A", "B", 1.0);
g.addEdge("B", "C", 2.0);
g.addEdge("C", "D", 3.0);
g.addEdge("A", "D", 10.0);
assertEquals(Double.POSITIVE_INFINITY, g.excentricidad("A"), 0.01);
assertEquals(Double.POSITIVE_INFINITY, g.excentricidad("B"), 0.01);
assertEquals(Double.POSITIVE_INFINITY, g.excentricidad("C"), 0.01);
assertEquals(6.0, g.excentricidad("D"), 0.01);
// Prueba negativa
assertEquals(-1.0, g.excentricidad("X"), 0.01);
}
}
|
Arquisoft/Trivial3b
|
play-core/test/graph/GraphTest.java
|
Java
|
gpl-2.0
| 9,014
|
<?php
/**
* @file
*/
namespace Xylemical\Expressions;
use PHPUnit\Framework\TestCase;
class OperatorTest extends TestCase
{
public function testInvalidOperands()
{
$operator = new Operator('', 0, 0, 3, 'is_bool');
$this->expectException('Xylemical\\Expressions\\ExpressionException');
$operator->evaluate([], new Context, new Token(''));
}
}
|
smartcitiescommunity/Civikmind
|
plugins/formcreator/vendor/xylemical/php-expressions/tests/OperatorTest.php
|
PHP
|
gpl-2.0
| 386
|
<?php
namespace Octane\Tests\ExistingSite;
use weitzman\DrupalTestTraits\ExistingSiteBase;
/**
* This class can be extended or modified for project-specific testing.
*
* Note that ExistingSite tests typically reside in the relevant custom modules:
*
* `src/modules/custom_module_core/tests/src/ExistingSite`
*
* This base class, and the other tests here are meant to be used as starting
* points and examples.
*/
abstract class OctaneExistingSiteTestBase extends ExistingSiteBase {
}
|
phase2/octane
|
test/src/ExistingSite/OctaneExistingSiteTestBase.php
|
PHP
|
gpl-2.0
| 498
|
/**
* @author Steven Palmer
* @author url http://coalaweb.com
* @author email support@coalaweb.com
* @copyright Copyright (c) 2015 Steven Palmer All rights reserved.
*/
.sweet-alert fieldset input[type="text"] {display: none;}
|
isengartz/food
|
media/coalawebcontact/plugins/system/cwmailcheck/css/sweet-custom.css
|
CSS
|
gpl-2.0
| 272
|
<?php
//Create an Array for storing the dates that have events
$dates_with_events = array();
//Grab posts (endpoints)
$lcccevents = '';
$stockerevents = '';
$athleticevents = '';
$sportevents = '';
$categoryevents = '';
$domain = 'http://www.lorainccc.edu';
//$domain = 'http://' . $_SERVER['SERVER_NAME'];
$lcccevents = new Endpoint( $domain . '/mylccc/wp-json/wp/v2/lccc_events/?per_page=100' );
$athleticevents = new Endpoint( $domain . '/athletics/wp-json/wp/v2/lccc_events/?per_page=100' );
$stockerevents = new Endpoint( 'http://sites.lorainccc.edu/stocker/wp-json/wp/v2/lccc_events/?per_page=100' );
//Create instance
$multi = new MultiBlog( 1 );
$multi->add_endpoint ( $lcccevents );
$multi->add_endpoint ( $athleticevents );
$multi->add_endpoint ( $stockerevents );
//Fetch Posts(Events) from Endpoints
$posts = $multi->get_posts();
if(empty($posts)){
echo 'No Posts Found!';
}
//establishing current date for testing
$currentdate = date("Y-m-d");
//Filling array with dates with events
foreach ( $posts as $post ){
if( $post->event_end_date > $currentdate ){
array_push($dates_with_events, $post->event_end_date);
}
}
$dates_with_events = array_unique($dates_with_events);
$dates_with_events = array_filter($dates_with_events);
$dates_with_events = array_values($dates_with_events);
//echo '<br />';
//echo '<br />';
//echo 'Count: '.count($dates_with_events).'<br />';
//echo 'Without Empty: '.count($dates_with_events).'<br />';
//echo 'Events:'.'<br />';
/* for($y=0;$y < count($dates_with_events); $y++){
echo $y.': '.$dates_with_events[$y].'<br />';
}
*/
$current_month = date("n");
$current_year = date("Y");
$current_date = date("Y") . '-' . date("m") . '-' . date("d");
if(isset($_GET['disp_m'])){
$display_month = $_GET['disp_m'];
$display_year = $_GET['disp_y'];
} else {
$display_month = $current_month;
$display_year = $current_year;
}
$next_month = $display_month;
$next_year = $display_year;
$prev_month = $display_month;
$prev_year = $display_year;
if ($display_month == '12'){
$next_month = 1;
$next_year = date("Y")+1;
$prev_month -=1;
} elseif($display_month > '12'){
$next_month = 1;
$next_year = date("Y")+1;
$prev_month = 12;
} elseif($display_month < '12'){
$next_month +=1;
$prev_month -=1;
if ($prev_month == 0){
$prev_month = 12;
$prev_year -=1;
}
}
//echo 'Current Month: ' . $current_month . ' - ' . $current_year . '<br /><br />';
//echo 'Display Month: ' . $display_month . ' - ' . $display_year . '<br /><br />';
//echo 'Next Month: ' . $next_month . ' - ' . $next_year . '<br/><br />';
//echo 'Prev Month: ' . $prev_month . ' - ' . $prev_year . '<br/><br />';
$calendar = '<div id="calendar">';
$headings = array('Sun','Mon','Tues','Wed','Thurs','Fri','Sat');
$calendar .= '<div class="week heading"><div class="day heading"><div class="heading-text">'.implode('</div></div><div class="day heading"><div class="heading-text">', $headings).'</div></div></div>';
$running_day = date('w',mktime(0,0,0,$display_month,1,$display_year));
$days_in_month = date('t',mktime(0,0,0,$display_month,1,$display_year));
$days_in_this_week = 1;
$day_counter = 0;
$dates_array = array();
$calendar.= '<div class="week">';
for($x = 0; $x < $running_day; $x++):
$calendar.= '<div class="day-np"> </div>';
$days_in_this_week++;
endfor;
for($list_day = 1; $list_day <= $days_in_month; $list_day++):
// determine if day is single digit or two, and transform to two digits
if (strlen($list_day) == 1){
$day_of_week = '0' . $list_day;
}else{
$day_of_week = $list_day;
}
// determine if month is single digit or two, and transform to two digits
if (strlen($display_month) == 1){
$full_month = '0' . $display_month;
}else{
$full_month = $display_month;
}
// fully formed date to match WordPress date variable
$full_date = $display_year . '-' . $full_month . '-' . $day_of_week;
if($full_date == $current_date){
$bol_valid = false;
for($y=0;$y < count($dates_with_events); $y++){
if( $full_date == $dates_with_events[$y]){
$bol_valid = true;
}
}
if($bol_valid == true){
$calendar.= '<a href="/mylccc/day?d='.$full_date.'">';
$calendar.= '<div class="day current-day">';
$calendar.= '<div class="day-number">'.$list_day.'</div>';
$calendar.= '<a class="calendar-event-listing" href="/mylccc/day?d='.$full_date.'"></a>';
$calendar.= '</div></a>';
} else{
$calendar.= '<div class="day current-day">';
$calendar.= '<div class="day-number">'.$list_day.'</div>';
$calendar.= '</div>';
}
}else{
$bol_valid = false;
for($y=0;$y < count($dates_with_events); $y++){
if( $full_date == $dates_with_events[$y]){
$bol_valid = true;
}
}
if($bol_valid == true){
$calendar.= '<a style="display:block;" href="/mylccc/day?d='.$full_date.'">';
$calendar.= '<div class="day">';
$calendar.= '<div class="day-number">'.$list_day.'</div>';
$calendar.= '<a class="calendar-event-listing" href="/mylccc/day?d='.$full_date.'"></a>';
$calendar.= '</div></a>';
} else{
$calendar.= '<div class="day">';
$calendar.= '<div class="day-number">'.$list_day.'</div>';
$calendar.= '</div>';
}
}
if($running_day == 6):
$calendar.= '</div>';
if(($day_counter+1) != $days_in_month):
$calendar.= '<div class="week">';
endif;
$running_day = -1;
$days_in_this_week = 0;
endif;
$days_in_this_week++; $running_day++; $day_counter++;
endfor;
if($days_in_this_week < 8):
for($x = 1; $x <= (8 - $days_in_this_week); $x++):
$calendar.= '<div class="day-np"> </div>';
endfor;
endif;
$plugin_image_dir = plugin_dir_url( 'lccc-news.php').'lccc-news/images/';
if ($prev_month < $current_month && $prev_year == $current_year){
echo '<div class="calendar-header">';
echo '<div class="header-placeholder"> </div>';
echo '<div class="cur-month">' . date('F', mktime(0, 0, 0, $display_month, 10)) . ' ' . $display_year . '</div>';
echo '<div class="calendar-nav-next"><a href="?disp_m=' . $next_month . '&disp_y=' . $next_year . '"><img style="max-width:40%;" src="'.$plugin_image_dir.'Next-arrow.svg"></a></div></div><div style="clear:both;">';
echo '</div>';
}elseif($prev_month == $current_month && $prev_year == $current_year){
echo '<div class="calendar-header">';
echo '<div class="calendar-nav-prev"><a href="?disp_m=' . $prev_month . '&disp_y=' . $prev_year . '"><img style="max-width:40%;" src="'.$plugin_image_dir.'Prev-arrow.svg"></a></div>';
echo '<div class="cur-month">' . date('F', mktime(0, 0, 0, $display_month, 10)) . ' ' . $display_year . '</div>';
echo '<div class="calendar-nav-next"><a href="?disp_m=' . $next_month . '&disp_y=' . $next_year . '"><img style="max-width:40%;" src="'.$plugin_image_dir.'Next-arrow.svg"></a></div>';
echo '</div>';
echo '<div style="clear:both;"></div>';
}else{
echo '<div class="calendar-header">';
echo '<div class="calendar-nav-prev"><a href="?disp_m=' . $prev_month . '&disp_y=' . $prev_year . '"><img style="max-width:40%;" src="'.$plugin_image_dir.'Prev-arrow.svg"></a></div>';
echo '<div class="cur-month">' . date('F', mktime(0, 0, 0, $display_month, 10)) . ' ' . $display_year . '</div>';
echo '<div class="calendar-nav-next"><a href="?disp_m=' . $next_month . '&disp_y=' . $next_year . '"><img style="max-width:40%;" src="'.$plugin_image_dir.'Next-arrow.svg"></a></div>';
echo '</div>';
echo '<div style="clear:both;"></div>';
}
echo $calendar;
?>
|
lorainccc/lccc-news
|
php/original-calendar-working.php
|
PHP
|
gpl-2.0
| 7,672
|
namespace L2dotNET.GameService.model.skills2.speceffects
{
public class b_regen_mp_by_sit : TSpecEffect
{
public b_regen_mp_by_sit(double value)
{
this.value = value;
}
public override void OnStand(L2Player player)
{
if (mul)
player.CharacterStat.URegMpMul -= value;
else
player.CharacterStat.SpecBonusRegMP -= value;
}
public override void OnSit(L2Player player)
{
if (mul)
player.CharacterStat.URegMpMul += value;
else
player.CharacterStat.SpecBonusRegMP += value;
}
}
}
|
domis045/L2dotNET
|
src/L2dotNET.Game/model/skills2/speceffects/b_regen_mp_by_sit.cs
|
C#
|
gpl-2.0
| 687
|
<?php
/**
* FW Gallery 3.0
* @copyright (C) 2014 Fastw3b
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @link http://www.fastw3b.net/ Official website
**/
defined( '_JEXEC' ) or die( 'Restricted access' );
JHTML :: _('behavior.framework', true);
JHTML :: _('behavior.formvalidation');
JHTML :: script('administrator/components/com_fwgallery/assets/js/moorainbow.1.2b2.js');
JToolBarHelper :: title(JText::_('FWG_CONFIG').': <small><small>[ '.JText::_('FWG_EDIT').' ]</small></small>', 'fwgallery-config.png' );
JToolBarHelper::save();
JToolBarHelper::cancel();
$color = $this->obj->params->get('gallery_color');
if (preg_match('/[0-9a-fA-F]{3,6}/', $color)) $color = '#'.$color;
else $color = '';
?>
<form action="index.php?option=com_fwgallery&view=config" method="post" name="adminForm" id="adminForm" class="form-validate" enctype="multipart/form-data">
<div class="span6">
<fieldset class="adminform">
<legend><?php echo JText::_('FWG_IMAGE_SETTINGS'); ?></legend>
<table class="admintable">
<tr>
<td class="key">
<?php echo JText::_('FWG_THUMB_WIDTH'); ?> <span class="badge" title="<?php echo JText::_('FWG_TYPE_THE_WIDTH_FOR_THE_THUMBNAILS__THAT_WILL_SUIT_YOUR_NEEDS_MOST'); ?>">?</span><span class="badge badge-warning">*</span>
</td>
<td>
<input type="text" class="inputbox required validate-numeric" name="config[im_th_w]" value="<?php echo $this->obj->params->get('im_th_w', 160); ?>" size="5"/>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_THUMB_HEIGHT'); ?> <span class="badge" title="<?php echo JText::_('FWG_TYPE_THE_HEIGHT_FOR_THE_THUMBNAILS__THAT_WILL_SUIT_YOUR_NEEDS_MOST'); ?>">?</span> <span class="badge badge-warning">*</span>
</td>
<td>
<input type="text" class="inputbox required validate-numeric" name="config[im_th_h]" value="<?php echo $this->obj->params->get('im_th_h', 120); ?>" size="5"/>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_MEDIUM_SIZE_WIDTH'); ?> <span class="badge" title="<?php echo JText::_('FWG_THE_WIDTH_FOR_THE_MEDIUM_SIZE_IMAGE_DURING_FULL_SCREEN_VIEW'); ?>">?</span> <span class="badge badge-warning">*</span>
</td>
<td>
<input type="text" class="inputbox required validate-numeric" name="config[im_mid_w]" value="<?php echo $this->obj->params->get('im_mid_w', 340); ?>" size="5"/>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_MEDIUM_SIZE_HEIGHT'); ?> <span class="badge" title="<?php echo JText::_('FWG_THE_HEIGHT_FOR_THE_MEDIUM_SIZE_IMAGE_DURING_FULL_SCREEN_VIEW'); ?>">?</span> <span class="badge badge-warning">*</span>
</td>
<td>
<input type="text" class="inputbox required validate-numeric" name="config[im_mid_h]" value="<?php echo $this->obj->params->get('im_mid_h', 255); ?>" size="5"/>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_BIG_SIZE_WIDTH'); ?> <span class="badge" title="<?php echo JText::_('FWG_THE_PARAMETERS_OF_THE_IMAGE_FOR_LIGHTBOX_EFFECT_VIEW'); ?>">?</span> <span class="badge badge-warning">*</span>
</td>
<td>
<input type="text" class="inputbox required validate-numeric" name="config[im_max_w]" value="<?php echo $this->obj->params->get('im_max_w', 800); ?>" size="5"/>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_BIG_SIZE_HEIGHT'); ?> <span class="badge" title=" title="<?php echo JText::_('FWG_THE_PARAMETERS_OF_THE_IMAGE_FOR_LIGHTBOX_EFFECT_VIEW'); ?>"">?</span> <span class="badge badge-warning">*</span>
</td>
<td>
<input type="text" class="inputbox required validate-numeric" name="config[im_max_h]" value="<?php echo $this->obj->params->get('im_max_h', 600); ?>" size="5"/>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_THUMB_AND_MEDIUM_IMAGES_SHRINKING_METHOD'); ?>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'im_just_shrink', '', $this->obj->params->get('im_just_shrink'), JText :: _('FWG_JUST_SHRINK'), JText :: _('FWG_SHRINK_AND_CUT')); ?>
</fieldset>
</td>
</tr>
</table>
</fieldset>
<fieldset class="adminform">
<legend><?php echo JText::_('FWG_LAYOUT_SETTINGS'); ?></legend>
<table class="admintable">
<tr>
<td class="key">
<?php echo JText::_('FWG_GALLERIES_DEFAULT_COLOR'); ?> <span class="badge" title="<?php echo JText :: _('FWG_SELECT_ANY_COLOR_FROM_THE_COLOR_PALETTE_OR_JUST_TYPE_THE_COLOR__S_CODE__IF_YOU_KNOW_IT'); ?>">?</span>
</td>
<td id="color-row"<?php if ($color) { ?> style="background-color:<?php echo $color; ?>"<?php } ?>>
<img id="myRainbow" src="<?php echo JURI :: root(true); ?>/administrator/components/com_fwgallery/assets/images/rainbow.png" alt="[r]" width="16" height="16" />
<input id="color" name="config[gallery_color]" type="text" size="13" value="<?php echo $color; ?>" />
<button type="button" id="myRainbowButton"><?php echo JText :: _('FWG_SELECT'); ?></button>
<button type="button" id="myRainbowClearButton"><?php echo JText :: _('FWG_CLEAR'); ?></button>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_GALLERIES_IN_A_ROW'); ?> <span class="badge" title="<?php echo JText :: _('FWG_THE_NUMBER_DEPENDS_ON_THE_THUMB_SIZES_AND_THE_TEMPLATE_OF_YOUR_SITE__OBLIGATORY_FIELD'); ?>">?</span><span class="badge badge-warning">*</span>
</td>
<td>
<?php echo JHTML :: _('select.genericlist', $this->columns, 'config[galleries_a_row]', '', 'id', 'name', $this->obj->params->get('galleries_a_row', 3)); ?>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_IMAGES_IN_A_ROW'); ?> <span class="badge" title="<?php echo JText :: _('FWG_THE_NUMBER_DEPENDS_ON_THE_THUMB_SIZES_AND_THE_TEMPLATE_OF_YOUR_SITE__OBLIGATORY_FIELD'); ?>">?</span><span class="badge badge-warning">*</span>
</td>
<td>
<?php echo JHTML :: _('select.genericlist', $this->columns, 'config[images_a_row]', '', 'id', 'name', $this->obj->params->get('images_a_row', 3)); ?>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_GALLERIES_ROWS_PER_PAGE'); ?> <span class="badge" title="<?php echo JText::_('FWG_TYPE_THE_NUMBER_OF_GALLERIES__YOU_WANT_TO_BE_DISPLAYED_PER_PAGE'); ?>">?</span>
</td>
<td>
<input type="text" class="inputbox required validate-numeric" name="config[galleries_rows]" value="<?php echo $this->obj->params->get('galleries_rows', 4); ?>" size="5"/>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_IMAGES_ROWS_PER_PAGE'); ?> <span class="badge" title="<?php echo JText::_('FWG_TYPE_THE_NUMBER_OF_IMAGES_YOU_WANT_TO_BE_DISPLAYED_PER_PAGE'); ?>">?</span>
</td>
<td>
<input type="text" class="inputbox required validate-numeric" name="config[images_rows]" value="<?php echo $this->obj->params->get('images_rows', 4); ?>" size="5"/>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_DEFAULT_GALLERIES_ORDERING'); ?> <span class="badge" title="<?php echo JText::_('FWG_SELECT_ONE_OF_THE_FOUR_GALLERIES___ORDER_TYPES__THIS_OPTION_IS_AVAILABLE_ON_FRONT_END_TOO'); ?>">?</span>
</td>
<td>
<?php echo JHTML :: _('select.genericlist', array(
JHTML :: _('select.option', 'name', JText :: _('FWG_ALPHABETICALLY'), 'id', 'name'),
JHTML :: _('select.option', 'new', JText :: _('FWG_NEWEST_FIRST'), 'id', 'name'),
JHTML :: _('select.option', 'old', JText :: _('FWG_OLDEST_FIRST'), 'id', 'name'),
JHTML :: _('select.option', 'order', JText :: _('FWG_ORDERING'), 'id', 'name')
), 'config[ordering_galleries]', '', 'id', 'name', $this->obj->params->get('ordering_galleries', 'order')); ?>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_DEFAULT_IMAGES_ORDERING'); ?> <span class="badge" title="<?php echo JText::_('FWG_SELECT_ONE_OF_THE_FOUR_POSSIBLE_TYPES_OF_ORDER_FOR_IMAGES__THE_OPTION_IS_AVAILABLE_ON_FRONT_END_TOO'); ?>">?</span>
</td>
<td>
<?php echo JHTML :: _('select.genericlist', array(
JHTML :: _('select.option', 'name', JText :: _('FWG_ALPHABETICALLY'), 'id', 'name'),
JHTML :: _('select.option', 'new', JText :: _('FWG_NEWEST_FIRST'), 'id', 'name'),
JHTML :: _('select.option', 'old', JText :: _('FWG_OLDEST_FIRST'), 'id', 'name'),
JHTML :: _('select.option', 'order', JText :: _('FWG_ORDERING'), 'id', 'name'),
JHTML :: _('select.option', 'voting', JText :: _('FWG_VOTING'), 'id', 'name')
), 'config[ordering_images]', '', 'id', 'name', $this->obj->params->get('ordering_images', 'order')); ?>
</td>
</tr>
</table>
</fieldset>
<fieldset class="adminform">
<legend><?php echo JText::_('FWG_WATERMARK'); ?></legend>
<table class="admintable">
<tr>
<td class="key">
<?php echo JText::_('FWG_USE_WATERMARK'); ?> <span class="badge" title="<?php echo JText::_('FWG_YES_NO_OPTION__IF_YOU_DON__T_WANT_TO_USE_IT__THEN_SELECT__QUOT_NO_QUOT__HERE'); ?>">?</span>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'use_watermark', '', $this->obj->params->get('use_watermark')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_WATERMARK_POSITION'); ?> <span class="badge" title="<?php echo JText::_('FWG_SELECT_ONE_OF_THE_5_POSSIBLE_LOCATIONS_OF_THE_WATERMARK_SIGN_ON_IMAGES'); ?>">?</span>
</td>
<td>
<?php echo JHTML :: _('select.genericlist', array(
JHTML :: _('select.option', 'center', JText :: _('FWG_CENTER'), 'id', 'name'),
JHTML :: _('select.option', 'left top', JText :: _('FWG_LEFT_TOP'), 'id', 'name'),
JHTML :: _('select.option', 'right top', JText :: _('FWG_RIGHT_TOP'), 'id', 'name'),
JHTML :: _('select.option', 'left bottom', JText :: _('FWG_LEFT_BOTTOM'), 'id', 'name'),
JHTML :: _('select.option', 'right bottom', JText :: _('FWG_RIGHT_BOTTOM'), 'id', 'name')
), 'config[watermark_position]', '', 'id', 'name', $this->obj->params->get('watermark_position', 'left bottom')); ?>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_WATERMARK_FILE'); ?> <span class="badge" title="<?php echo JText::_('FWG_UPLOAD_A_FILE__THAT_WILL_BE_USED_AS_A_WATERMARK_ON_IMAGES'); ?>">?</span>
</td>
<td>
<?php
if ($this->obj->params->get('watermark_file')) {
if ($path = JFHelper :: getWatermarkFilename()) {
?>
<img src="<?php echo JURI :: root(true); ?>/<?php echo $path; ?>" /><br/>
<input type="checkbox" name="delete_watermark" value="1" /> <?php echo JText :: _('FWG_REMOVE_WATERMARK'); ?><br/>
<?php
} else {
?>
<p style="color:#f00;"><?php echo JText :: _('FWG_WATERMARK_FILE_NOT_FOUND_'); ?></p>
<?php
}
}
?>
<input id="watermark_file" type="file" class="inputbox" name="watermark_file" />
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_WATERMARK_TEXT'); ?> <span class="badge" title="<?php echo JText::_('FWG_TYPE_A_TEXT__THAT_WILL_BE_USED_AS_A_WATERMARK__IF_YOU_UPLOAD_A_FILE__THEN_TEXT_WON__T_BE_DISPLAYED'); ?>">?</span>
</td>
<td>
<input type="text" class="inputbox" name="config[watermark_text]" value="<?php echo $this->obj->params->get('watermark_text'); ?>" size="35"/>
</td>
</tr>
</table>
</fieldset>
<fieldset class="adminform">
<legend><?php echo JText::_('FWG_VOTING_SYSTEM'); ?></legend>
<table class="admintable">
<tr>
<td class="key">
<?php echo JText::_('FWG_USE_VOTING'); ?> <span class="badge" title="<?php echo JText::_('FWG_YES_NO_OPTION__SELECT__QUOT_NO_QUOT__IF_YOU_DON__T_WANT_TO_USE_VOTING_AT_ALL'); ?>">?</span>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'use_voting', '', $this->obj->params->get('use_voting')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_PUBLIC_VOTING'); ?> <span class="badge" title="<?php echo JText::_('FWG_LET_THE_VISITORS_PUBLIC_POLLS'); ?>">?</span>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'public_voting', '', $this->obj->params->get('public_voting')); ?>
</fieldset>
</td>
</tr>
</table>
</fieldset>
</div>
<div class="span6">
<fieldset class="adminform">
<legend><?php echo JText::_('FWG_DISPLAYING_SETTINGS'); ?></legend>
<table class="admintable">
<tr>
<td class="key">
<?php echo JText::_('FWG_DISPLAY_TOTAL_GALLERIES_COUNTER'); ?> <span class="badge" title="<?php echo JText::_('FWG_YES_NO_OPTION__SELECT__QUOT_NO_QUOT___IF_YOU_WANT_TO_HIDE_IT'); ?>">?</span>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'display_total_galleries', '', $this->obj->params->get('display_total_galleries')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_DISPLAY_GALLERY_OWNER_NAME'); ?> <span class="badge" title="<?php echo JText::_('FWG_YES_NO_OPTION__SELECT__QUOT_NO_QUOT___IF_YOU_WANT_TO_HIDE_IT'); ?>">?</span>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'display_owner_gallery', '', $this->obj->params->get('display_owner_gallery')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_DISPLAY_IMAGE_OWNER_NAME'); ?> <span class="badge" title="<?php echo JText::_('FWG_YES_NO_OPTION__SELECT__QUOT_NO_QUOT___IF_YOU_WANT_TO_HIDE_IT'); ?>">?</span>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'display_owner_image', '', $this->obj->params->get('display_owner_image')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_DISPLAY_GALLERY_DATE'); ?> <span class="badge" title="<?php echo JText::_('FWG_SHOW_OR_HIDE_THE_CREATION_DATE_OF_THE_GALLERY__BY_SELECTING_YES_NO'); ?>">?</span>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'display_date_gallery', '', $this->obj->params->get('display_date_gallery')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_DISPLAY_ORDER_BY_OPTION'); ?> <span class="badge" title="<?php echo JText::_('FWG_YES_NO_OPTION__SELECT__QUOT_NO_QUOT___IF_YOU_WANT_TO_HIDE_IT_IN_THE_FRONT_END'); ?>">?</span>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'display_gallery_sorting', '', $this->obj->params->get('display_gallery_sorting')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_DISPLAY_GALLERY_NAME'); ?> <span class="badge" title="<?php echo JText::_('FWG_SHOW_OR_HIDE_THE_NAME_OF_THE_GALLERY__CLICKING_YES_NO'); ?>">?</span>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'display_name_gallery', '', $this->obj->params->get('display_name_gallery')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_DISPLAY_IMAGE_NAME'); ?> <span class="badge" title="<?php echo JText::_('FWG_SHOW_OR_HIDE_THE_NAME_OF_THE_IMAGES___ADDING_TO_THE_GALLERY__CLICKING_YES_NO'); ?>">?</span>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'display_name_image', '', $this->obj->params->get('display_name_image')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_DISPLAY_IMAGE_DATE'); ?> <span class="badge" title="<?php echo JText::_('FWG_SHOW_OR_HIDE_THE_DATE_OF_THE_IMAGES___ADDING_TO_THE_GALLERY__CLICKING_YES_NO'); ?>">?</span>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'display_date_image', '', $this->obj->params->get('display_date_image')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_DISPLAY_IMAGE_VIEWS'); ?> <span class="badge" title="<?php echo JText::_('FWG_SHOW_OR_HIDE_THE_NUMBER_OF_IMAGE_VIEWS__SELECTING_YES_NO_OPTIONS'); ?>">?</span>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'display_image_views', '', $this->obj->params->get('display_image_views')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_ALLOW_IMAGE_DOWNLOAD'); ?>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'allow_image_download', '', $this->obj->params->get('allow_image_download')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_DISPLAY_IMAGE_TAGS'); ?>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'display_image_tags', '', $this->obj->params->get('display_image_tags')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_ALLOW_PRINT_BUTTON'); ?>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'allow_print_button', '', $this->obj->params->get('allow_print_button')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_HIDE_BOTTOM_IMAGES'); ?>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'hide_bottom_image', '', $this->obj->params->get('hide_bottom_image')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_DISPLAY_USERS_COPYRIGHT'); ?> <span class="badge" title="<?php echo JText::_('FWG_SHOW_OR_HIDE_USERS_COPYRIGHT_SELECTING_YES_NO'); ?>">?</span>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'display_user_copyright', '', $this->obj->params->get('display_user_copyright')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_DATE_FORMAT'); ?> <span class="badge" title="<?php echo JText::_('FWG_SET_A_SUITABLE_DATE_FORMAT_FOR_THE_FRONT_END__MONTH__DAY_AND_YEAR'); ?>">?</span>
</td>
<td>
<input type="text" class="inputbox" name="config[date_format]" value="<?php echo $this->obj->params->get('date_format', '%B %d, %Y'); ?>" size="15"/>
<a href="http://docs.joomla.org/How_do_you_change_the_date_format%3F" target="_blank"><?php echo JText::_('FWG_DATE_OPTIONS'); ?></a>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_DISPLAY_ICON_NEW_DAYS'); ?> <span class="badge" title="<?php echo JText::_('FWG_THE_NUMBER_OF_DAYS__WHEN_ADDED_IMAGE_WILL_HAVE_THE_ICON__QUOT_NEW_QUOT__IN_THE_LEFT_TOP'); ?>">?</span>
</td>
<td>
<input type="text" class="inputbox" name="config[new_days]" value="<?php echo $this->obj->params->get('new_days', 7); ?>" size="5"/>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText :: _('FWG_DISPLAY_LIGHTBOX_GALLERIES'); ?>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'display_galleries_lightbox', '', $this->obj->params->get('display_galleries_lightbox')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_HIDE_MIGNIFIER__LIGHTBOX_EFFECT_'); ?>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'hide_mignifier', '', $this->obj->params->get('hide_mignifier')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_HIDE_SINGLE_IMAGE_VIEW'); ?>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'hide_single_image_view', '', $this->obj->params->get('hide_single_image_view')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_HIDE_IPHONE_APP_PROMO'); ?>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'hide_iphone_app_promo', '', $this->obj->params->get('hide_iphone_app_promo')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_DISPLAY_SOCIAL_SHARING'); ?>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'display_social_sharing', '', $this->obj->params->get('display_social_sharing')); ?>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo JText::_('FWG_HIDE_FASTW3B_COPYRIGHT'); ?> <span class="badge" title="<?php echo JText::_('FWG_IF_YOU_DON__T_WANT_TO_DISPLAY_FASTW3B_COPYRIGHT_ON_THE_FRONT_END_OF_YOUR_WEBSITE__THEN_SELECT__QUOT_NO_QUOT__HERE'); ?>">?</span>
</td>
<td>
<fieldset class="radio btn-group">
<?php echo JHTML :: _('select.booleanlist', 'hide_fw_copyright', '', $this->obj->params->get('hide_fw_copyright')); ?>
</fieldset>
<div id="fw-copyright-donation" style="display:none">
<?php echo JText :: _('FWG_FWGALLERY_COPYRIGHT_HIDE'); ?>
</div>
</td>
</tr>
</table>
</fieldset>
<?php
if ($this->plugins) {
?>
<fieldset class="adminform">
<legend><?php echo JText::_('FWG_ADDITIONAL_SETTINGS'); ?></legend>
<?php
foreach ($this->plugins as $plugin) if ($plugin) {
?>
<fieldset class="adminform">
<?php
echo $plugin;
?>
</fieldset>
<?php
}
?>
</fieldset>
<?php
}
?>
</div>
<div style="clear:both;"></div>
<input type="hidden" name="task" value="" />
</form>
<script type="text/javascript">
var copyrightEff;
var fwgRainbow;
window.addEvent('domready', function() {
document.getElement('#myRainbowButton').addEvent('click', function(ev) {
document.getElement('#myRainbow').fireEvent('click', ev);
});
document.getElement('#myRainbowClearButton').addEvent('click', function(ev) {
document.getElement('#color').value = '';
document.getElement('#color-row').setStyle('background-color', '');
});
document.getElement('#color').addEvent('keyup', function() {
if (this.value.match(/^#[0-9a-fA-F]{3,6}$/)) {
document.getElement('#color-row').setStyle('background-color', this.value);
fwgRainbow.manualSet(this.value, 'hex');
} else {
document.getElement('#color-row').setStyle('background-color', '');
}
});
fwgRainbow = new MooRainbow('myRainbow', {
wheel: true,
imgPath: '<?php echo JURI :: root(true); ?>/administrator/components/com_fwgallery/assets/images/',
onChange: function(color) {
document.getElement('#color').value = color.hex;
document.getElement('#color-row').setStyle('background-color', color.hex);
},
onComplete: function(color) {
document.getElement('#color').value = color.hex;
document.getElement('#color-row').setStyle('background-color', color.hex);
}
});
<?php
if ($color) {
?>
fwgRainbow.manualSet('<?php echo $color; ?>', 'hex');
<?php
}
?>
document.getElements('#adminForm input').each(function (el) {
if (el.name == 'hide_fw_copyright') {
el.addEvent('click', check_copyright);
el.addEvent('change', check_copyright);
}
});
copyrightEff = new Fx.Slide(document.getElement('#fw-copyright-donation'));
copyrightEff.hide();
document.getElement('#fw-copyright-donation').setStyle('display', '');
check_copyright();
});
function check_copyright() {
document.getElements('#adminForm input').each(function (el) {
if (el.name == 'hide_fw_copyright' && el.checked) {
if (el.value == '0') copyrightEff.slideOut();
else copyrightEff.slideIn()
}
});
}
Joomla.submitbutton = function(task) {
if (task == 'save') {
if (!document.formvalidator.isValid(document.getElement('#adminForm'))) {
alert('<?php echo JText :: _('FWG_NOT_ALL_REQUIRED_FIELDS_PROPERLY_FILLED_IN'); ?>');
return;
}
if (document.getElement('#watermark_file') && document.getElement('#watermark_file').value && !document.getElement('#watermark_file').value.match(/\.png$/i)) {
alert('<?php echo JText :: _('FWG_ALLOWED_PNG_AND_GIF_FILES_AS_WATERMARK_IMAGES_ONLY'); ?>');
return;
}
}
document.getElement('#adminForm').task.value = task;
document.getElement('#adminForm').submit();
}
</script>
|
Jbouska419/craftsman
|
administrator/components/com_fwgallery/views/config/tmpl/edit.php
|
PHP
|
gpl-2.0
| 27,789
|
<?php
/*
* @version $Id: ruleticket.php 22657 2014-02-12 16:17:54Z moyo $
-------------------------------------------------------------------------
GLPI - Gestionnaire Libre de Parc Informatique
Copyright (C) 2003-2014 by the INDEPNET Development Team.
http://indepnet.net/ http://glpi-project.org
-------------------------------------------------------------------------
LICENSE
This file is part of GLPI.
GLPI is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
GLPI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
/** @file
* @brief
*/
include ('../inc/includes.php');
$rulecollection = new RuleTicketCollection($_SESSION['glpiactive_entity']);
include (GLPI_ROOT . "/front/rule.common.php");
?>
|
elitelinux/hack-space
|
php/front/ruleticket.php
|
PHP
|
gpl-2.0
| 1,285
|
body.mlyrics {
color: rgb(219,219,219);
background-color: rgb(102,102,102);
padding: 10px;
font-family: Ubuntu, Lucida Grande, Lucida Sans, Helvetica, Arial, Sans;
}
h1#mlyrics_title {
color: white;
font-size: 14px;
font-weight: bold;
}
h2#mlyrics_artist {
font-size: 12px;
}
h3#mlyrics_album {
font-size: 12px;
}
p.mlyrics_lyrics {
font-size: 11px;
margin-top: 0;
margin-bottom: 0;
}
body.mlyrics p.header,
body.mlyrics p.separator1,
body.mlyrics p.separator2 {
display: none;
}
/* Text selection color */
::-moz-selection {
background-color: rgb(251,212,227);
color: rgb(5,5,5);
}
.mlyrics_lyrics_timetracked {
font-size: 11px;
color: rgb(178, 18, 88);
}
|
FreeleX/MLyrics
|
chrome/content/style/bluemonday.css
|
CSS
|
gpl-2.0
| 692
|
<?php
/**
* Action functions
*
* Inject content through template hooks
*
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
if ( ! function_exists( 'wolf_404_bg' ) ) {
/**
* Output 404 page background CSS in head
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_404_bg() {
if ( is_404() && wolf_get_theme_option( '404_bg' ) ) {
?>
<style type="text/css">
.error404 #page-content{
background-image: url(<?php echo esc_url( wolf_get_url_from_attachment_id( wolf_get_theme_option( '404_bg' ), 'extra-large' ) ); ?>);
}
</style>
<?php
}
}
add_action( 'wp_head', 'wolf_404_bg' );
}
if ( ! function_exists( 'wolf_scroll_arrow' ) ) {
/**
* Output scroll arrow
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_scroll_arrow() {
if ( ! is_404() )
?>
<div id="top"></div><a id="top-arrow" class="scroll" href="#top"></a>
<?php
}
add_action( 'wolf_body_start', 'wolf_scroll_arrow' );
}
if ( ! function_exists( 'wolf_page_loader' ) ) {
/**
* Output loader overlay
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_page_loader() {
if ( wolf_get_theme_option( 'page_transition' ) ) :
$loader = wolf_get_theme_option( 'loader_type' );
?>
<div id="loading-overlay"><div id="loader">
<?php if ( wolf_get_theme_option( 'loading_logo' ) ) : ?>
<img id="loading-logo" src="<?php echo esc_url( wolf_get_url_from_attachment_id( wolf_get_theme_option( 'loading_logo' ), 'logo' ) ); ?>" alt="loading-logo">
<?php endif; ?>
<?php if ( wolf_get_theme_option( 'loader' ) ) : ?>
<?php if ( 'loader1' == $loader ) : ?>
<div class="loader1"></div>
<?php elseif ( 'loader2' == $loader ) : ?>
<div class="loader2">
<div class="loader2-double-bounce1"></div>
<div class="loader2-double-bounce2"></div>
</div>
<?php elseif ( 'loader3' == $loader ) : ?>
<div class="loader3">
<div class="loader3-rect1"></div>
<div class="loader3-rect2"></div>
<div class="loader3-rect3"></div>
<div class="loader3-rect4"></div>
<div class="loader3-rect5"></div>
</div>
<?php elseif ( 'loader4' == $loader ) : ?>
<div class="loader4">
<div class="loader4-cube1"></div>
<div class="loader4-cube2"></div>
</div>
<?php elseif ( 'loader5' == $loader ) : ?>
<!-- <div class="loader5"></div> -->
<div class="loading">
<div class="loading-bar"></div>
<div class="loading-bar"></div>
<div class="loading-bar"></div>
<div class="loading-bar"></div>
</div>
<?php elseif ( 'loader6' == $loader ) : ?>
<div class="loader6">
<div class="loader6-dot1"></div>
<div class="loader6-dot2"></div>
</div>
<?php elseif ( 'loader7' == $loader ) : ?>
<div class="loader7">
<div class="loader7-bounce1"></div>
<div class="loader7-bounce2"></div>
<div class="loader7-bounce3"></div>
</div>
<?php elseif ( 'loader8' == $loader ) : ?>
<div class="loader8">
<div class="loader8-container loader8-container1">
<div class="loader8-circle1"></div>
<div class="loader8-circle2"></div>
<div class="loader8-circle3"></div>
<div class="loader8-circle4"></div>
</div>
<div class="loader8-container loader8-container2">
<div class="loader8-circle1"></div>
<div class="loader8-circle2"></div>
<div class="loader8-circle3"></div>
<div class="loader8-circle4"></div>
</div>
<div class="loader8-container loader8-container3">
<div class="loader8-circle1"></div>
<div class="loader8-circle2"></div>
<div class="loader8-circle3"></div>
<div class="loader8-circle4"></div>
</div>
</div>
<?php endif; ?>
<?php endif; ?>
</div></div>
<?php
endif;
}
add_action( 'wolf_body_start', 'wolf_page_loader' );
}
if ( ! function_exists( 'wolf_top_search_form' ) ) {
/**
* Output search form
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_top_search_form() {
if ( wolf_get_theme_option( 'search_menu_item' ) ) {
echo '<div id="top-search-form-container"><div id="top-search-form">';
get_search_form();
echo '</div></div>';
}
}
add_action( 'wolf_body_start', 'wolf_top_search_form' );
}
if ( ! function_exists( 'wolf_output_message_bar' ) ) {
/**
* Output message bar plugin function
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_output_message_bar() {
if ( function_exists( 'wolf_message_bar' ) )
wolf_message_bar();
}
add_action( 'wolf_body_start', 'wolf_output_message_bar' );
}
if ( ! function_exists( 'wolf_output_top_bar' ) ) {
/**
* Output message bar plugin function
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_output_top_bar() {
if ( wolf_get_theme_option( 'top_bar' ) && 'left' != wolf_get_theme_option( 'menu_position' ) ) {
get_template_part( 'partials/top', 'bar' );
}
}
add_action( 'wolf_body_start', 'wolf_output_top_bar' );
}
if ( ! function_exists( 'wolf_main_menu' ) ) {
/**
* Output main menu
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_main_menu() {
if ( 'default' == wolf_get_theme_option( 'menu_position' ) || 'center' == wolf_get_theme_option( 'menu_position' ) ) {
echo '<div id="ceiling">';
get_template_part( 'partials/navigation/navigation', 'desktop' );
echo '</div>';
}
}
add_action( 'wolf_body_start', 'wolf_main_menu' );
}
if ( ! function_exists( 'wolf_main_menu_logo_centered' ) ) {
/**
* Output main menu
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_main_menu_logo_centered() {
if ( 'logo-centered' == wolf_get_theme_option( 'menu_position' ) ) {
echo '<div id="ceiling">';
get_template_part( 'partials/navigation/navigation', 'logo-centered' );
echo '</div>';
}
}
add_action( 'wolf_body_start', 'wolf_main_menu_logo_centered' );
}
if ( ! function_exists( 'wolf_left_main_menu' ) ) {
/**
* Output main menu
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_left_main_menu() {
if ( 'left' == wolf_get_theme_option( 'menu_position' ) )
get_template_part( 'partials/navigation/navigation', 'left' );
}
add_action( 'wolf_site_content_start', 'wolf_left_main_menu' );
}
if ( ! function_exists( 'wolf_output_mobile_hello_bar' ) ) {
/**
* Output mobile hello bar
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_output_mobile_hello_bar() {
if ( 'modern' != wolf_get_theme_option( 'menu_position' ) ) :
?>
<div id="mobile-bar" class="clearfix">
<div id="mobile-bar-inner">
<div id="menu-toggle" class="menu-toggle">
<div class="burger-before"></div>
<div class="burger"></div>
<div class="burger-after"></div>
</div>
<?php echo wolf_logo(); ?>
</div>
</div>
<?php
endif;
}
add_action( 'wolf_body_start', 'wolf_output_mobile_hello_bar' );
}
if ( ! function_exists( 'wolf_output_side_menu_toggle' ) ) {
/**
* Output Secondary Menu toggle
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_output_side_menu_toggle() {
$menus = array( 'default', 'center', 'logo-centered' );
if ( wolf_get_theme_option( 'additional_toggle_menu' ) && in_array( wolf_get_theme_option( 'menu_position' ), $menus ) ) : ?>
<div id="side-menu-toggle" class="toggle-add-menu"><div class="plus"></div></div>
<?php
endif;
}
add_action( 'wolf_body_start', 'wolf_output_side_menu_toggle' );
}
if ( ! function_exists( 'wolf_additional_menu' ) ) {
/**
* Output secondary menu
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_additional_menu() {
if ( wolf_get_theme_option( 'additional_toggle_menu' ) && ( 'default' == wolf_get_theme_option( 'menu_position' ) || 'center' == wolf_get_theme_option( 'menu_position' ) || 'logo-centered' == wolf_get_theme_option( 'menu_position' ) ) ) {
if ( 'side' == wolf_get_theme_option( 'additional_toggle_menu_type' ) )
get_template_part( 'partials/navigation/navigation', 'side-panel' );
if ( 'overlay' == wolf_get_theme_option( 'additional_toggle_menu_type' ) )
get_template_part( 'partials/navigation/navigation', 'overlay' );
}
}
add_action( 'wolf_body_start', 'wolf_additional_menu' );
}
if ( ! function_exists( 'wolf_mobile_menu' ) ) {
/**
* Output mobile menu
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_mobile_menu() {
if ( 'modern' != wolf_get_theme_option( 'menu_position' ) )
get_template_part( 'partials/navigation/navigation', 'mobile' );
}
add_action( 'wolf_body_start', 'wolf_mobile_menu' );
}
if ( ! function_exists( 'wolf_modern_menu_toggle' ) ) {
/**
* Output modern menu
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_modern_menu_toggle() {
if ( 'modern' == wolf_get_theme_option( 'menu_position' ) ) {
?>
<div id="menu-toggle-modern" class="menu-toggle">
<div class="burger-before"></div>
<div class="burger"></div>
<div class="burger-after"></div>
</div>
<?php
}
}
add_action( 'wolf_body_start', 'wolf_modern_menu_toggle' );
}
if ( ! function_exists( 'wolf_modern_menu_overlay' ) ) {
/**
* Output modern menu overlay
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_modern_menu_overlay() {
if ( 'modern' == wolf_get_theme_option( 'menu_position' ) ) {
?>
<div id="modern-menu-overlay"></div>
<?php
}
}
add_action( 'wolf_body_start', 'wolf_modern_menu_overlay' );
}
if ( ! function_exists( 'wolf_modern_menu' ) ) {
/**
* Output modern menu
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_modern_menu() {
if ( 'modern' == wolf_get_theme_option( 'menu_position' ) )
get_template_part( 'partials/navigation/navigation', 'modern' );
}
add_action( 'wolf_body_start', 'wolf_modern_menu' );
}
if ( ! function_exists( 'wolf_cart_menu_item' ) ) {
/**
* Add a cart menu item
*
* @access public
* @since 1.0.0
* @param
* @return void
*/
function wolf_cart_menu_item ( $items, $args ) {
if ( class_exists( 'WooCommerce' ) && function_exists( 'wc_get_page_id' ) ) {
$cart_url = get_permalink( wc_get_page_id( 'cart' ) );
$woo_item = '<li class="cart-menu-item">';
$woo_item .= "<a class='cart-menu-item-link' href='$cart_url'>";
$woo_item .= '<span class="product-count">' . WC()->cart->cart_contents_count . '</span>';
$woo_item .= '<span class="cart-text">' . __( 'Cart', 'wolf' ) . '</span>';
$woo_item .= '</a>';
$woo_item .= '<span class="cart-menu-panel">';
$woo_item .= "<a href='$cart_url'>";
$woo_item .= '<span class="icon-cart"></span>';
$woo_item .= '<span class="panel-product-count">';
$woo_item .= sprintf( _n( '%d item', '%d items', WC()->cart->cart_contents_count, 'wolf' ), WC()->cart->cart_contents_count );
$woo_item .= '</span></br>'; // count
$woo_item .= '<span class="panel-total">';
$woo_item .= __( 'Total', 'wolf' ) . ' ' . WC()->cart->get_cart_total();
$woo_item .= '</span>'; // total
//' . __( 'Total', 'wolf' ) . ' ' . $total . '
$woo_item .= '</a>';
$woo_item .= '</span>';
$woo_item .= '</li>';
// var_dump( $woocommerce->cart );
if ( ( $args->theme_location == 'primary' || $args->theme_location == 'primary-right' ) && wolf_get_theme_option( 'cart_menu_item' ) ) {
$items .= $woo_item;
}
}
return $items;
}
add_filter( 'wp_nav_menu_items', 'wolf_cart_menu_item', 10, 2 );
}
if ( ! function_exists( 'wolf_main_menu_socials' ) ) {
/**
* Output social icons in main menu
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_main_menu_socials( $items, $args ) {
$services = wolf_get_theme_option( 'menu_socials_services' );
$socials_item = '';
if ( $services ) {
$socials_item = '<li class="socials-menu-item">';
$socials_item .= wolf_theme_socials( $services, '1x', 'span' );
$socials_item .= '</li>';
}
if ( 'default' == wolf_get_theme_option( 'menu_position' ) || 'logo-centered' == wolf_get_theme_option( 'menu_position' ) ) {
if ( $args->theme_location == 'primary' || $args->theme_location == 'primary-right' ) {
$items .= $socials_item;
}
}
return $items;
}
add_filter( 'wp_nav_menu_items', 'wolf_main_menu_socials', 10, 2 );
}
if ( ! function_exists( 'wolf_search_menu_item' ) ) {
/**
* Add a search menu item
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_search_menu_item( $items, $args ) {
$search_item = '<li class="search-menu-item">
<a class="search-menu-item-link" href="#">
<span class="search-text">' . __( 'Search', 'wolf' ) . '</span></a></li>';
if ( ( $args->theme_location == 'primary' || $args->theme_location == 'primary-right' ) && wolf_get_theme_option( 'search_menu_item' ) ) {
$items .= $search_item;
}
return $items;
}
add_filter( 'wp_nav_menu_items', 'wolf_search_menu_item', 10, 2 );
}
if ( ! function_exists( 'wolf_toggle_menu_item' ) ) {
/**
* Add a toggle menu item
*/
function wolf_toggle_menu_item ( $items, $args ) {
$menus = array( 'default', 'center', 'logo-centered' );
$toggle_text = wolf_get_theme_option( 'toggle_side_menu_item_text' );
$toggle_item = '<li class="toggle-menu-item"><a class="toggle-menu-item-link toggle-add-menu" href="#">';
if ( $toggle_text )
$toggle_item .= '<span class="toggle-text">' . $toggle_text . '</span>';
$toggle_item .= '</a></li>';
if (
( $args->theme_location == 'primary' || $args->theme_location == 'primary-right' )
&& wolf_get_theme_option( 'additional_toggle_menu' )
&& in_array( wolf_get_theme_option( 'menu_position' ), $menus )
) {
$items .= $toggle_item;
}
return $items;
}
add_filter( 'wp_nav_menu_items', 'wolf_toggle_menu_item', 10, 2 );
}
if ( ! function_exists( 'wolf_header_overlay' ) ) {
/**
* Output home header
*/
function wolf_header_overlay() {
if ( ! wolf_is_slider_in_home_header() && 'wolf_slider' != wolf_get_theme_option( 'home_header_type' ) ) :
?>
<div class="header-overlay"></div>
<?php endif;
}
add_action( 'wolf_header_start', 'wolf_header_overlay' );
}
if ( ! function_exists( 'wolf_home_header' ) ) {
/**
* Output home header
*/
function wolf_home_header() {
if (
is_front_page() && ! is_paged()
|| is_page_template( 'page-templates/home.php' )
&& 'none' != wolf_get_theme_option( 'home_header_type' )
)
get_template_part( 'partials/header', 'home' );
}
add_action( 'wolf_header_start', 'wolf_home_header' );
}
if ( ! function_exists( 'wolf_header_gallery_slideshow' ) ) {
/**
* Output header gallery slideshow
*/
function wolf_header_gallery_slideshow() {
if ( is_single() && 'gallery' == get_post_format() ) {
get_template_part( 'partials/slider', 'header-gallery' );
}
}
add_action( 'wolf_header_start', 'wolf_header_gallery_slideshow' );
}
if ( ! function_exists( 'wolf_scroll_down_arrow' ) ) {
/**
* Output scroll down arrow
*/
function wolf_scroll_down_arrow() {
if ( wolf_get_theme_option( 'scroll_down_arrow' ) ) {
?>
<a id="scroll-down" class="scroll" href="#main"></a>
<?php
}
}
add_action( 'wolf_header_end', 'wolf_scroll_down_arrow' );
}
if ( ! function_exists( 'wolf_share_links' ) ) {
/**
* Share links below single posts
*
* @param bool $display
* @return string
*/
function wolf_share_links() {
$post_type = get_post_type();
if ( wolf_get_theme_option( $post_type . '_share' ) ) { // is theme option checked
get_template_part( 'partials/share', 'post' );
}
}
add_action( 'wolf_post_end_singular', 'wolf_share_links' );
}
if ( ! function_exists( 'wolf_author_meta' ) ) {
/**
* Output author bio box
*/
function wolf_author_meta() {
if (
wolf_get_theme_option( 'show_author_box' )
&& 'post' == get_post_type() || 'review' == get_post_type()
) {
get_template_part( 'partials/author', 'bio' );
}
}
add_action( 'wolf_post_end_singular', 'wolf_author_meta' );
}
if ( ! function_exists( 'wolf_display_author_info_in_author_archive' ) ) {
/**
* Display the author info at the top of the author archive pages
*/
function wolf_display_author_info_in_author_archive() {
if ( is_author() && wolf_get_theme_option( 'show_author_box' ) )
get_template_part( 'partials/author', 'bio' );
}
add_action( 'wolf_page_before', 'wolf_display_author_info_in_author_archive' );
}
if ( ! function_exists( 'wolf_output_music_network' ) ) {
/**
* Output music network icons
*/
// function wolf_output_music_network() {
// if ( function_exists( 'wolf_music_network' ) ) {
// if ( wolf_is_music_network() ) {
// echo '<div class="music-social-icons-container">';
// wolf_music_network();
// echo '</div>';
// }
// }
// }
add_action( 'wolf_footer_before', 'wolf_output_music_network' );
}
if ( ! function_exists( 'wolf_bottom_menu' ) ) {
/**
* Output bottom menu
*/
function wolf_bottom_menu() {
if ( has_nav_menu( 'tertiary' ) ) {
?>
<nav id="site-navigation-tertiary" class="wrap navigation tertiary-navigation" role="navigation">
<?php wp_nav_menu(
array(
'theme_location' => 'tertiary',
'menu_class' => 'nav-menu-tertiary inline-list',
'fallback_cb' => '',
'depth' => 1,
)
); ?>
</nav><!-- #site-navigation-tertiary-->
<?php
}
}
add_action( 'wolf_footer_end', 'wolf_bottom_menu' );
}
if ( ! function_exists( 'wolf_bottom_socials' ) ) {
/**
* Output social icons
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_bottom_socials() {
if ( wolf_get_theme_option( 'bottom_socials' ) ) {
$services = wolf_get_theme_option( 'bottom_socials_services' );
echo wolf_theme_socials( $services, '1x' );
}
}
add_action( 'wolf_footer_end', 'wolf_bottom_socials' );
}
if ( ! function_exists( 'wolf_output_pagination' ) ) {
/**
* Output pagination on blog page
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_output_pagination() {
if ( wolf_is_blog() ) {
get_template_part( 'partials/pagination' );
}
}
add_action( 'wolf_page_after', 'wolf_output_pagination' );
}
if ( ! function_exists( 'wolf_print_post_navigation' ) ) {
/**
* Output related post or post nav depending on metabox
*
* @access public
* @since 1.0.0
* @return void
*/
function wolf_print_post_navigation() {
$nav_type = wolf_get_single_blog_post_nav_type();
$post_types = array( 'post' );
if ( in_array( get_post_type(), $post_types ) ) {
if ( 'related' == $nav_type ) {
get_template_part( 'partials/related', 'posts' );
} else {
wolf_post_nav();
}
}
}
add_action( 'wolf_post_end', 'wolf_print_post_navigation' );
}
|
estrategasdigitales/dictobas
|
wp-content/themes/decibel/includes/actions.php
|
PHP
|
gpl-2.0
| 19,600
|
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ir.nikagram.messenger.support.widget;
import static ir.nikagram.messenger.support.widget.RecyclerView.NO_POSITION;
import android.content.Context;
import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.accessibility.AccessibilityEventCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.support.v4.view.accessibility.AccessibilityRecordCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
/**
* A LayoutManager that lays out children in a staggered grid formation.
* It supports horizontal & vertical layout as well as an ability to layout children in reverse.
* <p>
* Staggered grids are likely to have gaps at the edges of the layout. To avoid these gaps,
* StaggeredGridLayoutManager can offset spans independently or move items between spans. You can
* control this behavior via {@link #setGapStrategy(int)}.
*/
public class StaggeredGridLayoutManager extends RecyclerView.LayoutManager {
public static final String TAG = "StaggeredGridLayoutManager";
private static final boolean DEBUG = false;
public static final int HORIZONTAL = OrientationHelper.HORIZONTAL;
public static final int VERTICAL = OrientationHelper.VERTICAL;
/**
* Does not do anything to hide gaps.
*/
public static final int GAP_HANDLING_NONE = 0;
@SuppressWarnings("unused")
@Deprecated
public static final int GAP_HANDLING_LAZY = 1;
/**
* When scroll state is changed to {@link RecyclerView#SCROLL_STATE_IDLE}, StaggeredGrid will
* check if there are gaps in the because of full span items. If it finds, it will re-layout
* and move items to correct positions with animations.
* <p>
* For example, if LayoutManager ends up with the following layout due to adapter changes:
* <pre>
* AAA
* _BC
* DDD
* </pre>
* <p>
* It will animate to the following state:
* <pre>
* AAA
* BC_
* DDD
* </pre>
*/
public static final int GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS = 2;
private static final int INVALID_OFFSET = Integer.MIN_VALUE;
/**
* While trying to find next view to focus, LayoutManager will not try to scroll more
* than this factor times the total space of the list. If layout is vertical, total space is the
* height minus padding, if layout is horizontal, total space is the width minus padding.
*/
private static final float MAX_SCROLL_FACTOR = 1 / 3f;
/**
* Number of spans
*/
private int mSpanCount = -1;
private Span[] mSpans;
/**
* Primary orientation is the layout's orientation, secondary orientation is the orientation
* for spans. Having both makes code much cleaner for calculations.
*/
@NonNull
OrientationHelper mPrimaryOrientation;
@NonNull
OrientationHelper mSecondaryOrientation;
private int mOrientation;
/**
* The width or height per span, depending on the orientation.
*/
private int mSizePerSpan;
@NonNull
private final LayoutState mLayoutState;
private boolean mReverseLayout = false;
/**
* Aggregated reverse layout value that takes RTL into account.
*/
boolean mShouldReverseLayout = false;
/**
* Temporary variable used during fill method to check which spans needs to be filled.
*/
private BitSet mRemainingSpans;
/**
* When LayoutManager needs to scroll to a position, it sets this variable and requests a
* layout which will check this variable and re-layout accordingly.
*/
int mPendingScrollPosition = NO_POSITION;
/**
* Used to keep the offset value when {@link #scrollToPositionWithOffset(int, int)} is
* called.
*/
int mPendingScrollPositionOffset = INVALID_OFFSET;
/**
* Keeps the mapping between the adapter positions and spans. This is necessary to provide
* a consistent experience when user scrolls the list.
*/
LazySpanLookup mLazySpanLookup = new LazySpanLookup();
/**
* how we handle gaps in UI.
*/
private int mGapStrategy = GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS;
/**
* Saved state needs this information to properly layout on restore.
*/
private boolean mLastLayoutFromEnd;
/**
* Saved state and onLayout needs this information to re-layout properly
*/
private boolean mLastLayoutRTL;
/**
* SavedState is not handled until a layout happens. This is where we keep it until next
* layout.
*/
private SavedState mPendingSavedState;
/**
* Re-used measurement specs. updated by onLayout.
*/
private int mFullSizeSpec;
/**
* Re-used rectangle to get child decor offsets.
*/
private final Rect mTmpRect = new Rect();
/**
* Re-used anchor info.
*/
private final AnchorInfo mAnchorInfo = new AnchorInfo();
/**
* If a full span item is invalid / or created in reverse direction; it may create gaps in
* the UI. While laying out, if such case is detected, we set this flag.
* <p>
* After scrolling stops, we check this flag and if it is set, re-layout.
*/
private boolean mLaidOutInvalidFullSpan = false;
/**
* Works the same way as {@link android.widget.AbsListView#setSmoothScrollbarEnabled(boolean)}.
* see {@link android.widget.AbsListView#setSmoothScrollbarEnabled(boolean)}
*/
private boolean mSmoothScrollbarEnabled = true;
private final Runnable mCheckForGapsRunnable = new Runnable() {
@Override
public void run() {
checkForGaps();
}
};
/**
* Constructor used when layout manager is set in XML by RecyclerView attribute
* "layoutManager". Defaults to single column and vertical.
*/
@SuppressWarnings("unused")
public StaggeredGridLayoutManager(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes) {
Properties properties = getProperties(context, attrs, defStyleAttr, defStyleRes);
setOrientation(properties.orientation);
setSpanCount(properties.spanCount);
setReverseLayout(properties.reverseLayout);
setAutoMeasureEnabled(mGapStrategy != GAP_HANDLING_NONE);
mLayoutState = new LayoutState();
createOrientationHelpers();
}
/**
* Creates a StaggeredGridLayoutManager with given parameters.
*
* @param spanCount If orientation is vertical, spanCount is number of columns. If
* orientation is horizontal, spanCount is number of rows.
* @param orientation {@link #VERTICAL} or {@link #HORIZONTAL}
*/
public StaggeredGridLayoutManager(int spanCount, int orientation) {
mOrientation = orientation;
setSpanCount(spanCount);
setAutoMeasureEnabled(mGapStrategy != GAP_HANDLING_NONE);
mLayoutState = new LayoutState();
createOrientationHelpers();
}
private void createOrientationHelpers() {
mPrimaryOrientation = OrientationHelper.createOrientationHelper(this, mOrientation);
mSecondaryOrientation = OrientationHelper
.createOrientationHelper(this, 1 - mOrientation);
}
/**
* Checks for gaps in the UI that may be caused by adapter changes.
* <p>
* When a full span item is laid out in reverse direction, it sets a flag which we check when
* scroll is stopped (or re-layout happens) and re-layout after first valid item.
*/
private boolean checkForGaps() {
if (getChildCount() == 0 || mGapStrategy == GAP_HANDLING_NONE || !isAttachedToWindow()) {
return false;
}
final int minPos, maxPos;
if (mShouldReverseLayout) {
minPos = getLastChildPosition();
maxPos = getFirstChildPosition();
} else {
minPos = getFirstChildPosition();
maxPos = getLastChildPosition();
}
if (minPos == 0) {
View gapView = hasGapsToFix();
if (gapView != null) {
mLazySpanLookup.clear();
requestSimpleAnimationsInNextLayout();
requestLayout();
return true;
}
}
if (!mLaidOutInvalidFullSpan) {
return false;
}
int invalidGapDir = mShouldReverseLayout ? LayoutState.LAYOUT_START : LayoutState.LAYOUT_END;
final LazySpanLookup.FullSpanItem invalidFsi = mLazySpanLookup
.getFirstFullSpanItemInRange(minPos, maxPos + 1, invalidGapDir, true);
if (invalidFsi == null) {
mLaidOutInvalidFullSpan = false;
mLazySpanLookup.forceInvalidateAfter(maxPos + 1);
return false;
}
final LazySpanLookup.FullSpanItem validFsi = mLazySpanLookup
.getFirstFullSpanItemInRange(minPos, invalidFsi.mPosition,
invalidGapDir * -1, true);
if (validFsi == null) {
mLazySpanLookup.forceInvalidateAfter(invalidFsi.mPosition);
} else {
mLazySpanLookup.forceInvalidateAfter(validFsi.mPosition + 1);
}
requestSimpleAnimationsInNextLayout();
requestLayout();
return true;
}
@Override
public void onScrollStateChanged(int state) {
if (state == RecyclerView.SCROLL_STATE_IDLE) {
checkForGaps();
}
}
@Override
public void onDetachedFromWindow(RecyclerView view, RecyclerView.Recycler recycler) {
removeCallbacks(mCheckForGapsRunnable);
for (int i = 0; i < mSpanCount; i++) {
mSpans[i].clear();
}
}
/**
* Checks for gaps if we've reached to the top of the list.
* <p>
* Intermediate gaps created by full span items are tracked via mLaidOutInvalidFullSpan field.
*/
View hasGapsToFix() {
int startChildIndex = 0;
int endChildIndex = getChildCount() - 1;
BitSet mSpansToCheck = new BitSet(mSpanCount);
mSpansToCheck.set(0, mSpanCount, true);
final int firstChildIndex, childLimit;
final int preferredSpanDir = mOrientation == VERTICAL && isLayoutRTL() ? 1 : -1;
if (mShouldReverseLayout) {
firstChildIndex = endChildIndex;
childLimit = startChildIndex - 1;
} else {
firstChildIndex = startChildIndex;
childLimit = endChildIndex + 1;
}
final int nextChildDiff = firstChildIndex < childLimit ? 1 : -1;
for (int i = firstChildIndex; i != childLimit; i += nextChildDiff) {
View child = getChildAt(i);
LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (mSpansToCheck.get(lp.mSpan.mIndex)) {
if (checkSpanForGap(lp.mSpan)) {
return child;
}
mSpansToCheck.clear(lp.mSpan.mIndex);
}
if (lp.mFullSpan) {
continue; // quick reject
}
if (i + nextChildDiff != childLimit) {
View nextChild = getChildAt(i + nextChildDiff);
boolean compareSpans = false;
if (mShouldReverseLayout) {
// ensure child's end is below nextChild's end
int myEnd = mPrimaryOrientation.getDecoratedEnd(child);
int nextEnd = mPrimaryOrientation.getDecoratedEnd(nextChild);
if (myEnd < nextEnd) {
return child;//i should have a better position
} else if (myEnd == nextEnd) {
compareSpans = true;
}
} else {
int myStart = mPrimaryOrientation.getDecoratedStart(child);
int nextStart = mPrimaryOrientation.getDecoratedStart(nextChild);
if (myStart > nextStart) {
return child;//i should have a better position
} else if (myStart == nextStart) {
compareSpans = true;
}
}
if (compareSpans) {
// equal, check span indices.
LayoutParams nextLp = (LayoutParams) nextChild.getLayoutParams();
if (lp.mSpan.mIndex - nextLp.mSpan.mIndex < 0 != preferredSpanDir < 0) {
return child;
}
}
}
}
// everything looks good
return null;
}
private boolean checkSpanForGap(Span span) {
if (mShouldReverseLayout) {
if (span.getEndLine() < mPrimaryOrientation.getEndAfterPadding()) {
// if it is full span, it is OK
final View endView = span.mViews.get(span.mViews.size() - 1);
final LayoutParams lp = span.getLayoutParams(endView);
return !lp.mFullSpan;
}
} else if (span.getStartLine() > mPrimaryOrientation.getStartAfterPadding()) {
// if it is full span, it is OK
final View startView = span.mViews.get(0);
final LayoutParams lp = span.getLayoutParams(startView);
return !lp.mFullSpan;
}
return false;
}
/**
* Sets the number of spans for the layout. This will invalidate all of the span assignments
* for Views.
* <p>
* Calling this method will automatically result in a new layout request unless the spanCount
* parameter is equal to current span count.
*
* @param spanCount Number of spans to layout
*/
public void setSpanCount(int spanCount) {
assertNotInLayoutOrScroll(null);
if (spanCount != mSpanCount) {
invalidateSpanAssignments();
mSpanCount = spanCount;
mRemainingSpans = new BitSet(mSpanCount);
mSpans = new Span[mSpanCount];
for (int i = 0; i < mSpanCount; i++) {
mSpans[i] = new Span(i);
}
requestLayout();
}
}
/**
* Sets the orientation of the layout. StaggeredGridLayoutManager will do its best to keep
* scroll position if this method is called after views are laid out.
*
* @param orientation {@link #HORIZONTAL} or {@link #VERTICAL}
*/
public void setOrientation(int orientation) {
if (orientation != HORIZONTAL && orientation != VERTICAL) {
throw new IllegalArgumentException("invalid orientation.");
}
assertNotInLayoutOrScroll(null);
if (orientation == mOrientation) {
return;
}
mOrientation = orientation;
OrientationHelper tmp = mPrimaryOrientation;
mPrimaryOrientation = mSecondaryOrientation;
mSecondaryOrientation = tmp;
requestLayout();
}
/**
* Sets whether LayoutManager should start laying out items from the end of the UI. The order
* items are traversed is not affected by this call.
* <p>
* For vertical layout, if it is set to <code>true</code>, first item will be at the bottom of
* the list.
* <p>
* For horizontal layouts, it depends on the layout direction.
* When set to true, If {@link RecyclerView} is LTR, than it will layout from RTL, if
* {@link RecyclerView}} is RTL, it will layout from LTR.
*
* @param reverseLayout Whether layout should be in reverse or not
*/
public void setReverseLayout(boolean reverseLayout) {
assertNotInLayoutOrScroll(null);
if (mPendingSavedState != null && mPendingSavedState.mReverseLayout != reverseLayout) {
mPendingSavedState.mReverseLayout = reverseLayout;
}
mReverseLayout = reverseLayout;
requestLayout();
}
/**
* Returns the current gap handling strategy for StaggeredGridLayoutManager.
* <p>
* Staggered grid may have gaps in the layout due to changes in the adapter. To avoid gaps,
* StaggeredGridLayoutManager provides 2 options. Check {@link #GAP_HANDLING_NONE} and
* {@link #GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS} for details.
* <p>
* By default, StaggeredGridLayoutManager uses {@link #GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS}.
*
* @return Current gap handling strategy.
* @see #setGapStrategy(int)
* @see #GAP_HANDLING_NONE
* @see #GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS
*/
public int getGapStrategy() {
return mGapStrategy;
}
/**
* Sets the gap handling strategy for StaggeredGridLayoutManager. If the gapStrategy parameter
* is different than the current strategy, calling this method will trigger a layout request.
*
* @param gapStrategy The new gap handling strategy. Should be
* {@link #GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS} or {@link
* #GAP_HANDLING_NONE}.
* @see #getGapStrategy()
*/
public void setGapStrategy(int gapStrategy) {
assertNotInLayoutOrScroll(null);
if (gapStrategy == mGapStrategy) {
return;
}
if (gapStrategy != GAP_HANDLING_NONE &&
gapStrategy != GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS) {
throw new IllegalArgumentException("invalid gap strategy. Must be GAP_HANDLING_NONE "
+ "or GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS");
}
mGapStrategy = gapStrategy;
setAutoMeasureEnabled(mGapStrategy != GAP_HANDLING_NONE);
requestLayout();
}
@Override
public void assertNotInLayoutOrScroll(String message) {
if (mPendingSavedState == null) {
super.assertNotInLayoutOrScroll(message);
}
}
/**
* Returns the number of spans laid out by StaggeredGridLayoutManager.
*
* @return Number of spans in the layout
*/
public int getSpanCount() {
return mSpanCount;
}
/**
* For consistency, StaggeredGridLayoutManager keeps a mapping between spans and items.
* <p>
* If you need to cancel current assignments, you can call this method which will clear all
* assignments and request a new layout.
*/
public void invalidateSpanAssignments() {
mLazySpanLookup.clear();
requestLayout();
}
/**
* Calculates the views' layout order. (e.g. from end to start or start to end)
* RTL layout support is applied automatically. So if layout is RTL and
* {@link #getReverseLayout()} is {@code true}, elements will be laid out starting from left.
*/
private void resolveShouldLayoutReverse() {
// A == B is the same result, but we rather keep it readable
if (mOrientation == VERTICAL || !isLayoutRTL()) {
mShouldReverseLayout = mReverseLayout;
} else {
mShouldReverseLayout = !mReverseLayout;
}
}
boolean isLayoutRTL() {
return getLayoutDirection() == ViewCompat.LAYOUT_DIRECTION_RTL;
}
/**
* Returns whether views are laid out in reverse order or not.
* <p>
* Not that this value is not affected by RecyclerView's layout direction.
*
* @return True if layout is reversed, false otherwise
* @see #setReverseLayout(boolean)
*/
public boolean getReverseLayout() {
return mReverseLayout;
}
@Override
public void setMeasuredDimension(Rect childrenBounds, int wSpec, int hSpec) {
// we don't like it to wrap content in our non-scroll direction.
final int width, height;
final int horizontalPadding = getPaddingLeft() + getPaddingRight();
final int verticalPadding = getPaddingTop() + getPaddingBottom();
if (mOrientation == VERTICAL) {
final int usedHeight = childrenBounds.height() + verticalPadding;
height = chooseSize(hSpec, usedHeight, getMinimumHeight());
width = chooseSize(wSpec, mSizePerSpan * mSpanCount + horizontalPadding,
getMinimumWidth());
} else {
final int usedWidth = childrenBounds.width() + horizontalPadding;
width = chooseSize(wSpec, usedWidth, getMinimumWidth());
height = chooseSize(hSpec, mSizePerSpan * mSpanCount + verticalPadding,
getMinimumHeight());
}
setMeasuredDimension(width, height);
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
onLayoutChildren(recycler, state, true);
}
private void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state,
boolean shouldCheckForGaps) {
final AnchorInfo anchorInfo = mAnchorInfo;
anchorInfo.reset();
if (mPendingSavedState != null || mPendingScrollPosition != NO_POSITION) {
if (state.getItemCount() == 0) {
removeAndRecycleAllViews(recycler);
return;
}
}
if (mPendingSavedState != null) {
applyPendingSavedState(anchorInfo);
} else {
resolveShouldLayoutReverse();
anchorInfo.mLayoutFromEnd = mShouldReverseLayout;
}
updateAnchorInfoForLayout(state, anchorInfo);
if (mPendingSavedState == null) {
if (anchorInfo.mLayoutFromEnd != mLastLayoutFromEnd ||
isLayoutRTL() != mLastLayoutRTL) {
mLazySpanLookup.clear();
anchorInfo.mInvalidateOffsets = true;
}
}
if (getChildCount() > 0 && (mPendingSavedState == null ||
mPendingSavedState.mSpanOffsetsSize < 1)) {
if (anchorInfo.mInvalidateOffsets) {
for (int i = 0; i < mSpanCount; i++) {
// Scroll to position is set, clear.
mSpans[i].clear();
if (anchorInfo.mOffset != INVALID_OFFSET) {
mSpans[i].setLine(anchorInfo.mOffset);
}
}
} else {
for (int i = 0; i < mSpanCount; i++) {
mSpans[i].cacheReferenceLineAndClear(mShouldReverseLayout, anchorInfo.mOffset);
}
}
}
detachAndScrapAttachedViews(recycler);
mLayoutState.mRecycle = false;
mLaidOutInvalidFullSpan = false;
updateMeasureSpecs(mSecondaryOrientation.getTotalSpace());
updateLayoutState(anchorInfo.mPosition, state);
if (anchorInfo.mLayoutFromEnd) {
// Layout start.
setLayoutStateDirection(LayoutState.LAYOUT_START);
fill(recycler, mLayoutState, state);
// Layout end.
setLayoutStateDirection(LayoutState.LAYOUT_END);
mLayoutState.mCurrentPosition = anchorInfo.mPosition + mLayoutState.mItemDirection;
fill(recycler, mLayoutState, state);
} else {
// Layout end.
setLayoutStateDirection(LayoutState.LAYOUT_END);
fill(recycler, mLayoutState, state);
// Layout start.
setLayoutStateDirection(LayoutState.LAYOUT_START);
mLayoutState.mCurrentPosition = anchorInfo.mPosition + mLayoutState.mItemDirection;
fill(recycler, mLayoutState, state);
}
repositionToWrapContentIfNecessary();
if (getChildCount() > 0) {
if (mShouldReverseLayout) {
fixEndGap(recycler, state, true);
fixStartGap(recycler, state, false);
} else {
fixStartGap(recycler, state, true);
fixEndGap(recycler, state, false);
}
}
boolean hasGaps = false;
if (shouldCheckForGaps && !state.isPreLayout()) {
final boolean needToCheckForGaps = mGapStrategy != GAP_HANDLING_NONE
&& getChildCount() > 0
&& (mLaidOutInvalidFullSpan || hasGapsToFix() != null);
if (needToCheckForGaps) {
removeCallbacks(mCheckForGapsRunnable);
if (checkForGaps()) {
hasGaps = true;
}
}
mPendingScrollPosition = NO_POSITION;
mPendingScrollPositionOffset = INVALID_OFFSET;
}
mLastLayoutFromEnd = anchorInfo.mLayoutFromEnd;
mLastLayoutRTL = isLayoutRTL();
mPendingSavedState = null; // we don't need this anymore
if (hasGaps) {
onLayoutChildren(recycler, state, false);
}
}
private void repositionToWrapContentIfNecessary() {
if (mSecondaryOrientation.getMode() == View.MeasureSpec.EXACTLY) {
return; // nothing to do
}
float maxSize = 0;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i ++) {
View child = getChildAt(i);
float size = mSecondaryOrientation.getDecoratedMeasurement(child);
if (size < maxSize) {
continue;
}
LayoutParams layoutParams = (LayoutParams) child.getLayoutParams();
if (layoutParams.isFullSpan()) {
size = 1f * size / mSpanCount;
}
maxSize = Math.max(maxSize, size);
}
int before = mSizePerSpan;
int desired = Math.round(maxSize * mSpanCount);
if (mSecondaryOrientation.getMode() == View.MeasureSpec.AT_MOST) {
desired = Math.min(desired, mSecondaryOrientation.getTotalSpace());
}
updateMeasureSpecs(desired);
if (mSizePerSpan == before) {
return; // nothing has changed
}
for (int i = 0; i < childCount; i ++) {
View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp.mFullSpan) {
continue;
}
if (isLayoutRTL() && mOrientation == VERTICAL) {
int newOffset = -(mSpanCount - 1 - lp.mSpan.mIndex) * mSizePerSpan;
int prevOffset = -(mSpanCount - 1 - lp.mSpan.mIndex) * before;
child.offsetLeftAndRight(newOffset - prevOffset);
} else {
int newOffset = lp.mSpan.mIndex * mSizePerSpan;
int prevOffset = lp.mSpan.mIndex * before;
if (mOrientation == VERTICAL) {
child.offsetLeftAndRight(newOffset - prevOffset);
} else {
child.offsetTopAndBottom(newOffset - prevOffset);
}
}
}
}
private void applyPendingSavedState(AnchorInfo anchorInfo) {
if (DEBUG) {
Log.d(TAG, "found saved state: " + mPendingSavedState);
}
if (mPendingSavedState.mSpanOffsetsSize > 0) {
if (mPendingSavedState.mSpanOffsetsSize == mSpanCount) {
for (int i = 0; i < mSpanCount; i++) {
mSpans[i].clear();
int line = mPendingSavedState.mSpanOffsets[i];
if (line != Span.INVALID_LINE) {
if (mPendingSavedState.mAnchorLayoutFromEnd) {
line += mPrimaryOrientation.getEndAfterPadding();
} else {
line += mPrimaryOrientation.getStartAfterPadding();
}
}
mSpans[i].setLine(line);
}
} else {
mPendingSavedState.invalidateSpanInfo();
mPendingSavedState.mAnchorPosition = mPendingSavedState.mVisibleAnchorPosition;
}
}
mLastLayoutRTL = mPendingSavedState.mLastLayoutRTL;
setReverseLayout(mPendingSavedState.mReverseLayout);
resolveShouldLayoutReverse();
if (mPendingSavedState.mAnchorPosition != NO_POSITION) {
mPendingScrollPosition = mPendingSavedState.mAnchorPosition;
anchorInfo.mLayoutFromEnd = mPendingSavedState.mAnchorLayoutFromEnd;
} else {
anchorInfo.mLayoutFromEnd = mShouldReverseLayout;
}
if (mPendingSavedState.mSpanLookupSize > 1) {
mLazySpanLookup.mData = mPendingSavedState.mSpanLookup;
mLazySpanLookup.mFullSpanItems = mPendingSavedState.mFullSpanItems;
}
}
void updateAnchorInfoForLayout(RecyclerView.State state, AnchorInfo anchorInfo) {
if (updateAnchorFromPendingData(state, anchorInfo)) {
return;
}
if (updateAnchorFromChildren(state, anchorInfo)) {
return;
}
if (DEBUG) {
Log.d(TAG, "Deciding anchor info from fresh state");
}
anchorInfo.assignCoordinateFromPadding();
anchorInfo.mPosition = 0;
}
private boolean updateAnchorFromChildren(RecyclerView.State state, AnchorInfo anchorInfo) {
// We don't recycle views out of adapter order. This way, we can rely on the first or
// last child as the anchor position.
// Layout direction may change but we should select the child depending on the latest
// layout direction. Otherwise, we'll choose the wrong child.
anchorInfo.mPosition = mLastLayoutFromEnd
? findLastReferenceChildPosition(state.getItemCount())
: findFirstReferenceChildPosition(state.getItemCount());
anchorInfo.mOffset = INVALID_OFFSET;
return true;
}
boolean updateAnchorFromPendingData(RecyclerView.State state, AnchorInfo anchorInfo) {
// Validate scroll position if exists.
if (state.isPreLayout() || mPendingScrollPosition == NO_POSITION) {
return false;
}
// Validate it.
if (mPendingScrollPosition < 0 || mPendingScrollPosition >= state.getItemCount()) {
mPendingScrollPosition = NO_POSITION;
mPendingScrollPositionOffset = INVALID_OFFSET;
return false;
}
if (mPendingSavedState == null || mPendingSavedState.mAnchorPosition == NO_POSITION
|| mPendingSavedState.mSpanOffsetsSize < 1) {
// If item is visible, make it fully visible.
final View child = findViewByPosition(mPendingScrollPosition);
if (child != null) {
// Use regular anchor position, offset according to pending offset and target
// child
anchorInfo.mPosition = mShouldReverseLayout ? getLastChildPosition()
: getFirstChildPosition();
if (mPendingScrollPositionOffset != INVALID_OFFSET) {
if (anchorInfo.mLayoutFromEnd) {
final int target = mPrimaryOrientation.getEndAfterPadding() -
mPendingScrollPositionOffset;
anchorInfo.mOffset = target - mPrimaryOrientation.getDecoratedEnd(child);
} else {
final int target = mPrimaryOrientation.getStartAfterPadding() +
mPendingScrollPositionOffset;
anchorInfo.mOffset = target - mPrimaryOrientation.getDecoratedStart(child);
}
return true;
}
// no offset provided. Decide according to the child location
final int childSize = mPrimaryOrientation.getDecoratedMeasurement(child);
if (childSize > mPrimaryOrientation.getTotalSpace()) {
// Item does not fit. Fix depending on layout direction.
anchorInfo.mOffset = anchorInfo.mLayoutFromEnd
? mPrimaryOrientation.getEndAfterPadding()
: mPrimaryOrientation.getStartAfterPadding();
return true;
}
final int startGap = mPrimaryOrientation.getDecoratedStart(child)
- mPrimaryOrientation.getStartAfterPadding();
if (startGap < 0) {
anchorInfo.mOffset = -startGap;
return true;
}
final int endGap = mPrimaryOrientation.getEndAfterPadding() -
mPrimaryOrientation.getDecoratedEnd(child);
if (endGap < 0) {
anchorInfo.mOffset = endGap;
return true;
}
// child already visible. just layout as usual
anchorInfo.mOffset = INVALID_OFFSET;
} else {
// Child is not visible. Set anchor coordinate depending on in which direction
// child will be visible.
anchorInfo.mPosition = mPendingScrollPosition;
if (mPendingScrollPositionOffset == INVALID_OFFSET) {
final int position = calculateScrollDirectionForPosition(
anchorInfo.mPosition);
anchorInfo.mLayoutFromEnd = position == LayoutState.LAYOUT_END;
anchorInfo.assignCoordinateFromPadding();
} else {
anchorInfo.assignCoordinateFromPadding(mPendingScrollPositionOffset);
}
anchorInfo.mInvalidateOffsets = true;
}
} else {
anchorInfo.mOffset = INVALID_OFFSET;
anchorInfo.mPosition = mPendingScrollPosition;
}
return true;
}
void updateMeasureSpecs(int totalSpace) {
mSizePerSpan = totalSpace / mSpanCount;
//noinspection ResourceType
mFullSizeSpec = View.MeasureSpec.makeMeasureSpec(
totalSpace, mSecondaryOrientation.getMode());
}
@Override
public boolean supportsPredictiveItemAnimations() {
return mPendingSavedState == null;
}
/**
* Returns the adapter position of the first visible view for each span.
* <p>
* Note that, this value is not affected by layout orientation or item order traversal.
* ({@link #setReverseLayout(boolean)}). Views are sorted by their positions in the adapter,
* not in the layout.
* <p>
* If RecyclerView has item decorators, they will be considered in calculations as well.
* <p>
* StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Those
* views are ignored in this method.
*
* @param into An array to put the results into. If you don't provide any, LayoutManager will
* create a new one.
* @return The adapter position of the first visible item in each span. If a span does not have
* any items, {@link RecyclerView#NO_POSITION} is returned for that span.
* @see #findFirstCompletelyVisibleItemPositions(int[])
* @see #findLastVisibleItemPositions(int[])
*/
public int[] findFirstVisibleItemPositions(int[] into) {
if (into == null) {
into = new int[mSpanCount];
} else if (into.length < mSpanCount) {
throw new IllegalArgumentException("Provided int[]'s size must be more than or equal"
+ " to span count. Expected:" + mSpanCount + ", array size:" + into.length);
}
for (int i = 0; i < mSpanCount; i++) {
into[i] = mSpans[i].findFirstVisibleItemPosition();
}
return into;
}
/**
* Returns the adapter position of the first completely visible view for each span.
* <p>
* Note that, this value is not affected by layout orientation or item order traversal.
* ({@link #setReverseLayout(boolean)}). Views are sorted by their positions in the adapter,
* not in the layout.
* <p>
* If RecyclerView has item decorators, they will be considered in calculations as well.
* <p>
* StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Those
* views are ignored in this method.
*
* @param into An array to put the results into. If you don't provide any, LayoutManager will
* create a new one.
* @return The adapter position of the first fully visible item in each span. If a span does
* not have any items, {@link RecyclerView#NO_POSITION} is returned for that span.
* @see #findFirstVisibleItemPositions(int[])
* @see #findLastCompletelyVisibleItemPositions(int[])
*/
public int[] findFirstCompletelyVisibleItemPositions(int[] into) {
if (into == null) {
into = new int[mSpanCount];
} else if (into.length < mSpanCount) {
throw new IllegalArgumentException("Provided int[]'s size must be more than or equal"
+ " to span count. Expected:" + mSpanCount + ", array size:" + into.length);
}
for (int i = 0; i < mSpanCount; i++) {
into[i] = mSpans[i].findFirstCompletelyVisibleItemPosition();
}
return into;
}
/**
* Returns the adapter position of the last visible view for each span.
* <p>
* Note that, this value is not affected by layout orientation or item order traversal.
* ({@link #setReverseLayout(boolean)}). Views are sorted by their positions in the adapter,
* not in the layout.
* <p>
* If RecyclerView has item decorators, they will be considered in calculations as well.
* <p>
* StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Those
* views are ignored in this method.
*
* @param into An array to put the results into. If you don't provide any, LayoutManager will
* create a new one.
* @return The adapter position of the last visible item in each span. If a span does not have
* any items, {@link RecyclerView#NO_POSITION} is returned for that span.
* @see #findLastCompletelyVisibleItemPositions(int[])
* @see #findFirstVisibleItemPositions(int[])
*/
public int[] findLastVisibleItemPositions(int[] into) {
if (into == null) {
into = new int[mSpanCount];
} else if (into.length < mSpanCount) {
throw new IllegalArgumentException("Provided int[]'s size must be more than or equal"
+ " to span count. Expected:" + mSpanCount + ", array size:" + into.length);
}
for (int i = 0; i < mSpanCount; i++) {
into[i] = mSpans[i].findLastVisibleItemPosition();
}
return into;
}
/**
* Returns the adapter position of the last completely visible view for each span.
* <p>
* Note that, this value is not affected by layout orientation or item order traversal.
* ({@link #setReverseLayout(boolean)}). Views are sorted by their positions in the adapter,
* not in the layout.
* <p>
* If RecyclerView has item decorators, they will be considered in calculations as well.
* <p>
* StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Those
* views are ignored in this method.
*
* @param into An array to put the results into. If you don't provide any, LayoutManager will
* create a new one.
* @return The adapter position of the last fully visible item in each span. If a span does not
* have any items, {@link RecyclerView#NO_POSITION} is returned for that span.
* @see #findFirstCompletelyVisibleItemPositions(int[])
* @see #findLastVisibleItemPositions(int[])
*/
public int[] findLastCompletelyVisibleItemPositions(int[] into) {
if (into == null) {
into = new int[mSpanCount];
} else if (into.length < mSpanCount) {
throw new IllegalArgumentException("Provided int[]'s size must be more than or equal"
+ " to span count. Expected:" + mSpanCount + ", array size:" + into.length);
}
for (int i = 0; i < mSpanCount; i++) {
into[i] = mSpans[i].findLastCompletelyVisibleItemPosition();
}
return into;
}
@Override
public int computeHorizontalScrollOffset(RecyclerView.State state) {
return computeScrollOffset(state);
}
private int computeScrollOffset(RecyclerView.State state) {
if (getChildCount() == 0) {
return 0;
}
return ScrollbarHelper.computeScrollOffset(state, mPrimaryOrientation,
findFirstVisibleItemClosestToStart(!mSmoothScrollbarEnabled, true)
, findFirstVisibleItemClosestToEnd(!mSmoothScrollbarEnabled, true),
this, mSmoothScrollbarEnabled, mShouldReverseLayout);
}
@Override
public int computeVerticalScrollOffset(RecyclerView.State state) {
return computeScrollOffset(state);
}
@Override
public int computeHorizontalScrollExtent(RecyclerView.State state) {
return computeScrollExtent(state);
}
private int computeScrollExtent(RecyclerView.State state) {
if (getChildCount() == 0) {
return 0;
}
return ScrollbarHelper.computeScrollExtent(state, mPrimaryOrientation,
findFirstVisibleItemClosestToStart(!mSmoothScrollbarEnabled, true)
, findFirstVisibleItemClosestToEnd(!mSmoothScrollbarEnabled, true),
this, mSmoothScrollbarEnabled);
}
@Override
public int computeVerticalScrollExtent(RecyclerView.State state) {
return computeScrollExtent(state);
}
@Override
public int computeHorizontalScrollRange(RecyclerView.State state) {
return computeScrollRange(state);
}
private int computeScrollRange(RecyclerView.State state) {
if (getChildCount() == 0) {
return 0;
}
return ScrollbarHelper.computeScrollRange(state, mPrimaryOrientation,
findFirstVisibleItemClosestToStart(!mSmoothScrollbarEnabled, true)
, findFirstVisibleItemClosestToEnd(!mSmoothScrollbarEnabled, true),
this, mSmoothScrollbarEnabled);
}
@Override
public int computeVerticalScrollRange(RecyclerView.State state) {
return computeScrollRange(state);
}
private void measureChildWithDecorationsAndMargin(View child, LayoutParams lp,
boolean alreadyMeasured) {
if (lp.mFullSpan) {
if (mOrientation == VERTICAL) {
measureChildWithDecorationsAndMargin(child, mFullSizeSpec,
getChildMeasureSpec(getHeight(), getHeightMode(), 0, lp.height, true),
alreadyMeasured);
} else {
measureChildWithDecorationsAndMargin(child,
getChildMeasureSpec(getWidth(), getWidthMode(), 0, lp.width, true),
mFullSizeSpec, alreadyMeasured);
}
} else {
if (mOrientation == VERTICAL) {
measureChildWithDecorationsAndMargin(child,
getChildMeasureSpec(mSizePerSpan, getWidthMode(), 0, lp.width, false),
getChildMeasureSpec(getHeight(), getHeightMode(), 0, lp.height, true),
alreadyMeasured);
} else {
measureChildWithDecorationsAndMargin(child,
getChildMeasureSpec(getWidth(), getWidthMode(), 0, lp.width, true),
getChildMeasureSpec(mSizePerSpan, getHeightMode(), 0, lp.height, false),
alreadyMeasured);
}
}
}
private void measureChildWithDecorationsAndMargin(View child, int widthSpec,
int heightSpec, boolean alreadyMeasured) {
calculateItemDecorationsForChild(child, mTmpRect);
LayoutParams lp = (LayoutParams) child.getLayoutParams();
widthSpec = updateSpecWithExtra(widthSpec, lp.leftMargin + mTmpRect.left,
lp.rightMargin + mTmpRect.right);
heightSpec = updateSpecWithExtra(heightSpec, lp.topMargin + mTmpRect.top,
lp.bottomMargin + mTmpRect.bottom);
final boolean measure = alreadyMeasured
? shouldReMeasureChild(child, widthSpec, heightSpec, lp)
: shouldMeasureChild(child, widthSpec, heightSpec, lp);
if (measure) {
child.measure(widthSpec, heightSpec);
}
}
private int updateSpecWithExtra(int spec, int startInset, int endInset) {
if (startInset == 0 && endInset == 0) {
return spec;
}
final int mode = View.MeasureSpec.getMode(spec);
if (mode == View.MeasureSpec.AT_MOST || mode == View.MeasureSpec.EXACTLY) {
return View.MeasureSpec.makeMeasureSpec(
Math.max(0, View.MeasureSpec.getSize(spec) - startInset - endInset), mode);
}
return spec;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
if (state instanceof SavedState) {
mPendingSavedState = (SavedState) state;
requestLayout();
} else if (DEBUG) {
Log.d(TAG, "invalid saved state class");
}
}
@Override
public Parcelable onSaveInstanceState() {
if (mPendingSavedState != null) {
return new SavedState(mPendingSavedState);
}
SavedState state = new SavedState();
state.mReverseLayout = mReverseLayout;
state.mAnchorLayoutFromEnd = mLastLayoutFromEnd;
state.mLastLayoutRTL = mLastLayoutRTL;
if (mLazySpanLookup != null && mLazySpanLookup.mData != null) {
state.mSpanLookup = mLazySpanLookup.mData;
state.mSpanLookupSize = state.mSpanLookup.length;
state.mFullSpanItems = mLazySpanLookup.mFullSpanItems;
} else {
state.mSpanLookupSize = 0;
}
if (getChildCount() > 0) {
state.mAnchorPosition = mLastLayoutFromEnd ? getLastChildPosition()
: getFirstChildPosition();
state.mVisibleAnchorPosition = findFirstVisibleItemPositionInt();
state.mSpanOffsetsSize = mSpanCount;
state.mSpanOffsets = new int[mSpanCount];
for (int i = 0; i < mSpanCount; i++) {
int line;
if (mLastLayoutFromEnd) {
line = mSpans[i].getEndLine(Span.INVALID_LINE);
if (line != Span.INVALID_LINE) {
line -= mPrimaryOrientation.getEndAfterPadding();
}
} else {
line = mSpans[i].getStartLine(Span.INVALID_LINE);
if (line != Span.INVALID_LINE) {
line -= mPrimaryOrientation.getStartAfterPadding();
}
}
state.mSpanOffsets[i] = line;
}
} else {
state.mAnchorPosition = NO_POSITION;
state.mVisibleAnchorPosition = NO_POSITION;
state.mSpanOffsetsSize = 0;
}
if (DEBUG) {
Log.d(TAG, "saved state:\n" + state);
}
return state;
}
@Override
public void onInitializeAccessibilityNodeInfoForItem(RecyclerView.Recycler recycler,
RecyclerView.State state, View host, AccessibilityNodeInfoCompat info) {
ViewGroup.LayoutParams lp = host.getLayoutParams();
if (!(lp instanceof LayoutParams)) {
super.onInitializeAccessibilityNodeInfoForItem(host, info);
return;
}
LayoutParams sglp = (LayoutParams) lp;
if (mOrientation == HORIZONTAL) {
info.setCollectionItemInfo(AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain(
sglp.getSpanIndex(), sglp.mFullSpan ? mSpanCount : 1,
-1, -1,
sglp.mFullSpan, false));
} else { // VERTICAL
info.setCollectionItemInfo(AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain(
-1, -1,
sglp.getSpanIndex(), sglp.mFullSpan ? mSpanCount : 1,
sglp.mFullSpan, false));
}
}
@Override
public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(event);
if (getChildCount() > 0) {
final AccessibilityRecordCompat record = AccessibilityEventCompat
.asRecord(event);
final View start = findFirstVisibleItemClosestToStart(false, true);
final View end = findFirstVisibleItemClosestToEnd(false, true);
if (start == null || end == null) {
return;
}
final int startPos = getPosition(start);
final int endPos = getPosition(end);
if (startPos < endPos) {
record.setFromIndex(startPos);
record.setToIndex(endPos);
} else {
record.setFromIndex(endPos);
record.setToIndex(startPos);
}
}
}
/**
* Finds the first fully visible child to be used as an anchor child if span count changes when
* state is restored. If no children is fully visible, returns a partially visible child instead
* of returning null.
*/
int findFirstVisibleItemPositionInt() {
final View first = mShouldReverseLayout ? findFirstVisibleItemClosestToEnd(true, true) :
findFirstVisibleItemClosestToStart(true, true);
return first == null ? NO_POSITION : getPosition(first);
}
@Override
public int getRowCountForAccessibility(RecyclerView.Recycler recycler,
RecyclerView.State state) {
if (mOrientation == HORIZONTAL) {
return mSpanCount;
}
return super.getRowCountForAccessibility(recycler, state);
}
@Override
public int getColumnCountForAccessibility(RecyclerView.Recycler recycler,
RecyclerView.State state) {
if (mOrientation == VERTICAL) {
return mSpanCount;
}
return super.getColumnCountForAccessibility(recycler, state);
}
/**
* This is for internal use. Not necessarily the child closest to start but the first child
* we find that matches the criteria.
* This method does not do any sorting based on child's start coordinate, instead, it uses
* children order.
*/
View findFirstVisibleItemClosestToStart(boolean fullyVisible, boolean acceptPartiallyVisible) {
final int boundsStart = mPrimaryOrientation.getStartAfterPadding();
final int boundsEnd = mPrimaryOrientation.getEndAfterPadding();
final int limit = getChildCount();
View partiallyVisible = null;
for (int i = 0; i < limit; i++) {
final View child = getChildAt(i);
final int childStart = mPrimaryOrientation.getDecoratedStart(child);
final int childEnd = mPrimaryOrientation.getDecoratedEnd(child);
if(childEnd <= boundsStart || childStart >= boundsEnd) {
continue; // not visible at all
}
if (childStart >= boundsStart || !fullyVisible) {
// when checking for start, it is enough even if part of the child's top is visible
// as long as fully visible is not requested.
return child;
}
if (acceptPartiallyVisible && partiallyVisible == null) {
partiallyVisible = child;
}
}
return partiallyVisible;
}
/**
* This is for internal use. Not necessarily the child closest to bottom but the first child
* we find that matches the criteria.
* This method does not do any sorting based on child's end coordinate, instead, it uses
* children order.
*/
View findFirstVisibleItemClosestToEnd(boolean fullyVisible, boolean acceptPartiallyVisible) {
final int boundsStart = mPrimaryOrientation.getStartAfterPadding();
final int boundsEnd = mPrimaryOrientation.getEndAfterPadding();
View partiallyVisible = null;
for (int i = getChildCount() - 1; i >= 0; i--) {
final View child = getChildAt(i);
final int childStart = mPrimaryOrientation.getDecoratedStart(child);
final int childEnd = mPrimaryOrientation.getDecoratedEnd(child);
if(childEnd <= boundsStart || childStart >= boundsEnd) {
continue; // not visible at all
}
if (childEnd <= boundsEnd || !fullyVisible) {
// when checking for end, it is enough even if part of the child's bottom is visible
// as long as fully visible is not requested.
return child;
}
if (acceptPartiallyVisible && partiallyVisible == null) {
partiallyVisible = child;
}
}
return partiallyVisible;
}
private void fixEndGap(RecyclerView.Recycler recycler, RecyclerView.State state,
boolean canOffsetChildren) {
final int maxEndLine = getMaxEnd(Integer.MIN_VALUE);
if (maxEndLine == Integer.MIN_VALUE) {
return;
}
int gap = mPrimaryOrientation.getEndAfterPadding() - maxEndLine;
int fixOffset;
if (gap > 0) {
fixOffset = -scrollBy(-gap, recycler, state);
} else {
return; // nothing to fix
}
gap -= fixOffset;
if (canOffsetChildren && gap > 0) {
mPrimaryOrientation.offsetChildren(gap);
}
}
private void fixStartGap(RecyclerView.Recycler recycler, RecyclerView.State state,
boolean canOffsetChildren) {
final int minStartLine = getMinStart(Integer.MAX_VALUE);
if (minStartLine == Integer.MAX_VALUE) {
return;
}
int gap = minStartLine - mPrimaryOrientation.getStartAfterPadding();
int fixOffset;
if (gap > 0) {
fixOffset = scrollBy(gap, recycler, state);
} else {
return; // nothing to fix
}
gap -= fixOffset;
if (canOffsetChildren && gap > 0) {
mPrimaryOrientation.offsetChildren(-gap);
}
}
private void updateLayoutState(int anchorPosition, RecyclerView.State state) {
mLayoutState.mAvailable = 0;
mLayoutState.mCurrentPosition = anchorPosition;
int startExtra = 0;
int endExtra = 0;
if (isSmoothScrolling()) {
final int targetPos = state.getTargetScrollPosition();
if (targetPos != NO_POSITION) {
if (mShouldReverseLayout == targetPos < anchorPosition) {
endExtra = mPrimaryOrientation.getTotalSpace();
} else {
startExtra = mPrimaryOrientation.getTotalSpace();
}
}
}
// Line of the furthest row.
final boolean clipToPadding = getClipToPadding();
if (clipToPadding) {
mLayoutState.mStartLine = mPrimaryOrientation.getStartAfterPadding() - startExtra;
mLayoutState.mEndLine = mPrimaryOrientation.getEndAfterPadding() + endExtra;
} else {
mLayoutState.mEndLine = mPrimaryOrientation.getEnd() + endExtra;
mLayoutState.mStartLine = -startExtra;
}
mLayoutState.mStopInFocusable = false;
mLayoutState.mRecycle = true;
mLayoutState.mInfinite = mPrimaryOrientation.getMode() == View.MeasureSpec.UNSPECIFIED &&
mPrimaryOrientation.getEnd() == 0;
}
private void setLayoutStateDirection(int direction) {
mLayoutState.mLayoutDirection = direction;
mLayoutState.mItemDirection = (mShouldReverseLayout == (direction == LayoutState.LAYOUT_START)) ?
LayoutState.ITEM_DIRECTION_TAIL : LayoutState.ITEM_DIRECTION_HEAD;
}
@Override
public void offsetChildrenHorizontal(int dx) {
super.offsetChildrenHorizontal(dx);
for (int i = 0; i < mSpanCount; i++) {
mSpans[i].onOffset(dx);
}
}
@Override
public void offsetChildrenVertical(int dy) {
super.offsetChildrenVertical(dy);
for (int i = 0; i < mSpanCount; i++) {
mSpans[i].onOffset(dy);
}
}
@Override
public void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount) {
handleUpdate(positionStart, itemCount, AdapterHelper.UpdateOp.REMOVE);
}
@Override
public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) {
handleUpdate(positionStart, itemCount, AdapterHelper.UpdateOp.ADD);
}
@Override
public void onItemsChanged(RecyclerView recyclerView) {
mLazySpanLookup.clear();
requestLayout();
}
@Override
public void onItemsMoved(RecyclerView recyclerView, int from, int to, int itemCount) {
handleUpdate(from, to, AdapterHelper.UpdateOp.MOVE);
}
@Override
public void onItemsUpdated(RecyclerView recyclerView, int positionStart, int itemCount,
Object payload) {
handleUpdate(positionStart, itemCount, AdapterHelper.UpdateOp.UPDATE);
}
/**
* Checks whether it should invalidate span assignments in response to an adapter change.
*/
private void handleUpdate(int positionStart, int itemCountOrToPosition, int cmd) {
int minPosition = mShouldReverseLayout ? getLastChildPosition() : getFirstChildPosition();
final int affectedRangeEnd;// exclusive
final int affectedRangeStart;// inclusive
if (cmd == AdapterHelper.UpdateOp.MOVE) {
if (positionStart < itemCountOrToPosition) {
affectedRangeEnd = itemCountOrToPosition + 1;
affectedRangeStart = positionStart;
} else {
affectedRangeEnd = positionStart + 1;
affectedRangeStart = itemCountOrToPosition;
}
} else {
affectedRangeStart = positionStart;
affectedRangeEnd = positionStart + itemCountOrToPosition;
}
mLazySpanLookup.invalidateAfter(affectedRangeStart);
switch (cmd) {
case AdapterHelper.UpdateOp.ADD:
mLazySpanLookup.offsetForAddition(positionStart, itemCountOrToPosition);
break;
case AdapterHelper.UpdateOp.REMOVE:
mLazySpanLookup.offsetForRemoval(positionStart, itemCountOrToPosition);
break;
case AdapterHelper.UpdateOp.MOVE:
// TODO optimize
mLazySpanLookup.offsetForRemoval(positionStart, 1);
mLazySpanLookup.offsetForAddition(itemCountOrToPosition, 1);
break;
}
if (affectedRangeEnd <= minPosition) {
return;
}
int maxPosition = mShouldReverseLayout ? getFirstChildPosition() : getLastChildPosition();
if (affectedRangeStart <= maxPosition) {
requestLayout();
}
}
private int fill(RecyclerView.Recycler recycler, LayoutState layoutState,
RecyclerView.State state) {
mRemainingSpans.set(0, mSpanCount, true);
// The target position we are trying to reach.
final int targetLine;
// Line of the furthest row.
if (mLayoutState.mInfinite) {
if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) {
targetLine = Integer.MAX_VALUE;
} else { // LAYOUT_START
targetLine = Integer.MIN_VALUE;
}
} else {
if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) {
targetLine = layoutState.mEndLine + layoutState.mAvailable;
} else { // LAYOUT_START
targetLine = layoutState.mStartLine - layoutState.mAvailable;
}
}
updateAllRemainingSpans(layoutState.mLayoutDirection, targetLine);
if (DEBUG) {
Log.d(TAG, "FILLING targetLine: " + targetLine + "," +
"remaining spans:" + mRemainingSpans + ", state: " + layoutState);
}
// the default coordinate to add new view.
final int defaultNewViewLine = mShouldReverseLayout
? mPrimaryOrientation.getEndAfterPadding()
: mPrimaryOrientation.getStartAfterPadding();
boolean added = false;
while (layoutState.hasMore(state)
&& (mLayoutState.mInfinite || !mRemainingSpans.isEmpty())) {
View view = layoutState.next(recycler);
LayoutParams lp = ((LayoutParams) view.getLayoutParams());
final int position = lp.getViewLayoutPosition();
final int spanIndex = mLazySpanLookup.getSpan(position);
Span currentSpan;
final boolean assignSpan = spanIndex == LayoutParams.INVALID_SPAN_ID;
if (assignSpan) {
currentSpan = lp.mFullSpan ? mSpans[0] : getNextSpan(layoutState);
mLazySpanLookup.setSpan(position, currentSpan);
if (DEBUG) {
Log.d(TAG, "assigned " + currentSpan.mIndex + " for " + position);
}
} else {
if (DEBUG) {
Log.d(TAG, "using " + spanIndex + " for pos " + position);
}
currentSpan = mSpans[spanIndex];
}
// assign span before measuring so that item decorators can get updated span index
lp.mSpan = currentSpan;
if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) {
addView(view);
} else {
addView(view, 0);
}
measureChildWithDecorationsAndMargin(view, lp, false);
final int start;
final int end;
if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) {
start = lp.mFullSpan ? getMaxEnd(defaultNewViewLine)
: currentSpan.getEndLine(defaultNewViewLine);
end = start + mPrimaryOrientation.getDecoratedMeasurement(view);
if (assignSpan && lp.mFullSpan) {
LazySpanLookup.FullSpanItem fullSpanItem;
fullSpanItem = createFullSpanItemFromEnd(start);
fullSpanItem.mGapDir = LayoutState.LAYOUT_START;
fullSpanItem.mPosition = position;
mLazySpanLookup.addFullSpanItem(fullSpanItem);
}
} else {
end = lp.mFullSpan ? getMinStart(defaultNewViewLine)
: currentSpan.getStartLine(defaultNewViewLine);
start = end - mPrimaryOrientation.getDecoratedMeasurement(view);
if (assignSpan && lp.mFullSpan) {
LazySpanLookup.FullSpanItem fullSpanItem;
fullSpanItem = createFullSpanItemFromStart(end);
fullSpanItem.mGapDir = LayoutState.LAYOUT_END;
fullSpanItem.mPosition = position;
mLazySpanLookup.addFullSpanItem(fullSpanItem);
}
}
// check if this item may create gaps in the future
if (lp.mFullSpan && layoutState.mItemDirection == LayoutState.ITEM_DIRECTION_HEAD) {
if (assignSpan) {
mLaidOutInvalidFullSpan = true;
} else {
final boolean hasInvalidGap;
if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) {
hasInvalidGap = !areAllEndsEqual();
} else { // layoutState.mLayoutDirection == LAYOUT_START
hasInvalidGap = !areAllStartsEqual();
}
if (hasInvalidGap) {
final LazySpanLookup.FullSpanItem fullSpanItem = mLazySpanLookup
.getFullSpanItem(position);
if (fullSpanItem != null) {
fullSpanItem.mHasUnwantedGapAfter = true;
}
mLaidOutInvalidFullSpan = true;
}
}
}
attachViewToSpans(view, lp, layoutState);
final int otherStart;
final int otherEnd;
if (isLayoutRTL() && mOrientation == VERTICAL) {
otherEnd = lp.mFullSpan ? mSecondaryOrientation.getEndAfterPadding() :
mSecondaryOrientation.getEndAfterPadding()
- (mSpanCount - 1 - currentSpan.mIndex) * mSizePerSpan;
otherStart = otherEnd - mSecondaryOrientation.getDecoratedMeasurement(view);
} else {
otherStart = lp.mFullSpan ? mSecondaryOrientation.getStartAfterPadding()
: currentSpan.mIndex * mSizePerSpan +
mSecondaryOrientation.getStartAfterPadding();
otherEnd = otherStart + mSecondaryOrientation.getDecoratedMeasurement(view);
}
if (mOrientation == VERTICAL) {
layoutDecoratedWithMargins(view, otherStart, start, otherEnd, end);
} else {
layoutDecoratedWithMargins(view, start, otherStart, end, otherEnd);
}
if (lp.mFullSpan) {
updateAllRemainingSpans(mLayoutState.mLayoutDirection, targetLine);
} else {
updateRemainingSpans(currentSpan, mLayoutState.mLayoutDirection, targetLine);
}
recycle(recycler, mLayoutState);
if (mLayoutState.mStopInFocusable && view.isFocusable()) {
if (lp.mFullSpan) {
mRemainingSpans.clear();
} else {
mRemainingSpans.set(currentSpan.mIndex, false);
}
}
added = true;
}
if (!added) {
recycle(recycler, mLayoutState);
}
final int diff;
if (mLayoutState.mLayoutDirection == LayoutState.LAYOUT_START) {
final int minStart = getMinStart(mPrimaryOrientation.getStartAfterPadding());
diff = mPrimaryOrientation.getStartAfterPadding() - minStart;
} else {
final int maxEnd = getMaxEnd(mPrimaryOrientation.getEndAfterPadding());
diff = maxEnd - mPrimaryOrientation.getEndAfterPadding();
}
return diff > 0 ? Math.min(layoutState.mAvailable, diff) : 0;
}
private LazySpanLookup.FullSpanItem createFullSpanItemFromEnd(int newItemTop) {
LazySpanLookup.FullSpanItem fsi = new LazySpanLookup.FullSpanItem();
fsi.mGapPerSpan = new int[mSpanCount];
for (int i = 0; i < mSpanCount; i++) {
fsi.mGapPerSpan[i] = newItemTop - mSpans[i].getEndLine(newItemTop);
}
return fsi;
}
private LazySpanLookup.FullSpanItem createFullSpanItemFromStart(int newItemBottom) {
LazySpanLookup.FullSpanItem fsi = new LazySpanLookup.FullSpanItem();
fsi.mGapPerSpan = new int[mSpanCount];
for (int i = 0; i < mSpanCount; i++) {
fsi.mGapPerSpan[i] = mSpans[i].getStartLine(newItemBottom) - newItemBottom;
}
return fsi;
}
private void attachViewToSpans(View view, LayoutParams lp, LayoutState layoutState) {
if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) {
if (lp.mFullSpan) {
appendViewToAllSpans(view);
} else {
lp.mSpan.appendToSpan(view);
}
} else {
if (lp.mFullSpan) {
prependViewToAllSpans(view);
} else {
lp.mSpan.prependToSpan(view);
}
}
}
private void recycle(RecyclerView.Recycler recycler, LayoutState layoutState) {
if (!layoutState.mRecycle || layoutState.mInfinite) {
return;
}
if (layoutState.mAvailable == 0) {
// easy, recycle line is still valid
if (layoutState.mLayoutDirection == LayoutState.LAYOUT_START) {
recycleFromEnd(recycler, layoutState.mEndLine);
} else {
recycleFromStart(recycler, layoutState.mStartLine);
}
} else {
// scrolling case, recycle line can be shifted by how much space we could cover
// by adding new views
if (layoutState.mLayoutDirection == LayoutState.LAYOUT_START) {
// calculate recycle line
int scrolled = layoutState.mStartLine - getMaxStart(layoutState.mStartLine);
final int line;
if (scrolled < 0) {
line = layoutState.mEndLine;
} else {
line = layoutState.mEndLine - Math.min(scrolled, layoutState.mAvailable);
}
recycleFromEnd(recycler, line);
} else {
// calculate recycle line
int scrolled = getMinEnd(layoutState.mEndLine) - layoutState.mEndLine;
final int line;
if (scrolled < 0) {
line = layoutState.mStartLine;
} else {
line = layoutState.mStartLine + Math.min(scrolled, layoutState.mAvailable);
}
recycleFromStart(recycler, line);
}
}
}
private void appendViewToAllSpans(View view) {
// traverse in reverse so that we end up assigning full span items to 0
for (int i = mSpanCount - 1; i >= 0; i--) {
mSpans[i].appendToSpan(view);
}
}
private void prependViewToAllSpans(View view) {
// traverse in reverse so that we end up assigning full span items to 0
for (int i = mSpanCount - 1; i >= 0; i--) {
mSpans[i].prependToSpan(view);
}
}
private void layoutDecoratedWithMargins(View child, int left, int top, int right, int bottom) {
LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (DEBUG) {
Log.d(TAG, "layout decorated pos: " + lp.getViewLayoutPosition() + ", span:"
+ lp.getSpanIndex() + ", fullspan:" + lp.mFullSpan
+ ". l:" + left + ",t:" + top
+ ", r:" + right + ", b:" + bottom);
}
layoutDecorated(child, left + lp.leftMargin, top + lp.topMargin, right - lp.rightMargin
, bottom - lp.bottomMargin);
}
private void updateAllRemainingSpans(int layoutDir, int targetLine) {
for (int i = 0; i < mSpanCount; i++) {
if (mSpans[i].mViews.isEmpty()) {
continue;
}
updateRemainingSpans(mSpans[i], layoutDir, targetLine);
}
}
private void updateRemainingSpans(Span span, int layoutDir, int targetLine) {
final int deletedSize = span.getDeletedSize();
if (layoutDir == LayoutState.LAYOUT_START) {
final int line = span.getStartLine();
if (line + deletedSize <= targetLine) {
mRemainingSpans.set(span.mIndex, false);
}
} else {
final int line = span.getEndLine();
if (line - deletedSize >= targetLine) {
mRemainingSpans.set(span.mIndex, false);
}
}
}
private int getMaxStart(int def) {
int maxStart = mSpans[0].getStartLine(def);
for (int i = 1; i < mSpanCount; i++) {
final int spanStart = mSpans[i].getStartLine(def);
if (spanStart > maxStart) {
maxStart = spanStart;
}
}
return maxStart;
}
private int getMinStart(int def) {
int minStart = mSpans[0].getStartLine(def);
for (int i = 1; i < mSpanCount; i++) {
final int spanStart = mSpans[i].getStartLine(def);
if (spanStart < minStart) {
minStart = spanStart;
}
}
return minStart;
}
boolean areAllEndsEqual() {
int end = mSpans[0].getEndLine(Span.INVALID_LINE);
for (int i = 1; i < mSpanCount; i++) {
if (mSpans[i].getEndLine(Span.INVALID_LINE) != end) {
return false;
}
}
return true;
}
boolean areAllStartsEqual() {
int start = mSpans[0].getStartLine(Span.INVALID_LINE);
for (int i = 1; i < mSpanCount; i++) {
if (mSpans[i].getStartLine(Span.INVALID_LINE) != start) {
return false;
}
}
return true;
}
private int getMaxEnd(int def) {
int maxEnd = mSpans[0].getEndLine(def);
for (int i = 1; i < mSpanCount; i++) {
final int spanEnd = mSpans[i].getEndLine(def);
if (spanEnd > maxEnd) {
maxEnd = spanEnd;
}
}
return maxEnd;
}
private int getMinEnd(int def) {
int minEnd = mSpans[0].getEndLine(def);
for (int i = 1; i < mSpanCount; i++) {
final int spanEnd = mSpans[i].getEndLine(def);
if (spanEnd < minEnd) {
minEnd = spanEnd;
}
}
return minEnd;
}
private void recycleFromStart(RecyclerView.Recycler recycler, int line) {
while (getChildCount() > 0) {
View child = getChildAt(0);
if (mPrimaryOrientation.getDecoratedEnd(child) <= line) {
LayoutParams lp = (LayoutParams) child.getLayoutParams();
// Don't recycle the last View in a span not to lose span's start/end lines
if (lp.mFullSpan) {
for (int j = 0; j < mSpanCount; j++) {
if (mSpans[j].mViews.size() == 1) {
return;
}
}
for (int j = 0; j < mSpanCount; j++) {
mSpans[j].popStart();
}
} else {
if (lp.mSpan.mViews.size() == 1) {
return;
}
lp.mSpan.popStart();
}
removeAndRecycleView(child, recycler);
} else {
return;// done
}
}
}
private void recycleFromEnd(RecyclerView.Recycler recycler, int line) {
final int childCount = getChildCount();
int i;
for (i = childCount - 1; i >= 0; i--) {
View child = getChildAt(i);
if (mPrimaryOrientation.getDecoratedStart(child) >= line) {
LayoutParams lp = (LayoutParams) child.getLayoutParams();
// Don't recycle the last View in a span not to lose span's start/end lines
if (lp.mFullSpan) {
for (int j = 0; j < mSpanCount; j++) {
if (mSpans[j].mViews.size() == 1) {
return;
}
}
for (int j = 0; j < mSpanCount; j++) {
mSpans[j].popEnd();
}
} else {
if (lp.mSpan.mViews.size() == 1) {
return;
}
lp.mSpan.popEnd();
}
removeAndRecycleView(child, recycler);
} else {
return;// done
}
}
}
/**
* @return True if last span is the first one we want to fill
*/
private boolean preferLastSpan(int layoutDir) {
if (mOrientation == HORIZONTAL) {
return (layoutDir == LayoutState.LAYOUT_START) != mShouldReverseLayout;
}
return ((layoutDir == LayoutState.LAYOUT_START) == mShouldReverseLayout) == isLayoutRTL();
}
/**
* Finds the span for the next view.
*/
private Span getNextSpan(LayoutState layoutState) {
final boolean preferLastSpan = preferLastSpan(layoutState.mLayoutDirection);
final int startIndex, endIndex, diff;
if (preferLastSpan) {
startIndex = mSpanCount - 1;
endIndex = -1;
diff = -1;
} else {
startIndex = 0;
endIndex = mSpanCount;
diff = 1;
}
if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) {
Span min = null;
int minLine = Integer.MAX_VALUE;
final int defaultLine = mPrimaryOrientation.getStartAfterPadding();
for (int i = startIndex; i != endIndex; i += diff) {
final Span other = mSpans[i];
int otherLine = other.getEndLine(defaultLine);
if (otherLine < minLine) {
min = other;
minLine = otherLine;
}
}
return min;
} else {
Span max = null;
int maxLine = Integer.MIN_VALUE;
final int defaultLine = mPrimaryOrientation.getEndAfterPadding();
for (int i = startIndex; i != endIndex; i += diff) {
final Span other = mSpans[i];
int otherLine = other.getStartLine(defaultLine);
if (otherLine > maxLine) {
max = other;
maxLine = otherLine;
}
}
return max;
}
}
@Override
public boolean canScrollVertically() {
return mOrientation == VERTICAL;
}
@Override
public boolean canScrollHorizontally() {
return mOrientation == HORIZONTAL;
}
@Override
public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler,
RecyclerView.State state) {
return scrollBy(dx, recycler, state);
}
@Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler,
RecyclerView.State state) {
return scrollBy(dy, recycler, state);
}
private int calculateScrollDirectionForPosition(int position) {
if (getChildCount() == 0) {
return mShouldReverseLayout ? LayoutState.LAYOUT_END : LayoutState.LAYOUT_START;
}
final int firstChildPos = getFirstChildPosition();
return position < firstChildPos != mShouldReverseLayout ? LayoutState.LAYOUT_START : LayoutState.LAYOUT_END;
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
int position) {
LinearSmoothScroller scroller = new LinearSmoothScroller(recyclerView.getContext()) {
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
final int direction = calculateScrollDirectionForPosition(targetPosition);
if (direction == 0) {
return null;
}
if (mOrientation == HORIZONTAL) {
return new PointF(direction, 0);
} else {
return new PointF(0, direction);
}
}
};
scroller.setTargetPosition(position);
startSmoothScroll(scroller);
}
@Override
public void scrollToPosition(int position) {
if (mPendingSavedState != null && mPendingSavedState.mAnchorPosition != position) {
mPendingSavedState.invalidateAnchorPositionInfo();
}
mPendingScrollPosition = position;
mPendingScrollPositionOffset = INVALID_OFFSET;
requestLayout();
}
/**
* Scroll to the specified adapter position with the given offset from layout start.
* <p>
* Note that scroll position change will not be reflected until the next layout call.
* <p>
* If you are just trying to make a position visible, use {@link #scrollToPosition(int)}.
*
* @param position Index (starting at 0) of the reference item.
* @param offset The distance (in pixels) between the start edge of the item view and
* start edge of the RecyclerView.
* @see #setReverseLayout(boolean)
* @see #scrollToPosition(int)
*/
public void scrollToPositionWithOffset(int position, int offset) {
if (mPendingSavedState != null) {
mPendingSavedState.invalidateAnchorPositionInfo();
}
mPendingScrollPosition = position;
mPendingScrollPositionOffset = offset;
requestLayout();
}
int scrollBy(int dt, RecyclerView.Recycler recycler, RecyclerView.State state) {
final int referenceChildPosition;
final int layoutDir;
if (dt > 0) { // layout towards end
layoutDir = LayoutState.LAYOUT_END;
referenceChildPosition = getLastChildPosition();
} else {
layoutDir = LayoutState.LAYOUT_START;
referenceChildPosition = getFirstChildPosition();
}
mLayoutState.mRecycle = true;
updateLayoutState(referenceChildPosition, state);
setLayoutStateDirection(layoutDir);
mLayoutState.mCurrentPosition = referenceChildPosition + mLayoutState.mItemDirection;
final int absDt = Math.abs(dt);
mLayoutState.mAvailable = absDt;
int consumed = fill(recycler, mLayoutState, state);
final int totalScroll;
if (absDt < consumed) {
totalScroll = dt;
} else if (dt < 0) {
totalScroll = -consumed;
} else { // dt > 0
totalScroll = consumed;
}
if (DEBUG) {
Log.d(TAG, "asked " + dt + " scrolled" + totalScroll);
}
mPrimaryOrientation.offsetChildren(-totalScroll);
// always reset this if we scroll for a proper save instance state
mLastLayoutFromEnd = mShouldReverseLayout;
return totalScroll;
}
private int getLastChildPosition() {
final int childCount = getChildCount();
return childCount == 0 ? 0 : getPosition(getChildAt(childCount - 1));
}
private int getFirstChildPosition() {
final int childCount = getChildCount();
return childCount == 0 ? 0 : getPosition(getChildAt(0));
}
/**
* Finds the first View that can be used as an anchor View.
*
* @return Position of the View or 0 if it cannot find any such View.
*/
private int findFirstReferenceChildPosition(int itemCount) {
final int limit = getChildCount();
for (int i = 0; i < limit; i++) {
final View view = getChildAt(i);
final int position = getPosition(view);
if (position >= 0 && position < itemCount) {
return position;
}
}
return 0;
}
/**
* Finds the last View that can be used as an anchor View.
*
* @return Position of the View or 0 if it cannot find any such View.
*/
private int findLastReferenceChildPosition(int itemCount) {
for (int i = getChildCount() - 1; i >= 0; i--) {
final View view = getChildAt(i);
final int position = getPosition(view);
if (position >= 0 && position < itemCount) {
return position;
}
}
return 0;
}
@SuppressWarnings("deprecation")
@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
if (mOrientation == HORIZONTAL) {
return new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.FILL_PARENT);
} else {
return new LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
}
@Override
public RecyclerView.LayoutParams generateLayoutParams(Context c, AttributeSet attrs) {
return new LayoutParams(c, attrs);
}
@Override
public RecyclerView.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
if (lp instanceof ViewGroup.MarginLayoutParams) {
return new LayoutParams((ViewGroup.MarginLayoutParams) lp);
} else {
return new LayoutParams(lp);
}
}
@Override
public boolean checkLayoutParams(RecyclerView.LayoutParams lp) {
return lp instanceof LayoutParams;
}
public int getOrientation() {
return mOrientation;
}
@Nullable
@Override
public View onFocusSearchFailed(View focused, int direction, RecyclerView.Recycler recycler,
RecyclerView.State state) {
if (getChildCount() == 0) {
return null;
}
final View directChild = findContainingItemView(focused);
if (directChild == null) {
return null;
}
resolveShouldLayoutReverse();
final int layoutDir = convertFocusDirectionToLayoutDirection(direction);
if (layoutDir == LayoutState.INVALID_LAYOUT) {
return null;
}
LayoutParams prevFocusLayoutParams = (LayoutParams) directChild.getLayoutParams();
boolean prevFocusFullSpan = prevFocusLayoutParams.mFullSpan;
final Span prevFocusSpan = prevFocusLayoutParams.mSpan;
final int referenceChildPosition;
if (layoutDir == LayoutState.LAYOUT_END) { // layout towards end
referenceChildPosition = getLastChildPosition();
} else {
referenceChildPosition = getFirstChildPosition();
}
updateLayoutState(referenceChildPosition, state);
setLayoutStateDirection(layoutDir);
mLayoutState.mCurrentPosition = referenceChildPosition + mLayoutState.mItemDirection;
mLayoutState.mAvailable = (int) (MAX_SCROLL_FACTOR * mPrimaryOrientation.getTotalSpace());
mLayoutState.mStopInFocusable = true;
mLayoutState.mRecycle = false;
fill(recycler, mLayoutState, state);
mLastLayoutFromEnd = mShouldReverseLayout;
if (!prevFocusFullSpan) {
View view = prevFocusSpan.getFocusableViewAfter(referenceChildPosition, layoutDir);
if (view != null && view != directChild) {
return view;
}
}
// either could not find from the desired span or prev view is full span.
// traverse all spans
if (preferLastSpan(layoutDir)) {
for (int i = mSpanCount - 1; i >= 0; i --) {
View view = mSpans[i].getFocusableViewAfter(referenceChildPosition, layoutDir);
if (view != null && view != directChild) {
return view;
}
}
} else {
for (int i = 0; i < mSpanCount; i ++) {
View view = mSpans[i].getFocusableViewAfter(referenceChildPosition, layoutDir);
if (view != null && view != directChild) {
return view;
}
}
}
return null;
}
/**
* Converts a focusDirection to orientation.
*
* @param focusDirection One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
* {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT},
* {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD}
* or 0 for not applicable
* @return {@link LayoutState#LAYOUT_START} or {@link LayoutState#LAYOUT_END} if focus direction
* is applicable to current state, {@link LayoutState#INVALID_LAYOUT} otherwise.
*/
private int convertFocusDirectionToLayoutDirection(int focusDirection) {
switch (focusDirection) {
case View.FOCUS_BACKWARD:
return LayoutState.LAYOUT_START;
case View.FOCUS_FORWARD:
return LayoutState.LAYOUT_END;
case View.FOCUS_UP:
return mOrientation == VERTICAL ? LayoutState.LAYOUT_START
: LayoutState.INVALID_LAYOUT;
case View.FOCUS_DOWN:
return mOrientation == VERTICAL ? LayoutState.LAYOUT_END
: LayoutState.INVALID_LAYOUT;
case View.FOCUS_LEFT:
return mOrientation == HORIZONTAL ? LayoutState.LAYOUT_START
: LayoutState.INVALID_LAYOUT;
case View.FOCUS_RIGHT:
return mOrientation == HORIZONTAL ? LayoutState.LAYOUT_END
: LayoutState.INVALID_LAYOUT;
default:
if (DEBUG) {
Log.d(TAG, "Unknown focus request:" + focusDirection);
}
return LayoutState.INVALID_LAYOUT;
}
}
/**
* LayoutParams used by StaggeredGridLayoutManager.
* <p>
* Note that if the orientation is {@link #VERTICAL}, the width parameter is ignored and if the
* orientation is {@link #HORIZONTAL} the height parameter is ignored because child view is
* expected to fill all of the space given to it.
*/
public static class LayoutParams extends RecyclerView.LayoutParams {
/**
* Span Id for Views that are not laid out yet.
*/
public static final int INVALID_SPAN_ID = -1;
// Package scope to be able to access from tests.
Span mSpan;
boolean mFullSpan;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(ViewGroup.MarginLayoutParams source) {
super(source);
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
public LayoutParams(RecyclerView.LayoutParams source) {
super(source);
}
/**
* When set to true, the item will layout using all span area. That means, if orientation
* is vertical, the view will have full width; if orientation is horizontal, the view will
* have full height.
*
* @param fullSpan True if this item should traverse all spans.
* @see #isFullSpan()
*/
public void setFullSpan(boolean fullSpan) {
mFullSpan = fullSpan;
}
/**
* Returns whether this View occupies all available spans or just one.
*
* @return True if the View occupies all spans or false otherwise.
* @see #setFullSpan(boolean)
*/
public boolean isFullSpan() {
return mFullSpan;
}
/**
* Returns the Span index to which this View is assigned.
*
* @return The Span index of the View. If View is not yet assigned to any span, returns
* {@link #INVALID_SPAN_ID}.
*/
public final int getSpanIndex() {
if (mSpan == null) {
return INVALID_SPAN_ID;
}
return mSpan.mIndex;
}
}
// Package scoped to access from tests.
class Span {
static final int INVALID_LINE = Integer.MIN_VALUE;
private ArrayList<View> mViews = new ArrayList<>();
int mCachedStart = INVALID_LINE;
int mCachedEnd = INVALID_LINE;
int mDeletedSize = 0;
final int mIndex;
private Span(int index) {
mIndex = index;
}
int getStartLine(int def) {
if (mCachedStart != INVALID_LINE) {
return mCachedStart;
}
if (mViews.size() == 0) {
return def;
}
calculateCachedStart();
return mCachedStart;
}
void calculateCachedStart() {
final View startView = mViews.get(0);
final LayoutParams lp = getLayoutParams(startView);
mCachedStart = mPrimaryOrientation.getDecoratedStart(startView);
if (lp.mFullSpan) {
LazySpanLookup.FullSpanItem fsi = mLazySpanLookup
.getFullSpanItem(lp.getViewLayoutPosition());
if (fsi != null && fsi.mGapDir == LayoutState.LAYOUT_START) {
mCachedStart -= fsi.getGapForSpan(mIndex);
}
}
}
// Use this one when default value does not make sense and not having a value means a bug.
int getStartLine() {
if (mCachedStart != INVALID_LINE) {
return mCachedStart;
}
calculateCachedStart();
return mCachedStart;
}
int getEndLine(int def) {
if (mCachedEnd != INVALID_LINE) {
return mCachedEnd;
}
final int size = mViews.size();
if (size == 0) {
return def;
}
calculateCachedEnd();
return mCachedEnd;
}
void calculateCachedEnd() {
final View endView = mViews.get(mViews.size() - 1);
final LayoutParams lp = getLayoutParams(endView);
mCachedEnd = mPrimaryOrientation.getDecoratedEnd(endView);
if (lp.mFullSpan) {
LazySpanLookup.FullSpanItem fsi = mLazySpanLookup
.getFullSpanItem(lp.getViewLayoutPosition());
if (fsi != null && fsi.mGapDir == LayoutState.LAYOUT_END) {
mCachedEnd += fsi.getGapForSpan(mIndex);
}
}
}
// Use this one when default value does not make sense and not having a value means a bug.
int getEndLine() {
if (mCachedEnd != INVALID_LINE) {
return mCachedEnd;
}
calculateCachedEnd();
return mCachedEnd;
}
void prependToSpan(View view) {
LayoutParams lp = getLayoutParams(view);
lp.mSpan = this;
mViews.add(0, view);
mCachedStart = INVALID_LINE;
if (mViews.size() == 1) {
mCachedEnd = INVALID_LINE;
}
if (lp.isItemRemoved() || lp.isItemChanged()) {
mDeletedSize += mPrimaryOrientation.getDecoratedMeasurement(view);
}
}
void appendToSpan(View view) {
LayoutParams lp = getLayoutParams(view);
lp.mSpan = this;
mViews.add(view);
mCachedEnd = INVALID_LINE;
if (mViews.size() == 1) {
mCachedStart = INVALID_LINE;
}
if (lp.isItemRemoved() || lp.isItemChanged()) {
mDeletedSize += mPrimaryOrientation.getDecoratedMeasurement(view);
}
}
// Useful method to preserve positions on a re-layout.
void cacheReferenceLineAndClear(boolean reverseLayout, int offset) {
int reference;
if (reverseLayout) {
reference = getEndLine(INVALID_LINE);
} else {
reference = getStartLine(INVALID_LINE);
}
clear();
if (reference == INVALID_LINE) {
return;
}
if ((reverseLayout && reference < mPrimaryOrientation.getEndAfterPadding()) ||
(!reverseLayout && reference > mPrimaryOrientation.getStartAfterPadding())) {
return;
}
if (offset != INVALID_OFFSET) {
reference += offset;
}
mCachedStart = mCachedEnd = reference;
}
void clear() {
mViews.clear();
invalidateCache();
mDeletedSize = 0;
}
void invalidateCache() {
mCachedStart = INVALID_LINE;
mCachedEnd = INVALID_LINE;
}
void setLine(int line) {
mCachedEnd = mCachedStart = line;
}
void popEnd() {
final int size = mViews.size();
View end = mViews.remove(size - 1);
final LayoutParams lp = getLayoutParams(end);
lp.mSpan = null;
if (lp.isItemRemoved() || lp.isItemChanged()) {
mDeletedSize -= mPrimaryOrientation.getDecoratedMeasurement(end);
}
if (size == 1) {
mCachedStart = INVALID_LINE;
}
mCachedEnd = INVALID_LINE;
}
void popStart() {
View start = mViews.remove(0);
final LayoutParams lp = getLayoutParams(start);
lp.mSpan = null;
if (mViews.size() == 0) {
mCachedEnd = INVALID_LINE;
}
if (lp.isItemRemoved() || lp.isItemChanged()) {
mDeletedSize -= mPrimaryOrientation.getDecoratedMeasurement(start);
}
mCachedStart = INVALID_LINE;
}
public int getDeletedSize() {
return mDeletedSize;
}
LayoutParams getLayoutParams(View view) {
return (LayoutParams) view.getLayoutParams();
}
void onOffset(int dt) {
if (mCachedStart != INVALID_LINE) {
mCachedStart += dt;
}
if (mCachedEnd != INVALID_LINE) {
mCachedEnd += dt;
}
}
public int findFirstVisibleItemPosition() {
return mReverseLayout
? findOneVisibleChild(mViews.size() - 1, -1, false)
: findOneVisibleChild(0, mViews.size(), false);
}
public int findFirstCompletelyVisibleItemPosition() {
return mReverseLayout
? findOneVisibleChild(mViews.size() - 1, -1, true)
: findOneVisibleChild(0, mViews.size(), true);
}
public int findLastVisibleItemPosition() {
return mReverseLayout
? findOneVisibleChild(0, mViews.size(), false)
: findOneVisibleChild(mViews.size() - 1, -1, false);
}
public int findLastCompletelyVisibleItemPosition() {
return mReverseLayout
? findOneVisibleChild(0, mViews.size(), true)
: findOneVisibleChild(mViews.size() - 1, -1, true);
}
int findOneVisibleChild(int fromIndex, int toIndex, boolean completelyVisible) {
final int start = mPrimaryOrientation.getStartAfterPadding();
final int end = mPrimaryOrientation.getEndAfterPadding();
final int next = toIndex > fromIndex ? 1 : -1;
for (int i = fromIndex; i != toIndex; i += next) {
final View child = mViews.get(i);
final int childStart = mPrimaryOrientation.getDecoratedStart(child);
final int childEnd = mPrimaryOrientation.getDecoratedEnd(child);
if (childStart < end && childEnd > start) {
if (completelyVisible) {
if (childStart >= start && childEnd <= end) {
return getPosition(child);
}
} else {
return getPosition(child);
}
}
}
return NO_POSITION;
}
/**
* Depending on the layout direction, returns the View that is after the given position.
*/
public View getFocusableViewAfter(int referenceChildPosition, int layoutDir) {
View candidate = null;
if (layoutDir == LayoutState.LAYOUT_START) {
final int limit = mViews.size();
for (int i = 0; i < limit; i++) {
final View view = mViews.get(i);
if (view.isFocusable() &&
(getPosition(view) > referenceChildPosition == mReverseLayout) ) {
candidate = view;
} else {
break;
}
}
} else {
for (int i = mViews.size() - 1; i >= 0; i--) {
final View view = mViews.get(i);
if (view.isFocusable() &&
(getPosition(view) > referenceChildPosition == !mReverseLayout)) {
candidate = view;
} else {
break;
}
}
}
return candidate;
}
}
/**
* An array of mappings from adapter position to span.
* This only grows when a write happens and it grows up to the size of the adapter.
*/
static class LazySpanLookup {
private static final int MIN_SIZE = 10;
int[] mData;
List<FullSpanItem> mFullSpanItems;
/**
* Invalidates everything after this position, including full span information
*/
int forceInvalidateAfter(int position) {
if (mFullSpanItems != null) {
for (int i = mFullSpanItems.size() - 1; i >= 0; i--) {
FullSpanItem fsi = mFullSpanItems.get(i);
if (fsi.mPosition >= position) {
mFullSpanItems.remove(i);
}
}
}
return invalidateAfter(position);
}
/**
* returns end position for invalidation.
*/
int invalidateAfter(int position) {
if (mData == null) {
return RecyclerView.NO_POSITION;
}
if (position >= mData.length) {
return RecyclerView.NO_POSITION;
}
int endPosition = invalidateFullSpansAfter(position);
if (endPosition == RecyclerView.NO_POSITION) {
Arrays.fill(mData, position, mData.length, LayoutParams.INVALID_SPAN_ID);
return mData.length;
} else {
// just invalidate items in between
Arrays.fill(mData, position, endPosition + 1, LayoutParams.INVALID_SPAN_ID);
return endPosition + 1;
}
}
int getSpan(int position) {
if (mData == null || position >= mData.length) {
return LayoutParams.INVALID_SPAN_ID;
} else {
return mData[position];
}
}
void setSpan(int position, Span span) {
ensureSize(position);
mData[position] = span.mIndex;
}
int sizeForPosition(int position) {
int len = mData.length;
while (len <= position) {
len *= 2;
}
return len;
}
void ensureSize(int position) {
if (mData == null) {
mData = new int[Math.max(position, MIN_SIZE) + 1];
Arrays.fill(mData, LayoutParams.INVALID_SPAN_ID);
} else if (position >= mData.length) {
int[] old = mData;
mData = new int[sizeForPosition(position)];
System.arraycopy(old, 0, mData, 0, old.length);
Arrays.fill(mData, old.length, mData.length, LayoutParams.INVALID_SPAN_ID);
}
}
void clear() {
if (mData != null) {
Arrays.fill(mData, LayoutParams.INVALID_SPAN_ID);
}
mFullSpanItems = null;
}
void offsetForRemoval(int positionStart, int itemCount) {
if (mData == null || positionStart >= mData.length) {
return;
}
ensureSize(positionStart + itemCount);
System.arraycopy(mData, positionStart + itemCount, mData, positionStart,
mData.length - positionStart - itemCount);
Arrays.fill(mData, mData.length - itemCount, mData.length,
LayoutParams.INVALID_SPAN_ID);
offsetFullSpansForRemoval(positionStart, itemCount);
}
private void offsetFullSpansForRemoval(int positionStart, int itemCount) {
if (mFullSpanItems == null) {
return;
}
final int end = positionStart + itemCount;
for (int i = mFullSpanItems.size() - 1; i >= 0; i--) {
FullSpanItem fsi = mFullSpanItems.get(i);
if (fsi.mPosition < positionStart) {
continue;
}
if (fsi.mPosition < end) {
mFullSpanItems.remove(i);
} else {
fsi.mPosition -= itemCount;
}
}
}
void offsetForAddition(int positionStart, int itemCount) {
if (mData == null || positionStart >= mData.length) {
return;
}
ensureSize(positionStart + itemCount);
System.arraycopy(mData, positionStart, mData, positionStart + itemCount,
mData.length - positionStart - itemCount);
Arrays.fill(mData, positionStart, positionStart + itemCount,
LayoutParams.INVALID_SPAN_ID);
offsetFullSpansForAddition(positionStart, itemCount);
}
private void offsetFullSpansForAddition(int positionStart, int itemCount) {
if (mFullSpanItems == null) {
return;
}
for (int i = mFullSpanItems.size() - 1; i >= 0; i--) {
FullSpanItem fsi = mFullSpanItems.get(i);
if (fsi.mPosition < positionStart) {
continue;
}
fsi.mPosition += itemCount;
}
}
/**
* Returns when invalidation should end. e.g. hitting a full span position.
* Returned position SHOULD BE invalidated.
*/
private int invalidateFullSpansAfter(int position) {
if (mFullSpanItems == null) {
return RecyclerView.NO_POSITION;
}
final FullSpanItem item = getFullSpanItem(position);
// if there is an fsi at this position, get rid of it.
if (item != null) {
mFullSpanItems.remove(item);
}
int nextFsiIndex = -1;
final int count = mFullSpanItems.size();
for (int i = 0; i < count; i++) {
FullSpanItem fsi = mFullSpanItems.get(i);
if (fsi.mPosition >= position) {
nextFsiIndex = i;
break;
}
}
if (nextFsiIndex != -1) {
FullSpanItem fsi = mFullSpanItems.get(nextFsiIndex);
mFullSpanItems.remove(nextFsiIndex);
return fsi.mPosition;
}
return RecyclerView.NO_POSITION;
}
public void addFullSpanItem(FullSpanItem fullSpanItem) {
if (mFullSpanItems == null) {
mFullSpanItems = new ArrayList<>();
}
final int size = mFullSpanItems.size();
for (int i = 0; i < size; i++) {
FullSpanItem other = mFullSpanItems.get(i);
if (other.mPosition == fullSpanItem.mPosition) {
if (DEBUG) {
throw new IllegalStateException("two fsis for same position");
} else {
mFullSpanItems.remove(i);
}
}
if (other.mPosition >= fullSpanItem.mPosition) {
mFullSpanItems.add(i, fullSpanItem);
return;
}
}
// if it is not added to a position.
mFullSpanItems.add(fullSpanItem);
}
public FullSpanItem getFullSpanItem(int position) {
if (mFullSpanItems == null) {
return null;
}
for (int i = mFullSpanItems.size() - 1; i >= 0; i--) {
final FullSpanItem fsi = mFullSpanItems.get(i);
if (fsi.mPosition == position) {
return fsi;
}
}
return null;
}
/**
* @param minPos inclusive
* @param maxPos exclusive
* @param gapDir if not 0, returns FSIs on in that direction
* @param hasUnwantedGapAfter If true, when full span item has unwanted gaps, it will be
* returned even if its gap direction does not match.
*/
public FullSpanItem getFirstFullSpanItemInRange(int minPos, int maxPos, int gapDir,
boolean hasUnwantedGapAfter) {
if (mFullSpanItems == null) {
return null;
}
final int limit = mFullSpanItems.size();
for (int i = 0; i < limit; i++) {
FullSpanItem fsi = mFullSpanItems.get(i);
if (fsi.mPosition >= maxPos) {
return null;
}
if (fsi.mPosition >= minPos
&& (gapDir == 0 || fsi.mGapDir == gapDir ||
(hasUnwantedGapAfter && fsi.mHasUnwantedGapAfter))) {
return fsi;
}
}
return null;
}
/**
* We keep information about full span items because they may create gaps in the UI.
*/
static class FullSpanItem implements Parcelable {
int mPosition;
int mGapDir;
int[] mGapPerSpan;
// A full span may be laid out in primary direction but may have gaps due to
// invalidation of views after it. This is recorded during a reverse scroll and if
// view is still on the screen after scroll stops, we have to recalculate layout
boolean mHasUnwantedGapAfter;
public FullSpanItem(Parcel in) {
mPosition = in.readInt();
mGapDir = in.readInt();
mHasUnwantedGapAfter = in.readInt() == 1;
int spanCount = in.readInt();
if (spanCount > 0) {
mGapPerSpan = new int[spanCount];
in.readIntArray(mGapPerSpan);
}
}
public FullSpanItem() {
}
int getGapForSpan(int spanIndex) {
return mGapPerSpan == null ? 0 : mGapPerSpan[spanIndex];
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mPosition);
dest.writeInt(mGapDir);
dest.writeInt(mHasUnwantedGapAfter ? 1 : 0);
if (mGapPerSpan != null && mGapPerSpan.length > 0) {
dest.writeInt(mGapPerSpan.length);
dest.writeIntArray(mGapPerSpan);
} else {
dest.writeInt(0);
}
}
@Override
public String toString() {
return "FullSpanItem{" +
"mPosition=" + mPosition +
", mGapDir=" + mGapDir +
", mHasUnwantedGapAfter=" + mHasUnwantedGapAfter +
", mGapPerSpan=" + Arrays.toString(mGapPerSpan) +
'}';
}
public static final Parcelable.Creator<FullSpanItem> CREATOR
= new Parcelable.Creator<FullSpanItem>() {
@Override
public FullSpanItem createFromParcel(Parcel in) {
return new FullSpanItem(in);
}
@Override
public FullSpanItem[] newArray(int size) {
return new FullSpanItem[size];
}
};
}
}
/**
* @hide
*/
public static class SavedState implements Parcelable {
int mAnchorPosition;
int mVisibleAnchorPosition; // Replacement for span info when spans are invalidated
int mSpanOffsetsSize;
int[] mSpanOffsets;
int mSpanLookupSize;
int[] mSpanLookup;
List<LazySpanLookup.FullSpanItem> mFullSpanItems;
boolean mReverseLayout;
boolean mAnchorLayoutFromEnd;
boolean mLastLayoutRTL;
public SavedState() {
}
SavedState(Parcel in) {
mAnchorPosition = in.readInt();
mVisibleAnchorPosition = in.readInt();
mSpanOffsetsSize = in.readInt();
if (mSpanOffsetsSize > 0) {
mSpanOffsets = new int[mSpanOffsetsSize];
in.readIntArray(mSpanOffsets);
}
mSpanLookupSize = in.readInt();
if (mSpanLookupSize > 0) {
mSpanLookup = new int[mSpanLookupSize];
in.readIntArray(mSpanLookup);
}
mReverseLayout = in.readInt() == 1;
mAnchorLayoutFromEnd = in.readInt() == 1;
mLastLayoutRTL = in.readInt() == 1;
//noinspection unchecked
mFullSpanItems = in.readArrayList(
LazySpanLookup.FullSpanItem.class.getClassLoader());
}
public SavedState(SavedState other) {
mSpanOffsetsSize = other.mSpanOffsetsSize;
mAnchorPosition = other.mAnchorPosition;
mVisibleAnchorPosition = other.mVisibleAnchorPosition;
mSpanOffsets = other.mSpanOffsets;
mSpanLookupSize = other.mSpanLookupSize;
mSpanLookup = other.mSpanLookup;
mReverseLayout = other.mReverseLayout;
mAnchorLayoutFromEnd = other.mAnchorLayoutFromEnd;
mLastLayoutRTL = other.mLastLayoutRTL;
mFullSpanItems = other.mFullSpanItems;
}
void invalidateSpanInfo() {
mSpanOffsets = null;
mSpanOffsetsSize = 0;
mSpanLookupSize = 0;
mSpanLookup = null;
mFullSpanItems = null;
}
void invalidateAnchorPositionInfo() {
mSpanOffsets = null;
mSpanOffsetsSize = 0;
mAnchorPosition = NO_POSITION;
mVisibleAnchorPosition = NO_POSITION;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mAnchorPosition);
dest.writeInt(mVisibleAnchorPosition);
dest.writeInt(mSpanOffsetsSize);
if (mSpanOffsetsSize > 0) {
dest.writeIntArray(mSpanOffsets);
}
dest.writeInt(mSpanLookupSize);
if (mSpanLookupSize > 0) {
dest.writeIntArray(mSpanLookup);
}
dest.writeInt(mReverseLayout ? 1 : 0);
dest.writeInt(mAnchorLayoutFromEnd ? 1 : 0);
dest.writeInt(mLastLayoutRTL ? 1 : 0);
dest.writeList(mFullSpanItems);
}
public static final Parcelable.Creator<SavedState> CREATOR
= new Parcelable.Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
/**
* Data class to hold the information about an anchor position which is used in onLayout call.
*/
private class AnchorInfo {
int mPosition;
int mOffset;
boolean mLayoutFromEnd;
boolean mInvalidateOffsets;
void reset() {
mPosition = NO_POSITION;
mOffset = INVALID_OFFSET;
mLayoutFromEnd = false;
mInvalidateOffsets = false;
}
void assignCoordinateFromPadding() {
mOffset = mLayoutFromEnd ? mPrimaryOrientation.getEndAfterPadding()
: mPrimaryOrientation.getStartAfterPadding();
}
void assignCoordinateFromPadding(int addedDistance) {
if (mLayoutFromEnd) {
mOffset = mPrimaryOrientation.getEndAfterPadding() - addedDistance;
} else {
mOffset = mPrimaryOrientation.getStartAfterPadding() + addedDistance;
}
}
}
}
|
amirlotfi/Nikagram
|
app/src/main/java/ir/nikagram/messenger/support/widget/StaggeredGridLayoutManager.java
|
Java
|
gpl-2.0
| 117,717
|
<?php
/*
*
* Ampoliros Application Server
*
* http://www.ampoliros.com
*
*
*
* Copyright (C) 2000-2004 Solarix
*
* 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
*
*/
// $Id: AllAmpolirosTests.php,v 1.4 2004-07-08 15:04:27 alex Exp $
/**
* Ampoliros test case.
* How to run the tests:
* carthag carthag.dev.unit.textui.TestRunner AllAmpolirosTests
* @package com.solarix.ampoliros.tests
* @author Alex Pagnoni <alex.pagnoni@solarix.it>
* @copyright Copyright 2000-2004 Solarix Srl
* @since 4.0
*/
package('com.solarix.ampoliros.tests');
import('carthag.dev.unit.framework.TestSuite');
import('com.solarix.ampoliros.tests.core.AllAmpolirosCoreTests');
import('com.solarix.ampoliros.tests.datatransfer.AllAmpolirosDatatransferTests');
/**
* @package com.solarix.ampoliros.tests
* @author Alex Pagnoni <alex.pagnoni@solarix.it>
* @copyright Copyright 2000-2004 Solarix Srl
* @since 4.0
*/
class AllAmpolirosTests extends Object {
public static function suite() {
require('ampoliros.php');
$suite= new TestSuite('Ampoliros');
$suite -> addTest(AllAmpolirosCoreTests :: suite());
$suite -> addTest(AllAmpolirosDatatransferTests :: suite());
return $suite;
}
}
?>
|
alexpagnoni/ampoliros
|
var/classes/com/solarix/ampoliros/tests/AllAmpolirosTests.php
|
PHP
|
gpl-2.0
| 1,961
|
/*****************************************************************************\
* jobcomp_pgsql.c - Store/Get all information in a postgresql storage.
*
* $Id: storage_pgsql.c 10893 2007-01-29 21:53:48Z da $
*****************************************************************************
* Copyright (C) 2004-2007 The Regents of the University of California.
* Copyright (C) 2008-2009 Lawrence Livermore National Security.
* Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
* Written by Danny Auble <da@llnl.gov>
*
* This file is part of SLURM, a resource management program.
* For details, see <https://computing.llnl.gov/linux/slurm/>.
* Please also read the included file: DISCLAIMER.
*
* SLURM 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.
*
* In addition, as a special exception, the copyright holders give permission
* to link the code of portions of this program with the OpenSSL library under
* certain conditions as described in each individual source file, and
* distribute linked combinations including the two. You must obey the GNU
* General Public License in all respects for all of the code used other than
* OpenSSL. If you modify file(s) with this exception, you may extend this
* exception to your version of the file(s), but you are not obligated to do
* so. If you do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source files in
* the program, then also delete it here.
*
* SLURM 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 SLURM; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
\*****************************************************************************/
#include "pgsql_jobcomp_process.h"
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include "src/common/parse_time.h"
#include "src/common/node_select.h"
#include "src/common/uid.h"
/*
* These variables are required by the generic plugin interface. If they
* are not found in the plugin, the plugin loader will ignore it.
*
* plugin_name - a string giving a human-readable description of the
* plugin. There is no maximum length, but the symbol must refer to
* a valid string.
*
* plugin_type - a string suggesting the type of the plugin or its
* applicability to a particular form of data or method of data handling.
* If the low-level plugin API is used, the contents of this string are
* unimportant and may be anything. SLURM uses the higher-level plugin
* interface which requires this string to be of the form
*
* <application>/<method>
*
* where <application> is a description of the intended application of
* the plugin (e.g., "jobacct" for SLURM job completion logging) and <method>
* is a description of how this plugin satisfies that application. SLURM will
* only load job completion logging plugins if the plugin_type string has a
* prefix of "jobacct/".
*
* plugin_version - an unsigned 32-bit integer giving the version number
* of the plugin. If major and minor revisions are desired, the major
* version number may be multiplied by a suitable magnitude constant such
* as 100 or 1000. Various SLURM versions will likely require a certain
* minimum version for their plugins as the job accounting API
* matures.
*/
const char plugin_name[] = "Job completion POSTGRESQL plugin";
const char plugin_type[] = "jobcomp/pgsql";
const uint32_t plugin_version = 100;
PGconn *jobcomp_pgsql_db = NULL;
char *jobcomp_table = "jobcomp_table";
storage_field_t jobcomp_table_fields[] = {
{ "jobid", "integer not null" },
{ "uid", "smallint not null" },
{ "user_name", "text not null" },
{ "gid", "smallint not null" },
{ "group_name", "text not null" },
{ "name", "text not null" },
{ "state", "smallint not null" },
{ "partition", "text not null" },
{ "timelimit", "text not null" },
{ "starttime", "bigint default 0 not null" },
{ "endtime", "bigint default 0 not null" },
{ "nodelist", "text" },
{ "nodecnt", "integer not null" },
{ "proc_cnt", "integer not null" },
{ "connect_type", "text" },
{ "reboot", "text" },
{ "rotate", "text" },
{ "maxprocs", "integer default 0 not null" },
{ "geometry", "text" },
{ "start", "text" },
{ "blockid", "text" },
{ NULL, NULL}
};
/* Type for error string table entries */
typedef struct {
int xe_number;
char *xe_message;
} slurm_errtab_t;
static slurm_errtab_t slurm_errtab[] = {
{0, "No error"},
{-1, "Unspecified error"}
};
/* A plugin-global errno. */
static int plugin_errno = SLURM_SUCCESS;
/* File descriptor used for logging */
static pthread_mutex_t jobcomp_lock = PTHREAD_MUTEX_INITIALIZER;
static pgsql_db_info_t *_pgsql_jobcomp_create_db_info()
{
pgsql_db_info_t *db_info = xmalloc(sizeof(pgsql_db_info_t));
db_info->port = slurm_get_jobcomp_port();
/* it turns out it is better if using defaults to let postgres
handle them on it's own terms */
if(!db_info->port) {
db_info->port = DEFAULT_PGSQL_PORT;
slurm_set_jobcomp_port(db_info->port);
}
db_info->host = slurm_get_jobcomp_host();
db_info->user = slurm_get_jobcomp_user();
db_info->pass = slurm_get_jobcomp_pass();
return db_info;
}
static int _pgsql_jobcomp_check_tables(char *user)
{
int i = 0, job_found = 0;
PGresult *result = NULL;
char *query = xstrdup_printf("select tablename from pg_tables "
"where tableowner='%s' "
"and tablename !~ '^pg_+'", user);
if(!(result =
pgsql_db_query_ret(jobcomp_pgsql_db, query))) {
xfree(query);
return SLURM_ERROR;
}
xfree(query);
for (i = 0; i < PQntuples(result); i++) {
if(!job_found
&& !strcmp(jobcomp_table, PQgetvalue(result, i, 0)))
job_found = 1;
}
PQclear(result);
if(!job_found)
if(pgsql_db_create_table(jobcomp_pgsql_db, "public", jobcomp_table,
jobcomp_table_fields,
")") == SLURM_ERROR)
return SLURM_ERROR;
return SLURM_SUCCESS;
}
/* get the user name for the give user_id */
static char *_get_user_name(uint32_t user_id)
{
static uint32_t cache_uid = 0;
static char cache_name[32] = "root", *uname;
char *ret_name = NULL;
slurm_mutex_lock(&jobcomp_lock);
if (user_id != cache_uid) {
uname = uid_to_string((uid_t) user_id);
snprintf(cache_name, sizeof(cache_name), "%s", uname);
xfree(uname);
cache_uid = user_id;
}
ret_name = xstrdup(cache_name);
slurm_mutex_unlock(&jobcomp_lock);
return ret_name;
}
/* get the group name for the give group_id */
static char *_get_group_name(uint32_t group_id)
{
static uint32_t cache_gid = 0;
static char cache_name[32] = "root", *gname;
char *ret_name = NULL;
slurm_mutex_lock(&jobcomp_lock);
if (group_id != cache_gid) {
gname = gid_to_string((gid_t) group_id);
snprintf(cache_name, sizeof(cache_name), "%s", gname);
xfree(gname);
cache_gid = group_id;
}
ret_name = xstrdup(cache_name);
slurm_mutex_unlock(&jobcomp_lock);
return ret_name;
}
/*
* Linear search through table of errno values and strings,
* returns NULL on error, string on success.
*/
static char *_lookup_slurm_api_errtab(int errnum)
{
char *res = NULL;
int i;
for (i = 0; i < sizeof(slurm_errtab) / sizeof(slurm_errtab_t); i++) {
if (slurm_errtab[i].xe_number == errnum) {
res = slurm_errtab[i].xe_message;
break;
}
}
return res;
}
/*
* init() is called when the plugin is loaded, before any other functions
* are called. Put global initialization here.
*/
extern int init ( void )
{
static int first = 1;
if(first) {
/* since this can be loaded from many different places
only tell us once. */
verbose("%s loaded", plugin_name);
first = 0;
} else {
debug4("%s loaded", plugin_name);
}
return SLURM_SUCCESS;
}
extern int fini ( void )
{
if (jobcomp_pgsql_db) {
PQfinish(jobcomp_pgsql_db);
jobcomp_pgsql_db = NULL;
}
return SLURM_SUCCESS;
}
extern int slurm_jobcomp_set_location(char *location)
{
pgsql_db_info_t *db_info = _pgsql_jobcomp_create_db_info();
int rc = SLURM_SUCCESS;
char *db_name = NULL;
int i = 0;
if(jobcomp_pgsql_db && PQstatus(jobcomp_pgsql_db) == CONNECTION_OK)
return SLURM_SUCCESS;
if(!location)
db_name = slurm_get_jobcomp_loc();
else {
while(location[i]) {
if(location[i] == '.' || location[i] == '/') {
debug("%s doesn't look like a database "
"name using %s",
location, DEFAULT_JOB_COMP_DB);
break;
}
i++;
}
if(location[i])
db_name = xstrdup(DEFAULT_JOB_COMP_DB);
else
db_name = xstrdup(location);
}
debug2("pgsql_connect() called for db %s", db_name);
pgsql_get_db_connection(&jobcomp_pgsql_db, db_name, db_info);
xfree(db_name);
rc = _pgsql_jobcomp_check_tables(db_info->user);
destroy_pgsql_db_info(db_info);
if(rc == SLURM_SUCCESS)
debug("Jobcomp database init finished");
else
debug("Jobcomp database init failed");
return rc;
}
extern int slurm_jobcomp_log_record(struct job_record *job_ptr)
{
int rc = SLURM_SUCCESS;
char *usr_str = NULL, *grp_str = NULL, lim_str[32];
char *connect_type = NULL, *reboot = NULL, *rotate = NULL,
*geometry = NULL, *start = NULL,
*blockid = NULL;
enum job_states job_state;
char *query = NULL;
uint32_t time_limit, start_time, end_time;
if(!jobcomp_pgsql_db || PQstatus(jobcomp_pgsql_db) != CONNECTION_OK) {
char *loc = slurm_get_jobcomp_loc();
if(slurm_jobcomp_set_location(loc) == SLURM_ERROR) {
xfree(loc);
return SLURM_ERROR;
}
xfree(loc);
}
usr_str = _get_user_name(job_ptr->user_id);
grp_str = _get_group_name(job_ptr->group_id);
if ((job_ptr->time_limit == NO_VAL) && job_ptr->part_ptr)
time_limit = job_ptr->part_ptr->max_time;
else
time_limit = job_ptr->time_limit;
if (time_limit == INFINITE)
strcpy(lim_str, "UNLIMITED");
else {
snprintf(lim_str, sizeof(lim_str), "%lu",
(unsigned long) time_limit);
}
/* Job will typically be COMPLETING when this is called.
* We remove the flags to get the eventual completion state:
* JOB_FAILED, JOB_TIMEOUT, etc. */
if (IS_JOB_RESIZING(job_ptr)) {
job_state = JOB_RESIZING;
if (job_ptr->resize_time)
start_time = job_ptr->resize_time;
else
start_time = job_ptr->start_time;
end_time = time(NULL);
} else {
job_state = job_ptr->job_state & JOB_STATE_BASE;
if (job_ptr->resize_time)
start_time = job_ptr->resize_time;
else if (job_ptr->start_time > job_ptr->end_time) {
/* Job cancelled while pending and
* expected start time is in the future. */
start_time = 0;
} else
start_time = job_ptr->start_time;
end_time = job_ptr->end_time;
}
connect_type = select_g_select_jobinfo_xstrdup(job_ptr->select_jobinfo,
SELECT_PRINT_CONNECTION);
reboot = select_g_select_jobinfo_xstrdup(job_ptr->select_jobinfo,
SELECT_PRINT_REBOOT);
rotate = select_g_select_jobinfo_xstrdup(job_ptr->select_jobinfo,
SELECT_PRINT_ROTATE);
geometry = select_g_select_jobinfo_xstrdup(job_ptr->select_jobinfo,
SELECT_PRINT_GEOMETRY);
start = select_g_select_jobinfo_xstrdup(job_ptr->select_jobinfo,
SELECT_PRINT_START);
#ifdef HAVE_BG
blockid = select_g_select_jobinfo_xstrdup(job_ptr->select_jobinfo,
SELECT_PRINT_BG_ID);
#else
blockid = select_g_select_jobinfo_xstrdup(job_ptr->select_jobinfo,
SELECT_PRINT_RESV_ID);
#endif
query = xstrdup_printf(
"insert into %s (jobid, uid, user_name, gid, group_name, "
"name, state, proc_cnt, partition, timelimit, "
"starttime, endtime, nodecnt",
jobcomp_table);
if(job_ptr->nodes)
xstrcat(query, ", nodelist");
if(connect_type)
xstrcat(query, ", connect_type");
if(reboot)
xstrcat(query, ", reboot");
if(rotate)
xstrcat(query, ", rotate");
if(job_ptr->details && (job_ptr->details->max_cpus != NO_VAL))
xstrcat(query, ", maxprocs");
if(geometry)
xstrcat(query, ", geometry");
if(start)
xstrcat(query, ", start");
if(blockid)
xstrcat(query, ", blockid");
xstrfmtcat(query, ") values (%u, %u, '%s', %u, '%s', \"%s\", %d, %u, "
"'%s', \"%s\", %u, %u, %u",
job_ptr->job_id, job_ptr->user_id, usr_str,
job_ptr->group_id, grp_str, job_ptr->name,
job_state, job_ptr->total_cpus, job_ptr->partition, lim_str,
start_time, end_time, job_ptr->node_cnt);
if(job_ptr->nodes)
xstrfmtcat(query, ", '%s'", job_ptr->nodes);
if(connect_type) {
xstrfmtcat(query, ", '%s'", connect_type);
xfree(connect_type);
}
if(reboot) {
xstrfmtcat(query, ", '%s'", reboot);
xfree(reboot);
}
if(rotate) {
xstrfmtcat(query, ", '%s'", rotate);
xfree(rotate);
}
if(job_ptr->details && (job_ptr->details->max_cpus != NO_VAL))
xstrfmtcat(query, ", '%u'", job_ptr->details->max_cpus);
if(geometry) {
xstrfmtcat(query, ", '%s'", geometry);
xfree(geometry);
}
if(start) {
xstrfmtcat(query, ", '%s'", start);
xfree(start);
}
if(blockid) {
xstrfmtcat(query, ", '%s'", blockid);
xfree(blockid);
}
xstrcat(query, ")");
//info("here is the query %s", query);
rc = pgsql_db_query(jobcomp_pgsql_db, query);
xfree(usr_str);
return rc;
}
extern int slurm_jobcomp_get_errno()
{
return plugin_errno;
}
extern char *slurm_jobcomp_strerror(int errnum)
{
char *res = _lookup_slurm_api_errtab(errnum);
return (res ? res : strerror(errnum));
}
/*
* get info from the storage
* in/out job_list List of job_rec_t *
* note List needs to be freed when called
*/
extern List slurm_jobcomp_get_jobs(slurmdb_job_cond_t *job_cond)
{
List job_list = NULL;
if(!jobcomp_pgsql_db || PQstatus(jobcomp_pgsql_db) != CONNECTION_OK) {
char *loc = slurm_get_jobcomp_loc();
if(slurm_jobcomp_set_location(loc) == SLURM_ERROR) {
xfree(loc);
return NULL;
}
xfree(loc);
}
job_list = pgsql_jobcomp_process_get_jobs(job_cond);
return job_list;
}
/*
* expire old info from the storage
*/
extern int slurm_jobcomp_archive(slurmdb_archive_cond_t *arch_cond)
{
if(!jobcomp_pgsql_db || PQstatus(jobcomp_pgsql_db) != CONNECTION_OK) {
char *loc = slurm_get_jobcomp_loc();
if(slurm_jobcomp_set_location(loc) == SLURM_ERROR) {
xfree(loc);
return SLURM_ERROR;
}
xfree(loc);
}
return pgsql_jobcomp_process_archive(arch_cond);
}
|
grondo/slurm
|
src/plugins/jobcomp/pgsql/jobcomp_pgsql.c
|
C
|
gpl-2.0
| 14,583
|
/*
* CAN bus driver for Microchip 251x CAN Controller with SPI Interface
*
* MCP2510 support and bug fixes by Christian Pellegrin
* <chripell@evolware.org>
*
* Copyright 2009 Christian Pellegrin EVOL S.r.l.
*
* Copyright 2007 Raymarine UK, Ltd. All Rights Reserved.
* Written under contract by:
* Chris Elston, Katalix Systems, Ltd.
*
* Based on Microchip MCP251x CAN controller driver written by
* David Vrabel, Copyright 2006 Arcom Control Systems Ltd.
*
* Based on CAN bus driver for the CCAN controller written by
* - Sascha Hauer, Marc Kleine-Budde, Pengutronix
* - Simon Kallweit, intefo AG
* Copyright 2007
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the version 2 of the GNU General Public License
* 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
*
*
*
* Your platform definition file should specify something like:
*
* static struct mcp251x_platform_data mcp251x_info = {
* .oscillator_frequency = 8000000,
* .board_specific_setup = &mcp251x_setup,
* .power_enable = mcp251x_power_enable,
* .transceiver_enable = NULL,
* };
*
* static struct spi_board_info spi_board_info[] = {
* {
* .modalias = "mcp2510",
* // or "mcp2515" depending on your controller
* .platform_data = &mcp251x_info,
* .irq = IRQ_EINT13,
* .max_speed_hz = 2*1000*1000,
* .chip_select = 2,
* },
* };
*
* Please see mcp251x.h for a description of the fields in
* struct mcp251x_platform_data.
*
*/
#include <linux/can/core.h>
#include <linux/can/dev.h>
#include <linux/can/platform/mcp251x.h>
#include <linux/completion.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/freezer.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/spi/spi.h>
#include <linux/uaccess.h>
/* SPI interface instruction set */
#define INSTRUCTION_WRITE 0x02
#define INSTRUCTION_READ 0x03
#define INSTRUCTION_BIT_MODIFY 0x05
#define INSTRUCTION_LOAD_TXB(n) (0x40 + 2 * (n))
#define INSTRUCTION_READ_RXB(n) (((n) == 0) ? 0x90 : 0x94)
#define INSTRUCTION_RESET 0xC0
#define RTS_TXB0 0x01
#define RTS_TXB1 0x02
#define RTS_TXB2 0x04
#define INSTRUCTION_RTS(n) (0x80 | ((n) & 0x07))
/* MPC251x registers */
#define CANSTAT 0x0e
#define CANCTRL 0x0f
# define CANCTRL_REQOP_MASK 0xe0
# define CANCTRL_REQOP_CONF 0x80
# define CANCTRL_REQOP_LISTEN_ONLY 0x60
# define CANCTRL_REQOP_LOOPBACK 0x40
# define CANCTRL_REQOP_SLEEP 0x20
# define CANCTRL_REQOP_NORMAL 0x00
# define CANCTRL_ABAT 0x10
# define CANCTRL_OSM 0x08
# define CANCTRL_CLKEN 0x04
#define TEC 0x1c
#define REC 0x1d
#define CNF1 0x2a
# define CNF1_SJW_SHIFT 6
#define CNF2 0x29
# define CNF2_BTLMODE 0x80
# define CNF2_SAM 0x40
# define CNF2_PS1_SHIFT 3
#define CNF3 0x28
# define CNF3_SOF 0x08
# define CNF3_WAKFIL 0x04
# define CNF3_PHSEG2_MASK 0x07
#define CANINTE 0x2b
# define CANINTE_MERRE 0x80
# define CANINTE_WAKIE 0x40
# define CANINTE_ERRIE 0x20
# define CANINTE_TX2IE 0x10
# define CANINTE_TX1IE 0x08
# define CANINTE_TX0IE 0x04
# define CANINTE_RX1IE 0x02
# define CANINTE_RX0IE 0x01
#define CANINTF 0x2c
# define CANINTF_MERRF 0x80
# define CANINTF_WAKIF 0x40
# define CANINTF_ERRIF 0x20
# define CANINTF_TX2IF 0x10
# define CANINTF_TX1IF 0x08
# define CANINTF_TX0IF 0x04
# define CANINTF_RX1IF 0x02
# define CANINTF_RX0IF 0x01
# define CANINTF_RX (CANINTF_RX0IF | CANINTF_RX1IF)
# define CANINTF_TX (CANINTF_TX2IF | CANINTF_TX1IF | CANINTF_TX0IF)
# define CANINTF_ERR (CANINTF_ERRIF)
#define EFLG 0x2d
# define EFLG_EWARN 0x01
# define EFLG_RXWAR 0x02
# define EFLG_TXWAR 0x04
# define EFLG_RXEP 0x08
# define EFLG_TXEP 0x10
# define EFLG_TXBO 0x20
# define EFLG_RX0OVR 0x40
# define EFLG_RX1OVR 0x80
#define TXBCTRL(n) (((n) * 0x10) + 0x30 + TXBCTRL_OFF)
# define TXBCTRL_ABTF 0x40
# define TXBCTRL_MLOA 0x20
# define TXBCTRL_TXERR 0x10
# define TXBCTRL_TXREQ 0x08
#define TXBSIDH(n) (((n) * 0x10) + 0x30 + TXBSIDH_OFF)
# define SIDH_SHIFT 3
#define TXBSIDL(n) (((n) * 0x10) + 0x30 + TXBSIDL_OFF)
# define SIDL_SID_MASK 7
# define SIDL_SID_SHIFT 5
# define SIDL_EXIDE_SHIFT 3
# define SIDL_EID_SHIFT 16
# define SIDL_EID_MASK 3
#define TXBEID8(n) (((n) * 0x10) + 0x30 + TXBEID8_OFF)
#define TXBEID0(n) (((n) * 0x10) + 0x30 + TXBEID0_OFF)
#define TXBDLC(n) (((n) * 0x10) + 0x30 + TXBDLC_OFF)
# define DLC_RTR_SHIFT 6
#define TXBCTRL_OFF 0
#define TXBSIDH_OFF 1
#define TXBSIDL_OFF 2
#define TXBEID8_OFF 3
#define TXBEID0_OFF 4
#define TXBDLC_OFF 5
#define TXBDAT_OFF 6
#define RXBCTRL(n) (((n) * 0x10) + 0x60 + RXBCTRL_OFF)
# define RXBCTRL_BUKT 0x04
# define RXBCTRL_RXM0 0x20
# define RXBCTRL_RXM1 0x40
#define RXBSIDH(n) (((n) * 0x10) + 0x60 + RXBSIDH_OFF)
# define RXBSIDH_SHIFT 3
#define RXBSIDL(n) (((n) * 0x10) + 0x60 + RXBSIDL_OFF)
# define RXBSIDL_IDE 0x08
# define RXBSIDL_SRR 0x10
# define RXBSIDL_EID 3
# define RXBSIDL_SHIFT 5
#define RXBEID8(n) (((n) * 0x10) + 0x60 + RXBEID8_OFF)
#define RXBEID0(n) (((n) * 0x10) + 0x60 + RXBEID0_OFF)
#define RXBDLC(n) (((n) * 0x10) + 0x60 + RXBDLC_OFF)
# define RXBDLC_LEN_MASK 0x0f
# define RXBDLC_RTR 0x40
#define RXBCTRL_OFF 0
#define RXBSIDH_OFF 1
#define RXBSIDL_OFF 2
#define RXBEID8_OFF 3
#define RXBEID0_OFF 4
#define RXBDLC_OFF 5
#define RXBDAT_OFF 6
#define RXFSIDH(n) ((n) * 4)
#define RXFSIDL(n) ((n) * 4 + 1)
#define RXFEID8(n) ((n) * 4 + 2)
#define RXFEID0(n) ((n) * 4 + 3)
#define RXMSIDH(n) ((n) * 4 + 0x20)
#define RXMSIDL(n) ((n) * 4 + 0x21)
#define RXMEID8(n) ((n) * 4 + 0x22)
#define RXMEID0(n) ((n) * 4 + 0x23)
#define GET_BYTE(val, byte) \
(((val) >> ((byte) * 8)) & 0xff)
#define SET_BYTE(val, byte) \
(((val) & 0xff) << ((byte) * 8))
/*
* Buffer size required for the largest SPI transfer (i.e., reading a
* frame)
*/
#define CAN_FRAME_MAX_DATA_LEN 8
#define SPI_TRANSFER_BUF_LEN (6 + CAN_FRAME_MAX_DATA_LEN)
#define CAN_FRAME_MAX_BITS 128
#define TX_ECHO_SKB_MAX 1
#define DEVICE_NAME "mcp251x"
static int mcp251x_enable_dma; /* Enable SPI DMA. Default: 0 (Off) */
module_param(mcp251x_enable_dma, int, S_IRUGO);
MODULE_PARM_DESC(mcp251x_enable_dma, "Enable SPI DMA. Default: 0 (Off)");
static struct can_bittiming_const mcp251x_bittiming_const = {
.name = DEVICE_NAME,
.tseg1_min = 3,
.tseg1_max = 16,
.tseg2_min = 2,
.tseg2_max = 8,
.sjw_max = 4,
.brp_min = 1,
.brp_max = 64,
.brp_inc = 1,
};
enum mcp251x_model {
CAN_MCP251X_MCP2510 = 0x2510,
CAN_MCP251X_MCP2515 = 0x2515,
};
struct mcp251x_priv {
struct can_priv can;
struct net_device *net;
struct spi_device *spi;
enum mcp251x_model model;
struct mutex mcp_lock; /* SPI device lock */
u8 *spi_tx_buf;
u8 *spi_rx_buf;
dma_addr_t spi_tx_dma;
dma_addr_t spi_rx_dma;
struct sk_buff *tx_skb;
int tx_len;
struct workqueue_struct *wq;
struct work_struct tx_work;
struct work_struct restart_work;
int force_quit;
int after_suspend;
#define AFTER_SUSPEND_UP 1
#define AFTER_SUSPEND_DOWN 2
#define AFTER_SUSPEND_POWER 4
#define AFTER_SUSPEND_RESTART 8
int restart_tx;
};
#define MCP251X_IS(_model) \
static inline int mcp251x_is_##_model(struct spi_device *spi) \
{ \
struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev); \
return priv->model == CAN_MCP251X_MCP##_model; \
}
MCP251X_IS(2510);
MCP251X_IS(2515);
static void mcp251x_clean(struct net_device *net)
{
struct mcp251x_priv *priv = netdev_priv(net);
if (priv->tx_skb || priv->tx_len)
net->stats.tx_errors++;
if (priv->tx_skb)
dev_kfree_skb(priv->tx_skb);
if (priv->tx_len)
can_free_echo_skb(priv->net, 0);
priv->tx_skb = NULL;
priv->tx_len = 0;
}
/*
* Note about handling of error return of mcp251x_spi_trans: accessing
* registers via SPI is not really different conceptually than using
* normal I/O assembly instructions, although it's much more
* complicated from a practical POV. So it's not advisable to always
* check the return value of this function. Imagine that every
* read{b,l}, write{b,l} and friends would be bracketed in "if ( < 0)
* error();", it would be a great mess (well there are some situation
* when exception handling C++ like could be useful after all). So we
* just check that transfers are OK at the beginning of our
* conversation with the chip and to avoid doing really nasty things
* (like injecting bogus packets in the network stack).
*/
static int mcp251x_spi_trans(struct spi_device *spi, int len)
{
struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev);
struct spi_transfer t = {
.tx_buf = priv->spi_tx_buf,
.rx_buf = priv->spi_rx_buf,
.len = len,
.cs_change = 0,
};
struct spi_message m;
int ret;
spi_message_init(&m);
if (mcp251x_enable_dma) {
t.tx_dma = priv->spi_tx_dma;
t.rx_dma = priv->spi_rx_dma;
m.is_dma_mapped = 1;
}
spi_message_add_tail(&t, &m);
ret = spi_sync(spi, &m);
if (ret)
dev_err(&spi->dev, "spi transfer failed: ret = %d\n", ret);
return ret;
}
static u8 mcp251x_read_reg(struct spi_device *spi, uint8_t reg)
{
struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev);
u8 val = 0;
priv->spi_tx_buf[0] = INSTRUCTION_READ;
priv->spi_tx_buf[1] = reg;
mcp251x_spi_trans(spi, 3);
val = priv->spi_rx_buf[2];
return val;
}
static void mcp251x_read_2regs(struct spi_device *spi, uint8_t reg,
uint8_t *v1, uint8_t *v2)
{
struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev);
priv->spi_tx_buf[0] = INSTRUCTION_READ;
priv->spi_tx_buf[1] = reg;
mcp251x_spi_trans(spi, 4);
*v1 = priv->spi_rx_buf[2];
*v2 = priv->spi_rx_buf[3];
}
static void mcp251x_write_reg(struct spi_device *spi, u8 reg, uint8_t val)
{
struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev);
priv->spi_tx_buf[0] = INSTRUCTION_WRITE;
priv->spi_tx_buf[1] = reg;
priv->spi_tx_buf[2] = val;
mcp251x_spi_trans(spi, 3);
}
static void mcp251x_write_bits(struct spi_device *spi, u8 reg,
u8 mask, uint8_t val)
{
struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev);
priv->spi_tx_buf[0] = INSTRUCTION_BIT_MODIFY;
priv->spi_tx_buf[1] = reg;
priv->spi_tx_buf[2] = mask;
priv->spi_tx_buf[3] = val;
mcp251x_spi_trans(spi, 4);
}
static void mcp251x_hw_tx_frame(struct spi_device *spi, u8 *buf,
int len, int tx_buf_idx)
{
struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev);
if (mcp251x_is_2510(spi)) {
int i;
for (i = 1; i < TXBDAT_OFF + len; i++)
mcp251x_write_reg(spi, TXBCTRL(tx_buf_idx) + i,
buf[i]);
} else {
memcpy(priv->spi_tx_buf, buf, TXBDAT_OFF + len);
mcp251x_spi_trans(spi, TXBDAT_OFF + len);
}
}
static void mcp251x_hw_tx(struct spi_device *spi, struct can_frame *frame,
int tx_buf_idx)
{
struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev);
u32 sid, eid, exide, rtr;
u8 buf[SPI_TRANSFER_BUF_LEN];
exide = (frame->can_id & CAN_EFF_FLAG) ? 1 : 0; /* Extended ID Enable */
if (exide)
sid = (frame->can_id & CAN_EFF_MASK) >> 18;
else
sid = frame->can_id & CAN_SFF_MASK; /* Standard ID */
eid = frame->can_id & CAN_EFF_MASK; /* Extended ID */
rtr = (frame->can_id & CAN_RTR_FLAG) ? 1 : 0; /* Remote transmission */
buf[TXBCTRL_OFF] = INSTRUCTION_LOAD_TXB(tx_buf_idx);
buf[TXBSIDH_OFF] = sid >> SIDH_SHIFT;
buf[TXBSIDL_OFF] = ((sid & SIDL_SID_MASK) << SIDL_SID_SHIFT) |
(exide << SIDL_EXIDE_SHIFT) |
((eid >> SIDL_EID_SHIFT) & SIDL_EID_MASK);
buf[TXBEID8_OFF] = GET_BYTE(eid, 1);
buf[TXBEID0_OFF] = GET_BYTE(eid, 0);
buf[TXBDLC_OFF] = (rtr << DLC_RTR_SHIFT) | frame->can_dlc;
memcpy(buf + TXBDAT_OFF, frame->data, frame->can_dlc);
mcp251x_hw_tx_frame(spi, buf, frame->can_dlc, tx_buf_idx);
/* use INSTRUCTION_RTS, to avoid "repeated frame problem" */
priv->spi_tx_buf[0] = INSTRUCTION_RTS(1 << tx_buf_idx);
mcp251x_spi_trans(priv->spi, 1);
}
static void mcp251x_hw_rx_frame(struct spi_device *spi, u8 *buf,
int buf_idx)
{
struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev);
if (mcp251x_is_2510(spi)) {
int i, len;
for (i = 1; i < RXBDAT_OFF; i++)
buf[i] = mcp251x_read_reg(spi, RXBCTRL(buf_idx) + i);
len = get_can_dlc(buf[RXBDLC_OFF] & RXBDLC_LEN_MASK);
for (; i < (RXBDAT_OFF + len); i++)
buf[i] = mcp251x_read_reg(spi, RXBCTRL(buf_idx) + i);
} else {
priv->spi_tx_buf[RXBCTRL_OFF] = INSTRUCTION_READ_RXB(buf_idx);
mcp251x_spi_trans(spi, SPI_TRANSFER_BUF_LEN);
memcpy(buf, priv->spi_rx_buf, SPI_TRANSFER_BUF_LEN);
}
}
static void mcp251x_hw_rx(struct spi_device *spi, int buf_idx)
{
struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev);
struct sk_buff *skb;
struct can_frame *frame;
u8 buf[SPI_TRANSFER_BUF_LEN];
skb = alloc_can_skb(priv->net, &frame);
if (!skb) {
dev_err(&spi->dev, "cannot allocate RX skb\n");
priv->net->stats.rx_dropped++;
return;
}
mcp251x_hw_rx_frame(spi, buf, buf_idx);
if (buf[RXBSIDL_OFF] & RXBSIDL_IDE) {
/* Extended ID format */
frame->can_id = CAN_EFF_FLAG;
frame->can_id |=
/* Extended ID part */
SET_BYTE(buf[RXBSIDL_OFF] & RXBSIDL_EID, 2) |
SET_BYTE(buf[RXBEID8_OFF], 1) |
SET_BYTE(buf[RXBEID0_OFF], 0) |
/* Standard ID part */
(((buf[RXBSIDH_OFF] << RXBSIDH_SHIFT) |
(buf[RXBSIDL_OFF] >> RXBSIDL_SHIFT)) << 18);
/* Remote transmission request */
if (buf[RXBDLC_OFF] & RXBDLC_RTR)
frame->can_id |= CAN_RTR_FLAG;
} else {
/* Standard ID format */
frame->can_id =
(buf[RXBSIDH_OFF] << RXBSIDH_SHIFT) |
(buf[RXBSIDL_OFF] >> RXBSIDL_SHIFT);
if (buf[RXBSIDL_OFF] & RXBSIDL_SRR)
frame->can_id |= CAN_RTR_FLAG;
}
/* Data length */
frame->can_dlc = get_can_dlc(buf[RXBDLC_OFF] & RXBDLC_LEN_MASK);
memcpy(frame->data, buf + RXBDAT_OFF, frame->can_dlc);
priv->net->stats.rx_packets++;
priv->net->stats.rx_bytes += frame->can_dlc;
netif_rx_ni(skb);
}
static void mcp251x_hw_sleep(struct spi_device *spi)
{
// mcp251x_write_reg(spi, CANCTRL, CANCTRL_REQOP_SLEEP);
}
static netdev_tx_t mcp251x_hard_start_xmit(struct sk_buff *skb,
struct net_device *net)
{
struct mcp251x_priv *priv = netdev_priv(net);
struct spi_device *spi = priv->spi;
if (priv->tx_skb || priv->tx_len) {
dev_warn(&spi->dev, "hard_xmit called while tx busy\n");
return NETDEV_TX_BUSY;
}
if (can_dropped_invalid_skb(net, skb))
return NETDEV_TX_OK;
netif_stop_queue(net);
priv->tx_skb = skb;
queue_work(priv->wq, &priv->tx_work);
return NETDEV_TX_OK;
}
static int mcp251x_do_set_mode(struct net_device *net, enum can_mode mode)
{
struct mcp251x_priv *priv = netdev_priv(net);
switch (mode) {
case CAN_MODE_START:
mcp251x_clean(net);
/* We have to delay work since SPI I/O may sleep */
priv->can.state = CAN_STATE_ERROR_ACTIVE;
priv->restart_tx = 1;
if (priv->can.restart_ms == 0)
priv->after_suspend = AFTER_SUSPEND_RESTART;
queue_work(priv->wq, &priv->restart_work);
break;
default:
return -EOPNOTSUPP;
}
return 0;
}
static int mcp251x_set_normal_mode(struct spi_device *spi)
{
struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev);
unsigned long timeout;
/* Enable interrupts */
mcp251x_write_reg(spi, CANINTE,
CANINTE_ERRIE | CANINTE_TX2IE | CANINTE_TX1IE |
CANINTE_TX0IE | CANINTE_RX1IE | CANINTE_RX0IE);
if (priv->can.ctrlmode & CAN_CTRLMODE_LOOPBACK) {
/* Put device into loopback mode */
mcp251x_write_reg(spi, CANCTRL, CANCTRL_REQOP_LOOPBACK | CANCTRL_CLKEN);
} else if (priv->can.ctrlmode & CAN_CTRLMODE_LISTENONLY) {
/* Put device into listen-only mode */
mcp251x_write_reg(spi, CANCTRL, CANCTRL_REQOP_LISTEN_ONLY | CANCTRL_CLKEN);
} else {
/* Put device into normal mode */
mcp251x_write_reg(spi, CANCTRL, CANCTRL_REQOP_NORMAL | CANCTRL_CLKEN);
netdev_info(priv->net, "CANCTRL: 0x%02x\n",
mcp251x_read_reg(spi, CANCTRL));
/* Wait for the device to enter normal mode */
timeout = jiffies + HZ;
while (mcp251x_read_reg(spi, CANSTAT) & CANCTRL_REQOP_MASK) {
schedule();
if (time_after(jiffies, timeout)) {
dev_err(&spi->dev, "MCP251x didn't"
" enter in normal mode\n");
return -EBUSY;
}
}
}
priv->can.state = CAN_STATE_ERROR_ACTIVE;
return 0;
}
static int mcp251x_do_set_bittiming(struct net_device *net)
{
struct mcp251x_priv *priv = netdev_priv(net);
struct can_bittiming *bt = &priv->can.bittiming;
struct spi_device *spi = priv->spi;
mcp251x_write_reg(spi, CNF1, ((bt->sjw - 1) << CNF1_SJW_SHIFT) |
(bt->brp - 1));
mcp251x_write_reg(spi, CNF2, CNF2_BTLMODE |
(priv->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES ?
CNF2_SAM : 0) |
((bt->phase_seg1 - 1) << CNF2_PS1_SHIFT) |
(bt->prop_seg - 1));
mcp251x_write_bits(spi, CNF3, CNF3_PHSEG2_MASK,
(bt->phase_seg2 - 1));
netdev_info(net, "CNF: 0x%02x 0x%02x 0x%02x\n",
mcp251x_read_reg(spi, CNF1),
mcp251x_read_reg(spi, CNF2),
mcp251x_read_reg(spi, CNF3));
netdev_info(net, "CANCTRL: 0x%02x\n",
mcp251x_read_reg(spi, CANCTRL));
return 0;
}
static int mcp251x_setup(struct net_device *net, struct mcp251x_priv *priv,
struct spi_device *spi)
{
mcp251x_do_set_bittiming(net);
mcp251x_write_reg(spi, RXBCTRL(0),
RXBCTRL_BUKT | RXBCTRL_RXM0 | RXBCTRL_RXM1);
mcp251x_write_reg(spi, RXBCTRL(1),
RXBCTRL_RXM0 | RXBCTRL_RXM1);
return 0;
}
static int mcp251x_hw_reset(struct spi_device *spi)
{
struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev);
int ret;
unsigned long timeout;
priv->spi_tx_buf[0] = INSTRUCTION_RESET;
ret = spi_write(spi, priv->spi_tx_buf, 1);
if (ret) {
dev_err(&spi->dev, "reset failed: ret = %d\n", ret);
return -EIO;
}
/* Wait for reset to finish */
timeout = jiffies + HZ;
mdelay(10);
while ((mcp251x_read_reg(spi, CANSTAT) & CANCTRL_REQOP_MASK)
!= CANCTRL_REQOP_CONF) {
schedule();
if (time_after(jiffies, timeout)) {
dev_err(&spi->dev, "MCP251x didn't"
" enter in conf mode after reset\n");
return -EBUSY;
}
}
return 0;
}
static int mcp251x_hw_probe(struct spi_device *spi)
{
int st1, st2;
mcp251x_hw_reset(spi);
/*
* Please note that these are "magic values" based on after
* reset defaults taken from data sheet which allows us to see
* if we really have a chip on the bus (we avoid common all
* zeroes or all ones situations)
*/
st1 = mcp251x_read_reg(spi, CANSTAT) & 0xEE;
st2 = mcp251x_read_reg(spi, CANCTRL) & 0x17;
dev_dbg(&spi->dev, "CANSTAT 0x%02x CANCTRL 0x%02x\n", st1, st2);
/* Check for power up default values */
return (st1 == 0x80 && st2 == 0x07) ? 1 : 0;
}
static void mcp251x_open_clean(struct net_device *net)
{
struct mcp251x_priv *priv = netdev_priv(net);
struct spi_device *spi = priv->spi;
struct mcp251x_platform_data *pdata = spi->dev.platform_data;
free_irq(spi->irq, priv);
mcp251x_hw_sleep(spi);
if (pdata->transceiver_enable)
pdata->transceiver_enable(0);
close_candev(net);
}
static int mcp251x_stop(struct net_device *net)
{
struct mcp251x_priv *priv = netdev_priv(net);
struct spi_device *spi = priv->spi;
struct mcp251x_platform_data *pdata = spi->dev.platform_data;
close_candev(net);
priv->force_quit = 1;
free_irq(spi->irq, priv);
destroy_workqueue(priv->wq);
priv->wq = NULL;
mutex_lock(&priv->mcp_lock);
/* Disable and clear pending interrupts */
mcp251x_write_reg(spi, CANINTE, 0x00);
mcp251x_write_reg(spi, CANINTF, 0x00);
mcp251x_write_reg(spi, TXBCTRL(0), 0);
mcp251x_clean(net);
mcp251x_hw_sleep(spi);
if (pdata->transceiver_enable)
pdata->transceiver_enable(0);
priv->can.state = CAN_STATE_STOPPED;
mutex_unlock(&priv->mcp_lock);
return 0;
}
static void mcp251x_error_skb(struct net_device *net, int can_id, int data1)
{
struct sk_buff *skb;
struct can_frame *frame;
skb = alloc_can_err_skb(net, &frame);
if (skb) {
frame->can_id |= can_id;
frame->data[1] = data1;
netif_rx_ni(skb);
} else {
dev_err(&net->dev,
"cannot allocate error skb\n");
}
}
static void mcp251x_tx_work_handler(struct work_struct *ws)
{
struct mcp251x_priv *priv = container_of(ws, struct mcp251x_priv,
tx_work);
struct spi_device *spi = priv->spi;
struct net_device *net = priv->net;
struct can_frame *frame;
mutex_lock(&priv->mcp_lock);
if (priv->tx_skb) {
if (priv->can.state == CAN_STATE_BUS_OFF) {
mcp251x_clean(net);
} else {
frame = (struct can_frame *)priv->tx_skb->data;
if (frame->can_dlc > CAN_FRAME_MAX_DATA_LEN)
frame->can_dlc = CAN_FRAME_MAX_DATA_LEN;
mcp251x_hw_tx(spi, frame, 0);
priv->tx_len = 1 + frame->can_dlc;
can_put_echo_skb(priv->tx_skb, net, 0);
priv->tx_skb = NULL;
}
}
mutex_unlock(&priv->mcp_lock);
}
static void mcp251x_restart_work_handler(struct work_struct *ws)
{
struct mcp251x_priv *priv = container_of(ws, struct mcp251x_priv,
restart_work);
struct spi_device *spi = priv->spi;
struct net_device *net = priv->net;
mutex_lock(&priv->mcp_lock);
if (priv->after_suspend) {
mdelay(10);
mcp251x_hw_reset(spi);
mcp251x_setup(net, priv, spi);
if (priv->after_suspend & AFTER_SUSPEND_RESTART) {
mcp251x_set_normal_mode(spi);
} else if (priv->after_suspend & AFTER_SUSPEND_UP) {
netif_device_attach(net);
mcp251x_clean(net);
mcp251x_set_normal_mode(spi);
netif_wake_queue(net);
} else {
mcp251x_hw_sleep(spi);
}
priv->after_suspend = 0;
priv->force_quit = 0;
}
if (priv->restart_tx) {
priv->restart_tx = 0;
mcp251x_write_reg(spi, TXBCTRL(0), 0);
mcp251x_clean(net);
netif_wake_queue(net);
mcp251x_error_skb(net, CAN_ERR_RESTARTED, 0);
}
mutex_unlock(&priv->mcp_lock);
}
static irqreturn_t mcp251x_can_ist(int irq, void *dev_id)
{
struct mcp251x_priv *priv = dev_id;
struct spi_device *spi = priv->spi;
struct net_device *net = priv->net;
mutex_lock(&priv->mcp_lock);
while (!priv->force_quit) {
enum can_state new_state;
u8 intf, eflag;
u8 clear_intf = 0;
int can_id = 0, data1 = 0;
mcp251x_read_2regs(spi, CANINTF, &intf, &eflag);
/* mask out flags we don't care about */
intf &= CANINTF_RX | CANINTF_TX | CANINTF_ERR;
/* receive buffer 0 */
if (intf & CANINTF_RX0IF) {
mcp251x_hw_rx(spi, 0);
/*
* Free one buffer ASAP
* (The MCP2515 does this automatically.)
*/
if (mcp251x_is_2510(spi))
mcp251x_write_bits(spi, CANINTF, CANINTF_RX0IF, 0x00);
}
/* receive buffer 1 */
if (intf & CANINTF_RX1IF) {
mcp251x_hw_rx(spi, 1);
/* the MCP2515 does this automatically */
if (mcp251x_is_2510(spi))
clear_intf |= CANINTF_RX1IF;
}
/* any error or tx interrupt we need to clear? */
if (intf & (CANINTF_ERR | CANINTF_TX))
clear_intf |= intf & (CANINTF_ERR | CANINTF_TX);
if (clear_intf)
mcp251x_write_bits(spi, CANINTF, clear_intf, 0x00);
if (eflag)
mcp251x_write_bits(spi, EFLG, eflag, 0x00);
/* Update can state */
if (eflag & EFLG_TXBO) {
netdev_err(net, "err: bus off\n");
new_state = CAN_STATE_BUS_OFF;
can_id |= CAN_ERR_BUSOFF;
} else if (eflag & EFLG_TXEP) {
netdev_err(net, "err: txep\n");
new_state = CAN_STATE_ERROR_PASSIVE;
can_id |= CAN_ERR_CRTL;
data1 |= CAN_ERR_CRTL_TX_PASSIVE;
} else if (eflag & EFLG_RXEP) {
netdev_err(net, "err: rxep\n");
new_state = CAN_STATE_ERROR_PASSIVE;
can_id |= CAN_ERR_CRTL;
data1 |= CAN_ERR_CRTL_RX_PASSIVE;
} else if (eflag & EFLG_TXWAR) {
netdev_err(net, "err: txwar\n");
new_state = CAN_STATE_ERROR_WARNING;
can_id |= CAN_ERR_CRTL;
data1 |= CAN_ERR_CRTL_TX_WARNING;
} else if (eflag & EFLG_RXWAR) {
netdev_err(net, "err: rxwar\n");
new_state = CAN_STATE_ERROR_WARNING;
can_id |= CAN_ERR_CRTL;
data1 |= CAN_ERR_CRTL_RX_WARNING;
} else {
new_state = CAN_STATE_ERROR_ACTIVE;
}
/* Update can state statistics */
switch (priv->can.state) {
case CAN_STATE_ERROR_ACTIVE:
if (new_state >= CAN_STATE_ERROR_WARNING &&
new_state <= CAN_STATE_BUS_OFF)
priv->can.can_stats.error_warning++;
case CAN_STATE_ERROR_WARNING: /* fallthrough */
if (new_state >= CAN_STATE_ERROR_PASSIVE &&
new_state <= CAN_STATE_BUS_OFF)
priv->can.can_stats.error_passive++;
break;
default:
break;
}
priv->can.state = new_state;
if (intf & CANINTF_ERRIF) {
/* Handle overflow counters */
if (eflag & (EFLG_RX0OVR | EFLG_RX1OVR)) {
if (eflag & EFLG_RX0OVR) {
net->stats.rx_over_errors++;
net->stats.rx_errors++;
}
if (eflag & EFLG_RX1OVR) {
net->stats.rx_over_errors++;
net->stats.rx_errors++;
}
can_id |= CAN_ERR_CRTL;
data1 |= CAN_ERR_CRTL_RX_OVERFLOW;
}
mcp251x_error_skb(net, can_id, data1);
}
if (priv->can.state == CAN_STATE_BUS_OFF) {
if (priv->can.restart_ms == 0) {
priv->force_quit = 1;
can_bus_off(net);
mcp251x_hw_sleep(spi);
break;
}
}
if (intf == 0)
break;
if (intf & CANINTF_TX) {
net->stats.tx_packets++;
net->stats.tx_bytes += priv->tx_len - 1;
if (priv->tx_len) {
can_get_echo_skb(net, 0);
priv->tx_len = 0;
}
netif_wake_queue(net);
}
}
mutex_unlock(&priv->mcp_lock);
return IRQ_HANDLED;
}
static int mcp251x_open(struct net_device *net)
{
struct mcp251x_priv *priv = netdev_priv(net);
struct spi_device *spi = priv->spi;
struct mcp251x_platform_data *pdata = spi->dev.platform_data;
int ret;
ret = open_candev(net);
if (ret) {
netdev_err(net, "failed to open can device\n");
return ret;
}
mutex_lock(&priv->mcp_lock);
if (pdata->transceiver_enable)
pdata->transceiver_enable(1);
priv->force_quit = 0;
priv->tx_skb = NULL;
priv->tx_len = 0;
ret = request_threaded_irq(spi->irq, NULL, mcp251x_can_ist,
pdata->irq_flags ? pdata->irq_flags : IRQF_TRIGGER_FALLING,
DEVICE_NAME, priv);
if (ret) {
netdev_err(net, "failed to acquire irq %d\n", spi->irq);
if (pdata->transceiver_enable)
pdata->transceiver_enable(0);
close_candev(net);
goto open_unlock;
}
priv->wq = create_freezable_workqueue("mcp251x_wq");
INIT_WORK(&priv->tx_work, mcp251x_tx_work_handler);
INIT_WORK(&priv->restart_work, mcp251x_restart_work_handler);
ret = mcp251x_hw_reset(spi);
if (ret) {
mcp251x_open_clean(net);
goto open_unlock;
}
ret = mcp251x_setup(net, priv, spi);
if (ret) {
mcp251x_open_clean(net);
goto open_unlock;
}
ret = mcp251x_set_normal_mode(spi);
if (ret) {
mcp251x_open_clean(net);
goto open_unlock;
}
netif_wake_queue(net);
open_unlock:
mutex_unlock(&priv->mcp_lock);
return ret;
}
static const struct net_device_ops mcp251x_netdev_ops = {
.ndo_open = mcp251x_open,
.ndo_stop = mcp251x_stop,
.ndo_start_xmit = mcp251x_hard_start_xmit,
};
static int __devinit mcp251x_can_probe(struct spi_device *spi)
{
struct net_device *net;
struct mcp251x_priv *priv;
struct mcp251x_platform_data *pdata = spi->dev.platform_data;
int ret = -ENODEV;
if (!pdata)
/* Platform data is required for osc freq */
goto error_out;
/* Allocate can/net device */
net = alloc_candev(sizeof(struct mcp251x_priv), TX_ECHO_SKB_MAX);
if (!net) {
ret = -ENOMEM;
goto error_alloc;
}
net->netdev_ops = &mcp251x_netdev_ops;
net->flags |= IFF_ECHO;
priv = netdev_priv(net);
priv->can.bittiming_const = &mcp251x_bittiming_const;
priv->can.do_set_mode = mcp251x_do_set_mode;
priv->can.clock.freq = pdata->oscillator_frequency / 2;
priv->can.ctrlmode_supported = CAN_CTRLMODE_3_SAMPLES |
CAN_CTRLMODE_LOOPBACK | CAN_CTRLMODE_LISTENONLY;
priv->model = spi_get_device_id(spi)->driver_data;
priv->net = net;
dev_set_drvdata(&spi->dev, priv);
priv->spi = spi;
mutex_init(&priv->mcp_lock);
/* If requested, allocate DMA buffers */
if (mcp251x_enable_dma) {
spi->dev.coherent_dma_mask = ~0;
/*
* Minimum coherent DMA allocation is PAGE_SIZE, so allocate
* that much and share it between Tx and Rx DMA buffers.
*/
priv->spi_tx_buf = dma_alloc_coherent(&spi->dev,
PAGE_SIZE,
&priv->spi_tx_dma,
GFP_DMA);
if (priv->spi_tx_buf) {
priv->spi_rx_buf = (u8 *)(priv->spi_tx_buf +
(PAGE_SIZE / 2));
priv->spi_rx_dma = (dma_addr_t)(priv->spi_tx_dma +
(PAGE_SIZE / 2));
} else {
/* Fall back to non-DMA */
mcp251x_enable_dma = 0;
}
}
/* Allocate non-DMA buffers */
if (!mcp251x_enable_dma) {
priv->spi_tx_buf = kmalloc(SPI_TRANSFER_BUF_LEN, GFP_KERNEL);
if (!priv->spi_tx_buf) {
ret = -ENOMEM;
goto error_tx_buf;
}
priv->spi_rx_buf = kmalloc(SPI_TRANSFER_BUF_LEN, GFP_KERNEL);
if (!priv->spi_rx_buf) {
ret = -ENOMEM;
goto error_rx_buf;
}
}
if (pdata->power_enable)
pdata->power_enable(1);
/* Call out to platform specific setup */
if (pdata->board_specific_setup)
pdata->board_specific_setup(spi);
SET_NETDEV_DEV(net, &spi->dev);
/* Configure the SPI bus */
spi->mode = SPI_MODE_0;
spi->bits_per_word = 8;
spi_setup(spi);
/* Here is OK to not lock the MCP, no one knows about it yet */
if (!mcp251x_hw_probe(spi)) {
dev_info(&spi->dev, "Probe failed\n");
goto error_probe;
}
mcp251x_hw_sleep(spi);
if (pdata->transceiver_enable)
pdata->transceiver_enable(0);
ret = register_candev(net);
if (!ret) {
netdev_info(priv->net, "probed\n");
return ret;
}
error_probe:
if (!mcp251x_enable_dma)
kfree(priv->spi_rx_buf);
error_rx_buf:
if (!mcp251x_enable_dma)
kfree(priv->spi_tx_buf);
error_tx_buf:
free_candev(net);
if (mcp251x_enable_dma)
dma_free_coherent(&spi->dev, PAGE_SIZE,
priv->spi_tx_buf, priv->spi_tx_dma);
error_alloc:
if (pdata->power_enable)
pdata->power_enable(0);
dev_err(&spi->dev, "probe failed\n");
error_out:
return ret;
}
static int __devexit mcp251x_can_remove(struct spi_device *spi)
{
struct mcp251x_platform_data *pdata = spi->dev.platform_data;
struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev);
struct net_device *net = priv->net;
unregister_candev(net);
free_candev(net);
if (mcp251x_enable_dma) {
dma_free_coherent(&spi->dev, PAGE_SIZE,
priv->spi_tx_buf, priv->spi_tx_dma);
} else {
kfree(priv->spi_tx_buf);
kfree(priv->spi_rx_buf);
}
if (pdata->power_enable)
pdata->power_enable(0);
return 0;
}
#ifdef CONFIG_PM
static int mcp251x_can_suspend(struct spi_device *spi, pm_message_t state)
{
struct mcp251x_platform_data *pdata = spi->dev.platform_data;
struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev);
struct net_device *net = priv->net;
priv->force_quit = 1;
disable_irq(spi->irq);
/*
* Note: at this point neither IST nor workqueues are running.
* open/stop cannot be called anyway so locking is not needed
*/
if (netif_running(net)) {
netif_device_detach(net);
mcp251x_hw_sleep(spi);
if (pdata->transceiver_enable)
pdata->transceiver_enable(0);
priv->after_suspend = AFTER_SUSPEND_UP;
} else {
priv->after_suspend = AFTER_SUSPEND_DOWN;
}
if (pdata->power_enable) {
pdata->power_enable(0);
priv->after_suspend |= AFTER_SUSPEND_POWER;
}
return 0;
}
static int mcp251x_can_resume(struct spi_device *spi)
{
struct mcp251x_platform_data *pdata = spi->dev.platform_data;
struct mcp251x_priv *priv = dev_get_drvdata(&spi->dev);
if (priv->after_suspend & AFTER_SUSPEND_POWER) {
pdata->power_enable(1);
queue_work(priv->wq, &priv->restart_work);
} else {
if (priv->after_suspend & AFTER_SUSPEND_UP) {
if (pdata->transceiver_enable)
pdata->transceiver_enable(1);
queue_work(priv->wq, &priv->restart_work);
} else {
priv->after_suspend = 0;
}
}
priv->force_quit = 0;
enable_irq(spi->irq);
return 0;
}
#else
#define mcp251x_can_suspend NULL
#define mcp251x_can_resume NULL
#endif
static const struct spi_device_id mcp251x_id_table[] = {
{ "mcp2510", CAN_MCP251X_MCP2510 },
{ "mcp2515", CAN_MCP251X_MCP2515 },
{ },
};
MODULE_DEVICE_TABLE(spi, mcp251x_id_table);
static struct spi_driver mcp251x_can_driver = {
.driver = {
.name = DEVICE_NAME,
.bus = &spi_bus_type,
.owner = THIS_MODULE,
},
.id_table = mcp251x_id_table,
.probe = mcp251x_can_probe,
.remove = __devexit_p(mcp251x_can_remove),
.suspend = mcp251x_can_suspend,
.resume = mcp251x_can_resume,
};
static int __init mcp251x_can_init(void)
{
return spi_register_driver(&mcp251x_can_driver);
}
static void __exit mcp251x_can_exit(void)
{
spi_unregister_driver(&mcp251x_can_driver);
}
module_init(mcp251x_can_init);
module_exit(mcp251x_can_exit);
MODULE_AUTHOR("Chris Elston <celston@katalix.com>, "
"Christian Pellegrin <chripell@evolware.org>");
MODULE_DESCRIPTION("Microchip 251x CAN driver");
MODULE_LICENSE("GPL v2");
|
abusnooze/mint-v3.2-psp26
|
drivers/net/can/mcp251x.c
|
C
|
gpl-2.0
| 33,044
|
# vim:fileencoding=utf-8:noet
try:
import pygit2 as git
class Repository(object):
__slots__ = ('directory')
def __init__(self, directory):
self.directory = directory
def _repo(self):
return git.Repository(self.directory)
def status(self, path=None):
'''Return status of repository or file.
Without file argument: returns status of the repository:
:First column: working directory status (D: dirty / space)
:Second column: index status (I: index dirty / space)
:Third column: presense of untracked files (U: untracked files / space)
:None: repository clean
With file argument: returns status of this file. Output is
equivalent to the first two columns of "git status --porcelain"
(except for merge statuses as they are not supported by libgit2).
'''
if path:
try:
status = self._repo().status_file(path)
except (KeyError, ValueError):
return None
if status == git.GIT_STATUS_CURRENT:
return None
else:
if status & git.GIT_STATUS_WT_NEW:
return '??'
if status & git.GIT_STATUS_IGNORED:
return '!!'
if status & git.GIT_STATUS_INDEX_NEW:
index_status = 'A'
elif status & git.GIT_STATUS_INDEX_DELETED:
index_status = 'D'
elif status & git.GIT_STATUS_INDEX_MODIFIED:
index_status = 'M'
else:
index_status = ' '
if status & git.GIT_STATUS_WT_DELETED:
wt_status = 'D'
elif status & git.GIT_STATUS_WT_MODIFIED:
wt_status = 'M'
else:
wt_status = ' '
return index_status + wt_status
else:
wt_column = ' '
index_column = ' '
untracked_column = ' '
for status in self._repo().status().values():
if status & git.GIT_STATUS_WT_NEW:
untracked_column = 'U'
continue
if status & (git.GIT_STATUS_WT_DELETED
| git.GIT_STATUS_WT_MODIFIED):
wt_column = 'D'
if status & (git.GIT_STATUS_INDEX_NEW
| git.GIT_STATUS_INDEX_MODIFIED
| git.GIT_STATUS_INDEX_DELETED):
index_column = 'I'
r = wt_column + index_column + untracked_column
return r if r != ' ' else None
def branch(self):
try:
ref = self._repo().lookup_reference('HEAD')
except KeyError:
return None
try:
target = ref.target
except ValueError:
return '[DETACHED HEAD]'
if target.startswith('refs/heads/'):
return target[11:]
else:
return '[DETACHED HEAD]'
except ImportError:
from subprocess import Popen, PIPE
def readlines(cmd, cwd):
p = Popen(cmd, shell=False, stdout=PIPE, stderr=PIPE, cwd=cwd)
p.stderr.close()
with p.stdout:
for line in p.stdout:
yield line[:-1].decode('utf-8')
class Repository(object):
__slots__ = ('directory',)
def __init__(self, directory):
self.directory = directory
def _gitcmd(self, *args):
return readlines(('git',) + args, self.directory)
def status(self, path=None):
if path:
try:
return next(self._gitcmd('status', '--porcelain', '--ignored', '--', path))[:2]
except StopIteration:
return None
else:
wt_column = ' '
index_column = ' '
untracked_column = ' '
for line in self._gitcmd('status', '--porcelain'):
if line[0] == '?':
untracked_column = 'U'
continue
elif line[0] == '!':
continue
if line[0] != ' ':
index_column = 'I'
if line[1] != ' ':
wt_column = 'D'
r = wt_column + index_column + untracked_column
return r if r != ' ' else None
def branch(self):
for line in self._gitcmd('branch', '-l'):
if line[0] == '*':
return line[2:]
return None
|
DaneelOliwan/dotfiles-vim
|
.vim/bundle/powerline/powerline/lib/vcs/git.py
|
Python
|
gpl-2.0
| 3,605
|
# TeXplate
LaTeX template for Master's reports
# How to use it?
* Please to replace new commands in ```main.tex``` file.
* Please to use the logo of your Master in ```img/``` and rename it ```master_logo.png```
* You can write a Makefile for the project (and create a pull request so :-)), or use some Tex Editors like TexStudio, TexMaker, etc...
# Contents
* Presentation file
* Introduction file
* Chapter One/Two/Three file
* Conclusion file
* BibTeX
# License
GNUGpl v3
|
k0pernicus/TeXplate
|
README.md
|
Markdown
|
gpl-2.0
| 493
|
<?php
/**
* Mkdir class
*
* Class to rename directory/file & manage errors in doing so.
*
* PHP version 3
*
* 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.
*
* @category Chisimba
* @package files
* @author David Wafula
* @copyright 2010, University of the Witwatersrand & AVOIR Project
* @license http://www.gnu.org/licenses/gpl-2.0.txt The GNU General Public License
* @link http://avoir.uwc.ac.za,http://www.chisimba.com
* @see References to other sections (if any)...
*/
class rename extends object
{
/**
*
* @var string $oldFilePath The old file including its path,
* or the folder if rename a folder.
*
*/
var $oldFilePath;
/**
*
* @var string $newFilePath The new file including its path,
* or the folder if rename a folder.
*
*/
var $newFilePath;
/**
*
* @var boolean $err TRUE|FALSE; TRUE if error, else false
*
*/
var $err;
/**
*
* @var string $errMst The error message
*
*/
var $errMsg;
/**
*
* @var object $objLanguage String to hold the language object
*
*/
var $objLanguage;
/**
*
* Standard init method to set the default values for
* the properties.
*
*/
function init()
{
$this->oldFilePath = NULL;
$this->newFilePath = NULL;
$this->err = NULL;
$this->errMsg = NULL;
// Create an instance of the language object
$this->objLanguage = $this->getObject('language', 'language');
}
/**
*
* Renames a file/folder. Needs oldFilePath and newFilePath to be set
* to a valid path before hand
*
* @access Public
*
*/
function rename()
{
if ($this->oldFilePath != NULL && $this->newFilePath != NULL) {
rename($this->oldFilePath,$this->newFilePath);
//If the file path is null
} else {
$this->err = TRUE;
$this->errMsg = $this->objLanguage->languageText('mod_files_err_nofilepath')
. ": Old - " . $this->oldFilePath.", New - " . $this->newFilePath;
return FALSE;
}
} //function
} // end of class
?>
|
chisimba/chisimba
|
app/core_modules/files/classes/rename_class_inc.php
|
PHP
|
gpl-2.0
| 2,996
|
var searchData=
[
['vectororient',['vectorOrient',['../group___t_xC3_xA1rol_xC3_xB3k.html#gab13a5c3bc64237cc95301c3359a757c8',1,'RobotStateHistory']]]
];
|
muszkab/Alkalmazasfejlesztes-hazi
|
RobotDiagnosticApp/docs/html/search/variables_b.js
|
JavaScript
|
gpl-2.0
| 156
|
/* $Revision: 77449 $ */
/** @file
* VBoxGuestLibR0 - Physical memory heap.
*/
/*
* Copyright (C) 2006-2007 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
#include "VBGLInternal.h"
/**
* Checks whether the host supports physical page lists or not.
*
* @returns true if it does, false if it doesn't.
*/
DECLR0VBGL(bool) VbglR0CanUsePhysPageList(void)
{
int rc = vbglR0Enter();
return RT_SUCCESS(rc)
&& VBGLR0_CAN_USE_PHYS_PAGE_LIST(/*a_fLocked =*/ false);
}
|
VirtualMonitor/VirtualMonitor
|
src/VBox/Additions/common/VBoxGuestLib/VbglR0CanUsePhysPageList.cpp
|
C++
|
gpl-2.0
| 1,404
|
<?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\DICOM;
use PHPExiftool\Driver\AbstractTag;
class GridPitch extends AbstractTag
{
protected $Id = '0018,7044';
protected $Name = 'GridPitch';
protected $FullName = 'DICOM::Main';
protected $GroupName = 'DICOM';
protected $g0 = 'DICOM';
protected $g1 = 'DICOM';
protected $g2 = 'Image';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Grid Pitch';
}
|
Droces/casabio
|
vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/DICOM/GridPitch.php
|
PHP
|
gpl-2.0
| 695
|
## Description
<!-- Describe the overall purpose of this pull request (PR). If applicable also add bug references and screenshots.-->
## Checklist
- [ ] Commit messages are descriptive and explain the rationale for changes
- [ ] I used the same coding style as the surrounding code <!-- yet to be formally defined, see issue #161 -->
- [ ] I have tested the proposed changes
- [ ] I extended the documentation, if necessary
- [ ] The proposed change builds also on our build bots (check after submission)
|
gemrb/gemrb
|
.github/PULL_REQUEST_TEMPLATE.md
|
Markdown
|
gpl-2.0
| 508
|
/*
* Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TRINITYCORE_CREATURE_H
#define TRINITYCORE_CREATURE_H
#include "Common.h"
#include "Unit.h"
#include "UpdateMask.h"
#include "ItemPrototype.h"
#include "LootMgr.h"
#include "DatabaseEnv.h"
#include "Cell.h"
#include <list>
struct SpellEntry;
class CreatureAI;
class Quest;
class Player;
class WorldSession;
class CreatureGroup;
enum CreatureFlagsExtra
{
CREATURE_FLAG_EXTRA_INSTANCE_BIND = 0x00000001, // creature kill bind instance with killer and killer's group
CREATURE_FLAG_EXTRA_CIVILIAN = 0x00000002, // not aggro (ignore faction/reputation hostility)
CREATURE_FLAG_EXTRA_NO_PARRY = 0x00000004, // creature can't parry
CREATURE_FLAG_EXTRA_NO_PARRY_HASTEN = 0x00000008, // creature can't counter-attack at parry
CREATURE_FLAG_EXTRA_NO_BLOCK = 0x00000010, // creature can't block
CREATURE_FLAG_EXTRA_NO_CRUSH = 0x00000020, // creature can't do crush attacks
CREATURE_FLAG_EXTRA_NO_XP_AT_KILL = 0x00000040, // creature kill not provide XP
CREATURE_FLAG_EXTRA_TRIGGER = 0x00000080, // trigger creature
CREATURE_FLAG_EXTRA_NO_TAUNT = 0x00000100, // creature is immune to taunt auras and effect attack me
CREATURE_FLAG_EXTRA_WORLDEVENT = 0x00004000, // custom flag for world event creatures (left room for merging)
CREATURE_FLAG_EXTRA_GUARD = 0x00008000, // Creature is guard
CREATURE_FLAG_EXTRA_NO_CRIT = 0x00020000, // creature can't do critical strikes
CREATURE_FLAG_EXTRA_NO_SKILLGAIN = 0x00040000, // creature won't increase weapon skills
CREATURE_FLAG_EXTRA_TAUNT_DIMINISH = 0x00080000, // Taunt is a subject to diminishing returns on this creautre
CREATURE_FLAG_EXTRA_ALL_DIMINISH = 0x00100000, // Creature is subject to all diminishing returns as player are
CREATURE_FLAG_EXTRA_DUNGEON_BOSS = 0x10000000, // creature is a dungeon boss (SET DYNAMICALLY, DO NOT ADD IN DB)
};
#define CREATURE_FLAG_EXTRA_DB_ALLOWED (CREATURE_FLAG_EXTRA_INSTANCE_BIND | CREATURE_FLAG_EXTRA_CIVILIAN | \
CREATURE_FLAG_EXTRA_NO_PARRY | CREATURE_FLAG_EXTRA_NO_PARRY_HASTEN | CREATURE_FLAG_EXTRA_NO_BLOCK | \
CREATURE_FLAG_EXTRA_NO_CRUSH | CREATURE_FLAG_EXTRA_NO_XP_AT_KILL | CREATURE_FLAG_EXTRA_TRIGGER | \
CREATURE_FLAG_EXTRA_NO_TAUNT | CREATURE_FLAG_EXTRA_WORLDEVENT | CREATURE_FLAG_EXTRA_NO_CRIT | \
CREATURE_FLAG_EXTRA_NO_SKILLGAIN | CREATURE_FLAG_EXTRA_TAUNT_DIMINISH | CREATURE_FLAG_EXTRA_ALL_DIMINISH | \
CREATURE_FLAG_EXTRA_GUARD)
// GCC have alternative #pragma pack(N) syntax and old gcc version not support pack(push, N), also any gcc version not support it at some platform
#if defined(__GNUC__)
#pragma pack(1)
#else
#pragma pack(push, 1)
#endif
#define MAX_KILL_CREDIT 2
#define CREATURE_REGEN_INTERVAL 2 * IN_MILLISECONDS
#define MAX_CREATURE_QUEST_ITEMS 6
#define MAX_EQUIPMENT_ITEMS 3
// from `creature_template` table
struct CreatureTemplate
{
uint32 Entry;
uint32 DifficultyEntry[MAX_DIFFICULTY - 1];
uint32 KillCredit[MAX_KILL_CREDIT];
uint32 Modelid1;
uint32 Modelid2;
uint32 Modelid3;
uint32 Modelid4;
std::string Name;
std::string SubName;
std::string IconName;
uint32 GossipMenuId;
uint8 minlevel;
uint8 maxlevel;
uint32 expansion;
uint32 faction_A;
uint32 faction_H;
uint32 npcflag;
float speed_walk;
float speed_run;
float scale;
uint32 rank;
float mindmg;
float maxdmg;
uint32 dmgschool;
uint32 attackpower;
float dmg_multiplier;
uint32 baseattacktime;
uint32 rangeattacktime;
uint32 unit_class; // enum Classes. Note only 4 classes are known for creatures.
uint32 unit_flags; // enum UnitFlags mask values
uint32 dynamicflags;
uint32 family; // enum CreatureFamily values (optional)
uint32 trainer_type;
uint32 trainer_spell;
uint32 trainer_class;
uint32 trainer_race;
float minrangedmg;
float maxrangedmg;
uint32 rangedattackpower;
uint32 type; // enum CreatureType values
uint32 type_flags; // enum CreatureTypeFlags mask values
uint32 lootid;
uint32 pickpocketLootId;
uint32 SkinLootId;
int32 resistance[MAX_SPELL_SCHOOL];
uint32 spells[CREATURE_MAX_SPELLS];
uint32 PetSpellDataId;
uint32 VehicleId;
uint32 mingold;
uint32 maxgold;
std::string AIName;
uint32 MovementType;
uint32 InhabitType;
float ModHealth;
float ModMana;
float ModArmor;
bool RacialLeader;
uint32 questItems[MAX_CREATURE_QUEST_ITEMS];
uint32 movementId;
bool RegenHealth;
uint32 equipmentId;
uint32 MechanicImmuneMask;
uint32 flags_extra;
uint32 ScriptID;
uint32 GetRandomValidModelId() const;
uint32 GetFirstValidModelId() const;
// helpers
SkillType GetRequiredLootSkill() const
{
if (type_flags & CREATURE_TYPEFLAGS_HERBLOOT)
return SKILL_HERBALISM;
else if (type_flags & CREATURE_TYPEFLAGS_MININGLOOT)
return SKILL_MINING;
else if (type_flags & CREATURE_TYPEFLAGS_ENGINEERLOOT)
return SKILL_ENGINERING;
else
return SKILL_SKINNING; // normal case
}
bool isTameable(bool exotic) const
{
if (type != CREATURE_TYPE_BEAST || family == 0 || (type_flags & CREATURE_TYPEFLAGS_TAMEABLE) == 0)
return false;
// if can tame exotic then can tame any temable
return exotic || (type_flags & CREATURE_TYPEFLAGS_EXOTIC) == 0;
}
};
// Benchmarked: Faster than std::map (insert/find)
typedef UNORDERED_MAP<uint32, CreatureTemplate> CreatureTemplateContainer;
// Represents max amount of expansions.
// TODO: Add MAX_EXPANSION constant.
#define MAX_CREATURE_BASE_HP 3
// Defines base stats for creatures (used to calculate HP/mana/armor).
struct CreatureBaseStats
{
uint32 BaseHealth[MAX_CREATURE_BASE_HP];
uint32 BaseMana;
uint32 BaseArmor;
// Helpers
uint32 GenerateHealth(CreatureTemplate const* info) const
{
return uint32((BaseHealth[info->expansion] * info->ModHealth) + 0.5f);
}
uint32 GenerateMana(CreatureTemplate const* info) const
{
// Mana can be 0.
if (!BaseMana)
return 0;
return uint32((BaseMana * info->ModMana) + 0.5f);
}
uint32 GenerateArmor(CreatureTemplate const* info) const
{
return uint32((BaseArmor * info->ModArmor) + 0.5f);
}
static CreatureBaseStats const* GetBaseStats(uint8 level, uint8 unitClass);
};
typedef UNORDERED_MAP<uint16, CreatureBaseStats> CreatureBaseStatsMap;
struct CreatureLocale
{
StringVector Name;
StringVector SubName;
};
struct GossipMenuItemsLocale
{
StringVector OptionText;
StringVector BoxText;
};
struct PointOfInterestLocale
{
StringVector IconName;
};
struct EquipmentInfo
{
uint32 ItemEntry[MAX_EQUIPMENT_ITEMS];
};
// Benchmarked: Faster than std::map (insert/find)
typedef UNORDERED_MAP<uint16, EquipmentInfo> EquipmentInfoContainer;
// from `creature` table
struct CreatureData
{
explicit CreatureData() : dbData(true) {}
uint32 id; // entry in creature_template
uint16 mapid;
uint16 phaseMask;
uint32 displayid;
int32 equipmentId;
float posX;
float posY;
float posZ;
float orientation;
uint32 spawntimesecs;
float spawndist;
uint32 currentwaypoint;
uint32 curhealth;
uint32 curmana;
bool is_dead;
uint8 movementType;
uint8 spawnMask;
uint32 npcflag;
uint32 unit_flags; // enum UnitFlags mask values
uint32 dynamicflags;
bool dbData;
};
// `creature_addon` table
struct CreatureAddon
{
uint32 guidOrEntry;
uint32 path_id;
uint32 mount;
uint32 bytes1;
uint32 bytes2;
uint32 emote;
std::vector<uint32> auras;
};
typedef UNORDERED_MAP<uint32, CreatureAddon> CreatureAddonContainer;
struct CreatureModelInfo
{
float bounding_radius;
float combat_reach;
uint8 gender;
uint32 modelid_other_gender;
};
// Benchmarked: Faster than std::map (insert/find)
typedef UNORDERED_MAP<uint16, CreatureModelInfo> CreatureModelContainer;
enum InhabitTypeValues
{
INHABIT_GROUND = 1,
INHABIT_WATER = 2,
INHABIT_AIR = 4,
INHABIT_ANYWHERE = INHABIT_GROUND | INHABIT_WATER | INHABIT_AIR
};
// Enums used by StringTextData::Type (CreatureEventAI)
enum ChatType
{
CHAT_TYPE_SAY = 0,
CHAT_TYPE_YELL = 1,
CHAT_TYPE_TEXT_EMOTE = 2,
CHAT_TYPE_BOSS_EMOTE = 3,
CHAT_TYPE_WHISPER = 4,
CHAT_TYPE_BOSS_WHISPER = 5,
CHAT_TYPE_ZONE_YELL = 6,
CHAT_TYPE_END = 255
};
// GCC have alternative #pragma pack() syntax and old gcc version not support pack(pop), also any gcc version not support it at some platform
#if defined(__GNUC__)
#pragma pack()
#else
#pragma pack(pop)
#endif
// Vendors
struct VendorItem
{
VendorItem(uint32 _item, int32 _maxcount, uint32 _incrtime, uint32 _ExtendedCost)
: item(_item), maxcount(_maxcount), incrtime(_incrtime), ExtendedCost(_ExtendedCost) {}
uint32 item;
uint32 maxcount; // 0 for infinity item amount
uint32 incrtime; // time for restore items amount if maxcount != 0
uint32 ExtendedCost;
//helpers
bool IsGoldRequired(ItemTemplate const* pProto) const { return pProto->Flags2 & ITEM_FLAGS_EXTRA_EXT_COST_REQUIRES_GOLD || !ExtendedCost; }
};
typedef std::vector<VendorItem*> VendorItemList;
struct VendorItemData
{
VendorItemList m_items;
VendorItem* GetItem(uint32 slot) const
{
if (slot >= m_items.size()) return NULL;
return m_items[slot];
}
bool Empty() const { return m_items.empty(); }
uint8 GetItemCount() const { return m_items.size(); }
void AddItem(uint32 item, int32 maxcount, uint32 ptime, uint32 ExtendedCost)
{
m_items.push_back(new VendorItem(item, maxcount, ptime, ExtendedCost));
}
bool RemoveItem(uint32 item_id);
VendorItem const* FindItemCostPair(uint32 item_id, uint32 extendedCost) const;
void Clear()
{
for (VendorItemList::const_iterator itr = m_items.begin(); itr != m_items.end(); ++itr)
delete (*itr);
m_items.clear();
}
};
struct VendorItemCount
{
explicit VendorItemCount(uint32 _item, uint32 _count)
: itemId(_item), count(_count), lastIncrementTime(time(NULL)) {}
uint32 itemId;
uint32 count;
time_t lastIncrementTime;
};
typedef std::list<VendorItemCount> VendorItemCounts;
struct TrainerSpell
{
TrainerSpell() : spell(0), spellCost(0), reqSkill(0), reqSkillValue(0), reqLevel(0)
{
for (uint8 i = 0; i < MAX_SPELL_EFFECTS ; ++i)
learnedSpell[i] = 0;
}
uint32 spell;
uint32 spellCost;
uint32 reqSkill;
uint32 reqSkillValue;
uint32 reqLevel;
uint32 learnedSpell[3];
// helpers
bool IsCastable() const { return learnedSpell[0] != spell; }
};
typedef UNORDERED_MAP<uint32 /*spellid*/, TrainerSpell> TrainerSpellMap;
struct TrainerSpellData
{
TrainerSpellData() : trainerType(0) {}
~TrainerSpellData() { spellList.clear(); }
TrainerSpellMap spellList;
uint32 trainerType; // trainer type based at trainer spells, can be different from creature_template value.
// req. for correct show non-prof. trainers like weaponmaster, allowed values 0 and 2.
TrainerSpell const* Find(uint32 spell_id) const;
};
typedef std::map<uint32, time_t> CreatureSpellCooldowns;
// max different by z coordinate for creature aggro reaction
#define CREATURE_Z_ATTACK_RANGE 3
#define MAX_VENDOR_ITEMS 150 // Limitation in 3.x.x item count in SMSG_LIST_INVENTORY
class Creature : public Unit, public GridObject<Creature>
{
public:
explicit Creature();
virtual ~Creature();
void AddToWorld();
void RemoveFromWorld();
void DisappearAndDie();
bool Create(uint32 guidlow, Map *map, uint32 phaseMask, uint32 Entry, uint32 vehId, uint32 team, float x, float y, float z, float ang, const CreatureData *data = NULL);
bool LoadCreaturesAddon(bool reload = false);
void SelectLevel(const CreatureTemplate *cinfo);
void LoadEquipment(uint32 equip_entry, bool force=false);
uint32 GetDBTableGUIDLow() const { return m_DBTableGuid; }
void Update(uint32 time); // overwrited Unit::Update
void GetRespawnCoord(float &x, float &y, float &z, float* ori = NULL, float* dist =NULL) const;
uint32 GetEquipmentId() const { return GetCreatureInfo()->equipmentId; }
void SetCorpseDelay(uint32 delay) { m_corpseDelay = delay; }
uint32 GetCorpseDelay() const { return m_corpseDelay; }
bool isRacialLeader() const { return GetCreatureInfo()->RacialLeader; }
bool isCivilian() const { return GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_CIVILIAN; }
bool isTrigger() const { return GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_TRIGGER; }
bool isGuard() const { return GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_GUARD; }
bool canWalk() const { return GetCreatureInfo()->InhabitType & INHABIT_GROUND; }
bool canSwim() const { return GetCreatureInfo()->InhabitType & INHABIT_WATER; }
//bool canFly() const { return GetCreatureInfo()->InhabitType & INHABIT_AIR; }
void SetReactState(ReactStates st) { m_reactState = st; }
ReactStates GetReactState() { return m_reactState; }
bool HasReactState(ReactStates state) const { return (m_reactState == state); }
void InitializeReactState()
{
if (isTotem() || isTrigger() || GetCreatureType() == CREATURE_TYPE_CRITTER || isSpiritService())
SetReactState(REACT_PASSIVE);
else
SetReactState(REACT_AGGRESSIVE);
/*else if (isCivilian())
SetReactState(REACT_DEFENSIVE);*/;
}
///// TODO RENAME THIS!!!!!
bool isCanTrainingOf(Player* player, bool msg) const;
bool isCanInteractWithBattleMaster(Player* player, bool msg) const;
bool isCanTrainingAndResetTalentsOf(Player* pPlayer) const;
bool canCreatureAttack(Unit const *pVictim, bool force = true) const;
bool IsImmunedToSpell(SpellEntry const* spellInfo);
// redefine Unit::IsImmunedToSpell
bool IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const;
// redefine Unit::IsImmunedToSpellEffect
bool isElite() const
{
if (isPet())
return false;
uint32 rank = GetCreatureInfo()->rank;
return rank != CREATURE_ELITE_NORMAL && rank != CREATURE_ELITE_RARE;
}
bool isWorldBoss() const
{
if (isPet())
return false;
return GetCreatureInfo()->rank == CREATURE_ELITE_WORLDBOSS;
}
bool IsDungeonBoss() const;
uint8 getLevelForTarget(WorldObject const* target) const; // overwrite Unit::getLevelForTarget for boss level support
bool IsInEvadeMode() const { return HasUnitState(UNIT_STAT_EVADE); }
bool AIM_Initialize(CreatureAI* ai = NULL);
void Motion_Initialize();
void AI_SendMoveToPacket(float x, float y, float z, uint32 time, uint32 MovementFlags, uint8 type);
CreatureAI * AI() const { return (CreatureAI*)i_AI; }
//Bot commands
void SetBotAI(CreatureAI *newAI)
{
bot_AI = newAI;
}
CreatureAI *GetBotAI(){ return bot_AI; }
void SetIAmABot(bool bot){ is_a_bot = bot; }
bool GetIAmABot(){ return is_a_bot; }
uint32 GetShieldBlockValue() const //dunno mob block value
{
return (getLevel()/2 + uint32(GetStat(STAT_STRENGTH)/20));
}
SpellSchoolMask GetMeleeDamageSchoolMask() const { return m_meleeDamageSchoolMask; }
void SetMeleeDamageSchool(SpellSchools school) { m_meleeDamageSchoolMask = SpellSchoolMask(1 << school); }
void _AddCreatureSpellCooldown(uint32 spell_id, time_t end_time);
void _AddCreatureCategoryCooldown(uint32 category, time_t apply_time);
void AddCreatureSpellCooldown(uint32 spellid);
bool HasSpellCooldown(uint32 spell_id) const;
bool HasCategoryCooldown(uint32 spell_id) const;
bool HasSpell(uint32 spellID) const;
bool UpdateEntry(uint32 entry, uint32 team=ALLIANCE, const CreatureData* data=NULL);
bool UpdateStats(Stats stat);
bool UpdateAllStats();
void UpdateResistances(uint32 school);
void UpdateArmor();
void UpdateMaxHealth();
void UpdateMaxPower(Powers power);
void UpdateAttackPowerAndDamage(bool ranged = false);
void UpdateDamagePhysical(WeaponAttackType attType);
uint32 GetCurrentEquipmentId() { return m_equipmentId; }
void SetCurrentEquipmentId(uint32 entry) { m_equipmentId = entry; }
float GetSpellDamageMod(int32 Rank);
VendorItemData const* GetVendorItems() const;
uint32 GetVendorItemCurrentCount(VendorItem const* vItem);
uint32 UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 used_count);
TrainerSpellData const* GetTrainerSpells() const;
CreatureTemplate const *GetCreatureInfo() const { return m_creatureInfo; }
CreatureData const *GetCreatureData() const { return m_creatureData; }
CreatureAddon const* GetCreatureAddon() const;
std::string GetAIName() const;
std::string GetScriptName() const;
uint32 GetScriptId() const;
void Say(int32 textId, uint32 language, uint64 TargetGuid) { MonsterSay(textId, language, TargetGuid); }
void Yell(int32 textId, uint32 language, uint64 TargetGuid) { MonsterYell(textId, language, TargetGuid); }
void TextEmote(int32 textId, uint64 TargetGuid, bool IsBossEmote = false) { MonsterTextEmote(textId, TargetGuid, IsBossEmote); }
void Whisper(int32 textId, uint64 receiver, bool IsBossWhisper = false) { MonsterWhisper(textId, receiver, IsBossWhisper); }
void YellToZone(int32 textId, uint32 language, uint64 TargetGuid) { MonsterYellToZone(textId, language, TargetGuid); }
// override WorldObject function for proper name localization
const char* GetNameForLocaleIdx(LocaleConstant locale_idx) const;
void setDeathState(DeathState s); // override virtual Unit::setDeathState
bool FallGround();
bool LoadFromDB(uint32 guid, Map *map);
void SaveToDB();
// overriden in Pet
virtual void SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask);
virtual void DeleteFromDB(); // overriden in Pet
Loot loot;
bool lootForPickPocketed;
bool lootForBody;
Player *GetLootRecipient() const;
Group *GetLootRecipientGroup() const;
bool hasLootRecipient() const { return m_lootRecipient || m_lootRecipientGroup; }
bool isTappedBy(Player *player) const; // return true if the creature is tapped by the player or a member of his party.
void SetLootRecipient (Unit* unit);
void AllLootRemovedFromCorpse();
uint16 GetLootMode() { return m_LootMode; }
bool HasLootMode(uint16 lootMode) { return m_LootMode & lootMode; }
void SetLootMode(uint16 lootMode) { m_LootMode = lootMode; }
void AddLootMode(uint16 lootMode) { m_LootMode |= lootMode; }
void RemoveLootMode(uint16 lootMode) { m_LootMode &= ~lootMode; }
void ResetLootMode() { m_LootMode = LOOT_MODE_DEFAULT; }
SpellEntry const *reachWithSpellAttack(Unit *pVictim);
SpellEntry const *reachWithSpellCure(Unit *pVictim);
uint32 m_spells[CREATURE_MAX_SPELLS];
CreatureSpellCooldowns m_CreatureSpellCooldowns;
CreatureSpellCooldowns m_CreatureCategoryCooldowns;
bool canStartAttack(Unit const* u, bool force) const;
float GetAttackDistance(Unit const* pl) const;
void SendAIReaction(AiReaction reactionType);
Unit* SelectNearestTarget(float dist = 0) const;
Unit* SelectNearestTargetInAttackDistance(float dist = 0) const;
void DoFleeToGetAssistance();
void CallForHelp(float fRadius);
void CallAssistance();
void SetNoCallAssistance(bool val) { m_AlreadyCallAssistance = val; }
void SetNoSearchAssistance(bool val) { m_AlreadySearchedAssistance = val; }
bool HasSearchedAssistance() { return m_AlreadySearchedAssistance; }
bool CanAssistTo(const Unit* u, const Unit* enemy, bool checkfaction = true) const;
bool _IsTargetAcceptable(const Unit* target) const;
MovementGeneratorType GetDefaultMovementType() const { return m_defaultMovementType; }
void SetDefaultMovementType(MovementGeneratorType mgt) { m_defaultMovementType = mgt; }
// for use only in LoadHelper, Map::Add Map::CreatureCellRelocation
Cell const& GetCurrentCell() const { return m_currentCell; }
void SetCurrentCell(Cell const& cell) { m_currentCell = cell; }
void RemoveCorpse(bool setSpawnTime = true);
bool isDeadByDefault() const { return m_isDeadByDefault; };
void ForcedDespawn(uint32 timeMSToDespawn = 0);
void DespawnOrUnsummon(uint32 msTimeToDespawn = 0);
time_t const& GetRespawnTime() const { return m_respawnTime; }
time_t GetRespawnTimeEx() const;
void SetRespawnTime(uint32 respawn) { m_respawnTime = respawn ? time(NULL) + respawn : 0; }
void Respawn(bool force = false);
void SaveRespawnTime();
uint32 GetRespawnDelay() const { return m_respawnDelay; }
void SetRespawnDelay(uint32 delay) { m_respawnDelay = delay; }
float GetRespawnRadius() const { return m_respawnradius; }
void SetRespawnRadius(float dist) { m_respawnradius = dist; }
uint32 m_groupLootTimer; // (msecs)timer used for group loot
uint32 lootingGroupLowGUID; // used to find group which is looting corpse
void SendZoneUnderAttackMessage(Player* attacker);
void SetInCombatWithZone();
bool hasQuest(uint32 quest_id) const;
bool hasInvolvedQuest(uint32 quest_id) const;
bool isRegeneratingHealth() { return m_regenHealth; }
void setRegeneratingHealth(bool state) { m_regenHealth = state; }
virtual uint8 GetPetAutoSpellSize() const { return MAX_SPELL_CHARM; }
virtual uint32 GetPetAutoSpellOnPos(uint8 pos) const
{
if (pos >= MAX_SPELL_CHARM || m_charmInfo->GetCharmSpell(pos)->GetType() != ACT_ENABLED)
return 0;
else
return m_charmInfo->GetCharmSpell(pos)->GetAction();
}
void SetHomePosition(float x, float y, float z, float o) { m_homePosition.Relocate(x, y, z, o); }
void SetHomePosition(const Position &pos) { m_homePosition.Relocate(pos); }
void GetHomePosition(float &x, float &y, float &z, float &ori) { m_homePosition.GetPosition(x, y, z, ori); }
Position GetHomePosition() { return m_homePosition; }
uint32 GetWaypointPath(){return m_path_id;}
void LoadPath(uint32 pathid) { m_path_id = pathid; }
uint32 GetCurrentWaypointID(){return m_waypointID;}
void UpdateWaypointID(uint32 wpID){m_waypointID = wpID;}
void SearchFormation();
CreatureGroup *GetFormation() {return m_formation;}
void SetFormation(CreatureGroup *formation) {m_formation = formation;}
Unit *SelectVictim();
void SetDeadByDefault (bool death_state) {m_isDeadByDefault = death_state;}
void SetDisableReputationGain(bool disable) { DisableReputationGain = disable; }
bool IsReputationGainDisabled() { return DisableReputationGain; }
bool IsDamageEnoughForLootingAndReward() const { return m_PlayerDamageReq == 0; }
void LowerPlayerDamageReq(uint32 unDamage)
{
if (m_PlayerDamageReq)
m_PlayerDamageReq > unDamage ? m_PlayerDamageReq -= unDamage : m_PlayerDamageReq = 0;
}
void ResetPlayerDamageReq() { m_PlayerDamageReq = GetHealth() / 2; }
uint32 m_PlayerDamageReq;
uint32 GetOriginalEntry() const { return m_originalEntry; }
void SetOriginalEntry(uint32 entry) { m_originalEntry = entry; }
static float _GetDamageMod(int32 Rank);
float m_SightDistance, m_CombatDistance;
void SetGUIDTransport(uint32 guid) { guid_transport=guid; }
uint32 GetGUIDTransport() { return guid_transport; }
void FarTeleportTo(Map* map, float X, float Y, float Z, float O);
protected:
bool CreateFromProto(uint32 guidlow, uint32 Entry, uint32 vehId, uint32 team, const CreatureData *data = NULL);
bool InitEntry(uint32 entry, uint32 team=ALLIANCE, const CreatureData* data=NULL);
// vendor items
VendorItemCounts m_vendorItemCounts;
static float _GetHealthMod(int32 Rank);
uint32 m_lootMoney;
uint64 m_lootRecipient;
uint32 m_lootRecipientGroup;
/// Timers
time_t m_corpseRemoveTime; // (msecs)timer for death or corpse disappearance
time_t m_respawnTime; // (secs) time of next respawn
uint32 m_respawnDelay; // (secs) delay between corpse disappearance and respawning
uint32 m_corpseDelay; // (secs) delay between death and corpse disappearance
float m_respawnradius;
ReactStates m_reactState; // for AI, not charmInfo
void RegenerateMana();
void RegenerateHealth();
void Regenerate(Powers power);
MovementGeneratorType m_defaultMovementType;
Cell m_currentCell; // store current cell where creature listed
uint32 m_DBTableGuid; ///< For new or temporary creatures is 0 for saved it is lowguid
uint32 m_equipmentId;
bool m_AlreadyCallAssistance;
bool m_AlreadySearchedAssistance;
bool m_regenHealth;
bool m_AI_locked;
bool m_isDeadByDefault;
SpellSchoolMask m_meleeDamageSchoolMask;
uint32 m_originalEntry;
Position m_homePosition;
bool DisableReputationGain;
CreatureTemplate const* m_creatureInfo; // in difficulty mode > 0 can different from sObjectMgr->GetCreatureTemplate(GetEntry())
CreatureData const* m_creatureData;
uint16 m_LootMode; // bitmask, default LOOT_MODE_DEFAULT, determines what loot will be lootable
uint32 guid_transport;
bool isVisibleForInState(WorldObject const* seer) const;
bool canSeeAlways(WorldObject const* obj) const;
private:
bool is_a_bot;
CreatureAI *bot_AI;
//WaypointMovementGenerator vars
uint32 m_waypointID;
uint32 m_path_id;
//Formation var
CreatureGroup *m_formation;
bool TriggerJustRespawned;
};
class AssistDelayEvent : public BasicEvent
{
public:
AssistDelayEvent(const uint64& victim, Unit& owner) : BasicEvent(), m_victim(victim), m_owner(owner) { }
bool Execute(uint64 e_time, uint32 p_time);
void AddAssistant(const uint64& guid) { m_assistants.push_back(guid); }
private:
AssistDelayEvent();
uint64 m_victim;
std::list<uint64> m_assistants;
Unit& m_owner;
};
class ForcedDespawnDelayEvent : public BasicEvent
{
public:
ForcedDespawnDelayEvent(Creature& owner) : BasicEvent(), m_owner(owner) { }
bool Execute(uint64 e_time, uint32 p_time);
private:
Creature& m_owner;
};
#endif
|
sucofog/chaoscore
|
src/server/game/Entities/Creature/Creature.h
|
C
|
gpl-2.0
| 29,713
|
from random import randint, shuffle, choice
from time import clock
from _utils import InvalidTableException, copy_table
def solve(table):
table = _check_table(table)
if _is_done(table):
return table
else:
coordinates = _get_minimum_array(table)
trials = table[coordinates[0]][coordinates[1]]["possibilities"][:]
shuffle(trials)
for elem in trials:
try:
ctable = copy_table(table)
ctable[coordinates[0]][coordinates[1]]["possibilities"] = [elem]
# print_table(ctable)
# print
return solve(ctable)
except InvalidTableException:
pass
# print "subiu"
raise InvalidTableException("Nao ha solucao")
def _is_done(table):
for line in table:
for elem in line:
if len(elem["possibilities"]) > 1:
return False
elif len(elem["possibilities"]) == 0:
raise InvalidTableException("Celula Vazia")
return True
def _check_table(table):
#find unchecked
#clean other possibilities
#raise exception if some possibility becomes void
while not _is_check_done(table):
unchecked_set = _find_unchecked(table)
for value,x,y in unchecked_set:
_fix_house(table,value,x,y)
_fix_column(table,value,x,y)
_fix_line(table,value,x,y)
table[y][x]["checked"] = True
return table
def _is_check_done(table):
for line in table:
for elem in line:
if len(elem["possibilities"]) == 1 and not elem["checked"]:
return False
return True
def _find_unchecked(table):
result = set()
for i, line in enumerate(table):
for j, elem in enumerate(line):
if len(elem["possibilities"]) == 1 and not elem["checked"]:
result.add((elem["possibilities"][0],j,i))
return result
def _fix_house(table,value,x,y):
x0 = (x/3)*3 + 1
y0 = (y/3)*3 + 1
to_fix = [(x0-1,y0-1),(x0-1,y0),(x0-1,y0+1),(x0,y0-1),(x0,y0),(x0,y0+1),(x0+1,y0-1),(x0+1,y0),(x0+1,y0+1)]
to_fix.remove((x,y))
for i,j in to_fix:
_fix(table,value,i,j)
def _fix_column(table,value,x,y):
columns = range(len(table))
columns.remove(y)
for j in columns:
_fix(table,value,x,j)
def _fix_line(table,value,x,y):
lines = range(len(table))
lines.remove(x)
for i in lines:
_fix(table,value,i,y)
def _fix(table, value, x, y):
try:
table[y][x]["possibilities"].remove(value)
except ValueError:
pass
if len(table[y][x]["possibilities"]) < 1:
raise InvalidTableException("Nao deu!")
def _get_minimum_array(table):
result = list()
size = len(table)
for i, line in enumerate(table):
for j, elem in enumerate(line):
if not elem["checked"]:
if not result:
result.append((i,j))
size = len(elem["possibilities"])
elif len(elem["possibilities"]) == size:
result.append((i,j))
elif len(elem["possibilities"]) < size:
result = list()
result.append((i,j))
size = len(elem["possibilities"])
return choice(result)
|
jonasrla/web_sudoku
|
helper/solver.py
|
Python
|
gpl-2.0
| 3,362
|
# -*- coding: utf-8 -*-
from sqlalchemy import text
from listenbrainz import db
class User(object):
""" User class required by the api-compat """
def __init__(self, id, created, name, api_key):
self.id = id
self.created = created
self.name = name
self.api_key = api_key
@staticmethod
def get_id(mb_id):
with db.engine.connect() as connection:
result = connection.execute(text(""" SELECT id FROM "user" WHERE
musicbrainz_id = :mb_id """), {"mb_id": mb_id})
row = result.fetchone()
if row:
return row[0]
return None
@staticmethod
def load_by_name(mb_id):
with db.engine.connect() as connection:
result = connection.execute(text(""" SELECT id, created, musicbrainz_id, auth_token \
FROM "user" \
WHERE musicbrainz_id = :mb_id """), {"mb_id": mb_id})
row = result.fetchone()
if row:
return User(row['id'], row['created'], row['musicbrainz_id'], row['auth_token'])
return None
@staticmethod
def load_by_id(serial):
with db.engine.connect() as connection:
result = connection.execute(text(""" SELECT id, created, musicbrainz_id, auth_token \
FROM "user"
WHERE id=:id """), {"id": serial})
row = result.fetchone()
if row:
return User(row['id'], row['created'], row['musicbrainz_id'], row['auth_token'])
return None
@staticmethod
def load_by_sessionkey(session_key, api_key):
with db.engine.connect() as connection:
result = connection.execute(text("""
SELECT "user".id
, "user".created
, "user".musicbrainz_id
, "user".auth_token
FROM api_compat.session, "user"
WHERE api_key = :api_key AND sid = :sk AND "user".id = session.user_id
"""), {
"api_key": api_key,
"sk": session_key
})
row = result.fetchone()
if row:
return User(row['id'], row['created'], row['musicbrainz_id'], row['auth_token'])
return None
@staticmethod
def get_play_count(user_id, listenstore):
""" Get playcount from the given user name.
"""
user = User.load_by_id(user_id)
return listenstore.get_listen_count_for_user(user.id)
|
metabrainz/listenbrainz-server
|
listenbrainz/db/lastfm_user.py
|
Python
|
gpl-2.0
| 2,716
|
/*
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __UNIT_H
#define __UNIT_H
#include "DBCStructure.h"
#include "EventProcessor.h"
#include "FollowerReference.h"
#include "FollowerRefManager.h"
#include "HostileRefManager.h"
#include "MotionMaster.h"
#include "Object.h"
#include "SpellAuraDefines.h"
#include "ThreatManager.h"
#define WORLD_TRIGGER 12999
enum SpellInterruptFlags
{
SPELL_INTERRUPT_FLAG_MOVEMENT = 0x01, // why need this for instant?
SPELL_INTERRUPT_FLAG_PUSH_BACK = 0x02, // push back
SPELL_INTERRUPT_FLAG_UNK3 = 0x04, // any info?
SPELL_INTERRUPT_FLAG_INTERRUPT = 0x08, // interrupt
SPELL_INTERRUPT_FLAG_ABORT_ON_DMG = 0x10 // _complete_ interrupt on direct damage
//SPELL_INTERRUPT_UNK = 0x20 // unk, 564 of 727 spells having this spell start with "Glyph"
};
// See SpellAuraInterruptFlags for other values definitions
enum SpellChannelInterruptFlags
{
CHANNEL_INTERRUPT_FLAG_INTERRUPT = 0x08, // interrupt
CHANNEL_FLAG_DELAY = 0x4000
};
enum SpellAuraInterruptFlags
{
AURA_INTERRUPT_FLAG_HITBYSPELL = 0x00000001, // 0 removed when getting hit by a negative spell?
AURA_INTERRUPT_FLAG_TAKE_DAMAGE = 0x00000002, // 1 removed by any damage
AURA_INTERRUPT_FLAG_CAST = 0x00000004, // 2 cast any spells
AURA_INTERRUPT_FLAG_MOVE = 0x00000008, // 3 removed by any movement
AURA_INTERRUPT_FLAG_TURNING = 0x00000010, // 4 removed by any turning
AURA_INTERRUPT_FLAG_JUMP = 0x00000020, // 5 removed by entering combat
AURA_INTERRUPT_FLAG_NOT_MOUNTED = 0x00000040, // 6 removed by dismounting
AURA_INTERRUPT_FLAG_NOT_ABOVEWATER = 0x00000080, // 7 removed by entering water
AURA_INTERRUPT_FLAG_NOT_UNDERWATER = 0x00000100, // 8 removed by leaving water
AURA_INTERRUPT_FLAG_NOT_SHEATHED = 0x00000200, // 9 removed by unsheathing
AURA_INTERRUPT_FLAG_TALK = 0x00000400, // 10 talk to npc / loot? action on creature
AURA_INTERRUPT_FLAG_USE = 0x00000800, // 11 mine/use/open action on gameobject
AURA_INTERRUPT_FLAG_MELEE_ATTACK = 0x00001000, // 12 removed by attacking
AURA_INTERRUPT_FLAG_SPELL_ATTACK = 0x00002000, // 13 ???
AURA_INTERRUPT_FLAG_UNK14 = 0x00004000, // 14
AURA_INTERRUPT_FLAG_TRANSFORM = 0x00008000, // 15 removed by transform?
AURA_INTERRUPT_FLAG_UNK16 = 0x00010000, // 16
AURA_INTERRUPT_FLAG_MOUNT = 0x00020000, // 17 misdirect, aspect, swim speed
AURA_INTERRUPT_FLAG_NOT_SEATED = 0x00040000, // 18 removed by standing up (used by food and drink mostly and sleep/Fake Death like)
AURA_INTERRUPT_FLAG_CHANGE_MAP = 0x00080000, // 19 leaving map/getting teleported
AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION = 0x00100000, // 20 removed by auras that make you invulnerable, or make other to lose selection on you
AURA_INTERRUPT_FLAG_UNK21 = 0x00200000, // 21
AURA_INTERRUPT_FLAG_TELEPORTED = 0x00400000, // 22
AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT = 0x00800000, // 23 removed by entering pvp combat
AURA_INTERRUPT_FLAG_DIRECT_DAMAGE = 0x01000000, // 24 removed by any direct damage
AURA_INTERRUPT_FLAG_LANDING = 0x02000000, // 25 removed by hitting the ground
AURA_INTERRUPT_FLAG_NOT_VICTIM = (AURA_INTERRUPT_FLAG_HITBYSPELL | AURA_INTERRUPT_FLAG_TAKE_DAMAGE | AURA_INTERRUPT_FLAG_DIRECT_DAMAGE)
};
enum SpellModOp
{
SPELLMOD_DAMAGE = 0,
SPELLMOD_DURATION = 1,
SPELLMOD_THREAT = 2,
SPELLMOD_EFFECT1 = 3,
SPELLMOD_CHARGES = 4,
SPELLMOD_RANGE = 5,
SPELLMOD_RADIUS = 6,
SPELLMOD_CRITICAL_CHANCE = 7,
SPELLMOD_ALL_EFFECTS = 8,
SPELLMOD_NOT_LOSE_CASTING_TIME = 9,
SPELLMOD_CASTING_TIME = 10,
SPELLMOD_COOLDOWN = 11,
SPELLMOD_EFFECT2 = 12,
SPELLMOD_IGNORE_ARMOR = 13,
SPELLMOD_COST = 14,
SPELLMOD_CRIT_DAMAGE_BONUS = 15,
SPELLMOD_RESIST_MISS_CHANCE = 16,
SPELLMOD_JUMP_TARGETS = 17,
SPELLMOD_CHANCE_OF_SUCCESS = 18,
SPELLMOD_ACTIVATION_TIME = 19,
SPELLMOD_DAMAGE_MULTIPLIER = 20,
SPELLMOD_GLOBAL_COOLDOWN = 21,
SPELLMOD_DOT = 22,
SPELLMOD_EFFECT3 = 23,
SPELLMOD_BONUS_MULTIPLIER = 24,
// spellmod 25
SPELLMOD_PROC_PER_MINUTE = 26,
SPELLMOD_VALUE_MULTIPLIER = 27,
SPELLMOD_RESIST_DISPEL_CHANCE = 28,
SPELLMOD_CRIT_DAMAGE_BONUS_2 = 29, //one not used spell
SPELLMOD_SPELL_COST_REFUND_ON_FAIL = 30
};
#define MAX_SPELLMOD 32
enum SpellValueMod
{
SPELLVALUE_BASE_POINT0,
SPELLVALUE_BASE_POINT1,
SPELLVALUE_BASE_POINT2,
SPELLVALUE_RADIUS_MOD,
SPELLVALUE_MAX_TARGETS,
SPELLVALUE_AURA_STACK
};
class CustomSpellValues
{
typedef std::pair<SpellValueMod, int32> CustomSpellValueMod;
typedef std::vector<CustomSpellValueMod> StorageType;
public:
typedef StorageType::const_iterator const_iterator;
public:
void AddSpellMod(SpellValueMod mod, int32 value)
{
storage_.push_back(CustomSpellValueMod(mod, value));
}
const_iterator begin() const
{
return storage_.begin();
}
const_iterator end() const
{
return storage_.end();
}
private:
StorageType storage_;
};
enum SpellFacingFlags
{
SPELL_FACING_FLAG_INFRONT = 0x0001
};
#define BASE_MINDAMAGE 1.0f
#define BASE_MAXDAMAGE 2.0f
#define BASE_ATTACK_TIME 2000
// byte value (UNIT_FIELD_BYTES_1, 0)
enum UnitStandStateType
{
UNIT_STAND_STATE_STAND = 0,
UNIT_STAND_STATE_SIT = 1,
UNIT_STAND_STATE_SIT_CHAIR = 2,
UNIT_STAND_STATE_SLEEP = 3,
UNIT_STAND_STATE_SIT_LOW_CHAIR = 4,
UNIT_STAND_STATE_SIT_MEDIUM_CHAIR = 5,
UNIT_STAND_STATE_SIT_HIGH_CHAIR = 6,
UNIT_STAND_STATE_DEAD = 7,
UNIT_STAND_STATE_KNEEL = 8,
UNIT_STAND_STATE_SUBMERGED = 9
};
// byte flag value (UNIT_FIELD_BYTES_1, 2)
enum UnitStandFlags
{
UNIT_STAND_FLAGS_UNK1 = 0x01,
UNIT_STAND_FLAGS_CREEP = 0x02,
UNIT_STAND_FLAGS_UNTRACKABLE = 0x04,
UNIT_STAND_FLAGS_UNK4 = 0x08,
UNIT_STAND_FLAGS_UNK5 = 0x10,
UNIT_STAND_FLAGS_ALL = 0xFF
};
// byte flags value (UNIT_FIELD_BYTES_1, 3)
enum UnitBytes1_Flags
{
UNIT_BYTE1_FLAG_ALWAYS_STAND = 0x01,
UNIT_BYTE1_FLAG_HOVER = 0x02,
UNIT_BYTE1_FLAG_UNK_3 = 0x04,
UNIT_BYTE1_FLAG_ALL = 0xFF
};
// high byte (3 from 0..3) of UNIT_FIELD_BYTES_2
enum ShapeshiftForm
{
FORM_NONE = 0x00,
FORM_CAT = 0x01,
FORM_TREE = 0x02,
FORM_TRAVEL = 0x03,
FORM_AQUA = 0x04,
FORM_BEAR = 0x05,
FORM_AMBIENT = 0x06,
FORM_GHOUL = 0x07,
FORM_DIREBEAR = 0x08,
FORM_STEVES_GHOUL = 0x09,
FORM_THARONJA_SKELETON = 0x0A,
FORM_TEST_OF_STRENGTH = 0x0B,
FORM_BLB_PLAYER = 0x0C,
FORM_SHADOW_DANCE = 0x0D,
FORM_CREATUREBEAR = 0x0E,
FORM_CREATURECAT = 0x0F,
FORM_GHOSTWOLF = 0x10,
FORM_BATTLESTANCE = 0x11,
FORM_DEFENSIVESTANCE = 0x12,
FORM_BERSERKERSTANCE = 0x13,
FORM_TEST = 0x14,
FORM_ZOMBIE = 0x15,
FORM_METAMORPHOSIS = 0x16,
FORM_UNDEAD = 0x19,
FORM_MASTER_ANGLER = 0x1A,
FORM_FLIGHT_EPIC = 0x1B,
FORM_SHADOW = 0x1C,
FORM_FLIGHT = 0x1D,
FORM_STEALTH = 0x1E,
FORM_MOONKIN = 0x1F,
FORM_SPIRITOFREDEMPTION = 0x20
};
// low byte (0 from 0..3) of UNIT_FIELD_BYTES_2
enum SheathState
{
SHEATH_STATE_UNARMED = 0, // non prepared weapon
SHEATH_STATE_MELEE = 1, // prepared melee weapon
SHEATH_STATE_RANGED = 2 // prepared ranged weapon
};
#define MAX_SHEATH_STATE 3
// byte (1 from 0..3) of UNIT_FIELD_BYTES_2
enum UnitPVPStateFlags
{
UNIT_BYTE2_FLAG_PVP = 0x01,
UNIT_BYTE2_FLAG_UNK1 = 0x02,
UNIT_BYTE2_FLAG_FFA_PVP = 0x04,
UNIT_BYTE2_FLAG_SANCTUARY = 0x08,
UNIT_BYTE2_FLAG_UNK4 = 0x10,
UNIT_BYTE2_FLAG_UNK5 = 0x20,
UNIT_BYTE2_FLAG_UNK6 = 0x40,
UNIT_BYTE2_FLAG_UNK7 = 0x80
};
// byte (2 from 0..3) of UNIT_FIELD_BYTES_2
enum UnitRename
{
UNIT_CAN_BE_RENAMED = 0x01,
UNIT_CAN_BE_ABANDONED = 0x02
};
#define CREATURE_MAX_SPELLS 8
#define MAX_SPELL_CHARM 4
#define MAX_SPELL_VEHICLE 6
#define MAX_SPELL_POSSESS 8
#define MAX_SPELL_CONTROL_BAR 10
#define MAX_AGGRO_RESET_TIME 10 // in seconds
#define MAX_AGGRO_RADIUS 45.0f // yards
enum Swing
{
NOSWING = 0,
SINGLEHANDEDSWING = 1,
TWOHANDEDSWING = 2
};
enum VictimState
{
VICTIMSTATE_INTACT = 0, // set when attacker misses
VICTIMSTATE_HIT = 1, // victim got clear/blocked hit
VICTIMSTATE_DODGE = 2,
VICTIMSTATE_PARRY = 3,
VICTIMSTATE_INTERRUPT = 4,
VICTIMSTATE_BLOCKS = 5, // unused? not set when blocked, even on full block
VICTIMSTATE_EVADES = 6,
VICTIMSTATE_IS_IMMUNE = 7,
VICTIMSTATE_DEFLECTS = 8
};
enum HitInfo
{
HITINFO_NORMALSWING = 0x00000000,
HITINFO_UNK1 = 0x00000001, // req correct packet structure
HITINFO_AFFECTS_VICTIM = 0x00000002,
HITINFO_OFFHAND = 0x00000004,
HITINFO_UNK2 = 0x00000008,
HITINFO_MISS = 0x00000010,
HITINFO_FULL_ABSORB = 0x00000020,
HITINFO_PARTIAL_ABSORB = 0x00000040,
HITINFO_FULL_RESIST = 0x00000080,
HITINFO_PARTIAL_RESIST = 0x00000100,
HITINFO_CRITICALHIT = 0x00000200, // critical hit
// 0x00000400
// 0x00000800
// 0x00001000
HITINFO_BLOCK = 0x00002000, // blocked damage
// 0x00004000 // Hides worldtext for 0 damage
// 0x00008000 // Related to blood visual
HITINFO_GLANCING = 0x00010000,
HITINFO_CRUSHING = 0x00020000,
HITINFO_NO_ANIMATION = 0x00040000,
// 0x00080000
// 0x00100000
HITINFO_SWINGNOHITSOUND = 0x00200000, // unused?
// 0x00400000
HITINFO_RAGE_GAIN = 0x00800000
};
//i would like to remove this: (it is defined in item.h
enum InventorySlot
{
NULL_BAG = 0,
NULL_SLOT = 255
};
struct FactionTemplateEntry;
struct SpellValue;
class AuraApplication;
class Aura;
class UnitAura;
class AuraEffect;
class Creature;
class Spell;
class SpellInfo;
class DynamicObject;
class GameObject;
class Item;
class Pet;
class PetAura;
class Minion;
class Guardian;
class UnitAI;
class Totem;
class Transport;
class Vehicle;
class VehicleJoinEvent;
class TransportBase;
class SpellCastTargets;
typedef std::list<Unit*> UnitList;
typedef std::list< std::pair<Aura*, uint8> > DispelChargesList;
struct SpellImmune
{
uint32 type;
uint32 spellId;
};
typedef std::list<SpellImmune> SpellImmuneList;
enum UnitModifierType
{
BASE_VALUE = 0,
BASE_PCT = 1,
TOTAL_VALUE = 2,
TOTAL_PCT = 3,
MODIFIER_TYPE_END = 4
};
enum WeaponDamageRange
{
MINDAMAGE,
MAXDAMAGE
};
enum DamageTypeToSchool
{
RESISTANCE,
DAMAGE_DEALT,
DAMAGE_TAKEN
};
enum AuraRemoveMode
{
AURA_REMOVE_NONE = 0,
AURA_REMOVE_BY_DEFAULT = 1, // scripted remove, remove by stack with aura with different ids and sc aura remove
AURA_REMOVE_BY_CANCEL,
AURA_REMOVE_BY_ENEMY_SPELL, // dispel and absorb aura destroy
AURA_REMOVE_BY_EXPIRE, // aura duration has ended
AURA_REMOVE_BY_DEATH
};
enum TriggerCastFlags
{
TRIGGERED_NONE = 0x00000000, //! Not triggered
TRIGGERED_IGNORE_GCD = 0x00000001, //! Will ignore GCD
TRIGGERED_IGNORE_SPELL_AND_CATEGORY_CD = 0x00000002, //! Will ignore Spell and Category cooldowns
TRIGGERED_IGNORE_POWER_AND_REAGENT_COST = 0x00000004, //! Will ignore power and reagent cost
TRIGGERED_IGNORE_CAST_ITEM = 0x00000008, //! Will not take away cast item or update related achievement criteria
TRIGGERED_IGNORE_AURA_SCALING = 0x00000010, //! Will ignore aura scaling
TRIGGERED_IGNORE_CAST_IN_PROGRESS = 0x00000020, //! Will not check if a current cast is in progress
TRIGGERED_IGNORE_COMBO_POINTS = 0x00000040, //! Will ignore combo point requirement
TRIGGERED_CAST_DIRECTLY = 0x00000080, //! In Spell::prepare, will be cast directly without setting containers for executed spell
TRIGGERED_IGNORE_AURA_INTERRUPT_FLAGS = 0x00000100, //! Will ignore interruptible aura's at cast
TRIGGERED_IGNORE_SET_FACING = 0x00000200, //! Will not adjust facing to target (if any)
TRIGGERED_IGNORE_SHAPESHIFT = 0x00000400, //! Will ignore shapeshift checks
TRIGGERED_IGNORE_CASTER_AURASTATE = 0x00000800, //! Will ignore caster aura states including combat requirements and death state
TRIGGERED_IGNORE_CASTER_MOUNTED_OR_ON_VEHICLE = 0x00002000, //! Will ignore mounted/on vehicle restrictions
TRIGGERED_IGNORE_CASTER_AURAS = 0x00010000, //! Will ignore caster aura restrictions or requirements
TRIGGERED_DISALLOW_PROC_EVENTS = 0x00020000, //! Disallows proc events from triggered spell (default)
TRIGGERED_DONT_REPORT_CAST_ERROR = 0x00040000, //! Will return SPELL_FAILED_DONT_REPORT in CheckCast functions
TRIGGERED_IGNORE_EQUIPPED_ITEM_REQUIREMENT = 0x00080000, //! Will ignore equipped item requirements
TRIGGERED_FULL_MASK = 0xFFFFFFFF
};
enum UnitMods
{
UNIT_MOD_STAT_STRENGTH, // UNIT_MOD_STAT_STRENGTH..UNIT_MOD_STAT_SPIRIT must be in existed order, it's accessed by index values of Stats enum.
UNIT_MOD_STAT_AGILITY,
UNIT_MOD_STAT_STAMINA,
UNIT_MOD_STAT_INTELLECT,
UNIT_MOD_STAT_SPIRIT,
UNIT_MOD_HEALTH,
UNIT_MOD_MANA, // UNIT_MOD_MANA..UNIT_MOD_RUNIC_POWER must be in existed order, it's accessed by index values of Powers enum.
UNIT_MOD_RAGE,
UNIT_MOD_FOCUS,
UNIT_MOD_ENERGY,
UNIT_MOD_HAPPINESS,
UNIT_MOD_RUNE,
UNIT_MOD_RUNIC_POWER,
UNIT_MOD_ARMOR, // UNIT_MOD_ARMOR..UNIT_MOD_RESISTANCE_ARCANE must be in existed order, it's accessed by index values of SpellSchools enum.
UNIT_MOD_RESISTANCE_HOLY,
UNIT_MOD_RESISTANCE_FIRE,
UNIT_MOD_RESISTANCE_NATURE,
UNIT_MOD_RESISTANCE_FROST,
UNIT_MOD_RESISTANCE_SHADOW,
UNIT_MOD_RESISTANCE_ARCANE,
UNIT_MOD_ATTACK_POWER,
UNIT_MOD_ATTACK_POWER_RANGED,
UNIT_MOD_DAMAGE_MAINHAND,
UNIT_MOD_DAMAGE_OFFHAND,
UNIT_MOD_DAMAGE_RANGED,
UNIT_MOD_END,
// synonyms
UNIT_MOD_STAT_START = UNIT_MOD_STAT_STRENGTH,
UNIT_MOD_STAT_END = UNIT_MOD_STAT_SPIRIT + 1,
UNIT_MOD_RESISTANCE_START = UNIT_MOD_ARMOR,
UNIT_MOD_RESISTANCE_END = UNIT_MOD_RESISTANCE_ARCANE + 1,
UNIT_MOD_POWER_START = UNIT_MOD_MANA,
UNIT_MOD_POWER_END = UNIT_MOD_RUNIC_POWER + 1
};
enum BaseModGroup
{
CRIT_PERCENTAGE,
RANGED_CRIT_PERCENTAGE,
OFFHAND_CRIT_PERCENTAGE,
SHIELD_BLOCK_VALUE,
BASEMOD_END
};
enum BaseModType
{
FLAT_MOD,
PCT_MOD,
MOD_END
};
enum DeathState
{
ALIVE = 0,
JUST_DIED = 1,
CORPSE = 2,
DEAD = 3,
JUST_RESPAWNED = 4
};
enum UnitState
{
UNIT_STATE_DIED = 0x00000001, // player has fake death aura
UNIT_STATE_MELEE_ATTACKING = 0x00000002, // player is melee attacking someone
//UNIT_STATE_MELEE_ATTACK_BY = 0x00000004, // player is melee attack by someone
UNIT_STATE_STUNNED = 0x00000008,
UNIT_STATE_ROAMING = 0x00000010,
UNIT_STATE_CHASE = 0x00000020,
//UNIT_STATE_SEARCHING = 0x00000040,
UNIT_STATE_FLEEING = 0x00000080,
UNIT_STATE_IN_FLIGHT = 0x00000100, // player is in flight mode
UNIT_STATE_FOLLOW = 0x00000200,
UNIT_STATE_ROOT = 0x00000400,
UNIT_STATE_CONFUSED = 0x00000800,
UNIT_STATE_DISTRACTED = 0x00001000,
UNIT_STATE_ISOLATED = 0x00002000, // area auras do not affect other players
UNIT_STATE_ATTACK_PLAYER = 0x00004000,
UNIT_STATE_CASTING = 0x00008000,
UNIT_STATE_POSSESSED = 0x00010000,
UNIT_STATE_CHARGING = 0x00020000,
UNIT_STATE_JUMPING = 0x00040000,
UNIT_STATE_MOVE = 0x00100000,
UNIT_STATE_ROTATING = 0x00200000,
UNIT_STATE_EVADE = 0x00400000,
UNIT_STATE_ROAMING_MOVE = 0x00800000,
UNIT_STATE_CONFUSED_MOVE = 0x01000000,
UNIT_STATE_FLEEING_MOVE = 0x02000000,
UNIT_STATE_CHASE_MOVE = 0x04000000,
UNIT_STATE_FOLLOW_MOVE = 0x08000000,
UNIT_STATE_IGNORE_PATHFINDING = 0x10000000, // do not use pathfinding in any MovementGenerator
UNIT_STATE_UNATTACKABLE = UNIT_STATE_IN_FLIGHT,
// for real move using movegen check and stop (except unstoppable flight)
UNIT_STATE_MOVING = UNIT_STATE_ROAMING_MOVE | UNIT_STATE_CONFUSED_MOVE | UNIT_STATE_FLEEING_MOVE | UNIT_STATE_CHASE_MOVE | UNIT_STATE_FOLLOW_MOVE,
UNIT_STATE_CONTROLLED = (UNIT_STATE_CONFUSED | UNIT_STATE_STUNNED | UNIT_STATE_FLEEING),
UNIT_STATE_LOST_CONTROL = (UNIT_STATE_CONTROLLED | UNIT_STATE_JUMPING | UNIT_STATE_CHARGING),
UNIT_STATE_SIGHTLESS = (UNIT_STATE_LOST_CONTROL | UNIT_STATE_EVADE),
UNIT_STATE_CANNOT_AUTOATTACK = (UNIT_STATE_LOST_CONTROL | UNIT_STATE_CASTING),
UNIT_STATE_CANNOT_TURN = (UNIT_STATE_LOST_CONTROL | UNIT_STATE_ROTATING),
// stay by different reasons
UNIT_STATE_NOT_MOVE = UNIT_STATE_ROOT | UNIT_STATE_STUNNED | UNIT_STATE_DIED | UNIT_STATE_DISTRACTED,
UNIT_STATE_ALL_STATE = 0xffffffff //(UNIT_STATE_STOPPED | UNIT_STATE_MOVING | UNIT_STATE_IN_COMBAT | UNIT_STATE_IN_FLIGHT)
};
enum UnitMoveType
{
MOVE_WALK = 0,
MOVE_RUN = 1,
MOVE_RUN_BACK = 2,
MOVE_SWIM = 3,
MOVE_SWIM_BACK = 4,
MOVE_TURN_RATE = 5,
MOVE_FLIGHT = 6,
MOVE_FLIGHT_BACK = 7,
MOVE_PITCH_RATE = 8
};
#define MAX_MOVE_TYPE 9
extern float baseMoveSpeed[MAX_MOVE_TYPE];
extern float playerBaseMoveSpeed[MAX_MOVE_TYPE];
enum WeaponAttackType
{
BASE_ATTACK = 0,
OFF_ATTACK = 1,
RANGED_ATTACK = 2,
MAX_ATTACK
};
enum CombatRating
{
CR_WEAPON_SKILL = 0,
CR_DEFENSE_SKILL = 1,
CR_DODGE = 2,
CR_PARRY = 3,
CR_BLOCK = 4,
CR_HIT_MELEE = 5,
CR_HIT_RANGED = 6,
CR_HIT_SPELL = 7,
CR_CRIT_MELEE = 8,
CR_CRIT_RANGED = 9,
CR_CRIT_SPELL = 10,
CR_HIT_TAKEN_MELEE = 11,
CR_HIT_TAKEN_RANGED = 12,
CR_HIT_TAKEN_SPELL = 13,
CR_CRIT_TAKEN_MELEE = 14,
CR_CRIT_TAKEN_RANGED = 15,
CR_CRIT_TAKEN_SPELL = 16,
CR_HASTE_MELEE = 17,
CR_HASTE_RANGED = 18,
CR_HASTE_SPELL = 19,
CR_WEAPON_SKILL_MAINHAND = 20,
CR_WEAPON_SKILL_OFFHAND = 21,
CR_WEAPON_SKILL_RANGED = 22,
CR_EXPERTISE = 23,
CR_ARMOR_PENETRATION = 24
};
#define MAX_COMBAT_RATING 25
enum DamageEffectType
{
DIRECT_DAMAGE = 0, // used for normal weapon damage (not for class abilities or spells)
SPELL_DIRECT_DAMAGE = 1, // spell/class abilities damage
DOT = 2,
HEAL = 3,
NODAMAGE = 4, // used also in case when damage applied to health but not applied to spell channelInterruptFlags/etc
SELF_DAMAGE = 5
};
// Value masks for UNIT_FIELD_FLAGS
enum UnitFlags
{
UNIT_FLAG_SERVER_CONTROLLED = 0x00000001, // set only when unit movement is controlled by server - by SPLINE/MONSTER_MOVE packets, together with UNIT_FLAG_STUNNED; only set to units controlled by client; client function CGUnit_C::IsClientControlled returns false when set for owner
UNIT_FLAG_NON_ATTACKABLE = 0x00000002, // not attackable
UNIT_FLAG_DISABLE_MOVE = 0x00000004,
UNIT_FLAG_PVP_ATTACKABLE = 0x00000008, // allow apply pvp rules to attackable state in addition to faction dependent state
UNIT_FLAG_RENAME = 0x00000010,
UNIT_FLAG_PREPARATION = 0x00000020, // don't take reagents for spells with SPELL_ATTR5_NO_REAGENT_WHILE_PREP
UNIT_FLAG_UNK_6 = 0x00000040,
UNIT_FLAG_NOT_ATTACKABLE_1 = 0x00000080, // ?? (UNIT_FLAG_PVP_ATTACKABLE | UNIT_FLAG_NOT_ATTACKABLE_1) is NON_PVP_ATTACKABLE
UNIT_FLAG_IMMUNE_TO_PC = 0x00000100, // disables combat/assistance with PlayerCharacters (PC) - see Unit::_IsValidAttackTarget, Unit::_IsValidAssistTarget
UNIT_FLAG_IMMUNE_TO_NPC = 0x00000200, // disables combat/assistance with NonPlayerCharacters (NPC) - see Unit::_IsValidAttackTarget, Unit::_IsValidAssistTarget
UNIT_FLAG_LOOTING = 0x00000400, // loot animation
UNIT_FLAG_PET_IN_COMBAT = 0x00000800, // in combat?, 2.0.8
UNIT_FLAG_PVP = 0x00001000, // changed in 3.0.3
UNIT_FLAG_SILENCED = 0x00002000, // silenced, 2.1.1
UNIT_FLAG_UNK_14 = 0x00004000, // 2.0.8
UNIT_FLAG_UNK_15 = 0x00008000,
UNIT_FLAG_UNK_16 = 0x00010000,
UNIT_FLAG_PACIFIED = 0x00020000, // 3.0.3 ok
UNIT_FLAG_STUNNED = 0x00040000, // 3.0.3 ok
UNIT_FLAG_IN_COMBAT = 0x00080000,
UNIT_FLAG_TAXI_FLIGHT = 0x00100000, // disable casting at client side spell not allowed by taxi flight (mounted?), probably used with 0x4 flag
UNIT_FLAG_DISARMED = 0x00200000, // 3.0.3, disable melee spells casting..., "Required melee weapon" added to melee spells tooltip.
UNIT_FLAG_CONFUSED = 0x00400000,
UNIT_FLAG_FLEEING = 0x00800000,
UNIT_FLAG_PLAYER_CONTROLLED = 0x01000000, // used in spell Eyes of the Beast for pet... let attack by controlled creature
UNIT_FLAG_NOT_SELECTABLE = 0x02000000,
UNIT_FLAG_SKINNABLE = 0x04000000,
UNIT_FLAG_MOUNT = 0x08000000,
UNIT_FLAG_UNK_28 = 0x10000000,
UNIT_FLAG_UNK_29 = 0x20000000, // used in Feing Death spell
UNIT_FLAG_SHEATHE = 0x40000000,
UNIT_FLAG_UNK_31 = 0x80000000,
MAX_UNIT_FLAGS = 33
};
// Value masks for UNIT_FIELD_FLAGS_2
enum UnitFlags2
{
UNIT_FLAG2_FEIGN_DEATH = 0x00000001,
UNIT_FLAG2_UNK1 = 0x00000002, // Hide unit model (show only player equip)
UNIT_FLAG2_IGNORE_REPUTATION = 0x00000004,
UNIT_FLAG2_COMPREHEND_LANG = 0x00000008,
UNIT_FLAG2_MIRROR_IMAGE = 0x00000010,
UNIT_FLAG2_INSTANTLY_APPEAR_MODEL = 0x00000020, // Unit model instantly appears when summoned (does not fade in)
UNIT_FLAG2_FORCE_MOVEMENT = 0x00000040,
UNIT_FLAG2_DISARM_OFFHAND = 0x00000080,
UNIT_FLAG2_DISABLE_PRED_STATS = 0x00000100, // Player has disabled predicted stats (Used by raid frames)
UNIT_FLAG2_DISARM_RANGED = 0x00000400, // this does not disable ranged weapon display (maybe additional flag needed?)
UNIT_FLAG2_REGENERATE_POWER = 0x00000800,
UNIT_FLAG2_RESTRICT_PARTY_INTERACTION = 0x00001000, // Restrict interaction to party or raid
UNIT_FLAG2_PREVENT_SPELL_CLICK = 0x00002000, // Prevent spellclick
UNIT_FLAG2_ALLOW_ENEMY_INTERACT = 0x00004000,
UNIT_FLAG2_DISABLE_TURN = 0x00008000,
UNIT_FLAG2_UNK2 = 0x00010000,
UNIT_FLAG2_PLAY_DEATH_ANIM = 0x00020000, // Plays special death animation upon death
UNIT_FLAG2_ALLOW_CHEAT_SPELLS = 0x00040000 // Allows casting spells with AttributesEx7 & SPELL_ATTR7_IS_CHEAT_SPELL
};
/// Non Player Character flags
enum NPCFlags
{
UNIT_NPC_FLAG_NONE = 0x00000000,
UNIT_NPC_FLAG_GOSSIP = 0x00000001, // 100%
UNIT_NPC_FLAG_QUESTGIVER = 0x00000002, // guessed, probably ok
UNIT_NPC_FLAG_UNK1 = 0x00000004,
UNIT_NPC_FLAG_UNK2 = 0x00000008,
UNIT_NPC_FLAG_TRAINER = 0x00000010, // 100%
UNIT_NPC_FLAG_TRAINER_CLASS = 0x00000020, // 100%
UNIT_NPC_FLAG_TRAINER_PROFESSION = 0x00000040, // 100%
UNIT_NPC_FLAG_VENDOR = 0x00000080, // 100%
UNIT_NPC_FLAG_VENDOR_AMMO = 0x00000100, // 100%, general goods vendor
UNIT_NPC_FLAG_VENDOR_FOOD = 0x00000200, // 100%
UNIT_NPC_FLAG_VENDOR_POISON = 0x00000400, // guessed
UNIT_NPC_FLAG_VENDOR_REAGENT = 0x00000800, // 100%
UNIT_NPC_FLAG_REPAIR = 0x00001000, // 100%
UNIT_NPC_FLAG_FLIGHTMASTER = 0x00002000, // 100%
UNIT_NPC_FLAG_SPIRITHEALER = 0x00004000, // guessed
UNIT_NPC_FLAG_SPIRITGUIDE = 0x00008000, // guessed
UNIT_NPC_FLAG_INNKEEPER = 0x00010000, // 100%
UNIT_NPC_FLAG_BANKER = 0x00020000, // 100%
UNIT_NPC_FLAG_PETITIONER = 0x00040000, // 100% 0xC0000 = guild petitions, 0x40000 = arena team petitions
UNIT_NPC_FLAG_TABARDDESIGNER = 0x00080000, // 100%
UNIT_NPC_FLAG_BATTLEMASTER = 0x00100000, // 100%
UNIT_NPC_FLAG_AUCTIONEER = 0x00200000, // 100%
UNIT_NPC_FLAG_STABLEMASTER = 0x00400000, // 100%
UNIT_NPC_FLAG_GUILD_BANKER = 0x00800000, // cause client to send 997 opcode
UNIT_NPC_FLAG_SPELLCLICK = 0x01000000, // cause client to send 1015 opcode (spell click)
UNIT_NPC_FLAG_PLAYER_VEHICLE = 0x02000000 // players with mounts that have vehicle data should have it set
};
enum MovementFlags
{
MOVEMENTFLAG_NONE = 0x00000000,
MOVEMENTFLAG_FORWARD = 0x00000001,
MOVEMENTFLAG_BACKWARD = 0x00000002,
MOVEMENTFLAG_STRAFE_LEFT = 0x00000004,
MOVEMENTFLAG_STRAFE_RIGHT = 0x00000008,
MOVEMENTFLAG_LEFT = 0x00000010,
MOVEMENTFLAG_RIGHT = 0x00000020,
MOVEMENTFLAG_PITCH_UP = 0x00000040,
MOVEMENTFLAG_PITCH_DOWN = 0x00000080,
MOVEMENTFLAG_WALKING = 0x00000100, // Walking
MOVEMENTFLAG_ONTRANSPORT = 0x00000200, // Used for flying on some creatures
MOVEMENTFLAG_DISABLE_GRAVITY = 0x00000400, // Former MOVEMENTFLAG_LEVITATING. This is used when walking is not possible.
MOVEMENTFLAG_ROOT = 0x00000800, // Must not be set along with MOVEMENTFLAG_MASK_MOVING
MOVEMENTFLAG_FALLING = 0x00001000, // damage dealt on that type of falling
MOVEMENTFLAG_FALLING_FAR = 0x00002000,
MOVEMENTFLAG_PENDING_STOP = 0x00004000,
MOVEMENTFLAG_PENDING_STRAFE_STOP = 0x00008000,
MOVEMENTFLAG_PENDING_FORWARD = 0x00010000,
MOVEMENTFLAG_PENDING_BACKWARD = 0x00020000,
MOVEMENTFLAG_PENDING_STRAFE_LEFT = 0x00040000,
MOVEMENTFLAG_PENDING_STRAFE_RIGHT = 0x00080000,
MOVEMENTFLAG_PENDING_ROOT = 0x00100000,
MOVEMENTFLAG_SWIMMING = 0x00200000, // appears with fly flag also
MOVEMENTFLAG_ASCENDING = 0x00400000, // press "space" when flying
MOVEMENTFLAG_DESCENDING = 0x00800000,
MOVEMENTFLAG_CAN_FLY = 0x01000000, // Appears when unit can fly AND also walk
MOVEMENTFLAG_FLYING = 0x02000000, // unit is actually flying. pretty sure this is only used for players. creatures use disable_gravity
MOVEMENTFLAG_SPLINE_ELEVATION = 0x04000000, // used for flight paths
MOVEMENTFLAG_SPLINE_ENABLED = 0x08000000, // used for flight paths
MOVEMENTFLAG_WATERWALKING = 0x10000000, // prevent unit from falling through water
MOVEMENTFLAG_FALLING_SLOW = 0x20000000, // active rogue safe fall spell (passive)
MOVEMENTFLAG_HOVER = 0x40000000, // hover, cannot jump
/// @todo Check if PITCH_UP and PITCH_DOWN really belong here..
MOVEMENTFLAG_MASK_MOVING =
MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_BACKWARD | MOVEMENTFLAG_STRAFE_LEFT | MOVEMENTFLAG_STRAFE_RIGHT |
MOVEMENTFLAG_PITCH_UP | MOVEMENTFLAG_PITCH_DOWN | MOVEMENTFLAG_FALLING | MOVEMENTFLAG_FALLING_FAR | MOVEMENTFLAG_ASCENDING | MOVEMENTFLAG_DESCENDING |
MOVEMENTFLAG_SPLINE_ELEVATION,
MOVEMENTFLAG_MASK_TURNING =
MOVEMENTFLAG_LEFT | MOVEMENTFLAG_RIGHT,
MOVEMENTFLAG_MASK_MOVING_FLY =
MOVEMENTFLAG_FLYING | MOVEMENTFLAG_ASCENDING | MOVEMENTFLAG_DESCENDING,
/// @todo if needed: add more flags to this masks that are exclusive to players
MOVEMENTFLAG_MASK_PLAYER_ONLY =
MOVEMENTFLAG_FLYING,
/// Movement flags that have change status opcodes associated for players
MOVEMENTFLAG_MASK_HAS_PLAYER_STATUS_OPCODE = MOVEMENTFLAG_DISABLE_GRAVITY | MOVEMENTFLAG_ROOT |
MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_WATERWALKING | MOVEMENTFLAG_FALLING_SLOW | MOVEMENTFLAG_HOVER
};
enum MovementFlags2
{
MOVEMENTFLAG2_NONE = 0x00000000,
MOVEMENTFLAG2_NO_STRAFE = 0x00000001,
MOVEMENTFLAG2_NO_JUMPING = 0x00000002,
MOVEMENTFLAG2_UNK3 = 0x00000004, // Overrides various clientside checks
MOVEMENTFLAG2_FULL_SPEED_TURNING = 0x00000008,
MOVEMENTFLAG2_FULL_SPEED_PITCHING = 0x00000010,
MOVEMENTFLAG2_ALWAYS_ALLOW_PITCHING = 0x00000020,
MOVEMENTFLAG2_UNK7 = 0x00000040,
MOVEMENTFLAG2_UNK8 = 0x00000080,
MOVEMENTFLAG2_UNK9 = 0x00000100,
MOVEMENTFLAG2_UNK10 = 0x00000200,
MOVEMENTFLAG2_INTERPOLATED_MOVEMENT = 0x00000400,
MOVEMENTFLAG2_INTERPOLATED_TURNING = 0x00000800,
MOVEMENTFLAG2_INTERPOLATED_PITCHING = 0x00001000,
MOVEMENTFLAG2_UNK14 = 0x00002000,
MOVEMENTFLAG2_UNK15 = 0x00004000,
MOVEMENTFLAG2_UNK16 = 0x00008000
};
enum UnitTypeMask
{
UNIT_MASK_NONE = 0x00000000,
UNIT_MASK_SUMMON = 0x00000001,
UNIT_MASK_MINION = 0x00000002,
UNIT_MASK_GUARDIAN = 0x00000004,
UNIT_MASK_TOTEM = 0x00000008,
UNIT_MASK_PET = 0x00000010,
UNIT_MASK_VEHICLE = 0x00000020,
UNIT_MASK_PUPPET = 0x00000040,
UNIT_MASK_HUNTER_PET = 0x00000080,
UNIT_MASK_CONTROLABLE_GUARDIAN = 0x00000100,
UNIT_MASK_ACCESSORY = 0x00000200
};
namespace Movement{
class MoveSpline;
}
struct DiminishingReturn
{
DiminishingReturn(DiminishingGroup group, uint32 t, uint32 count)
: DRGroup(group), stack(0), hitTime(t), hitCount(count)
{}
DiminishingGroup DRGroup:16;
uint16 stack:16;
uint32 hitTime;
uint32 hitCount;
};
enum MeleeHitOutcome
{
MELEE_HIT_EVADE, MELEE_HIT_MISS, MELEE_HIT_DODGE, MELEE_HIT_BLOCK, MELEE_HIT_PARRY,
MELEE_HIT_GLANCING, MELEE_HIT_CRIT, MELEE_HIT_CRUSHING, MELEE_HIT_NORMAL
};
class DispelInfo
{
public:
explicit DispelInfo(Unit* dispeller, uint32 dispellerSpellId, uint8 chargesRemoved) :
_dispellerUnit(dispeller), _dispellerSpell(dispellerSpellId), _chargesRemoved(chargesRemoved) {}
Unit* GetDispeller() const { return _dispellerUnit; }
uint32 GetDispellerSpellId() const { return _dispellerSpell; }
uint8 GetRemovedCharges() const { return _chargesRemoved; }
void SetRemovedCharges(uint8 amount)
{
_chargesRemoved = amount;
}
private:
Unit* _dispellerUnit;
uint32 _dispellerSpell;
uint8 _chargesRemoved;
};
struct CleanDamage
{
CleanDamage(uint32 mitigated, uint32 absorbed, WeaponAttackType _attackType, MeleeHitOutcome _hitOutCome) :
absorbed_damage(absorbed), mitigated_damage(mitigated), attackType(_attackType), hitOutCome(_hitOutCome) {}
uint32 absorbed_damage;
uint32 mitigated_damage;
WeaponAttackType attackType;
MeleeHitOutcome hitOutCome;
};
struct CalcDamageInfo;
class DamageInfo
{
private:
Unit* const m_attacker;
Unit* const m_victim;
uint32 m_damage;
SpellInfo const* const m_spellInfo;
SpellSchoolMask const m_schoolMask;
DamageEffectType const m_damageType;
WeaponAttackType m_attackType;
uint32 m_absorb;
uint32 m_resist;
uint32 m_block;
public:
explicit DamageInfo(Unit* _attacker, Unit* _victim, uint32 _damage, SpellInfo const* _spellInfo, SpellSchoolMask _schoolMask, DamageEffectType _damageType);
explicit DamageInfo(CalcDamageInfo& dmgInfo);
void ModifyDamage(int32 amount);
void AbsorbDamage(uint32 amount);
void ResistDamage(uint32 amount);
void BlockDamage(uint32 amount);
Unit* GetAttacker() const { return m_attacker; }
Unit* GetVictim() const { return m_victim; }
SpellInfo const* GetSpellInfo() const { return m_spellInfo; }
SpellSchoolMask GetSchoolMask() const { return m_schoolMask; }
DamageEffectType GetDamageType() const { return m_damageType; }
WeaponAttackType GetAttackType() const { return m_attackType; }
uint32 GetDamage() const { return m_damage; }
uint32 GetAbsorb() const { return m_absorb; }
uint32 GetResist() const { return m_resist; }
uint32 GetBlock() const { return m_block; }
};
class HealInfo
{
private:
uint32 m_heal;
uint32 m_absorb;
public:
explicit HealInfo(uint32 heal)
: m_heal(heal)
{
m_absorb = 0;
}
void AbsorbHeal(uint32 amount)
{
amount = std::min(amount, GetHeal());
m_absorb += amount;
m_heal -= amount;
}
uint32 GetHeal() const { return m_heal; }
};
class ProcEventInfo
{
public:
ProcEventInfo(Unit* actor, Unit* actionTarget, Unit* procTarget, uint32 typeMask,
uint32 spellTypeMask, uint32 spellPhaseMask, uint32 hitMask,
Spell* spell, DamageInfo* damageInfo, HealInfo* healInfo);
Unit* GetActor() { return _actor; }
Unit* GetActionTarget() const { return _actionTarget; }
Unit* GetProcTarget() const { return _procTarget; }
uint32 GetTypeMask() const { return _typeMask; }
uint32 GetSpellTypeMask() const { return _spellTypeMask; }
uint32 GetSpellPhaseMask() const { return _spellPhaseMask; }
uint32 GetHitMask() const { return _hitMask; }
SpellInfo const* GetSpellInfo() const { return NULL; }
SpellSchoolMask GetSchoolMask() const { return SPELL_SCHOOL_MASK_NONE; }
DamageInfo* GetDamageInfo() const { return _damageInfo; }
HealInfo* GetHealInfo() const { return _healInfo; }
private:
Unit* const _actor;
Unit* const _actionTarget;
Unit* const _procTarget;
uint32 _typeMask;
uint32 _spellTypeMask;
uint32 _spellPhaseMask;
uint32 _hitMask;
Spell* _spell;
DamageInfo* _damageInfo;
HealInfo* _healInfo;
};
// Struct for use in Unit::CalculateMeleeDamage
// Need create structure like in SMSG_ATTACKERSTATEUPDATE opcode
struct CalcDamageInfo
{
Unit *attacker; // Attacker
Unit *target; // Target for damage
uint32 damageSchoolMask;
uint32 damage;
uint32 absorb;
uint32 resist;
uint32 blocked_amount;
uint32 HitInfo;
uint32 TargetState;
// Helper
WeaponAttackType attackType; //
uint32 procAttacker;
uint32 procVictim;
uint32 procEx;
uint32 cleanDamage; // Used only for rage calculation
MeleeHitOutcome hitOutCome; /// @todo remove this field (need use TargetState)
};
// Spell damage info structure based on structure sending in SMSG_SPELLNONMELEEDAMAGELOG opcode
struct SpellNonMeleeDamage
{
SpellNonMeleeDamage(Unit* _attacker, Unit* _target, uint32 _SpellID, uint32 _schoolMask)
: target(_target), attacker(_attacker), SpellID(_SpellID), damage(0), overkill(0), schoolMask(_schoolMask),
absorb(0), resist(0), physicalLog(false), unused(false), blocked(0), HitInfo(0), cleanDamage(0)
{}
Unit *target;
Unit *attacker;
uint32 SpellID;
uint32 damage;
uint32 overkill;
uint32 schoolMask;
uint32 absorb;
uint32 resist;
bool physicalLog;
bool unused;
uint32 blocked;
uint32 HitInfo;
// Used for help
uint32 cleanDamage;
};
struct SpellPeriodicAuraLogInfo
{
SpellPeriodicAuraLogInfo(AuraEffect const* _auraEff, uint32 _damage, uint32 _overDamage, uint32 _absorb, uint32 _resist, float _multiplier, bool _critical)
: auraEff(_auraEff), damage(_damage), overDamage(_overDamage), absorb(_absorb), resist(_resist), multiplier(_multiplier), critical(_critical){}
AuraEffect const* auraEff;
uint32 damage;
uint32 overDamage; // overkill/overheal
uint32 absorb;
uint32 resist;
float multiplier;
bool critical;
};
uint32 createProcExtendMask(SpellNonMeleeDamage* damageInfo, SpellMissInfo missCondition);
struct RedirectThreatInfo
{
RedirectThreatInfo() : _targetGUID(0), _threatPct(0) { }
uint64 _targetGUID;
uint32 _threatPct;
uint64 GetTargetGUID() const { return _targetGUID; }
uint32 GetThreatPct() const { return _threatPct; }
void Set(uint64 guid, uint32 pct)
{
_targetGUID = guid;
_threatPct = pct;
}
void ModifyThreatPct(int32 amount)
{
amount += _threatPct;
_threatPct = uint32(std::max(0, amount));
}
};
#define MAX_DECLINED_NAME_CASES 5
struct DeclinedName
{
std::string name[MAX_DECLINED_NAME_CASES];
};
enum CurrentSpellTypes
{
CURRENT_MELEE_SPELL = 0,
CURRENT_GENERIC_SPELL = 1,
CURRENT_CHANNELED_SPELL = 2,
CURRENT_AUTOREPEAT_SPELL = 3
};
#define CURRENT_FIRST_NON_MELEE_SPELL 1
#define CURRENT_MAX_SPELL 4
struct GlobalCooldown
{
explicit GlobalCooldown(uint32 _dur = 0, uint32 _time = 0) : duration(_dur), cast_time(_time) {}
uint32 duration;
uint32 cast_time;
};
typedef UNORDERED_MAP<uint32 /*category*/, GlobalCooldown> GlobalCooldownList;
class GlobalCooldownMgr // Shared by Player and CharmInfo
{
public:
GlobalCooldownMgr() {}
public:
bool HasGlobalCooldown(SpellInfo const* spellInfo) const;
void AddGlobalCooldown(SpellInfo const* spellInfo, uint32 gcd);
void CancelGlobalCooldown(SpellInfo const* spellInfo);
private:
GlobalCooldownList m_GlobalCooldowns;
};
enum ActiveStates
{
ACT_PASSIVE = 0x01, // 0x01 - passive
ACT_DISABLED = 0x81, // 0x80 - castable
ACT_ENABLED = 0xC1, // 0x40 | 0x80 - auto cast + castable
ACT_COMMAND = 0x07, // 0x01 | 0x02 | 0x04
ACT_REACTION = 0x06, // 0x02 | 0x04
ACT_DECIDE = 0x00 // custom
};
enum ReactStates
{
REACT_PASSIVE = 0,
REACT_DEFENSIVE = 1,
REACT_AGGRESSIVE = 2
};
enum CommandStates
{
COMMAND_STAY = 0,
COMMAND_FOLLOW = 1,
COMMAND_ATTACK = 2,
COMMAND_ABANDON = 3
};
#define UNIT_ACTION_BUTTON_ACTION(X) (uint32(X) & 0x00FFFFFF)
#define UNIT_ACTION_BUTTON_TYPE(X) ((uint32(X) & 0xFF000000) >> 24)
#define MAKE_UNIT_ACTION_BUTTON(A, T) (uint32(A) | (uint32(T) << 24))
struct UnitActionBarEntry
{
UnitActionBarEntry() : packedData(uint32(ACT_DISABLED) << 24) {}
uint32 packedData;
// helper
ActiveStates GetType() const { return ActiveStates(UNIT_ACTION_BUTTON_TYPE(packedData)); }
uint32 GetAction() const { return UNIT_ACTION_BUTTON_ACTION(packedData); }
bool IsActionBarForSpell() const
{
ActiveStates Type = GetType();
return Type == ACT_DISABLED || Type == ACT_ENABLED || Type == ACT_PASSIVE;
}
void SetActionAndType(uint32 action, ActiveStates type)
{
packedData = MAKE_UNIT_ACTION_BUTTON(action, type);
}
void SetType(ActiveStates type)
{
packedData = MAKE_UNIT_ACTION_BUTTON(UNIT_ACTION_BUTTON_ACTION(packedData), type);
}
void SetAction(uint32 action)
{
packedData = (packedData & 0xFF000000) | UNIT_ACTION_BUTTON_ACTION(action);
}
};
typedef std::list<Player*> SharedVisionList;
enum CharmType
{
CHARM_TYPE_CHARM,
CHARM_TYPE_POSSESS,
CHARM_TYPE_VEHICLE,
CHARM_TYPE_CONVERT
};
typedef UnitActionBarEntry CharmSpellInfo;
enum ActionBarIndex
{
ACTION_BAR_INDEX_START = 0,
ACTION_BAR_INDEX_PET_SPELL_START = 3,
ACTION_BAR_INDEX_PET_SPELL_END = 7,
ACTION_BAR_INDEX_END = 10
};
#define MAX_UNIT_ACTION_BAR_INDEX (ACTION_BAR_INDEX_END-ACTION_BAR_INDEX_START)
struct CharmInfo
{
public:
explicit CharmInfo(Unit* unit);
~CharmInfo();
void RestoreState();
uint32 GetPetNumber() const { return _petnumber; }
void SetPetNumber(uint32 petnumber, bool statwindow);
void SetCommandState(CommandStates st) { _CommandState = st; }
CommandStates GetCommandState() const { return _CommandState; }
bool HasCommandState(CommandStates state) const { return (_CommandState == state); }
void InitPossessCreateSpells();
void InitCharmCreateSpells();
void InitPetActionBar();
void InitEmptyActionBar(bool withAttack = true);
//return true if successful
bool AddSpellToActionBar(SpellInfo const* spellInfo, ActiveStates newstate = ACT_DECIDE);
bool RemoveSpellFromActionBar(uint32 spell_id);
void LoadPetActionBar(const std::string& data);
void BuildActionBar(WorldPacket* data);
void SetSpellAutocast(SpellInfo const* spellInfo, bool state);
void SetActionBar(uint8 index, uint32 spellOrAction, ActiveStates type)
{
PetActionBar[index].SetActionAndType(spellOrAction, type);
}
UnitActionBarEntry const* GetActionBarEntry(uint8 index) const { return &(PetActionBar[index]); }
void ToggleCreatureAutocast(SpellInfo const* spellInfo, bool apply);
CharmSpellInfo* GetCharmSpell(uint8 index) { return &(_charmspells[index]); }
GlobalCooldownMgr& GetGlobalCooldownMgr() { return m_GlobalCooldownMgr; }
void SetIsCommandAttack(bool val);
bool IsCommandAttack();
void SetIsCommandFollow(bool val);
bool IsCommandFollow();
void SetIsAtStay(bool val);
bool IsAtStay();
void SetIsFollowing(bool val);
bool IsFollowing();
void SetIsReturning(bool val);
bool IsReturning();
void SaveStayPosition();
void GetStayPosition(float &x, float &y, float &z);
private:
Unit* _unit;
UnitActionBarEntry PetActionBar[MAX_UNIT_ACTION_BAR_INDEX];
CharmSpellInfo _charmspells[4];
CommandStates _CommandState;
uint32 _petnumber;
bool _barInit;
//for restoration after charmed
ReactStates _oldReactState;
bool _isCommandAttack;
bool _isCommandFollow;
bool _isAtStay;
bool _isFollowing;
bool _isReturning;
float _stayX;
float _stayY;
float _stayZ;
GlobalCooldownMgr m_GlobalCooldownMgr;
};
// for clearing special attacks
#define REACTIVE_TIMER_START 4000
enum ReactiveType
{
REACTIVE_DEFENSE = 0,
REACTIVE_HUNTER_PARRY = 1,
REACTIVE_OVERPOWER = 2
};
#define MAX_REACTIVE 3
#define SUMMON_SLOT_PET 0
#define SUMMON_SLOT_TOTEM 1
#define MAX_TOTEM_SLOT 5
#define SUMMON_SLOT_MINIPET 5
#define SUMMON_SLOT_QUEST 6
#define MAX_SUMMON_SLOT 7
#define MAX_GAMEOBJECT_SLOT 4
enum PlayerTotemType
{
SUMMON_TYPE_TOTEM_FIRE = 63,
SUMMON_TYPE_TOTEM_EARTH = 81,
SUMMON_TYPE_TOTEM_WATER = 82,
SUMMON_TYPE_TOTEM_AIR = 83
};
// delay time next attack to prevent client attack animation problems
#define ATTACK_DISPLAY_DELAY 200
#define MAX_PLAYER_STEALTH_DETECT_RANGE 30.0f // max distance for detection targets by player
struct SpellProcEventEntry; // used only privately
class Unit : public WorldObject
{
public:
typedef std::set<Unit*> AttackerSet;
typedef std::set<Unit*> ControlList;
typedef std::multimap<uint32, Aura*> AuraMap;
typedef std::pair<AuraMap::const_iterator, AuraMap::const_iterator> AuraMapBounds;
typedef std::pair<AuraMap::iterator, AuraMap::iterator> AuraMapBoundsNonConst;
typedef std::multimap<uint32, AuraApplication*> AuraApplicationMap;
typedef std::pair<AuraApplicationMap::const_iterator, AuraApplicationMap::const_iterator> AuraApplicationMapBounds;
typedef std::pair<AuraApplicationMap::iterator, AuraApplicationMap::iterator> AuraApplicationMapBoundsNonConst;
typedef std::multimap<AuraStateType, AuraApplication*> AuraStateAurasMap;
typedef std::pair<AuraStateAurasMap::const_iterator, AuraStateAurasMap::const_iterator> AuraStateAurasMapBounds;
typedef std::list<AuraEffect*> AuraEffectList;
typedef std::list<Aura*> AuraList;
typedef std::list<AuraApplication *> AuraApplicationList;
typedef std::list<DiminishingReturn> Diminishing;
typedef std::set<uint32> ComboPointHolderSet;
typedef std::map<uint8, AuraApplication*> VisibleAuraMap;
virtual ~Unit();
UnitAI* GetAI() { return i_AI; }
void SetAI(UnitAI* newAI) { i_AI = newAI; }
void AddToWorld();
void RemoveFromWorld();
void CleanupBeforeRemoveFromMap(bool finalCleanup);
void CleanupsBeforeDelete(bool finalCleanup = true); // used in ~Creature/~Player (or before mass creature delete to remove cross-references to already deleted units)
DiminishingLevels GetDiminishing(DiminishingGroup group);
void IncrDiminishing(DiminishingGroup group);
float ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration, Unit* caster, DiminishingLevels Level, int32 limitduration);
void ApplyDiminishingAura(DiminishingGroup group, bool apply);
void ClearDiminishings() { m_Diminishing.clear(); }
// target dependent range checks
float GetSpellMaxRangeForTarget(Unit const* target, SpellInfo const* spellInfo) const;
float GetSpellMinRangeForTarget(Unit const* target, SpellInfo const* spellInfo) const;
virtual void Update(uint32 time);
void setAttackTimer(WeaponAttackType type, uint32 time) { m_attackTimer[type] = time; }
void resetAttackTimer(WeaponAttackType type = BASE_ATTACK);
uint32 getAttackTimer(WeaponAttackType type) const { return m_attackTimer[type]; }
bool isAttackReady(WeaponAttackType type = BASE_ATTACK) const { return m_attackTimer[type] == 0; }
bool haveOffhandWeapon() const;
bool CanDualWield() const { return m_canDualWield; }
void SetCanDualWield(bool value) { m_canDualWield = value; }
float GetCombatReach() const { return m_floatValues[UNIT_FIELD_COMBATREACH]; }
float GetMeleeReach() const;
bool IsWithinCombatRange(const Unit* obj, float dist2compare) const;
bool IsWithinMeleeRange(const Unit* obj, float dist = MELEE_RANGE) const;
void GetRandomContactPoint(const Unit* target, float &x, float &y, float &z, float distance2dMin, float distance2dMax) const;
uint32 m_extraAttacks;
bool m_canDualWield;
void _addAttacker(Unit* pAttacker); // must be called only from Unit::Attack(Unit*)
void _removeAttacker(Unit* pAttacker); // must be called only from Unit::AttackStop()
Unit* getAttackerForHelper() const; // If someone wants to help, who to give them
bool Attack(Unit* victim, bool meleeAttack);
void CastStop(uint32 except_spellid = 0);
bool AttackStop();
void RemoveAllAttackers();
AttackerSet const& getAttackers() const { return m_attackers; }
bool isAttackingPlayer() const;
Unit* GetVictim() const { return m_attacking; }
void CombatStop(bool includingCast = false);
void CombatStopWithPets(bool includingCast = false);
void StopAttackFaction(uint32 faction_id);
Unit* SelectNearbyTarget(Unit* exclude = NULL, float dist = NOMINAL_MELEE_RANGE) const;
void SendMeleeAttackStop(Unit* victim = NULL);
void SendMeleeAttackStart(Unit* victim);
void AddUnitState(uint32 f) { m_state |= f; }
bool HasUnitState(const uint32 f) const { return (m_state & f); }
void ClearUnitState(uint32 f) { m_state &= ~f; }
bool CanFreeMove() const;
uint32 HasUnitTypeMask(uint32 mask) const { return mask & m_unitTypeMask; }
void AddUnitTypeMask(uint32 mask) { m_unitTypeMask |= mask; }
bool IsSummon() const { return m_unitTypeMask & UNIT_MASK_SUMMON; }
bool IsGuardian() const { return m_unitTypeMask & UNIT_MASK_GUARDIAN; }
bool IsPet() const { return m_unitTypeMask & UNIT_MASK_PET; }
bool IsHunterPet() const{ return m_unitTypeMask & UNIT_MASK_HUNTER_PET; }
bool IsTotem() const { return m_unitTypeMask & UNIT_MASK_TOTEM; }
bool IsVehicle() const { return m_unitTypeMask & UNIT_MASK_VEHICLE; }
uint8 getLevel() const { return uint8(GetUInt32Value(UNIT_FIELD_LEVEL)); }
uint8 getLevelForTarget(WorldObject const* /*target*/) const { return getLevel(); }
void SetLevel(uint8 lvl);
uint8 getRace() const { return GetByteValue(UNIT_FIELD_BYTES_0, 0); }
uint32 getRaceMask() const { return 1 << (getRace()-1); }
uint8 getClass() const { return GetByteValue(UNIT_FIELD_BYTES_0, 1); }
uint32 getClassMask() const { return 1 << (getClass()-1); }
uint8 getGender() const { return GetByteValue(UNIT_FIELD_BYTES_0, 2); }
float GetStat(Stats stat) const { return float(GetUInt32Value(UNIT_FIELD_STAT0+stat)); }
void SetStat(Stats stat, int32 val) { SetStatInt32Value(UNIT_FIELD_STAT0+stat, val); }
uint32 GetArmor() const { return GetResistance(SPELL_SCHOOL_NORMAL); }
void SetArmor(int32 val) { SetResistance(SPELL_SCHOOL_NORMAL, val); }
uint32 GetResistance(SpellSchools school) const { return GetUInt32Value(UNIT_FIELD_RESISTANCES+school); }
uint32 GetResistance(SpellSchoolMask mask) const;
void SetResistance(SpellSchools school, int32 val) { SetStatInt32Value(UNIT_FIELD_RESISTANCES+school, val); }
uint32 GetHealth() const { return GetUInt32Value(UNIT_FIELD_HEALTH); }
uint32 GetMaxHealth() const { return GetUInt32Value(UNIT_FIELD_MAXHEALTH); }
bool IsFullHealth() const { return GetHealth() == GetMaxHealth(); }
bool HealthBelowPct(int32 pct) const { return GetHealth() < CountPctFromMaxHealth(pct); }
bool HealthBelowPctDamaged(int32 pct, uint32 damage) const { return int64(GetHealth()) - int64(damage) < int64(CountPctFromMaxHealth(pct)); }
bool HealthAbovePct(int32 pct) const { return GetHealth() > CountPctFromMaxHealth(pct); }
bool HealthAbovePctHealed(int32 pct, uint32 heal) const { return uint64(GetHealth()) + uint64(heal) > CountPctFromMaxHealth(pct); }
float GetHealthPct() const { return GetMaxHealth() ? 100.f * GetHealth() / GetMaxHealth() : 0.0f; }
uint32 CountPctFromMaxHealth(int32 pct) const { return CalculatePct(GetMaxHealth(), pct); }
uint32 CountPctFromCurHealth(int32 pct) const { return CalculatePct(GetHealth(), pct); }
void SetHealth(uint32 val);
void SetMaxHealth(uint32 val);
inline void SetFullHealth() { SetHealth(GetMaxHealth()); }
int32 ModifyHealth(int32 val);
int32 GetHealthGain(int32 dVal);
Powers getPowerType() const { return Powers(GetByteValue(UNIT_FIELD_BYTES_0, 3)); }
void setPowerType(Powers power);
uint32 GetPower(Powers power) const { return GetUInt32Value(UNIT_FIELD_POWER1 +power); }
uint32 GetMaxPower(Powers power) const { return GetUInt32Value(UNIT_FIELD_MAXPOWER1+power); }
void SetPower(Powers power, uint32 val);
void SetMaxPower(Powers power, uint32 val);
// returns the change in power
int32 ModifyPower(Powers power, int32 val);
int32 ModifyPowerPct(Powers power, float pct, bool apply = true);
uint32 GetAttackTime(WeaponAttackType att) const;
void SetAttackTime(WeaponAttackType att, uint32 val) { SetFloatValue(UNIT_FIELD_BASEATTACKTIME+att, val*m_modAttackSpeedPct[att]); }
void ApplyAttackTimePercentMod(WeaponAttackType att, float val, bool apply);
void ApplyCastTimePercentMod(float val, bool apply);
SheathState GetSheath() const { return SheathState(GetByteValue(UNIT_FIELD_BYTES_2, 0)); }
virtual void SetSheath(SheathState sheathed) { SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); }
// faction template id
uint32 getFaction() const { return GetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE); }
void setFaction(uint32 faction) { SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, faction); }
FactionTemplateEntry const* GetFactionTemplateEntry() const;
ReputationRank GetReactionTo(Unit const* target) const;
ReputationRank static GetFactionReactionTo(FactionTemplateEntry const* factionTemplateEntry, Unit const* target);
bool IsHostileTo(Unit const* unit) const;
bool IsHostileToPlayers() const;
bool IsFriendlyTo(Unit const* unit) const;
bool IsNeutralToAll() const;
bool IsInPartyWith(Unit const* unit) const;
bool IsInRaidWith(Unit const* unit) const;
void GetPartyMembers(std::list<Unit*> &units);
bool IsContestedGuard() const;
bool IsPvP() const { return HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP); }
void SetPvP(bool state);
uint32 GetCreatureType() const;
uint32 GetCreatureTypeMask() const;
uint8 getStandState() const { return GetByteValue(UNIT_FIELD_BYTES_1, 0); }
bool IsSitState() const;
bool IsStandState() const;
void SetStandState(uint8 state);
void SetStandFlags(uint8 flags) { SetByteFlag(UNIT_FIELD_BYTES_1, 2, flags); }
void RemoveStandFlags(uint8 flags) { RemoveByteFlag(UNIT_FIELD_BYTES_1, 2, flags); }
bool IsMounted() const { return HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT); }
uint32 GetMountID() const { return GetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID); }
void Mount(uint32 mount, uint32 vehicleId = 0, uint32 creatureEntry = 0);
void Dismount();
uint16 GetMaxSkillValueForLevel(Unit const* target = NULL) const { return (target ? getLevelForTarget(target) : getLevel()) * 5; }
void DealDamageMods(Unit* victim, uint32 &damage, uint32* absorb);
uint32 DealDamage(Unit* victim, uint32 damage, CleanDamage const* cleanDamage = NULL, DamageEffectType damagetype = DIRECT_DAMAGE, SpellSchoolMask damageSchoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* spellProto = NULL, bool durabilityLoss = true);
void Kill(Unit* victim, bool durabilityLoss = true);
int32 DealHeal(Unit* victim, uint32 addhealth);
void ProcDamageAndSpell(Unit* victim, uint32 procAttacker, uint32 procVictim, uint32 procEx, uint32 amount, WeaponAttackType attType = BASE_ATTACK, SpellInfo const* procSpell = NULL, SpellInfo const* procAura = NULL);
void ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellInfo const* procSpell, uint32 damage, SpellInfo const* procAura = NULL);
void GetProcAurasTriggeredOnEvent(AuraApplicationList& aurasTriggeringProc, AuraApplicationList* procAuras, ProcEventInfo eventInfo);
void TriggerAurasProcOnEvent(CalcDamageInfo& damageInfo);
void TriggerAurasProcOnEvent(AuraApplicationList* myProcAuras, AuraApplicationList* targetProcAuras,
Unit* actionTarget, uint32 typeMaskActor, uint32 typeMaskActionTarget,
uint32 spellTypeMask, uint32 spellPhaseMask, uint32 hitMask, Spell* spell,
DamageInfo* damageInfo, HealInfo* healInfo);
void TriggerAurasProcOnEvent(ProcEventInfo& eventInfo, AuraApplicationList& procAuras);
void HandleEmoteCommand(uint32 anim_id);
void AttackerStateUpdate (Unit* victim, WeaponAttackType attType = BASE_ATTACK, bool extra = false);
void CalculateMeleeDamage(Unit* victim, uint32 damage, CalcDamageInfo* damageInfo, WeaponAttackType attackType = BASE_ATTACK);
void DealMeleeDamage(CalcDamageInfo* damageInfo, bool durabilityLoss);
void HandleProcExtraAttackFor(Unit* victim);
void CalculateSpellDamageTaken(SpellNonMeleeDamage* damageInfo, int32 damage, SpellInfo const* spellInfo, WeaponAttackType attackType = BASE_ATTACK, bool crit = false);
void DealSpellDamage(SpellNonMeleeDamage* damageInfo, bool durabilityLoss);
// player or player's pet resilience (-1%)
float GetMeleeCritChanceReduction() const { return GetCombatRatingReduction(CR_CRIT_TAKEN_MELEE); }
float GetRangedCritChanceReduction() const { return GetCombatRatingReduction(CR_CRIT_TAKEN_RANGED); }
float GetSpellCritChanceReduction() const { return GetCombatRatingReduction(CR_CRIT_TAKEN_SPELL); }
// player or player's pet resilience (-1%)
uint32 GetMeleeCritDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_MELEE, 2.2f, 33.0f, damage); }
uint32 GetRangedCritDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_RANGED, 2.2f, 33.0f, damage); }
uint32 GetSpellCritDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_SPELL, 2.2f, 33.0f, damage); }
// player or player's pet resilience (-1%), cap 100%
uint32 GetMeleeDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_MELEE, 2.0f, 100.0f, damage); }
uint32 GetRangedDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_RANGED, 2.0f, 100.0f, damage); }
uint32 GetSpellDamageReduction(uint32 damage) const { return GetCombatRatingDamageReduction(CR_CRIT_TAKEN_SPELL, 2.0f, 100.0f, damage); }
void ApplyResilience(Unit const* victim, float* crit, int32* damage, bool isCrit, CombatRating type) const;
float MeleeSpellMissChance(Unit const* victim, WeaponAttackType attType, int32 skillDiff, uint32 spellId) const;
SpellMissInfo MeleeSpellHitResult(Unit* victim, SpellInfo const* spellInfo);
SpellMissInfo MagicSpellHitResult(Unit* victim, SpellInfo const* spellInfo);
SpellMissInfo SpellHitResult(Unit* victim, SpellInfo const* spellInfo, bool canReflect = false);
float GetUnitDodgeChance() const;
float GetUnitParryChance() const;
float GetUnitBlockChance() const;
float GetUnitMissChance(WeaponAttackType attType) const;
float GetUnitCriticalChance(WeaponAttackType attackType, const Unit* victim) const;
int32 GetMechanicResistChance(SpellInfo const* spellInfo) const;
bool CanUseAttackType(uint8 attacktype) const;
virtual uint32 GetShieldBlockValue() const =0;
uint32 GetShieldBlockValue(uint32 soft_cap, uint32 hard_cap) const;
uint32 GetUnitMeleeSkill(Unit const* target = NULL) const;
uint32 GetDefenseSkillValue(Unit const* target = NULL) const;
uint32 GetWeaponSkillValue(WeaponAttackType attType, Unit const* target = NULL) const;
float GetWeaponProcChance() const;
float GetPPMProcChance(uint32 WeaponSpeed, float PPM, const SpellInfo* spellProto) const;
MeleeHitOutcome RollMeleeOutcomeAgainst (const Unit* victim, WeaponAttackType attType) const;
MeleeHitOutcome RollMeleeOutcomeAgainst (const Unit* victim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const;
bool IsVendor() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_VENDOR); }
bool IsTrainer() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_TRAINER); }
bool IsQuestGiver() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_QUESTGIVER); }
bool IsGossip() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); }
bool IsTaxi() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_FLIGHTMASTER); }
bool IsGuildMaster() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_PETITIONER); }
bool IsBattleMaster() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_BATTLEMASTER); }
bool IsBanker() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_BANKER); }
bool IsInnkeeper() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_INNKEEPER); }
bool IsSpiritHealer() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPIRITHEALER); }
bool IsSpiritGuide() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPIRITGUIDE); }
bool IsTabardDesigner()const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_TABARDDESIGNER); }
bool IsAuctioner() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_AUCTIONEER); }
bool IsArmorer() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_REPAIR); }
bool IsServiceProvider() const;
bool IsSpiritService() const { return HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPIRITHEALER | UNIT_NPC_FLAG_SPIRITGUIDE); }
bool IsInFlight() const { return HasUnitState(UNIT_STATE_IN_FLIGHT); }
bool IsInCombat() const { return HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT); }
void CombatStart(Unit* target, bool initialAggro = true);
void SetInCombatState(bool PvP, Unit* enemy = NULL);
void SetInCombatWith(Unit* enemy);
void ClearInCombat();
uint32 GetCombatTimer() const { return m_CombatTimer; }
bool HasAuraTypeWithFamilyFlags(AuraType auraType, uint32 familyName, uint32 familyFlags) const;
bool virtual HasSpell(uint32 /*spellID*/) const { return false; }
bool HasBreakableByDamageAuraType(AuraType type, uint32 excludeAura = 0) const;
bool HasBreakableByDamageCrowdControlAura(Unit* excludeCasterChannel = NULL) const;
bool HasStealthAura() const { return HasAuraType(SPELL_AURA_MOD_STEALTH); }
bool HasInvisibilityAura() const { return HasAuraType(SPELL_AURA_MOD_INVISIBILITY); }
bool isFeared() const { return HasAuraType(SPELL_AURA_MOD_FEAR); }
bool isInRoots() const { return HasAuraType(SPELL_AURA_MOD_ROOT); }
bool IsPolymorphed() const;
bool isFrozen() const;
bool isTargetableForAttack(bool checkFakeDeath = true) const;
bool IsValidAttackTarget(Unit const* target) const;
bool _IsValidAttackTarget(Unit const* target, SpellInfo const* bySpell, WorldObject const* obj = NULL) const;
bool IsValidAssistTarget(Unit const* target) const;
bool _IsValidAssistTarget(Unit const* target, SpellInfo const* bySpell) const;
virtual bool IsInWater() const;
virtual bool IsUnderWater() const;
virtual void UpdateUnderwaterState(Map* m, float x, float y, float z);
bool isInAccessiblePlaceFor(Creature const* c) const;
void SendHealSpellLog(Unit* victim, uint32 SpellID, uint32 Damage, uint32 OverHeal, uint32 Absorb, bool critical = false);
int32 HealBySpell(Unit* victim, SpellInfo const* spellInfo, uint32 addHealth, bool critical = false);
void SendEnergizeSpellLog(Unit* victim, uint32 spellID, int32 damage, Powers powerType);
void EnergizeBySpell(Unit* victim, uint32 SpellID, int32 Damage, Powers powertype);
uint32 SpellNonMeleeDamageLog(Unit* victim, uint32 spellID, uint32 damage);
void CastSpell(SpellCastTargets const& targets, SpellInfo const* spellInfo, CustomSpellValues const* value, TriggerCastFlags triggerFlags = TRIGGERED_NONE, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0);
void CastSpell(Unit* victim, uint32 spellId, bool triggered, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0);
void CastSpell(Unit* victim, uint32 spellId, TriggerCastFlags triggerFlags = TRIGGERED_NONE, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0);
void CastSpell(Unit* victim, SpellInfo const* spellInfo, bool triggered, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0);
void CastSpell(Unit* victim, SpellInfo const* spellInfo, TriggerCastFlags triggerFlags = TRIGGERED_NONE, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0);
void CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0);
void CastSpell(GameObject* go, uint32 spellId, bool triggered, Item* castItem = NULL, AuraEffect* triggeredByAura = NULL, uint64 originalCaster = 0);
void CastCustomSpell(Unit* victim, uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0);
void CastCustomSpell(uint32 spellId, SpellValueMod mod, int32 value, Unit* victim, bool triggered, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0);
void CastCustomSpell(uint32 spellId, SpellValueMod mod, int32 value, Unit* victim = NULL, TriggerCastFlags triggerFlags = TRIGGERED_NONE, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0);
void CastCustomSpell(uint32 spellId, CustomSpellValues const &value, Unit* victim = NULL, TriggerCastFlags triggerFlags = TRIGGERED_NONE, Item* castItem = NULL, AuraEffect const* triggeredByAura = NULL, uint64 originalCaster = 0);
Aura* AddAura(uint32 spellId, Unit* target);
Aura* AddAura(SpellInfo const* spellInfo, uint8 effMask, Unit* target);
void SetAuraStack(uint32 spellId, Unit* target, uint32 stack);
void SendPlaySpellVisual(uint32 id);
void SendPlaySpellImpact(uint64 guid, uint32 id);
void DeMorph();
void SendAttackStateUpdate(CalcDamageInfo* damageInfo);
void SendAttackStateUpdate(uint32 HitInfo, Unit* target, uint8 SwingType, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount);
void SendSpellNonMeleeDamageLog(SpellNonMeleeDamage* log);
void SendSpellNonMeleeDamageLog(Unit* target, uint32 SpellID, uint32 Damage, SpellSchoolMask damageSchoolMask, uint32 AbsorbedDamage, uint32 Resist, bool PhysicalDamage, uint32 Blocked, bool CriticalHit = false);
void SendPeriodicAuraLog(SpellPeriodicAuraLogInfo* pInfo);
void SendSpellMiss(Unit* target, uint32 spellID, SpellMissInfo missInfo);
void SendSpellDamageResist(Unit* target, uint32 spellId);
void SendSpellDamageImmune(Unit* target, uint32 spellId);
void NearTeleportTo(float x, float y, float z, float orientation, bool casting = false);
void SendTeleportPacket(Position& pos);
virtual bool UpdatePosition(float x, float y, float z, float ang, bool teleport = false);
// returns true if unit's position really changed
bool UpdatePosition(const Position &pos, bool teleport = false);
void UpdateOrientation(float orientation);
void UpdateHeight(float newZ);
void KnockbackFrom(float x, float y, float speedXY, float speedZ);
void JumpTo(float speedXY, float speedZ, bool forward = true);
void JumpTo(WorldObject* obj, float speedZ);
void MonsterMoveWithSpeed(float x, float y, float z, float speed, bool generatePath = false, bool forceDestination = false);
//void SetFacing(float ori, WorldObject* obj = NULL);
//void SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint8 type, uint32 MovementFlags, uint32 Time, Player* player = NULL);
void SendMovementFlagUpdate(bool self = false);
bool IsLevitating() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_DISABLE_GRAVITY); }
bool IsWalking() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_WALKING); }
virtual bool SetWalk(bool enable);
virtual bool SetDisableGravity(bool disable, bool packetOnly = false);
virtual bool SetSwim(bool enable);
virtual bool SetCanFly(bool enable);
virtual bool SetWaterWalking(bool enable, bool packetOnly = false);
virtual bool SetFeatherFall(bool enable, bool packetOnly = false);
virtual bool SetHover(bool enable, bool packetOnly = false);
void SetInFront(WorldObject const* target);
void SetFacingTo(float ori);
void SetFacingToObject(WorldObject* object);
void SendChangeCurrentVictimOpcode(HostileReference* pHostileReference);
void SendClearThreatListOpcode();
void SendRemoveFromThreatListOpcode(HostileReference* pHostileReference);
void SendThreatListUpdate();
void SendClearTarget();
void BuildHeartBeatMsg(WorldPacket* data) const;
bool IsAlive() const { return (m_deathState == ALIVE); }
bool isDying() const { return (m_deathState == JUST_DIED); }
bool isDead() const { return (m_deathState == DEAD || m_deathState == CORPSE); }
DeathState getDeathState() const { return m_deathState; }
virtual void setDeathState(DeathState s); // overwrited in Creature/Player/Pet
uint64 GetOwnerGUID() const { return GetUInt64Value(UNIT_FIELD_SUMMONEDBY); }
void SetOwnerGUID(uint64 owner);
uint64 GetCreatorGUID() const { return GetUInt64Value(UNIT_FIELD_CREATEDBY); }
void SetCreatorGUID(uint64 creator) { SetUInt64Value(UNIT_FIELD_CREATEDBY, creator); }
uint64 GetMinionGUID() const { return GetUInt64Value(UNIT_FIELD_SUMMON); }
void SetMinionGUID(uint64 guid) { SetUInt64Value(UNIT_FIELD_SUMMON, guid); }
uint64 GetCharmerGUID() const { return GetUInt64Value(UNIT_FIELD_CHARMEDBY); }
void SetCharmerGUID(uint64 owner) { SetUInt64Value(UNIT_FIELD_CHARMEDBY, owner); }
uint64 GetCharmGUID() const { return GetUInt64Value(UNIT_FIELD_CHARM); }
void SetPetGUID(uint64 guid) { m_SummonSlot[SUMMON_SLOT_PET] = guid; }
uint64 GetPetGUID() const { return m_SummonSlot[SUMMON_SLOT_PET]; }
void SetCritterGUID(uint64 guid) { SetUInt64Value(UNIT_FIELD_CRITTER, guid); }
uint64 GetCritterGUID() const { return GetUInt64Value(UNIT_FIELD_CRITTER); }
bool IsControlledByPlayer() const { return m_ControlledByPlayer; }
uint64 GetCharmerOrOwnerGUID() const;
uint64 GetCharmerOrOwnerOrOwnGUID() const;
bool IsCharmedOwnedByPlayerOrPlayer() const { return IS_PLAYER_GUID(GetCharmerOrOwnerOrOwnGUID()); }
Player* GetSpellModOwner() const;
Unit* GetOwner() const;
Guardian* GetGuardianPet() const;
Minion* GetFirstMinion() const;
Unit* GetCharmer() const;
Unit* GetCharm() const;
Unit* GetCharmerOrOwner() const;
Unit* GetCharmerOrOwnerOrSelf() const;
Player* GetCharmerOrOwnerPlayerOrPlayerItself() const;
Player* GetAffectingPlayer() const;
void SetMinion(Minion *minion, bool apply);
void GetAllMinionsByEntry(std::list<Creature*>& Minions, uint32 entry);
void RemoveAllMinionsByEntry(uint32 entry);
void SetCharm(Unit* target, bool apply);
Unit* GetNextRandomRaidMemberOrPet(float radius);
bool SetCharmedBy(Unit* charmer, CharmType type, AuraApplication const* aurApp = NULL);
void RemoveCharmedBy(Unit* charmer);
void RestoreFaction();
ControlList m_Controlled;
Unit* GetFirstControlled() const;
void RemoveAllControlled();
bool IsCharmed() const { return GetCharmerGUID() != 0; }
bool isPossessed() const { return HasUnitState(UNIT_STATE_POSSESSED); }
bool isPossessedByPlayer() const;
bool isPossessing() const;
bool isPossessing(Unit* u) const;
CharmInfo* GetCharmInfo() { return m_charmInfo; }
CharmInfo* InitCharmInfo();
void DeleteCharmInfo();
void UpdateCharmAI();
//Player* GetMoverSource() const;
Player* m_movedPlayer;
SharedVisionList const& GetSharedVisionList() { return m_sharedVision; }
void AddPlayerToVision(Player* player);
void RemovePlayerFromVision(Player* player);
bool HasSharedVision() const { return !m_sharedVision.empty(); }
void RemoveBindSightAuras();
void RemoveCharmAuras();
Pet* CreateTamedPetFrom(Creature* creatureTarget, uint32 spell_id = 0);
Pet* CreateTamedPetFrom(uint32 creatureEntry, uint32 spell_id = 0);
bool InitTamedPet(Pet* pet, uint8 level, uint32 spell_id);
// aura apply/remove helpers - you should better not use these
Aura* _TryStackingOrRefreshingExistingAura(SpellInfo const* newAura, uint8 effMask, Unit* caster, int32* baseAmount = NULL, Item* castItem = NULL, uint64 casterGUID = 0);
void _AddAura(UnitAura* aura, Unit* caster);
AuraApplication * _CreateAuraApplication(Aura* aura, uint8 effMask);
void _ApplyAuraEffect(Aura* aura, uint8 effIndex);
void _ApplyAura(AuraApplication * aurApp, uint8 effMask);
void _UnapplyAura(AuraApplicationMap::iterator &i, AuraRemoveMode removeMode);
void _UnapplyAura(AuraApplication * aurApp, AuraRemoveMode removeMode);
void _RemoveNoStackAuraApplicationsDueToAura(Aura* aura);
void _RemoveNoStackAurasDueToAura(Aura* aura);
bool _IsNoStackAuraDueToAura(Aura* appliedAura, Aura* existingAura) const;
void _RegisterAuraEffect(AuraEffect* aurEff, bool apply);
// m_ownedAuras container management
AuraMap & GetOwnedAuras() { return m_ownedAuras; }
AuraMap const& GetOwnedAuras() const { return m_ownedAuras; }
void RemoveOwnedAura(AuraMap::iterator &i, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT);
void RemoveOwnedAura(uint32 spellId, uint64 casterGUID = 0, uint8 reqEffMask = 0, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT);
void RemoveOwnedAura(Aura* aura, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT);
Aura* GetOwnedAura(uint32 spellId, uint64 casterGUID = 0, uint64 itemCasterGUID = 0, uint8 reqEffMask = 0, Aura* except = NULL) const;
// m_appliedAuras container management
AuraApplicationMap & GetAppliedAuras() { return m_appliedAuras; }
AuraApplicationMap const& GetAppliedAuras() const { return m_appliedAuras; }
void RemoveAura(AuraApplicationMap::iterator &i, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT);
void RemoveAura(uint32 spellId, uint64 casterGUID = 0, uint8 reqEffMask = 0, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT);
void RemoveAura(AuraApplication * aurApp, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT);
void RemoveAura(Aura* aur, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT);
void RemoveAurasDueToSpell(uint32 spellId, uint64 casterGUID = 0, uint8 reqEffMask = 0, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT);
void RemoveAuraFromStack(uint32 spellId, uint64 casterGUID = 0, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT);
void RemoveAurasDueToSpellByDispel(uint32 spellId, uint32 dispellerSpellId, uint64 casterGUID, Unit* dispeller, uint8 chargesRemoved = 1);
void RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit* stealer);
void RemoveAurasDueToItemSpell(uint32 spellId, uint64 castItemGuid);
void RemoveAurasByType(AuraType auraType, uint64 casterGUID = 0, Aura* except = NULL, bool negative = true, bool positive = true);
void RemoveNotOwnSingleTargetAuras(uint32 newPhase = 0x0);
void RemoveAurasWithInterruptFlags(uint32 flag, uint32 except = 0);
void RemoveAurasWithAttribute(uint32 flags);
void RemoveAurasWithFamily(SpellFamilyNames family, uint32 familyFlag1, uint32 familyFlag2, uint32 familyFlag3, uint64 casterGUID);
void RemoveAurasWithMechanic(uint32 mechanic_mask, AuraRemoveMode removemode = AURA_REMOVE_BY_DEFAULT, uint32 except=0);
void RemoveMovementImpairingAuras();
void RemoveAreaAurasDueToLeaveWorld();
void RemoveAllAuras();
void RemoveArenaAuras();
void RemoveAllAurasOnDeath();
void RemoveAllAurasRequiringDeadTarget();
void RemoveAllAurasExceptType(AuraType type);
void RemoveAllAurasExceptType(AuraType type1, AuraType type2); /// @todo: once we support variadic templates use them here
void DelayOwnedAuras(uint32 spellId, uint64 caster, int32 delaytime);
void _RemoveAllAuraStatMods();
void _ApplyAllAuraStatMods();
AuraEffectList const& GetAuraEffectsByType(AuraType type) const { return m_modAuras[type]; }
AuraList & GetSingleCastAuras() { return m_scAuras; }
AuraList const& GetSingleCastAuras() const { return m_scAuras; }
AuraEffect* GetAuraEffect(uint32 spellId, uint8 effIndex, uint64 casterGUID = 0) const;
AuraEffect* GetAuraEffectOfRankedSpell(uint32 spellId, uint8 effIndex, uint64 casterGUID = 0) const;
AuraEffect* GetAuraEffect(AuraType type, SpellFamilyNames name, uint32 iconId, uint8 effIndex) const; // spell mustn't have familyflags
AuraEffect* GetAuraEffect(AuraType type, SpellFamilyNames family, uint32 familyFlag1, uint32 familyFlag2, uint32 familyFlag3, uint64 casterGUID =0) const;
AuraEffect* GetDummyAuraEffect(SpellFamilyNames name, uint32 iconId, uint8 effIndex) const;
AuraApplication * GetAuraApplication(uint32 spellId, uint64 casterGUID = 0, uint64 itemCasterGUID = 0, uint8 reqEffMask = 0, AuraApplication * except = NULL) const;
Aura* GetAura(uint32 spellId, uint64 casterGUID = 0, uint64 itemCasterGUID = 0, uint8 reqEffMask = 0) const;
AuraApplication * GetAuraApplicationOfRankedSpell(uint32 spellId, uint64 casterGUID = 0, uint64 itemCasterGUID = 0, uint8 reqEffMask = 0, AuraApplication * except = NULL) const;
Aura* GetAuraOfRankedSpell(uint32 spellId, uint64 casterGUID = 0, uint64 itemCasterGUID = 0, uint8 reqEffMask = 0) const;
void GetDispellableAuraList(Unit* caster, uint32 dispelMask, DispelChargesList& dispelList);
bool HasAuraEffect(uint32 spellId, uint8 effIndex, uint64 caster = 0) const;
uint32 GetAuraCount(uint32 spellId) const;
bool HasAura(uint32 spellId, uint64 casterGUID = 0, uint64 itemCasterGUID = 0, uint8 reqEffMask = 0) const;
bool HasAuraType(AuraType auraType) const;
bool HasAuraTypeWithCaster(AuraType auratype, uint64 caster) const;
bool HasAuraTypeWithMiscvalue(AuraType auratype, int32 miscvalue) const;
bool HasAuraTypeWithAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const;
bool HasAuraTypeWithValue(AuraType auratype, int32 value) const;
bool HasNegativeAuraWithInterruptFlag(uint32 flag, uint64 guid = 0) const;
bool HasNegativeAuraWithAttribute(uint32 flag, uint64 guid = 0) const;
bool HasAuraWithMechanic(uint32 mechanicMask) const;
AuraEffect* IsScriptOverriden(SpellInfo const* spell, int32 script) const;
uint32 GetDiseasesByCaster(uint64 casterGUID, bool remove = false);
uint32 GetDoTsByCaster(uint64 casterGUID) const;
int32 GetTotalAuraModifier(AuraType auratype) const;
float GetTotalAuraMultiplier(AuraType auratype) const;
int32 GetMaxPositiveAuraModifier(AuraType auratype) const;
int32 GetMaxNegativeAuraModifier(AuraType auratype) const;
int32 GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const;
float GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const;
int32 GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask, const AuraEffect* except = NULL) const;
int32 GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const;
int32 GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const;
float GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const;
int32 GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const;
int32 GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const;
int32 GetTotalAuraModifierByAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const;
float GetTotalAuraMultiplierByAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const;
int32 GetMaxPositiveAuraModifierByAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const;
int32 GetMaxNegativeAuraModifierByAffectMask(AuraType auratype, SpellInfo const* affectedSpell) const;
float GetResistanceBuffMods(SpellSchools school, bool positive) const;
void SetResistanceBuffMods(SpellSchools school, bool positive, float val);
void ApplyResistanceBuffModsMod(SpellSchools school, bool positive, float val, bool apply);
void ApplyResistanceBuffModsPercentMod(SpellSchools school, bool positive, float val, bool apply);
void InitStatBuffMods();
void ApplyStatBuffMod(Stats stat, float val, bool apply);
void ApplyStatPercentBuffMod(Stats stat, float val, bool apply);
void SetCreateStat(Stats stat, float val) { m_createStats[stat] = val; }
void SetCreateHealth(uint32 val) { SetUInt32Value(UNIT_FIELD_BASE_HEALTH, val); }
uint32 GetCreateHealth() const { return GetUInt32Value(UNIT_FIELD_BASE_HEALTH); }
void SetCreateMana(uint32 val) { SetUInt32Value(UNIT_FIELD_BASE_MANA, val); }
uint32 GetCreateMana() const { return GetUInt32Value(UNIT_FIELD_BASE_MANA); }
uint32 GetCreatePowers(Powers power) const;
float GetPosStat(Stats stat) const { return GetFloatValue(UNIT_FIELD_POSSTAT0+stat); }
float GetNegStat(Stats stat) const { return GetFloatValue(UNIT_FIELD_NEGSTAT0+stat); }
float GetCreateStat(Stats stat) const { return m_createStats[stat]; }
void SetCurrentCastedSpell(Spell* pSpell);
virtual void ProhibitSpellSchool(SpellSchoolMask /*idSchoolMask*/, uint32 /*unTimeMs*/) { }
void InterruptSpell(CurrentSpellTypes spellType, bool withDelayed = true, bool withInstant = true);
void FinishSpell(CurrentSpellTypes spellType, bool ok = true);
// set withDelayed to true to account delayed spells as casted
// delayed+channeled spells are always accounted as casted
// we can skip channeled or delayed checks using flags
bool IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled = false, bool skipAutorepeat = false, bool isAutoshoot = false, bool skipInstant = true) const;
// set withDelayed to true to interrupt delayed spells too
// delayed+channeled spells are always interrupted
void InterruptNonMeleeSpells(bool withDelayed, uint32 spellid = 0, bool withInstant = true);
Spell* GetCurrentSpell(CurrentSpellTypes spellType) const { return m_currentSpells[spellType]; }
Spell* GetCurrentSpell(uint32 spellType) const { return m_currentSpells[spellType]; }
Spell* FindCurrentSpellBySpellId(uint32 spell_id) const;
int32 GetCurrentSpellCastTime(uint32 spell_id) const;
uint64 m_SummonSlot[MAX_SUMMON_SLOT];
uint64 m_ObjectSlot[MAX_GAMEOBJECT_SLOT];
ShapeshiftForm GetShapeshiftForm() const { return ShapeshiftForm(GetByteValue(UNIT_FIELD_BYTES_2, 3)); }
void SetShapeshiftForm(ShapeshiftForm form);
bool IsInFeralForm() const;
bool IsInDisallowedMountForm() const;
float m_modMeleeHitChance;
float m_modRangedHitChance;
float m_modSpellHitChance;
int32 m_baseSpellCritChance;
float m_threatModifier[MAX_SPELL_SCHOOL];
float m_modAttackSpeedPct[3];
// Event handler
EventProcessor m_Events;
// stat system
bool HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply);
void SetModifierValue(UnitMods unitMod, UnitModifierType modifierType, float value) { m_auraModifiersGroup[unitMod][modifierType] = value; }
float GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const;
float GetTotalStatValue(Stats stat) const;
float GetTotalAuraModValue(UnitMods unitMod) const;
SpellSchools GetSpellSchoolByAuraGroup(UnitMods unitMod) const;
Stats GetStatByAuraGroup(UnitMods unitMod) const;
Powers GetPowerTypeByAuraGroup(UnitMods unitMod) const;
bool CanModifyStats() const { return m_canModifyStats; }
void SetCanModifyStats(bool modifyStats) { m_canModifyStats = modifyStats; }
virtual bool UpdateStats(Stats stat) = 0;
virtual bool UpdateAllStats() = 0;
virtual void UpdateResistances(uint32 school) = 0;
virtual void UpdateArmor() = 0;
virtual void UpdateMaxHealth() = 0;
virtual void UpdateMaxPower(Powers power) = 0;
virtual void UpdateAttackPowerAndDamage(bool ranged = false) = 0;
virtual void UpdateDamagePhysical(WeaponAttackType attType) = 0;
float GetTotalAttackPowerValue(WeaponAttackType attType) const;
float GetWeaponDamageRange(WeaponAttackType attType, WeaponDamageRange type) const;
void SetBaseWeaponDamage(WeaponAttackType attType, WeaponDamageRange damageRange, float value) { m_weaponDamage[attType][damageRange] = value; }
bool isInFrontInMap(Unit const* target, float distance, float arc = M_PI) const;
bool isInBackInMap(Unit const* target, float distance, float arc = M_PI) const;
// Visibility system
bool IsVisible() const;
void SetVisible(bool x);
// common function for visibility checks for player/creatures with detection code
void SetPhaseMask(uint32 newPhaseMask, bool update);// overwrite WorldObject::SetPhaseMask
void UpdateObjectVisibility(bool forced = true);
SpellImmuneList m_spellImmune[MAX_SPELL_IMMUNITY];
uint32 m_lastSanctuaryTime;
// Threat related methods
bool CanHaveThreatList() const;
void AddThreat(Unit* victim, float fThreat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* threatSpell = NULL);
float ApplyTotalThreatModifier(float fThreat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL);
void DeleteThreatList();
void TauntApply(Unit* victim);
void TauntFadeOut(Unit* taunter);
ThreatManager& getThreatManager() { return m_ThreatManager; }
void addHatedBy(HostileReference* pHostileReference) { m_HostileRefManager.insertFirst(pHostileReference); };
void removeHatedBy(HostileReference* /*pHostileReference*/) { /* nothing to do yet */ }
HostileRefManager& getHostileRefManager() { return m_HostileRefManager; }
VisibleAuraMap const* GetVisibleAuras() { return &m_visibleAuras; }
AuraApplication * GetVisibleAura(uint8 slot) const;
void SetVisibleAura(uint8 slot, AuraApplication * aur);
void RemoveVisibleAura(uint8 slot);
uint32 GetInterruptMask() const { return m_interruptMask; }
void AddInterruptMask(uint32 mask) { m_interruptMask |= mask; }
void UpdateInterruptMask();
uint32 GetDisplayId() const { return GetUInt32Value(UNIT_FIELD_DISPLAYID); }
virtual void SetDisplayId(uint32 modelId);
uint32 GetNativeDisplayId() const { return GetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID); }
void RestoreDisplayId();
void SetNativeDisplayId(uint32 modelId) { SetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID, modelId); }
void setTransForm(uint32 spellid) { m_transform = spellid;}
uint32 getTransForm() const { return m_transform;}
// DynamicObject management
void _RegisterDynObject(DynamicObject* dynObj);
void _UnregisterDynObject(DynamicObject* dynObj);
DynamicObject* GetDynObject(uint32 spellId);
void RemoveDynObject(uint32 spellId);
void RemoveAllDynObjects();
GameObject* GetGameObject(uint32 spellId) const;
void AddGameObject(GameObject* gameObj);
void RemoveGameObject(GameObject* gameObj, bool del);
void RemoveGameObject(uint32 spellid, bool del);
void RemoveAllGameObjects();
uint32 CalculateDamage(WeaponAttackType attType, bool normalized, bool addTotalPct);
float GetAPMultiplier(WeaponAttackType attType, bool normalized);
void ModifyAuraState(AuraStateType flag, bool apply);
uint32 BuildAuraStateUpdateForTarget(Unit* target) const;
bool HasAuraState(AuraStateType flag, SpellInfo const* spellProto = NULL, Unit const* Caster = NULL) const;
void UnsummonAllTotems();
Unit* GetMagicHitRedirectTarget(Unit* victim, SpellInfo const* spellInfo);
Unit* GetMeleeHitRedirectTarget(Unit* victim, SpellInfo const* spellInfo = NULL);
int32 SpellBaseDamageBonusDone(SpellSchoolMask schoolMask) const;
int32 SpellBaseDamageBonusTaken(SpellSchoolMask schoolMask) const;
uint32 SpellDamageBonusDone(Unit* victim, SpellInfo const* spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack = 1) const;
uint32 SpellDamageBonusTaken(Unit* caster, SpellInfo const* spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack = 1) const;
int32 SpellBaseHealingBonusDone(SpellSchoolMask schoolMask) const;
int32 SpellBaseHealingBonusTaken(SpellSchoolMask schoolMask) const;
uint32 SpellHealingBonusDone(Unit* victim, SpellInfo const* spellProto, uint32 healamount, DamageEffectType damagetype, uint32 stack = 1) const;
uint32 SpellHealingBonusTaken(Unit* caster, SpellInfo const* spellProto, uint32 healamount, DamageEffectType damagetype, uint32 stack = 1) const;
uint32 MeleeDamageBonusDone(Unit* pVictim, uint32 damage, WeaponAttackType attType, SpellInfo const* spellProto = NULL);
uint32 MeleeDamageBonusTaken(Unit* attacker, uint32 pdamage, WeaponAttackType attType, SpellInfo const* spellProto = NULL);
bool isSpellBlocked(Unit* victim, SpellInfo const* spellProto, WeaponAttackType attackType = BASE_ATTACK);
bool isBlockCritical();
bool isSpellCrit(Unit* victim, SpellInfo const* spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType = BASE_ATTACK) const;
uint32 SpellCriticalDamageBonus(SpellInfo const* spellProto, uint32 damage, Unit* victim);
uint32 SpellCriticalHealingBonus(SpellInfo const* spellProto, uint32 damage, Unit* victim);
void SetLastManaUse(uint32 spellCastTime) { m_lastManaUse = spellCastTime; }
bool IsUnderLastManaUseEffect() const;
void SetContestedPvP(Player* attackedPlayer = NULL);
uint32 GetCastingTimeForBonus(SpellInfo const* spellProto, DamageEffectType damagetype, uint32 CastingTime) const;
float CalculateDefaultCoefficient(SpellInfo const* spellInfo, DamageEffectType damagetype) const;
uint32 GetRemainingPeriodicAmount(uint64 caster, uint32 spellId, AuraType auraType, uint8 effectIndex = 0) const;
void ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply);
void ApplySpellDispelImmunity(const SpellInfo* spellProto, DispelType type, bool apply);
virtual bool IsImmunedToSpell(SpellInfo const* spellInfo) const; // redefined in Creature
bool IsImmunedToDamage(SpellSchoolMask meleeSchoolMask) const;
bool IsImmunedToDamage(SpellInfo const* spellInfo) const;
virtual bool IsImmunedToSpellEffect(SpellInfo const* spellInfo, uint32 index) const; // redefined in Creature
static bool IsDamageReducedByArmor(SpellSchoolMask damageSchoolMask, SpellInfo const* spellInfo = NULL, uint8 effIndex = MAX_SPELL_EFFECTS);
uint32 CalcArmorReducedDamage(Unit* victim, const uint32 damage, SpellInfo const* spellInfo, WeaponAttackType attackType = MAX_ATTACK);
uint32 CalcSpellResistance(Unit* victim, SpellSchoolMask schoolMask, SpellInfo const* spellInfo) const;
void CalcAbsorbResist(Unit* victim, SpellSchoolMask schoolMask, DamageEffectType damagetype, uint32 const damage, uint32* absorb, uint32* resist, SpellInfo const* spellInfo = NULL);
void CalcHealAbsorb(Unit* victim, SpellInfo const* spellInfo, uint32& healAmount, uint32& absorb);
void UpdateSpeed(UnitMoveType mtype, bool forced);
float GetSpeed(UnitMoveType mtype) const;
float GetSpeedRate(UnitMoveType mtype) const { return m_speed_rate[mtype]; }
void SetSpeed(UnitMoveType mtype, float rate, bool forced = false);
float ApplyEffectModifiers(SpellInfo const* spellProto, uint8 effect_index, float value) const;
int32 CalculateSpellDamage(Unit const* target, SpellInfo const* spellProto, uint8 effect_index, int32 const* basePoints = NULL) const;
int32 CalcSpellDuration(SpellInfo const* spellProto);
int32 ModSpellDuration(SpellInfo const* spellProto, Unit const* target, int32 duration, bool positive, uint32 effectMask);
void ModSpellCastTime(SpellInfo const* spellProto, int32& castTime, Spell* spell = NULL);
float CalculateLevelPenalty(SpellInfo const* spellProto) const;
void addFollower(FollowerReference* pRef) { m_FollowingRefManager.insertFirst(pRef); }
void removeFollower(FollowerReference* /*pRef*/) { /* nothing to do yet */ }
static Unit* GetUnit(WorldObject& object, uint64 guid);
static Player* GetPlayer(WorldObject& object, uint64 guid);
static Creature* GetCreature(WorldObject& object, uint64 guid);
MotionMaster* GetMotionMaster() { return &i_motionMaster; }
const MotionMaster* GetMotionMaster() const { return &i_motionMaster; }
bool IsStopped() const { return !(HasUnitState(UNIT_STATE_MOVING)); }
void StopMoving();
void AddUnitMovementFlag(uint32 f) { m_movementInfo.flags |= f; }
void RemoveUnitMovementFlag(uint32 f) { m_movementInfo.flags &= ~f; }
bool HasUnitMovementFlag(uint32 f) const { return (m_movementInfo.flags & f) == f; }
uint32 GetUnitMovementFlags() const { return m_movementInfo.flags; }
void SetUnitMovementFlags(uint32 f) { m_movementInfo.flags = f; }
void AddExtraUnitMovementFlag(uint16 f) { m_movementInfo.flags2 |= f; }
void RemoveExtraUnitMovementFlag(uint16 f) { m_movementInfo.flags2 &= ~f; }
uint16 HasExtraUnitMovementFlag(uint16 f) const { return m_movementInfo.flags2 & f; }
uint16 GetExtraUnitMovementFlags() const { return m_movementInfo.flags2; }
void SetExtraUnitMovementFlags(uint16 f) { m_movementInfo.flags2 = f; }
float GetPositionZMinusOffset() const;
void SetControlled(bool apply, UnitState state);
void AddComboPointHolder(uint32 lowguid) { m_ComboPointHolders.insert(lowguid); }
void RemoveComboPointHolder(uint32 lowguid) { m_ComboPointHolders.erase(lowguid); }
void ClearComboPointHolders();
///----------Pet responses methods-----------------
void SendPetActionFeedback (uint8 msg);
void SendPetTalk (uint32 pettalk);
void SendPetAIReaction(uint64 guid);
///----------End of Pet responses methods----------
void propagateSpeedChange() { GetMotionMaster()->propagateSpeedChange(); }
// reactive attacks
void ClearAllReactives();
void StartReactiveTimer(ReactiveType reactive) { m_reactiveTimer[reactive] = REACTIVE_TIMER_START;}
void UpdateReactives(uint32 p_time);
// group updates
void UpdateAuraForGroup(uint8 slot);
// proc trigger system
bool CanProc() const {return !m_procDeep;}
void SetCantProc(bool apply);
// pet auras
typedef std::set<PetAura const*> PetAuraSet;
PetAuraSet m_petAuras;
void AddPetAura(PetAura const* petSpell);
void RemovePetAura(PetAura const* petSpell);
uint32 GetModelForForm(ShapeshiftForm form) const;
uint32 GetModelForTotem(PlayerTotemType totemType);
// Redirect Threat
void SetRedirectThreat(uint64 guid, uint32 pct) { _redirectThreadInfo.Set(guid, pct); }
void ResetRedirectThreat() { SetRedirectThreat(0, 0); }
void ModifyRedirectThreat(int32 amount) { _redirectThreadInfo.ModifyThreatPct(amount); }
uint32 GetRedirectThreatPercent() const { return _redirectThreadInfo.GetThreatPct(); }
Unit* GetRedirectThreatTarget();
friend class VehicleJoinEvent;
bool IsAIEnabled, NeedChangeAI;
uint64 LastCharmerGUID;
bool CreateVehicleKit(uint32 id, uint32 creatureEntry);
void RemoveVehicleKit();
Vehicle* GetVehicleKit()const { return m_vehicleKit; }
Vehicle* GetVehicle() const { return m_vehicle; }
void SetVehicle(Vehicle* vehicle) { m_vehicle = vehicle; }
bool IsOnVehicle(const Unit* vehicle) const;
Unit* GetVehicleBase() const;
Creature* GetVehicleCreatureBase() const;
uint64 GetTransGUID() const;
/// Returns the transport this unit is on directly (if on vehicle and transport, return vehicle)
TransportBase* GetDirectTransport() const;
bool m_ControlledByPlayer;
bool HandleSpellClick(Unit* clicker, int8 seatId = -1);
void EnterVehicle(Unit* base, int8 seatId = -1);
void ExitVehicle(Position const* exitPosition = NULL);
void ChangeSeat(int8 seatId, bool next = true);
// Should only be called by AuraEffect::HandleAuraControlVehicle(AuraApplication const* auraApp, uint8 mode, bool apply) const;
void _ExitVehicle(Position const* exitPosition = NULL);
void _EnterVehicle(Vehicle* vehicle, int8 seatId, AuraApplication const* aurApp = NULL);
void BuildMovementPacket(ByteBuffer *data) const;
bool isMoving() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_MASK_MOVING); }
bool isTurning() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_MASK_TURNING); }
virtual bool CanFly() const = 0;
bool IsFlying() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_FLYING | MOVEMENTFLAG_DISABLE_GRAVITY); }
bool IsFalling() const;
void RewardRage(uint32 damage, uint32 weaponSpeedHitFactor, bool attacker);
virtual float GetFollowAngle() const { return static_cast<float>(M_PI/2); }
void OutDebugInfo() const;
virtual bool isBeingLoaded() const { return false;}
bool IsDuringRemoveFromWorld() const {return m_duringRemoveFromWorld;}
Pet* ToPet() { if (IsPet()) return reinterpret_cast<Pet*>(this); else return NULL; }
Pet const* ToPet() const { if (IsPet()) return reinterpret_cast<Pet const*>(this); else return NULL; }
Totem* ToTotem() { if (IsTotem()) return reinterpret_cast<Totem*>(this); else return NULL; }
Totem const* ToTotem() const { if (IsTotem()) return reinterpret_cast<Totem const*>(this); else return NULL; }
TempSummon* ToTempSummon() { if (IsSummon()) return reinterpret_cast<TempSummon*>(this); else return NULL; }
TempSummon const* ToTempSummon() const { if (IsSummon()) return reinterpret_cast<TempSummon const*>(this); else return NULL; }
uint64 GetTarget() const { return GetUInt64Value(UNIT_FIELD_TARGET); }
virtual void SetTarget(uint64 /*guid*/) = 0;
// Movement info
Movement::MoveSpline * movespline;
// Part of Evade mechanics
time_t GetLastDamagedTime() const { return _lastDamagedTime; }
void SetLastDamagedTime(time_t val) { _lastDamagedTime = val; }
protected:
explicit Unit (bool isWorldObject);
void BuildValuesUpdate(uint8 updatetype, ByteBuffer* data, Player* target) const;
UnitAI* i_AI, *i_disabledAI;
void _UpdateSpells(uint32 time);
void _DeleteRemovedAuras();
void _UpdateAutoRepeatSpell();
bool m_AutoRepeatFirstCast;
uint32 m_attackTimer[MAX_ATTACK];
float m_createStats[MAX_STATS];
AttackerSet m_attackers;
Unit* m_attacking;
DeathState m_deathState;
int32 m_procDeep;
typedef std::list<DynamicObject*> DynObjectList;
DynObjectList m_dynObj;
typedef std::list<GameObject*> GameObjectList;
GameObjectList m_gameObj;
bool m_isSorted;
uint32 m_transform;
Spell* m_currentSpells[CURRENT_MAX_SPELL];
AuraMap m_ownedAuras;
AuraApplicationMap m_appliedAuras;
AuraList m_removedAuras;
AuraMap::iterator m_auraUpdateIterator;
uint32 m_removedAurasCount;
AuraEffectList m_modAuras[TOTAL_AURAS];
AuraList m_scAuras; // casted singlecast auras
AuraApplicationList m_interruptableAuras; // auras which have interrupt mask applied on unit
AuraStateAurasMap m_auraStateAuras; // Used for improve performance of aura state checks on aura apply/remove
uint32 m_interruptMask;
float m_auraModifiersGroup[UNIT_MOD_END][MODIFIER_TYPE_END];
float m_weaponDamage[MAX_ATTACK][2];
bool m_canModifyStats;
VisibleAuraMap m_visibleAuras;
float m_speed_rate[MAX_MOVE_TYPE];
CharmInfo* m_charmInfo;
SharedVisionList m_sharedVision;
virtual SpellSchoolMask GetMeleeDamageSchoolMask() const;
MotionMaster i_motionMaster;
uint32 m_reactiveTimer[MAX_REACTIVE];
uint32 m_regenTimer;
ThreatManager m_ThreatManager;
Vehicle* m_vehicle;
Vehicle* m_vehicleKit;
uint32 m_unitTypeMask;
LiquidTypeEntry const* _lastLiquid;
bool IsAlwaysVisibleFor(WorldObject const* seer) const;
bool IsAlwaysDetectableFor(WorldObject const* seer) const;
void DisableSpline();
private:
bool IsTriggeredAtSpellProcEvent(Unit* victim, Aura* aura, SpellInfo const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const* & spellProcEvent);
bool HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
bool HandleAuraProc(Unit* victim, uint32 damage, Aura* triggeredByAura, SpellInfo const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown, bool * handled);
bool HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown);
bool HandleOverrideClassScriptAuraProc(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 cooldown);
bool HandleAuraRaidProcFromChargeWithValue(AuraEffect* triggeredByAura);
bool HandleAuraRaidProcFromCharge(AuraEffect* triggeredByAura);
void UpdateSplineMovement(uint32 t_diff);
// player or player's pet
float GetCombatRatingReduction(CombatRating cr) const;
uint32 GetCombatRatingDamageReduction(CombatRating cr, float rate, float cap, uint32 damage) const;
void SetFeared(bool apply);
void SetConfused(bool apply);
void SetStunned(bool apply);
void SetRooted(bool apply);
uint32 m_rootTimes;
uint32 m_state; // Even derived shouldn't modify
uint32 m_CombatTimer;
uint32 m_lastManaUse; // msecs
TimeTrackerSmall m_movesplineTimer;
Diminishing m_Diminishing;
// Manage all Units that are threatened by us
HostileRefManager m_HostileRefManager;
FollowerRefManager m_FollowingRefManager;
ComboPointHolderSet m_ComboPointHolders;
RedirectThreatInfo _redirectThreadInfo;
bool m_cleanupDone; // lock made to not add stuff after cleanup before delete
bool m_duringRemoveFromWorld; // lock made to not add stuff after begining removing from world
bool _isWalkingBeforeCharm; // Are we walking before we were charmed?
time_t _lastDamagedTime; // Part of Evade mechanics
};
namespace Trinity
{
// Binary predicate for sorting Units based on percent value of a power
class PowerPctOrderPred
{
public:
PowerPctOrderPred(Powers power, bool ascending = true) : m_power(power), m_ascending(ascending) {}
bool operator() (const Unit* a, const Unit* b) const
{
float rA = a->GetMaxPower(m_power) ? float(a->GetPower(m_power)) / float(a->GetMaxPower(m_power)) : 0.0f;
float rB = b->GetMaxPower(m_power) ? float(b->GetPower(m_power)) / float(b->GetMaxPower(m_power)) : 0.0f;
return m_ascending ? rA < rB : rA > rB;
}
private:
const Powers m_power;
const bool m_ascending;
};
// Binary predicate for sorting Units based on percent value of health
class HealthPctOrderPred
{
public:
HealthPctOrderPred(bool ascending = true) : m_ascending(ascending) {}
bool operator() (const Unit* a, const Unit* b) const
{
float rA = a->GetMaxHealth() ? float(a->GetHealth()) / float(a->GetMaxHealth()) : 0.0f;
float rB = b->GetMaxHealth() ? float(b->GetHealth()) / float(b->GetMaxHealth()) : 0.0f;
return m_ascending ? rA < rB : rA > rB;
}
private:
const bool m_ascending;
};
}
#endif
|
EBC88/TrinityCoreArenas
|
src/server/game/Entities/Unit/Unit.h
|
C
|
gpl-2.0
| 110,072
|
require_relative './spec_helper'
require 'norikra/typedef'
require 'json'
require 'digest'
describe Norikra::Typedef do
context 'instanciated as lazy typedef' do
it 'has no fields' do
t = Norikra::Typedef.new
expect(t.fields.size).to eql(0)
expect(t.baseset).to be_nil
end
it 'has no query/data fieldsets' do
t = Norikra::Typedef.new
expect(t.queryfieldsets.size).to eql(0)
expect(t.datafieldsets.size).to eql(0)
end
describe '#lazy?' do
it 'returns true' do
t = Norikra::Typedef.new
expect(t.lazy?).to be_true
end
end
describe '#reserve' do
it 'add field definition without any baseset' do
t = Norikra::Typedef.new
t.reserve('k', 'string')
expect(t.fields['k'].type).to eql('string')
expect(t.fields['k'].optional?).to be_true
t.reserve('l', 'long', false)
expect(t.fields['l'].type).to eql('long')
expect(t.fields['l'].optional?).to be_false
end
end
describe '#activate' do
context 'without any fields reserved' do
it 'stores all fields in specified fieldset' do
t = Norikra::Typedef.new
set = Norikra::FieldSet.new({'a'=>'string','b'=>'long','c'=>'double'})
t.activate(set)
expect(t.fields.size).to eql(3)
expect(t.fields['a'].optional?).to be_false
expect(t.fields.object_id).not_to eql(set.fields.object_id)
expect(t.baseset.object_id).not_to eql(set.object_id)
end
end
end
end
context 'instanciated as non-lazy typedef' do
it 'has no query/data fieldsets' do
t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'})
expect(t.queryfieldsets.size).to eql(0)
expect(t.datafieldsets.size).to eql(0)
end
it 'has all fields as required' do
t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'})
expect(t.fields['a'].type).to eql('string')
expect(t.fields['a'].optional?).to be_false
expect(t.fields['b'].type).to eql('long')
expect(t.fields['b'].optional?).to be_false
end
describe '#lazy?' do
it 'returns false' do
t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'})
expect(t.lazy?).to be_false
end
end
describe '#field_defined?' do
it 'returns boolean to indicate all fields specified exists or not' do
t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'})
expect(t.field_defined?(['a','b'])).to be_true
expect(t.field_defined?(['a'])).to be_true
expect(t.field_defined?(['b'])).to be_true
expect(t.field_defined?([])).to be_true
expect(t.field_defined?(['a','b','c'])).to be_false
expect(t.field_defined?(['a','c'])).to be_false
expect(t.field_defined?(['c'])).to be_false
end
end
describe '#reserve' do
it 'adds field definitions as required or optional' do
t = Norikra::Typedef.new({'a' => 'string'})
expect(t.fields.size).to eql(1)
t.reserve('b', 'boolean', false)
expect(t.fields.size).to eql(2)
expect(t.fields['b'].type).to eql('boolean')
expect(t.fields['b'].optional?).to be_false
t.reserve('c', 'double', true)
expect(t.fields.size).to eql(3)
expect(t.fields['c'].type).to eql('double')
expect(t.fields['c'].optional?).to be_true
end
end
describe '#consistent?' do
context 'without any additional reserved fields' do
it 'checks all fields of specified fieldset are super-set of baseset or not' do
t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'})
set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long'})
expect(t.consistent?(set)).to be_true
set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long', 'c' => 'double'})
expect(t.consistent?(set)).to be_true
set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'int'})
expect(t.consistent?(set)).to be_false
set = Norikra::FieldSet.new({'a' => 'string'})
expect(t.consistent?(set)).to be_false
end
end
context 'with some additional reserved fields' do
it 'checks all fields of specified fieldset with baseset and additional reserved fields' do
t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'})
t.reserve('c', 'double', false) # required
t.reserve('d', 'boolean', true) # optional
set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long'})
expect(t.consistent?(set)).to be_false
set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long', 'c' => 'double'})
expect(t.consistent?(set)).to be_true
set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long', 'c' => 'double', 'd' => 'boolean'})
expect(t.consistent?(set)).to be_true
set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long', 'c' => 'double', 'd' => 'string'})
expect(t.consistent?(set)).to be_false
set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long', 'c' => 'double', 'd' => 'boolean', 'e' => 'string'})
expect(t.consistent?(set)).to be_true
end
end
end
describe '#push' do
it 'does not accepts fieldset which conflicts pre-defined fields' do
t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'})
expect { t.push(:query, Norikra::FieldSet.new({'a'=>'string','b'=>'int'})) }.to raise_error(ArgumentError)
expect { t.push(:data, Norikra::FieldSet.new({'a'=>'string'})) }.to raise_error(ArgumentError)
end
it 'accepts fieldsets which is consistent with self' do
t = Norikra::Typedef.new({'a'=>'string','b'=>'long'})
expect(t.fields.size).to eql(2)
expect { t.push(:query, Norikra::FieldSet.new({'a'=>'string','b'=>'long'})) }.not_to raise_error(ArgumentError)
expect { t.push(:data, Norikra::FieldSet.new({'a'=>'string','b'=>'long'})) }.not_to raise_error(ArgumentError)
expect(t.fields.size).to eql(2)
set_a = Norikra::FieldSet.new({'a'=>'string','b'=>'long','c'=>'double'})
t.push(:data, set_a)
expect(t.fields.size).to eql(3)
expect(t.fields['c'].type).to eql('double')
expect(t.fields['c'].optional?).to be_true
t.push(:query, Norikra::FieldSet.new({'a'=>'string','b'=>'long','d'=>'string'}))
expect(t.fields.size).to eql(4)
expect(t.fields['d'].type).to eql('string')
expect(t.fields['d'].optional?).to be_true
end
end
describe '#refer' do
context 'for event defined by data-fieldset already known' do
it 'returns fieldset that already known itself' do
t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'})
set1 = Norikra::FieldSet.new({'a'=>'string','b'=>'long'})
t.push(:data, set1)
r = t.refer({'a'=>'foobar','b'=>200000000})
expect(r).to be_instance_of(Norikra::FieldSet)
expect(r.object_id).to eql(set1.object_id)
end
end
context 'for event with known fields only' do
it 'returns fieldset that is overwritten with known field definitions' do
t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'})
t.reserve('c','boolean',true)
t.reserve('d','double',true)
r = t.refer({'a'=>'hoge','b'=>'2000','c'=>'true','d'=>'3.14'})
expect(t.datafieldsets.include?(r)).to be_false
expect(r.fields['a'].type).to eql('string')
expect(r.fields['b'].type).to eql('long')
expect(r.fields['c'].type).to eql('boolean')
expect(r.fields['d'].type).to eql('double')
end
end
context 'for event with some unknown fields' do
it 'returns fieldset that contains fields as string for unknowns' do
t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'})
r = t.refer({'a'=>'hoge','b'=>'2000','c'=>'true','d'=>'3.14'})
expect(t.datafieldsets.include?(r)).to be_false
expect(r.fields['a'].type).to eql('string')
expect(r.fields['b'].type).to eql('long')
expect(r.fields['c'].type).to eql('string')
expect(r.fields['d'].type).to eql('string')
end
end
end
describe '#format' do
it 'returns hash value with formatted fields as defined' do
t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'})
t.reserve('c','boolean',true)
t.reserve('d','double',true)
d = t.format({'a'=>'hoge','b'=>'2000','c'=>'true','d'=>'3.14'})
expect(d['a']).to be_instance_of(String)
expect(d['a']).to eql('hoge')
expect(d['b']).to be_instance_of(Fixnum)
expect(d['b']).to eql(2000)
expect(d['c']).to be_instance_of(TrueClass)
expect(d['c']).to eql(true)
expect(d['d']).to be_instance_of(Float)
expect(d['d']).to eql(3.14)
end
end
end
end
|
achied/norikra
|
spec/typedef_spec.rb
|
Ruby
|
gpl-2.0
| 9,075
|
/**
* @file
* Main JS file for react functionality.
*
*/
(function ($) {
Drupal.behaviors.react_blocks = {
attach: function (context) {
// A div with some text in it
var CommentBox = React.createClass({displayName: 'CommentBox',
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
getInitialState: function() {
return {data: []};
},
componentDidMount: function() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function() {
return (
React.createElement("div", {className: "commentBox"},
React.createElement("h3", null, React.createElement("b", null, "Check them out!")),
React.createElement(CommentList, {data: this.state.data})
)
);
}
});
var CommentList = React.createClass({displayName: 'CommentList',
render: function() {
var commentNodes = this.props.data.map(function (comment) {
return (
React.createElement(Comment, {author: comment.name},
comment.subject
)
);
});
return (
React.createElement("div", {className: "commentList"},
commentNodes
)
);
}
});
var Comment = React.createClass({displayName: 'Comment',
render: function() {
return (
React.createElement("div", {className: "comment"},
React.createElement("h2", {className: "commentAuthor"},
this.props.name
),
this.props.subject
)
);
}
});
// Render our reactComponent
React.render(
React.createElement(CommentBox, {url: "../api/v1/comment.json", pollInterval: 2000}),
document.getElementById('recent-comments')
);
}
}
})(jQuery);
|
changemachine/jellyfish
|
sites/all/modules/react_blocks/build/.module-cache/fcda948e5eafc0c8b5f89fe71d221f278abccbd5.js
|
JavaScript
|
gpl-2.0
| 2,307
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Noised.Core.DB;
using Noised.Core.IOC;
using Noised.Logging;
namespace Noised.Core.Plugins
{
/// <summary>
/// Basic plugin loader
/// </summary>
public class PluginLoader : IPluginLoader
{
#region Fields
private const String PLUGIN_TYPE_NAME = "Noised.Core.Plugins.IPlugin";
private List<IPlugin> plugins = new List<IPlugin>();
private readonly Dictionary<IPlugin, PluginMetaData> metaDataStore = new Dictionary<IPlugin, PluginMetaData>();
#endregion
#region IPluginLoader
public int LoadPlugins()
{
var logger = IoC.Get<ILogging>();
using (var unitOfWork = IoC.Get<IUnitOfWork>())
{
var files = unitOfWork.PluginRepository.GetFiles(".nplugin");
FileInfo currentFile = null;
foreach (var file in files)
{
currentFile = file;
IEnumerable<Type> pluginTypes;
try
{
//Getting IPlugin types from the plugin assembly
Assembly assembly = Assembly.LoadFrom(file.FullName);
Type pluginBaseType = Type.GetType(PLUGIN_TYPE_NAME);
pluginTypes = assembly.GetTypes().Where(pluginBaseType.IsAssignableFrom);
if (pluginTypes != null && pluginTypes.Any())
{
//Plugin init data
var pluginInitializer =
new PluginInitializer
{
Logging = logger
};
//Instantiate the first IPlugin type found
Type concreteType = pluginTypes.First();
var plugin = (IPlugin)Activator.CreateInstance(concreteType, pluginInitializer);
plugins.Add(plugin);
//Loading meta data
PluginMetaData metaData = null;
metaData = unitOfWork.PluginRepository.GetForFile(file);
if (metaData != null)
{
metaDataStore.Add(plugin, metaData);
}
else
{
throw new Exception("No PluginMetaData found for file " + file);
}
IoC.Get<ILogging>().Info(
String.Format("Loaded Plugin {0} - {1}",
metaData.Name,
metaData.Description));
}
else
{
IoC.Get<ILogging>().Error(
String.Format("No IPlugin implementation found in assembly {0}", file));
}
}
catch (Exception e)
{
IoC.Get<ILogging>().Error(
"Could not load plugin " + currentFile.FullName);
IoC.Get<ILogging>().Error(e.Message);
}
}
plugins = plugins.OrderByDescending(p => p.GetMetaData().Priority).ToList();
return plugins.Count;
}
}
public IEnumerable<IPlugin> GetPlugins()
{
return plugins;
}
public IEnumerable<T> GetPlugins<T>() where T : IPlugin
{
var concretPlugins = new List<T>();
foreach (var plugin in plugins)
{
if (plugin is T)
{
concretPlugins.Add((T)plugin);
}
}
return concretPlugins;
}
public T GetPlugin<T>() where T : IPlugin
{
IPlugin plugin = GetPlugins<T>().OrderByDescending(p => p.GetMetaData().Priority).FirstOrDefault();
if (plugin != null)
return (T)plugin;
return default(T);
}
public PluginMetaData GetMetaData(IPlugin plugin)
{
PluginMetaData ret;
metaDataStore.TryGetValue(plugin, out ret);
return ret;
}
#endregion
};
}
|
bennygr/noised
|
src/NoisedCore/Plugins/PluginLoader.cs
|
C#
|
gpl-2.0
| 4,643
|
/* created by click/linuxmodule/fixincludes.pl on Tue Nov 25 22:39:40 2014 */
/* from /lib/modules/2.6.27.5-117.fc10.i686/build/include/config/cgroup/sched.h */
|
songxingshen/myclick
|
include/click-linuxmodule/include0/config/cgroup/sched.h
|
C
|
gpl-2.0
| 161
|
<!DOCTYPE html>
<html>
<!-- Mirrored from www.w3schools.com/js/tryjs_datatypes_addstring.htm by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:14:24 GMT -->
<body>
<p id="demo"></p>
<script>
var x = 16 + "Volvo";
document.getElementById("demo").innerHTML = x;
</script>
</body>
<!-- Mirrored from www.w3schools.com/js/tryjs_datatypes_addstring.htm by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:14:24 GMT -->
</html>
|
platinhom/ManualHom
|
Coding/W3School/W3Schools_Offline_2015/www.w3schools.com/js/tryjs_datatypes_addstring.html
|
HTML
|
gpl-2.0
| 455
|
#pragma once
#include "pebble.h"
#include "row.h"
#include "queue.h"
typedef struct MenuCallbacks {
void (*select_click)(MenuLayer*, MenuIndex*, void*);
void (*remove_callback)(void*);
} MenuCallbacks;
typedef struct Menu {
int id;
struct Menu *menu;
int size;
char *title;
Row **row;
MenuCallbacks callbacks;
Window *window;
MenuLayer *layer;
uint32_t load_image_resource_id;
GBitmap *load_image;
BitmapLayer *load_layer;
} Menu;
extern Menu* menu_create(uint32_t load_image_resource_id, MenuCallbacks callbacks);
extern void menu_add_rows(void *menu, char *title, Queue *queue);
extern void menu_init_text_scroll(Menu **menu);
extern void menu_deinit_text_scroll();
|
victorhaggqvist/Slebble
|
src/c/menu.h
|
C
|
gpl-2.0
| 728
|
import javax.swing.JLabel;
|
plumer/java-8e-assignments
|
learn/ch12/MyFrameWithComponents.java
|
Java
|
gpl-2.0
| 27
|
<?php
/*-------------------------------------------------------------------------------------------------------------| www.vdm.io |------/
____ ____ __ __ __
/\ _`\ /\ _`\ __ /\ \__ __/\ \ /\ \__
\ \,\L\_\ __ _ __ ___ ___ ___ ___ \ \ \/\ \/\_\ ____\ \ ,_\ _ __ /\_\ \ \____ __ __\ \ ,_\ ___ _ __
\/_\__ \ /'__`\/\`'__\/' __` __`\ / __`\ /' _ `\ \ \ \ \ \/\ \ /',__\\ \ \/ /\`'__\/\ \ \ '__`\/\ \/\ \\ \ \/ / __`\/\`'__\
/\ \L\ \/\ __/\ \ \/ /\ \/\ \/\ \/\ \L\ \/\ \/\ \ \ \ \_\ \ \ \/\__, `\\ \ \_\ \ \/ \ \ \ \ \L\ \ \ \_\ \\ \ \_/\ \L\ \ \ \/
\ `\____\ \____\\ \_\ \ \_\ \_\ \_\ \____/\ \_\ \_\ \ \____/\ \_\/\____/ \ \__\\ \_\ \ \_\ \_,__/\ \____/ \ \__\ \____/\ \_\
\/_____/\/____/ \/_/ \/_/\/_/\/_/\/___/ \/_/\/_/ \/___/ \/_/\/___/ \/__/ \/_/ \/_/\/___/ \/___/ \/__/\/___/ \/_/
/------------------------------------------------------------------------------------------------------------------------------------/
@version 2.0.x
@created 22nd October, 2015
@package Sermon Distributor
@subpackage default_preachers-table.php
@author Llewellyn van der Merwe <https://www.vdm.io/>
@copyright Copyright (C) 2015. All Rights Reserved
@license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html
A sermon distributor that links to Dropbox.
/----------------------------------------------------------------------------------------------------------------------------------*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// Column counter
$column_nr = 1;
// build the table class
$color = $this->params->get('preachers_table_color');
switch ($color)
{
case 1:
// Red
$tableClass = ' metro-red';
break;
case 2:
// Purple
$tableClass = ' metro-purple';
break;
case 3:
// Green
$tableClass = ' metro-green';
break;
case 4:
// Dark Blue
$tableClass = ' metro-blue';
break;
case 6:
// Uikit style
$tableClass = ' uk-table';
break;
case 7:
// Custom Style
$tableClass = ' preachers-table';
break;
default:
// Light Blue and other
$tableClass = '';
break;
}
?>
<table class="footable<?php echo $tableClass; ?>" data-page-size="100">
<thead>
<tr>
<th data-toggle="true"><?php echo JText::_('COM_SERMONDISTRIBUTOR_NAME'); ?></th>
<?php if ($this->params->get('preachers_desc')): ?>
<th data-hide="all"><?php echo JText::_('COM_SERMONDISTRIBUTOR_DESCRIPTION'); $column_nr++; ?></th>
<?php endif; ?>
<?php if ($this->params->get('preachers_website')): ?>
<th data-hide="all"><?php echo JText::_('COM_SERMONDISTRIBUTOR_WEBSITE'); $column_nr++; ?></th>
<?php endif; ?>
<?php if ($this->params->get('preachers_email')): ?>
<th data-hide="all"><?php echo JText::_('COM_SERMONDISTRIBUTOR_EMAIL'); $column_nr++; ?></th>
<?php endif; ?>
<?php if ($this->params->get('preachers_hits')): ?>
<th data-type="numeric"><?php echo JText::_('COM_SERMONDISTRIBUTOR_HITS'); $column_nr++; ?></th>
<?php endif; ?>
<?php if ($this->params->get('preachers_sermon_count')): ?>
<th data-type="numeric" data-hide="phone,tablet"><?php echo JText::_('COM_SERMONDISTRIBUTOR_SERMON_COUNT'); $column_nr++;?></th>
<?php endif; ?>
</tr>
</thead>
<tfoot class="hide-if-no-paging">
<tr>
<td colspan="<?php echo $column_nr; ?>">
<div class="pagination pagination-centered"></div>
</td>
</tr>
</tfoot>
<tbody>
<?php foreach ($this->items as $item): ?>
<tr><?php $item->params = $this->params; echo JLayoutHelper::render('preachersrow', $item); ?></tr>
<?php endforeach; ?>
</tbody>
</table>
<script>
// page loading pause
jQuery(window).load(function() {
// do some stuff once page is loaded
jQuery('.footable').footable();
});
</script>
|
SermonDistributor/Joomla-3-Component
|
site/views/preachers/tmpl/default_preachers-table.php
|
PHP
|
gpl-2.0
| 4,011
|
Imports Keyoti.RapidFindReplace.WPF
Public Class ViewModelUsage
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
_searchTextBox.Focus()
End Sub
Sub _searchTextBox_KeyUp(sender As Object, e As KeyEventArgs)
If cb1.IsChecked Then
Dim viewModel As RapidFindReplaceControlViewModel = CType(_searchTextBox.DataContext, RapidFindReplaceControlViewModel)
viewModel.FindText(viewModel.FindScope)
End If
End Sub
End Class
|
keyoti/RapidFindReplaceWPF
|
RapidFindReplace-Demo-VB/Views/ViewModelUsage.xaml.vb
|
Visual Basic
|
gpl-2.0
| 605
|
<!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 textmining</title>
<link rel="stylesheet" type="text/css" href="../../CRAN_web.css" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="citation_title" content="Integration of Text Mining and Topic Modeling Packages [R package textmining version 0.0.1]" />
<meta name="citation_author1" content="Maciej Eder" />
<meta name="citation_author2" content="Tomasz Melcer" />
<meta name="citation_publication_date.Published" content="2016-09-26" />
<meta name="citation_public_url" content="https://CRAN.R-project.org/package=textmining" />
<meta name="DC.identifier" content="https://CRAN.R-project.org/package=textmining" />
<meta name="DC.publisher" content="Comprehensive R Archive Network (CRAN)" />
<style type="text/css">
table td { vertical-align: top; }
</style>
</head>
<body>
<h2>textmining: Integration of Text Mining and Topic Modeling Packages</h2>
<p>A framework for text mining and topic modelling. It provides an easy interface for using different topic modeling methods within R, by integrating the already existing packages. Full functionality of the package requires a local installation of 'TreeTagger'.</p>
<table summary="Package textmining summary">
<tr>
<td>Version:</td>
<td>0.0.1</td>
</tr>
<tr>
<td>Depends:</td>
<td><a href="../stylo/index.html">stylo</a>, <a href="../tm/index.html">tm</a>, <a href="../NLP/index.html">NLP</a>, <a href="../caret/index.html">caret</a></td>
</tr>
<tr>
<td>Imports:</td>
<td><a href="../mallet/index.html">mallet</a>, <a href="../rJava/index.html">rJava</a>, <a href="../networkD3/index.html">networkD3</a>, <a href="../wordcloud/index.html">wordcloud</a>, <a href="../dplyr/index.html">dplyr</a>, <a href="../koRpus/index.html">koRpus</a>, <a href="../topicmodels/index.html">topicmodels</a>, <a href="../slam/index.html">slam</a>, methods, <a href="../SnowballC/index.html">SnowballC</a></td>
</tr>
<tr>
<td>Suggests:</td>
<td><a href="../testthat/index.html">testthat</a>, <a href="../stringi/index.html">stringi</a>, <a href="../LDAvis/index.html">LDAvis</a></td>
</tr>
<tr>
<td>Published:</td>
<td>2016-09-26</td>
</tr>
<tr>
<td>Author:</td>
<td>Jan Idziak [cre],
Maciej Eder [aut],
Tomasz Melcer [aut],
Andrew Goldstone [cph]</td>
</tr>
<tr>
<td>Maintainer:</td>
<td>Jan Idziak <JanIdziak at gmail.com></td>
</tr>
<tr>
<td>License:</td>
<td><a href="../../licenses/GPL-3">GPL-3</a></td>
</tr>
<tr>
<td>NeedsCompilation:</td>
<td>no</td>
</tr>
<tr>
<td>Materials:</td>
<td><a href="README.html">README</a> </td>
</tr>
<tr>
<td>CRAN checks:</td>
<td><a href="../../checks/check_results_textmining.html">textmining results</a></td>
</tr>
</table>
<h4>Downloads:</h4>
<table summary="Package textmining downloads">
<tr>
<td> Reference manual: </td>
<td> <a href="textmining.pdf"> textmining.pdf </a> </td>
</tr>
<tr>
<td> Package source: </td>
<td> <a href="../../../src/contrib/textmining_0.0.1.tar.gz"> textmining_0.0.1.tar.gz </a> </td>
</tr>
<tr>
<td> Windows binaries: </td>
<td> r-devel: <a href="../../../bin/windows/contrib/3.5/textmining_0.0.1.zip">textmining_0.0.1.zip</a>, r-release: <a href="../../../bin/windows/contrib/3.4/textmining_0.0.1.zip">textmining_0.0.1.zip</a>, r-oldrel: <a href="../../../bin/windows/contrib/3.3/textmining_0.0.1.zip">textmining_0.0.1.zip</a> </td>
</tr>
<tr>
<td> OS X El Capitan binaries: </td>
<td> r-release: <a href="../../../bin/macosx/el-capitan/contrib/3.4/textmining_0.0.1.tgz">textmining_0.0.1.tgz</a> </td>
</tr>
<tr>
<td> OS X Mavericks binaries: </td>
<td> r-oldrel: <a href="../../../bin/macosx/mavericks/contrib/3.3/textmining_0.0.1.tgz">textmining_0.0.1.tgz</a> </td>
</tr>
</table>
<h4>Linking:</h4>
<p>Please use the canonical form
<a href="https://CRAN.R-project.org/package=textmining"><samp>https://CRAN.R-project.org/package=textmining</samp></a>
to link to this page.</p>
</body>
</html>
|
esander91/NamespacePollution
|
Code/GetMetaDataFromCRAN/raw_html/textmining.html
|
HTML
|
gpl-2.0
| 4,208
|
#!/usr/bin/perl
##########################################################################
# This program estimates transition probabilities for the GHMM
# bmajoros@tigr.org
##########################################################################
use strict;
use GffTranscriptReader;
my $usage="$0 <*.gff>";
die "$usage\n" unless @ARGV==1;
my ($chunksGff)=@ARGV;
my $gffReader=new GffTranscriptReader();
my $transcripts=$gffReader->loadGFF($chunksGff);#"chunks.gff");
my ($AG_GT,$AG_TAG,$ATG_GT,$ATG_TAG);
my (@intronPhases,@GT,@AG,@initGT,@finalAG);
my $numTranscripts=@$transcripts;
for(my $i=0 ; $i<$numTranscripts ; ++$i)
{
my $transcript=$transcripts->[$i];
my $strand=$transcript->getStrand();
my $numExons=$transcript->numExons();
if($numExons==1) {++$ATG_TAG}
else
{
++$ATG_GT;
++$AG_TAG;
my $numAG=$numExons-1;
$AG_GT+=($numAG-1);
# Now handle intron phases
for(my $i=0 ; $i<$numExons ; ++$i)
{
my $exon=$transcript->getIthExon($i);
my $exonFrame=$exon->getFrame();
my $exonLength=$exon->getLength();
my $beginPhase=$exonFrame;
my $endPhase=($beginPhase+$exonLength)%3;
my $hasDonor=($i+1<$numExons);
my $hasAcceptor=($i>0);
if($hasDonor) {++$GT[$endPhase]}
if($hasAcceptor) {++$AG[$beginPhase]}
if($hasDonor && $hasAcceptor)
{++$intronPhases[$beginPhase]->[$endPhase]}
if(!$hasAcceptor && $hasDonor) {++$initGT[$endPhase]} # initial exon
if($hasAcceptor && !$hasDonor) {++$finalAG[$beginPhase]} # final exon
}
}
}
my $AG=$AG_GT+$AG_TAG;
my $GT=$AG_GT+$ATG_GT;
my $ATG=$ATG_GT+$ATG_TAG;
my $TAG=$AG_TAG+$ATG_TAG;
my $P_ATG_GT=$ATG_GT/$ATG;
my $P_ATG_TAG=$ATG_TAG/$ATG;
my $P_AG_GT=$AG_GT/$AG;
my $P_AG_TAG=$AG_TAG/$AG;
my $P_mGT_mATG=$ATG_GT/$GT;
my $P_mGT_mAG=$AG_GT/$GT;
my $P_mTAG_mATG=$ATG_TAG/$TAG;
my $P_mTAG_mAG=$AG_TAG/$TAG;
my $numSignalTypes=24; # |{ATG,GT,AG,TAG,POLYA,PROMOTER,GT#,AG#}|=12, *2=24
print "$numSignalTypes\n";
# FORWARD STRAND:
print "PROMOTER -> ATG : 1\n";
print "ATG -> GT : $P_ATG_GT\n";
print "ATG -> TAG : $P_ATG_TAG\n";
print "GT -> AG : 1\n";
print "AG -> GT : $P_AG_GT\n";
print "AG -> TAG : $P_AG_TAG\n";
print "TAG -> POLYA : 0.5\n";
print "TAG -> ATG : 0.125\n";
print "TAG -> PROMOTER : 0.125\n";
print "TAG -> -TAG : 0.125\n";
print "TAG -> -POLYA : 0.125\n";
print "POLYA -> ATG : 0.25\n";
print "POLYA -> PROMOTER : 0.25\n";
print "POLYA -> -TAG : 0.25\n";
print "POLYA -> -POLYA : 0.25\n";
for(my $i=0 ; $i<3 ; ++$i)
{
print "GT$i -> AG$i : 1\n";
my $AGi=$AG[$i];
for(my $j=0 ; $j<3 ; ++$j)
{
my $AGi_GTj=$intronPhases[$i]->[$j];
my $p=$AGi_GTj/$AGi;
print "AG$i -> GT$j : $p\n";
}
my $GTi=$initGT[$i];
my $ATG_GTi=$GTi/$ATG;
print "ATG -> GT$i : $ATG_GTi\n";
my $final_AGi=$finalAG[$i];
my $AGi_TAG=$final_AGi/$AGi;
print "AG$i -> TAG : $AGi_TAG\n";
}
# REVERSE STRAND:
print "-PROMOTER -> ATG : 0.25\n";
print "-PROMOTER -> PROMOTER : 0.25\n";
print "-PROMOTER -> -TAG : 0.25\n";
print "-PROMOTER -> -POLYA : 0.25\n";
print "-ATG -> -PROMOTER : 0.5\n";
print "-ATG -> ATG : 0.125\n";
print "-ATG -> PROMOTER : 0.125\n";
print "-ATG -> -TAG : 0.125\n";
print "-ATG -> -POLYA : 0.125\n";
print "-GT -> -ATG : $P_mGT_mATG\n";
print "-GT -> -AG : $P_mGT_mAG\n";
print "-AG -> -GT : 1\n";
print "-TAG -> -ATG : $P_mTAG_mATG\n";
print "-TAG -> -AG : $P_mTAG_mAG\n";
print "-POLYA -> -TAG : 1\n";
for(my $i=0 ; $i<3 ; ++$i)
{
print "-AG$i -> -GT$i : 1\n";
my $GTi=$GT[$i];
for(my $j=0 ; $j<3 ; ++$j)
{
my $AGj_GTi=$intronPhases[$j]->[$i];
my $p=$AGj_GTi/$GTi;
print "-GT$i -> -AG$j : $p\n";
}
my $init_GTi=$initGT[$i];
my $GTi_ATG=$init_GTi/$GTi;
print "-GT$i -> -ATG : $GTi_ATG\n";
my $final_AGi=$finalAG[$i];
my $TAG_AGi=$final_AGi/$TAG;
print "-TAG -> -AG$i : $TAG_AGi\n";
}
|
bmajoros/GeneZilla
|
get-trans-distr.pl
|
Perl
|
gpl-2.0
| 3,865
|
<?php
/* * * * * * * * * *
* Author: Calc, calc@list.ru, 8(916) 506-7002
* mxtel, 2010, Calc (r)
* * * * * * * * * */
defined("INDEX") or die('404 go to <a href="/">index.php</a>');
$do = get_var('do',0);
$id = get_var('id',0);
$pid = get_var('pid',0);
$type= get_var('type','port'); //get for ajah
$oid = get_var('oid',0);
$table = 'inbound_opts';
$tbl = new tbl($table);
// id oid pid type tid
list($oid, $pid, $type, $tid) =
array(
post_var('oid',$oid), post_var('pid',$pid),
post_var('type',$type), post_var('tid'));
switch($do) {
case 1: //добавляем элемент
_mysql_query($tbl->insert(
array(0, $oid, $pid, $type, $tid)));
redir("gr=$gr&oid=$oid&pid=$pid",1);
break;
case 2:
$hide = $_GET['hide'];
if($hide!=1) $hide=0;
_mysql_query($tbl->update_k(array('id'=>$id), array('hide'=>$hide)));
redir("gr=$gr&oid=$oid&pid=$pid",1);
break;
case 10:
_mysql_query($tbl->update(array('id'=>$id),
array(0, $oid, $pid, $type, $tid)));
redir("gr=$gr&oid=$oid&pid=$pid",1);
break;
case 11:
do_del($table,$id,"gr=$gr&oid=$oid&pid=$pid",'','',1);
break;
case 'ajah_tid':
$ret = '';
$tbl = $type;
if($type=='port'){ $tbl = 'users'; $n = 'intno';}
$ret.= tag_f_se('tid', $tid, db_sel1($tbl, $n, '', "where oid=$oid"));
echo $ret;
exit();
break;
case 'ajah_main':
$ret = maintbl();
echo $ret;
exit();
break;
}
$tid = 0;
if($id) {
$q = "select * from $table where id=$id";
$r = mysql_query($q);
list($id,$oid, $pid,$type,$tid) = mysql_fetch_array($r);
}
$int_a = db_sel('users','intno','',"oid=$oid and ");
$int_a[0] = 'Внешний';
$peer_a = db_sel('peers','','',"oid in($oid,24) and ");
//$peer_a1 = $peer_a2;
$peer_a[0] = 'Все';
$body.='
<form action="?gr='.$gr.'&oid='.$oid.'&pid='.$pid.'&do='.( ($id==0) ? 1 : 10 ).'&id='.$id.'" method="post">
Пир: '.tag_f_se('pid',$pid, $peer_a,'pid').'
Тип: '.tag_f_se('type',$type,$r_types,'type',1).'
Значение: <span id="tid">'.tag_f_se('tid',$tid,db_sel1('users', 'intno','',$w="where oid=$oid")).'</span>
'.tag_f_sm($id).'
'.tag_f_hi('oid',$oid).'
</form>';
// запрос для формы ajah
$jq.= "
$(\"#pid\").change(function() {
val = $(\"#pid\").val();
url = './?gr=$gr&oid=$oid&pid=' + val + '&do=ajah_main';
$(\"#main\").text(\"\").load(url);
});
$(\"#type\").change(function() {
val = $(\"#type\").val();
url = './?gr=$gr&oid=$oid&pid=$pid&do=ajah_tid&type=' + val;
$(\"#tid\").text(\"\").load(url);
});
";
$body.= tag_a("?gr=user&oid=$oid",'Назад');
$body.= '<div id="main">';
$body.= maintbl();
$body.= '</div>';
function maintbl() {
global $gr,$oid,$pid,$table;
$q = " select
io.id, io.oid, io.pid, io.type, io.tid,
p.name, o.name
from
$table as io
left join peers as p on p.id=io.pid
left join org as o on o.id=io.oid
where io.pid=$pid
order by io.type";
//echo $q;
$r = _mysql_query($q);
$n = mysql_num_rows($r);
$body = '';
$body.= tag_t_o_('maintbl');
$body.= tag_tr();
$body.= tag_th('id');
$body.= tag_th('oid');
$body.= tag_th('pid');
$body.= tag_th('type');
$body.= tag_th('tid');
$body.= tag_th('x');
$body.= tag_tr(1);
$exten = '';
if($n) {
for($i=0;$i<$n;$i++) {
list($id, $oid, $pid, $type, $tid, $pname, $oname) = mysql_fetch_array($r);
$body.= tag_tr();
$body.= tag_td(tag_a("?gr=$gr&oid=$oid&pid=$pid&id=$id",$id),$i);
$body.= tag_td($oname,$i);
$body.= tag_td($pname,$i);
$body.= tag_td($type,$i);
$body.= tag_td(db_field('users', $tid, 'intno'),$i);
$body.= tag_td(tag_a_x("?gr=$gr&oid=$oid&pid=$pid&id=$id&do=11"),$i);
$acc = '';
$body.= tag_tr(1);
}
}
$body.= '<td colspan="9">'.$n.' записей</td>';
$body.= tag_t_c();
$exten = file_get_contents("./tmp/ext.inbound");
$body.= '<pre>';
$body.= $exten;
$body.= '</pre>';
$body.= 'Входящая маршрутизация устанавливает макрос, который будет обслуживать
входящий вызов. Если макрос не указан, то вызов будет поступать на все
локальные номера, закрепленные за пиром.';
return $body;
}
|
Calc86/tel
|
mods/iopt.php
|
PHP
|
gpl-2.0
| 4,787
|
package com.dynamo2.tianma.model;
public class ObjectField extends MongodbModel {
private String name;
private String uniqueMark;
private int type;
private String linkedObject;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUniqueMark() {
return uniqueMark;
}
public void setUniqueMark(String uniqueMark) {
this.uniqueMark = uniqueMark;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getLinkedObject() {
return linkedObject;
}
public void setLinkedObject(String linkedObject) {
this.linkedObject = linkedObject;
}
}
|
dynamo2/tianma
|
mycrm/src/main/java/com/dynamo2/tianma/model/ObjectField.java
|
Java
|
gpl-2.0
| 715
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<% hijack_title() %>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="style/hijack_style.css" />
<script language="javascript" type="text/javascript" src="script/brs_hijack.js"></script>
<script language="javascript" type="text/javascript" src="script/brs_hijack_03A_E_IP_problem_staticIP_B_macClone_plzWait.js"></script>
<% hijack_language() %>
</head>
<body>
<% form_submit("func", "BRS_03A_detcInetType.html", "wizard_detwan") %>
<div class="wizard_content_div">
<div class="wizard_words_div">
<div class="waiting_connect_div" align="center">
<h1 class="h1_black"><!--please waite a moment--></h1>
</div>
<div class="waiting_img_div" align="center">
<img id="waiting_img" alt="waiting" />
</div>
</div>
</div>
</form>
</body>
</html>
|
emuikernel/WNR2000v4
|
git_home/net-web.git/www/browser_hijack/BRS_03A_E_IP_problem_staticIP_B_macClone_plzWait.html
|
HTML
|
gpl-2.0
| 968
|
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : Variable Reference: $disp_payload_begin</title>
<link rel="stylesheet" href="../sample.css" type="text/css">
<link rel="stylesheet" href="../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Sat Nov 21 22:13:19 2015 -->
<!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net -->
<!-- http://phpxref.sourceforge.net/ -->
<script src="../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
ext='.html';
relbase='../';
subdir='_variables';
filename='index.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
logVariable('disp_payload_begin');
// -->
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
[<a href="../index.html">Top level directory</a>]<br>
<script language="JavaScript" type="text/javascript">
<!--
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
// -->
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h3>Variable Cross Reference</h3>
<h2><a href="index.html#disp_payload_begin">$disp_payload_begin</a></h2>
<br><b>Referenced 1 times:</b><ul>
<li><a href="../inc/items/items.ctrl.php.html">/inc/items/items.ctrl.php</a> -> <a href="../inc/items/items.ctrl.php.source.html#l1957"> line 1957</a></li>
</ul>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Sat Nov 21 22:13:19 2015</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
|
mgsolipa/b2evolution_phpxref
|
_variables/disp_payload_begin.html
|
HTML
|
gpl-2.0
| 4,557
|