code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
/*
Copyright (C) 2009 by Joris Guisson (joris.guisson@gmail.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "httpannouncejob.h"
#include <version.h>
#include <klocalizedstring.h>
#include <util/log.h>
#include <util/functions.h>
#include <QTimer>
#include <QTcpSocket>
namespace bt
{
HTTPAnnounceJob::HTTPAnnounceJob(const QUrl& url) : url(url), get_id(0), proxy_port(-1)
{
qWarning()<<"not ported";
/*
http = new QHttp(this); PORT: KF5
connect(http, &QHttp::requestFinished, this, &HTTPAnnounceJob::requestFinished);
connect(http, &QHttp::readyRead, this, &HTTPAnnounceJob::readData);
connect(http, &QHttp::sslErrors, this, &HTTPAnnounceJob::sslErrors);
*/
}
HTTPAnnounceJob::~HTTPAnnounceJob()
{
}
void HTTPAnnounceJob::start()
{
sendRequest();
}
void HTTPAnnounceJob::sendRequest()
{
/*QHttp::ConnectionMode mode = url.protocol() == "https" ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp; PORT: KF5
quint16 port = url.port() < 0 ? 0 : url.port();
quint16 default_port = mode == QHttp::ConnectionModeHttps ? 443 : 80;
http->setHost(url.host(), mode, port);
if (!proxy_host.isEmpty() && proxy_port > 0)
http->setProxy(proxy_host, proxy_port);
QHttpRequestHeader hdr("GET", url.encodedPathAndQuery(), 1, 1);
hdr.setValue("User-Agent", bt::GetVersionString());
hdr.setValue("Connection", "close");
hdr.setValue("Host", QString("%1:%2").arg(url.host()).arg(url.port(default_port)));
get_id = http->request(hdr);
Out(SYS_TRK | LOG_DEBUG) << "Request sent" << endl;*/
}
void HTTPAnnounceJob::kill(bool quietly)
{
/*http->abort();PORT: KF5
if (!quietly)
emitResult();*/
}
void HTTPAnnounceJob::requestFinished(int id, bool err)
{
/*if (get_id != id) PORT: KF5
return;
if (err)
{
setErrorText(http->errorString());
emitResult();
}
else
{
switch (http->lastResponse().statusCode())
{
case 300:
case 301:
case 302:
case 303:
case 307:
handleRedirect(http->lastResponse());
break;
case 403:
setError(KIO::ERR_ACCESS_DENIED);
emitResult();
break;
case 404:
setError(KIO::ERR_DOES_NOT_EXIST);
emitResult();
break;
case 500:
setError(KIO::ERR_INTERNAL_SERVER);
emitResult();
break;
default:
emitResult();
break;
}
}*/
}
// void HTTPAnnounceJob::readData(const QHttpResponseHeader& hdr) PORT: KF5
// {
// const int MAX_REPLY_SIZE = 1024 * 1024;
//
// int ba = http->bytesAvailable();
// int current_size = reply_data.size();
// if (current_size + ba > MAX_REPLY_SIZE)
// {
// // If the reply is larger then a mega byte, the server
// // has probably gone bonkers
// http->abort();
// Out(SYS_TRK | LOG_DEBUG) << "Tracker sending back to much data in announce reply, aborting ..." << endl;
// }
// else
// {
// // enlarge reply data and read data to it
// reply_data.resize(current_size + ba);
// http->read(reply_data.data() + current_size, ba);
// }
// }
void HTTPAnnounceJob::setProxy(const QString& host, int port)
{
proxy_host = host;
proxy_port = port;
}
// void HTTPAnnounceJob::handleRedirect(const QHttpResponseHeader& hdr) PORT: KF5
// {
// if (!hdr.hasKey("Location"))
// {
// setErrorText(i18n("Redirect without a redirect location"));
// emitResult();
// }
// else
// {
// reply_data.clear();
// url = hdr.value("Location");
// Out(SYS_TRK | LOG_DEBUG) << "Redirected to " << hdr.value("Location") << endl;
// sendRequest();
// }
// }
void HTTPAnnounceJob::sslErrors(const QList<QSslError>& errors)
{
/*KUrl u = url; PORT: KF5
u.setQuery(QString());
Out(SYS_TRK | LOG_NOTICE) << "SSL errors detected when announcing to " << u.prettyUrl() << ":" << endl;
foreach (const QSslError& err, errors)
Out(SYS_TRK | LOG_NOTICE) << err.errorString() << endl;
Out(SYS_TRK | LOG_NOTICE) << "Errors will be ignored " << endl;
http->ignoreSslErrors();*/
}
}
| fonic/libktorrent | src/tracker/httpannouncejob.cpp | C++ | gpl-2.0 | 5,476 |
<?php
/**
* NoNumber Framework Helper File: Assignments: ZOO
*
* @package NoNumber Framework
* @version 12.7.9
*
* @author Peter van Westen <peter@nonumber.nl>
* @link http://www.nonumber.nl
* @copyright Copyright © 2012 NoNumber All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
// No direct access
defined('_JEXEC') or die;
/**
* Assignments: ZOO
*/
class NNFrameworkAssignmentsZOO
{
var $_version = '12.7.9';
/**
* passCategories_Zoo
*
* @param <object> $params
* inc_children
* inc_categories
* inc_items
* @param <array> $selection
* @param <string> $assignment
*
* @return <bool>
*/
function passCategories_ZOO(&$main, &$params, $selection = array(), $assignment = 'all', $article = 0)
{
if ($main->_params->option != 'com_zoo') {
return ($assignment == 'exclude');
}
if (!$main->_params->view) {
$main->_params->view = $main->_params->task;
}
$pass = (
($params->inc_apps && $main->_params->view == 'frontpage')
|| ($params->inc_categories && $main->_params->view == 'category')
|| ($params->inc_items && $main->_params->view == 'item')
);
if (!$pass) {
return ($assignment == 'exclude');
}
$selection = $main->makeArray($selection);
$cats = array();
if ($article && isset($article->catid)) {
$cats = $article->catid;
} else {
switch ($main->_params->view) {
case 'frontpage':
if ($main->_params->id) {
$cats[] = $main->_params->id;
} else {
$menuparams = $main->getMenuItemParams($main->_params->Itemid);
if (isset($menuparams->application)) {
$cats[] = 'app'.$menuparams->application;
}
}
break;
case 'category':
if ($main->_params->id) {
$cats[] = $main->_params->id;
} else {
$menuparams = $main->getMenuItemParams($main->_params->Itemid);
if (isset($menuparams->category)) {
$cats[] = $menuparams->category;
}
}
if ($cats['0']) {
$query = $main->_db->getQuery(true);
$query->select('c.application_id');
$query->from('#__zoo_category AS c');
$query->where('c.id = '.(int) $cats['0']);
$main->_db->setQuery($query);
if ($main->_db->loadResult()) {
$cats[] = 'app'.$main->_db->loadResult();
}
}
break;
case 'item':
$id = $main->_params->id;
if (!$id) {
$menuparams = $main->getMenuItemParams($main->_params->Itemid);
$id = isset($menuparams->item_id) ? $menuparams->item_id : '';
}
if ($id) {
$query = $main->_db->getQuery(true);
$query->select('c.category_id');
$query->from('#__zoo_category_item AS c');
$query->where('c.item_id = '.(int) $id);
$query->where('c.category_id != 0');
$main->_db->setQuery($query);
$cats = $main->_db->loadResultArray();
$query = $main->_db->getQuery(true);
$query->select('i.application_id');
$query->from('#__zoo_item AS i');
$query->where('i.id = '.(int) $id);
$main->_db->setQuery($query);
$cats[] = 'app'.$main->_db->loadResult();
}
break;
default:
return ($assignment == 'exclude');
break;
}
}
$cats = $main->makeArray($cats);
$pass = $main->passSimple($cats, $selection, 'include');
if ($pass && $params->inc_children == 2) {
return ($assignment == 'exclude');
} else if (!$pass && $params->inc_children) {
foreach ($cats as $cat) {
$cats = array_merge($cats, self::getCatParentIds($main, $cat));
}
}
return $main->passSimple($cats, $selection, $assignment);
}
function getCatParentIds(&$main, $id = 0)
{
$parent_ids = array();
if (!$id) {
return $parent_ids;
}
while ($id) {
if (substr($id, 0, 3) == 'app') {
$parent_ids[] = $id;
break;
} else {
$query = $main->_db->getQuery(true);
$query->select('c.parent');
$query->from('#__zoo_category AS c');
$query->where('c.id = '.(int) $id);
$main->_db->setQuery($query);
$pid = $main->_db->loadResult();
if ($pid) {
$parent_ids[] = $pid;
} else {
$query = $main->_db->getQuery(true);
$query->select('c.application_id');
$query->from('#__zoo_category AS c');
$query->where('c.id = '.(int) $id);
$main->_db->setQuery($query);
$app = $main->_db->loadResult();
if ($app) {
$parent_ids[] = 'app'.$app;
}
break;
}
$id = $pid;
}
}
return $parent_ids;
}
} | Jak95/www.jak95.ru-joomla | plugins/system/nnframework/helpers/assignments/zoo.php | PHP | gpl-2.0 | 4,496 |
<?php
sql_column_exists('users', 'gp_id' , '!ALTER TABLE `users` ADD COLUMN `gp_id` BIGINT(20) NULL AFTER `fb_token`');
sql_column_exists('users', 'gp_token', '!ALTER TABLE `users` ADD COLUMN `gp_token` VARCHAR(255) NULL AFTER `gp_id`');
sql_column_exists('users', 'tw_id' , '!ALTER TABLE `users` ADD COLUMN `tw_id` BIGINT(20) NULL AFTER `gp_token`');
sql_column_exists('users', 'tw_token', '!ALTER TABLE `users` ADD COLUMN `tw_token` VARCHAR(255) NULL AFTER `tw_id`');
sql_column_exists('users', 'ms_id' , '!ALTER TABLE `users` ADD COLUMN `ms_id` BIGINT(20) NULL AFTER `tw_token`');
sql_column_exists('users', 'ms_token', '!ALTER TABLE `users` ADD COLUMN `ms_token` VARCHAR(255) NULL AFTER `ms_id`');
sql_column_exists('users', 'yh_id' , '!ALTER TABLE `users` ADD COLUMN `yh_id` BIGINT(20) NULL AFTER `ms_token`');
sql_column_exists('users', 'yh_token', '!ALTER TABLE `users` ADD COLUMN `yh_token` VARCHAR(255) NULL AFTER `yh_id`');
?>
| phoenixz/base | init/framework/0.3.2.php | PHP | gpl-2.0 | 968 |
<?php
class td_module_blog extends td_module {
var $td_post_theme_settings;
var $is_single; //true if we are on a single page
function __construct($post = '') {
// construct the class without the post object, used in the author template for the box
if (empty($post)) {
return;
}
parent::__construct($post);
//read post settings
$this->td_post_theme_settings = get_post_meta($post->ID, 'td_post_theme_settings', true);
$this->is_single = is_single();
}
function get_social_sharing() {
$social_sharing = 1;
$closing_class_tags = 'td-tags-and-social-wrapper-box-bottom-line';
if (!$this->is_single) {
return;
}
$buffy = $this_post_tags = $wrapper_post_tags = '';
if (td_util::get_option('tds_social_show') == 'hide') {
$social_sharing = 0;
} else {
$closing_class_tags = '';
}
//if the post has tags
$this_post_tags = $this->get_the_tags();
if(!empty($this_post_tags)) {
$wrapper_post_tags = '<div class="td-tags-and-social-wrapper-box ' . $closing_class_tags . '"> ' . $this_post_tags . '</div>';
}
$buffy .= '
<div class="td-social-sharing">
' . $wrapper_post_tags;
if($social_sharing == 1) {
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $this->post->ID ), 'single-post-thumbnail' );
$twetter_user = td_util::get_option('tds_tweeter_username');
$buffy .= '
<div class="td-tags-and-social-wrapper-box td-tags-and-social-wrapper-box-bottom-line">
<a class="td-social-sharing-buttons td-social-twitter" href="https://twitter.com/intent/tweet?text=' . urlencode($this->title) . '&url=' . urlencode(get_permalink()) . '&via=' . urlencode($twetter_user ? $twetter_user : get_bloginfo('name')) .'" onclick="if(!document.getElementById(\'td_social_networks_buttons\')){window.open(this.href, \'mywin\',
\'left=50,top=50,width=600,height=350,toolbar=0\'); return false;}" ><div class="td-sp td-sp-share-twitter"></div><div class="td-social-but-text">Twitter</div></a>
<a class="td-social-sharing-buttons td-social-facebook" href="http://www.facebook.com/sharer.php?u=' . urlencode(get_permalink()) . '" onclick="window.open(this.href, \'mywin\',
\'left=50,top=50,width=600,height=350,toolbar=0\'); return false;"><div class="td-sp td-sp-share-facebook"></div><div class="td-social-but-text">Facebook</div></a>
<a class="td-social-sharing-buttons td-social-google" href="http://plus.google.com/share?url=' . get_permalink() . '" onclick="window.open(this.href, \'mywin\',
\'left=50,top=50,width=600,height=350,toolbar=0\'); return false;"><div class="td-sp td-sp-share-google"></div><div class="td-social-but-text">Google +</div></a>
<a class="td-social-sharing-buttons td-social-pinterest" href="http://pinterest.com/pin/create/button/?url=' . get_permalink() . '&media=' . (!empty($image[0]) ? $image[0] : '') . '" onclick="window.open(this.href, \'mywin\',
\'left=50,top=50,width=600,height=350,toolbar=0\'); return false;"><div class="td-sp td-sp-share-pinterest"></div><div class="td-social-but-text">Pinterest</div></a>
</div>';
}
return $buffy . '</div>';
}
function get_social_like_tweet() {
if (!$this->is_single) {
return;
}
if (td_util::get_option('tds_like_tweet_show') != 'show') {
return;
}
$buffy = '';
$buffy .= '<div id="td_social_networks_buttons" class="td-social-like-tweet">';
$buffy .= '<ul>';
$buffy .= '<li class="td-like-tweet-twitter">';
$buffy .= '<a href="https://twitter.com/share" class="twitter-share-button" data-url="' . $this->href . '" data-text="' . $this->title . '" data-via="' . td_util::get_option('tds_' . 'social_twitter') . '" data-lang="en">tweet</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>';
$buffy .= '</li>';
$buffy .= '<li class="td-like-tweet-facebook">';
$buffy .= '<iframe src="http://www.facebook.com/plugins/like.php?href=' . $this->href . '&layout=button_count&show_faces=false&width=105&action=like&colorscheme=light&height=21" style="border:none; overflow:hidden; width:105px; height:21px; background-color:transparent;"></iframe>';
$buffy .= '</li>';
$buffy .= '<li class="td-like-tweet-google">';
$buffy .= '
<div class="g-plusone" data-size="medium" data-href="' . $this->href . '"></div>
<script type="text/javascript">
(function() {
var po = document.createElement("script"); po.type = "text/javascript"; po.async = true;
po.src = "https://apis.google.com/js/plusone.js";
var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(po, s);
})();
</script>
';
$buffy .= '</li>';
$buffy .= '</ul>';
$buffy .= '</div>';
return $buffy;
}
function get_post_pagination() {
if (!$this->is_single) {
return;
}
return wp_link_pages(array(
'before' => '<div class="page-nav page-nav-post">',
'after' => '</div>',
'link_before' => '<span>',
'link_after' => '</span>',
'echo' => false,
'nextpagelink' => ' ' . __td('Next') . ' <img width="6" class="td-retina right-arrow" src="' . get_template_directory_uri() . '/images/icons/similar-right.png" alt=""/>',
'previouspagelink' => '<img width="6" class="td-retina left-arrow" src="' . get_template_directory_uri() . '/images/icons/similar-left.png" alt=""/> ' . __td('Prev')
));
}
function get_title($excerpt_lenght = '') {
//just use h1 instead of h3
$var_single = 0;
if (is_single()) {
$var_single = 1;
}
$buffy = '';
$buffy .= '<h1 itemprop="name" class="entry-title">';
if ($var_single == 0) {
$buffy .='<a itemprop="url" href="' . $this->href . '" rel="bookmark" title="' . $this->title_attribute . '">';
}
$buffy .= $this->title;
if ($var_single == 0) {
$buffy .='</a>';
}
$buffy .= '</h1>';
return $buffy;
}
//$show_stars_on_review - not used
function get_author($show_stars_on_review = '') {
$buffy = '';
$buffy .='<div class="td-clear-author"></div>';
$buffy .= parent::get_author(false);
return $buffy;
}
/**
* get_image v010 - modified on wp_010 - returns the featured image of a single post
* @param $thumbType
* @return string
*/
function get_image($thumbType) {
global $page;
//show only on the first page when we have posts with pages
if (!empty($page) and $page > 1) {
return;
}
//do not show the featured image if the global setting is set to hide - show the video preview regardless of the setting
if (td_util::get_option('tds_show_featured_image') == 'hide' and get_post_format($this->post->ID) != 'video') {
return;
}
//do not show the featured image on gallery post format
if (get_post_format($this->post->ID) == 'gallery') {
return;
}
//handle video post format
if (get_post_format($this->post->ID) == 'video') {
//if it's a video post...
$td_post_video = get_post_meta($this->post->ID, 'td_post_video', true);
$td_video_support = new td_video_support();
//render the video if the post has a video in the featured video section of the post
if (!empty($td_post_video['td_video'])) {
return $td_video_support->renderVideo($td_post_video['td_video']);
}
} else {
//if it's a normal post, show the default thumb
if ($this->post_has_thumb) {
//get the featured image id + full info about the 640px wide one
$featured_image_id = get_post_thumbnail_id($this->post->ID);
$featured_image_info = td_util::attachment_get_full_info($featured_image_id, $thumbType);
//get the full size for the popup
$featured_image_full_size_src = td_util::attachment_get_src($featured_image_id, 'full');
$buffy = '';
$show_td_modal_image = td_util::get_option('tds_featured_image_view_setting') ;
if (is_single()) {
if ($show_td_modal_image != 'no_modal') {
//wrap the image_html with a link + add td-modal-image class
$image_html = '<a href="' . $featured_image_full_size_src['src'] . '" data-caption="' . htmlentities($featured_image_info['caption'], ENT_QUOTES) . '">';
$image_html .= '<img width="' . $featured_image_info['width'] . '" height="' . $featured_image_info['height'] . '" itemprop="image" class="entry-thumb td-modal-image" src="' . $featured_image_info['src'] . '" alt="' . $featured_image_info['alt'] . '" title="' . $featured_image_info['title'] . '"/>';
$image_html .= '</a>';
} else { //no_modal
$image_html = '<img width="' . $featured_image_info['width'] . '" height="' . $featured_image_info['height'] . '" itemprop="image" class="entry-thumb" src="' . $featured_image_info['src'] . '" alt="' . $featured_image_info['alt'] . '" title="' . $featured_image_info['title'] . '"/>';
}
} else {
//on blog index page
$image_html = '<a href="' . $this->href . '"><img width="' . $featured_image_info['width'] . '" height="' . $featured_image_info['height'] . '" itemprop="image" class="entry-thumb" src="' . $featured_image_info['src'] . '" alt="' . $featured_image_info['alt'] . '" title="' . $featured_image_info['title'] . '"/></a>';
}
$buffy .= '<div class="td-post-featured-image">';
// caption - put html5 wrapper on when we have a caption
if (!empty($featured_image_info['caption'])) {
$buffy .= '<figure>';
$buffy .= $image_html;
$buffy .= '<figcaption class="wp-caption-text">' . $featured_image_info['caption'] . '</figcaption>';
$buffy .= '</figure>';
} else {
$buffy .= $image_html;
}
$buffy .= '</div>';
return $buffy;
} else {
return ''; //the post has no thumb
}
}
}
function get_category() {
$buffy = '';
$buffy .= '<ul class="td-category">';
$categories = get_the_category($this->post->ID);
$cat_array = array();
if($categories){
foreach($categories as $category) {
if ($category->name != TD_FEATURED_CAT) { //ignore the featured category name
//get the parent of this cat
$td_parent_cat_obj = get_category($category->category_parent);
//if we have a parent, shot it first
if (!empty($td_parent_cat_obj->name)) {
$tax_meta__color_parent = td_util::get_category_option($td_parent_cat_obj->cat_ID,'tdc_color');//swich by RADU A, get_tax_meta($td_parent_cat_obj->cat_ID,'tdc_color');
$tax_meta__hide_on_post_parent = td_util::get_category_option($td_parent_cat_obj->cat_ID,'tdc_hide_on_post');//swich by RADU A, get_tax_meta($td_parent_cat_obj->cat_ID,'tdc_hide_on_post');
$cat_array[$td_parent_cat_obj->name] = array(
'color' => $tax_meta__color_parent,
'link' => get_category_link($td_parent_cat_obj->cat_ID),
'hide_on_post' => $tax_meta__hide_on_post_parent
);
}
//show the category, only if we didn't already showed the parent
$tax_meta_color = td_util::get_category_option($category->cat_ID,'tdc_color');//swich by RADU A, get_tax_meta($category->cat_ID,'tdc_color');
$tax_meta__hide_on_post_parent = td_util::get_category_option($category->cat_ID,'tdc_hide_on_post');//swich by RADU A, get_tax_meta($category->cat_ID,'tdc_hide_on_post');
$cat_array[$category->name] = array(
'color' => $tax_meta_color,
'link' => get_category_link($category->cat_ID),
'hide_on_post' => $tax_meta__hide_on_post_parent
);
}
}
}
foreach ($cat_array as $td_cat_name => $td_cat_parms) {
if ($td_cat_parms['hide_on_post'] == 'hide') {
continue;
}
if (!empty($td_cat_parms['color'])) {
$td_cat_color = ' style="background-color:' . $td_cat_parms['color'] . ';"';
} else {
$td_cat_color = '';
}
$buffy .= '<li class="entry-category"><a ' . $td_cat_color . ' href="' . $td_cat_parms['link'] . '">' . $td_cat_name . '</a></li>';
}
$buffy .= '</ul>';
return $buffy;
}
function get_item_scope() {
//show the review meta only on single posts that are reviews, the rest have to be article (in article lists)
if (td_review::has_review($this->td_review) and is_single()) {
return 'itemscope itemtype="http://schema.org/Review"';
} else {
return 'itemscope itemtype="http://schema.org/Article"';
}
}
function get_item_scope_meta() {
$buffy = ''; //the vampire slayer
$author_id = $this->post->post_author;
$buffy .= '<meta itemprop="author" content = "' . get_the_author_meta('display_name', $author_id) . '">';
$authorMetaGoogle = get_the_author_meta('googleplus', $author_id);
if (!empty($authorMetaGoogle)) {
echo '<a href="' . $authorMetaGoogle . '?rel=author"></a>';
}
if (td_review::has_review($this->td_review) and is_single()) { //show the review meta only on single posts that are reviews, the rest have to be article (in article lists)
$td_article_date_unix = get_the_time('U', $this->post->ID);
if (!empty($this->td_review['review'])) {
$buffy .= '<meta itemprop="about" content = "' . $this->td_review['review'] . '">';
} else {
//we have no review :|
$buffy .= '<meta itemprop="about" content = "' . $this->get_excerpt(25) . '">';
}
$buffy .= '<meta itemprop="itemreviewed" content = "' . $this->title . '">';
$buffy .= '<meta itemprop="datePublished" content="' . date(DATE_W3C, $td_article_date_unix) . '">';
//$buffy .= '<meta itemprop="url" rel="author" content = "' . get_author_posts_url($author_id) . '">';
$buffy .= '<span class="td-page-meta" itemprop="reviewRating" itemscope itemtype="' . td_global::$http_or_https . '://schema.org/Rating">';
$buffy .= '<meta itemprop="worstRating" content = "1">';
$buffy .= '<meta itemprop="bestRating" content = "5">';
$buffy .= '<meta itemprop="ratingValue" content = "' . td_review::calculate_total_stars($this->td_review) . '">';
$buffy .= ' </span>';
}
return $buffy;
}
function get_content() {
/* ----------------------------------------------------------------------------
Prepare the content
*/
$content = get_the_content(__td('Continue', TD_THEME_NAME));
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
/* ----------------------------------------------------------------------------
Smart list support @todo reorganizare partea asta
*/
$td_smart_list = get_post_meta($this->post->ID, 'td_smart_list', true);
if (!empty($td_smart_list['smart_list_template'])) {
switch ($td_smart_list['smart_list_template']) {
case 'td_smart_list_1':
$td_smart_list_obj = new td_smart_list_1();
break;
case 'td_smart_list_2':
$td_smart_list_obj = new td_smart_list_2();
break;
case 'td_smart_list_3':
$td_smart_list_obj = new td_smart_list_3();
break;
case 'td_smart_list_4':
$td_smart_list_obj = new td_smart_list_4();
break;
}
if (isset($td_smart_list_obj)) {
return $td_smart_list_obj->render_from_post_content($content);
} else {
//there was an error?
}
}
/* ----------------------------------------------------------------------------
end smart list - if we have a list, the function returns above
*/
/* ----------------------------------------------------------------------------
ad support on content
*/
$tds_inline_ad_paragraph = td_util::get_option('tds_inline_ad_paragraph');
$tds_inline_ad_align = td_util::get_option('tds_inline_ad_align');
if (td_util::is_ad_spot_enabled('content_inline') and is_single() ) {
if (empty($tds_inline_ad_paragraph)) {
$tds_inline_ad_paragraph = 0;
}
$content_buffer = ''; // we replace the content with this buffer at the end
$content_parts = preg_split('/(<p.*>)/U', $content, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
//print_r($content_parts);
//die;
//$content_parts = explode('<p>', $content);
foreach ($content_parts as $content_part_index => $content_part) {
if (!empty($content_part)) {
if ($tds_inline_ad_paragraph == $content_part_index / 2) { //we have 0 = > <p> 1 => content - that's why we have to divide by 2
//it's time to show the ad
switch ($tds_inline_ad_align) {
case 'left':
$content_buffer .= td_global_blocks::get_instance('td_ad_box')->render(array('spot_id' => 'content_inline', 'align' => 'left'));
break;
case 'right':
$content_buffer .= td_global_blocks::get_instance('td_ad_box')->render(array('spot_id' => 'content_inline', 'align' => 'right'));
break;
default:
$content_buffer .= td_global_blocks::get_instance('td_ad_box')->render(array('spot_id' => 'content_inline'));
break;
}
}
$content_buffer .= $content_part;
}
} //end foreach
$content = $content_buffer;
}
//add the top ad
if (td_util::is_ad_spot_enabled('content_top') and is_single()) {
$content = td_global_blocks::get_instance('td_ad_box')->render(array('spot_id' => 'content_top')) . $content;
}
//add bottom ad
if (td_util::is_ad_spot_enabled('content_bottom') and is_single()) {
$content = $content . td_global_blocks::get_instance('td_ad_box')->render(array('spot_id' => 'content_bottom'));
}
return $content;
}
/* ----------------------------------------------------------------------------
Single page
*/
function get_review() {
if (!$this->is_single) {
return;
}
if (td_review::has_review($this->td_review)) {
//print_r($this->td_review);
$buffy = '';
$buffy .= td_review::render_table($this->td_review);
return $buffy;
}
}
function get_source_and_via() {
if (!$this->is_single) {
return;
}
$buffy ='';
//via and sourcet
if (!empty($this->td_post_theme_settings['td_source']) or !empty($this->td_post_theme_settings['td_source_2']) or !empty($this->td_post_theme_settings['td_via']) or !empty($this->td_post_theme_settings['td_via_2'])) {
$buffy .= '<div class="post-source-via">';
if (!empty($this->td_post_theme_settings['td_via']) or !empty($this->td_post_theme_settings['td_via_2'])) {
$buffy .= '<div class="post-via"><span>' . __td('VIA') . '</span>';
if (!empty($this->td_post_theme_settings['td_via'])) {
$buffy .= ' <a rel="nofollow" href="' . $this->td_post_theme_settings['td_via_url'] . '">' . $this->td_post_theme_settings['td_via'] . '</a>';
}
if (!empty($this->td_post_theme_settings['td_via_2'])) {
$buffy .= ' <a rel="nofollow" href="' . $this->td_post_theme_settings['td_via_2_url'] . '">' . $this->td_post_theme_settings['td_via_2'] . '</a>';
}
$buffy .= '</div>';
}
if (!empty($this->td_post_theme_settings['td_source']) or !empty($this->td_post_theme_settings['td_source_2'])) {
$buffy .= '<div class="post-via"><span>' . __td('SOURCE') . '</span>';
if (!empty($this->td_post_theme_settings['td_source'])) {
$buffy .= ' <a rel="nofollow" href="' . $this->td_post_theme_settings['td_source_url'] . '">' . $this->td_post_theme_settings['td_source'] . '</a>';
}
if (!empty($this->td_post_theme_settings['td_source_2'])) {
$buffy .= ' <a rel="nofollow" href="' . $this->td_post_theme_settings['td_source_2_url'] . '">' . $this->td_post_theme_settings['td_source_2'] . '</a>';
}
$buffy .= '</div>';
}
$buffy .= '</div>';
}
return $buffy;
}
function get_the_tags() {
if (!$this->is_single) {
return;
}
if (td_util::get_option('tds_show_tags') == 'hide') {
return;
}
$buffy = '';
$td_post_tags = get_the_tags();
if ($td_post_tags) {
$buffy .= '<ul class="td-tags clearfix"><li><span class="td-tag-black">' . __td('TAGS') . '</span></li>';
foreach ($td_post_tags as $tag) {
$buffy .= '<li><a href="' . get_tag_link($tag->term_id) . '">' . $tag->name . '</a></li>';
}
$buffy .= '</ul>';
}
return $buffy;
}
function get_next_prev_posts() {
if (!$this->is_single) {
return;
}
if (td_util::get_option('tds_show_next_prev') == 'hide') {
return;
}
$buffy = '';
$next_post = get_next_post();
$prev_post = get_previous_post();
if (!empty($next_post) or !empty($prev_post)) {
$buffy .= '<div class="wpb_row row-fluid next-prev">';
if (!empty($prev_post)) {
$buffy .= '<div class="span6 prev-post">';
$buffy .= '<div><img width="6" class="td-retina" src="' . get_template_directory_uri() .
'/images/icons/similar-left.png" alt=""/>' . __td('Previous article', TD_THEME_NAME) . '</div>';
$buffy .= '<a href="' . get_permalink($prev_post->ID) . '">' . $prev_post->post_title . '</a>';
$buffy .= '</div>';
} else {
$buffy .= '<div class="span6 prev-post">';
$buffy .= '</div>';
}
if (!empty($next_post)) {
$buffy .= '<div class="span6 next-post">';
$buffy .= '<div>' . __td('Next article', TD_THEME_NAME) . '<img width="6" class="td-retina" src="' .
get_template_directory_uri() . '/images/icons/similar-right.png" alt=""/></div>';
$buffy .= '<a href="' . get_permalink($next_post->ID) . '">' . $next_post->post_title . '</a>';
$buffy .= '</div>';
}
$buffy .= '</div>'; //end fluid row
}
return $buffy;
}
function get_author_box($author_id = '') {
if (!$this->is_single) {
return;
}
if (td_util::get_option('tds_show_author_box') == 'hide') {
return;
}
if (empty($author_id)) {
$author_id = $this->post->post_author;
}
$buffy = '';
$authorDescription = get_the_author_meta('description');
$hideAuthor = td_util::get_option('hide_author');
if (empty($hideAuthor)) {
$buffy .= '<div class="author-box-wrap">';
$buffy .= '<a href="' . get_author_posts_url($author_id) . '">' ;
$buffy .= get_avatar(get_the_author_meta('email', $author_id), '106');
$buffy .= '</a>';
$buffy .= '<div class="desc">';
$buffy .= '<div class="td-author-name">';
$buffy .= '<a href="' . get_author_posts_url($author_id) . '">' . get_the_author_meta('display_name', $author_id) . '</a>' ;
$buffy .= '</div>';
$buffy .= '<div class="vcard author"><span class="fn">';
$buffy .= get_the_author_meta('description', $author_id);
$buffy .= '</span></div>';
$buffy .= '<div class="td-author-social">';
foreach (td_social_icons::$td_social_icons_array as $td_social_id => $td_social_name) {
//echo get_the_author_meta($td_social_id) . '<br>';
$authorMeta = get_the_author_meta($td_social_id);
if (!empty($authorMeta)) {
//the theme can use the twitter id instead of the full url. This avoids problems with yoast plugin
if ($td_social_id == 'twitter') {
if(filter_var($authorMeta, FILTER_VALIDATE_URL)){
} else {
$authorMeta = str_replace('@', '', $authorMeta);
$authorMeta = 'http://twitter.com/' . $authorMeta;
}
}
$buffy .= td_social_icons::get_icon($authorMeta, $td_social_id, 4, 16);
}
}
$buffy .= '</div>';
$buffy .= '<div class="clearfix"></div>';
$buffy .= '</div>'; ////desc
$buffy .= '</div>'; //author-box-wrap
}
return $buffy;
}
function related_posts() {
global $post; //this is used by the loop down
if (!$this->is_single) {
return;
}
if (td_util::get_option('tds_similar_articles') == 'hide') {
return;
}
if (td_util::get_option('tds_similar_articles_count') == '') {
$tds_similar_articles_count = 2;
} else {
$tds_similar_articles_count = td_util::get_option('tds_similar_articles_count');
}
if (td_global::$cur_single_template_sidebar_pos == 'no_sidebar') {
$tds_similar_articles_count = 3;
}
$buffy = '';
$buffy .= '<div class="art-img-text-down similar-articles">';
$args = array();
switch (td_util::get_option('tds_similar_articles_type')) {
//by tag
case 'by_tag':
$tags = wp_get_post_tags($this->post->ID);
if ($tags) {
$taglist = array();
for ($i = 0; $i <= 4; $i++) {
if (!empty($tags[$i])) {
$taglist[] = $tags[$i]->term_id;
} else {
break;
}
}
$args = array(
'tag__in' => $taglist,
'post__not_in' => array($this->post->ID),
'showposts' => $tds_similar_articles_count,
'ignore_sticky_posts' => 1
);
}
break;
//by title
case 'by_auth':
$args = array(
'author' => $this->post->post_author,
'post__not_in' => array($this->post->ID),
'showposts' => $tds_similar_articles_count,
'ignore_sticky_posts' => 1
);
break;
//by category
default:
$args = array(
'category__in' => wp_get_post_categories($this->post->ID),
'post__not_in' => array($this->post->ID),
'showposts' => $tds_similar_articles_count,
'ignore_sticky_posts' => 1
);
break;
}
if (!empty($args)) {
//do the query
$my_query = new WP_Query($args);
if ($my_query->have_posts()) {
$buffy .= '<h4 class="block-title"><span>' . __td('SIMILAR ARTICLES') . '</span></h4>';
$td_template_layout = new td_template_layout(''); //invalid sidebar position, it will default to 2 + 1
if (td_global::$cur_single_template_sidebar_pos == 'no_sidebar') {
$td_template_layout->set_columns(3);
} else {
$td_template_layout->set_columns(2);
}
while ($my_query->have_posts()) : $my_query->the_post();
$buffy .= $td_template_layout->layout_open_element();
$td_module_6 = new td_module_6($post);
$buffy .= $td_module_6->render();
$buffy .= $td_template_layout->layout_close_element();
$td_template_layout->layout_next();
endwhile;
$buffy .= $td_template_layout->close_all_tags();
}
}
$buffy .= '</div>';
wp_reset_query();
return $buffy;
}
}
| bwdk/autopanorama | wp-content/themes/Newspaper/includes/modules/module_modifier/td_module_blog.php | PHP | gpl-2.0 | 32,203 |
<?php
/**
* @package WordPress
* @subpackage ThemeWoot
* @author ThemeWoot Team
*
* This source file is subject to the GNU GENERAL PUBLIC LICENSE (GPL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.gnu.org/licenses/gpl-3.0.txt
*/
$link = twoot_get_frontend_func('meta', 'post_link')=='custom' && twoot_get_frontend_func('meta', 'custom_url')!=false? twoot_get_frontend_func('meta', 'custom_url'):get_permalink();
?>
<?php if(has_post_thumbnail()) : ?>
<figure class="featured-image img-preload img-hover">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php echo twoot_get_frontend_func('resize_thumbnail', get_post_thumbnail_id(), get_the_title(), 580, 430, true); ?>
<div class="overlay"></div>
<header class="item-head">
<h3 class="title item-title"><a href="<?php echo $link; ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
<?php echo get_the_term_list( get_the_ID(), 'portfolio_cat', '<div class="cats meta">', ', ', '</div>' ); ?>
</header>
</a>
</figure>
<?php endif; ?> | junxionstrategy/svnindia | wp-content/themes/emulate/templates/content/loop-portfolio-list.php | PHP | gpl-2.0 | 1,174 |
/*
* drivers/cpufreq/cpufreq_zzmoove.c
*
* Copyright (C) 2001 Russell King
* (C) 2003 Venkatesh Pallipadi <venkatesh.pallipadi@intel.com>
* Jun Nakajima <jun.nakajima@intel.com>
* (C) 2009 Alexander Clouter <alex@digriz.org.uk>
* (C) 2012 Michael Weingaertner <mialwe@googlemail.com>
* Zane Zaminsky <cyxman@yahoo.com>
* Jean-Pierre Rasquin <yank555.lu@gmail.com>
* ffolkes <ffolkes@ffolkes.com>
*
* 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.
*
* -------------------------------------------------------------------------------------------------------------------------------------------------------
* - Description: -
* -------------------------------------------------------------------------------------------------------------------------------------------------------
*
* 'ZZMoove' governor is based on the modified 'conservative' (original author Alexander Clouter <alex@digriz.org.uk>) 'smoove' governor from Michael
* Weingaertner <mialwe@googlemail.com> (source: https://github.com/mialwe/mngb/) ported/modified/optimzed for I9300 since November 2012 and further
* improved for exynos and snapdragon platform (but also working on other platforms like OMAP) by ZaneZam,Yank555 and ffolkes in 2013/14/15
* CPU Hotplug modifications partially taken from ktoonservative governor from ktoonsez KT747-JB kernel (https://github.com/ktoonsez/KT747-JB)
*
* --------------------------------------------------------------------------------------------------------------------------------------------------------
* - -
* --------------------------------------------------------------------------------------------------------------------------------------------------------
*/
// ZZ: disable kernel power management
// #define DISABLE_POWER_MANAGEMENT
// AP: use msm8974 lcd status notifier
// #define USE_LCD_NOTIFIER
#include <linux/cpu.h>
#ifdef USE_LCD_NOTIFIER
#include <linux/lcd_notify.h>
#endif /* USE_LCD_NOTIFIER */
#include <linux/cpufreq.h>
#if defined(CONFIG_HAS_EARLYSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)
#include <linux/earlysuspend.h>
#endif /* defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef CONFIG_EXYNOS4_EXPORT_TEMP
#include <linux/exynos4_export_temp.h> // ZZ: Exynos4 temperatue reading support
#endif /* CONFIG_EXYNOS4_EXPORT_TEMP */
#include <linux/hrtimer.h>
#include <linux/init.h>
#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/kernel_stat.h>
#include <linux/ktime.h>
#include <linux/module.h>
#include <linux/mutex.h>
#if defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)
#include <linux/powersuspend.h>
#endif /* defined(CONFIG_HAS_EARLYSUSPEND)... */
#include <linux/sched.h>
#include <linux/tick.h>
#include <linux/version.h>
// #define ENABLE_SNAP_THERMAL_SUPPORT // ZZ: Snapdragon temperature tripping support
#if defined(CONFIG_THERMAL_TSENS8974) || defined(CONFIG_THERMAL_TSENS8960) && defined(ENABLE_SNAP_THERMAL_SUPPORT) // ZZ: Snapdragon temperature sensor
#include <linux/msm_tsens.h>
#endif /* defined(CONFIG_THERMAL_TSENS8974)... */
// #define ENABLE_INPUTBOOSTER // ZZ: enable/disable inputbooster support
// #define ENABLE_WORK_RESTARTLOOP // ZZ: enable/disable restart loop for touchboost (DO NOT ENABLE IN THIS VERSION -> NOT STABLE YET!)
#ifdef ENABLE_INPUTBOOSTER
#include <linux/slab.h>
#include <linux/input.h>
#endif /* ENABLE_INPUTBOOSTER */
// Yank: enable/disable sysfs interface to display current zzmoove version
#define ZZMOOVE_VERSION "develop"
// ZZ: support for 2,4,6 or 8 cores (this will enable/disable hotplug threshold tuneables and limit hotplug max limit tuneable)
#define MAX_CORES (4)
// ZZ: enable/disable hotplug support
// #define ENABLE_HOTPLUGGING
// ZZ: enable support for native hotplugging on snapdragon platform
// #define SNAP_NATIVE_HOTPLUGGING
// ZZ: enable for sources with backported cpufreq implementation of 3.10 kernel
#define CPU_IDLE_TIME_IN_CPUFREQ
// ZZ: enable/disable music limits
#define ENABLE_MUSIC_LIMITS
// ZZ: enable/disable freq auto adjusting
#define ENABLE_AUTO_ADJUST_FREQ
// ZZ: enable/disable profiles support
#define ENABLE_PROFILES_SUPPORT
// ZZ: include profiles header file and set name for 'custom' profile (informational for a changed profile value)
#ifdef ENABLE_PROFILES_SUPPORT
#include "cpufreq_zzmoove_profiles.h"
#define DEF_PROFILE_NUMBER (0) // ZZ: default profile number (profile = 0 = 'none' = tuneable mode)
static char custom_profile[20] = "custom"; // ZZ: name to show in sysfs if any profile value has changed
// ff: allows tuneables to be tweaked without reverting to "custom" profile
#define DEF_PROFILE_STICKY_MODE (1)
#endif /* ENABLE_PROFILES_SUPPORT */
// Yank: enable/disable debugging code
// #define ZZMOOVE_DEBUG
/*
* The polling frequency of this governor depends on the capability of
* the processor. Default polling frequency is 1000 times the transition
* latency of the processor. The governor will work on any processor with
* transition latency <= 10mS, using appropriate samplingrate. For CPUs
* with transition latency > 10mS (mostly drivers with CPUFREQ_ETERNAL)
* this governor will not work. All times here are in uS.
*/
#define TRANSITION_LATENCY_LIMIT (10 * 1000 * 1000) // ZZ: default transition latency limit
#define LATENCY_MULTIPLIER (1000) // ZZ: default latency multiplier
#define MIN_LATENCY_MULTIPLIER (100) // ZZ: default min latency multiplier
#define MIN_SAMPLING_RATE_RATIO (2) // ZZ: default min sampling rate ratio
// ZZ: general tuneable defaults
#define DEF_FREQUENCY_UP_THRESHOLD (70) // ZZ: default regular scaling up threshold
#ifdef ENABLE_HOTPLUGGING
#define DEF_FREQUENCY_UP_THRESHOLD_HOTPLUG (68) // ZZ: default hotplug up threshold for all cpus (cpu0 stays allways on)
#define DEF_FREQUENCY_UP_THRESHOLD_HOTPLUG_FREQ (0) // Yank: default hotplug up threshold frequency for all cpus (0 = disabled)
#endif /* ENABLE_HOTPLUGGING */
#define DEF_SMOOTH_UP (75) // ZZ: default cpu load trigger for 'boosting' scaling frequency
#define DEF_FREQUENCY_DOWN_THRESHOLD (52) // ZZ: default regular scaling down threshold
#ifdef ENABLE_HOTPLUGGING
#define DEF_FREQUENCY_DOWN_THRESHOLD_HOTPLUG (55) // ZZ: default hotplug down threshold for all cpus (cpu0 stays allways on)
#define DEF_FREQUENCY_DOWN_THRESHOLD_HOTPLUG_FREQ (0) // Yank: default hotplug down threshold frequency for all cpus (0 = disabled)
#endif /* ENABLE_HOTPLUGGING */
#define DEF_IGNORE_NICE (0) // ZZ: default ignore nice load
#ifdef ENABLE_AUTO_ADJUST_FREQ
#define DEF_AUTO_ADJUST_FREQ (0) // ZZ: default auto adjust frequency thresholds
#endif /* ENABLE_AUTO_ADJUST_FREQ */
// ZZ: hotplug-switch, -block, -idle, -limit and scaling-block, -fastdown, -responiveness, -proportional tuneable defaults
#ifdef ENABLE_HOTPLUGGING
#define DEF_DISABLE_HOTPLUG (0) // ZZ: default hotplug switch
#define DEF_HOTPLUG_BLOCK_UP_CYCLES (0) // ZZ: default hotplug up block cycles
#define DEF_HOTPLUG_BLOCK_DOWN_CYCLES (0) // ZZ: default hotplug down block cycles
#define DEF_BLOCK_UP_MULTIPLIER_HOTPLUG1 (0) // ff: default hotplug up block multiplier for core 2
#define DEF_BLOCK_UP_MULTIPLIER_HOTPLUG2 (0) // ff: default hotplug up block multiplier for core 3
#define DEF_BLOCK_UP_MULTIPLIER_HOTPLUG3 (0) // ff: default hotplug up block multiplier for core 4
#define DEF_BLOCK_UP_MULTIPLIER_HOTPLUG4 (0) // ff: default hotplug up block multiplier for core 5
#define DEF_BLOCK_UP_MULTIPLIER_HOTPLUG5 (0) // ff: default hotplug up block multiplier for core 6
#define DEF_BLOCK_UP_MULTIPLIER_HOTPLUG6 (0) // ff: default hotplug up block multiplier for core 7
#define DEF_BLOCK_UP_MULTIPLIER_HOTPLUG7 (0) // ff: default hotplug up block multiplier for core 8
#define DEF_BLOCK_DOWN_MULTIPLIER_HOTPLUG1 (0) // ff: default hotplug down block multiplier for core 2
#define DEF_BLOCK_DOWN_MULTIPLIER_HOTPLUG2 (0) // ff: default hotplug down block multiplier for core 3
#define DEF_BLOCK_DOWN_MULTIPLIER_HOTPLUG3 (0) // ff: default hotplug down block multiplier for core 4
#define DEF_BLOCK_DOWN_MULTIPLIER_HOTPLUG4 (0) // ff: default hotplug down block multiplier for core 5
#define DEF_BLOCK_DOWN_MULTIPLIER_HOTPLUG5 (0) // ff: default hotplug down block multiplier for core 6
#define DEF_BLOCK_DOWN_MULTIPLIER_HOTPLUG6 (0) // ff: default hotplug down block multiplier for core 7
#define DEF_BLOCK_DOWN_MULTIPLIER_HOTPLUG7 (0) // ff: default hotplug down block multiplier for core 8
#define DEF_HOTPLUG_STAGGER_UP (0) // ff: only bring one core up at a time when hotplug_online_work() called
#define DEF_HOTPLUG_STAGGER_DOWN (0) // ff: only bring one core down at a time when hotplug_offline_work() called
#define DEF_HOTPLUG_IDLE_THRESHOLD (0) // ZZ: default hotplug idle threshold
#define DEF_HOTPLUG_IDLE_FREQ (0) // ZZ: default hotplug idle freq
#define DEF_HOTPLUG_ENGAGE_FREQ (0) // ZZ: default hotplug engage freq. the frequency below which we run on only one core (0 = disabled) (ffolkes)
#define DEF_HOTPLUG_MAX_LIMIT (0) // ff: default for hotplug_max_limit. the number of cores we allow to be online (0 = disabled)
#define DEF_HOTPLUG_MIN_LIMIT (0) // ff: default for hotplug_min_limit. the number of cores we require to be online (0 = disabled)
#define DEF_HOTPLUG_LOCK (0) // ff: default for hotplug_lock. the number of cores we require to be online (0 = disabled)
#endif /* ENABLE_HOTPLUGGING */
#define DEF_SCALING_BLOCK_THRESHOLD (0) // ZZ: default scaling block threshold
#define DEF_SCALING_BLOCK_CYCLES (0) // ZZ: default scaling block cycles
#define DEF_SCALING_BLOCK_FREQ (0) // ZZ: default scaling block freq
#define DEF_SCALING_UP_BLOCK_CYCLES (0) // ff: default scaling-up block cycles
#define DEF_SCALING_UP_BLOCK_FREQ (0) // ff: default scaling-up block frequency threshold
#ifdef CONFIG_EXYNOS4_EXPORT_TEMP
#define DEF_TMU_READ_DELAY (1000) // ZZ: delay for cpu temperature reading in ms (tmu driver polling intervall is 10 sec)
#define DEF_SCALING_BLOCK_TEMP (0) // ZZ: default cpu temperature threshold in °C
#endif /* CONFIG_EXYNOS4_EXPORT_TEMP */
#ifdef ENABLE_SNAP_THERMAL_SUPPORT // ff: snapdragon temperature tripping defaults
#define DEF_SCALING_TRIP_TEMP (60) // ff: default trip cpu temp
#define DEF_TMU_CHECK_DELAY (2500) // ZZ: default delay for snapdragon thermal tripping
#define DEF_TMU_CHECK_DELAY_SLEEP (10000) // ZZ: default delay for snapdragon thermal tripping at sleep
#endif /* ENABLE_SNAP_THERMAL_SUPPORT */
#define DEF_SCALING_BLOCK_FORCE_DOWN (2) // ZZ: default scaling block force down
#define DEF_SCALING_FASTDOWN_FREQ (0) // ZZ: default scaling fastdown freq. the frequency beyond which we apply a different up_threshold (ffolkes)
#define DEF_SCALING_FASTDOWN_UP_THRESHOLD (95) // ZZ: default scaling fastdown up threshold. the up threshold when scaling fastdown freq has been exceeded (ffolkes)
#define DEF_SCALING_FASTDOWN_DOWN_THRESHOLD (90) // ZZ: default scaling fastdown up threshold. the down threshold when scaling fastdown freq has been exceeded (ffolkes)
#define DEF_SCALING_RESPONSIVENESS_FREQ (0) // ZZ: default frequency below which we use a lower up threshold (ffolkes)
#define DEF_SCALING_RESPONSIVENESS_UP_THRESHOLD (30) // ZZ: default up threshold we use when below scaling responsiveness freq (ffolkes)
#define DEF_SCALING_PROPORTIONAL (0) // ZZ: default proportional scaling
// ZZ: sampling rate idle and sampling down momentum tuneable defaults
#define DEF_SAMPLING_RATE_IDLE_THRESHOLD (0) // ZZ: default sampling rate idle threshold
#define DEF_SAMPLING_RATE_IDLE (180000)// ZZ: default sampling rate idle (must not be 0!)
#define DEF_SAMPLING_RATE_IDLE_DELAY (0) // ZZ: default sampling rate idle delay
#define DEF_SAMPLING_DOWN_FACTOR (1) // ZZ: default sampling down factor (stratosk default = 4) here disabled by default
#define MAX_SAMPLING_DOWN_FACTOR (100000)// ZZ: changed from 10 to 100000 for sampling down momentum implementation
#define DEF_SAMPLING_DOWN_MOMENTUM (0) // ZZ: default sampling down momentum, here disabled by default
#define DEF_SAMPLING_DOWN_MAX_MOMENTUM (0) // ZZ: default sampling down max momentum stratosk default=16, here disabled by default
#define DEF_SAMPLING_DOWN_MOMENTUM_SENSITIVITY (50) // ZZ: default sampling down momentum sensitivity
#define MAX_SAMPLING_DOWN_MOMENTUM_SENSITIVITY (1000) // ZZ: default maximum for sampling down momentum sensitivity
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
// ZZ: tuneable defaults for early suspend
#define MAX_SAMPLING_RATE_SLEEP_MULTIPLIER (8) // ZZ: default maximum for sampling rate sleep multiplier
#define DEF_SAMPLING_RATE_SLEEP_MULTIPLIER (2) // ZZ: default sampling rate sleep multiplier
#define DEF_UP_THRESHOLD_SLEEP (90) // ZZ: default up threshold sleep
#define DEF_DOWN_THRESHOLD_SLEEP (44) // ZZ: default down threshold sleep
#define DEF_SMOOTH_UP_SLEEP (75) // ZZ: default smooth up sleep
#define DEF_EARLY_DEMAND_SLEEP (1) // ZZ: default early demand sleep
#define DEF_GRAD_UP_THRESHOLD_SLEEP (30) // ZZ: default grad up sleep
#define DEF_FAST_SCALING_SLEEP_UP (0) // Yank: default fast scaling sleep for upscaling
#define DEF_FAST_SCALING_SLEEP_DOWN (0) // Yank: default fast scaling sleep for downscaling
#define DEF_FREQ_LIMIT_SLEEP (0) // ZZ: default freq limit sleep
#ifdef ENABLE_HOTPLUGGING
#define DEF_DISABLE_HOTPLUG_SLEEP (0) // ZZ: default hotplug sleep switch
#endif /* ENABLE_HOTPLUGGING */
#endif /* ENABLE_HOTPLUGGING */
/*
* ZZ: Hotplug Sleep: 0 do not touch hotplug settings at suspend, so all cores will stay online
* the value is equivalent to the amount of cores which should be online at suspend
*/
#ifdef ENABLE_HOTPLUGGING
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
#define DEF_HOTPLUG_SLEEP (0) // ZZ: default hotplug sleep
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#endif /* ENABLE_HOTPLUGGING */
// ZZ: tuneable defaults for Early Demand
#define DEF_GRAD_UP_THRESHOLD (25) // ZZ: default grad up threshold
#define DEF_EARLY_DEMAND (0) // ZZ: default early demand, default off
/*
* ZZ: Frequency Limit: 0 do not limit frequency and use the full range up to policy->max limit
* values policy->min to policy->max in khz
*/
#define DEF_FREQ_LIMIT (0) // ZZ: default freq limit
/*
* ZZ: Fast Scaling: 0 do not activate fast scaling function
* values 1-4 to enable fast scaling and 5 for auto fast scaling (insane scaling)
*/
#define DEF_FAST_SCALING_UP (0) // Yank: default fast scaling for upscaling
#define DEF_FAST_SCALING_DOWN (0) // Yank: default fast scaling for downscaling
#define DEF_AFS_THRESHOLD1 (25) // ZZ: default auto fast scaling step one
#define DEF_AFS_THRESHOLD2 (50) // ZZ: default auto fast scaling step two
#define DEF_AFS_THRESHOLD3 (75) // ZZ: default auto fast scaling step three
#define DEF_AFS_THRESHOLD4 (90) // ZZ: default auto fast scaling step four
// ff: Input Booster defaults
#ifdef ENABLE_INPUTBOOSTER
#define DEF_INPUTBOOST_CYCLES (0) // ff: default number of cycles to boost up/down thresholds
#define DEF_INPUTBOOST_UP_THRESHOLD (80) // ff: default up threshold for inputbooster
#define DEF_INPUTBOOST_PUNCH_CYCLES (20) // ff: default number of cycles to meet or exceed punch freq
#define DEF_INPUTBOOST_PUNCH_FREQ (0) // ff: default frequency to keep cur_freq at or above
#define DEF_INPUTBOOST_PUNCH_ON_FINGERDOWN (0) // ff: default for constant punching (like a touchbooster)
#define DEF_INPUTBOOST_PUNCH_ON_FINGERMOVE (0) // ff: default for constant punching (like a touchbooster)
#define DEF_INPUTBOOST_PUNCH_ON_EPENMOVE (0) // ff: default for constant punching (like a touchbooster)
#define DEF_INPUTBOOST_ON_TSP (1) // ff: default to boost on touchscreen input events
#define DEF_INPUTBOOST_ON_TSP_HOVER (1) // ff: default to boost on touchscreen hovering input events
#define DEF_INPUTBOOST_ON_GPIO (1) // ff: default to boost on gpio (button) input events
#define DEF_INPUTBOOST_ON_TK (1) // ff: default to boost on touchkey input events
#define DEF_INPUTBOOST_ON_EPEN (1) // ff: default to boost on e-pen input events
#define DEF_INPUTBOOST_TYPINGBOOSTER_UP_THRESHOLD (40) // ff: default up threshold for typing booster
#define DEF_INPUTBOOST_TYPINGBOOSTER_CORES (3) // ff: default cores for typing booster
#endif /* ENABLE_INPUTBOOSTER */
// ff: Music Detection defaults
#ifdef ENABLE_MUSIC_LIMITS
#define DEF_MUSIC_MAX_FREQ (0) // ff: default maximum freq to maintain while music is on
#define DEF_MUSIC_MIN_FREQ (0) // ff: default minimum freq to maintain while music is on
#ifdef ENABLE_HOTPLUGGING
#define DEF_MUSIC_MIN_CORES (2) // ZZ: default minimum cores online while music is on
#endif /* ENABLE_HOTPLUGGING */
#endif /* ENABLE_MUSIC_LIMITS */
// ZZ: Sampling Down Momentum variables
static unsigned int min_sampling_rate; // ZZ: minimal possible sampling rate
static unsigned int orig_sampling_down_factor; // ZZ: for saving previously set sampling down factor
static unsigned int zz_sampling_down_factor = DEF_SAMPLING_DOWN_FACTOR; // ff: actual use variable, so dbs_tuner_ins version stays constant
static unsigned int orig_sampling_down_max_mom; // ZZ: for saving previously set smapling down max momentum
static unsigned int zz_sampling_down_max_mom; // ff: actual use variable, so dbs_tuner_ins version stays constant
// ZZ: search limit for frequencies in scaling table, variables for scaling modes and state flag for suspend detection
static struct cpufreq_frequency_table *system_freq_table; // ZZ: static system frequency table
static int scaling_mode_up; // ZZ: fast scaling up mode holding up value during runtime
static int scaling_mode_down; // ZZ: fast scaling down mode holding down value during runtime
static bool freq_table_desc = false; // ZZ: true for descending order, false for ascending order
static int freq_init_count = 0; // ZZ: flag for executing freq table order and limit optimization code at gov start
static unsigned int max_scaling_freq_soft = 0; // ZZ: init value for 'soft' scaling limit, 0 = full range
static unsigned int max_scaling_freq_hard = 0; // ZZ: init value for 'hard' scaling limit, 0 = full range
static unsigned int min_scaling_freq_soft = 0; // ZZ: init value for 'soft' scaling limit, 0 = full range
static unsigned int min_scaling_freq_hard = 0; // ZZ: init value for 'hard' scaling limit, 0 = full range
static unsigned int system_table_end = CPUFREQ_TABLE_END; // ZZ: system freq table end for order detection, table size calculation and freq validations
static unsigned int limit_table_end = CPUFREQ_TABLE_END; // ZZ: initial (full range) search end limit for frequency table in descending ordered table
static unsigned int limit_table_start = 0; // ZZ: search start limit for frequency table in ascending order
static unsigned int freq_table_size = 0; // Yank: upper index limit of frequency table
static unsigned int min_scaling_freq = 0; // Yank: lowest frequency index in global frequency table
static bool suspend_flag = false; // ZZ: flag for suspend status, true = in early suspend
// ZZ: hotplug-, scaling-block, scaling fastdown vars and sampling rate idle counters. flags for scaling, setting profile, cpu temp reading and hotplugging
#ifdef ENABLE_HOTPLUGGING
static int possible_cpus = 0; // ZZ: for holding the maximal amount of cores for hotplugging
static unsigned int hplg_down_block_cycles = 0; // ZZ: delay cycles counter for hotplug down blocking
static unsigned int hplg_up_block_cycles = 0; // ZZ: delay cycles counter for hotplug up blocking
static unsigned int num_online_cpus_last = 0; // ff: how many cores were online last cycle
static unsigned int zz_hotplug_block_up_cycles = 0;
static unsigned int zz_hotplug_block_down_cycles = 0;
#endif /* ENABLE_HOTPLUGGING */
static unsigned int scaling_block_cycles_count = 0; // ZZ: scaling block cycles counter
static unsigned int sampling_rate_step_up_delay = 0; // ZZ: sampling rate idle up delay cycles
static unsigned int sampling_rate_step_down_delay = 0; // ZZ: sampling rate idle down delay cycles
static unsigned int scaling_up_threshold = 0; // ZZ: scaling up threshold for fastdown/responsiveness functionality
static unsigned int scaling_down_threshold = 0; // ZZ: scaling down threshold for fastdown functionality
#ifdef ENABLE_HOTPLUGGING
static bool hotplug_idle_flag = false; // ZZ: flag for hotplug idle mode
static int __refdata enable_cores = 0; // ZZ: mode for enabling offline cores for various functions in the governor
static int __refdata disable_cores = 0; // ZZ: mode for disabling online cores for various functions in the governor
static bool hotplug_up_in_progress; // ZZ: flag for hotplug up function call - block if hotplugging is in progress
static bool hotplug_down_in_progress; // ZZ: flag for hotplug down function call - block if hotplugging is in progress
static bool boost_hotplug = false; // ZZ: early demand boost hotplug flag
#endif /* ENABLE_HOTPLUGGING */
static bool boost_freq = false; // ZZ: early demand boost freq flag
static bool force_down_scaling = false; // ZZ: force down scaling flag
static bool cancel_up_scaling = false; // ZZ: cancel up scaling flag
#ifdef ENABLE_PROFILES_SUPPORT
static bool set_profile_active = false; // ZZ: flag to avoid changing of any tuneables during profile apply
#endif
#ifdef CONFIG_EXYNOS4_EXPORT_TEMP
#ifdef ENABLE_HOTPLUGGING
static bool hotplug_up_temp_block; // ZZ: flag for blocking up hotplug work during temp freq blocking
#endif /* ENABLE_HOTPLUGGING */
static bool cancel_temp_reading = false; // ZZ: flag for starting temp reading work
static bool temp_reading_started = false; // ZZ: flag for canceling temp reading work
// ZZ: Exynos CPU temp reading work
static void tmu_read_temperature(struct work_struct * tmu_read_work); // ZZ: prepare temp reading work
static DECLARE_DELAYED_WORK(tmu_read_work, tmu_read_temperature); // ZZ: declare delayed work for temp reading
static unsigned int cpu_temp; // ZZ: static var for holding current cpu temp
#endif /* CONFIG_EXYNOS4_EXPORT_TEMP */
// ZZ: current load & frequency for hotplugging work and scaling. max/min frequency for proportional scaling and auto freq threshold adjustment
static unsigned int cur_load = 0; // ZZ: current load for hotplugging functions
static unsigned int cur_freq = 0; // ZZ: current frequency for hotplugging functions
static unsigned int pol_max = 0; // ZZ: current max freq for proportional scaling and auto adjustment of freq thresholds
static unsigned int pol_min = 0; // ZZ: current min freq for auto adjustment of freq thresholds
#ifdef ENABLE_AUTO_ADJUST_FREQ
static unsigned int old_pol_max = 0; // ZZ: previous max freq for auto adjustment of freq thresholds
static unsigned int pol_step = 0; // ZZ: policy change step for auto adjustment of freq thresholds
// ZZ: temp variables and flags to hold offset values for auto adjustment of freq thresholds
#ifdef ENABLE_HOTPLUGGING
static unsigned int temp_hotplug_engage_freq = 0;
static bool temp_hotplug_engage_freq_flag = false;
static unsigned int temp_hotplug_idle_freq = 0;
static bool temp_hotplug_idle_freq_flag = false;
#endif /* ENABLE_HOTPLUGGING */
static unsigned int temp_scaling_block_freq = 0;
static bool temp_scaling_block_freq_flag = false;
static unsigned int temp_scaling_fastdown_freq = 0;
static bool temp_scaling_fastdown_freq_flag = false;
static unsigned int temp_scaling_responsiveness_freq = 0;
static bool temp_scaling_responsiveness_freq_flag = false;
#ifdef ENABLE_MUSIC_LIMITS
static unsigned int temp_music_min_freq = 0;
static bool temp_music_min_freq_flag = false;
static unsigned int temp_music_max_freq = 0;
static bool temp_music_max_freq_flag = false;
#endif /* ENABLE_MUSIC_LIMITS */
#ifdef ENABLE_HOTPLUGGING
static unsigned int temp_up_threshold_hotplug_freq1 = 0;
static bool temp_up_threshold_hotplug_freq1_flag = false;
static unsigned int temp_down_threshold_hotplug_freq1 = 0;
static bool temp_down_threshold_hotplug_freq1_flag = false;
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
static unsigned int temp_up_threshold_hotplug_freq2 = 0;
static bool temp_up_threshold_hotplug_freq2_flag = false;
static unsigned int temp_up_threshold_hotplug_freq3 = 0;
static bool temp_up_threshold_hotplug_freq3_flag = false;
static unsigned int temp_down_threshold_hotplug_freq2 = 0;
static bool temp_down_threshold_hotplug_freq2_flag = false;
static unsigned int temp_down_threshold_hotplug_freq3 = 0;
static bool temp_down_threshold_hotplug_freq3_flag = false;
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
static unsigned int temp_up_threshold_hotplug_freq4 = 0;
static bool temp_up_threshold_hotplug_freq4_flag = false;
static unsigned int temp_up_threshold_hotplug_freq5 = 0;
static bool temp_up_threshold_hotplug_freq5_flag = false;
static unsigned int temp_down_threshold_hotplug_freq4 = 0;
static bool temp_down_threshold_hotplug_freq4_flag = false;
static unsigned int temp_down_threshold_hotplug_freq5 = 0;
static bool temp_down_threshold_hotplug_freq5_flag = false;
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
static unsigned int temp_up_threshold_hotplug_freq6 = 0;
static bool temp_up_threshold_hotplug_freq6_flag = false;
static unsigned int temp_up_threshold_hotplug_freq7 = 0;
static bool temp_up_threshold_hotplug_freq7_flag = false;
static unsigned int temp_down_threshold_hotplug_freq6 = 0;
static bool temp_down_threshold_hotplug_freq6_flag = false;
static unsigned int temp_down_threshold_hotplug_freq7 = 0;
static bool temp_down_threshold_hotplug_freq7_flag = false;
#endif /* (MAX_CORES == 8) */
#endif /* ENABLE_HOTPLUGGING */
#ifdef ENABLE_INPUTBOOSTER
static unsigned int temp_inputboost_punch_freq = 0;
static bool temp_inputboost_punch_freq_flag = false;
#endif /* ENABLE_INPUTBOOSTER */
#endif /* ENABLE_AUTO_ADJUST_FREQ */
#ifdef ENABLE_HOTPLUGGING
// ZZ: hotplug load thresholds array
static int hotplug_thresholds[2][8] = {
{ 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 },
{ 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 }
};
// ZZ: hotplug frequencies thresholds array
static int hotplug_thresholds_freq[2][8] = {
{ 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 },
{ 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 }
};
#ifdef ENABLE_AUTO_ADJUST_FREQ
// ZZ: hotplug frequencies out of range array
static int hotplug_freq_threshold_out_of_range[2][8] = {
{ 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 },
{ 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 }
};
#endif /* ENABLE_AUTO_ADJUST_FREQ */
#endif /* ENABLE_HOTPLUGGING */
// ZZ: core on which we currently run
static unsigned int on_cpu = 0;
// ZZ: Early Suspend variables
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
static unsigned int sampling_rate_awake; // ZZ: for saving sampling rate awake value
static unsigned int up_threshold_awake; // ZZ: for saving up threshold awake value
static unsigned int down_threshold_awake; // ZZ: for saving down threshold awake value
static unsigned int smooth_up_awake; // ZZ: for saving smooth up awake value
static unsigned int freq_limit_awake; // ZZ: for saving frequency limit awake value
static unsigned int fast_scaling_up_awake; // Yank: for saving fast scaling awake value for upscaling
static unsigned int fast_scaling_down_awake; // Yank: for saving fast scaling awake value for downscaling
#ifdef ENABLE_HOTPLUGGING
static unsigned int disable_hotplug_awake; // ZZ: for saving hotplug switch
static unsigned int hotplug1_awake; // ZZ: for saving hotplug1 threshold awake value
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
static unsigned int hotplug2_awake; // ZZ: for saving hotplug2 threshold awake value
static unsigned int hotplug3_awake; // ZZ: for saving hotplug3 threshold awake value
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
static unsigned int hotplug4_awake; // ZZ: for saving hotplug4 threshold awake value
static unsigned int hotplug5_awake; // ZZ: for saving hotplug5 threshold awake value
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
static unsigned int hotplug6_awake; // ZZ: for saving hotplug6 threshold awake value
static unsigned int hotplug7_awake; // ZZ: for saving hotplug7 threshold awake value
#endif /* (MAX_CORES == 8) */
#endif /* ENABLE_HOTPLUGGING */
static unsigned int sampling_rate_asleep; // ZZ: for setting sampling rate value at early suspend
static unsigned int up_threshold_asleep; // ZZ: for setting up threshold value at early suspend
static unsigned int down_threshold_asleep; // ZZ: for setting down threshold value at early suspend
static unsigned int smooth_up_asleep; // ZZ: for setting smooth scaling value at early suspend
static unsigned int freq_limit_asleep; // ZZ: for setting frequency limit value at early suspend
static unsigned int fast_scaling_up_asleep; // Yank: for setting fast scaling value at early suspend for upscaling
static unsigned int fast_scaling_down_asleep; // Yank: for setting fast scaling value at early suspend for downscaling
#ifdef ENABLE_HOTPLUGGING
static unsigned int disable_hotplug_asleep; // ZZ: for setting hotplug on/off at early suspend
#endif /* ENABLE_HOTPLUGGING */
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#if defined(USE_LCD_NOTIFIER) && !defined(CONFIG_POWERSUSPEND)
static struct notifier_block zzmoove_lcd_notif;
#endif /* defined(USE_LCD_NOTIFIER)... */
#ifdef ENABLE_INPUTBOOSTER
// ff: Input Booster variables
static unsigned int boost_on_tsp = DEF_INPUTBOOST_ON_TSP; // ff: hardcoded since it'd be silly not to use it
static unsigned int boost_on_tsp_hover = DEF_INPUTBOOST_ON_TSP_HOVER;
static unsigned int boost_on_gpio = DEF_INPUTBOOST_ON_GPIO; // ff: hardcoded since it'd be silly not to use it
static unsigned int boost_on_tk = DEF_INPUTBOOST_ON_TK; // ff: hardcoded since it'd be silly not to use it
static unsigned int boost_on_epen = DEF_INPUTBOOST_ON_EPEN; // ff: hardcoded since it'd be silly not to use it
static unsigned int inputboost_last_type = 0;
static unsigned int inputboost_last_code = 0;
static unsigned int inputboost_last_value = 0;
static int inputboost_report_btn_touch = -1;
static int inputboost_report_btn_toolfinger = -1;
static int inputboost_report_mt_trackingid = 0;
static bool flg_inputboost_report_mt_touchmajor = false;
static bool flg_inputboost_report_abs_xy = false;
int flg_ctr_cpuboost = 0;
static int flg_ctr_inputboost = 0;
static int flg_ctr_inputboost_punch = 0;
static int flg_ctr_inputbooster_typingbooster = 0;
static int ctr_inputboost_typingbooster_taps = 0;
static struct timeval time_typingbooster_lasttapped;
#ifdef ZZMOOVE_DEBUG
static struct timeval time_touchbooster_lastrun;
static unsigned int time_since_touchbooster_lastrun = 0;
#endif /* ZZMOOVE_DEBUG */
#endif /* ENABLE_INPUTBOOSTER */
// ff: other variables
static int scaling_up_block_cycles_count = 0;
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
#ifdef ENABLE_MUSIC_LIMITS
static int music_max_freq_step = 0;
#endif /* ENABLE_MUSIC_LIMITS */
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_WORK_RESTARTLOOP
struct work_struct work_restartloop;
static bool work_restartloop_in_progress = false; // ZZ: flag to avoid loop restart to frequently
#endif /* ENABLE_WORK_RESTARTLOOP */
#ifdef ENABLE_SNAP_THERMAL_SUPPORT
static void tmu_check_work(struct work_struct * work_tmu_check);
static DECLARE_DELAYED_WORK(work_tmu_check, tmu_check_work);
static int tmu_temp_cpu = 0;
static int tmu_temp_cpu_last = 0;
static int flg_ctr_tmu_overheating = 0;
static int tmu_throttle_steps = 0;
static int ctr_tmu_neutral = 0;
static int ctr_tmu_falling = 0;
#endif /* ENABLE_SNAP_THERMAL_SUPPORT */
#ifdef ENABLE_HOTPLUGGING
struct work_struct hotplug_offline_work; // ZZ: hotplugging down work
struct work_struct hotplug_online_work; // ZZ: hotplugging up work
#endif /* ENABLE_HOTPLUGGING */
static void do_dbs_timer(struct work_struct *work);
struct cpu_dbs_info_s {
u64 time_in_idle; // ZZ: for exit time handling
u64 idle_exit_time; // ZZ: for exit time handling
u64 prev_cpu_idle;
u64 prev_cpu_wall;
u64 prev_cpu_nice;
struct cpufreq_policy *cur_policy;
struct delayed_work work;
unsigned int down_skip; // ZZ: Sampling Down reactivated
unsigned int requested_freq;
unsigned int rate_mult; // ZZ: Sampling Down Momentum - sampling rate multiplier
unsigned int momentum_adder; // ZZ: Sampling Down Momentum - adder
int cpu;
unsigned int enable:1;
unsigned int prev_load; // ZZ: Early Demand - for previous load
/*
* percpu mutex that serializes governor limit change with
* do_dbs_timer invocation. We do not want do_dbs_timer to run
* when user is changing the governor or limits.
*/
struct mutex timer_mutex;
};
static bool dbs_info_enabled = false;
static DEFINE_PER_CPU(struct cpu_dbs_info_s, cs_cpu_dbs_info);
static unsigned int dbs_enable; // number of CPUs using this policy
static DEFINE_MUTEX(dbs_mutex); // dbs_mutex protects dbs_enable in governor start/stop.
static struct workqueue_struct *dbs_wq;
#ifdef ENABLE_WORK_RESTARTLOOP
static struct workqueue_struct *dbs_aux_wq;
#endif /* ENABLE_WORK_RESTARTLOOP */
static struct dbs_tuners {
#ifdef ENABLE_PROFILES_SUPPORT
char profile[20]; // ZZ: profile tuneable
unsigned int profile_number; // ZZ: profile number tuneable
unsigned int profile_sticky_mode; // ff: sticky profile mode
#endif /* ENABLE_PROFILES_SUPPORT */
#ifdef ENABLE_AUTO_ADJUST_FREQ
unsigned int auto_adjust_freq_thresholds; // ZZ: auto adjust freq thresholds tuneable
#endif /* ENABLE_AUTO_ADJUST_FREQ */
unsigned int sampling_rate; // ZZ: normal sampling rate tuneable
unsigned int sampling_rate_current; // ZZ: currently active sampling rate tuneable
unsigned int sampling_rate_idle; // ZZ: sampling rate at idle tuneable
unsigned int sampling_rate_idle_threshold; // ZZ: sampling rate switching threshold tuneable
unsigned int sampling_rate_idle_delay; // ZZ: sampling rate switching delay tuneable
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
unsigned int sampling_rate_sleep_multiplier; // ZZ: sampling rate sleep multiplier tuneable for early suspend
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
unsigned int sampling_down_factor; // ZZ: sampling down factor tuneable (reactivated)
unsigned int sampling_down_momentum; // ZZ: sampling down momentum tuneable
unsigned int sampling_down_max_mom; // ZZ: sampling down momentum max tuneable
unsigned int sampling_down_mom_sens; // ZZ: sampling down momentum sensitivity tuneable
unsigned int up_threshold; // ZZ: scaling up threshold tuneable
#ifdef ENABLE_HOTPLUGGING
unsigned int up_threshold_hotplug1; // ZZ: up threshold hotplug tuneable for core1
unsigned int up_threshold_hotplug_freq1; // Yank: up threshold hotplug freq tuneable for core1
unsigned int block_up_multiplier_hotplug1;
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
unsigned int up_threshold_hotplug2; // ZZ: up threshold hotplug tuneable for core2
unsigned int up_threshold_hotplug_freq2; // Yank: up threshold hotplug freq tuneable for core2
unsigned int block_up_multiplier_hotplug2;
unsigned int up_threshold_hotplug3; // ZZ: up threshold hotplug tuneable for core3
unsigned int up_threshold_hotplug_freq3; // Yank: up threshold hotplug freq tuneable for core3
unsigned int block_up_multiplier_hotplug3;
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
unsigned int up_threshold_hotplug4; // ZZ: up threshold hotplug tuneable for core4
unsigned int up_threshold_hotplug_freq4; // Yank: up threshold hotplug freq tuneable for core4
unsigned int block_up_multiplier_hotplug4;
unsigned int up_threshold_hotplug5; // ZZ: up threshold hotplug tuneable for core5
unsigned int up_threshold_hotplug_freq5; // Yank: up threshold hotplug freq tuneable for core5
unsigned int block_up_multiplier_hotplug5;
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
unsigned int up_threshold_hotplug6; // ZZ: up threshold hotplug tuneable for core6
unsigned int up_threshold_hotplug_freq6; // Yank: up threshold hotplug freq tuneable for core6
unsigned int block_up_multiplier_hotplug6;
unsigned int up_threshold_hotplug7; // ZZ: up threshold hotplug tuneable for core7
unsigned int up_threshold_hotplug_freq7; // Yank: up threshold hotplug freq tuneable for core7
unsigned int block_up_multiplier_hotplug7;
#endif /* (MAX_CORES == 8) */
#endif /* ENABLE_HOTPLUGGING */
unsigned int up_threshold_sleep; // ZZ: up threshold sleep tuneable for early suspend
unsigned int down_threshold; // ZZ: down threshold tuneable
#ifdef ENABLE_HOTPLUGGING
unsigned int down_threshold_hotplug1; // ZZ: down threshold hotplug tuneable for core1
unsigned int down_threshold_hotplug_freq1; // Yank: down threshold hotplug freq tuneable for core1
unsigned int block_down_multiplier_hotplug1;
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
unsigned int down_threshold_hotplug2; // ZZ: down threshold hotplug tuneable for core2
unsigned int down_threshold_hotplug_freq2; // Yank: down threshold hotplug freq tuneable for core2
unsigned int block_down_multiplier_hotplug2;
unsigned int down_threshold_hotplug3; // ZZ: down threshold hotplug tuneable for core3
unsigned int down_threshold_hotplug_freq3; // Yank: down threshold hotplug freq tuneable for core3
unsigned int block_down_multiplier_hotplug3;
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
unsigned int down_threshold_hotplug4; // ZZ: down threshold hotplug tuneable for core4
unsigned int down_threshold_hotplug_freq4; // Yank: down threshold hotplug freq tuneable for core4
unsigned int block_down_multiplier_hotplug4;
unsigned int down_threshold_hotplug5; // ZZ: down threshold hotplug tuneable for core5
unsigned int down_threshold_hotplug_freq5; // Yank: down threshold hotplug_freq tuneable for core5
unsigned int block_down_multiplier_hotplug5;
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
unsigned int down_threshold_hotplug6; // ZZ: down threshold hotplug tuneable for core6
unsigned int down_threshold_hotplug_freq6; // Yank: down threshold hotplug freq tuneable for core6
unsigned int block_down_multiplier_hotplug6;
unsigned int down_threshold_hotplug7; // ZZ: down threshold hotplug tuneable for core7
unsigned int down_threshold_hotplug_freq7; // Yank: down threshold hotplug freq tuneable for core7
unsigned int block_down_multiplier_hotplug7;
#endif /* (MAX_CORES == 8) */
#endif /* ENABLE_HOTPLUGGING */
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
unsigned int down_threshold_sleep; // ZZ: down threshold sleep tuneable for early suspend
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
unsigned int ignore_nice; // ZZ: ignore nice load tuneable
unsigned int smooth_up; // ZZ: smooth up tuneable
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
unsigned int smooth_up_sleep; // ZZ: smooth up sleep tuneable for early suspend
#ifdef ENABLE_HOTPLUGGING
unsigned int hotplug_sleep; // ZZ: hotplug sleep tuneable for early suspend
#endif /* ENABLE_HOTPLUGGING */
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
unsigned int freq_limit; // ZZ: freq limit tuneable
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
unsigned int freq_limit_sleep; // ZZ: freq limit sleep tuneable for early suspend
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
unsigned int fast_scaling_up; // Yank: fast scaling tuneable for upscaling
unsigned int fast_scaling_down; // Yank: fast scaling tuneable for downscaling
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
unsigned int fast_scaling_sleep_up; // Yank: fast scaling sleep tuneable for early suspend for upscaling
unsigned int fast_scaling_sleep_down; // Yank: fast scaling sleep tuneable for early suspend for downscaling
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
unsigned int afs_threshold1; // ZZ: auto fast scaling step one threshold
unsigned int afs_threshold2; // ZZ: auto fast scaling step two threshold
unsigned int afs_threshold3; // ZZ: auto fast scaling step three threshold
unsigned int afs_threshold4; // ZZ: auto fast scaling step four threshold
unsigned int grad_up_threshold; // ZZ: early demand grad up threshold tuneable
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
unsigned int grad_up_threshold_sleep; // ZZ: early demand grad up threshold tuneable for early suspend
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
unsigned int early_demand; // ZZ: early demand master switch tuneable
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
unsigned int early_demand_sleep; // ZZ: early demand master switch tuneable for early suspend
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_HOTPLUGGING
unsigned int disable_hotplug; // ZZ: hotplug switch tuneable
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
unsigned int disable_hotplug_sleep; // ZZ: hotplug switch for sleep tuneable for early suspend
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
unsigned int hotplug_block_up_cycles; // ZZ: hotplug up block cycles tuneable
unsigned int hotplug_block_down_cycles; // ZZ: hotplug down block cycles tuneable
unsigned int hotplug_stagger_up; // ff: hotplug stagger up tuneable
unsigned int hotplug_stagger_down; // ff: hotplug stagger down tuneable
unsigned int hotplug_idle_threshold; // ZZ: hotplug idle threshold tuneable
unsigned int hotplug_idle_freq; // ZZ: hotplug idle freq tuneable
unsigned int hotplug_engage_freq; // ZZ: frequency below which we run on only one core (ffolkes)
unsigned int hotplug_max_limit; // ff: the number of cores we allow to be online
unsigned int hotplug_min_limit; // ff: the number of cores we require to be online
unsigned int hotplug_min_limit_saved; // ff: the number of cores we require to be online
unsigned int hotplug_min_limit_touchbooster; // ff: the number of cores we require to be online
unsigned int hotplug_lock; // ff: the number of cores we allow to be online
#endif /* ENABLE_HOTPLUGGING */
unsigned int scaling_block_threshold; // ZZ: scaling block threshold tuneable
unsigned int scaling_block_cycles; // ZZ: scaling block cycles tuneable
unsigned int scaling_up_block_cycles; // ff: scaling-up block cycles tuneable
unsigned int scaling_up_block_freq; // ff: scaling-up block freq threshold tuneable
#ifdef CONFIG_EXYNOS4_EXPORT_TEMP
unsigned int scaling_block_temp; // ZZ: scaling block temp tuneable
#endif /* CONFIG_EXYNOS4_EXPORT_TEMP */
#ifdef ENABLE_SNAP_THERMAL_SUPPORT
unsigned int scaling_trip_temp; // ff: snapdragon temperature tripping
#endif /* ENABLE_SNAP_THERMAL_SUPPORT */
unsigned int scaling_block_freq; // ZZ: scaling block freq tuneable
unsigned int scaling_block_force_down; // ZZ: scaling block force down tuneable
unsigned int scaling_fastdown_freq; // ZZ: frequency beyond which we apply a different up threshold (ffolkes)
unsigned int scaling_fastdown_up_threshold; // ZZ: up threshold when scaling fastdown freq exceeded (ffolkes)
unsigned int scaling_fastdown_down_threshold; // ZZ: down threshold when scaling fastdown freq exceeded (ffolkes)
unsigned int scaling_responsiveness_freq; // ZZ: frequency below which we use a lower up threshold (ffolkes)
unsigned int scaling_responsiveness_up_threshold; // ZZ: up threshold we use when below scaling responsiveness freq (ffolkes)
unsigned int scaling_proportional; // ZZ: proportional to load scaling
#ifdef ENABLE_INPUTBOOSTER
// ff: input booster
unsigned int inputboost_cycles; // ff: default number of cycles to boost up/down thresholds
unsigned int inputboost_up_threshold; // ff: default up threshold for inputbooster
unsigned int inputboost_punch_cycles; // ff: default number of cycles to meet or exceed punch freq
unsigned int inputboost_punch_freq; // ff: default frequency to keep cur_freq at or above
unsigned int inputboost_punch_on_fingerdown;
unsigned int inputboost_punch_on_fingermove;
unsigned int inputboost_punch_on_epenmove;
unsigned int inputboost_typingbooster_up_threshold;
unsigned int inputboost_typingbooster_cores;
#endif /* ENABLE_INPUTBOOSTER */
#ifdef ENABLE_MUSIC_LIMITS
// ff: Music Detection
unsigned int music_max_freq; // ff: music max freq
unsigned int music_min_freq; // ff: music min freq
#ifdef ENABLE_HOTPLUGGING
unsigned int music_min_cores; // ff: music min freq
#endif /* ENABLE_HOTPLUGGING */
unsigned int music_state; // ff: music state
#endif /* ENABLE_MUSIC_LIMITS */
// ZZ: set tuneable default values
} dbs_tuners_ins = {
#ifdef ENABLE_PROFILES_SUPPORT
.profile = "none",
.profile_number = DEF_PROFILE_NUMBER,
.profile_sticky_mode = DEF_PROFILE_STICKY_MODE,
#endif /* ENABLE_PROFILES_SUPPORT */
#ifdef ENABLE_AUTO_ADJUST_FREQ
.auto_adjust_freq_thresholds = DEF_AUTO_ADJUST_FREQ,
#endif /* ENABLE_AUTO_ADJUST_FREQ */
.sampling_rate_idle = DEF_SAMPLING_RATE_IDLE,
.sampling_rate_idle_threshold = DEF_SAMPLING_RATE_IDLE_THRESHOLD,
.sampling_rate_idle_delay = DEF_SAMPLING_RATE_IDLE_DELAY,
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
.sampling_rate_sleep_multiplier = DEF_SAMPLING_RATE_SLEEP_MULTIPLIER,
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
.sampling_down_factor = DEF_SAMPLING_DOWN_FACTOR,
.sampling_down_momentum = DEF_SAMPLING_DOWN_MOMENTUM,
.sampling_down_max_mom = DEF_SAMPLING_DOWN_MAX_MOMENTUM,
.sampling_down_mom_sens = DEF_SAMPLING_DOWN_MOMENTUM_SENSITIVITY,
.up_threshold = DEF_FREQUENCY_UP_THRESHOLD,
#ifdef ENABLE_HOTPLUGGING
.up_threshold_hotplug1 = DEF_FREQUENCY_UP_THRESHOLD_HOTPLUG,
.up_threshold_hotplug_freq1 = DEF_FREQUENCY_UP_THRESHOLD_HOTPLUG_FREQ,
.block_up_multiplier_hotplug1 = DEF_BLOCK_UP_MULTIPLIER_HOTPLUG1,
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
.up_threshold_hotplug2 = DEF_FREQUENCY_UP_THRESHOLD_HOTPLUG,
.up_threshold_hotplug_freq2 = DEF_FREQUENCY_UP_THRESHOLD_HOTPLUG_FREQ,
.block_up_multiplier_hotplug2 = DEF_BLOCK_UP_MULTIPLIER_HOTPLUG2,
.up_threshold_hotplug3 = DEF_FREQUENCY_UP_THRESHOLD_HOTPLUG,
.up_threshold_hotplug_freq3 = DEF_FREQUENCY_UP_THRESHOLD_HOTPLUG_FREQ,
.block_up_multiplier_hotplug3 = DEF_BLOCK_UP_MULTIPLIER_HOTPLUG3,
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
.up_threshold_hotplug4 = DEF_FREQUENCY_UP_THRESHOLD_HOTPLUG,
.up_threshold_hotplug_freq4 = DEF_FREQUENCY_UP_THRESHOLD_HOTPLUG_FREQ,
.block_up_multiplier_hotplug4 = DEF_BLOCK_UP_MULTIPLIER_HOTPLUG4,
.up_threshold_hotplug5 = DEF_FREQUENCY_UP_THRESHOLD_HOTPLUG,
.up_threshold_hotplug_freq5 = DEF_FREQUENCY_UP_THRESHOLD_HOTPLUG_FREQ,
.block_up_multiplier_hotplug5 = DEF_BLOCK_UP_MULTIPLIER_HOTPLUG5,
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
.up_threshold_hotplug6 = DEF_FREQUENCY_UP_THRESHOLD_HOTPLUG,
.up_threshold_hotplug_freq6 = DEF_FREQUENCY_UP_THRESHOLD_HOTPLUG_FREQ,
.block_up_multiplier_hotplug6 = DEF_BLOCK_UP_MULTIPLIER_HOTPLUG6,
.up_threshold_hotplug7 = DEF_FREQUENCY_UP_THRESHOLD_HOTPLUG,
.up_threshold_hotplug_freq7 = DEF_FREQUENCY_UP_THRESHOLD_HOTPLUG_FREQ,
.block_up_multiplier_hotplug7 = DEF_BLOCK_UP_MULTIPLIER_HOTPLUG7,
#endif /* (MAX_CORES == 8) */
#endif /* ENABLE_HOTPLUGGING */
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
.up_threshold_sleep = DEF_UP_THRESHOLD_SLEEP,
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
.down_threshold = DEF_FREQUENCY_DOWN_THRESHOLD,
#ifdef ENABLE_HOTPLUGGING
.down_threshold_hotplug1 = DEF_FREQUENCY_DOWN_THRESHOLD_HOTPLUG,
.down_threshold_hotplug_freq1 = DEF_FREQUENCY_DOWN_THRESHOLD_HOTPLUG_FREQ,
.block_down_multiplier_hotplug1 = DEF_BLOCK_DOWN_MULTIPLIER_HOTPLUG1,
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
.down_threshold_hotplug2 = DEF_FREQUENCY_DOWN_THRESHOLD_HOTPLUG,
.down_threshold_hotplug_freq2 = DEF_FREQUENCY_DOWN_THRESHOLD_HOTPLUG_FREQ,
.block_down_multiplier_hotplug2 = DEF_BLOCK_DOWN_MULTIPLIER_HOTPLUG2,
.down_threshold_hotplug3 = DEF_FREQUENCY_DOWN_THRESHOLD_HOTPLUG,
.down_threshold_hotplug_freq3 = DEF_FREQUENCY_DOWN_THRESHOLD_HOTPLUG_FREQ,
.block_down_multiplier_hotplug3 = DEF_BLOCK_DOWN_MULTIPLIER_HOTPLUG3,
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
.down_threshold_hotplug4 = DEF_FREQUENCY_DOWN_THRESHOLD_HOTPLUG,
.down_threshold_hotplug_freq4 = DEF_FREQUENCY_DOWN_THRESHOLD_HOTPLUG_FREQ,
.block_down_multiplier_hotplug4 = DEF_BLOCK_DOWN_MULTIPLIER_HOTPLUG4,
.down_threshold_hotplug5 = DEF_FREQUENCY_DOWN_THRESHOLD_HOTPLUG,
.down_threshold_hotplug_freq5 = DEF_FREQUENCY_DOWN_THRESHOLD_HOTPLUG_FREQ,
.block_down_multiplier_hotplug5 = DEF_BLOCK_DOWN_MULTIPLIER_HOTPLUG5,
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
.down_threshold_hotplug6 = DEF_FREQUENCY_DOWN_THRESHOLD_HOTPLUG,
.down_threshold_hotplug_freq6 = DEF_FREQUENCY_DOWN_THRESHOLD_HOTPLUG_FREQ,
.block_down_multiplier_hotplug6 = DEF_BLOCK_DOWN_MULTIPLIER_HOTPLUG6,
.down_threshold_hotplug7 = DEF_FREQUENCY_DOWN_THRESHOLD_HOTPLUG,
.down_threshold_hotplug_freq7 = DEF_FREQUENCY_DOWN_THRESHOLD_HOTPLUG_FREQ,
.block_down_multiplier_hotplug7 = DEF_BLOCK_DOWN_MULTIPLIER_HOTPLUG7,
#endif /* (MAX_CORES == 8) */
#endif /* ENABLE_HOTPLUGGING */
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
.down_threshold_sleep = DEF_DOWN_THRESHOLD_SLEEP,
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
.ignore_nice = DEF_IGNORE_NICE,
.smooth_up = DEF_SMOOTH_UP,
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
.smooth_up_sleep = DEF_SMOOTH_UP_SLEEP,
#ifdef ENABLE_HOTPLUGGING
.hotplug_sleep = DEF_HOTPLUG_SLEEP,
#endif /* ENABLE_HOTPLUGGING */
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
.freq_limit = DEF_FREQ_LIMIT,
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
.freq_limit_sleep = DEF_FREQ_LIMIT_SLEEP,
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
.fast_scaling_up = DEF_FAST_SCALING_UP,
.fast_scaling_down = DEF_FAST_SCALING_DOWN,
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
.fast_scaling_sleep_up = DEF_FAST_SCALING_SLEEP_UP,
.fast_scaling_sleep_down = DEF_FAST_SCALING_SLEEP_DOWN,
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
.afs_threshold1 = DEF_AFS_THRESHOLD1,
.afs_threshold2 = DEF_AFS_THRESHOLD2,
.afs_threshold3 = DEF_AFS_THRESHOLD3,
.afs_threshold4 = DEF_AFS_THRESHOLD4,
.grad_up_threshold = DEF_GRAD_UP_THRESHOLD,
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
.grad_up_threshold_sleep = DEF_GRAD_UP_THRESHOLD_SLEEP,
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
.early_demand = DEF_EARLY_DEMAND,
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
.early_demand_sleep = DEF_EARLY_DEMAND_SLEEP,
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_HOTPLUGGING
.disable_hotplug = DEF_DISABLE_HOTPLUG,
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
.disable_hotplug_sleep = DEF_DISABLE_HOTPLUG_SLEEP,
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
.hotplug_block_up_cycles = DEF_HOTPLUG_BLOCK_UP_CYCLES,
.hotplug_block_down_cycles = DEF_HOTPLUG_BLOCK_DOWN_CYCLES,
.hotplug_stagger_up = DEF_HOTPLUG_STAGGER_UP,
.hotplug_stagger_down = DEF_HOTPLUG_STAGGER_DOWN,
.hotplug_idle_threshold = DEF_HOTPLUG_IDLE_THRESHOLD,
.hotplug_idle_freq = DEF_HOTPLUG_IDLE_FREQ,
.hotplug_engage_freq = DEF_HOTPLUG_ENGAGE_FREQ,
.hotplug_max_limit = DEF_HOTPLUG_MAX_LIMIT,
.hotplug_min_limit = DEF_HOTPLUG_MIN_LIMIT,
.hotplug_min_limit_saved = DEF_HOTPLUG_MIN_LIMIT,
.hotplug_min_limit_touchbooster = 0,
.hotplug_lock = DEF_HOTPLUG_LOCK,
#endif /* ENABLE_HOTPLUGGING */
.scaling_block_threshold = DEF_SCALING_BLOCK_THRESHOLD,
.scaling_block_cycles = DEF_SCALING_BLOCK_CYCLES,
.scaling_up_block_cycles = DEF_SCALING_UP_BLOCK_CYCLES,
.scaling_up_block_freq = DEF_SCALING_UP_BLOCK_FREQ,
#ifdef CONFIG_EXYNOS4_EXPORT_TEMP
.scaling_block_temp = DEF_SCALING_BLOCK_TEMP,
#endif /* CONFIG_EXYNOS4_EXPORT_TEMP */
#ifdef ENABLE_SNAP_THERMAL_SUPPORT
.scaling_trip_temp = DEF_SCALING_TRIP_TEMP,
#endif /* ENABLE_SNAP_THERMAL_SUPPORT */
.scaling_block_freq = DEF_SCALING_BLOCK_FREQ,
.scaling_block_force_down = DEF_SCALING_BLOCK_FORCE_DOWN,
.scaling_fastdown_freq = DEF_SCALING_FASTDOWN_FREQ,
.scaling_fastdown_up_threshold = DEF_SCALING_FASTDOWN_UP_THRESHOLD,
.scaling_fastdown_down_threshold = DEF_SCALING_FASTDOWN_DOWN_THRESHOLD,
.scaling_responsiveness_freq = DEF_SCALING_RESPONSIVENESS_FREQ,
.scaling_responsiveness_up_threshold = DEF_SCALING_RESPONSIVENESS_UP_THRESHOLD,
.scaling_proportional = DEF_SCALING_PROPORTIONAL,
#ifdef ENABLE_INPUTBOOSTER
// ff: Input Booster
.inputboost_cycles = DEF_INPUTBOOST_CYCLES,
.inputboost_up_threshold = DEF_INPUTBOOST_UP_THRESHOLD,
.inputboost_punch_cycles = DEF_INPUTBOOST_PUNCH_CYCLES,
.inputboost_punch_freq = DEF_INPUTBOOST_PUNCH_FREQ,
.inputboost_punch_on_fingerdown = DEF_INPUTBOOST_PUNCH_ON_FINGERDOWN,
.inputboost_punch_on_fingermove = DEF_INPUTBOOST_PUNCH_ON_FINGERMOVE,
.inputboost_punch_on_epenmove = DEF_INPUTBOOST_PUNCH_ON_EPENMOVE,
.inputboost_typingbooster_up_threshold = DEF_INPUTBOOST_TYPINGBOOSTER_UP_THRESHOLD,
.inputboost_typingbooster_cores = DEF_INPUTBOOST_TYPINGBOOSTER_CORES,
#endif /* ENABLE_INPUTBOOSTER */
#ifdef ENABLE_MUSIC_LIMITS
.music_max_freq = DEF_MUSIC_MAX_FREQ,
.music_min_freq = DEF_MUSIC_MIN_FREQ,
#ifdef ENABLE_HOTPLUGGING
.music_min_cores = DEF_MUSIC_MIN_CORES,
#endif /* ENABLE_HOTPLUGGING */
.music_state = 0,
#endif /* ENABLE_MUSIC_LIMITS */
};
#ifdef ENABLE_INPUTBOOSTER
// ff: Input Booster
static void interactive_input_event(struct input_handle *handle, unsigned int type, unsigned int code, int value)
{
unsigned int time_since_typingbooster_lasttapped = 0;
unsigned int flg_do_punch_id = 0;
struct timeval time_now;
bool flg_inputboost_mt_touchmajor = false;
bool flg_inputboost_abs_xy = false;
bool flg_force_punch = false;
int inputboost_btn_toolfinger = -1;
int inputboost_btn_touch = -1;
int inputboost_mt_trackingid = 0;
int tmp_flg_ctr_inputboost_punch = 0;
// ff: don't do any boosting when overheating
#ifdef ENABLE_SNAP_THERMAL_SUPPORT
if (tmu_throttle_steps > 0)
return;
#endif /* ENABLE_SNAP_THERMAL_SUPPORT */
/*
* ff: ignore events if inputboost isn't enabled (we shouldn't ever be here in that case)
* or screen-off (but allow power press)
*/
if (!dbs_tuners_ins.inputboost_cycles
|| (suspend_flag && inputboost_last_code != 116))
return;
if (type == EV_SYN && code == SYN_REPORT) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] syn input event. device: %s, saw_touchmajor: %d, saw_xy: %d, toolfinger: %d, touch: %d, trackingid: %d\n",
handle->dev->name, flg_inputboost_report_mt_touchmajor, flg_inputboost_report_abs_xy, inputboost_report_btn_toolfinger, inputboost_report_btn_touch, inputboost_report_mt_trackingid);
#endif /* ZZMOOVE_DEBUG */
if (strstr(handle->dev->name, "touchscreen") || strstr(handle->dev->name, "synaptics")) {
// ff: don't boost if not enabled, or while sleeping
if (!boost_on_tsp || suspend_flag)
return;
// ff: save the event's data flags
flg_inputboost_mt_touchmajor = flg_inputboost_report_mt_touchmajor;
flg_inputboost_abs_xy = flg_inputboost_report_abs_xy;
inputboost_btn_toolfinger = inputboost_report_btn_toolfinger;
inputboost_btn_touch = inputboost_report_btn_touch;
inputboost_mt_trackingid = inputboost_report_mt_trackingid;
// ff: reset the event's data flags
flg_inputboost_report_mt_touchmajor = false;
flg_inputboost_report_abs_xy = false;
inputboost_report_btn_toolfinger = -1;
inputboost_report_btn_touch = -1;
inputboost_report_mt_trackingid = 0;
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] syn input event. device: %s, saw_touchmajor: %d, saw_xy: %d, toolfinger: %d, touch: %d, trackingid: %d\n",
handle->dev->name, flg_inputboost_mt_touchmajor, flg_inputboost_abs_xy, inputboost_btn_toolfinger, inputboost_btn_touch, inputboost_mt_trackingid);
#endif /* ZZMOOVE_DEBUG */
// ff: try to determine what kind of event we just saw
if (!flg_inputboost_mt_touchmajor
&& (flg_inputboost_abs_xy || inputboost_mt_trackingid < 0)
&& inputboost_btn_touch < 0) {
/*
* ff: assume hovering since:
* no width was reported, and btn_touch isn't set, and (xy coords were included or trackingid is -1 meaning hover-up)
*/
// ff: don't boost if not enabled
if (!boost_on_tsp_hover)
return;
#ifdef ZZMOOVE_DEBUG
// ff: hover is hardcoded to only punch on first hover, otherwise it'd be punching constantly
if (inputboost_mt_trackingid > 0) {
pr_info("[zzmoove] touch - first hover btn_touch: %d\n", inputboost_btn_touch);
/*// ff: unused, but kept for future use
flg_do_punch_id = 4;
flg_force_punch = false;*/
} else if (inputboost_mt_trackingid < 0) {
pr_info("[zzmoove] touch - end hover btn_touch: %d\n", inputboost_btn_touch);
/*// ff: don't boost if not enabled, or while sleeping
flg_ctr_inputboost_punch = 0;
flg_ctr_inputboost = 0;*/
} else {
pr_info("[zzmoove] touch - update hover btn_touch: %d\n", inputboost_btn_touch);
}
#endif /* ZZMOOVE_DEBUG */
} else if (inputboost_mt_trackingid > 0) {
// ff: new finger detected event
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] touch - first touch\n");
#endif /* ZZMOOVE_DEBUG */
flg_do_punch_id = 2;
// ff: should we boost on every finger down event?
if (dbs_tuners_ins.inputboost_punch_on_fingerdown)
flg_force_punch = true;
// ff: typing booster. detects rapid taps, and if found, boosts core count and up_threshold
if (dbs_tuners_ins.inputboost_typingbooster_up_threshold) {
// ff: save current time
do_gettimeofday(&time_now);
// ff: get time difference
time_since_typingbooster_lasttapped = (time_now.tv_sec - time_typingbooster_lasttapped.tv_sec) * MSEC_PER_SEC +
(time_now.tv_usec - time_typingbooster_lasttapped.tv_usec) / USEC_PER_MSEC;
// ff: was that typing or just a doubletap?
if (time_since_typingbooster_lasttapped < 250) {
// ff: tap is probably typing
ctr_inputboost_typingbooster_taps++;
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] inputboost - typing booster - valid tap: %d\n", ctr_inputboost_typingbooster_taps);
#endif /* ZZMOOVE_DEBUG */
} else {
// ff: tap too quick, probably a doubletap, ignore
ctr_inputboost_typingbooster_taps = 0;
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] inputboost - typing booster - invalid tap: %d (age: %d)\n", ctr_inputboost_typingbooster_taps, time_since_typingbooster_lasttapped);
#endif /* ZZMOOVE_DEBUG */
}
if ((flg_ctr_inputbooster_typingbooster < 1 && ctr_inputboost_typingbooster_taps > 1) // ff: if booster wasn't on, require 3 taps
|| (flg_ctr_inputbooster_typingbooster > 0 && ctr_inputboost_typingbooster_taps > 0)) { // ff: otherwise, refill with only 2
#ifdef ZZMOOVE_DEBUG
// ff: probably typing, so start the typing booster
if (flg_ctr_inputbooster_typingbooster < 1)
pr_info("[zzmoove] inputboost - typing booster on!\n");
#endif /* ZZMOOVE_DEBUG */
// ff: set typing booster up_threshold counter
flg_ctr_inputbooster_typingbooster = 15;
// ff: request a punch
flg_do_punch_id = 12;
/*
* ff: forcing this will effectively turn this into a touchbooster,
* as it will keep applying the punch freq until the typing (taps) stops
*/
flg_force_punch = true;
#ifdef ZZMOOVE_DEBUG
} else {
pr_info("[zzmoove] inputboost - typing booster - tapctr: %d, flgctr: %d\n", ctr_inputboost_typingbooster_taps, flg_ctr_inputbooster_typingbooster);
#endif /* ZZMOOVE_DEBUG */
}
// ff: and finally, set the time so we can compare to it on the next tap
do_gettimeofday(&time_typingbooster_lasttapped);
}
#ifdef ZZMOOVE_DEBUG
} else if (inputboost_mt_trackingid < 0) {
// ff: finger-lifted event. do nothing
pr_info("[zzmoove] touch - end touch\n");
#endif /* ZZMOOVE_DEBUG */
} else if (flg_inputboost_mt_touchmajor) {
// ff: width was reported, assume regular tap
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] touch - update touch\n");
#endif /* ZZMOOVE_DEBUG */
// ff: should we treat this like a touchbooster and always punch on movement?
if (dbs_tuners_ins.inputboost_punch_on_fingermove) {
flg_do_punch_id = 3;
flg_force_punch = true;
}
} else {
// ff: unknown event. do nothing
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] touch - unknown\n");
#endif /* ZZMOOVE_DEBUG */
return;
}
} else if (strstr(handle->dev->name, "gpio")) {
// ff: don't boost if not enabled, or while sleeping
if (!boost_on_gpio || suspend_flag)
return;
// ff: check for home button
if (inputboost_last_code == 172) {
if (suspend_flag) {
// ff: home press while suspended shouldn't boost as hard
flg_ctr_cpuboost = 2;
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] inputboost - gpio punched freq immediately!\n");
#endif /* ZZMOOVE_DEBUG */
} else {
// ff: home press while screen on should boost
flg_ctr_cpuboost = 10;
#ifdef ENABLE_WORK_RESTARTLOOP
queue_work_on(0, dbs_aux_wq, &work_restartloop);
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] inputboost - gpio punched freq immediately!\n");
#endif /* ZZMOOVE_DEBUG */
// ff: don't punch, since we just did manually
#endif /* ENABLE_WORK_RESTARTLOOP */
}
} else {
/*
* ff: other press (aka vol up on note4)
* treat it as a normal button press
*/
flg_do_punch_id = 7;
flg_force_punch = true;
}
} else if (strstr(handle->dev->name, "touchkey")) {
// ff: don't boost if not enabled, or while sleeping
if (!boost_on_tk || suspend_flag)
return;
// ff: check for recents button
if (inputboost_last_code == 254) {
/*
* ff: recents press. do more than punch,
* and set the max-boost and max-core counters, too
*/
flg_ctr_cpuboost = 20;
} else {
// ff: anything else (ie. back press)
flg_ctr_cpuboost = 3;
}
// ff: always manually punch for touchkeys
#ifdef ENABLE_WORK_RESTARTLOOP
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] inputboost - tk punched freq immediately!\n");
#endif /* ZZMOOVE_DEBUG */
queue_work_on(0, dbs_aux_wq, &work_restartloop);
#endif /* ENABLE_WORK_RESTARTLOOP */
// ff: don't punch, since we just did manually
} else if (strstr(handle->dev->name, "e-pen")) {
// ff: s-pen is hovering or writing
// ff: don't boost if not enabled, or while sleeping
if (!boost_on_epen || suspend_flag)
return;
// ff: request a punch
flg_do_punch_id = 11;
// ff: should we treat this like a touchbooster and always punch on movement?
if (dbs_tuners_ins.inputboost_punch_on_epenmove)
flg_force_punch = true;
} else if (strstr(handle->dev->name, "qpnp_pon")) {
// ff: on the note4/opo, this is the power key and volume down
/*
* ff: only boost if power is press while screen-off
* let it still apply a normal boost on screen-on to speed up going into suspend
*/
if (inputboost_last_code == 116 && suspend_flag) {
// disabled since we're still boosting in the pon driver
/*flg_ctr_cpuboost = 25;
flg_ctr_inputboost = 100;
queue_work_on(0, dbs_aux_wq, &work_restartloop);
pr_info("[zzmoove] inputboost - gpio/powerkey punched freq immediately and skipped the rest\n");*/
// ff: not only don't punch, but don't even start the booster, since we just did both with zzmoove_boost() externally
return;
} else {
// ff: even though it's coming from a different device, treat this if it was a gpio event anyway
flg_do_punch_id = 7;
flg_force_punch = true;
}
}
if (flg_do_punch_id // ff: punch is requested
&& dbs_tuners_ins.inputboost_punch_cycles // ff: punch is enabled
&& dbs_tuners_ins.inputboost_punch_freq // ff: punch is enabled
&& (flg_ctr_inputboost < 1 || flg_force_punch)) { // ff: this is the first event since the inputbooster ran out, or it is forced
// a punch length and frequency is set, so boost!
// ff: but only do so if it hasn't been punched yet, or if it hasn't been punched by a touch yet
// ff: save the punch counter state so we can avoid redundantly flushing the punch
tmp_flg_ctr_inputboost_punch = flg_ctr_inputboost_punch;
// ff: refill the punch counter. remember, flg_ctr_inputboost_punch is decremented before it is used, so add 1
flg_ctr_inputboost_punch = dbs_tuners_ins.inputboost_punch_cycles + 1;
// ff: don't immediately apply the punch if we're already boosted or punched
#ifdef ENABLE_WORK_RESTARTLOOP
if (flg_ctr_cpuboost < 5 && tmp_flg_ctr_inputboost_punch < 1) {
queue_work_on(0, dbs_aux_wq, &work_restartloop);
#endif /* ENABLE_WORK_RESTARTLOOP */
#ifdef ZZMOOVE_DEBUG
do_gettimeofday(&time_touchbooster_lastrun);
pr_info("[zzmoove] inputboost - punched freq immediately for: %d\n", flg_do_punch_id);
#endif /* ZZMOOVE_DEBUG */
#ifdef ENABLE_WORK_RESTARTLOOP
}
#endif /* ENABLE_WORK_RESTARTLOOP */
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] inputboost - punch set to %d mhz for %d cycles (punched by: %d, forced: %d)\n",
dbs_tuners_ins.inputboost_punch_freq, dbs_tuners_ins.inputboost_punch_cycles, flg_do_punch_id, flg_force_punch);
#endif /* ZZMOOVE_DEBUG */
}
// ff: refill the inputboost counter to apply the up_threshold
flg_ctr_inputboost = dbs_tuners_ins.inputboost_cycles;
} else {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] ev input event. name: %s, type: %d, code: %d, value: %d\n", handle->dev->name, type, code, value);
#endif /* ZZMOOVE_DEBUG */
// ff: we need to keep track of the data sent in this report
if (strstr(handle->dev->name, "touchscreen") || strstr(handle->dev->name, "synaptics")) {
if (code == BTN_TOOL_FINGER) {
// ff: 0 = nothing at all, 1 - touch OR hover starting
inputboost_report_btn_toolfinger = value;
} else if (code == BTN_TOUCH) {
// ff: 0 = up/hovering, 1 - touch starting
inputboost_report_btn_touch = value;
} else if (code == ABS_MT_TRACKING_ID) {
// ff: -1 = finger-up, >1 = finger-down
inputboost_report_mt_trackingid = value;
#ifdef ABS_MT_SUMSIZE
} else if (code == ABS_MT_TOUCH_MAJOR || code == ABS_MT_SUMSIZE) {
#else
} else if (code == ABS_MT_TOUCH_MAJOR) {
#endif /* ABS_MT_SUMSIZE */
// ff: this is a touch report
flg_inputboost_report_mt_touchmajor = true;
} else if (code == ABS_MT_POSITION_X || code == ABS_MT_POSITION_Y) {
// ff: this is a hover report, maybe
flg_inputboost_report_abs_xy = true;
}
} else {
// ff: a simple saving of the last event is sufficent for non-tsp events
inputboost_last_type = type;
inputboost_last_code = code;
inputboost_last_value = value;
}
}
}
static int input_dev_filter(const char *input_dev_name)
{
if (strstr(input_dev_name, "sec_touchscreen") ||
strstr(input_dev_name, "sec_e-pen") ||
strstr(input_dev_name, "gpio-keys") ||
strstr(input_dev_name, "sec_touchkey") ||
strstr(input_dev_name, "s2s_pwrkey") || // ZZ: opo power key?
strstr(input_dev_name, "msm8974-taiko-mtp-snd-card Button Jack") || // ZZ: opo sound button?
strstr(input_dev_name, "msm8974-taiko-mtp-snd-card Headset Jack") || // ZZ: opo headset jack
strstr(input_dev_name, "synaptics-rmi-ts") || // ZZ: opo touchscreen
strstr(input_dev_name, "qpnp_pon") // ff: note4/opo power and volume-down key
//strstr(input_dev_name, "es705") // ff: note4 always-on audio monitoring, but no input events are sent, so it's pointless
) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] inputboost - monitoring input device: %s\n", input_dev_name);
#endif /* ZZMOOVE_DEBUG */
return 0;
} else {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] inputboost - ignored input device: %s\n", input_dev_name);
#endif /* ZZMOOVE_DEBUG */
return 1;
}
}
static int interactive_input_connect(struct input_handler *handler, struct input_dev *dev, const struct input_device_id *id)
{
struct input_handle *handle;
int error;
if (input_dev_filter(dev->name))
return -ENODEV;
handle = kzalloc(sizeof(struct input_handle), GFP_KERNEL);
if (!handle)
return -ENOMEM;
handle->dev = dev;
handle->handler = handler;
handle->name = "cpufreq";
error = input_register_handle(handle);
if (error)
goto err2;
error = input_open_device(handle);
if (error)
goto err1;
return 0;
err1:
input_unregister_handle(handle);
err2:
kfree(handle);
return error;
}
static void interactive_input_disconnect(struct input_handle *handle)
{
// ff: reset counters
flg_ctr_inputboost = 0;
flg_ctr_inputboost_punch = 0;
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/interactive_input_disconnect] inputbooster - unregistering\n");
#endif /* ZZMOOVE_DEBUG */
input_close_device(handle);
input_unregister_handle(handle);
kfree(handle);
}
static const struct input_device_id interactive_ids[] = {
{ .driver_info = 1 },
{ },
};
static struct input_handler interactive_input_handler = {
.event = interactive_input_event,
.connect = interactive_input_connect,
.disconnect = interactive_input_disconnect,
.name = "zzmoove",
.id_table = interactive_ids,
};
#endif /* ENABLE_INPUTBOOSTER */
// Yank: return a valid value between min and max
static int validate_min_max(int val, int min, int max)
{
return min(max(val, min), max);
}
// ZZ: system table scaling mode with freq search optimizations and proportional freq option
static inline int zz_get_next_freq(unsigned int curfreq, unsigned int updown, unsigned int load)
{
int i = 0;
unsigned int prop_target = 0, zz_target = 0, dead_band_freq = 0; // ZZ: proportional freq, system table freq, dead band freq
int smooth_up_steps = 0; // Yank: smooth up steps
static int tmp_limit_table_start = 0;
static int tmp_max_scaling_freq_soft = 0;
static int tmp_limit_table_end = 0;
prop_target = pol_min + load * (pol_max - pol_min) / 100; // ZZ: prepare proportional target freq whitout deadband (directly mapped to min->max load)
if (dbs_tuners_ins.scaling_proportional == 2) // ZZ: mode '2' use proportional target frequencies only
return prop_target;
if (dbs_tuners_ins.scaling_proportional == 3) { // ZZ: mode '3' use proportional target frequencies only and switch to pol_min in deadband range
dead_band_freq = pol_max / 100 * load; // ZZ: use old calculation to get deadband frequencies (=lower than pol_min)
if (dead_band_freq > pol_min) // ZZ: the load usually is too unsteady so we rarely would reach pol_min when load is low
return prop_target; // ZZ: in fact it only will happen when load=0, so only return proportional frequencies if they
else // are out of deadband range and if we are in deadband range return min freq
return pol_min; // (thats a similar behaving as with old propotional freq calculation)
}
if (load <= dbs_tuners_ins.smooth_up) // Yank: consider smooth up
smooth_up_steps = 0; // Yank: load not reached, move by one step
else
smooth_up_steps = 1; // Yank: load reached, move by two steps
tmp_limit_table_start = limit_table_start; // ZZ: first assign new limits...
tmp_limit_table_end = limit_table_end;
tmp_max_scaling_freq_soft = max_scaling_freq_soft;
// ZZ: asc: min freq limit changed
if (!freq_table_desc && curfreq
< system_freq_table[min_scaling_freq].frequency) // ZZ: asc: but reset starting index if current freq is lower than soft/hard min limit otherwise we are
tmp_limit_table_start = 0; // shifting out of range and proportional freq is used instead because freq can't be found by loop
// ZZ: asc: max freq limit changed
if (!freq_table_desc && curfreq
> system_freq_table[max_scaling_freq_soft].frequency) // ZZ: asc: but reset ending index if current freq is higher than soft/hard max limit otherwise we are
tmp_limit_table_end = system_freq_table[freq_table_size].frequency; // shifting out of range and proportional freq is used instead because freq can't be found by loop
// ZZ: desc: max freq limit changed
if (freq_table_desc && curfreq
> system_freq_table[limit_table_start].frequency) // ZZ: desc: but reset starting index if current freq is higher than soft/hard max limit otherwise we are
tmp_limit_table_start = 0; // shifting out of range and proportional freq is used instead because freq can't be found by loop
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
#ifdef ENABLE_MUSIC_LIMITS
// ff: check to see if we need to override the screen-off limit with the music one
if (suspend_flag && dbs_tuners_ins.freq_limit_sleep
&& dbs_tuners_ins.freq_limit_sleep < dbs_tuners_ins.music_max_freq
&& dbs_tuners_ins.music_state) {
tmp_max_scaling_freq_soft = music_max_freq_step;
if (!freq_table_desc && curfreq // ZZ: asc: assign only if current freq is lower or equal soft/hard limit otherwise we are shifting out
<= system_freq_table[music_max_freq_step].frequency) // of range and proportional freq is used instead because freq can't be found by loop
tmp_limit_table_end = system_freq_table[music_max_freq_step].frequency;
if (freq_table_desc && curfreq
<= system_freq_table[music_max_freq_step].frequency) { // ZZ: desc: assign only if current freq is lower or equal soft/hard limit otherwise we are shifting out
tmp_limit_table_start = music_max_freq_step; // of range and proportional freq is used instead because freq can't be found by loop
} else if (freq_table_desc && curfreq
> system_freq_table[music_max_freq_step].frequency) {
tmp_limit_table_start = 0;
}
}
#endif /* ENABLE_MUSIC_LIMITS */
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
// ZZ: feq search loop with optimization
if (freq_table_desc) {
for (i = tmp_limit_table_start; (likely(system_freq_table[i].frequency != tmp_limit_table_end)); i++) {
if (unlikely(curfreq == system_freq_table[i].frequency)) { // Yank: we found where we currently are (i)
if (updown == 1) { // Yank: scale up, but don't go above softlimit
zz_target = min(system_freq_table[tmp_max_scaling_freq_soft].frequency,
system_freq_table[validate_min_max(i - 1 - smooth_up_steps - scaling_mode_up, 0, freq_table_size)].frequency);
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/zz_get_next_freq] desc - UP - val1: %d - val2: %d [steps: %d, smooth_up: %d, scaling_mode_up: %d]\n",
system_freq_table[tmp_max_scaling_freq_soft].frequency, system_freq_table[validate_min_max(i - 1 - smooth_up_steps - scaling_mode_up,
0, freq_table_size)].frequency, (1 + smooth_up_steps + scaling_mode_up), smooth_up_steps, scaling_mode_up);
#endif /* ZZMOOVE_DEBUG */
if (dbs_tuners_ins.scaling_proportional == 1) // ZZ: if proportional scaling is enabled
return min(zz_target, prop_target); // ZZ: check which freq is lower and return it
else
return zz_target; // ZZ: or return the found system table freq as usual
} else { // Yank: scale down, but don't go below min. freq.
zz_target = max(system_freq_table[min_scaling_freq].frequency,
system_freq_table[validate_min_max(i + 1 + scaling_mode_down, 0, freq_table_size)].frequency);
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/zz_get_next_freq] desc - DOWN - val1: %d - val2: %d [steps: %d, scaling_mode_down: %d]\n",
system_freq_table[tmp_max_scaling_freq_soft].frequency, system_freq_table[validate_min_max(i + 1 + scaling_mode_down,
0, freq_table_size)].frequency, (1 + scaling_mode_down), scaling_mode_down);
#endif /* ZZMOOVE_DEBUG */
if (dbs_tuners_ins.scaling_proportional == 1) // ZZ: if proportional scaling is enabled
return min(zz_target, prop_target); // ZZ: check which freq is lower and return it
else
return zz_target; // ZZ: or return the found system table freq as usual
}
}
} // ZZ: this shouldn't happen but if the freq is not found in system table
return prop_target; // fall back to proportional freq target to avoid returning 0
} else {
for (i = tmp_limit_table_start; (likely(system_freq_table[i].frequency <= tmp_limit_table_end)); i++) {
if (unlikely(curfreq == system_freq_table[i].frequency)) { // Yank: we found where we currently are (i)
if (updown == 1) { // Yank: scale up, but don't go above softlimit
zz_target = min(system_freq_table[tmp_max_scaling_freq_soft].frequency,
system_freq_table[validate_min_max(i + 1 + smooth_up_steps + scaling_mode_up, 0, freq_table_size)].frequency);
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/zz_get_next_freq] asc - UP - val1: %d - val2: %d [steps: %d, smooth_up: %d, scaling_mode_up: %d]\n",
system_freq_table[tmp_max_scaling_freq_soft].frequency, system_freq_table[validate_min_max(i + 1 + smooth_up_steps + scaling_mode_up,
0, freq_table_size)].frequency, (1 + smooth_up_steps + scaling_mode_up), smooth_up_steps, scaling_mode_up);
#endif /* ZZMOOVE_DEBUG */
if (dbs_tuners_ins.scaling_proportional == 1) // ZZ: if proportional scaling is enabled
return min(zz_target, prop_target); // ZZ: check which freq is lower and return it
else
return zz_target; // ZZ: or return the found system table freq as usual
} else { // Yank: scale down, but don't go below min. freq.
zz_target = max(system_freq_table[min_scaling_freq].frequency,
system_freq_table[validate_min_max(i - 1 - scaling_mode_down, 0, freq_table_size)].frequency);
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/zz_get_next_freq] asc - DOWN - val1: %d - val2: %d [steps: %d, scaling_mode_down: %d]\n",
system_freq_table[min_scaling_freq].frequency, system_freq_table[validate_min_max(i - 1 - scaling_mode_down,
0, freq_table_size)].frequency, (1 + scaling_mode_down), scaling_mode_down);
#endif /* ZZMOOVE_DEBUG */
if (dbs_tuners_ins.scaling_proportional == 1) // ZZ: if proportional scaling is enabled
return min(zz_target, prop_target); // ZZ: check which freq is lower and return it
else
return zz_target; // ZZ: or return the found system table freq as usual
}
}
} // ZZ: this shouldn't happen but if the freq is not found in system table
return prop_target; // fall back to proportional freq target to avoid returning 0
}
}
#ifdef ENABLE_HOTPLUGGING
// ZZ: function for enabling/disabling cores from offline/online state
static inline void __cpuinit enable_disable_cores(void)
{
int i = 0;
if (enable_cores == 1) { // ZZ: no limit, all cores
for (i = 1; i < possible_cpus; i++) { // ZZ: enable all offline cores
if (!cpu_online(i))
cpu_up(i);
}
enable_cores = 0; // ZZ: reset enable flag again
}
if (enable_cores == 2) { // ZZ: limit min cores
for (i = 1; i < num_possible_cpus(); i++) {
#ifdef ENABLE_MUSIC_LIMITS
if (!cpu_online(i) && (i < dbs_tuners_ins.hotplug_min_limit || (dbs_tuners_ins.music_state && i < dbs_tuners_ins.music_min_cores))
#else
if (!cpu_online(i) && (i < dbs_tuners_ins.hotplug_min_limit)
#endif /* ENABLE_MUSIC_LIMITS */
&& (!dbs_tuners_ins.hotplug_max_limit || i < dbs_tuners_ins.hotplug_max_limit)) {
// ff: this core is below the minimum, so bring it up
cpu_up(i);
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] hotplug_min_limit: CPU%d forced up\n", i);
#endif /* ZZMOOVE_DEBUG */
}
}
enable_cores = 0; // ZZ: reset disable flag again
}
if (disable_cores == 1) { // ZZ: limit max cores
for (i = num_possible_cpus() - 1; i >= 1; i--) {
if (cpu_online(i) && i >= dbs_tuners_ins.hotplug_max_limit && (!dbs_tuners_ins.hotplug_min_limit
#ifdef ENABLE_MUSIC_LIMITS
|| i >= dbs_tuners_ins.hotplug_min_limit || (dbs_tuners_ins.music_state && (!dbs_tuners_ins.music_min_cores || i >= dbs_tuners_ins.music_min_cores)))) {
#else
|| i >= dbs_tuners_ins.hotplug_min_limit)) {
#endif /* ENABLE_MUSIC_LIMITS */
// ff: this core is more than the limit, so turn it off, but don't go below hotplug_min_limit or music_min_cores
cpu_down(i);
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] hotplug_max_limit: CPU%d forced down\n", i);
#endif /* ZZMOOVE_DEBUG */
}
}
disable_cores = 0; // ZZ: reset disable flag again
}
if (disable_cores == 2) { // ZZ: lock current cores
for (i = 1; i < num_possible_cpus(); i++) {
if (!cpu_online(i) && i < dbs_tuners_ins.hotplug_lock) {
// ff: this core is less than the lock, so bring it up
cpu_up(i);
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] hotplug_lock: CPU%d forced up\n", i);
#endif /* ZZMOOVE_DEBUG */
} else if (cpu_online(i) && i >= dbs_tuners_ins.hotplug_lock) {
// ff: this core is more than the lock, so turn it off
cpu_down(i);
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] hotplug_lock: CPU%d forced down\n", i);
#endif /* ZZMOOVE_DEBUG */
}
}
disable_cores = 0; // ZZ: reset disable flag again
}
}
#endif /* ENABLE_HOTPLUGGING */
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: function for checking/adapting frequency values in tuneables
static inline unsigned int check_frequency(unsigned int input_freq)
{
int i, f;
unsigned int profile_relation = 0, system_min_freq = 0,
mid_freq = 0, found_freq = 0, adapted_freq = 0, calc_freq = 0,
system_max_freq = 0, next_freq = 0, max_freq_index = 0;
// ZZ: return if we have nothing to check
if (input_freq == 0)
return 0;
// ZZ: normal checking if given frequency is already in system freq table
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) {
if (unlikely(system_freq_table[i].frequency == input_freq))
found_freq = system_freq_table[i].frequency;
}
// ZZ: max freq index in table
max_freq_index = i - 1;
// ZZ: return if we already found a freq
if (found_freq != 0) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] check_freq: freq %d diretly found!\n", found_freq);
#endif /* ZZMOOVE_DEBUG */
return found_freq;
}
// ZZ: get highest/lowest freq in system table
if (!freq_table_desc) {
system_max_freq = system_freq_table[max_freq_index].frequency; // ZZ: ascending order so last freq is the max freq
for (f = 0; (likely(system_freq_table[f].frequency != system_table_end)); f++) { // ZZ: descending order so use the first available one as min freq
if (likely(system_freq_table[f].frequency != 0)) {
system_min_freq = system_freq_table[f].frequency;
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] check_freq: minimal possible freq %d\n", system_min_freq);
#endif /* ZZMOOVE_DEBUG */
break;
}
}
} else {
system_min_freq = system_freq_table[max_freq_index].frequency; // ZZ: ascending order so last freq is the min freq
for (f = 0; (likely(system_freq_table[f].frequency != system_table_end)); f++) { // ZZ: descending order so use the first available one as max freq
if (likely(system_freq_table[f].frequency != 0)) {
system_max_freq = system_freq_table[f].frequency;
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] check_freq: maximal possible freq %d\n", system_max_freq);
#endif /* ZZMOOVE_DEBUG */
break;
}
}
}
// ZZ: if we exceed limits return the max/min possible freq
if (input_freq > system_max_freq) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] check_freq: input freq too high switching to %d\n", system_max_freq);
#endif /* ZZMOOVE_DEBUG */
return system_max_freq;
} else if (input_freq < system_min_freq) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] check_freq: input freq too low switching to %d\n", system_min_freq);
#endif /* ZZMOOVE_DEBUG */
return system_min_freq;
}
// ZZ: if not found try to adapt frequency by using a per mille relation
// first reduce input value for calculation below
calc_freq = input_freq / 100;
/*
* ZZ: calcualte relation in per mille to the max freq given in profile
* and apply it on current system freq range, this gives some calculated freq
*/
profile_relation = ((calc_freq * 1000) / (PROFILE_MAX_FREQ / 100));
calc_freq = ((system_max_freq) / 1000) * profile_relation;
// ZZ: start searching in current system table
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) {
// ZZ: set where next freq is (table order)
if (!freq_table_desc) {
next_freq = i + 1;
} else {
next_freq = i - 1;
}
// ZZ: if the calculated freq is already a valid one, use it
if (system_freq_table[i].frequency == calc_freq || system_freq_table[next_freq].frequency == calc_freq)
return calc_freq;
// ZZ: if not go on with adaptation
if (system_max_freq == PROFILE_MAX_FREQ) { // ZZ: if we are in the same freq range
// ZZ: use input freq and if the given freq is between an existing freq pair
if (system_freq_table[i].frequency < input_freq && system_freq_table[next_freq].frequency > input_freq) {
mid_freq = (system_freq_table[i].frequency + system_freq_table[next_freq].frequency) / 2; // ZZ: calcualte the mid freq of that pair
if (input_freq > mid_freq) // ZZ: and decide if lower or higher value will be used
adapted_freq = system_freq_table[next_freq].frequency; // ZZ: adapt freq to max in range
else
adapted_freq = system_freq_table[i].frequency; // ZZ: adapt freq to min in range
break;
}
} else { // ZZ: we are on a different freq range so use calc freq
if (system_freq_table[i].frequency < calc_freq && system_freq_table[next_freq].frequency > calc_freq) {
mid_freq = (system_freq_table[i].frequency + system_freq_table[next_freq].frequency) / 2; // ZZ: calcualte the mid freq of that pair
if (calc_freq > mid_freq) // ZZ: and decide if lower or higher value will be used
adapted_freq = system_freq_table[next_freq].frequency; // ZZ: adapt freq to max in range
else
adapted_freq = system_freq_table[i].frequency; // ZZ: adapt freq to min in range
break;
}
}
}
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] check_freq: input freq was %d\n", input_freq);
pr_info("[zzmoove] check_freq: calculated freq is %d\n", calc_freq);
pr_info("[zzmoove] check_freq: relation to profile in per mille %d\n", profile_relation);
pr_info("[zzmoove] check_freq: lower freq %d on index %d", system_freq_table[i].frequency, i);
pr_info("[zzmoove] check_freq: higher freq %d on index %d", system_freq_table[next_freq].frequency, next_freq);
pr_info("[zzmoove] check_freq: found freq %d / mid freq %d / adapted freq %d\n", found_freq, mid_freq, adapted_freq);
#endif /* ZZMOOVE_DEBUG */
if (adapted_freq != 0) // ZZ: if freq was adapted
return adapted_freq; // ZZ: return adapted
return 0; // ZZ: freq not found = input out of range
}
#endif /* ENABLE_PROFILES_SUPPORT */
// ZZ: function for frequency table order detection and limit optimization
static inline void evaluate_scaling_order_limit_range(bool start, bool limit, bool suspend, unsigned int min_freq, unsigned int max_freq)
{
int i = 0;
int calc_index = 0;
system_freq_table = cpufreq_frequency_get_table(0); // ZZ: update static system frequency table
/*
* ZZ: execute at start and at limit case and in combination with limit case 3 times
* to catch all scaling max/min changes at/after gov start
*/
if (start || (limit && freq_init_count <= 1)) {
// ZZ: initialisation of freq search in scaling table
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) {
if (unlikely(max_freq == system_freq_table[i].frequency))
max_scaling_freq_hard = max_scaling_freq_soft = i; // ZZ: init soft and hard max value
if (unlikely(min_freq == system_freq_table[i].frequency))
min_scaling_freq_hard = i; // ZZ: init hard min value
// Yank: continue looping until table end is reached, we need this to set the table size limit below
}
freq_table_size = i - 1; // Yank: upper index limit of freq. table
/*
* ZZ: we have to take care about where we are in the frequency table. when using kernel sources without OC capability
* it might be that the first few indexes are containg no frequencies so a save index start point is needed.
*/
calc_index = freq_table_size - max_scaling_freq_hard; // ZZ: calculate the difference and use it as start point
if (calc_index == freq_table_size) // ZZ: if we are at the end of the table
calc_index = calc_index - 1; // ZZ: shift in range for order calculation below
// Yank: assert if CPU freq. table is in ascending or descending order
if (system_freq_table[calc_index].frequency > system_freq_table[calc_index+1].frequency) {
freq_table_desc = true; // Yank: table is in descending order as expected, lowest freq at the bottom of the table
min_scaling_freq = i - 1; // Yank: last valid frequency step (lowest frequency)
limit_table_start = max_scaling_freq_soft; // ZZ: we should use the actual max scaling soft limit value as search start point
} else {
freq_table_desc = false; // Yank: table is in ascending order, lowest freq at the top of the table
min_scaling_freq = 0; // Yank: first valid frequency step (lowest frequency)
limit_table_start = min_scaling_freq_hard; // ZZ: we should use the actual min scaling hard limit value as search start point
limit_table_end = max_freq; // ZZ: end searching at highest frequency limit
}
}
// ZZ: execute at limit case but not at suspend and in combination with start case 3 times at/after gov start
if ((limit && !suspend) || (limit && freq_init_count <= 1)) {
/*
* ZZ: obviously the 'limit case' will be executed multiple times at suspend for 'sanity' checks or boosts
* but we have already a early suspend code to handle scaling search limits so we have to differentiate
* to avoid double execution at suspend!
*/
if (max_freq != system_freq_table[max_scaling_freq_hard].frequency) { // Yank: if policy->max has changed...
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) {
if (unlikely(max_freq == system_freq_table[i].frequency)) {
max_scaling_freq_hard = i; // ZZ: ...set new freq scaling index
break;
}
}
}
if (!freq_table_desc) { // ZZ: if ascending ordered table is used
if (min_freq != system_freq_table[min_scaling_freq_hard].frequency) { // ZZ: and policy->min has changed...
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) {
if (unlikely(min_freq == system_freq_table[i].frequency)) {
min_scaling_freq_hard = limit_table_start = i; // ZZ: ...set new freq scaling index
if (min_scaling_freq_soft && (max_scaling_freq_hard < min_scaling_freq_soft)) // ZZ: if max hard limit is lower than min soft limit
limit_table_start = 0; // ZZ: reset min index
if (min_scaling_freq_soft && (min_scaling_freq_hard > min_scaling_freq_soft)) { // ZZ: if min hard limit is higher than min soft limit
limit_table_start = min_scaling_freq_hard; // ZZ: use min hard index
} else if (min_scaling_freq_soft && (min_scaling_freq_hard < min_scaling_freq_soft)) {
limit_table_start = min_scaling_freq_soft; // ZZ: use min soft index
}
break;
}
}
}
}
if (dbs_tuners_ins.freq_limit == 0 || // Yank: if there is no awake freq. limit
dbs_tuners_ins.freq_limit > system_freq_table[max_scaling_freq_hard].frequency) { // Yank: or it is higher than hard max frequency
max_scaling_freq_soft = max_scaling_freq_hard; // Yank: use hard max frequency
if (freq_table_desc) // ZZ: if descending ordered table is used
limit_table_start = max_scaling_freq_soft; // ZZ: we should use the actual scaling soft limit value as search start point
else
limit_table_end = system_freq_table[max_scaling_freq_soft].frequency; // ZZ: set search end point to max freq limit when using ascending table
} else {
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) {
if (unlikely(dbs_tuners_ins.freq_limit == system_freq_table[i].frequency)) { // Yank: else lookup awake max. frequency index
max_scaling_freq_soft = i;
if (freq_table_desc) // ZZ: if descending ordered table is used
limit_table_start = max_scaling_freq_soft; // ZZ: we should use the actual scaling soft limit value as search start point
else
limit_table_end = system_freq_table[i].frequency; // ZZ: set search end point to soft freq limit when using ascending table
break;
}
}
}
if (freq_init_count < 2) // ZZ: execute start and limit part together 3 times to catch a possible setting of
freq_init_count++; // ZZ: hard freq limit after gov start - after that skip 'start' part during
} // ZZ: normal operation and use only limit part to adjust limit optimizations
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
// ZZ: execute only at suspend but not at limit case
if (suspend && !limit) { // ZZ: only if we are at suspend
if (freq_limit_asleep == 0 || // Yank: if there is no sleep frequency limit
freq_limit_asleep > system_freq_table[max_scaling_freq_hard].frequency) { // Yank: or it is higher than hard max frequency
max_scaling_freq_soft = max_scaling_freq_hard; // Yank: use hard max frequency
if (freq_table_desc) // ZZ: if descending ordered table is used
limit_table_start = max_scaling_freq_soft; // ZZ: we should use the actual scaling soft limit value as search start point
else
limit_table_end = system_freq_table[max_scaling_freq_soft].frequency; // ZZ: set search end point to max freq limit when using ascending table
} else {
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) {
if (unlikely(freq_limit_asleep == system_freq_table[i].frequency)) { // Yank: else lookup sleep max. frequency index
max_scaling_freq_soft = i;
if (freq_table_desc) // ZZ: if descending ordered table is used
limit_table_start = max_scaling_freq_soft; // ZZ: we should use the actual scaling soft limit value as search start point
else
limit_table_end = system_freq_table[i].frequency; // ZZ: set search end point to max freq limit when using ascending table
break;
}
}
}
}
// ZZ: execute only at resume but not at limit or start case
if (!suspend && !limit && !start) { // ZZ: only if we are not at suspend
if (freq_limit_awake == 0 || // Yank: if there is no awake frequency limit
freq_limit_awake > system_freq_table[max_scaling_freq_hard].frequency) { // Yank: or it is higher than hard max frequency
max_scaling_freq_soft = max_scaling_freq_hard; // Yank: use hard max frequency
if (freq_table_desc) // ZZ: if descending ordered table is used
limit_table_start = max_scaling_freq_soft; // ZZ: we should use the actual scaling soft limit value as search start point
else
limit_table_end = system_freq_table[max_scaling_freq_soft].frequency; // ZZ: set search end point to max freq limit when using ascending table
} else {
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) {
if (unlikely(freq_limit_awake == system_freq_table[i].frequency)) { // Yank: else lookup awake max. frequency index
max_scaling_freq_soft = i;
if (freq_table_desc) // ZZ: if descending ordered table is used
limit_table_start = max_scaling_freq_soft; // ZZ: we should use the actual scaling soft limit value as search start point
else
limit_table_end = system_freq_table[i].frequency; // ZZ: set search end point to soft freq limit when using ascending table
break;
}
}
}
}
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
}
#ifdef ENABLE_AUTO_ADJUST_FREQ
// ZZ: function for auto adjusting frequency thresholds if max policy has changed
static inline void adjust_freq_thresholds(unsigned int step)
{
if (dbs_tuners_ins.auto_adjust_freq_thresholds != 0 && step != 0 && freq_init_count > 0) { // ZZ: start adjusting if enabled and after freq search is ready initialized
#ifdef ENABLE_HOTPLUGGING
// ZZ: adjust hotplug engage freq
if (dbs_tuners_ins.hotplug_engage_freq != 0) { // ZZ: adjust only if tuneable is set
if ((dbs_tuners_ins.hotplug_engage_freq + step < pol_min
|| dbs_tuners_ins.hotplug_engage_freq + step > pol_max)
&& !temp_hotplug_engage_freq_flag) { // ZZ: check if we would go under/over limits
temp_hotplug_engage_freq = dbs_tuners_ins.hotplug_engage_freq + step; // ZZ: if so do it temporary but do not save tuneable yet
temp_hotplug_engage_freq_flag = true; // ZZ: set temp saving flag
} else if (temp_hotplug_engage_freq_flag) { // ZZ: last time we were under/over limits
if (temp_hotplug_engage_freq + step < pol_min
|| temp_hotplug_engage_freq + step > pol_max) { // ZZ: and if we are still there
temp_hotplug_engage_freq = temp_hotplug_engage_freq + step; // ZZ: add step to temp var instead of tuneable var
} else {
dbs_tuners_ins.hotplug_engage_freq = temp_hotplug_engage_freq + step; // ZZ: else use it as offset for next step and finally save it in tuneable
temp_hotplug_engage_freq = 0; // ZZ: reset temp var
temp_hotplug_engage_freq_flag = false; // ZZ: reset temp flag
}
} else {
dbs_tuners_ins.hotplug_engage_freq += step; // ZZ: or change it directly in the tuneable if we are in good range
}
}
// ZZ: adjust hotplug idle freq
if (dbs_tuners_ins.hotplug_idle_freq != 0) {
if ((dbs_tuners_ins.hotplug_idle_freq + step < pol_min
|| dbs_tuners_ins.hotplug_idle_freq + step > pol_max)
&& !temp_hotplug_idle_freq_flag) {
temp_hotplug_idle_freq = dbs_tuners_ins.hotplug_idle_freq + step;
temp_hotplug_idle_freq_flag = true;
} else if (temp_hotplug_idle_freq_flag) {
if (temp_hotplug_idle_freq + step < pol_min
|| temp_hotplug_idle_freq + step > pol_max) {
temp_hotplug_idle_freq = temp_hotplug_idle_freq + step;
} else {
dbs_tuners_ins.hotplug_idle_freq = temp_hotplug_idle_freq + step;
temp_hotplug_idle_freq = 0;
temp_hotplug_idle_freq_flag = false;
}
} else {
dbs_tuners_ins.hotplug_idle_freq += step;
}
}
#endif /* ENABLE_HOTPLUGGING */
#ifdef ENABLE_INPUTBOOSTER
// ZZ: adjust inputboost punch freq
if (dbs_tuners_ins.inputboost_punch_freq != 0) {
if ((dbs_tuners_ins.inputboost_punch_freq + step < pol_min
|| dbs_tuners_ins.inputboost_punch_freq + step > pol_max)
&& !temp_inputboost_punch_freq_flag) {
temp_inputboost_punch_freq = dbs_tuners_ins.inputboost_punch_freq + step;
temp_inputboost_punch_freq_flag = true;
} else if (temp_inputboost_punch_freq_flag) {
if (temp_inputboost_punch_freq + step < pol_min
|| temp_inputboost_punch_freq + step > pol_max) {
temp_inputboost_punch_freq = temp_inputboost_punch_freq + step;
} else {
dbs_tuners_ins.inputboost_punch_freq = temp_inputboost_punch_freq + step;
temp_inputboost_punch_freq = 0;
temp_inputboost_punch_freq = false;
}
} else {
dbs_tuners_ins.inputboost_punch_freq += step;
}
}
#endif /* ENABLE_INPUTBOOSTER */
// ZZ: adjust scaling block freq
if (dbs_tuners_ins.scaling_block_freq != 0) {
if ((dbs_tuners_ins.scaling_block_freq + step < pol_min
|| dbs_tuners_ins.scaling_block_freq + step > pol_max)
&& !temp_scaling_block_freq_flag) {
temp_scaling_block_freq = dbs_tuners_ins.scaling_block_freq + step;
temp_scaling_block_freq_flag = true;
} else if (temp_scaling_block_freq_flag) {
if (temp_scaling_block_freq + step < pol_min
|| temp_scaling_block_freq + step > pol_max) {
temp_scaling_block_freq = temp_scaling_block_freq + step;
} else {
dbs_tuners_ins.scaling_block_freq = temp_scaling_block_freq + step;
temp_scaling_block_freq = 0;
temp_scaling_block_freq_flag = false;
}
} else {
dbs_tuners_ins.scaling_block_freq += step;
}
}
// ZZ: adjust scaling fastdown freq
if (dbs_tuners_ins.scaling_fastdown_freq != 0) {
if ((dbs_tuners_ins.scaling_fastdown_freq + step < pol_min
|| dbs_tuners_ins.scaling_fastdown_freq + step > pol_max)
&& !temp_scaling_fastdown_freq_flag) {
temp_scaling_fastdown_freq = dbs_tuners_ins.scaling_fastdown_freq + step;
temp_scaling_fastdown_freq_flag = true;
} else if (temp_scaling_fastdown_freq_flag) {
if (temp_scaling_fastdown_freq + step < pol_min
|| temp_scaling_fastdown_freq + step > pol_max) {
temp_scaling_fastdown_freq = temp_scaling_fastdown_freq + step;
} else {
dbs_tuners_ins.scaling_fastdown_freq = temp_scaling_fastdown_freq + step;
temp_scaling_fastdown_freq = 0;
temp_scaling_fastdown_freq_flag = false;
}
} else {
dbs_tuners_ins.scaling_fastdown_freq += step;
}
}
// ZZ: adjust scaling responsiveness freq
if (dbs_tuners_ins.scaling_responsiveness_freq != 0) {
if ((dbs_tuners_ins.scaling_responsiveness_freq + step < pol_min
|| dbs_tuners_ins.scaling_responsiveness_freq + step > pol_max)
&& !temp_scaling_responsiveness_freq_flag) {
temp_scaling_responsiveness_freq = dbs_tuners_ins.scaling_responsiveness_freq + step;
temp_scaling_responsiveness_freq_flag = true;
} else if (temp_scaling_responsiveness_freq_flag) {
if (temp_scaling_responsiveness_freq + step < pol_min
|| temp_scaling_responsiveness_freq + step > pol_max) {
temp_scaling_responsiveness_freq = temp_scaling_responsiveness_freq + step;
} else {
dbs_tuners_ins.scaling_responsiveness_freq = temp_scaling_responsiveness_freq + step;
temp_scaling_responsiveness_freq = 0;
temp_scaling_responsiveness_freq_flag = false;
}
} else {
dbs_tuners_ins.scaling_responsiveness_freq += step;
}
}
#ifdef ENABLE_MUSIC_LIMITS
// ZZ: adjust music min freq
if (dbs_tuners_ins.music_min_freq != 0) {
if ((dbs_tuners_ins.music_min_freq + step < pol_min
|| dbs_tuners_ins.music_min_freq + step > pol_max)
&& !temp_music_min_freq_flag) {
temp_music_min_freq = dbs_tuners_ins.music_min_freq + step;
temp_music_min_freq_flag = true;
} else if (temp_music_min_freq_flag) {
if (temp_music_min_freq + step < pol_min
|| temp_music_min_freq + step > pol_max) {
temp_music_min_freq = temp_music_min_freq + step;
} else {
dbs_tuners_ins.music_min_freq = temp_music_min_freq + step;
temp_music_min_freq = 0;
temp_music_min_freq = false;
}
} else {
dbs_tuners_ins.music_min_freq += step;
}
}
// ZZ: adjust music max freq
if (dbs_tuners_ins.music_max_freq != 0) {
if ((dbs_tuners_ins.music_max_freq + step < pol_min
|| dbs_tuners_ins.music_max_freq + step > pol_max)
&& !temp_music_max_freq_flag) {
temp_music_max_freq = dbs_tuners_ins.music_max_freq + step;
temp_music_max_freq_flag = true;
} else if (temp_music_max_freq_flag) {
if (temp_music_max_freq + step < pol_min
|| temp_music_max_freq + step > pol_max) {
temp_music_max_freq = temp_music_max_freq + step;
} else {
dbs_tuners_ins.music_max_freq = temp_music_max_freq + step;
temp_music_max_freq = 0;
temp_music_max_freq = false;
}
} else {
dbs_tuners_ins.music_max_freq += step;
}
}
#endif /* ENABLE_MUSIC_LIMITS */
#ifdef ENABLE_HOTPLUGGING
// ZZ: adjust up threshold hotplug freq1
if (dbs_tuners_ins.up_threshold_hotplug_freq1 != 0) {
if ((dbs_tuners_ins.up_threshold_hotplug_freq1 + step < pol_min
|| dbs_tuners_ins.up_threshold_hotplug_freq1 + step > pol_max)
&& !temp_up_threshold_hotplug_freq1_flag) {
temp_up_threshold_hotplug_freq1 = dbs_tuners_ins.up_threshold_hotplug_freq1 + step;
temp_up_threshold_hotplug_freq1_flag = true;
} else if (temp_up_threshold_hotplug_freq1_flag) {
if (temp_up_threshold_hotplug_freq1 + step < pol_min
|| temp_up_threshold_hotplug_freq1 + step > pol_max) {
temp_up_threshold_hotplug_freq1 = temp_up_threshold_hotplug_freq1 + step;
} else {
dbs_tuners_ins.up_threshold_hotplug_freq1 = temp_up_threshold_hotplug_freq1 + step;
temp_up_threshold_hotplug_freq1 = 0;
temp_up_threshold_hotplug_freq1_flag = false;
}
} else {
dbs_tuners_ins.up_threshold_hotplug_freq1 += step;
}
}
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
// ZZ: adjust up threshold hotplug freq2
if (dbs_tuners_ins.up_threshold_hotplug_freq2 != 0) {
if ((dbs_tuners_ins.up_threshold_hotplug_freq2 + step < pol_min
|| dbs_tuners_ins.up_threshold_hotplug_freq2 + step > pol_max)
&& !temp_up_threshold_hotplug_freq2_flag) {
temp_up_threshold_hotplug_freq2 = dbs_tuners_ins.up_threshold_hotplug_freq2 + step;
temp_up_threshold_hotplug_freq2_flag = true;
} else if (temp_up_threshold_hotplug_freq2_flag) {
if (temp_up_threshold_hotplug_freq2 + step < pol_min
|| temp_up_threshold_hotplug_freq2 + step > pol_max) {
temp_up_threshold_hotplug_freq2 = temp_up_threshold_hotplug_freq2 + step;
} else {
dbs_tuners_ins.up_threshold_hotplug_freq2 = temp_up_threshold_hotplug_freq2 + step;
temp_up_threshold_hotplug_freq2 = 0;
temp_up_threshold_hotplug_freq2_flag = false;
}
} else {
dbs_tuners_ins.up_threshold_hotplug_freq2 += step;
}
}
// ZZ: adjust up threshold hotplug freq3
if (dbs_tuners_ins.up_threshold_hotplug_freq3 != 0) {
if ((dbs_tuners_ins.up_threshold_hotplug_freq3 + step < pol_min
|| dbs_tuners_ins.up_threshold_hotplug_freq3 + step > pol_max)
&& !temp_up_threshold_hotplug_freq3_flag) {
temp_up_threshold_hotplug_freq3 = dbs_tuners_ins.up_threshold_hotplug_freq3 + step;
temp_up_threshold_hotplug_freq3_flag = true;
} else if (temp_up_threshold_hotplug_freq3_flag) {
if (temp_up_threshold_hotplug_freq3 + step < pol_min
|| temp_up_threshold_hotplug_freq3 + step > pol_max) {
temp_up_threshold_hotplug_freq3 = temp_up_threshold_hotplug_freq3 + step;
} else {
dbs_tuners_ins.up_threshold_hotplug_freq3 = temp_up_threshold_hotplug_freq3 + step;
temp_up_threshold_hotplug_freq3 = 0;
temp_up_threshold_hotplug_freq3_flag = false;
}
} else {
dbs_tuners_ins.up_threshold_hotplug_freq3 += step;
}
}
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
// ZZ: adjust up threshold hotplug freq4
if (dbs_tuners_ins.up_threshold_hotplug_freq4 != 0) {
if ((dbs_tuners_ins.up_threshold_hotplug_freq4 + step < pol_min
|| dbs_tuners_ins.up_threshold_hotplug_freq4 + step > pol_max)
&& !temp_up_threshold_hotplug_freq4_flag) {
temp_up_threshold_hotplug_freq4 = dbs_tuners_ins.up_threshold_hotplug_freq4 + step;
temp_up_threshold_hotplug_freq4_flag = true;
} else if (!temp_up_threshold_hotplug_freq4) {
if (temp_up_threshold_hotplug_freq4 + step < pol_min
|| temp_up_threshold_hotplug_freq4 + step > pol_max) {
temp_up_threshold_hotplug_freq4 = temp_up_threshold_hotplug_freq4 + step;
} else {
dbs_tuners_ins.up_threshold_hotplug_freq4 = temp_up_threshold_hotplug_freq4 + step;
temp_up_threshold_hotplug_freq4 = 0;
temp_up_threshold_hotplug_freq4_flag = false;
}
} else {
dbs_tuners_ins.up_threshold_hotplug_freq4 += step;
}
}
// ZZ: adjust up threshold hotplug freq5
if (dbs_tuners_ins.up_threshold_hotplug_freq5 != 0) {
if ((dbs_tuners_ins.up_threshold_hotplug_freq5 + step < pol_min
|| dbs_tuners_ins.up_threshold_hotplug_freq5 + step > pol_max)
&& !temp_up_threshold_hotplug_freq5_flag) {
temp_up_threshold_hotplug_freq5 = dbs_tuners_ins.up_threshold_hotplug_freq5 + step;
temp_up_threshold_hotplug_freq5_flag = true;
} else if (temp_up_threshold_hotplug_freq5_flag) {
if (temp_up_threshold_hotplug_freq5 + step < pol_min
|| temp_up_threshold_hotplug_freq5 + step > pol_max) {
temp_up_threshold_hotplug_freq5 = temp_up_threshold_hotplug_freq5 + step;
} else {
dbs_tuners_ins.up_threshold_hotplug_freq5 = temp_up_threshold_hotplug_freq5 + step;
temp_up_threshold_hotplug_freq5 = 0;
temp_up_threshold_hotplug_freq5_flag = false;
}
} else {
dbs_tuners_ins.up_threshold_hotplug_freq5 += step;
}
}
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
// ZZ: adjust up threshold hotplug freq6
if (dbs_tuners_ins.up_threshold_hotplug_freq6 != 0) {
if ((dbs_tuners_ins.up_threshold_hotplug_freq6 + step < pol_min
|| dbs_tuners_ins.up_threshold_hotplug_freq6 + step > pol_max)
&& !temp_up_threshold_hotplug_freq6_flag) {
temp_up_threshold_hotplug_freq6 = dbs_tuners_ins.up_threshold_hotplug_freq6 + step;
temp_up_threshold_hotplug_freq6_flag = true;
} else if (temp_up_threshold_hotplug_freq6_flag) {
if (temp_up_threshold_hotplug_freq6 + step < pol_min
|| temp_up_threshold_hotplug_freq6 + step > pol_max) {
temp_up_threshold_hotplug_freq6 = temp_up_threshold_hotplug_freq6 + step;
} else {
dbs_tuners_ins.up_threshold_hotplug_freq6 = temp_up_threshold_hotplug_freq6 + step;
temp_up_threshold_hotplug_freq6 = 0;
temp_up_threshold_hotplug_freq6_flag = false;
}
} else {
dbs_tuners_ins.up_threshold_hotplug_freq6 += step;
}
}
// ZZ: adjust up threshold hotplug freq7
if (dbs_tuners_ins.up_threshold_hotplug_freq7 != 0) {
if ((dbs_tuners_ins.up_threshold_hotplug_freq7 + step < pol_min
|| dbs_tuners_ins.up_threshold_hotplug_freq7 + step > pol_max)
&& !temp_up_threshold_hotplug_freq7_flag) {
temp_up_threshold_hotplug_freq7 = dbs_tuners_ins.up_threshold_hotplug_freq7 + step;
temp_up_threshold_hotplug_freq7_flag = true;
} else if (temp_up_threshold_hotplug_freq7_flag) {
if (temp_up_threshold_hotplug_freq7 + step < pol_min
|| temp_up_threshold_hotplug_freq7 + step > pol_max) {
temp_up_threshold_hotplug_freq7 = temp_up_threshold_hotplug_freq7 + step;
} else {
dbs_tuners_ins.up_threshold_hotplug_freq7 = temp_up_threshold_hotplug_freq7 + step;
temp_up_threshold_hotplug_freq7 = 0;
temp_up_threshold_hotplug_freq7_flag = false;
}
} else {
dbs_tuners_ins.up_threshold_hotplug_freq7 += step;
}
}
#endif /* (MAX_CORES == 8) */
// ZZ: adjust down threshold hotplug freq1
if (dbs_tuners_ins.down_threshold_hotplug_freq1 != 0) {
if ((dbs_tuners_ins.down_threshold_hotplug_freq1 + step < pol_min
|| dbs_tuners_ins.down_threshold_hotplug_freq1 + step > pol_max)
&& !temp_down_threshold_hotplug_freq1_flag) {
temp_down_threshold_hotplug_freq1 = dbs_tuners_ins.down_threshold_hotplug_freq1 + step;
temp_down_threshold_hotplug_freq1_flag = true;
} else if (temp_down_threshold_hotplug_freq1_flag) {
if (temp_down_threshold_hotplug_freq1 + step < pol_min
|| temp_down_threshold_hotplug_freq1 + step > pol_max) {
temp_down_threshold_hotplug_freq1 = temp_down_threshold_hotplug_freq1 + step;
} else {
dbs_tuners_ins.down_threshold_hotplug_freq1 = temp_down_threshold_hotplug_freq1 + step;
temp_down_threshold_hotplug_freq1 = 0;
temp_down_threshold_hotplug_freq1_flag = false;
}
} else {
dbs_tuners_ins.down_threshold_hotplug_freq1 += step;
}
}
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
// ZZ: adjust down threshold hotplug freq2
if (dbs_tuners_ins.down_threshold_hotplug_freq2 != 0) {
if ((dbs_tuners_ins.down_threshold_hotplug_freq2 + step < pol_min
|| dbs_tuners_ins.down_threshold_hotplug_freq2 + step > pol_max)
&& !temp_down_threshold_hotplug_freq2_flag) {
temp_down_threshold_hotplug_freq2 = dbs_tuners_ins.down_threshold_hotplug_freq2 + step;
temp_down_threshold_hotplug_freq2_flag = true;
} else if (temp_down_threshold_hotplug_freq2_flag) {
if (temp_down_threshold_hotplug_freq2 + step < pol_min
|| temp_down_threshold_hotplug_freq2 + step > pol_max) {
temp_down_threshold_hotplug_freq2 = temp_down_threshold_hotplug_freq2 + step;
} else {
dbs_tuners_ins.down_threshold_hotplug_freq2 = temp_down_threshold_hotplug_freq2 + step;
temp_down_threshold_hotplug_freq2 = 0;
temp_down_threshold_hotplug_freq2_flag = false;
}
} else {
dbs_tuners_ins.down_threshold_hotplug_freq2 += step;
}
}
// ZZ: adjust down threshold hotplug freq3
if (dbs_tuners_ins.down_threshold_hotplug_freq3 != 0) {
if ((dbs_tuners_ins.down_threshold_hotplug_freq3 + step < pol_min
|| dbs_tuners_ins.down_threshold_hotplug_freq3 + step > pol_max)
&& !temp_down_threshold_hotplug_freq3_flag) {
temp_down_threshold_hotplug_freq3 = dbs_tuners_ins.down_threshold_hotplug_freq3 + step;
temp_down_threshold_hotplug_freq3_flag = true;
} else if (temp_down_threshold_hotplug_freq3_flag) {
if (temp_down_threshold_hotplug_freq3 + step < pol_min
|| temp_down_threshold_hotplug_freq3 + step > pol_max) {
temp_down_threshold_hotplug_freq3 = temp_down_threshold_hotplug_freq3 + step;
} else {
dbs_tuners_ins.down_threshold_hotplug_freq3 = temp_down_threshold_hotplug_freq3 + step;
temp_down_threshold_hotplug_freq3 = 0;
temp_down_threshold_hotplug_freq3_flag = false;
}
} else {
dbs_tuners_ins.down_threshold_hotplug_freq3 += step;
}
}
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
// ZZ: adjust down threshold hotplug freq4
if (dbs_tuners_ins.down_threshold_hotplug_freq4 != 0) {
if ((dbs_tuners_ins.down_threshold_hotplug_freq4 + step < pol_min
|| dbs_tuners_ins.down_threshold_hotplug_freq4 + step > pol_max)
&& !temp_down_threshold_hotplug_freq4_flag) {
temp_down_threshold_hotplug_freq4 = dbs_tuners_ins.down_threshold_hotplug_freq4 + step;
temp_down_threshold_hotplug_freq4_flag = true;
} else if (temp_down_threshold_hotplug_freq4_flag) {
if (temp_down_threshold_hotplug_freq4 + step < pol_min
|| temp_down_threshold_hotplug_freq4 + step > pol_max) {
temp_down_threshold_hotplug_freq4 = temp_down_threshold_hotplug_freq4 + step;
} else {
dbs_tuners_ins.down_threshold_hotplug_freq4 = temp_down_threshold_hotplug_freq4 + step;
temp_down_threshold_hotplug_freq4 = 0;
temp_down_threshold_hotplug_freq4_flag = false;
}
} else {
dbs_tuners_ins.down_threshold_hotplug_freq4 += step;
}
}
// ZZ: adjust down threshold hotplug freq5
if (dbs_tuners_ins.down_threshold_hotplug_freq5 != 0) {
if ((dbs_tuners_ins.down_threshold_hotplug_freq5 + step < pol_min
|| dbs_tuners_ins.down_threshold_hotplug_freq5 + step > pol_max)
&& !temp_down_threshold_hotplug_freq5_flag) {
temp_down_threshold_hotplug_freq5 = dbs_tuners_ins.down_threshold_hotplug_freq5 + step;
temp_down_threshold_hotplug_freq5_flag = true;
} else if (temp_down_threshold_hotplug_freq5_flag) {
if (temp_down_threshold_hotplug_freq5 + step < pol_min
|| temp_down_threshold_hotplug_freq5 + step > pol_max) {
temp_down_threshold_hotplug_freq5 = temp_down_threshold_hotplug_freq5 + step;
} else {
dbs_tuners_ins.down_threshold_hotplug_freq5 = temp_down_threshold_hotplug_freq5 + step;
temp_down_threshold_hotplug_freq5 = 0;
temp_down_threshold_hotplug_freq5_flag = false;
}
} else {
dbs_tuners_ins.down_threshold_hotplug_freq5 += step;
}
}
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
// ZZ: adjust down threshold hotplug freq6
if (dbs_tuners_ins.down_threshold_hotplug_freq6 != 0) {
if ((dbs_tuners_ins.down_threshold_hotplug_freq6 + step < pol_min
|| dbs_tuners_ins.down_threshold_hotplug_freq6 + step > pol_max)
&& !temp_down_threshold_hotplug_freq6_flag) {
temp_down_threshold_hotplug_freq6 = dbs_tuners_ins.down_threshold_hotplug_freq6 + step;
temp_down_threshold_hotplug_freq6_flag = true;
} else if (temp_down_threshold_hotplug_freq6_flag) {
if (temp_down_threshold_hotplug_freq6 + step < pol_min
|| temp_down_threshold_hotplug_freq6 + step > pol_max) {
temp_down_threshold_hotplug_freq6 = temp_down_threshold_hotplug_freq6 + step;
} else {
dbs_tuners_ins.down_threshold_hotplug_freq6 = temp_down_threshold_hotplug_freq6 + step;
temp_down_threshold_hotplug_freq6 = 0;
temp_down_threshold_hotplug_freq6_flag = false;
}
} else {
dbs_tuners_ins.down_threshold_hotplug_freq6 += step;
}
}
// ZZ: adjust down threshold hotplug freq7
if (dbs_tuners_ins.down_threshold_hotplug_freq7 != 0) {
if ((dbs_tuners_ins.down_threshold_hotplug_freq7 + step < pol_min
|| dbs_tuners_ins.down_threshold_hotplug_freq7 + step > pol_max)
&& !temp_down_threshold_hotplug_freq7_flag) {
temp_down_threshold_hotplug_freq7 = dbs_tuners_ins.down_threshold_hotplug_freq7 + step;
temp_down_threshold_hotplug_freq7_flag = true;
} else if (temp_down_threshold_hotplug_freq7_flag) {
if (temp_down_threshold_hotplug_freq7 + step < pol_min
|| temp_down_threshold_hotplug_freq7 + step > pol_max) {
temp_down_threshold_hotplug_freq7 = temp_down_threshold_hotplug_freq7 + step;
} else {
dbs_tuners_ins.down_threshold_hotplug_freq7 = temp_down_threshold_hotplug_freq7 + step;
temp_down_threshold_hotplug_freq7 = 0;
temp_down_threshold_hotplug_freq7_flag = false;
}
} else {
dbs_tuners_ins.down_threshold_hotplug_freq7 += step;
}
}
#endif /* (MAX_CORES == 8) */
#endif /* ENABLE_HOTPLUGGING */
}
#ifdef ENABLE_HOTPLUGGING
/*
* ZZ: check if maximal/min freq is lower/higher than any hotplug freq thresholds,
* if so mark the affected freq threshold as out of range via a flag and fall back
* to the corresponding load threshold - this keeps hotplugging working properly
*/
if (unlikely(pol_max < dbs_tuners_ins.up_threshold_hotplug_freq1
|| dbs_tuners_ins.freq_limit < dbs_tuners_ins.up_threshold_hotplug_freq1
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
|| dbs_tuners_ins.freq_limit_sleep < dbs_tuners_ins.up_threshold_hotplug_freq1
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_MUSIC_LIMITS
|| dbs_tuners_ins.music_max_freq < dbs_tuners_ins.up_threshold_hotplug_freq1
|| dbs_tuners_ins.music_min_freq > dbs_tuners_ins.up_threshold_hotplug_freq1)) {
#else
)) {
#endif /* ENABLE_MUSIC_LIMITS */
hotplug_freq_threshold_out_of_range[0][0] = 1;
} else {
hotplug_freq_threshold_out_of_range[0][0] = 0;
}
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
if (unlikely(pol_max < dbs_tuners_ins.up_threshold_hotplug_freq2
|| dbs_tuners_ins.freq_limit < dbs_tuners_ins.up_threshold_hotplug_freq2
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
|| dbs_tuners_ins.freq_limit_sleep < dbs_tuners_ins.up_threshold_hotplug_freq2
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND) */
#ifdef ENABLE_MUSIC_LIMITS
|| dbs_tuners_ins.music_max_freq < dbs_tuners_ins.up_threshold_hotplug_freq2
|| dbs_tuners_ins.music_min_freq > dbs_tuners_ins.up_threshold_hotplug_freq2)) {
#else
)) {
#endif /* ENABLE_MUSIC_LIMITS */
hotplug_freq_threshold_out_of_range[0][1] = 1;
} else {
hotplug_freq_threshold_out_of_range[0][1] = 0;
}
if (unlikely(pol_max < dbs_tuners_ins.up_threshold_hotplug_freq3
|| dbs_tuners_ins.freq_limit < dbs_tuners_ins.up_threshold_hotplug_freq3
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
|| dbs_tuners_ins.freq_limit_sleep < dbs_tuners_ins.up_threshold_hotplug_freq3
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_MUSIC_LIMITS
|| dbs_tuners_ins.music_max_freq < dbs_tuners_ins.up_threshold_hotplug_freq3
|| dbs_tuners_ins.music_min_freq > dbs_tuners_ins.up_threshold_hotplug_freq3)) {
#else
)) {
#endif /* ENABLE_MUSIC_LIMITS */
hotplug_freq_threshold_out_of_range[0][2] = 1;
} else {
hotplug_freq_threshold_out_of_range[0][2] = 0;
}
#endif /* (MAX_CORES == 4 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
if (unlikely(pol_max < dbs_tuners_ins.up_threshold_hotplug_freq4
|| dbs_tuners_ins.freq_limit < dbs_tuners_ins.up_threshold_hotplug_freq4
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
|| dbs_tuners_ins.freq_limit_sleep < dbs_tuners_ins.up_threshold_hotplug_freq4
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_MUSIC_LIMITS
|| dbs_tuners_ins.music_max_freq < dbs_tuners_ins.up_threshold_hotplug_freq4
|| dbs_tuners_ins.music_min_freq > dbs_tuners_ins.up_threshold_hotplug_freq4)) {
#else
)) {
#endif /* ENABLE_MUSIC_LIMITS */
hotplug_freq_threshold_out_of_range[0][3] = 1;
} else {
hotplug_freq_threshold_out_of_range[0][3] = 0;
}
if (unlikely(pol_max < dbs_tuners_ins.up_threshold_hotplug_freq5
|| dbs_tuners_ins.freq_limit < dbs_tuners_ins.up_threshold_hotplug_freq5
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
|| dbs_tuners_ins.freq_limit_sleep < dbs_tuners_ins.up_threshold_hotplug_freq5
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_MUSIC_LIMITS
|| dbs_tuners_ins.music_max_freq < dbs_tuners_ins.up_threshold_hotplug_freq5
|| dbs_tuners_ins.music_min_freq > dbs_tuners_ins.up_threshold_hotplug_freq5)) {
#else
)) {
#endif /* ENABLE_MUSIC_LIMITS */
hotplug_freq_threshold_out_of_range[0][4] = 1;
} else {
hotplug_freq_threshold_out_of_range[0][4] = 0;
}
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
if (unlikely(pol_max < dbs_tuners_ins.up_threshold_hotplug_freq6
|| dbs_tuners_ins.freq_limit < dbs_tuners_ins.up_threshold_hotplug_freq6
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
|| dbs_tuners_ins.freq_limit_sleep < dbs_tuners_ins.up_threshold_hotplug_freq6
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_MUSIC_LIMITS
|| dbs_tuners_ins.music_max_freq < dbs_tuners_ins.up_threshold_hotplug_freq6
|| dbs_tuners_ins.music_min_freq > dbs_tuners_ins.up_threshold_hotplug_freq6)) {
#else
)) {
#endif /* ENABLE_MUSIC_LIMITS */
hotplug_freq_threshold_out_of_range[0][5] = 1;
} else {
hotplug_freq_threshold_out_of_range[0][5] = 0;
}
if (unlikely(pol_max < dbs_tuners_ins.up_threshold_hotplug_freq7
|| dbs_tuners_ins.freq_limit < dbs_tuners_ins.up_threshold_hotplug_freq7
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
|| dbs_tuners_ins.freq_limit_sleep < dbs_tuners_ins.up_threshold_hotplug_freq7
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_MUSIC_LIMITS
|| dbs_tuners_ins.music_max_freq < dbs_tuners_ins.up_threshold_hotplug_freq7
|| dbs_tuners_ins.music_min_freq > dbs_tuners_ins.up_threshold_hotplug_freq7)) {
#else
)) {
#endif /* ENABLE_MUSIC_LIMITS */
hotplug_freq_threshold_out_of_range[0][6] = 1;
} else {
hotplug_freq_threshold_out_of_range[0][6] = 0;
}
#endif /* (MAX_CORES == 8) */
if (unlikely(pol_max < dbs_tuners_ins.down_threshold_hotplug_freq1
|| dbs_tuners_ins.freq_limit < dbs_tuners_ins.down_threshold_hotplug_freq1
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
|| dbs_tuners_ins.freq_limit_sleep < dbs_tuners_ins.down_threshold_hotplug_freq1
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_MUSIC_LIMITS
|| dbs_tuners_ins.music_max_freq < dbs_tuners_ins.down_threshold_hotplug_freq1
|| dbs_tuners_ins.music_min_freq > dbs_tuners_ins.down_threshold_hotplug_freq1)) {
#else
)) {
#endif /* ENABLE_MUSIC_LIMITS */
hotplug_freq_threshold_out_of_range[1][0] = 1;
} else {
hotplug_freq_threshold_out_of_range[1][0] = 0;
}
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
if (unlikely(pol_max < dbs_tuners_ins.down_threshold_hotplug_freq2
|| dbs_tuners_ins.freq_limit < dbs_tuners_ins.down_threshold_hotplug_freq2
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
|| dbs_tuners_ins.freq_limit_sleep < dbs_tuners_ins.down_threshold_hotplug_freq2
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_MUSIC_LIMITS
|| dbs_tuners_ins.music_max_freq < dbs_tuners_ins.down_threshold_hotplug_freq2
|| dbs_tuners_ins.music_min_freq > dbs_tuners_ins.down_threshold_hotplug_freq2 )) {
#else
)) {
#endif /* ENABLE_MUSIC_LIMITS */
hotplug_freq_threshold_out_of_range[1][1] = 1;
} else {
hotplug_freq_threshold_out_of_range[1][1] = 0;
}
if (unlikely(pol_max < dbs_tuners_ins.down_threshold_hotplug_freq3
|| dbs_tuners_ins.freq_limit < dbs_tuners_ins.down_threshold_hotplug_freq3
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
|| dbs_tuners_ins.freq_limit_sleep < dbs_tuners_ins.down_threshold_hotplug_freq3
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_MUSIC_LIMITS
|| dbs_tuners_ins.music_max_freq < dbs_tuners_ins.down_threshold_hotplug_freq3
|| dbs_tuners_ins.music_min_freq > dbs_tuners_ins.down_threshold_hotplug_freq3)) {
#else
)) {
#endif /* ENABLE_MUSIC_LIMITS */
hotplug_freq_threshold_out_of_range[1][2] = 1;
} else {
hotplug_freq_threshold_out_of_range[1][2] = 0;
}
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
if (unlikely(pol_max < dbs_tuners_ins.down_threshold_hotplug_freq4
|| dbs_tuners_ins.freq_limit < dbs_tuners_ins.down_threshold_hotplug_freq4
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
|| dbs_tuners_ins.freq_limit_sleep < dbs_tuners_ins.down_threshold_hotplug_freq4
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_MUSIC_LIMITS
|| dbs_tuners_ins.music_max_freq < dbs_tuners_ins.down_threshold_hotplug_freq4
|| dbs_tuners_ins.music_min_freq > dbs_tuners_ins.down_threshold_hotplug_freq4)) {
#else
)) {
#endif /* ENABLE_MUSIC_LIMITS */
hotplug_freq_threshold_out_of_range[1][3] = 1;
} else {
hotplug_freq_threshold_out_of_range[1][3] = 0;
}
if (unlikely(pol_max < dbs_tuners_ins.down_threshold_hotplug_freq5
|| dbs_tuners_ins.freq_limit < dbs_tuners_ins.down_threshold_hotplug_freq5
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
|| dbs_tuners_ins.freq_limit_sleep < dbs_tuners_ins.down_threshold_hotplug_freq5
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_MUSIC_LIMITS
|| dbs_tuners_ins.music_max_freq < dbs_tuners_ins.down_threshold_hotplug_freq5
|| dbs_tuners_ins.music_min_freq > dbs_tuners_ins.down_threshold_hotplug_freq5)) {
#else
)) {
#endif /* ENABLE_MUSIC_LIMITS */
hotplug_freq_threshold_out_of_range[1][4] = 1;
} else {
hotplug_freq_threshold_out_of_range[1][4] = 0;
}
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
if (unlikely(pol_max < dbs_tuners_ins.down_threshold_hotplug_freq6
|| dbs_tuners_ins.freq_limit < dbs_tuners_ins.down_threshold_hotplug_freq6
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
|| dbs_tuners_ins.freq_limit_sleep < dbs_tuners_ins.down_threshold_hotplug_freq6
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_MUSIC_LIMITS
|| dbs_tuners_ins.music_max_freq < dbs_tuners_ins.down_threshold_hotplug_freq6
|| dbs_tuners_ins.music_min_freq > dbs_tuners_ins.down_threshold_hotplug_freq6)) {
#else
)) {
#endif /* ENABLE_MUSIC_LIMITS */
hotplug_freq_threshold_out_of_range[1][5] = 1;
} else {
hotplug_freq_threshold_out_of_range[1][5] = 0;
}
if (unlikely(pol_max < dbs_tuners_ins.down_threshold_hotplug_freq7
|| dbs_tuners_ins.freq_limit < dbs_tuners_ins.down_threshold_hotplug_freq7
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
|| dbs_tuners_ins.freq_limit_sleep < dbs_tuners_ins.down_threshold_hotplug_freq7
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_MUSIC_LIMITS
|| dbs_tuners_ins.music_max_freq < dbs_tuners_ins.down_threshold_hotplug_freq7
|| dbs_tuners_ins.music_min_freq > dbs_tuners_ins.down_threshold_hotplug_freq7)) {
#else
)) {
#endif /* ENABLE_MUSIC_LIMITS */
hotplug_freq_threshold_out_of_range[1][6] = 1;
} else {
hotplug_freq_threshold_out_of_range[1][6] = 0;
}
#endif /* (MAX_CORES == 8) */
#endif /* ENABLE_HOTPLUGGING */
}
#endif /* ENABLE_AUTO_ADJUST_FREQ */
// ZZ: compatibility with kernel version lower than 3.4
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,4,0)
static inline u64 get_cpu_idle_time_jiffy(unsigned int cpu, u64 *wall)
{
u64 idle_time;
u64 cur_wall_time;
u64 busy_time;
cur_wall_time = jiffies64_to_cputime64(get_jiffies_64());
busy_time = cputime64_add(kstat_cpu(cpu).cpustat.user,
kstat_cpu(cpu).cpustat.system);
busy_time = cputime64_add(busy_time, kstat_cpu(cpu).cpustat.irq);
busy_time = cputime64_add(busy_time, kstat_cpu(cpu).cpustat.softirq);
busy_time = cputime64_add(busy_time, kstat_cpu(cpu).cpustat.steal);
busy_time = cputime64_add(busy_time, kstat_cpu(cpu).cpustat.nice);
idle_time = cputime64_sub(cur_wall_time, busy_time);
if (wall)
*wall = (u64)jiffies_to_usecs(cur_wall_time);
return (u64)jiffies_to_usecs(idle_time);
}
#endif /* LINUX_VERSION_CODE... */
// ZZ: this function is placed here only from kernel version 3.4 to 3.8
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,4,0) && LINUX_VERSION_CODE < KERNEL_VERSION(3,8,0)
static inline u64 get_cpu_idle_time_jiffy(unsigned int cpu, u64 *wall)
{
u64 idle_time;
u64 cur_wall_time;
u64 busy_time;
cur_wall_time = jiffies64_to_cputime64(get_jiffies_64());
busy_time = kcpustat_cpu(cpu).cpustat[CPUTIME_USER];
busy_time += kcpustat_cpu(cpu).cpustat[CPUTIME_SYSTEM];
busy_time += kcpustat_cpu(cpu).cpustat[CPUTIME_IRQ];
busy_time += kcpustat_cpu(cpu).cpustat[CPUTIME_SOFTIRQ];
busy_time += kcpustat_cpu(cpu).cpustat[CPUTIME_STEAL];
busy_time += kcpustat_cpu(cpu).cpustat[CPUTIME_NICE];
idle_time = cur_wall_time - busy_time;
if (wall)
*wall = jiffies_to_usecs(cur_wall_time);
return jiffies_to_usecs(idle_time);
}
#endif /* LINUX_VERSION_CODE... */
/*
* ZZ: function has been moved out of governor since kernel version 3.8 and finally moved to cpufreq.c in kernel version 3.11
* overruling macro CPU_IDLE_TIME_IN_CPUFREQ included for sources with backported cpufreq implementation
*/
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,8,0) && !defined(CPU_IDLE_TIME_IN_CPUFREQ)
static inline u64 get_cpu_idle_time(unsigned int cpu, u64 *wall)
{
u64 idle_time = get_cpu_idle_time_us(cpu, NULL);
if (idle_time == -1ULL)
return get_cpu_idle_time_jiffy(cpu, wall);
else
idle_time += get_cpu_iowait_time_us(cpu, wall);
return idle_time;
}
#endif /* LINUX_VERSION_CODE... */
// keep track of frequency transitions
static int dbs_cpufreq_notifier(struct notifier_block *nb, unsigned long val, void *data)
{
struct cpufreq_freqs *freq = data;
struct cpu_dbs_info_s *this_dbs_info = &per_cpu(cs_cpu_dbs_info,
freq->cpu);
struct cpufreq_policy *policy;
if (!this_dbs_info->enable)
return 0;
policy = this_dbs_info->cur_policy;
/*
* we only care if our internally tracked freq moves outside
* the 'valid' ranges of frequency available to us otherwise
* we do not change it
*/
if (unlikely(this_dbs_info->requested_freq > policy->max
|| this_dbs_info->requested_freq < policy->min))
this_dbs_info->requested_freq = freq->new;
return 0;
}
static struct notifier_block dbs_cpufreq_notifier_block = {
.notifier_call = dbs_cpufreq_notifier
};
/************************** sysfs interface **************************/
static ssize_t show_sampling_rate_min(struct kobject *kobj, struct attribute *attr, char *buf)
{
return sprintf(buf, "%u\n", min_sampling_rate);
}
define_one_global_ro(sampling_rate_min);
// cpufreq_zzmoove governor tunables
#define show_one(file_name, object) \
static ssize_t show_##file_name \
(struct kobject *kobj, struct attribute *attr, char *buf) \
{ \
return sprintf(buf, "%u\n", dbs_tuners_ins.object); \
}
#ifdef ENABLE_PROFILES_SUPPORT
show_one(profile_number, profile_number); // ZZ: profile number tuneable
show_one(profile_sticky_mode, profile_sticky_mode); // ff: sticky profile mode
#endif /* ENABLE_PROFILES_SUPPORT */
#ifdef ENABLE_AUTO_ADJUST_FREQ
show_one(auto_adjust_freq_thresholds, auto_adjust_freq_thresholds); // ZZ: auto adjust freq thresholds tuneable
#endif /* ENABLE_AUTO_ADJUST_FREQ */
show_one(sampling_rate, sampling_rate); // ZZ: normal sampling rate tuneable
show_one(sampling_rate_current, sampling_rate_current); // ZZ: tuneable for showing the actual sampling rate
show_one(sampling_rate_idle_threshold, sampling_rate_idle_threshold); // ZZ: sampling rate idle threshold tuneable
show_one(sampling_rate_idle, sampling_rate_idle); // ZZ: tuneable for sampling rate at idle
show_one(sampling_rate_idle_delay, sampling_rate_idle_delay); // ZZ: DSR switching delay tuneable
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
show_one(sampling_rate_sleep_multiplier, sampling_rate_sleep_multiplier); // ZZ: sampling rate multiplier tuneable for early suspend
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
show_one(sampling_down_factor, sampling_down_factor); // ZZ: sampling down factor tuneable
show_one(sampling_down_max_momentum, sampling_down_max_mom); // ZZ: sampling down momentum tuneable
show_one(sampling_down_momentum_sensitivity, sampling_down_mom_sens); // ZZ: sampling down momentum sensitivity tuneable
show_one(up_threshold, up_threshold);
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
show_one(up_threshold_sleep, up_threshold_sleep); // ZZ: up threshold sleep tuneable for early suspend
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_HOTPLUGGING
show_one(up_threshold_hotplug1, up_threshold_hotplug1); // ZZ: up threshold hotplug tuneable for core1
show_one(up_threshold_hotplug_freq1, up_threshold_hotplug_freq1); // Yank: up threshold hotplug freq tuneable for core1
show_one(block_up_multiplier_hotplug1, block_up_multiplier_hotplug1); // ff: block up multiplier hotplug1 for core1
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
show_one(up_threshold_hotplug2, up_threshold_hotplug2); // ZZ: up threshold hotplug tuneable for core2
show_one(up_threshold_hotplug_freq2, up_threshold_hotplug_freq2); // Yank: up threshold hotplug freq tuneable for core2
show_one(block_up_multiplier_hotplug2, block_up_multiplier_hotplug2); // ff: block up multiplier hotplug2 for core2
show_one(up_threshold_hotplug3, up_threshold_hotplug3); // ZZ: up threshold hotplug tuneable for core3
show_one(up_threshold_hotplug_freq3, up_threshold_hotplug_freq3); // Yank: up threshold hotplug freq tuneable for core3
show_one(block_up_multiplier_hotplug3, block_up_multiplier_hotplug3); // ff: block up multiplier hotplug3 for core3
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
show_one(up_threshold_hotplug4, up_threshold_hotplug4); // ZZ: up threshold hotplug tuneable for core4
show_one(up_threshold_hotplug_freq4, up_threshold_hotplug_freq4); // Yank: up threshold hotplug freq tuneable for core4
show_one(block_up_multiplier_hotplug4, block_up_multiplier_hotplug4); // ff: block up multiplier hotplug3 for core4
show_one(up_threshold_hotplug5, up_threshold_hotplug5); // ZZ: up threshold hotplug tuneable for core5
show_one(up_threshold_hotplug_freq5, up_threshold_hotplug_freq5); // Yank: up threshold hotplug freq tuneable for core5
show_one(block_up_multiplier_hotplug5, block_up_multiplier_hotplug5); // ff: block up multiplier hotplug3 for core5
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
show_one(up_threshold_hotplug6, up_threshold_hotplug6); // ZZ: up threshold hotplug tuneable for core6
show_one(up_threshold_hotplug_freq6, up_threshold_hotplug_freq6); // Yank: up threshold hotplug freq tuneable for core6
show_one(block_up_multiplier_hotplug6, block_up_multiplier_hotplug6); // ff: block up multiplier hotplug3 for core6
show_one(up_threshold_hotplug7, up_threshold_hotplug7); // ZZ: up threshold hotplug tuneable for core7
show_one(up_threshold_hotplug_freq7, up_threshold_hotplug_freq7); // Yank: up threshold hotplug freq tuneable for core7
show_one(block_up_multiplier_hotplug7, block_up_multiplier_hotplug7); // ff: block up multiplier hotplug3 for core7
#endif /* (MAX_CORES == 8) */
#endif /* ENABLE_HOTPLUGGING */
show_one(down_threshold, down_threshold);
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
show_one(down_threshold_sleep, down_threshold_sleep); // ZZ: down threshold sleep tuneable for early suspend
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_HOTPLUGGING
show_one(down_threshold_hotplug1, down_threshold_hotplug1); // ZZ: down threshold hotplug tuneable for core1
show_one(down_threshold_hotplug_freq1, down_threshold_hotplug_freq1); // Yank: down threshold hotplug freq tuneable for core1
show_one(block_down_multiplier_hotplug1, block_down_multiplier_hotplug1); // ff: block down multiplier hotplug1 for core1
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
show_one(down_threshold_hotplug2, down_threshold_hotplug2); // ZZ: down threshold hotplug tuneable for core2
show_one(down_threshold_hotplug_freq2, down_threshold_hotplug_freq2); // Yank: down threshold hotplug freq tuneable for core2
show_one(block_down_multiplier_hotplug2, block_down_multiplier_hotplug2); // ff: block down multiplier hotplug2 for core 2
show_one(down_threshold_hotplug3, down_threshold_hotplug3); // ZZ: down threshold hotplug tuneable for core3
show_one(down_threshold_hotplug_freq3, down_threshold_hotplug_freq3); // Yank: down threshold hotplug freq tuneable for core3
show_one(block_down_multiplier_hotplug3, block_down_multiplier_hotplug3); // ff: block down multiplier hotplug3 for core3
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
show_one(down_threshold_hotplug4, down_threshold_hotplug4); // ZZ: down threshold hotplug tuneable for core4
show_one(down_threshold_hotplug_freq4, down_threshold_hotplug_freq4); // Yank: down threshold hotplug freq tuneable for core4
show_one(block_down_multiplier_hotplug4, block_down_multiplier_hotplug4); // ff: block down multiplier hotplug1 for core4
show_one(down_threshold_hotplug5, down_threshold_hotplug5); // ZZ: down threshold hotplug tuneable for core5
show_one(down_threshold_hotplug_freq5, down_threshold_hotplug_freq5); // Yank: down threshold hotplug freq tuneable for core5
show_one(block_down_multiplier_hotplug5, block_down_multiplier_hotplug5); // ff: block down multiplier hotplug1 for core5
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
show_one(down_threshold_hotplug6, down_threshold_hotplug6); // ZZ: down threshold hotplug tuneable for core6
show_one(down_threshold_hotplug_freq6, down_threshold_hotplug_freq6); // Yank: down threshold hotplug freq tuneable for core6
show_one(block_down_multiplier_hotplug6, block_down_multiplier_hotplug6); // ff: block down multiplier hotplug1 for core6
show_one(down_threshold_hotplug7, down_threshold_hotplug7); // ZZ: down threshold hotplug tuneable for core7
show_one(down_threshold_hotplug_freq7, down_threshold_hotplug_freq7); // Yank: down threshold hotplug freq tuneable for core7
show_one(block_down_multiplier_hotplug7, block_down_multiplier_hotplug7); // ff: block down multiplier hotplug1 for core7
#endif /* (MAX_CORES == 8) */
#endif /* ENABLE_HOTPLUGGING */
show_one(ignore_nice_load, ignore_nice); // ZZ: ignore nice load tuneable
show_one(smooth_up, smooth_up); // ZZ: smooth up tuneable
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
show_one(smooth_up_sleep, smooth_up_sleep); // ZZ: smooth up sleep tuneable for early suspend
#ifdef ENABLE_HOTPLUGGING
show_one(hotplug_sleep, hotplug_sleep); // ZZ: hotplug sleep tuneable for early suspend
#endif /* ENABLE_HOTPLUGGING */
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
show_one(freq_limit, freq_limit); // ZZ: freq limit tuneable
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
show_one(freq_limit_sleep, freq_limit_sleep); // ZZ: freq limit sleep tuneable for early suspend
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
show_one(fast_scaling_up, fast_scaling_up); // Yank: fast scaling tuneable for upscaling
show_one(fast_scaling_down, fast_scaling_down); // Yank: fast scaling tuneable for downscaling
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
show_one(fast_scaling_sleep_up, fast_scaling_sleep_up); // Yank: fast scaling sleep tuneable for early suspend for upscaling
show_one(fast_scaling_sleep_down, fast_scaling_sleep_down); // Yank: fast scaling sleep tuneable for early suspend for downscaling
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
show_one(afs_threshold1, afs_threshold1); // ZZ: auto fast scaling step one threshold
show_one(afs_threshold2, afs_threshold2); // ZZ: auto fast scaling step two threshold
show_one(afs_threshold3, afs_threshold3); // ZZ: auto fast scaling step three threshold
show_one(afs_threshold4, afs_threshold4); // ZZ: auto fast scaling step four threshold
show_one(grad_up_threshold, grad_up_threshold); // ZZ: early demand tuneable grad up threshold
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
show_one(grad_up_threshold_sleep, grad_up_threshold_sleep); // ZZ: early demand sleep tuneable grad up threshold
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
show_one(early_demand, early_demand); // ZZ: early demand tuneable master switch
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
show_one(early_demand_sleep, early_demand_sleep); // ZZ: early demand sleep tuneable master switch
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_HOTPLUGGING
show_one(disable_hotplug, disable_hotplug); // ZZ: hotplug switch tuneable
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
show_one(disable_hotplug_sleep, disable_hotplug_sleep); // ZZ: hotplug switch tuneable for sleep
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
show_one(hotplug_block_up_cycles, hotplug_block_up_cycles); // ZZ: hotplug up block cycles tuneable
show_one(hotplug_block_down_cycles, hotplug_block_down_cycles); // ZZ: hotplug down block cycles tuneable
show_one(hotplug_stagger_up, hotplug_stagger_up); // ff: hotplug stagger up tuneable
show_one(hotplug_stagger_down, hotplug_stagger_down); // ff: hotplug stagger down tuneable
show_one(hotplug_idle_threshold, hotplug_idle_threshold); // ZZ: hotplug idle threshold tuneable
show_one(hotplug_idle_freq, hotplug_idle_freq); // ZZ: hotplug idle freq tuneable
show_one(hotplug_engage_freq, hotplug_engage_freq); // ZZ: hotplug engage freq tuneable (ffolkes)
show_one(hotplug_max_limit, hotplug_max_limit); // ZZ: hotplug max limit tunable (ffolkes)
show_one(hotplug_min_limit, hotplug_min_limit); // ff: the number of cores we require to be online
show_one(hotplug_lock, hotplug_lock); // ff: the number of cores we require to be online
#endif /* ENABLE_HOTPLUGGING */
show_one(scaling_block_threshold, scaling_block_threshold); // ZZ: scaling block threshold tuneable
show_one(scaling_block_cycles, scaling_block_cycles); // ZZ: scaling block cycles tuneable
show_one(scaling_up_block_cycles, scaling_up_block_cycles); // ff: scaling-up block cycles tuneable
show_one(scaling_up_block_freq, scaling_up_block_freq); // ff: scaling-up block freq threshold tuneable
#ifdef CONFIG_EXYNOS4_EXPORT_TEMP
show_one(scaling_block_temp, scaling_block_temp); // ZZ: scaling block temp tuneable
#endif /* CONFIG_EXYNOS4_EXPORT_TEMP */
#ifdef ENABLE_SNAP_THERMAL_SUPPORT
show_one(scaling_trip_temp, scaling_trip_temp); // ff: snapdragon thermal tripping temperature
#endif /* ENABLE_SNAP_THERMAL_SUPPORT */
show_one(scaling_block_freq, scaling_block_freq); // ZZ: scaling block freq tuneable
show_one(scaling_block_force_down, scaling_block_force_down); // ZZ: scaling block force down tuneable
show_one(scaling_fastdown_freq, scaling_fastdown_freq); // ZZ: scaling fastdown freq tuneable (ffolkes)
show_one(scaling_fastdown_up_threshold, scaling_fastdown_up_threshold); // ZZ: scaling fastdown up threshold tuneable (ffolkes)
show_one(scaling_fastdown_down_threshold, scaling_fastdown_down_threshold); // ZZ: scaling fastdown down threshold tuneable (ffolkes-ZaneZam)
show_one(scaling_responsiveness_freq, scaling_responsiveness_freq); // ZZ: scaling responsiveness freq tuneable (ffolkes)
show_one(scaling_responsiveness_up_threshold, scaling_responsiveness_up_threshold); // ZZ: scaling responsiveness up threshold tuneable (ffolkes)
show_one(scaling_proportional, scaling_proportional); // ZZ: scaling proportional tuneable
#ifdef ENABLE_INPUTBOOSTER
show_one(inputboost_cycles, inputboost_cycles); // ff: inputbooster duration
show_one(inputboost_up_threshold, inputboost_up_threshold); // ff: inputbooster up threshold
show_one(inputboost_punch_cycles, inputboost_punch_cycles); // ff: inputbooster punch cycles
show_one(inputboost_punch_freq, inputboost_punch_freq); // ff: inputbooster punch freq
show_one(inputboost_punch_on_fingerdown, inputboost_punch_on_fingerdown); // ff: inputbooster punch on finger down
show_one(inputboost_punch_on_fingermove, inputboost_punch_on_fingermove); // ff: inputbooster punch on finger move
show_one(inputboost_punch_on_epenmove, inputboost_punch_on_epenmove); // ff: inputbooster punch on epen move
show_one(inputboost_typingbooster_up_threshold, inputboost_typingbooster_up_threshold); // ff: typingbooster up threshold
show_one(inputboost_typingbooster_cores, inputboost_typingbooster_cores); // ff: typingbooster boost cores
#endif /* ENABLE_INPUTBOOSTER */
#ifdef ENABLE_MUSIC_LIMITS
show_one(music_max_freq, music_max_freq); // ff: music max frequency
show_one(music_min_freq, music_min_freq); // ff: music min frequency
#ifdef ENABLE_HOTPLUGGING
show_one(music_min_cores, music_min_cores); // ZZ: music min online cores
#endif /* ENABLE_HOTPLUGGING */
show_one(music_state, music_state); // ff: music state
#endif /* ENABLE_MUSIC_LIMITS */
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: tuneable for showing the currently active governor settings profile
static ssize_t show_profile(struct kobject *kobj, struct attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", dbs_tuners_ins.profile);
}
#endif /* ENABLE_PROFILES_SUPPORT */
// ZZ: tuneable -> possible values: 0 (disable) to MAX_SAMPLING_DOWN_FACTOR, if not set default is 0
static ssize_t store_sampling_down_max_momentum(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input, j;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > MAX_SAMPLING_DOWN_FACTOR -
dbs_tuners_ins.sampling_down_factor || input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.sampling_down_max_mom != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.sampling_down_max_mom = zz_sampling_down_max_mom = input;
orig_sampling_down_max_mom = dbs_tuners_ins.sampling_down_max_mom;
// ZZ: reset sampling down factor to default if momentum was disabled
if (dbs_tuners_ins.sampling_down_max_mom == 0)
zz_sampling_down_factor = DEF_SAMPLING_DOWN_FACTOR;
// ZZ: reset momentum_adder and reset down sampling multiplier in case momentum was disabled
for_each_online_cpu(j) {
struct cpu_dbs_info_s *dbs_info;
dbs_info = &per_cpu(cs_cpu_dbs_info, j);
dbs_info->momentum_adder = 0;
if (dbs_tuners_ins.sampling_down_max_mom == 0)
dbs_info->rate_mult = 1;
}
return count;
}
// ZZ: tuneable -> possible values: 1 to MAX_SAMPLING_DOWN_MOMENTUM_SENSITIVITY, if not set default is 50
static ssize_t store_sampling_down_momentum_sensitivity(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input, j;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > MAX_SAMPLING_DOWN_MOMENTUM_SENSITIVITY
|| input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
// ff: do this so synapse can set 0.
if (!input)
input = 1;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.sampling_down_mom_sens != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.sampling_down_mom_sens = input;
// ZZ: reset momentum_adder
for_each_online_cpu(j) {
struct cpu_dbs_info_s *dbs_info;
dbs_info = &per_cpu(cs_cpu_dbs_info, j);
dbs_info->momentum_adder = 0;
}
return count;
}
/*
* ZZ: tunable for sampling down factor (reactivated function) added reset loop for momentum functionality
* -> possible values: 1 (disabled) to MAX_SAMPLING_DOWN_FACTOR, if not set default is 1
*/
static ssize_t store_sampling_down_factor(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input, j;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > MAX_SAMPLING_DOWN_FACTOR
|| input < 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.sampling_down_factor != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.sampling_down_factor = zz_sampling_down_factor = input;
// ZZ: reset down sampling multiplier in case it was active
for_each_online_cpu(j) {
struct cpu_dbs_info_s *dbs_info;
dbs_info = &per_cpu(cs_cpu_dbs_info, j);
dbs_info->rate_mult = 1;
}
return count;
}
static ssize_t store_sampling_rate(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.sampling_rate != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.sampling_rate = dbs_tuners_ins.sampling_rate_current
= max(input, min_sampling_rate); // ZZ: set it to new value
return count;
}
/*
* ZZ: tuneable -> possible values: 0 disable whole functionality and same as 'sampling_rate' any value
* above min_sampling_rate, if not set default is 180000
*/
static ssize_t store_sampling_rate_idle(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.sampling_rate_idle != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
if (input == 0)
dbs_tuners_ins.sampling_rate_current = dbs_tuners_ins.sampling_rate_idle
= dbs_tuners_ins.sampling_rate; // ZZ: set current and idle rate to normal = disable feature
else
dbs_tuners_ins.sampling_rate_idle = max(input, min_sampling_rate); // ZZ: set idle rate to new value
return count;
}
// ZZ: tuneable -> possible values: 0 disable threshold, any value under 100, if not set default is 0
static ssize_t store_sampling_rate_idle_threshold(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > 100
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.sampling_rate_idle_threshold != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.sampling_rate_idle_threshold = input;
return count;
}
// ZZ: tuneable -> possible values: 0 to disable, any value above 0 to enable, if not set default is 0
static ssize_t store_sampling_rate_idle_delay(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
if (input == 0)
sampling_rate_step_up_delay = 0;
sampling_rate_step_down_delay = 0;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.sampling_rate_idle_delay != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.sampling_rate_idle_delay = input;
return count;
}
// ZZ: tuneable -> possible values: 1 to 8, if not set default is 2
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
static ssize_t store_sampling_rate_sleep_multiplier(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > MAX_SAMPLING_RATE_SLEEP_MULTIPLIER || input < 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.sampling_rate_sleep_multiplier != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.sampling_rate_sleep_multiplier = input;
return count;
}
#endif /* ENABLE_PROFILES_SUPPORT */
static ssize_t store_up_threshold(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > 100
|| input <= dbs_tuners_ins.down_threshold
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.up_threshold != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.up_threshold = input;
return count;
}
// ZZ: tuneable -> possible values: range from above down_threshold_sleep value up to 100, if not set default is 90
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
static ssize_t store_up_threshold_sleep(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > 100
|| input <= dbs_tuners_ins.down_threshold_sleep
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.up_threshold_sleep != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.up_threshold_sleep = input;
return count;
}
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_HOTPLUGGING
#ifdef ENABLE_PROFILES_SUPPORT
// ff: tuneable -> possible values: range from 0 up to 25, if not set default is 1 (disabled)
#define store_block_up_multiplier_hotplug(name) \
static ssize_t store_block_up_multiplier_hotplug##name \
(struct kobject *a, struct attribute *b, const char *buf, size_t count) \
{ \
unsigned int input; \
int ret; \
ret = sscanf(buf, "%u", &input); \
\
if (ret != 1 || input < 0 || input > 25 || set_profile_active == true) \
return -EINVAL; \
\
if (!dbs_tuners_ins.profile_sticky_mode \
&& dbs_tuners_ins.profile_number != 0 \
&& dbs_tuners_ins.block_up_multiplier_hotplug##name != input) { \
dbs_tuners_ins.profile_number = 0; \
strncpy(dbs_tuners_ins.profile, custom_profile, \
sizeof(dbs_tuners_ins.profile)); \
} \
dbs_tuners_ins.block_up_multiplier_hotplug##name = input; \
\
return count; \
} \
#define store_block_down_multiplier_hotplug(name) \
static ssize_t store_block_down_multiplier_hotplug##name \
(struct kobject *a, struct attribute *b, const char *buf, size_t count) \
{ \
unsigned int input; \
int ret; \
ret = sscanf(buf, "%u", &input); \
\
if (ret != 1 || input < 0 || input > 25 || set_profile_active == true) \
return -EINVAL; \
\
if (!dbs_tuners_ins.profile_sticky_mode \
&& dbs_tuners_ins.profile_number != 0 \
&& dbs_tuners_ins.block_down_multiplier_hotplug##name != input) { \
dbs_tuners_ins.profile_number = 0; \
strncpy(dbs_tuners_ins.profile, custom_profile, \
sizeof(dbs_tuners_ins.profile)); \
} \
dbs_tuners_ins.block_down_multiplier_hotplug##name = input; \
\
return count; \
} \
// Yank: also use definitions for other hotplug tunables
#define store_up_threshold_hotplug(name,core) \
static ssize_t store_up_threshold_hotplug##name \
(struct kobject *a, struct attribute *b, const char *buf, size_t count) \
{ \
unsigned int input; \
int ret; \
ret = sscanf(buf, "%u", &input); \
\
if (ret != 1 || input < 0 || input > 100 || set_profile_active == true) \
return -EINVAL; \
\
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 \
&& dbs_tuners_ins.up_threshold_hotplug##name != input) { \
dbs_tuners_ins.profile_number = 0; \
strncpy(dbs_tuners_ins.profile, custom_profile, \
sizeof(dbs_tuners_ins.profile)); \
} \
\
dbs_tuners_ins.up_threshold_hotplug##name = input; \
hotplug_thresholds[0][core] = input; \
\
return count; \
} \
#define store_down_threshold_hotplug(name,core) \
static ssize_t store_down_threshold_hotplug##name \
(struct kobject *a, struct attribute *b, const char *buf, size_t count) \
{ \
unsigned int input; \
int ret; \
ret = sscanf(buf, "%u", &input); \
\
if (ret != 1 || input < 1 || input > 100 || set_profile_active == true) \
return -EINVAL; \
\
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 \
&& dbs_tuners_ins.down_threshold_hotplug##name != input) { \
dbs_tuners_ins.profile_number = 0; \
strncpy(dbs_tuners_ins.profile, custom_profile, \
sizeof(dbs_tuners_ins.profile)); \
} \
\
dbs_tuners_ins.down_threshold_hotplug##name = input; \
hotplug_thresholds[1][core] = input; \
\
return count; \
} \
/*
* ZZ: tuneables -> possible values: 0 to disable core (only in up thresholds), range from appropriate
* down threshold value up to 100, if not set default for up threshold is 68 and for down threshold is 55
*/
store_up_threshold_hotplug(1,0);
store_down_threshold_hotplug(1,0);
store_block_up_multiplier_hotplug(1);
store_block_down_multiplier_hotplug(1);
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
store_up_threshold_hotplug(2,1);
store_down_threshold_hotplug(2,1);
store_block_up_multiplier_hotplug(2);
store_block_down_multiplier_hotplug(2);
store_up_threshold_hotplug(3,2);
store_down_threshold_hotplug(3,2);
store_block_up_multiplier_hotplug(3);
store_block_down_multiplier_hotplug(3);
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
store_up_threshold_hotplug(4,3);
store_down_threshold_hotplug(4,3);
store_block_up_multiplier_hotplug(4);
store_block_down_multiplier_hotplug(4);
store_up_threshold_hotplug(5,4);
store_down_threshold_hotplug(5,4);
store_block_up_multiplier_hotplug(5);
store_block_down_multiplier_hotplug(5);
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
store_up_threshold_hotplug(6,5);
store_down_threshold_hotplug(6,5);
store_block_up_multiplier_hotplug(6);
store_block_down_multiplier_hotplug(6);
store_up_threshold_hotplug(7,6);
store_down_threshold_hotplug(7,6);
store_block_up_multiplier_hotplug(7);
store_block_down_multiplier_hotplug(7);
#endif /* (MAX_CORES == 8) */
#endif /* ENABLE_PROFILES_SUPPORT */
#ifndef ENABLE_PROFILES_SUPPORT
// ff: tuneable -> possible values: range from 0 up to 25, if not set default is 1 (disabled)
#define store_block_up_multiplier_hotplug(name) \
static ssize_t store_block_up_multiplier_hotplug##name \
(struct kobject *a, struct attribute *b, const char *buf, size_t count) \
{ \
unsigned int input; \
int ret; \
ret = sscanf(buf, "%u", &input); \
\
if (ret != 1 || input < 0 || input > 25) \
return -EINVAL; \
\
dbs_tuners_ins.block_up_multiplier_hotplug##name = input; \
\
return count; \
} \
#define store_block_down_multiplier_hotplug(name) \
static ssize_t store_block_down_multiplier_hotplug##name \
(struct kobject *a, struct attribute *b, const char *buf, size_t count) \
{ \
unsigned int input; \
int ret; \
ret = sscanf(buf, "%u", &input); \
\
if (ret != 1 || input < 0 || input > 25) \
return -EINVAL; \
\
dbs_tuners_ins.block_down_multiplier_hotplug##name = input; \
\
return count; \
} \
// Yank: also use definitions for other hotplug tunables
#define store_up_threshold_hotplug(name,core) \
static ssize_t store_up_threshold_hotplug##name \
(struct kobject *a, struct attribute *b, const char *buf, size_t count) \
{ \
unsigned int input; \
int ret; \
ret = sscanf(buf, "%u", &input); \
\
if (ret != 1 || input < 0 || input > 100) \
return -EINVAL; \
\
dbs_tuners_ins.up_threshold_hotplug##name = input; \
hotplug_thresholds[0][core] = input; \
\
return count; \
} \
#define store_down_threshold_hotplug(name,core) \
static ssize_t store_down_threshold_hotplug##name \
(struct kobject *a, struct attribute *b, const char *buf, size_t count) \
{ \
unsigned int input; \
int ret; \
ret = sscanf(buf, "%u", &input); \
\
if (ret != 1 || input < 1 || input > 100) \
return -EINVAL; \
\
dbs_tuners_ins.down_threshold_hotplug##name = input; \
hotplug_thresholds[1][core] = input; \
\
return count; \
} \
/*
* ZZ: tuneables -> possible values: 0 to disable core (only in up thresholds), range from appropriate
* down threshold value up to 100, if not set default for up threshold is 68 and for down threshold is 55
*/
store_up_threshold_hotplug(1,0);
store_down_threshold_hotplug(1,0);
store_block_up_multiplier_hotplug(1);
store_block_down_multiplier_hotplug(1);
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
store_up_threshold_hotplug(2,1);
store_down_threshold_hotplug(2,1);
store_block_up_multiplier_hotplug(2);
store_block_down_multiplier_hotplug(2);
store_up_threshold_hotplug(3,2);
store_down_threshold_hotplug(3,2);
store_block_up_multiplier_hotplug(3);
store_block_down_multiplier_hotplug(3);
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
store_up_threshold_hotplug(4,3);
store_down_threshold_hotplug(4,3);
store_block_up_multiplier_hotplug(4);
store_block_down_multiplier_hotplug(4);
store_up_threshold_hotplug(5,4);
store_down_threshold_hotplug(5,4);
store_block_up_multiplier_hotplug(5);
store_block_down_multiplier_hotplug(5);
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
store_up_threshold_hotplug(6,5);
store_down_threshold_hotplug(6,5);
store_block_up_multiplier_hotplug(6);
store_block_down_multiplier_hotplug(6);
store_up_threshold_hotplug(7,6);
store_down_threshold_hotplug(7,6);
store_block_up_multiplier_hotplug(7);
store_block_down_multiplier_hotplug(7);
#endif /* (MAX_CORES == 8) */
#endif /* ENABLE_PROFILES_SUPPORT */
#endif /* ENABLE_HOTPLUGGING */
static ssize_t store_down_threshold(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
// ZZ: cannot be lower than 11 otherwise freq will not fall (conservative governor)
if (ret != 1 || input < 11 || input > 100
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
// ZZ: instead of failing when set too high set it to the highest it can safely go (ffolkes)
if (dbs_tuners_ins.up_threshold != 0 && input >= dbs_tuners_ins.up_threshold) {
input = dbs_tuners_ins.up_threshold - 1;
}
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.down_threshold != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.down_threshold = input;
return count;
}
// ZZ: tuneable -> possible values: range from 11 to up_threshold_sleep but not up_threshold_sleep, if not set default is 44
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
static ssize_t store_down_threshold_sleep(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
// ZZ: cannot be lower than 11 otherwise freq will not fall (conservative governor)
if (ret != 1 || input < 11 || input > 100
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
// ZZ: instead of failing when set too high set it to the highest it can safely go (ffolkes)
if (dbs_tuners_ins.up_threshold != 0 && input >= dbs_tuners_ins.up_threshold) {
input = dbs_tuners_ins.up_threshold - 1;
}
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.down_threshold_sleep != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.down_threshold_sleep = input;
return count;
}
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
static ssize_t store_ignore_nice_load(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
unsigned int j;
ret = sscanf(buf, "%u", &input);
if (ret != 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
if (input > 1)
input = 1;
if (input == dbs_tuners_ins.ignore_nice) { // ZZ: nothing to do
return count;
}
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.ignore_nice != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.ignore_nice = input;
// ZZ: we need to re-evaluate prev_cpu_idle
for_each_online_cpu(j) {
struct cpu_dbs_info_s *dbs_info;
dbs_info = &per_cpu(cs_cpu_dbs_info, j);
dbs_info->prev_cpu_idle = get_cpu_idle_time(j,
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0) || defined(CPU_IDLE_TIME_IN_CPUFREQ) /* overrule for sources with backported cpufreq implementation */
&dbs_info->prev_cpu_wall, 0);
#else
&dbs_info->prev_cpu_wall);
#endif /* LINUX_VERSION_CODE... */
if (dbs_tuners_ins.ignore_nice)
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,4,0)
dbs_info->prev_cpu_nice = kcpustat_cpu(j).cpustat[CPUTIME_NICE];
#else
dbs_info->prev_cpu_nice = kstat_cpu(j).cpustat.nice;
#endif /* LINUX_VERSION_CODE... */
}
return count;
}
static ssize_t store_smooth_up(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > 100 || input < 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.smooth_up != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.smooth_up = input;
return count;
}
// ZZ: tuneable -> possible values: range from 1 to 100, if not set default is 100
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
static ssize_t store_smooth_up_sleep(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > 100 || input < 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.smooth_up_sleep != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.smooth_up_sleep = input;
return count;
}
/*
* ZZ: tuneable -> possible values: 0 do not touch the hotplug values on early suspend,
* input value 1 to MAX_CORES -> value equals cores to run at early suspend, if not set default is 0 (= all cores enabled)
*/
#ifdef ENABLE_HOTPLUGGING
static ssize_t store_hotplug_sleep(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input >= possible_cpus || (input < 0 && input != 0)
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.hotplug_sleep != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.hotplug_sleep = input;
return count;
}
#endif /* ENABLE_HOTPLUGGING */
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
/*
* ZZ: tuneable -> possible values: 0 disable, system table freq->min to freq->max in khz -> freqency soft-limit, if not set default is 0
* Yank: updated : possible values now depend on the system frequency table only
*/
static ssize_t store_freq_limit(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
int i = 0;
ret = sscanf(buf, "%u", &input);
if (ret != 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
if (input == 0) {
max_scaling_freq_soft = max_scaling_freq_hard;
if (freq_table_desc) // ZZ: if descending ordered table is used
limit_table_start = max_scaling_freq_soft; // ZZ: we should use the actual scaling soft limit value as search start point
else
limit_table_end = system_freq_table[freq_table_size].frequency; // ZZ: set search end point to max freq when using ascending table
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.freq_limit != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
freq_limit_awake = dbs_tuners_ins.freq_limit = input;
#else
dbs_tuners_ins.freq_limit = input;
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
return count;
}
#ifdef ENABLE_PROFILES_SUPPORT
input = check_frequency(input); // ZZ: check and adapt given freq if necessary
#endif /* ENABLE_PROFILES_SUPPORT */
if (input > system_freq_table[max_scaling_freq_hard].frequency) { // Yank: allow only frequencies below or equal to hard max limit
return -EINVAL;
} else {
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) {
if (unlikely(system_freq_table[i].frequency == input)) {
max_scaling_freq_soft = i;
if (freq_table_desc) // ZZ: if descending ordered table is used
limit_table_start = max_scaling_freq_soft; // ZZ: we should use the actual scaling soft limit value as search start point
else
limit_table_end = system_freq_table[i].frequency; // ZZ: set search end point to max soft freq limit when using ascenting table
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.freq_limit != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
freq_limit_awake = dbs_tuners_ins.freq_limit = input;
#else
dbs_tuners_ins.freq_limit = input;
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
return count;
}
}
}
return -EINVAL;
}
/*
* ZZ: tuneable -> possible values: 0 disable, system table freq->min to freq->max in khz -> freqency soft-limit,
* if not set default is 0
* Yank: updated : possible values now depend on the system frequency table only
*/
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
static ssize_t store_freq_limit_sleep(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
int i = 0;
ret = sscanf(buf, "%u", &input);
if (ret != 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
if (input == 0) {
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.freq_limit_sleep != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
freq_limit_asleep = dbs_tuners_ins.freq_limit_sleep = input;
return count;
}
#ifdef ENABLE_PROFILES_SUPPORT
input = check_frequency(input); // ZZ: check and adapt given freq if necessary
#endif /* ENABLE_PROFILES_SUPPORT */
if (input > system_freq_table[max_scaling_freq_hard].frequency) { // Yank: allow only frequencies below or equal to hard max
return -EINVAL;
} else {
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) {
if (unlikely(system_freq_table[i].frequency == input)) {
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.freq_limit_sleep != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
freq_limit_asleep = dbs_tuners_ins.freq_limit_sleep = input;
return count;
}
}
}
return -EINVAL;
}
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
// Yank: tuneable -> possible values 1-4 to enable fast scaling and 5 for auto fast scaling (insane scaling)
static ssize_t store_fast_scaling_up(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > 5 || input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.fast_scaling_up != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.fast_scaling_up = input;
if (input > 4) // ZZ: auto fast scaling mode
return count;
scaling_mode_up = input; // Yank: fast scaling up only
return count;
}
// Yank: tuneable -> possible values 1-4 to enable fast scaling and 5 for auto fast scaling (insane scaling)
static ssize_t store_fast_scaling_down(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > 5 || input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.fast_scaling_down != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.fast_scaling_down = input;
if (input > 4) // ZZ: auto fast scaling mode
return count;
scaling_mode_down = input; // Yank: fast scaling up only
return count;
}
// Yank: tuneable -> possible values 1-4 to enable fast scaling and 5 for auto fast scaling (insane scaling) in early suspend
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
static ssize_t store_fast_scaling_sleep_up(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > 5 || input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.fast_scaling_sleep_up != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.fast_scaling_sleep_up = input;
return count;
}
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
// Yank: tuneable -> possible values 1-4 to enable fast scaling and 5 for auto fast scaling (insane scaling) in early suspend
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
static ssize_t store_fast_scaling_sleep_down(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > 5 || input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.fast_scaling_sleep_down != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.fast_scaling_sleep_down = input;
return count;
}
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: tuneable -> possible values from 0 to 100
#define store_afs_threshold(name) \
static ssize_t store_afs_threshold##name(struct kobject *a, struct attribute *b, \
const char *buf, size_t count) \
{ \
unsigned int input; \
int ret; \
ret = sscanf(buf, "%u", &input); \
\
if (ret != 1 || input > 100 || input < 0 || set_profile_active == true) \
return -EINVAL; \
\
\
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 \
&& dbs_tuners_ins.afs_threshold##name != input) { \
dbs_tuners_ins.profile_number = 0; \
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile)); \
} \
\
dbs_tuners_ins.afs_threshold##name = input; \
\
return count; \
} \
store_afs_threshold(1);
store_afs_threshold(2);
store_afs_threshold(3);
store_afs_threshold(4);
#endif /* ENABLE_PROFILES_SUPPORT */
#ifndef ENABLE_PROFILES_SUPPORT
// ZZ: tuneable -> possible values from 0 to 100
#define store_afs_threshold(name) \
static ssize_t store_afs_threshold##name(struct kobject *a, struct attribute *b, \
const char *buf, size_t count) \
{ \
unsigned int input; \
int ret; \
ret = sscanf(buf, "%u", &input); \
\
if (ret != 1 || input > 100 || input < 0) \
return -EINVAL; \
\
dbs_tuners_ins.afs_threshold##name = input; \
\
return count; \
} \
store_afs_threshold(1);
store_afs_threshold(2);
store_afs_threshold(3);
store_afs_threshold(4);
#endif /* ENABLE_PROFILES_SUPPORT */
// ZZ: Early demand - tuneable grad up threshold -> possible values: from 1 to 100, if not set default is 50
static ssize_t store_grad_up_threshold(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > 100 || input < 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.grad_up_threshold != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.grad_up_threshold = input;
return count;
}
// ZZ: Early demand - tuneable grad up threshold sleep -> possible values: from 1 to 100, if not set default is 50
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
static ssize_t store_grad_up_threshold_sleep(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > 100 || input < 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.grad_up_threshold_sleep != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.grad_up_threshold_sleep = input;
return count;
}
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
// ZZ: Early demand - tuneable master switch -> possible values: 0 to disable, any value above 0 to enable, if not set default is 0
static ssize_t store_early_demand(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
input = !!input;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.early_demand != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.early_demand = !!input;
return count;
}
// ZZ: Early demand sleep - tuneable master switch -> possible values: 0 to disable, any value above 0 to enable, if not set default is 0
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
static ssize_t store_early_demand_sleep(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
input = !!input;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.early_demand_sleep != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.early_demand_sleep = !!input;
return count;
}
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_HOTPLUGGING
// ZZ: tuneable hotplug switch -> possible values: 0 to disable, any value above 0 to enable, if not set default is 0
static ssize_t store_disable_hotplug(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > 2 || input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.disable_hotplug != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.disable_hotplug = input;
if (input == 1) {
enable_cores = 1;
queue_work_on(0, dbs_wq, &hotplug_online_work);
}
return count;
}
// ZZ: tuneable hotplug switch for early supend -> possible values: 0 to disable, any value above 0 to enable, if not set default is 0
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
static ssize_t store_disable_hotplug_sleep(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > 2 || input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.disable_hotplug_sleep != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.disable_hotplug_sleep = input;
return count;
}
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
// ZZ: tuneable hotplug up block cycles -> possible values: 0 to disable, any value above 0 to enable, if not set default is 0
static ssize_t store_hotplug_block_up_cycles(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
if (input == 0)
hplg_up_block_cycles = 0;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.hotplug_block_up_cycles != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.hotplug_block_up_cycles = input;
return count;
}
// ZZ: tuneable hotplug down block cycles -> possible values: 0 to disable, any value above 0 to enable, if not set default is 0
static ssize_t store_hotplug_block_down_cycles(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
if (input == 0)
hplg_down_block_cycles = 0;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.hotplug_block_down_cycles != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.hotplug_block_down_cycles = input;
return count;
}
// ff: tuneable hotplug stagger up -> possible values: 0 to disable, any value above 0 to enable, if not set default is 0
static ssize_t store_hotplug_stagger_up(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
input = !!input;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.hotplug_stagger_up != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.hotplug_stagger_up = input;
return count;
}
// ff: tuneable hotplug stagger down -> possible values: 0 to disable, any value above 0 to enable, if not set default is 0
static ssize_t store_hotplug_stagger_down(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
input = !!input;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.hotplug_stagger_down != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.hotplug_stagger_down = input;
return count;
}
// ZZ: tuneable hotplug idle threshold -> possible values: range from 0 disabled to 100, if not set default is 0
static ssize_t store_hotplug_idle_threshold(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (((ret != 1 || input < 0 || input > 100) && input != 0)
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.hotplug_idle_threshold != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.hotplug_idle_threshold = input;
return count;
}
// ZZ: tuneable hotplug idle frequency -> frequency from where the hotplug idle should begin. possible values: all valid system frequencies
static ssize_t store_hotplug_idle_freq(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
int i = 0;
ret = sscanf(buf, "%u", &input);
if (ret != 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
if (input == 0) {
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.hotplug_idle_freq != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.hotplug_idle_freq = input;
return count;
}
#ifdef ENABLE_PROFILES_SUPPORT
input = check_frequency(input); // ZZ: check and adapt given freq if necessary
#endif /* ENABLE_PROFILES_SUPPORT */
if (input > system_freq_table[max_scaling_freq_hard].frequency) { // Yank: allow only frequencies below or equal to hard max
return -EINVAL;
} else {
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) {
if (unlikely(system_freq_table[i].frequency == input)) {
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.hotplug_idle_freq != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.hotplug_idle_freq = input;
return count;
}
}
}
return -EINVAL;
}
// ZZ: tuneable -> possible values: range from 0 (disabled) to policy->max, if not set default is 0 (ffolkes)
static ssize_t store_hotplug_engage_freq(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
int i = 0;
ret = sscanf(buf, "%u", &input);
if (ret != 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
if (input == 0) {
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.hotplug_engage_freq != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.hotplug_engage_freq = input;
return count;
}
#ifdef ENABLE_PROFILES_SUPPORT
input = check_frequency(input); // ZZ: check and adapt given freq if necessary
#endif /* ENABLE_PROFILES_SUPPORT */
if (input > system_freq_table[max_scaling_freq_hard].frequency) { // Yank: allow only frequencies below or equal to hard max
return -EINVAL;
} else {
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) {
if (unlikely(system_freq_table[i].frequency == input)) {
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.hotplug_engage_freq != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.hotplug_engage_freq = input;
return count;
}
}
}
return -EINVAL;
}
// ff: added tuneable hotplug_max_limit -> possible values: range from 0 disabled to 8, if not set default is 0
static ssize_t store_hotplug_max_limit(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (((ret != 1 || input < 0 || input > possible_cpus) && input != 0)
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.hotplug_max_limit != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.hotplug_max_limit = input;
if (input > 0) {
disable_cores = 1;
queue_work_on(0, dbs_wq, &hotplug_offline_work);
}
return count;
}
// ff: added tuneable hotplug_lock -> possible values: range from 0 disabled to 8, if not set default is 0
static ssize_t store_hotplug_lock(struct kobject *a, struct attribute *b,
const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (((ret != 1 || input < 0 || input > possible_cpus) && input != 0)
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.hotplug_lock != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.hotplug_lock = input;
if (input > 0) {
disable_cores = 2;
queue_work_on(0, dbs_wq, &hotplug_offline_work);
}
return count;
}
// ff: added tuneable hotplug_min_limit -> possible values: range from 0 disabled to 8, if not set default is 0
static ssize_t store_hotplug_min_limit(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (((ret != 1 || input < 1 || input > possible_cpus) && input != 0)
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.hotplug_min_limit != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.hotplug_min_limit = input;
dbs_tuners_ins.hotplug_min_limit_saved = input;
if (input > 1) {
enable_cores = 1;
queue_work_on(0, dbs_wq, &hotplug_online_work);
}
return count;
}
#endif /* ENABLE_HOTPLUGGING */
// ZZ: tuneable -> possible values: range from 0 (disabled) to policy->max, if not set default is 0 (ffolkes)
static ssize_t store_scaling_responsiveness_freq(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
int i = 0;
ret = sscanf(buf, "%u", &input);
if (ret != 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
if (input == 0) {
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.scaling_responsiveness_freq != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.scaling_responsiveness_freq = input;
return count;
}
#ifdef ENABLE_PROFILES_SUPPORT
input = check_frequency(input); // ZZ: check and adapt given freq if necessary
#endif /* ENABLE_PROFILES_SUPPORT */
if (input > system_freq_table[max_scaling_freq_hard].frequency) { // Yank: allow only frequencies below or equal to hard max
return -EINVAL;
} else {
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) {
if (unlikely(system_freq_table[i].frequency == input)) {
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.scaling_responsiveness_freq != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.scaling_responsiveness_freq = input;
return count;
}
}
}
return -EINVAL;
}
// ZZ: tuneable -> possible values: range from 11 to 100, if not set default is 30 (ffolkes)
static ssize_t store_scaling_responsiveness_up_threshold(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > 100 || input < 11
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.scaling_responsiveness_up_threshold != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.scaling_responsiveness_up_threshold = input;
return count;
}
// ZZ: tuneable scaling idle threshold -> possible values: range from 0 disabled to 100, if not set default is 0
static ssize_t store_scaling_block_threshold(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (((ret != 1 || input < 0 || input > 100) && input != 0)
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.scaling_block_threshold != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.scaling_block_threshold = input;
return count;
}
// ZZ: tuneable scaling block cycles -> possible values: 0 to disable, any value above 0 to enable, if not set default is 0
static ssize_t store_scaling_block_cycles(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
if (input == 0)
scaling_block_cycles_count = 0;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.scaling_block_cycles != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.scaling_block_cycles = input;
return count;
}
// ff: tuneable scaling-up block cycles -> possible values: 0 to disable, any value above 0 to enable, if not set default is 0
static ssize_t store_scaling_up_block_cycles(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
if (input == 0)
scaling_up_block_cycles_count = 0;
dbs_tuners_ins.scaling_up_block_cycles = input;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode
if (dbs_tuners_ins.profile_number != 0) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
return count;
}
// ff: tuneable -> possible values: range from 0 (disabled) to policy->max, if not set default is 0
static ssize_t store_scaling_up_block_freq(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
int i = 0;
ret = sscanf(buf, "%u", &input);
if (ret != 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
if (input == 0) {
dbs_tuners_ins.scaling_up_block_freq = input;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode
if (dbs_tuners_ins.profile_number != 0) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
return count;
}
#ifdef ENABLE_PROFILES_SUPPORT
input = check_frequency(input); // ZZ: check and adapt given freq if necessary
#endif /* ENABLE_PROFILES_SUPPORT */
if (input > system_freq_table[max_scaling_freq_hard].frequency) { // Yank: allow only frequencies below or equal to hard max
return -EINVAL;
} else {
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) {
if (unlikely(system_freq_table[i].frequency == input)) {
dbs_tuners_ins.scaling_up_block_freq = input;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode
if (dbs_tuners_ins.profile_number != 0) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
return count;
}
}
}
return -EINVAL;
}
#ifdef CONFIG_EXYNOS4_EXPORT_TEMP
// ZZ: tuneable scaling block temp -> possible values: 0 to disable, values from 30°C to 80°C, if not set default is 0
static ssize_t store_scaling_block_temp(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || (input < 30 && input != 0) || input > 80
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.scaling_block_temp != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.scaling_block_temp = input;
return count;
}
#endif /* CONFIG_EXYNOS4_EXPORT_TEMP */
// ff: added tuneable scaling_trip_temp -> possible values: 0 to disable, range from 40°C to 69°C if not set default is 0
#ifdef ENABLE_SNAP_THERMAL_SUPPORT
static ssize_t store_scaling_trip_temp(struct kobject *a, struct attribute *b,
const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || (input < 40 && input != 0) || input > 69
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.scaling_trip_temp != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.scaling_trip_temp = input;
return count;
}
#endif /* ENABLE_SNAP_THERMAL_SUPPORT */
// ZZ: tuneable scaling up idle frequency -> frequency from where the scaling up idle should begin. possible values all valid system frequenies
static ssize_t store_scaling_block_freq(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
int i = 0;
ret = sscanf(buf, "%u", &input);
if (ret != 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
if (input == 0) {
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.scaling_block_freq != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.scaling_block_freq = input;
return count;
}
#ifdef ENABLE_PROFILES_SUPPORT
input = check_frequency(input); // ZZ: check and adapt given freq if necessary
#endif /* ENABLE_PROFILES_SUPPORT */
if (input > system_freq_table[max_scaling_freq_hard].frequency) { // Yank: allow only frequencies below or equal to hard max
return -EINVAL;
} else {
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) {
if (unlikely(system_freq_table[i].frequency == input)) {
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.scaling_block_freq != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.scaling_block_freq = input;
return count;
}
}
}
return -EINVAL;
}
// ZZ: tuneable scaling block force down -> possible values: 0 to disable, 2 or any value above 2 to enable, if not set default is 2
static ssize_t store_scaling_block_force_down(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0 || input == 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.scaling_block_force_down != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.scaling_block_force_down = input;
return count;
}
// ZZ: tuneable scaling_fastdown_freq -> possible values: range from 0 (disabled) to policy->max, if not set default is 0 (ffolkes)
static ssize_t store_scaling_fastdown_freq(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
int i = 0;
ret = sscanf(buf, "%u", &input);
if (ret != 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
if (input == 0) {
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.scaling_fastdown_freq != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.scaling_fastdown_freq = input;
return count;
}
#ifdef ENABLE_PROFILES_SUPPORT
input = check_frequency(input); // ZZ: check and adapt given freq if necessary
#endif /* ENABLE_PROFILES_SUPPORT */
if (input > system_freq_table[max_scaling_freq_hard].frequency) { // Yank: allow only frequencies below or equal to hard max
return -EINVAL;
} else {
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) {
if (unlikely(system_freq_table[i].frequency == input)) {
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.scaling_fastdown_freq != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.scaling_fastdown_freq = input;
return count;
}
}
}
return -EINVAL;
}
// ZZ: tuneable scaling_fastdown_up_threshold -> possible values: range from above fastdown up threshold to 100, if not set default is 95 (ffolkes)
static ssize_t store_scaling_fastdown_up_threshold(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > 100 || input <= dbs_tuners_ins.scaling_fastdown_down_threshold
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.scaling_fastdown_up_threshold != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.scaling_fastdown_up_threshold = input;
return count;
}
// ZZ: tuneable scaling_fastdown_down_threshold -> possible values: range from 11 to 100, if not set default is 90 (ffolkes)
static ssize_t store_scaling_fastdown_down_threshold(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if ((ret != 1 || input > 100 || (input < 11 && input >= dbs_tuners_ins.scaling_fastdown_up_threshold))
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.scaling_fastdown_down_threshold != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.scaling_fastdown_down_threshold = input;
return count;
}
// ZZ: tuneable scaling proportinal -> possible values: 0 to disable, 1 to enable comparision between proportional and optimized freq, 2 to enable propotional freq usage only
// 3 to enable propotional freq usage only but with dead brand range to avoid not reaching of pol min freq, if not set default is 0
static ssize_t store_scaling_proportional(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0 || input > 3
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.scaling_proportional != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.scaling_proportional = input;
return count;
}
#ifdef ENABLE_INPUTBOOSTER
// ff: added tuneable inputboost_cycles -> possible values: range from 0 disabled to 1000, if not set default is 0
static ssize_t store_inputboost_cycles(struct kobject *a, struct attribute *b,
const char *buf, size_t count)
{
unsigned int input;
int ret;
int rc;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0 || input > 1000
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.inputboost_cycles != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
if (!input && dbs_tuners_ins.inputboost_cycles != input) {
// input is 0, and it wasn't before.
// so remove booster and unregister.
input_unregister_handler(&interactive_input_handler);
} else if (input && dbs_tuners_ins.inputboost_cycles == 0) {
// input is something other than 0, and it wasn't before,
// so add booster and register.
rc = input_register_handler(&interactive_input_handler);
if (!rc)
pr_info("[zzmoove/store_inputboost_cycles] inputbooster - registered\n");
else
pr_info("[zzmoove/store_inputboost_cycles] inputbooster - register FAILED\n");
}
dbs_tuners_ins.inputboost_cycles = input;
return count;
}
// ff: added tuneable inputboost_up_threshold -> possible values: range from 0 disabled (future use) to 100, if not set default is 50
static ssize_t store_inputboost_up_threshold(struct kobject *a, struct attribute *b,
const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0 || input > 100
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.inputboost_up_threshold != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.inputboost_up_threshold = input;
return count;
}
// ff: added tuneable inputboost_punch_cycles -> possible values: range from 0 disabled to 500, if not set default is 0
static ssize_t store_inputboost_punch_cycles(struct kobject *a, struct attribute *b,
const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0 || input > 500
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.inputboost_punch_cycles != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
if (!input) {
// reset some stuff.
flg_ctr_inputboost = 0;
flg_ctr_inputboost_punch = 0;
}
dbs_tuners_ins.inputboost_punch_cycles = input;
return count;
}
// ff: added tuneable inputboost_punch_freq -> possible values: range from 0 disabled to policy->max, if not set default is 0
static ssize_t store_inputboost_punch_freq(struct kobject *a, struct attribute *b,
const char *buf, size_t count)
{
unsigned int input;
unsigned int i;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
if (input == 0) {
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.inputboost_punch_freq != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.inputboost_punch_freq = input;
return count;
}
#ifdef ENABLE_PROFILES_SUPPORT
input = check_frequency(input); // ZZ: check and adapt given freq if necessary
#endif /* ENABLE_PROFILES_SUPPORT */
if (input > system_freq_table[max_scaling_freq_hard].frequency) { // Yank: allow only frequencies below or equal to hard max
return -EINVAL;
} else {
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) {
if (unlikely(system_freq_table[i].frequency == input)) {
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.inputboost_punch_freq != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.inputboost_punch_freq = input;
return count;
}
}
}
return -EINVAL;
}
// ff: added tuneable inputboost_punch_on_fingerdown -> possible values: range from 0 disabled to >0 enabled, if not set default is 0
static ssize_t store_inputboost_punch_on_fingerdown(struct kobject *a, struct attribute *b,
const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
if (input > 1)
input = 1;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.inputboost_punch_on_fingerdown != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.inputboost_punch_on_fingerdown = input;
return count;
}
// ff: added tuneable inputboost_punch_on_fingermove -> possible values: range from 0 disabled to >0 enabled, if not set default is 0
static ssize_t store_inputboost_punch_on_fingermove(struct kobject *a, struct attribute *b,
const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
if (input > 1)
input = 1;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.inputboost_punch_on_fingermove != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.inputboost_punch_on_fingermove = input;
return count;
}
// ff: added tuneable inputboost_punch_on_epenmove -> possible values: range from 0 disabled to >0 enabled, if not set default is 0
static ssize_t store_inputboost_punch_on_epenmove(struct kobject *a, struct attribute *b,
const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
if (input > 1)
input = 1;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.inputboost_punch_on_epenmove != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.inputboost_punch_on_epenmove = input;
return count;
}
// ff: added tuneable inputboost_typingbooster_up_threshold -> possible values: range from 0 disabled (future use) to 100, if not set default is 50
static ssize_t store_inputboost_typingbooster_up_threshold(struct kobject *a, struct attribute *b,
const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0 || input > 100
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.inputboost_typingbooster_up_threshold != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.inputboost_typingbooster_up_threshold = input;
return count;
}
#ifdef ENABLE_HOTPLUGGING
// ff: added tuneable inputboost_typingbooster_cores -> possible values: range from 0 disabled to 4, if not set default is 0
static ssize_t store_inputboost_typingbooster_cores(struct kobject *a, struct attribute *b,
const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0 || input > 4
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.inputboost_typingbooster_cores != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.inputboost_typingbooster_cores = input;
return count;
}
#endif /* ENABLE_HOTPLUGGING */
#endif /* ENABLE_INPUTBOOSTER */
#ifdef ENABLE_MUSIC_LIMITS
// ff: added tuneable music_max_freq -> possible values: range from 0 disabled to policy->max, if not set default is 0
static ssize_t store_music_max_freq(struct kobject *a, struct attribute *b,
const char *buf, size_t count)
{
unsigned int input;
unsigned int i;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
if (input == 0) {
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.music_max_freq != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
music_max_freq_step = 0;
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
dbs_tuners_ins.music_max_freq = input;
return count;
}
#ifdef ENABLE_PROFILES_SUPPORT
input = check_frequency(input); // ZZ: check and adapt given freq if necessary
#endif /* ENABLE_PROFILES_SUPPORT */
if (input > system_freq_table[max_scaling_freq_hard].frequency) { // Yank: allow only frequencies below or equal to hard max
return -EINVAL;
} else {
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) {
if (unlikely(system_freq_table[i].frequency == input)) {
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.music_max_freq != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.music_max_freq = input;
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
music_max_freq_step = i;
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
return count;
}
}
}
return -EINVAL;
}
// ff: added tuneable music_min_freq -> possible values: range from 0 disabled to policy->max, if not set default is 0
static ssize_t store_music_min_freq(struct kobject *a, struct attribute *b,
const char *buf, size_t count)
{
unsigned int input;
unsigned int i;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
if (input == 0) {
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.music_min_freq != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.music_min_freq = input;
return count;
}
#ifdef ENABLE_PROFILES_SUPPORT
input = check_frequency(input); // ZZ: check and adapt given freq if necessary
#endif /* ENABLE_PROFILES_SUPPORT */
if (input > system_freq_table[max_scaling_freq_hard].frequency) { // Yank: allow only frequencies below or equal to hard max
return -EINVAL;
} else {
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) {
if (unlikely(system_freq_table[i].frequency == input)) {
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.music_min_freq != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.music_min_freq = input;
return count;
}
}
}
return -EINVAL;
}
#ifdef ENABLE_HOTPLUGGING
// ZZ: added tuneable music_min_cores -> possible values: range from 0 disabled to 8, if not set default is 0
static ssize_t store_music_min_cores(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (((ret != 1 || input < 1 || input > possible_cpus) && input != 0)
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.music_min_cores != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.music_min_cores = input;
return count;
}
#endif /* ENABLE_HOTPLUGGING */
// ff: added tuneable music_state -> possible values: 0 or 1
static ssize_t store_music_state(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret, i;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0)
return -EINVAL;
if (input > 0) {
#ifdef ENABLE_HOTPLUGGING
// ZZ: if music min cores are set apply core setting
if (dbs_tuners_ins.music_min_cores > 0) {
enable_cores = 1;
queue_work_on(0, dbs_wq, &hotplug_online_work);
}
#endif /* ENABLE_HOTPLUGGING */
// ZZ: if music min limit is set change scaling min limit on ascending ordered table
if (dbs_tuners_ins.music_min_freq && !freq_table_desc) {
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) {
if (unlikely(system_freq_table[i].frequency == dbs_tuners_ins.music_min_freq)) {
if (i >= min_scaling_freq_hard) // ZZ: only if it is higher than current hard limit
min_scaling_freq_soft = limit_table_start = i;
}
}
}
dbs_tuners_ins.music_state = 1;
return count;
} else {
if (!freq_table_desc) { // ZZ: only on ascending ordered table
min_scaling_freq_soft = 0; // ZZ: reset saved freq soft limit
limit_table_start = 0; // ZZ: reset freq limit start point
}
dbs_tuners_ins.music_state = 0; // ZZ: disable music state
}
return count;
}
#endif /* ENABLE_MUSIC_LIMITS */
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: function for switching a settings profile either at governor start by macro 'DEF_PROFILE_NUMBER' or later by tuneable 'profile_number'
static inline int set_profile(int profile_num)
{
int i = 0; // ZZ: for main profile loop
int t = 0; // ZZ: for sub-loop
#ifdef ENABLE_INPUTBOOSTER
int rc = 0; // ZZ: for impubooster registering
#endif /* ENABLE_INPUTBOOSTER */
unsigned int j; // ZZ: for update routines
set_profile_active = true; // ZZ: avoid additional setting of tuneables during following loop
for (i = 0; (unlikely(zzmoove_profiles[i].profile_number != PROFILE_TABLE_END)); i++) {
if (unlikely(zzmoove_profiles[i].profile_number == profile_num)) {
#ifdef ENABLE_HOTPLUGGING
// ZZ: set disable_hotplug value
if (zzmoove_profiles[i].disable_hotplug > 0 && zzmoove_profiles[i].disable_hotplug < 2) {
dbs_tuners_ins.disable_hotplug = zzmoove_profiles[i].disable_hotplug;
if (zzmoove_profiles[i].disable_hotplug == 1) {
enable_cores = 1;
queue_work_on(0, dbs_wq, &hotplug_online_work);
}
}
// ZZ: set disable_hotplug_sleep value
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
if (zzmoove_profiles[i].disable_hotplug_sleep > 0 && zzmoove_profiles[i].disable_hotplug_sleep < 2)
dbs_tuners_ins.disable_hotplug_sleep = zzmoove_profiles[i].disable_hotplug_sleep;
// ZZ: set hotplug_sleep value
if (zzmoove_profiles[i].hotplug_sleep <= possible_cpus && zzmoove_profiles[i].hotplug_sleep >= 0)
dbs_tuners_ins.hotplug_sleep = zzmoove_profiles[i].hotplug_sleep;
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#endif /* ENABLE_HOTPLUGGING */
// ZZ: set down_threshold value
if (zzmoove_profiles[i].down_threshold > 11 && zzmoove_profiles[i].down_threshold <= 100
&& zzmoove_profiles[i].down_threshold < zzmoove_profiles[i].up_threshold)
dbs_tuners_ins.down_threshold = zzmoove_profiles[i].down_threshold;
#ifdef ENABLE_HOTPLUGGING
// ZZ: set down_threshold_hotplug1 value
if ((zzmoove_profiles[i].down_threshold_hotplug1 <= 100
&& zzmoove_profiles[i].down_threshold_hotplug1 >= 1)
|| zzmoove_profiles[i].down_threshold_hotplug1 == 0) {
dbs_tuners_ins.down_threshold_hotplug1 = zzmoove_profiles[i].down_threshold_hotplug1;
hotplug_thresholds[1][0] = zzmoove_profiles[i].down_threshold_hotplug1;
}
// ff: set block up multiplier for hotplug1
if (zzmoove_profiles[i].block_up_multiplier_hotplug1 >= 0 && zzmoove_profiles[i].block_up_multiplier_hotplug1 <= 25)
dbs_tuners_ins.block_up_multiplier_hotplug1 = zzmoove_profiles[i].block_up_multiplier_hotplug1;
// ff: set block down multiplier for hotplug1
if (zzmoove_profiles[i].block_down_multiplier_hotplug1 >= 0 && zzmoove_profiles[i].block_down_multiplier_hotplug1 <= 25)
dbs_tuners_ins.block_down_multiplier_hotplug1 = zzmoove_profiles[i].block_down_multiplier_hotplug1;
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
// ZZ: set down_threshold_hotplug2 value
if ((zzmoove_profiles[i].down_threshold_hotplug2 <= 100
&& zzmoove_profiles[i].down_threshold_hotplug2 >= 1)
|| zzmoove_profiles[i].down_threshold_hotplug2 == 0) {
dbs_tuners_ins.down_threshold_hotplug2 = zzmoove_profiles[i].down_threshold_hotplug2;
hotplug_thresholds[1][1] = zzmoove_profiles[i].down_threshold_hotplug2;
}
// ff: set block up multiplier for hotplug2
if (zzmoove_profiles[i].block_up_multiplier_hotplug2 >= 0 && zzmoove_profiles[i].block_up_multiplier_hotplug2 <= 25)
dbs_tuners_ins.block_up_multiplier_hotplug2 = zzmoove_profiles[i].block_up_multiplier_hotplug2;
// ff: set block down multiplier for hotplug2
if (zzmoove_profiles[i].block_down_multiplier_hotplug2 >= 0 && zzmoove_profiles[i].block_down_multiplier_hotplug2 <= 25)
dbs_tuners_ins.block_down_multiplier_hotplug2 = zzmoove_profiles[i].block_down_multiplier_hotplug2;
// ZZ: set down_threshold_hotplug3 value
if ((zzmoove_profiles[i].down_threshold_hotplug3 <= 100
&& zzmoove_profiles[i].down_threshold_hotplug3 >= 1)
|| zzmoove_profiles[i].down_threshold_hotplug3 == 0) {
dbs_tuners_ins.down_threshold_hotplug3 = zzmoove_profiles[i].down_threshold_hotplug3;
hotplug_thresholds[1][2] = zzmoove_profiles[i].down_threshold_hotplug3;
}
// ff: set block up multiplier for hotplug3
if (zzmoove_profiles[i].block_up_multiplier_hotplug3 >= 0 && zzmoove_profiles[i].block_up_multiplier_hotplug3 <= 25)
dbs_tuners_ins.block_up_multiplier_hotplug3 = zzmoove_profiles[i].block_up_multiplier_hotplug3;
// ff: set block down multiplier for hotplug3
if (zzmoove_profiles[i].block_down_multiplier_hotplug3 >= 0 && zzmoove_profiles[i].block_down_multiplier_hotplug3 <= 25)
dbs_tuners_ins.block_down_multiplier_hotplug3 = zzmoove_profiles[i].block_down_multiplier_hotplug3;
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
// ZZ: set down_threshold_hotplug4 value
if ((zzmoove_profiles[i].down_threshold_hotplug4 <= 100
&& zzmoove_profiles[i].down_threshold_hotplug4 >= 1)
|| zzmoove_profiles[i].down_threshold_hotplug4 == 0) {
dbs_tuners_ins.down_threshold_hotplug4 = zzmoove_profiles[i].down_threshold_hotplug4;
hotplug_thresholds[1][3] = zzmoove_profiles[i].down_threshold_hotplug4;
}
// ff: set block up multiplier for hotplug4
if (zzmoove_profiles[i].block_up_multiplier_hotplug4 >= 0 && zzmoove_profiles[i].block_up_multiplier_hotplug4 <= 25)
dbs_tuners_ins.block_up_multiplier_hotplug4 = zzmoove_profiles[i].block_up_multiplier_hotplug4;
// ff: set block down multiplier for hotplug4
if (zzmoove_profiles[i].block_down_multiplier_hotplug4 >= 0 && zzmoove_profiles[i].block_down_multiplier_hotplug4 <= 25)
dbs_tuners_ins.block_down_multiplier_hotplug4 = zzmoove_profiles[i].block_down_multiplier_hotplug4;
// ZZ: set down_threshold_hotplug5 value
if ((zzmoove_profiles[i].down_threshold_hotplug5 <= 100
&& zzmoove_profiles[i].down_threshold_hotplug5 >= 1)
|| zzmoove_profiles[i].down_threshold_hotplug5 == 0) {
dbs_tuners_ins.down_threshold_hotplug5 = zzmoove_profiles[i].down_threshold_hotplug5;
hotplug_thresholds[1][4] = zzmoove_profiles[i].down_threshold_hotplug5;
}
// ff: set block up multiplier for hotplug5
if (zzmoove_profiles[i].block_up_multiplier_hotplug5 >= 0 && zzmoove_profiles[i].block_up_multiplier_hotplug5 <= 25)
dbs_tuners_ins.block_up_multiplier_hotplug5 = zzmoove_profiles[i].block_up_multiplier_hotplug5;
// ff: set block down multiplier for hotplug5
if (zzmoove_profiles[i].block_down_multiplier_hotplug5 >= 0 && zzmoove_profiles[i].block_down_multiplier_hotplug5 <= 25)
dbs_tuners_ins.block_down_multiplier_hotplug5 = zzmoove_profiles[i].block_down_multiplier_hotplug5;
// ZZ: set down_threshold_hotplug6 value
if ((zzmoove_profiles[i].down_threshold_hotplug6 <= 100
&& zzmoove_profiles[i].down_threshold_hotplug6 >= 1)
|| zzmoove_profiles[i].down_threshold_hotplug6 == 0) {
dbs_tuners_ins.down_threshold_hotplug6 = zzmoove_profiles[i].down_threshold_hotplug6;
hotplug_thresholds[1][5] = zzmoove_profiles[i].down_threshold_hotplug6;
}
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
// ff: set block up multiplier for hotplug6
if (zzmoove_profiles[i].block_up_multiplier_hotplug6 >= 0 && zzmoove_profiles[i].block_up_multiplier_hotplug6 <= 25)
dbs_tuners_ins.block_up_multiplier_hotplug6 = zzmoove_profiles[i].block_up_multiplier_hotplug6;
// ff: set block down multiplier for hotplug6
if (zzmoove_profiles[i].block_down_multiplier_hotplug6 >= 0 && zzmoove_profiles[i].block_down_multiplier_hotplug6 <= 25)
dbs_tuners_ins.block_down_multiplier_hotplug6 = zzmoove_profiles[i].block_down_multiplier_hotplug6;
// ZZ: set down_threshold_hotplug7 value
if ((zzmoove_profiles[i].down_threshold_hotplug7 <= 100
&& zzmoove_profiles[i].down_threshold_hotplug7 >= 1)
|| zzmoove_profiles[i].down_threshold_hotplug7 == 0) {
dbs_tuners_ins.down_threshold_hotplug7 = zzmoove_profiles[i].down_threshold_hotplug7;
hotplug_thresholds[1][6] = zzmoove_profiles[i].down_threshold_hotplug7;
}
// ff: set block up multiplier for hotplug7
if (zzmoove_profiles[i].block_up_multiplier_hotplug7 >= 0 && zzmoove_profiles[i].block_up_multiplier_hotplug7 <= 25)
dbs_tuners_ins.block_up_multiplier_hotplug7 = zzmoove_profiles[i].block_up_multiplier_hotplug7;
// ff: set block down multiplier for hotplug7
if (zzmoove_profiles[i].block_down_multiplier_hotplug7 >= 0 && zzmoove_profiles[i].block_down_multiplier_hotplug7 <= 25)
dbs_tuners_ins.block_down_multiplier_hotplug7 = zzmoove_profiles[i].block_down_multiplier_hotplug7;
#endif /* (MAX_CORES == 8) */
// ZZ: set down_threshold_hotplug_freq1 value
if (zzmoove_profiles[i].down_threshold_hotplug_freq1 == 0) {
dbs_tuners_ins.down_threshold_hotplug_freq1 = zzmoove_profiles[i].down_threshold_hotplug_freq1;
hotplug_thresholds_freq[1][0] = zzmoove_profiles[i].down_threshold_hotplug_freq1;
}
zzmoove_profiles[i].down_threshold_hotplug_freq1 = check_frequency(zzmoove_profiles[i].down_threshold_hotplug_freq1);
if (system_freq_table && zzmoove_profiles[i].down_threshold_hotplug_freq1 <= system_freq_table[max_scaling_freq_hard].frequency) {
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].down_threshold_hotplug_freq1) {
dbs_tuners_ins.down_threshold_hotplug_freq1 = zzmoove_profiles[i].down_threshold_hotplug_freq1;
hotplug_thresholds_freq[1][0] = zzmoove_profiles[i].down_threshold_hotplug_freq1;
}
}
}
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
// ZZ: set down_threshold_hotplug_freq2 value
if (zzmoove_profiles[i].down_threshold_hotplug_freq2 == 0) {
dbs_tuners_ins.down_threshold_hotplug_freq2 = zzmoove_profiles[i].down_threshold_hotplug_freq2;
hotplug_thresholds_freq[1][1] = zzmoove_profiles[i].down_threshold_hotplug_freq2;
}
zzmoove_profiles[i].down_threshold_hotplug_freq2 = check_frequency(zzmoove_profiles[i].down_threshold_hotplug_freq2);
if (system_freq_table && zzmoove_profiles[i].down_threshold_hotplug_freq2 <= system_freq_table[max_scaling_freq_hard].frequency) {
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].down_threshold_hotplug_freq2) {
dbs_tuners_ins.down_threshold_hotplug_freq2 = zzmoove_profiles[i].down_threshold_hotplug_freq2;
hotplug_thresholds_freq[1][1] = zzmoove_profiles[i].down_threshold_hotplug_freq2;
}
}
}
// ZZ: set down_threshold_hotplug_freq3 value
if (zzmoove_profiles[i].down_threshold_hotplug_freq3 == 0) {
dbs_tuners_ins.down_threshold_hotplug_freq3 = zzmoove_profiles[i].down_threshold_hotplug_freq3;
hotplug_thresholds_freq[1][2] = zzmoove_profiles[i].down_threshold_hotplug_freq3;
}
zzmoove_profiles[i].down_threshold_hotplug_freq3 = check_frequency(zzmoove_profiles[i].down_threshold_hotplug_freq3);
if (system_freq_table && zzmoove_profiles[i].down_threshold_hotplug_freq3 <= system_freq_table[max_scaling_freq_hard].frequency) {
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].down_threshold_hotplug_freq3) {
dbs_tuners_ins.down_threshold_hotplug_freq3 = zzmoove_profiles[i].down_threshold_hotplug_freq3;
hotplug_thresholds_freq[1][2] = zzmoove_profiles[i].down_threshold_hotplug_freq3;
}
}
}
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
// ZZ: set down_threshold_hotplug_freq4 value
if (zzmoove_profiles[i].down_threshold_hotplug_freq4 == 0) {
dbs_tuners_ins.down_threshold_hotplug_freq4 = zzmoove_profiles[i].down_threshold_hotplug_freq4;
hotplug_thresholds_freq[1][3] = zzmoove_profiles[i].down_threshold_hotplug_freq4;
}
zzmoove_profiles[i].down_threshold_hotplug_freq4 = check_frequency(zzmoove_profiles[i].down_threshold_hotplug_freq4);
if (system_freq_table && zzmoove_profiles[i].down_threshold_hotplug_freq4 <= system_freq_table[max_scaling_freq_hard].frequency) {
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].down_threshold_hotplug_freq4) {
dbs_tuners_ins.down_threshold_hotplug_freq4 = zzmoove_profiles[i].down_threshold_hotplug_freq4;
hotplug_thresholds_freq[1][3] = zzmoove_profiles[i].down_threshold_hotplug_freq4;
}
}
}
// ZZ: set down_threshold_hotplug_freq5 value
if (zzmoove_profiles[i].down_threshold_hotplug_freq5 == 0) {
dbs_tuners_ins.down_threshold_hotplug_freq5 = zzmoove_profiles[i].down_threshold_hotplug_freq5;
hotplug_thresholds_freq[1][4] = zzmoove_profiles[i].down_threshold_hotplug_freq5;
}
zzmoove_profiles[i].down_threshold_hotplug_freq5 = check_frequency(zzmoove_profiles[i].down_threshold_hotplug_freq5);
if (system_freq_table && zzmoove_profiles[i].down_threshold_hotplug_freq5 <= system_freq_table[max_scaling_freq_hard].frequency) {
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].down_threshold_hotplug_freq5) {
dbs_tuners_ins.down_threshold_hotplug_freq5 = zzmoove_profiles[i].down_threshold_hotplug_freq5;
hotplug_thresholds_freq[1][4] = zzmoove_profiles[i].down_threshold_hotplug_freq5;
}
}
}
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
// ZZ: set down_threshold_hotplug_freq6 value
if (zzmoove_profiles[i].down_threshold_hotplug_freq6 == 0) {
dbs_tuners_ins.down_threshold_hotplug_freq6 = zzmoove_profiles[i].down_threshold_hotplug_freq6;
hotplug_thresholds_freq[1][5] = zzmoove_profiles[i].down_threshold_hotplug_freq6;
}
zzmoove_profiles[i].down_threshold_hotplug_freq6 = check_frequency(zzmoove_profiles[i].down_threshold_hotplug_freq6);
if (system_freq_table && zzmoove_profiles[i].down_threshold_hotplug_freq6 <= system_freq_table[max_scaling_freq_hard].frequency) {
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].down_threshold_hotplug_freq6) {
dbs_tuners_ins.down_threshold_hotplug_freq6 = zzmoove_profiles[i].down_threshold_hotplug_freq6;
hotplug_thresholds_freq[1][5] = zzmoove_profiles[i].down_threshold_hotplug_freq6;
}
}
}
// ZZ: set down_threshold_hotplug_freq7 value
if (zzmoove_profiles[i].down_threshold_hotplug_freq7 == 0) {
dbs_tuners_ins.down_threshold_hotplug_freq7 = zzmoove_profiles[i].down_threshold_hotplug_freq7;
hotplug_thresholds_freq[1][6] = zzmoove_profiles[i].down_threshold_hotplug_freq7;
}
zzmoove_profiles[i].down_threshold_hotplug_freq7 = check_frequency(zzmoove_profiles[i].down_threshold_hotplug_freq7);
if (system_freq_table && zzmoove_profiles[i].down_threshold_hotplug_freq7 <= system_freq_table[max_scaling_freq_hard].frequency) {
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].down_threshold_hotplug_freq7) {
dbs_tuners_ins.down_threshold_hotplug_freq7 = zzmoove_profiles[i].down_threshold_hotplug_freq7;
hotplug_thresholds_freq[1][6] = zzmoove_profiles[i].down_threshold_hotplug_freq7;
}
}
}
#endif /* (MAX_CORES == 8) */
#endif /* ENABLE_HOTPLUGGING */
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
// ZZ: set down_threshold_sleep value
if (zzmoove_profiles[i].down_threshold_sleep > 11 && zzmoove_profiles[i].down_threshold_sleep <= 100
&& zzmoove_profiles[i].down_threshold_sleep < dbs_tuners_ins.up_threshold_sleep)
dbs_tuners_ins.down_threshold_sleep = zzmoove_profiles[i].down_threshold_sleep;
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
// ZZ: set early_demand value
dbs_tuners_ins.early_demand = !!zzmoove_profiles[i].early_demand;
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
dbs_tuners_ins.early_demand_sleep = !!zzmoove_profiles[i].early_demand_sleep;
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
// Yank: set fast_scaling value
if (zzmoove_profiles[i].fast_scaling_up <= 5 && zzmoove_profiles[i].fast_scaling_up >= 0) {
dbs_tuners_ins.fast_scaling_up = zzmoove_profiles[i].fast_scaling_up;
if (zzmoove_profiles[i].fast_scaling_up > 4)
scaling_mode_up = 0;
else
scaling_mode_up = zzmoove_profiles[i].fast_scaling_up;
}
if (zzmoove_profiles[i].fast_scaling_down <= 5 && zzmoove_profiles[i].fast_scaling_down >= 0) {
dbs_tuners_ins.fast_scaling_down = zzmoove_profiles[i].fast_scaling_down;
if (zzmoove_profiles[i].fast_scaling_down > 4)
scaling_mode_down = 0;
else
scaling_mode_down = zzmoove_profiles[i].fast_scaling_down;
}
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
// ZZ: set fast_scaling_sleep value
if (zzmoove_profiles[i].fast_scaling_sleep_up <= 5 && zzmoove_profiles[i].fast_scaling_sleep_up >= 0)
dbs_tuners_ins.fast_scaling_sleep_up = zzmoove_profiles[i].fast_scaling_sleep_up;
if (zzmoove_profiles[i].fast_scaling_sleep_down <= 5 && zzmoove_profiles[i].fast_scaling_sleep_down >= 0)
dbs_tuners_ins.fast_scaling_sleep_down = zzmoove_profiles[i].fast_scaling_sleep_down;
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
// ZZ: set afs_threshold1 value
if (zzmoove_profiles[i].afs_threshold1 <= 100)
dbs_tuners_ins.afs_threshold1 = zzmoove_profiles[i].afs_threshold1;
// ZZ: set afs_threshold2 value
if (zzmoove_profiles[i].afs_threshold2 <= 100)
dbs_tuners_ins.afs_threshold2 = zzmoove_profiles[i].afs_threshold2;
// ZZ: set afs_threshold3 value
if (zzmoove_profiles[i].afs_threshold3 <= 100)
dbs_tuners_ins.afs_threshold3 = zzmoove_profiles[i].afs_threshold3;
// ZZ: set afs_threshold4 value
if (zzmoove_profiles[i].afs_threshold4 <= 100)
dbs_tuners_ins.afs_threshold4 = zzmoove_profiles[i].afs_threshold4;
// ZZ: set freq_limit value
if (system_freq_table && zzmoove_profiles[i].freq_limit == 0) {
max_scaling_freq_soft = max_scaling_freq_hard;
if (freq_table_desc)
limit_table_start = max_scaling_freq_soft;
else
limit_table_end = system_freq_table[freq_table_size].frequency;
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
freq_limit_awake = dbs_tuners_ins.freq_limit = zzmoove_profiles[i].freq_limit;
#else
dbs_tuners_ins.freq_limit = zzmoove_profiles[i].freq_limit;
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
} else if (system_freq_table && zzmoove_profiles[i].freq_limit <= system_freq_table[max_scaling_freq_hard].frequency) {
zzmoove_profiles[i].freq_limit = check_frequency(zzmoove_profiles[i].freq_limit);
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].freq_limit) {
max_scaling_freq_soft = t;
if (freq_table_desc)
limit_table_start = max_scaling_freq_soft;
else
limit_table_end = system_freq_table[t].frequency;
}
}
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
freq_limit_awake = dbs_tuners_ins.freq_limit = zzmoove_profiles[i].freq_limit;
#else
dbs_tuners_ins.freq_limit = zzmoove_profiles[i].freq_limit;
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
}
// ZZ: set freq_limit_sleep value
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
if (system_freq_table && zzmoove_profiles[i].freq_limit_sleep == 0) {
freq_limit_asleep = dbs_tuners_ins.freq_limit_sleep = zzmoove_profiles[i].freq_limit_sleep;
} else if (system_freq_table && zzmoove_profiles[i].freq_limit_sleep <= system_freq_table[max_scaling_freq_hard].frequency) {
zzmoove_profiles[i].freq_limit_sleep = check_frequency(zzmoove_profiles[i].freq_limit_sleep);
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].freq_limit_sleep)
freq_limit_asleep = dbs_tuners_ins.freq_limit_sleep = zzmoove_profiles[i].freq_limit_sleep;
}
}
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
// ZZ: set grad_up_threshold value
if (zzmoove_profiles[i].grad_up_threshold < 100 && zzmoove_profiles[i].grad_up_threshold > 1)
dbs_tuners_ins.grad_up_threshold = zzmoove_profiles[i].grad_up_threshold;
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
// ZZ: set grad_up_threshold sleep value
if (zzmoove_profiles[i].grad_up_threshold_sleep < 100 && zzmoove_profiles[i].grad_up_threshold_sleep > 1)
dbs_tuners_ins.grad_up_threshold_sleep = zzmoove_profiles[i].grad_up_threshold_sleep;
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_HOTPLUGGING
// ZZ: set hotplug_block_up_cycles value
if (zzmoove_profiles[i].hotplug_block_up_cycles >= 0)
dbs_tuners_ins.hotplug_block_up_cycles = zzmoove_profiles[i].hotplug_block_up_cycles;
// ZZ: set hotplug_block_down_cycles value
if (zzmoove_profiles[i].hotplug_block_down_cycles >= 0)
dbs_tuners_ins.hotplug_block_down_cycles = zzmoove_profiles[i].hotplug_block_down_cycles;
// ff: set hotplug_stagger_up value
if (zzmoove_profiles[i].hotplug_stagger_up >= 0)
dbs_tuners_ins.hotplug_stagger_up = zzmoove_profiles[i].hotplug_stagger_up;
// ff: set hotplug_stagger_down value
if (zzmoove_profiles[i].hotplug_stagger_down >= 0)
dbs_tuners_ins.hotplug_stagger_down = zzmoove_profiles[i].hotplug_stagger_down;
// ZZ: set hotplug_idle_threshold value
if (zzmoove_profiles[i].hotplug_idle_threshold >= 0 && zzmoove_profiles[i].hotplug_idle_threshold < 100)
dbs_tuners_ins.hotplug_idle_threshold = zzmoove_profiles[i].hotplug_idle_threshold;
// ZZ: set hotplug_idle_freq value
if (zzmoove_profiles[i].hotplug_idle_freq == 0) {
dbs_tuners_ins.hotplug_idle_freq = zzmoove_profiles[i].hotplug_idle_freq;
} else if (system_freq_table && zzmoove_profiles[i].hotplug_idle_freq <= system_freq_table[max_scaling_freq_hard].frequency) {
zzmoove_profiles[i].hotplug_idle_freq = check_frequency(zzmoove_profiles[i].hotplug_idle_freq);
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].hotplug_idle_freq) {
dbs_tuners_ins.hotplug_idle_freq = zzmoove_profiles[i].hotplug_idle_freq;
}
}
}
// ZZ: set hotplug_engage_freq value
if (zzmoove_profiles[i].hotplug_engage_freq == 0) {
dbs_tuners_ins.hotplug_engage_freq = zzmoove_profiles[i].hotplug_engage_freq;
} else if (system_freq_table && zzmoove_profiles[i].hotplug_engage_freq <= system_freq_table[max_scaling_freq_hard].frequency) {
zzmoove_profiles[i].hotplug_engage_freq = check_frequency(zzmoove_profiles[i].hotplug_engage_freq);
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].hotplug_engage_freq) {
dbs_tuners_ins.hotplug_engage_freq = zzmoove_profiles[i].hotplug_engage_freq;
}
}
}
// ff: set hotplug_max_limit value
if (zzmoove_profiles[i].hotplug_max_limit >= 0 && zzmoove_profiles[i].hotplug_max_limit < MAX_CORES)
dbs_tuners_ins.hotplug_max_limit = zzmoove_profiles[i].hotplug_max_limit;
// ff: set hotplug_min_limit value
if (zzmoove_profiles[i].hotplug_min_limit >= 0 && zzmoove_profiles[i].hotplug_min_limit < MAX_CORES)
dbs_tuners_ins.hotplug_min_limit = zzmoove_profiles[i].hotplug_min_limit;
// ff: set hotplug_lock value
if (zzmoove_profiles[i].hotplug_lock >= 0 && zzmoove_profiles[i].hotplug_lock < MAX_CORES)
dbs_tuners_ins.hotplug_lock = zzmoove_profiles[i].hotplug_lock;
#endif /* ENABLE_HOTPLUGGING */
#ifdef ENABLE_MUSIC_LIMITS
#ifdef ENABLE_HOTPLUGGING
// ZZ: set music min cores value
if (zzmoove_profiles[i].music_min_cores >= 0 && zzmoove_profiles[i].music_min_cores < MAX_CORES)
dbs_tuners_ins.music_min_cores = zzmoove_profiles[i].music_min_cores;
#endif /* ENABLE_HOTPLUGGING */
// ZZ: set music min freq value
if (zzmoove_profiles[i].music_min_freq == 0) {
dbs_tuners_ins.music_min_freq = zzmoove_profiles[i].music_min_freq;
} else if (system_freq_table && zzmoove_profiles[i].music_min_freq <= system_freq_table[max_scaling_freq_hard].frequency) {
zzmoove_profiles[i].music_min_freq = check_frequency(zzmoove_profiles[i].music_min_freq);
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].music_min_freq) {
dbs_tuners_ins.music_min_freq = zzmoove_profiles[i].music_min_freq;
}
}
}
// ZZ: set music max freq value
if (zzmoove_profiles[i].music_max_freq == 0) {
dbs_tuners_ins.music_max_freq = zzmoove_profiles[i].music_max_freq;
} else if (system_freq_table && zzmoove_profiles[i].music_max_freq <= system_freq_table[max_scaling_freq_hard].frequency) {
zzmoove_profiles[i].music_max_freq = check_frequency(zzmoove_profiles[i].music_max_freq);
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].music_max_freq) {
dbs_tuners_ins.music_max_freq = zzmoove_profiles[i].music_max_freq;
}
}
}
#endif /* ENABLE_MUSIC_LIMITS */
// ZZ: set scaling_responsiveness_freq value
if (zzmoove_profiles[i].scaling_responsiveness_freq == 0) {
dbs_tuners_ins.scaling_responsiveness_freq = zzmoove_profiles[i].scaling_responsiveness_freq;
} else if (system_freq_table && zzmoove_profiles[i].scaling_responsiveness_freq <= system_freq_table[max_scaling_freq_hard].frequency) {
zzmoove_profiles[i].scaling_responsiveness_freq = check_frequency(zzmoove_profiles[i].scaling_responsiveness_freq);
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].scaling_responsiveness_freq) {
dbs_tuners_ins.scaling_responsiveness_freq = zzmoove_profiles[i].scaling_responsiveness_freq;
}
}
}
// ZZ: set scaling_proportional value
if (zzmoove_profiles[i].scaling_proportional > 3) {
dbs_tuners_ins.scaling_proportional = 3;
} else if (zzmoove_profiles[i].scaling_proportional < 0) {
dbs_tuners_ins.scaling_proportional = 1;
} else {
dbs_tuners_ins.scaling_proportional = zzmoove_profiles[i].scaling_proportional;
}
#ifdef ENABLE_INPUTBOOSTER
// ZZ: set inputboost cycles value
if (zzmoove_profiles[i].inputboost_cycles >= 0 && zzmoove_profiles[i].inputboost_cycles <= 1000) {
if (!zzmoove_profiles[i].inputboost_cycles && dbs_tuners_ins.inputboost_cycles != zzmoove_profiles[i].inputboost_cycles) {
// ff: input is 0, and it wasn't before.
// ff: so remove booster and unregister.
input_unregister_handler(&interactive_input_handler);
} else if (zzmoove_profiles[i].inputboost_cycles && dbs_tuners_ins.inputboost_cycles == 0) {
// ff: input is something other than 0, and it wasn't before,
// ff: so add booster and register.
rc = input_register_handler(&interactive_input_handler);
if (!rc)
pr_info("[zzmoove/store_inputboost_cycles] inputbooster - registered\n");
else
pr_info("[zzmoove/store_inputboost_cycles] inputbooster - register FAILED\n");
}
dbs_tuners_ins.inputboost_cycles = zzmoove_profiles[i].inputboost_cycles;
}
// ZZ: set inputboost up threshold value
if (zzmoove_profiles[i].inputboost_up_threshold <= 100)
dbs_tuners_ins.inputboost_up_threshold = zzmoove_profiles[i].inputboost_up_threshold;
// ZZ: set inputboost punch cycles value
if (zzmoove_profiles[i].inputboost_punch_cycles >= 0)
dbs_tuners_ins.inputboost_punch_cycles = zzmoove_profiles[i].inputboost_punch_cycles;
// ZZ: set inputboost freq value
if (zzmoove_profiles[i].inputboost_punch_freq == 0) {
dbs_tuners_ins.inputboost_punch_freq = zzmoove_profiles[i].inputboost_punch_freq;
} else if (system_freq_table && zzmoove_profiles[i].inputboost_punch_freq <= system_freq_table[max_scaling_freq_hard].frequency) {
zzmoove_profiles[i].inputboost_punch_freq = check_frequency(zzmoove_profiles[i].inputboost_punch_freq);
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].inputboost_punch_freq) {
dbs_tuners_ins.inputboost_punch_freq = zzmoove_profiles[i].inputboost_punch_freq;
}
}
}
// ZZ: set inputboost punch punch on finger down value
if (zzmoove_profiles[i].inputboost_punch_on_fingerdown >= 0)
dbs_tuners_ins.inputboost_punch_on_fingerdown = zzmoove_profiles[i].inputboost_punch_on_fingerdown;
// ZZ: set inputboost punch punch on finger move value
if (zzmoove_profiles[i].inputboost_punch_on_fingermove >= 0)
dbs_tuners_ins.inputboost_punch_on_fingermove = zzmoove_profiles[i].inputboost_punch_on_fingermove;
// ZZ: set inputboost punch punch on epen move value
if (zzmoove_profiles[i].inputboost_punch_on_epenmove >= 0)
dbs_tuners_ins.inputboost_punch_on_epenmove = zzmoove_profiles[i].inputboost_punch_on_epenmove;
// ZZ: set inputboost up threshold value
if (zzmoove_profiles[i].inputboost_typingbooster_up_threshold <= 100)
dbs_tuners_ins.inputboost_typingbooster_up_threshold = zzmoove_profiles[i].inputboost_typingbooster_up_threshold;
#ifdef ENABLE_HOTPLUGGING
// ZZ: set inputboost cores value
if (zzmoove_profiles[i].inputboost_typingbooster_cores >= 0 && zzmoove_profiles[i].inputboost_typingbooster_cores < MAX_CORES)
dbs_tuners_ins.inputboost_typingbooster_cores = zzmoove_profiles[i].inputboost_typingbooster_cores;
#endif /* ENABLE_HOTPLUGGING */
#endif /* ENABLE_INPUTBOOSTER */
// ZZ: set scaling_responsiveness_up_threshold value
if (zzmoove_profiles[i].scaling_responsiveness_up_threshold <= 100 && zzmoove_profiles[i].scaling_responsiveness_up_threshold >= 11)
dbs_tuners_ins.scaling_responsiveness_up_threshold = zzmoove_profiles[i].scaling_responsiveness_up_threshold;
// ZZ: set ignore_nice_load value
if (zzmoove_profiles[i].ignore_nice_load > 1)
zzmoove_profiles[i].ignore_nice_load = 1;
dbs_tuners_ins.ignore_nice = zzmoove_profiles[i].ignore_nice_load;
// we need to re-evaluate prev_cpu_idle
for_each_online_cpu(j) {
struct cpu_dbs_info_s *dbs_info;
dbs_info = &per_cpu(cs_cpu_dbs_info, j);
dbs_info->prev_cpu_idle = get_cpu_idle_time(j,
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0) || defined(CPU_IDLE_TIME_IN_CPUFREQ) /* overrule for sources with backported cpufreq implementation */
&dbs_info->prev_cpu_wall, 0);
#else
&dbs_info->prev_cpu_wall);
#endif /* LINUX_VERSION_CODE... */
if (dbs_tuners_ins.ignore_nice)
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,4,0)
dbs_info->prev_cpu_nice = kcpustat_cpu(j).cpustat[CPUTIME_NICE];
#else
dbs_info->prev_cpu_nice = kstat_cpu(j).cpustat.nice;
#endif /* LINUX_VERSION_CODE... */
}
// ZZ: set sampling_down_factor value
if (zzmoove_profiles[i].sampling_down_factor <= MAX_SAMPLING_DOWN_FACTOR
&& zzmoove_profiles[i].sampling_down_factor >= 1)
dbs_tuners_ins.sampling_down_factor = zz_sampling_down_factor = zzmoove_profiles[i].sampling_down_factor;
// ZZ: Reset down sampling multiplier in case it was active
for_each_online_cpu(j) {
struct cpu_dbs_info_s *dbs_info;
dbs_info = &per_cpu(cs_cpu_dbs_info, j);
dbs_info->rate_mult = 1;
}
// ZZ: set sampling_down_max_momentum value
if (zzmoove_profiles[i].sampling_down_max_momentum <= MAX_SAMPLING_DOWN_FACTOR - dbs_tuners_ins.sampling_down_factor
&& zzmoove_profiles[i].sampling_down_max_momentum >= 0) {
dbs_tuners_ins.sampling_down_max_mom = zz_sampling_down_max_mom = zzmoove_profiles[i].sampling_down_max_momentum;
orig_sampling_down_max_mom = dbs_tuners_ins.sampling_down_max_mom;
}
// ZZ: Reset sampling down factor to default if momentum was disabled
if (dbs_tuners_ins.sampling_down_max_mom == 0)
zz_sampling_down_factor = DEF_SAMPLING_DOWN_FACTOR;
// ZZ: Reset momentum_adder and reset down sampling multiplier in case momentum was disabled
for_each_online_cpu(j) {
struct cpu_dbs_info_s *dbs_info;
dbs_info = &per_cpu(cs_cpu_dbs_info, j);
dbs_info->momentum_adder = 0;
if (dbs_tuners_ins.sampling_down_max_mom == 0)
dbs_info->rate_mult = 1;
}
// ZZ: set sampling_down_momentum_sensitivity value
if (zzmoove_profiles[i].sampling_down_momentum_sensitivity <= MAX_SAMPLING_DOWN_MOMENTUM_SENSITIVITY
&& zzmoove_profiles[i].sampling_down_momentum_sensitivity >= 1) {
dbs_tuners_ins.sampling_down_mom_sens = zzmoove_profiles[i].sampling_down_momentum_sensitivity;
// ZZ: Reset momentum_adder
for_each_online_cpu(j) {
struct cpu_dbs_info_s *dbs_info;
dbs_info = &per_cpu(cs_cpu_dbs_info, j);
dbs_info->momentum_adder = 0;
}
// ZZ: set sampling_rate value
dbs_tuners_ins.sampling_rate = dbs_tuners_ins.sampling_rate_current
= max(zzmoove_profiles[i].sampling_rate, min_sampling_rate);
// ZZ: set sampling_rate_idle value
if (zzmoove_profiles[i].sampling_rate_idle == 0) {
dbs_tuners_ins.sampling_rate_current = dbs_tuners_ins.sampling_rate
= dbs_tuners_ins.sampling_rate_idle;
} else {
dbs_tuners_ins.sampling_rate_idle = max(zzmoove_profiles[i].sampling_rate_idle, min_sampling_rate);
}
// ZZ: set sampling_rate_idle_delay value
if (zzmoove_profiles[i].sampling_rate_idle_delay >= 0) {
sampling_rate_step_up_delay = 0;
sampling_rate_step_down_delay = 0;
dbs_tuners_ins.sampling_rate_idle_delay = zzmoove_profiles[i].sampling_rate_idle_delay;
}
// ZZ: set sampling_rate_idle_threshold value
if (zzmoove_profiles[i].sampling_rate_idle_threshold <= 100)
dbs_tuners_ins.sampling_rate_idle_threshold = zzmoove_profiles[i].sampling_rate_idle_threshold;
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
// ZZ: set sampling_rate_sleep_multiplier value
if (zzmoove_profiles[i].sampling_rate_sleep_multiplier <= MAX_SAMPLING_RATE_SLEEP_MULTIPLIER
&& zzmoove_profiles[i].sampling_rate_sleep_multiplier >= 1)
dbs_tuners_ins.sampling_rate_sleep_multiplier = zzmoove_profiles[i].sampling_rate_sleep_multiplier;
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
// ZZ: set scaling_block_cycles value
if (zzmoove_profiles[i].scaling_block_cycles >= 0) {
dbs_tuners_ins.scaling_block_cycles = zzmoove_profiles[i].scaling_block_cycles;
if (zzmoove_profiles[i].scaling_block_cycles == 0)
scaling_block_cycles_count = 0;
}
#ifdef CONFIG_EXYNOS4_EXPORT_TEMP
// ZZ: set scaling_block_temp value
if ((zzmoove_profiles[i].scaling_block_temp >= 30 && zzmoove_profiles[i].scaling_block_temp <= 80)
|| zzmoove_profiles[i].scaling_block_temp == 0) {
dbs_tuners_ins.scaling_block_temp = zzmoove_profiles[i].scaling_block_temp;
}
#endif /* CONFIG_EXYNOS4_EXPORT_TEMP */
// ZZ: set scaling_block_freq value
if (zzmoove_profiles[i].scaling_block_freq == 0) {
dbs_tuners_ins.scaling_block_freq = zzmoove_profiles[i].scaling_block_freq;
} else if (system_freq_table && zzmoove_profiles[i].scaling_block_freq <= system_freq_table[max_scaling_freq_hard].frequency) {
zzmoove_profiles[i].scaling_block_freq = check_frequency(zzmoove_profiles[i].scaling_block_freq);
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].scaling_block_freq) {
dbs_tuners_ins.scaling_block_freq = zzmoove_profiles[i].scaling_block_freq;
}
}
}
// ZZ: set scaling_block_threshold value
if (zzmoove_profiles[i].scaling_block_threshold >= 0
&& zzmoove_profiles[i].scaling_block_threshold <= 100)
dbs_tuners_ins.scaling_block_threshold = zzmoove_profiles[i].scaling_block_threshold;
// ZZ: set scaling_block_force_down value
if (zzmoove_profiles[i].scaling_block_force_down >= 0
&& zzmoove_profiles[i].scaling_block_force_down != 1)
dbs_tuners_ins.scaling_block_force_down = zzmoove_profiles[i].scaling_block_force_down;
// ZZ: set scaling_fastdown_freq value
if (zzmoove_profiles[i].scaling_fastdown_freq == 0) {
dbs_tuners_ins.scaling_fastdown_freq = zzmoove_profiles[i].scaling_fastdown_freq;
} else if (system_freq_table && zzmoove_profiles[i].scaling_fastdown_freq <= system_freq_table[max_scaling_freq_hard].frequency) {
zzmoove_profiles[i].scaling_fastdown_freq = check_frequency(zzmoove_profiles[i].scaling_fastdown_freq);
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].scaling_fastdown_freq) {
dbs_tuners_ins.scaling_fastdown_freq = zzmoove_profiles[i].scaling_fastdown_freq;
}
}
}
// ZZ: set scaling_fastdown_up_threshold value
if (zzmoove_profiles[i].scaling_fastdown_up_threshold <= 100 && zzmoove_profiles[i].scaling_fastdown_up_threshold
> zzmoove_profiles[i].scaling_fastdown_down_threshold)
dbs_tuners_ins.scaling_fastdown_up_threshold = zzmoove_profiles[i].scaling_fastdown_up_threshold;
// ZZ: set scaling_fastdown_down_threshold value
if (zzmoove_profiles[i].scaling_fastdown_down_threshold < zzmoove_profiles[i].scaling_fastdown_up_threshold
&& zzmoove_profiles[i].scaling_fastdown_down_threshold > 11)
dbs_tuners_ins.scaling_fastdown_down_threshold = zzmoove_profiles[i].scaling_fastdown_down_threshold;
// ZZ: set smooth_up value
if (zzmoove_profiles[i].smooth_up <= 100 && zzmoove_profiles[i].smooth_up >= 1)
dbs_tuners_ins.smooth_up = zzmoove_profiles[i].smooth_up;
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
// ZZ: set smooth_up_sleep value
if (zzmoove_profiles[i].smooth_up_sleep <= 100 && zzmoove_profiles[i].smooth_up_sleep >= 1)
dbs_tuners_ins.smooth_up_sleep = zzmoove_profiles[i].smooth_up_sleep;
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
// ZZ: set up_threshold value
if (zzmoove_profiles[i].up_threshold <= 100 && zzmoove_profiles[i].up_threshold
>= zzmoove_profiles[i].down_threshold)
dbs_tuners_ins.up_threshold = zzmoove_profiles[i].up_threshold;
#ifdef ENABLE_HOTPLUGGING
// ZZ: set up_threshold_hotplug1 value
if (zzmoove_profiles[i].up_threshold_hotplug1 >= 0 && zzmoove_profiles[i].up_threshold_hotplug1 <= 100) {
dbs_tuners_ins.up_threshold_hotplug1 = zzmoove_profiles[i].up_threshold_hotplug1;
hotplug_thresholds[0][0] = zzmoove_profiles[i].up_threshold_hotplug1;
}
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
// ZZ: set up_threshold_hotplug2 value
if (zzmoove_profiles[i].up_threshold_hotplug2 >= 0 && zzmoove_profiles[i].up_threshold_hotplug2 <= 100) {
dbs_tuners_ins.up_threshold_hotplug2 = zzmoove_profiles[i].up_threshold_hotplug2;
hotplug_thresholds[0][1] = zzmoove_profiles[i].up_threshold_hotplug2;
}
// ZZ: set up_threshold_hotplug3 value
if (zzmoove_profiles[i].up_threshold_hotplug3 >= 0 && zzmoove_profiles[i].up_threshold_hotplug3 <= 100) {
dbs_tuners_ins.up_threshold_hotplug3 = zzmoove_profiles[i].up_threshold_hotplug3;
hotplug_thresholds[0][2] = zzmoove_profiles[i].up_threshold_hotplug3;
}
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
// ZZ: set up_threshold_hotplug4 value
if (zzmoove_profiles[i].up_threshold_hotplug4 >= 0 && zzmoove_profiles[i].up_threshold_hotplug4 <= 100) {
dbs_tuners_ins.up_threshold_hotplug4 = zzmoove_profiles[i].up_threshold_hotplug4;
hotplug_thresholds[0][3] = zzmoove_profiles[i].up_threshold_hotplug4;
}
// ZZ: set up_threshold_hotplug5 value
if (zzmoove_profiles[i].up_threshold_hotplug5 >= 0 && zzmoove_profiles[i].up_threshold_hotplug5 <= 100) {
dbs_tuners_ins.up_threshold_hotplug5 = zzmoove_profiles[i].up_threshold_hotplug5;
hotplug_thresholds[0][4] = zzmoove_profiles[i].up_threshold_hotplug5;
}
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
// ZZ: set up_threshold_hotplug6 value
if (zzmoove_profiles[i].up_threshold_hotplug6 >= 0 && zzmoove_profiles[i].up_threshold_hotplug6 <= 100) {
dbs_tuners_ins.up_threshold_hotplug6 = zzmoove_profiles[i].up_threshold_hotplug6;
hotplug_thresholds[0][5] = zzmoove_profiles[i].up_threshold_hotplug6;
}
// ZZ: set up_threshold_hotplug7 value
if (zzmoove_profiles[i].up_threshold_hotplug7 >= 0 && zzmoove_profiles[i].up_threshold_hotplug7 <= 100) {
dbs_tuners_ins.up_threshold_hotplug7 = zzmoove_profiles[i].up_threshold_hotplug7;
hotplug_thresholds[0][6] = zzmoove_profiles[i].up_threshold_hotplug7;
}
#endif /* (MAX_CORES == 8) */
// ZZ: set up_threshold_hotplug_freq1 value
if (zzmoove_profiles[i].up_threshold_hotplug_freq1 == 0) {
dbs_tuners_ins.up_threshold_hotplug_freq1 = zzmoove_profiles[i].up_threshold_hotplug_freq1;
hotplug_thresholds_freq[0][0] = zzmoove_profiles[i].up_threshold_hotplug_freq1;
}
if (system_freq_table && zzmoove_profiles[i].up_threshold_hotplug_freq1 <= system_freq_table[max_scaling_freq_hard].frequency) {
zzmoove_profiles[i].up_threshold_hotplug_freq1 = check_frequency(zzmoove_profiles[i].up_threshold_hotplug_freq1);
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].up_threshold_hotplug_freq1) {
dbs_tuners_ins.up_threshold_hotplug_freq1 = zzmoove_profiles[i].up_threshold_hotplug_freq1;
hotplug_thresholds_freq[0][0] = zzmoove_profiles[i].up_threshold_hotplug_freq1;
}
}
}
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
// ZZ: set up_threshold_hotplug_freq2 value
if (zzmoove_profiles[i].up_threshold_hotplug_freq2 == 0) {
dbs_tuners_ins.up_threshold_hotplug_freq2 = zzmoove_profiles[i].up_threshold_hotplug_freq2;
hotplug_thresholds_freq[0][1] = zzmoove_profiles[i].up_threshold_hotplug_freq2;
}
if (system_freq_table && zzmoove_profiles[i].up_threshold_hotplug_freq2 <= system_freq_table[max_scaling_freq_hard].frequency) {
zzmoove_profiles[i].up_threshold_hotplug_freq2 = check_frequency(zzmoove_profiles[i].up_threshold_hotplug_freq2);
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].up_threshold_hotplug_freq2) {
dbs_tuners_ins.up_threshold_hotplug_freq2 = zzmoove_profiles[i].up_threshold_hotplug_freq2;
hotplug_thresholds_freq[0][1] = zzmoove_profiles[i].up_threshold_hotplug_freq2;
}
}
}
// ZZ: set up_threshold_hotplug_freq3 value
if (zzmoove_profiles[i].up_threshold_hotplug_freq3 == 0) {
dbs_tuners_ins.up_threshold_hotplug_freq3 = zzmoove_profiles[i].up_threshold_hotplug_freq3;
hotplug_thresholds_freq[0][2] = zzmoove_profiles[i].up_threshold_hotplug_freq3;
}
if (system_freq_table && zzmoove_profiles[i].up_threshold_hotplug_freq3 <= system_freq_table[max_scaling_freq_hard].frequency) {
zzmoove_profiles[i].up_threshold_hotplug_freq3 = check_frequency(zzmoove_profiles[i].up_threshold_hotplug_freq3);
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].up_threshold_hotplug_freq3) {
dbs_tuners_ins.up_threshold_hotplug_freq3 = zzmoove_profiles[i].up_threshold_hotplug_freq3;
hotplug_thresholds_freq[0][2] = zzmoove_profiles[i].up_threshold_hotplug_freq3;
}
}
}
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
// ZZ: set up_threshold_hotplug_freq4 value
if (zzmoove_profiles[i].up_threshold_hotplug_freq4 == 0) {
dbs_tuners_ins.up_threshold_hotplug_freq4 = zzmoove_profiles[i].up_threshold_hotplug_freq4;
hotplug_thresholds_freq[0][3] = zzmoove_profiles[i].up_threshold_hotplug_freq4;
}
if (system_freq_table && zzmoove_profiles[i].up_threshold_hotplug_freq4 <= system_freq_table[max_scaling_freq_hard].frequency) {
zzmoove_profiles[i].up_threshold_hotplug_freq4 = check_frequency(zzmoove_profiles[i].up_threshold_hotplug_freq4);
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].up_threshold_hotplug_freq4) {
dbs_tuners_ins.up_threshold_hotplug_freq4 = zzmoove_profiles[i].up_threshold_hotplug_freq4;
hotplug_thresholds_freq[0][3] = zzmoove_profiles[i].up_threshold_hotplug_freq4;
}
}
}
// ZZ: set up_threshold_hotplug_freq5 value
if (zzmoove_profiles[i].up_threshold_hotplug_freq5 == 0) {
dbs_tuners_ins.up_threshold_hotplug_freq5 = zzmoove_profiles[i].up_threshold_hotplug_freq5;
hotplug_thresholds_freq[0][4] = zzmoove_profiles[i].up_threshold_hotplug_freq5;
}
if (system_freq_table && zzmoove_profiles[i].up_threshold_hotplug_freq5 <= system_freq_table[max_scaling_freq_hard].frequency) {
zzmoove_profiles[i].up_threshold_hotplug_freq5 = check_frequency(zzmoove_profiles[i].up_threshold_hotplug_freq5);
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].up_threshold_hotplug_freq5) {
dbs_tuners_ins.up_threshold_hotplug_freq5 = zzmoove_profiles[i].up_threshold_hotplug_freq5;
hotplug_thresholds_freq[0][4] = zzmoove_profiles[i].up_threshold_hotplug_freq5;
}
}
}
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
// ZZ: set up_threshold_hotplug_freq6 value
if (zzmoove_profiles[i].up_threshold_hotplug_freq6 == 0) {
dbs_tuners_ins.up_threshold_hotplug_freq6 = zzmoove_profiles[i].up_threshold_hotplug_freq6;
hotplug_thresholds_freq[0][5] = zzmoove_profiles[i].up_threshold_hotplug_freq6;
}
if (system_freq_table && zzmoove_profiles[i].up_threshold_hotplug_freq6 <= system_freq_table[max_scaling_freq_hard].frequency) {
zzmoove_profiles[i].up_threshold_hotplug_freq6 = check_frequency(zzmoove_profiles[i].up_threshold_hotplug_freq6);
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].up_threshold_hotplug_freq6) {
dbs_tuners_ins.up_threshold_hotplug_freq6 = zzmoove_profiles[i].up_threshold_hotplug_freq6;
hotplug_thresholds_freq[0][5] = zzmoove_profiles[i].up_threshold_hotplug_freq6;
}
}
}
// ZZ: set up_threshold_hotplug_freq7 value
if (zzmoove_profiles[i].up_threshold_hotplug_freq7 == 0) {
dbs_tuners_ins.up_threshold_hotplug_freq7 = zzmoove_profiles[i].up_threshold_hotplug_freq7;
hotplug_thresholds_freq[0][6] = zzmoove_profiles[i].up_threshold_hotplug_freq7;
}
if (system_freq_table && zzmoove_profiles[i].up_threshold_hotplug_freq7 <= system_freq_table[max_scaling_freq_hard].frequency) {
zzmoove_profiles[i].up_threshold_hotplug_freq7 = check_frequency(zzmoove_profiles[i].up_threshold_hotplug_freq7);
for (t = 0; (system_freq_table[t].frequency != system_table_end); t++) {
if (system_freq_table[t].frequency == zzmoove_profiles[i].up_threshold_hotplug_freq7) {
dbs_tuners_ins.up_threshold_hotplug_freq7 = zzmoove_profiles[i].up_threshold_hotplug_freq7;
hotplug_thresholds_freq[0][6] = zzmoove_profiles[i].up_threshold_hotplug_freq7;
}
}
}
#endif /* (MAX_CORES == 8) */
#endif /* ENABLE_HOTPLUGGING */
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
// ZZ: set up_threshold_sleep value
if (zzmoove_profiles[i].up_threshold_sleep <= 100 && zzmoove_profiles[i].up_threshold_sleep
> dbs_tuners_ins.down_threshold_sleep)
dbs_tuners_ins.up_threshold_sleep = zzmoove_profiles[i].up_threshold_sleep;
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND) */
#ifdef ENABLE_AUTO_ADJUST_FREQ
// ZZ: set auto_adjust_freq_thresholds value
if (zzmoove_profiles[i].auto_adjust_freq_thresholds > 1) {
zzmoove_profiles[i].auto_adjust_freq_thresholds = 1;
dbs_tuners_ins.auto_adjust_freq_thresholds = zzmoove_profiles[i].auto_adjust_freq_thresholds;
} else {
dbs_tuners_ins.auto_adjust_freq_thresholds = zzmoove_profiles[i].auto_adjust_freq_thresholds;
pol_step = 0;
}
#endif /* ENABLE_AUTO_ADJUST_FREQ */
// ZZ: set current profile number
dbs_tuners_ins.profile_number = profile_num;
// ZZ: set current profile name
strncpy(dbs_tuners_ins.profile, zzmoove_profiles[i].profile_name, sizeof(dbs_tuners_ins.profile));
set_profile_active = false; // ZZ: profile found - allow setting of tuneables again
return 1;
}
}
}
// ZZ: profile not found - allow setting of tuneables again
set_profile_active = false;
return 0;
}
// ff: added tuneable profile_sticky_mode -> possible values: 0 disabled, anything else enabled
static ssize_t store_profile_sticky_mode(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input < 0)
return -EINVAL;
dbs_tuners_ins.profile_sticky_mode = !!input;
return count;
}
// ZZ: tunable profile number -> for switching settings profiles, check zzmoove_profiles.h file for possible values
static ssize_t store_profile_number(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input; // ZZ: regular input handling of this tuneable
int ret_profile; // ZZ: return value for set_profile function
int ret; // ZZ: regular input handling of this tuneable
ret = sscanf(buf, "%u", &input); // ZZ: regular input handling of this tuneable
if (ret != 1)
return -EINVAL;
// ZZ: if input is 0 set profile to custom mode
if (input == 0) {
dbs_tuners_ins.profile_number = input;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
return count;
}
// ZZ: set profile and check result
ret_profile = set_profile(input);
if (ret_profile != 1)
return -EINVAL; // ZZ: given profile not available
else
return count; // ZZ: profile found return as normal
}
#endif /* ENABLE_PROFILES_SUPPORT */
#ifdef ENABLE_AUTO_ADJUST_FREQ
// ZZ: tunable auto adjust freq thresholds -> for a automatic adjustment of all freq thresholds.
static ssize_t store_auto_adjust_freq_thresholds(struct kobject *a, struct attribute *b, const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1
#ifdef ENABLE_PROFILES_SUPPORT
|| set_profile_active == true)
#else
)
#endif /* ENABLE_PROFILES_SUPPORT */
return -EINVAL;
input = !!input;
if (input == 0)
pol_step = 0;
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: set profile number to 0 and profile name to custom mode if value has changed
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 && dbs_tuners_ins.auto_adjust_freq_thresholds != input) {
dbs_tuners_ins.profile_number = 0;
strncpy(dbs_tuners_ins.profile, custom_profile, sizeof(dbs_tuners_ins.profile));
}
#endif /* ENABLE_PROFILES_SUPPORT */
dbs_tuners_ins.auto_adjust_freq_thresholds = input;
return count;
}
#endif /* ENABLE_AUTO_ADJUST_FREQ */
// Yank: add hotplug up/down threshold sysfs store interface
#ifdef ENABLE_HOTPLUGGING
#ifdef ENABLE_PROFILES_SUPPORT
#define store_up_threshold_hotplug_freq(name,core) \
static ssize_t store_up_threshold_hotplug_freq##name \
(struct kobject *a, struct attribute *b, const char *buf, size_t count) \
{ \
unsigned int input; \
int ret; \
int i = 0; \
\
ret = sscanf(buf, "%u", &input); \
if (ret != 1 || set_profile_active == true) \
return -EINVAL; \
\
if (input == 0) { \
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 \
&& (dbs_tuners_ins.up_threshold_hotplug_freq##name != input \
|| hotplug_thresholds_freq[0][core] == input)) { \
dbs_tuners_ins.profile_number = 0; \
strncpy(dbs_tuners_ins.profile, custom_profile, \
sizeof(dbs_tuners_ins.profile)); \
} \
dbs_tuners_ins.up_threshold_hotplug_freq##name = input; \
hotplug_thresholds_freq[0][core] = input; \
return count; \
} \
\
input = check_frequency(input); \
\
if (input > system_freq_table[max_scaling_freq_hard].frequency) { \
return -EINVAL; \
} else { \
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) { \
if (unlikely(system_freq_table[i].frequency == input)) { \
if (dbs_tuners_ins.profile_number != 0 \
&& !dbs_tuners_ins.profile_sticky_mode \
&& (dbs_tuners_ins.up_threshold_hotplug_freq##name != input \
|| hotplug_thresholds_freq[0][core] == input)) { \
dbs_tuners_ins.profile_number = 0; \
strncpy(dbs_tuners_ins.profile, custom_profile, \
sizeof(dbs_tuners_ins.profile)); \
} \
dbs_tuners_ins.up_threshold_hotplug_freq##name = input; \
hotplug_thresholds_freq[0][core] = input; \
return count; \
} \
} \
} \
return -EINVAL; \
} \
#define store_down_threshold_hotplug_freq(name,core) \
static ssize_t store_down_threshold_hotplug_freq##name \
(struct kobject *a, struct attribute *b, const char *buf, size_t count) \
{ \
unsigned int input; \
int ret; \
int i = 0; \
\
ret = sscanf(buf, "%u", &input); \
if (ret != 1 || set_profile_active == true) \
return -EINVAL; \
\
if (input == 0) { \
if (!dbs_tuners_ins.profile_sticky_mode && dbs_tuners_ins.profile_number != 0 \
&& (dbs_tuners_ins.down_threshold_hotplug_freq##name != input \
|| hotplug_thresholds_freq[1][core] == input)) { \
dbs_tuners_ins.profile_number = 0; \
strncpy(dbs_tuners_ins.profile, custom_profile, \
sizeof(dbs_tuners_ins.profile)); \
} \
dbs_tuners_ins.down_threshold_hotplug_freq##name = input; \
hotplug_thresholds_freq[1][core] = input; \
return count; \
} \
\
input = check_frequency(input); \
\
if (input > system_freq_table[max_scaling_freq_hard].frequency) { \
return -EINVAL; \
} else { \
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) { \
if (unlikely(system_freq_table[i].frequency == input)) { \
if (dbs_tuners_ins.profile_number != 0 \
&& !dbs_tuners_ins.profile_sticky_mode \
&& (dbs_tuners_ins.down_threshold_hotplug_freq##name != input \
|| hotplug_thresholds_freq[1][core] == input)) { \
dbs_tuners_ins.profile_number = 0; \
strncpy(dbs_tuners_ins.profile, custom_profile, \
sizeof(dbs_tuners_ins.profile)); \
} \
dbs_tuners_ins.down_threshold_hotplug_freq##name = input; \
hotplug_thresholds_freq[1][core] = input; \
return count; \
} \
} \
} \
return -EINVAL; \
} \
/*
* ZZ: tuneables -> possible values: 0 to disable core (only in up thresholds), range from above
* appropriate down thresholds up to scaling max frequency, if not set default for up and down
* thresholds is 0
*/
store_up_threshold_hotplug_freq(1,0);
store_down_threshold_hotplug_freq(1,0);
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
store_up_threshold_hotplug_freq(2,1);
store_down_threshold_hotplug_freq(2,1);
store_up_threshold_hotplug_freq(3,2);
store_down_threshold_hotplug_freq(3,2);
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
store_up_threshold_hotplug_freq(4,3);
store_down_threshold_hotplug_freq(4,3);
store_up_threshold_hotplug_freq(5,4);
store_down_threshold_hotplug_freq(5,4);
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
store_up_threshold_hotplug_freq(6,5);
store_down_threshold_hotplug_freq(6,5);
store_up_threshold_hotplug_freq(7,6);
store_down_threshold_hotplug_freq(7,6);
#endif /* (MAX_CORES == 8) */
#endif /* ENABLE_PROFILES_SUPPORT */
#ifndef ENABLE_PROFILES_SUPPORT
#define store_up_threshold_hotplug_freq(name,core) \
static ssize_t store_up_threshold_hotplug_freq##name \
(struct kobject *a, struct attribute *b, const char *buf, size_t count) \
{ \
unsigned int input; \
int ret; \
int i = 0; \
\
ret = sscanf(buf, "%u", &input); \
if (ret != 1) \
return -EINVAL; \
\
if (input == 0) { \
dbs_tuners_ins.up_threshold_hotplug_freq##name = input; \
hotplug_thresholds_freq[0][core] = input; \
return count; \
} \
\
if (input > system_freq_table[max_scaling_freq_hard].frequency) { \
return -EINVAL; \
} else { \
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) { \
if (unlikely(system_freq_table[i].frequency == input)) { \
dbs_tuners_ins.up_threshold_hotplug_freq##name = input; \
hotplug_thresholds_freq[0][core] = input; \
return count; \
} \
} \
} \
return -EINVAL; \
} \
#define store_down_threshold_hotplug_freq(name,core) \
static ssize_t store_down_threshold_hotplug_freq##name \
(struct kobject *a, struct attribute *b, const char *buf, size_t count) \
{ \
unsigned int input; \
int ret; \
int i = 0; \
\
ret = sscanf(buf, "%u", &input); \
if (ret != 1) \
return -EINVAL; \
\
if (input == 0) { \
dbs_tuners_ins.down_threshold_hotplug_freq##name = input; \
hotplug_thresholds_freq[1][core] = input; \
return count; \
} \
\
if (input > system_freq_table[max_scaling_freq_hard].frequency) { \
return -EINVAL; \
} else { \
for (i = 0; (likely(system_freq_table[i].frequency != system_table_end)); i++) { \
if (unlikely(system_freq_table[i].frequency == input)) { \
dbs_tuners_ins.down_threshold_hotplug_freq##name = input; \
hotplug_thresholds_freq[1][core] = input; \
return count; \
} \
} \
} \
return -EINVAL; \
} \
/*
* ZZ: tuneables -> possible values: 0 to disable core (only in up thresholds), range from above
* appropriate down thresholds up to scaling max frequency, if not set default for up and down
* thresholds is 0
*/
store_up_threshold_hotplug_freq(1,0);
store_down_threshold_hotplug_freq(1,0);
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
store_up_threshold_hotplug_freq(2,1);
store_down_threshold_hotplug_freq(2,1);
store_up_threshold_hotplug_freq(3,2);
store_down_threshold_hotplug_freq(3,2);
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
store_up_threshold_hotplug_freq(4,3);
store_down_threshold_hotplug_freq(4,3);
store_up_threshold_hotplug_freq(5,4);
store_down_threshold_hotplug_freq(5,4);
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
store_up_threshold_hotplug_freq(6,5);
store_down_threshold_hotplug_freq(6,5);
store_up_threshold_hotplug_freq(7,6);
store_down_threshold_hotplug_freq(7,6);
#endif /* (MAX_CORES == 8) */
#endif /* ENABLE_PROFILES_SUPPORT */
#endif /* ENABLE_HOTPLUGGING */
#ifdef ENABLE_PROFILES_SUPPORT
define_one_global_rw(profile_number);
define_one_global_rw(profile_sticky_mode);
define_one_global_ro(profile);
#endif /* ENABLE_PROFILES_SUPPORT */
#ifdef ENABLE_AUTO_ADJUST_FREQ
define_one_global_rw(auto_adjust_freq_thresholds);
#endif /* ENABLE_AUTO_ADJUST_FREQ */
define_one_global_ro(sampling_rate_current);
define_one_global_rw(sampling_rate);
define_one_global_rw(sampling_rate_idle_threshold);
define_one_global_rw(sampling_rate_idle);
define_one_global_rw(sampling_rate_idle_delay);
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
define_one_global_rw(sampling_rate_sleep_multiplier);
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
define_one_global_rw(sampling_down_factor);
define_one_global_rw(sampling_down_max_momentum);
define_one_global_rw(sampling_down_momentum_sensitivity);
define_one_global_rw(up_threshold);
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
define_one_global_rw(up_threshold_sleep);
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_HOTPLUGGING
define_one_global_rw(up_threshold_hotplug1);
define_one_global_rw(up_threshold_hotplug_freq1);
define_one_global_rw(block_up_multiplier_hotplug1);
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
define_one_global_rw(up_threshold_hotplug2);
define_one_global_rw(up_threshold_hotplug_freq2);
define_one_global_rw(block_up_multiplier_hotplug2);
define_one_global_rw(up_threshold_hotplug3);
define_one_global_rw(up_threshold_hotplug_freq3);
define_one_global_rw(block_up_multiplier_hotplug3);
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
define_one_global_rw(up_threshold_hotplug4);
define_one_global_rw(up_threshold_hotplug_freq4);
define_one_global_rw(block_up_multiplier_hotplug4);
define_one_global_rw(up_threshold_hotplug5);
define_one_global_rw(up_threshold_hotplug_freq5);
define_one_global_rw(block_up_multiplier_hotplug5);
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
define_one_global_rw(up_threshold_hotplug6);
define_one_global_rw(up_threshold_hotplug_freq6);
define_one_global_rw(block_up_multiplier_hotplug6);
define_one_global_rw(up_threshold_hotplug7);
define_one_global_rw(up_threshold_hotplug_freq7);
define_one_global_rw(block_up_multiplier_hotplug7);
#endif /* (MAX_CORES == 8) */
#endif /* ENABLE_HOTPLUGGING */
define_one_global_rw(down_threshold);
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
define_one_global_rw(down_threshold_sleep);
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_HOTPLUGGING
define_one_global_rw(down_threshold_hotplug1);
define_one_global_rw(down_threshold_hotplug_freq1);
define_one_global_rw(block_down_multiplier_hotplug1);
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
define_one_global_rw(down_threshold_hotplug2);
define_one_global_rw(down_threshold_hotplug_freq2);
define_one_global_rw(block_down_multiplier_hotplug2);
define_one_global_rw(down_threshold_hotplug3);
define_one_global_rw(down_threshold_hotplug_freq3);
define_one_global_rw(block_down_multiplier_hotplug3);
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
define_one_global_rw(down_threshold_hotplug4);
define_one_global_rw(down_threshold_hotplug_freq4);
define_one_global_rw(block_down_multiplier_hotplug4);
define_one_global_rw(down_threshold_hotplug5);
define_one_global_rw(down_threshold_hotplug_freq5);
define_one_global_rw(block_down_multiplier_hotplug5);
#endif
#if (MAX_CORES == 8)
define_one_global_rw(down_threshold_hotplug6);
define_one_global_rw(down_threshold_hotplug_freq6);
define_one_global_rw(block_down_multiplier_hotplug6);
define_one_global_rw(down_threshold_hotplug7);
define_one_global_rw(down_threshold_hotplug_freq7);
define_one_global_rw(block_down_multiplier_hotplug7);
#endif /* (MAX_CORES == 8) */
#endif /* ENABLE_HOTPLUGGING */
define_one_global_rw(ignore_nice_load);
define_one_global_rw(smooth_up);
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
define_one_global_rw(smooth_up_sleep);
#ifdef ENABLE_HOTPLUGGING
define_one_global_rw(hotplug_sleep);
#endif /* ENABLE_HOTPLUGGING */
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
define_one_global_rw(freq_limit);
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
define_one_global_rw(freq_limit_sleep);
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
define_one_global_rw(fast_scaling_up);
define_one_global_rw(fast_scaling_down);
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
define_one_global_rw(fast_scaling_sleep_up);
define_one_global_rw(fast_scaling_sleep_down);
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
define_one_global_rw(afs_threshold1);
define_one_global_rw(afs_threshold2);
define_one_global_rw(afs_threshold3);
define_one_global_rw(afs_threshold4);
define_one_global_rw(grad_up_threshold);
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
define_one_global_rw(grad_up_threshold_sleep);
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
define_one_global_rw(early_demand);
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
define_one_global_rw(early_demand_sleep);
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_HOTPLUGGING
define_one_global_rw(disable_hotplug);
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
define_one_global_rw(disable_hotplug_sleep);
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
define_one_global_rw(hotplug_block_up_cycles);
define_one_global_rw(hotplug_block_down_cycles);
define_one_global_rw(hotplug_stagger_up);
define_one_global_rw(hotplug_stagger_down);
define_one_global_rw(hotplug_idle_threshold);
define_one_global_rw(hotplug_idle_freq);
define_one_global_rw(hotplug_engage_freq);
define_one_global_rw(hotplug_max_limit);
define_one_global_rw(hotplug_min_limit);
define_one_global_rw(hotplug_lock);
#endif /* ENABLE_HOTPLUGGING */
define_one_global_rw(scaling_block_threshold);
define_one_global_rw(scaling_block_cycles);
define_one_global_rw(scaling_up_block_cycles);
define_one_global_rw(scaling_up_block_freq);
#ifdef CONFIG_EXYNOS4_EXPORT_TEMP
define_one_global_rw(scaling_block_temp);
#endif /* CONFIG_EXYNOS4_EXPORT_TEMP */
#ifdef ENABLE_SNAP_THERMAL_SUPPORT
define_one_global_rw(scaling_trip_temp);
#endif /* ENABLE_SNAP_THERMAL_SUPPORT */
define_one_global_rw(scaling_block_freq);
define_one_global_rw(scaling_block_force_down);
define_one_global_rw(scaling_fastdown_freq);
define_one_global_rw(scaling_fastdown_up_threshold);
define_one_global_rw(scaling_fastdown_down_threshold);
define_one_global_rw(scaling_responsiveness_freq);
define_one_global_rw(scaling_responsiveness_up_threshold);
define_one_global_rw(scaling_proportional);
#ifdef ENABLE_INPUTBOOSTER
// ff: Input Booster
define_one_global_rw(inputboost_cycles);
define_one_global_rw(inputboost_up_threshold);
define_one_global_rw(inputboost_punch_cycles);
define_one_global_rw(inputboost_punch_freq);
define_one_global_rw(inputboost_punch_on_fingerdown);
define_one_global_rw(inputboost_punch_on_fingermove);
define_one_global_rw(inputboost_punch_on_epenmove);
define_one_global_rw(inputboost_typingbooster_up_threshold);
define_one_global_rw(inputboost_typingbooster_cores);
#endif /* ENABLE_INPUTBOOSTER */
#ifdef ENABLE_MUSIC_LIMITS
// ff: Music Detection
define_one_global_rw(music_max_freq);
define_one_global_rw(music_min_freq);
#ifdef ENABLE_HOTPLUGGING
define_one_global_rw(music_min_cores);
#endif /* ENABLE_HOTPLUGGING */
define_one_global_rw(music_state);
#endif /* ENABLE_MUSIC_LIMITS */
// Yank: version info tunable
static ssize_t show_version(struct device *dev, struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", ZZMOOVE_VERSION);
}
static DEVICE_ATTR(version, S_IRUGO , show_version, NULL);
#ifdef ENABLE_PROFILES_SUPPORT
// ZZ: profiles version info tunable
static ssize_t show_version_profiles(struct device *dev, struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", profiles_file_version);
}
static DEVICE_ATTR(version_profiles, S_IRUGO , show_version_profiles, NULL);
// ZZ: print out all available profiles
static ssize_t show_profile_list(struct device *dev, struct device_attribute *attr, char *buf)
{
int i = 0, c = 0;
char profiles[512];
for (i = 0; (zzmoove_profiles[i].profile_number != PROFILE_TABLE_END); i++) {
c += sprintf(profiles+c, "profile: %d " "name: %s\n", zzmoove_profiles[i].profile_number,
zzmoove_profiles[i].profile_name);
}
return sprintf(buf, profiles);
}
static DEVICE_ATTR(profile_list, S_IRUGO , show_profile_list, NULL);
#endif /* ENABLE_PROFILES_SUPPORT */
#ifdef ZZMOOVE_DEBUG
// Yank: debug info
static ssize_t show_zzmoove_debug(struct device *dev, struct device_attribute *attr, char *buf)
{
return sprintf(buf, "available cores : %d\n"
#if (MAX_CORES == 2 || MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
"core 0 online : %d\n"
"core 1 online : %d\n"
#endif /* (MAX_CORES == 2 || MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
"core 2 online : %d\n"
"core 3 online : %d\n"
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
"core 4 online : %d\n"
"core 5 online : %d\n"
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
"core 6 online : %d\n"
"core 7 online : %d\n"
#endif /* (MAX_CORES == 8) */
#ifdef CONFIG_EXYNOS4_EXPORT_TEMP
"current cpu temp : %d C\n"
"scaling block temp : %d C\n"
#endif /* CONFIG_EXYNOS4_EXPORT_TEMP */
#ifdef ENABLE_SNAP_THERMAL_SUPPORT
"current cpu temp : %d C\n"
"thermal trip temp : %d C\n"
#endif /* ENABLE_SNAP_THERMAL_SUPPORT */
"running gov instances : %d\n"
#ifdef ENABLE_PROFILES_SUPPORT
"loaded profile : %s\n"
"loaded profile number : %d\n"
#endif /* ENABLE_PROFILES_SUPPORT */
"max freq : %d\n"
"min freq : %d\n"
#ifdef ENABLE_AUTO_ADJUST_FREQ
"auto adjust step : %d\n"
#endif /* ENABLE_AUTO_ADJUST_FREQ */
"current load : %d\n"
"current frequency : %d\n"
"current sampling rate : %u\n"
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
"freq limit awake : %u\n"
"freq limit asleep : %u\n"
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND) */
"freq table in desc order : %d\n"
"freq table size : %u\n"
"limit table start : %u\n"
"max scaling freq hard : %u\n"
"max scaling freq soft : %u\n"
"freq init count : %u\n"
"scaling boost : %d\n"
"scaling cancel up : %d\n"
"scaling mode up : %d\n"
"scaling force down : %d\n"
"scaling mode down : %d\n"
"scaling up threshold : %d\n"
#ifdef ENABLE_INPUTBOOSTER
"inputboost cycles : %d\n"
"inputboost up threshold : %d\n"
"inputboost punch cycles : %u\n"
"inputboost punch freq : %d\n"
"inputboost punch on finger down: %d\n"
"inputboost punch on finger move: %d\n"
"inputboost punch on epenmove : %d\n"
"inputboost typing up threshold : %d\n"
"inputboost typing cores : %d\n"
#endif /* ENABLE_INPUTBOOSTER */
"current sampling down factor : %d\n"
"current max momentum : %d\n"
#ifdef ENABLE_MUSIC_LIMITS
"music max freq : %d\n"
"music min freq : %d\n"
"music state : %d\n"
#endif /* ENABLE_MUSIC_LIMITS */
#ifdef ENABLE_HOTPLUGGING
"scaling down threshold : %d\n"
"hotplug block up cycles : %d\n"
"hotplug block down cycles : %d\n"
"hotplug up threshold1 : %d\n"
"hotplug up threshold2 : %d\n"
"hotplug up threshold3 : %d\n"
"hotplug up threshold1 freq : %d\n"
"hotplug up threshold2 freq : %d\n"
"hotplug up threshold3 freq : %d\n"
"hotplug down threshold1 : %d\n"
"hotplug down threshold2 : %d\n"
"hotplug down threshold3 : %d\n"
"hotplug down threshold1 freq : %d\n"
"hotplug down threshold2 freq : %d\n"
"hotplug down threshold3 freq : %d\n",
#else
"scaling down threshold : %d\n",
#endif /* ENABLE_HOTPLUGGING */
possible_cpus,
#if (MAX_CORES == 2 || MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
cpu_online(0),
cpu_online(1),
#endif
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
cpu_online(2),
cpu_online(3),
#endif
#if (MAX_CORES == 6 || MAX_CORES == 8)
cpu_online(4),
cpu_online(5),
#endif
#if (MAX_CORES == 8)
cpu_online(6),
cpu_online(7),
#endif
#ifdef CONFIG_EXYNOS4_EXPORT_TEMP
cpu_temp,
dbs_tuners_ins.scaling_block_temp,
#endif /* CONFIG_EXYNOS4_EXPORT_TEMP */
#ifdef ENABLE_SNAP_THERMAL_SUPPORT
tmu_temp_cpu,
dbs_tuners_ins.scaling_trip_temp,
#endif /* ENABLE_SNAP_THERMAL_SUPPORT */
dbs_enable,
#ifdef ENABLE_PROFILES_SUPPORT
dbs_tuners_ins.profile,
dbs_tuners_ins.profile_number,
#endif /* PROFILES_SUPPORT */
pol_max,
pol_min,
#ifdef ENABLE_AUTO_ADJUST_FREQ
pol_step,
#endif /* ENABLE_AUTO_ADJUST_FREQ */
cur_load,
cur_freq,
dbs_tuners_ins.sampling_rate_current,
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
freq_limit_awake,
freq_limit_asleep,
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND) */
freq_table_desc,
freq_table_size,
limit_table_start,
max_scaling_freq_hard,
max_scaling_freq_soft,
freq_init_count,
boost_freq,
cancel_up_scaling,
scaling_mode_up,
force_down_scaling,
scaling_mode_down,
scaling_up_threshold,
#ifdef ENABLE_INPUTBOOSTER
dbs_tuners_ins.inputboost_cycles,
dbs_tuners_ins.inputboost_up_threshold,
dbs_tuners_ins.inputboost_punch_cycles,
dbs_tuners_ins.inputboost_punch_freq,
dbs_tuners_ins.inputboost_punch_on_fingerdown,
dbs_tuners_ins.inputboost_punch_on_fingermove,
dbs_tuners_ins.inputboost_punch_on_epenmove,
dbs_tuners_ins.inputboost_typingbooster_up_threshold,
dbs_tuners_ins.inputboost_typingbooster_cores,
#endif /* ENABLE_INPUTBOOSTER */
zz_sampling_down_factor,
zz_sampling_down_max_mom,
#ifdef ENABLE_MUSIC_LIMITS
dbs_tuners_ins.music_max_freq,
dbs_tuners_ins.music_min_freq,
dbs_tuners_ins.music_state,
#endif /* ENABLE_MUSIC_LIMITS */
#ifdef ENABLE_HOTPLUGGING
scaling_down_threshold,
zz_hotplug_block_up_cycles,
zz_hotplug_block_down_cycles,
hotplug_thresholds[0][0],
hotplug_thresholds[0][1],
hotplug_thresholds[0][2],
hotplug_thresholds_freq[0][0],
hotplug_thresholds_freq[0][1],
hotplug_thresholds_freq[0][2],
hotplug_thresholds[1][0],
hotplug_thresholds[1][1],
hotplug_thresholds[1][2],
hotplug_thresholds_freq[1][0],
hotplug_thresholds_freq[1][1],
hotplug_thresholds_freq[1][2]);
#else
scaling_down_threshold);
#endif /* ENABLE_HOTPLUGGING */
}
static DEVICE_ATTR(zzmoove_debug, S_IRUGO , show_zzmoove_debug, NULL);
#endif /* ZZMOOVE_DEBUG */
static struct attribute *dbs_attributes[] = {
&sampling_rate_min.attr,
&sampling_rate.attr,
&sampling_rate_current.attr,
&sampling_rate_idle_threshold.attr,
&sampling_rate_idle.attr,
&sampling_rate_idle_delay.attr,
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
&sampling_rate_sleep_multiplier.attr,
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
&sampling_down_factor.attr,
&sampling_down_max_momentum.attr,
&sampling_down_momentum_sensitivity.attr,
&up_threshold.attr,
&down_threshold.attr,
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
&up_threshold_sleep.attr,
&down_threshold_sleep.attr,
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
&ignore_nice_load.attr,
&smooth_up.attr,
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
&smooth_up_sleep.attr,
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
&freq_limit.attr,
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
&freq_limit_sleep.attr,
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
&fast_scaling_up.attr,
&fast_scaling_down.attr,
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
&fast_scaling_sleep_up.attr,
&fast_scaling_sleep_down.attr,
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
&afs_threshold1.attr,
&afs_threshold2.attr,
&afs_threshold3.attr,
&afs_threshold4.attr,
&grad_up_threshold.attr,
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
&grad_up_threshold_sleep.attr,
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
&early_demand.attr,
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
&early_demand_sleep.attr,
#ifdef ENABLE_HOTPLUGGING
&hotplug_sleep.attr,
#endif /* ENABLE_HOTPLUGGING */
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#ifdef ENABLE_HOTPLUGGING
&disable_hotplug.attr,
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
&disable_hotplug_sleep.attr,
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
&hotplug_block_up_cycles.attr,
&hotplug_block_down_cycles.attr,
&hotplug_stagger_up.attr,
&hotplug_stagger_down.attr,
&hotplug_idle_threshold.attr,
&hotplug_idle_freq.attr,
&hotplug_engage_freq.attr,
&hotplug_max_limit.attr,
&hotplug_min_limit.attr,
&hotplug_lock.attr,
#endif /* ENABLE_HOTPLUGGING */
&scaling_block_threshold.attr,
&scaling_block_cycles.attr,
&scaling_up_block_cycles.attr,
&scaling_up_block_freq.attr,
#ifdef CONFIG_EXYNOS4_EXPORT_TEMP
&scaling_block_temp.attr,
#endif /* CONFIG_EXYNOS4_EXPORT_TEMP */
#ifdef ENABLE_SNAP_THERMAL_SUPPORT
&scaling_trip_temp.attr,
#endif /* ENABLE_SNAP_THERMAL_SUPPORT */
&scaling_block_freq.attr,
&scaling_block_force_down.attr,
&scaling_fastdown_freq.attr,
&scaling_fastdown_up_threshold.attr,
&scaling_fastdown_down_threshold.attr,
&scaling_responsiveness_freq.attr,
&scaling_responsiveness_up_threshold.attr,
&scaling_proportional.attr,
#ifdef ENABLE_HOTPLUGGING
&up_threshold_hotplug1.attr,
&up_threshold_hotplug_freq1.attr,
&block_up_multiplier_hotplug1.attr,
&down_threshold_hotplug1.attr,
&down_threshold_hotplug_freq1.attr,
&block_down_multiplier_hotplug1.attr,
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
&up_threshold_hotplug2.attr,
&up_threshold_hotplug_freq2.attr,
&block_up_multiplier_hotplug2.attr,
&down_threshold_hotplug2.attr,
&down_threshold_hotplug_freq2.attr,
&block_down_multiplier_hotplug2.attr,
&up_threshold_hotplug3.attr,
&up_threshold_hotplug_freq3.attr,
&block_up_multiplier_hotplug3.attr,
&down_threshold_hotplug3.attr,
&down_threshold_hotplug_freq3.attr,
&block_down_multiplier_hotplug3.attr,
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
&up_threshold_hotplug4.attr,
&up_threshold_hotplug_freq4.attr,
&block_up_multiplier_hotplug4.attr,
&down_threshold_hotplug4.attr,
&down_threshold_hotplug_freq4.attr,
&block_down_multiplier_hotplug4.attr,
&up_threshold_hotplug5.attr,
&up_threshold_hotplug_freq5.attr,
&block_up_multiplier_hotplug5.attr,
&down_threshold_hotplug5.attr,
&down_threshold_hotplug_freq5.attr,
&block_down_multiplier_hotplug5.attr,
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
&up_threshold_hotplug6.attr,
&up_threshold_hotplug_freq6.attr,
&block_up_multiplier_hotplug6.attr,
&down_threshold_hotplug6.attr,
&down_threshold_hotplug_freq6.attr,
&block_down_multiplier_hotplug6.attr,
&up_threshold_hotplug7.attr,
&up_threshold_hotplug_freq7.attr,
&block_up_multiplier_hotplug7.attr,
&down_threshold_hotplug7.attr,
&down_threshold_hotplug_freq7.attr,
&block_down_multiplier_hotplug7.attr,
#endif /* (MAX_CORES == 8) */
#endif /* ENABLE_HOTPLUGGING */
#ifdef ENABLE_INPUTBOOSTER
&inputboost_cycles.attr,
&inputboost_up_threshold.attr,
&inputboost_punch_cycles.attr,
&inputboost_punch_freq.attr,
&inputboost_punch_on_fingerdown.attr,
&inputboost_punch_on_fingermove.attr,
&inputboost_punch_on_epenmove.attr,
&inputboost_typingbooster_up_threshold.attr,
&inputboost_typingbooster_cores.attr,
#endif /* ENABLE_INPUTBOOSTER */
#ifdef ENABLE_MUSIC_LIMITS
&music_max_freq.attr,
&music_min_freq.attr,
#ifdef ENABLE_HOTPLUGGING
&music_min_cores.attr,
#endif /* ENABLE_HOTPLUGGING */
&music_state.attr,
#endif /* ENABLE_MUSIC_LIMITS */
&dev_attr_version.attr,
#ifdef ENABLE_PROFILES_SUPPORT
&dev_attr_version_profiles.attr,
&dev_attr_profile_list.attr,
&profile.attr,
&profile_number.attr,
&profile_sticky_mode.attr,
#endif /* ENABLE_PROFILES_SUPPORT */
#ifdef ENABLE_AUTO_ADJUST_FREQ
&auto_adjust_freq_thresholds.attr,
#endif /* ENABLE_AUTO_ADJUST_FREQ */
#ifdef ZZMOOVE_DEBUG
&dev_attr_zzmoove_debug.attr,
#endif /* ZZMOOVE_DEBUG */
NULL
};
static struct attribute_group dbs_attr_group = {
.attrs = dbs_attributes,
.name = "zzmoove",
};
/************************** sysfs end **************************/
static void dbs_check_cpu(struct cpu_dbs_info_s *this_dbs_info)
{
unsigned int j, load = 0, max_load = 0;
struct cpufreq_policy *policy;
#if defined(ZZMOOVE_DEBUG) && defined(ENABLE_INPUTBOOSTER)
struct timeval time_now;
#endif /* ZZMOOVE_DEBUG */
unsigned int down_threshold_override = 0;
#ifdef ENABLE_HOTPLUGGING
unsigned int num_online_cpus;
boost_hotplug = false; // ZZ: reset early demand boost hotplug flag
#endif /* ENABLE_HOTPLUGGING */
boost_freq = false; // ZZ: reset early demand boost freq flag
force_down_scaling = false; // ZZ: reset force down scaling flag
cancel_up_scaling = false; // ZZ: reset cancel up scaling flag
policy = this_dbs_info->cur_policy;
on_cpu = policy->cpu;
if (on_cpu == 0)
cur_freq = policy->cur; // Yank: store current frequency for hotplugging frequency thresholds
#ifdef ENABLE_INPUTBOOSTER
#ifdef ENABLE_SNAP_THERMAL_SUPPORT
if (tmu_throttle_steps < 1) {
#endif /* ENABLE_SNAP_THERMAL_SUPPORT */
if (flg_ctr_cpuboost > 0) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] manual max-boost call! boosting to: %d mhz %d more times, cur: %d\n", policy->max, flg_ctr_cpuboost, policy->cur);
#endif /* ZZMOOVE_DEBUG */
if (policy->cur < policy->max) {
__cpufreq_driver_target(policy, policy->max, CPUFREQ_RELATION_H);
}
flg_ctr_cpuboost--;
flg_ctr_inputboost_punch--;
scaling_up_block_cycles_count = 0;
return;
}
if (flg_ctr_inputboost_punch > 0) {
// decrement now, and boost to inputboost_punch_freq later on.
// ctr should have anticipated the lost final cycle by padding +1.
flg_ctr_inputboost_punch--;
if (!flg_ctr_inputboost_punch) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] inputboost - punch expired\n");
#endif /* ZZMOOVE_DEBUG */
} else {
if (policy->cur < dbs_tuners_ins.inputboost_punch_freq) {
#ifdef ZZMOOVE_DEBUG
// ZZ: save current time
do_gettimeofday(&time_now);
// ZZ: get time difference
time_since_touchbooster_lastrun = (time_now.tv_sec - time_touchbooster_lastrun.tv_sec) * MSEC_PER_SEC +
(time_now.tv_usec - time_touchbooster_lastrun.tv_usec) / USEC_PER_MSEC;
pr_info("[zzmoove/dbs_check_cpu] time since touch: %d ms\n", time_since_touchbooster_lastrun);
pr_info("[zzmoove/dbs_check_cpu] freq: %d too low, punching to %d immediately\n", policy->cur, dbs_tuners_ins.inputboost_punch_freq);
#endif /* ZZMOOVE_DEBUG */
__cpufreq_driver_target(policy, dbs_tuners_ins.inputboost_punch_freq, CPUFREQ_RELATION_H);
}
}
}
#ifdef ENABLE_SNAP_THERMAL_SUPPORT
} else {
// ff: reset all boosts
flg_ctr_cpuboost = 0;
flg_ctr_inputboost = 0;
flg_ctr_inputboost_punch = 0;
flg_ctr_inputbooster_typingbooster = 0;
// ff: check for cores that need to come down
#ifdef ENABLE_HOTPLUGGING
if (on_cpu == 0 && !dbs_tuners_ins.disable_hotplug && num_online_cpus() != 1)
queue_work_on(0, dbs_wq, &hotplug_offline_work);
#endif /* ENABLE_HOTPLUGGING */
}
#endif /* ENABLE_SNAP_THERMAL_SUPPORT */
#endif /* ENABLE_INPUTBOOSTER */
/*
* Every sampling_rate, we check, if current idle time is less than 20%
* (default), then we try to increase frequency. Every sampling_rate *
* sampling_down_factor, we check, if current idle time is more than 80%
* (default), then we try to decrease frequency.
*/
/*
* ZZ: Get absolute load and make calcualtions for early demand, auto fast
* scaling and scaling block functionality
*/
for_each_cpu(j, policy->cpus) {
struct cpu_dbs_info_s *j_dbs_info;
u64 cur_wall_time, cur_idle_time;
unsigned int idle_time, wall_time;
j_dbs_info = &per_cpu(cs_cpu_dbs_info, j);
cur_idle_time = get_cpu_idle_time(j,
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0) || defined(CPU_IDLE_TIME_IN_CPUFREQ) /* overrule for sources with backported cpufreq implementation */
&cur_wall_time, 0);
#else
&cur_wall_time);
#endif /* LINUX_VERSION_CODE... */
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,4,0)
wall_time = (unsigned int)
(cur_wall_time - j_dbs_info->prev_cpu_wall);
#else
wall_time = (unsigned int) cputime64_sub(cur_wall_time,
j_dbs_info->prev_cpu_wall);
#endif /* LINUX_VERSION_CODE... */
j_dbs_info->prev_cpu_wall = cur_wall_time;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,4,0)
idle_time = (unsigned int)
(cur_idle_time - j_dbs_info->prev_cpu_idle);
j_dbs_info->prev_cpu_idle = cur_idle_time;
#else
idle_time = (unsigned int) cputime64_sub(cur_idle_time,
j_dbs_info->prev_cpu_idle);
j_dbs_info->prev_cpu_idle = cur_idle_time;
#endif /* LINUX_VERSION_CODE... */
if (dbs_tuners_ins.ignore_nice) {
u64 cur_nice;
unsigned long cur_nice_jiffies;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,4,0)
cur_nice = kcpustat_cpu(j).cpustat[CPUTIME_NICE] -
j_dbs_info->prev_cpu_nice;
#else
cur_nice = cputime64_sub(kstat_cpu(j).cpustat.nice,
j_dbs_info->prev_cpu_nice);
#endif /* LINUX_VERSION_CODE... */
/*
* Assumption: nice time between sampling periods will
* be less than 2^32 jiffies for 32 bit sys
*/
cur_nice_jiffies = (unsigned long)
cputime64_to_jiffies64(cur_nice);
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,4,0)
j_dbs_info->prev_cpu_nice = kcpustat_cpu(j).cpustat[CPUTIME_NICE];
#else
j_dbs_info->prev_cpu_nice = kstat_cpu(j).cpustat.nice;
#endif /* LINUX_VERSION_CODE... */
idle_time += jiffies_to_usecs(cur_nice_jiffies);
}
if (unlikely(!wall_time || wall_time < idle_time))
continue;
load = 100 * (wall_time - idle_time) / wall_time;
#if defined(CONFIG_ARCH_EXYNOS4)
if (load > max_load)
#endif /* CONFIG_ARCH_EXYNOS4 */
cur_load = max_load = load; // ZZ: added static cur_load for hotplugging functions
/*
* ZZ: Early demand by Stratosk
* Calculate the gradient of load. If it is too steep we assume
* that the load will go over up_threshold in next iteration(s) and
* we increase the frequency immediately
*
* At suspend:
* Seperate early demand for suspend to be able to adjust scaling behaving at screen off and therefore to be
* able to react problems which can occur because of too strictly suspend settings
* So this will: boost freq and switch to fast scaling mode 2 at the same time if load is steep enough
* (the value in grad_up_threshold_sleep) and in addition will lower the sleep multiplier to 2
* (if it was set higher) when load goes above the value in grad_up_threshold_sleep
*/
if (dbs_tuners_ins.early_demand && !suspend_flag) {
// ZZ: early demand at awake
if (max_load > this_dbs_info->prev_load && max_load - this_dbs_info->prev_load
> dbs_tuners_ins.grad_up_threshold)
boost_freq = true;
#ifdef ENABLE_HOTPLUGGING
boost_hotplug = true;
#endif /* ENABLE_HOTPLUGGING */
// ZZ: early demand at suspend
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
} else if (dbs_tuners_ins.early_demand_sleep && suspend_flag) {
// ZZ: check if we are over sleep threshold
if (max_load > dbs_tuners_ins.grad_up_threshold_sleep
&& dbs_tuners_ins.sampling_rate_sleep_multiplier > 2)
dbs_tuners_ins.sampling_rate_current = dbs_tuners_ins.sampling_rate_idle * 2; // ZZ: lower sleep multiplier
else
dbs_tuners_ins.sampling_rate_current = dbs_tuners_ins.sampling_rate_idle
* dbs_tuners_ins.sampling_rate_sleep_multiplier; // ZZ: restore sleep multiplier
// ZZ: if load is steep enough enable freq boost and fast up scaling
if (max_load > this_dbs_info->prev_load && max_load - this_dbs_info->prev_load
> dbs_tuners_ins.grad_up_threshold_sleep) {
boost_freq = true; // ZZ: boost frequency
scaling_mode_up = 2; // ZZ: enable fast scaling up mode 2
} else {
scaling_mode_up = 0; // ZZ: disable fast scaling again
}
}
#else
}
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND) */
/*
* ZZ/Yank: Auto fast scaling mode
* Switch to all 4 fast scaling modes depending on load gradient
* the mode will start switching at given afs threshold load changes in both directions
*/
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
if ((dbs_tuners_ins.fast_scaling_up > 4 && !suspend_flag) ||
(dbs_tuners_ins.fast_scaling_sleep_up > 4 && suspend_flag) ) {
#else
if (dbs_tuners_ins.fast_scaling_up > 4 && !suspend_flag) {
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND) */
if (max_load > this_dbs_info->prev_load && max_load - this_dbs_info->prev_load <= dbs_tuners_ins.afs_threshold1) {
scaling_mode_up = 0;
} else if (max_load - this_dbs_info->prev_load <= dbs_tuners_ins.afs_threshold2) {
scaling_mode_up = 1;
} else if (max_load - this_dbs_info->prev_load <= dbs_tuners_ins.afs_threshold3) {
scaling_mode_up = 2;
} else if (max_load - this_dbs_info->prev_load <= dbs_tuners_ins.afs_threshold4) {
scaling_mode_up = 3;
} else {
scaling_mode_up = 4;
}
}
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
if ((dbs_tuners_ins.fast_scaling_down > 4 && !suspend_flag) ||
(dbs_tuners_ins.fast_scaling_sleep_down > 4 && suspend_flag) ) {
#else
if (dbs_tuners_ins.fast_scaling_down > 4 && !suspend_flag) {
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND) */
if (max_load < this_dbs_info->prev_load && this_dbs_info->prev_load - max_load <= dbs_tuners_ins.afs_threshold1) {
scaling_mode_down = 0;
} else if (this_dbs_info->prev_load - max_load <= dbs_tuners_ins.afs_threshold2) {
scaling_mode_down = 1;
} else if (this_dbs_info->prev_load - max_load <= dbs_tuners_ins.afs_threshold3) {
scaling_mode_down = 2;
} else if (this_dbs_info->prev_load - max_load <= dbs_tuners_ins.afs_threshold4) {
scaling_mode_down = 3;
} else {
scaling_mode_down = 4;
}
}
/*
* ZZ: Scaling block for reducing up scaling 'overhead'
*
* If the given freq threshold is reached do following:
* Calculate the gradient of load in both directions count them every time they are under the load threshold
* and block up scaling during that time. If max count of cycles (and therefore threshold hits) are reached
* switch to 'force down mode' which lowers the freq the next given block cycles. By all that we can avoid
* 'sticking' on max or relatively high frequency (caused by the very fast scaling behaving of zzmoove)
* when load is constantly on mid to higher load during a 'longer' peroid.
*
* Or if exynos4 CPU temperature reading is enabled below do following:
* Use current CPU temperature as a blocking threshold to lower the frequency and therefore keep the CPU cooler.
* so in particular this will lower the frequency to the frequency set in 'scaling_block_freq' and hold it
* there till the temperature goes under the temperature threshold again.
*
* u can choose here to use either fixed blocking cycles or the temperature threshold. using fixed blocking cycles disables
* temperature depending blocking. in case of temperature depending blocks u must set a target freq in scaling_block_freq
* tuneable. fixed block cycle feature can still be used optional without a frequency as 'starting threshold' like before
*/
#ifdef CONFIG_EXYNOS4_EXPORT_TEMP
if (dbs_tuners_ins.scaling_block_cycles == 0 && dbs_tuners_ins.scaling_block_freq != 0
&& cpu_temp >= dbs_tuners_ins.scaling_block_temp && !suspend_flag) {
if (policy->cur == dbs_tuners_ins.scaling_block_freq) {
cancel_up_scaling = true;
#ifdef ENABLE_HOTPLUGGING
hotplug_up_temp_block = true;
#endif /* ENABLE_HOTPLUGGING */
}
if (policy->cur > dbs_tuners_ins.scaling_block_freq || policy->cur == policy->max) {
scaling_mode_down = 0; // ZZ: if fast scaling down was enabled disable it to be sure that block freq will be met
force_down_scaling = true;
}
}
#endif /* CONFIG_EXYNOS4_EXPORT_TEMP */
// ZZ: start blocking if we are not at suspend freq threshold is reached and max load is not at maximum
if (dbs_tuners_ins.scaling_block_cycles != 0 && policy->cur >= dbs_tuners_ins.scaling_block_freq
&& !suspend_flag && max_load != 100) {
// ZZ: depending on load threshold count the gradients and block up scaling till max cycles are reached
if ((scaling_block_cycles_count <= dbs_tuners_ins.scaling_block_cycles && max_load > this_dbs_info->prev_load
&& max_load - this_dbs_info->prev_load >= dbs_tuners_ins.scaling_block_threshold) ||
(scaling_block_cycles_count <= dbs_tuners_ins.scaling_block_cycles && max_load < this_dbs_info->prev_load
&& this_dbs_info->prev_load - max_load >= dbs_tuners_ins.scaling_block_threshold) ||
dbs_tuners_ins.scaling_block_threshold == 0) {
scaling_block_cycles_count++; // ZZ: count gradients
cancel_up_scaling = true; // ZZ: block scaling up at the same time
}
// ZZ: then switch to 'force down mode'
if (scaling_block_cycles_count == dbs_tuners_ins.scaling_block_cycles) { // ZZ: amount of cycles is reached
if (dbs_tuners_ins.scaling_block_force_down != 0)
scaling_block_cycles_count = dbs_tuners_ins.scaling_block_cycles // ZZ: switch to force down mode if enabled
* dbs_tuners_ins.scaling_block_force_down;
else
scaling_block_cycles_count = 0; // ZZ: down force disabled start from scratch
}
// ZZ: and force down scaling during next given bock cycles
if (scaling_block_cycles_count > dbs_tuners_ins.scaling_block_cycles) {
if (unlikely(--scaling_block_cycles_count > dbs_tuners_ins.scaling_block_cycles))
force_down_scaling = true; // ZZ: force down scaling
else
scaling_block_cycles_count = 0; // ZZ: done -> reset counter
}
}
// ZZ: used for gradient load calculation in fast scaling, scaling block and early demand
if (dbs_tuners_ins.early_demand || dbs_tuners_ins.scaling_block_cycles != 0
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
|| dbs_tuners_ins.fast_scaling_up > 4 || dbs_tuners_ins.fast_scaling_down > 4 || (dbs_tuners_ins.early_demand_sleep && !suspend_flag))
this_dbs_info->prev_load = max_load;
#else
|| dbs_tuners_ins.fast_scaling_up > 4 || dbs_tuners_ins.fast_scaling_down > 4)
this_dbs_info->prev_load = max_load;
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
}
#ifdef ENABLE_HOTPLUGGING
// ZZ: if hotplug idle threshold is reached and cpu frequency is at its minimum disable hotplug
if (policy->cur < dbs_tuners_ins.hotplug_idle_freq && max_load < dbs_tuners_ins.hotplug_idle_threshold
&& dbs_tuners_ins.hotplug_idle_threshold != 0 && !suspend_flag)
hotplug_idle_flag = true;
else
hotplug_idle_flag = false;
num_online_cpus = num_online_cpus();
// ff: calculate hotplug block multipliers
if (num_online_cpus == 1) {
// ff: only main core is online, so apply block_up for core #2 (aka 1)
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] 1 core\n");
#endif /* ZZMOOVE_DEBUG */
zz_hotplug_block_up_cycles = dbs_tuners_ins.hotplug_block_up_cycles * dbs_tuners_ins.block_up_multiplier_hotplug1;
zz_hotplug_block_down_cycles = 0; // ff: if 1 core is online, we can't go below that, so it's a moot setting
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] 1 core - block up: %d, block down: %d\n", zz_hotplug_block_up_cycles, zz_hotplug_block_down_cycles);
#endif /* ZZMOOVE_DEBUG */
#if (MAX_CORES == 2 || MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
} else if (num_online_cpus == 2) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] 2 cores\n");
#endif /* ZZMOOVE_DEBUG */
#if (MAX_CORES == 2)
zz_hotplug_block_up_cycles = 0; // ff: if all cores are online, we can't go above that, so it's a moot setting
#else
zz_hotplug_block_up_cycles = dbs_tuners_ins.hotplug_block_up_cycles * dbs_tuners_ins.block_up_multiplier_hotplug2;
zz_hotplug_block_down_cycles = dbs_tuners_ins.hotplug_block_down_cycles * dbs_tuners_ins.block_down_multiplier_hotplug1;
#endif /* #if (MAX_CORES == 2) */
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] 2 cores - block up: %d, block down: %d\n", zz_hotplug_block_up_cycles, zz_hotplug_block_down_cycles);
#endif /* ZZMOOVE_DEBUG */
#endif /* (MAX_CORES == 2 || MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
} else if (num_online_cpus == 3) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] 3 cores\n");
#endif /* ZZMOOVE_DEBUG */
zz_hotplug_block_up_cycles = dbs_tuners_ins.hotplug_block_up_cycles * dbs_tuners_ins.block_up_multiplier_hotplug3;
zz_hotplug_block_down_cycles = dbs_tuners_ins.hotplug_block_down_cycles * dbs_tuners_ins.block_down_multiplier_hotplug2;
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] 3 cores - block up: %d, block down: %d\n", zz_hotplug_block_up_cycles, zz_hotplug_block_down_cycles);
#endif /* ZZMOOVE_DEBUG */
} else if (num_online_cpus == 4) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] 4 cores\n");
#endif /* ZZMOOVE_DEBUG */
#if (MAX_CORES == 4)
zz_hotplug_block_up_cycles = 0; // ff: if all cores are online, we can't go above that, so it's a moot setting
#else
zz_hotplug_block_up_cycles = dbs_tuners_ins.hotplug_block_up_cycles * dbs_tuners_ins.block_up_multiplier_hotplug4;
zz_hotplug_block_down_cycles = dbs_tuners_ins.hotplug_block_down_cycles * dbs_tuners_ins.block_down_multiplier_hotplug3;
#endif /* (MAX_CORES == 4) */
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] 4 cores - block up: %d, block down: %d\n", zz_hotplug_block_up_cycles, zz_hotplug_block_down_cycles);
#endif /* ZZMOOVE_DEBUG */
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
} else if (num_online_cpus == 5) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] 5 cores\n");
#endif /* ZZMOOVE_DEBUG */
zz_hotplug_block_up_cycles = dbs_tuners_ins.hotplug_block_up_cycles * dbs_tuners_ins.block_up_multiplier_hotplug5;
zz_hotplug_block_down_cycles = dbs_tuners_ins.hotplug_block_down_cycles * dbs_tuners_ins.block_down_multiplier_hotplug4;
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] 5 cores - block up: %d, block down: %d\n", zz_hotplug_block_up_cycles, zz_hotplug_block_down_cycles);
#endif /* ZZMOOVE_DEBUG */
} else if (num_online_cpus == 6) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] 6 cores\n");
#endif /* ZZMOOVE_DEBUG */
#if (MAX_CORES == 6)
zz_hotplug_block_up_cycles = 0; // ff: if all cores are online, we can't go above that, so it's a moot setting
#else
zz_hotplug_block_up_cycles = dbs_tuners_ins.hotplug_block_up_cycles * dbs_tuners_ins.block_up_multiplier_hotplug6;
zz_hotplug_block_down_cycles = dbs_tuners_ins.hotplug_block_down_cycles * dbs_tuners_ins.block_down_multiplier_hotplug5;
#endif /* (MAX_CORES == 6) */
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] 6 cores - block up: %d, block down: %d\n", zz_hotplug_block_up_cycles, zz_hotplug_block_down_cycles);
#endif /* ZZMOOVE_DEBUG */
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
} else if (num_online_cpus == 7) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] 7 cores\n");
#endif /* ZZMOOVE_DEBUG */
zz_hotplug_block_up_cycles = dbs_tuners_ins.hotplug_block_up_cycles * dbs_tuners_ins.block_up_multiplier_hotplug7;
zz_hotplug_block_down_cycles = dbs_tuners_ins.hotplug_block_down_cycles * dbs_tuners_ins.block_down_multiplier_hotplug6;
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] 7 cores - block up: %d, block down: %d\n", zz_hotplug_block_up_cycles, zz_hotplug_block_down_cycles);
#endif /* ZZMOOVE_DEBUG */
} else if (num_online_cpus == 8) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] 8 cores\n");
#endif /* ZZMOOVE_DEBUG */
zz_hotplug_block_up_cycles = 0; // ff: if all cores are online, we can't go above that, so it's a moot setting
zz_hotplug_block_down_cycles = dbs_tuners_ins.hotplug_block_down_cycles * dbs_tuners_ins.block_down_multiplier_hotplug7;
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] 8 cores - block up: %d, block down: %d\n", zz_hotplug_block_up_cycles, zz_hotplug_block_down_cycles);
#endif /* ZZMOOVE_DEBUG */
#endif /* (MAX_CORES == 8) */
}
// ff: make sure counters are synced
if (num_online_cpus != num_online_cpus_last) {
// ff: cores have been changed, counters invalid
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] reset block counters\n");
#endif /* ZZMOOVE_DEBUG */
hplg_up_block_cycles = 0;
hplg_down_block_cycles = 0;
}
// ff: save how many cores were on so we'll know if they changed
num_online_cpus_last = num_online_cpus;
// ZZ: block cycles to be able to slow down hotplugging - added hotplug enagage freq (ffolkes)
// ff: also added a check to see if hotplug_max_limit is requesting only 1 core - if so, no sense in wasting time with hotplugging work
// ff: also added a check for hotplug_lock - if it's enabled, don't hotplug.
if (on_cpu == 0) {
if (((!dbs_tuners_ins.disable_hotplug && num_online_cpus() != possible_cpus) || hotplug_idle_flag)
&& (!dbs_tuners_ins.hotplug_engage_freq || policy->cur >= dbs_tuners_ins.hotplug_engage_freq)
&& (!dbs_tuners_ins.hotplug_max_limit || dbs_tuners_ins.hotplug_max_limit > 1)
&& (!dbs_tuners_ins.hotplug_lock || num_online_cpus() > dbs_tuners_ins.hotplug_lock)) {
if (hplg_up_block_cycles > zz_hotplug_block_up_cycles
|| (!hotplug_up_in_progress && zz_hotplug_block_up_cycles == 0)) {
queue_work_on(0, dbs_wq, &hotplug_online_work);
if (zz_hotplug_block_up_cycles != 0)
hplg_up_block_cycles = 0;
}
if (zz_hotplug_block_up_cycles != 0)
hplg_up_block_cycles++;
}
}
#endif /* ENABLE_HOTPLUGGING */
// ZZ: Sampling rate idle
if (dbs_tuners_ins.sampling_rate_idle != dbs_tuners_ins.sampling_rate
&& max_load > dbs_tuners_ins.sampling_rate_idle_threshold
&& !suspend_flag && dbs_tuners_ins.sampling_rate_current != dbs_tuners_ins.sampling_rate) {
if (sampling_rate_step_up_delay >= dbs_tuners_ins.sampling_rate_idle_delay) {
dbs_tuners_ins.sampling_rate_current = dbs_tuners_ins.sampling_rate;
if (dbs_tuners_ins.sampling_rate_idle_delay != 0)
sampling_rate_step_up_delay = 0;
}
if (dbs_tuners_ins.sampling_rate_idle_delay != 0)
sampling_rate_step_up_delay++;
}
// ZZ: Scaling fastdown and responsiveness thresholds (ffolkes)
if (!suspend_flag && dbs_tuners_ins.scaling_fastdown_freq && policy->cur > dbs_tuners_ins.scaling_fastdown_freq) {
scaling_up_threshold = dbs_tuners_ins.scaling_fastdown_up_threshold;
} else if (!suspend_flag && dbs_tuners_ins.scaling_responsiveness_freq && policy->cur < dbs_tuners_ins.scaling_responsiveness_freq) {
scaling_up_threshold = dbs_tuners_ins.scaling_responsiveness_up_threshold;
} else {
scaling_up_threshold = dbs_tuners_ins.up_threshold;
}
#ifdef ENABLE_INPUTBOOSTER
// ff: apply inputboost up threshold(s)
if (flg_ctr_inputboost > 0 && !suspend_flag) {
if (flg_ctr_inputbooster_typingbooster > 0) {
// ff: override normal inputboost_up_threshold
scaling_up_threshold = dbs_tuners_ins.inputboost_typingbooster_up_threshold;
#ifdef ENABLE_HOTPLUGGING
if (num_online_cpus < dbs_tuners_ins.inputboost_typingbooster_cores) {
// ff: bring core(s) online
if (on_cpu == 0)
queue_work_on(0, dbs_wq, &hotplug_online_work);
}
#endif /* ENABLE_HOTPLUGGING */
flg_ctr_inputbooster_typingbooster--;
} else {
if (dbs_tuners_ins.inputboost_up_threshold) {
// ff: in the future there may be other boost options,
// so be prepared for this one to be 0
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] inputboost - boosting up threshold to: %d, from: %d, %d more times\n", dbs_tuners_ins.inputboost_up_threshold, scaling_up_threshold, flg_ctr_inputboost);
#endif /* ZZMOOVE_DEBUG */
scaling_up_threshold = dbs_tuners_ins.inputboost_up_threshold;
}
}
if (scaling_up_threshold <= dbs_tuners_ins.down_threshold) {
// ff: we need to adjust the down_threshold. also, don't go too low
down_threshold_override = max(11, (int)(scaling_up_threshold - 5));
}
flg_ctr_inputboost--;
#ifdef ZZMOOVE_DEBUG
if (flg_ctr_inputboost < 1) {
pr_info("[zzmoove/dbs_check_cpu] inputboost event expired\n");
}
#endif /* ZZMOOVE_DEBUG */
}
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] up_threshold: %d\n", scaling_up_threshold);
#endif /* ZZMOOVE_DEBUG */
#endif /* ENABLE_INPUTBOOSTER */
// Check for frequency increase
if ((max_load >= scaling_up_threshold || boost_freq) // ZZ: boost switch for early demand and scaling block switches added
&& !cancel_up_scaling && !force_down_scaling) {
#ifdef ENABLE_SNAP_THERMAL_SUPPORT
if (tmu_throttle_steps > 0) {
// ff: thermal throttling is in effect, disregard all other functions
this_dbs_info->requested_freq = zz_get_next_freq(policy->cur, 1, max_load);
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] thermal throttling - cur freq: %d, max: %d, new freq: %d\n", policy->cur, policy->max, this_dbs_info->requested_freq);
#endif /* ZZMOOVE_DEBUG */
__cpufreq_driver_target(policy, this_dbs_info->requested_freq,
CPUFREQ_RELATION_H);
return;
}
#endif /* ENABLE_SNAP_THERMAL_SUPPORT */
// ZZ: Sampling down momentum - if momentum is inactive switch to 'down_skip' method
if (zz_sampling_down_max_mom == 0 && zz_sampling_down_factor > 1)
this_dbs_info->down_skip = 0;
// ZZ: Frequency Limit: if we are at freq_limit break out early
if (dbs_tuners_ins.freq_limit != 0
&& policy->cur == dbs_tuners_ins.freq_limit) {
#ifdef ENABLE_MUSIC_LIMITS
// ff: but what if the music max freq wants to take over?
if (suspend_flag && dbs_tuners_ins.music_max_freq && dbs_tuners_ins.music_state && policy->cur < dbs_tuners_ins.music_max_freq) {
// ff: this is ugly, but this IF is so much easier like this.
} else {
return;
}
#else
return;
#endif /* ENABLE_MUSIC_LIMITS */
}
// if we are already at full speed then break out early but not if freq limit is set
if (policy->cur == policy->max && dbs_tuners_ins.freq_limit == 0) // ZZ: changed check from reqested_freq to current freq (DerTeufel1980)
return;
// ZZ: Sampling down momentum - if momentum is active and we are switching to max speed, apply sampling_down_factor
if (zz_sampling_down_max_mom != 0 && policy->cur < policy->max)
this_dbs_info->rate_mult = zz_sampling_down_factor;
this_dbs_info->requested_freq = zz_get_next_freq(policy->cur, 1, max_load);
if (dbs_tuners_ins.freq_limit != 0
&& this_dbs_info->requested_freq > dbs_tuners_ins.freq_limit) {
#ifdef ENABLE_MUSIC_LIMITS
// ff: right now we normally would let the freq_limit snub this, but we have to see if music needs to take over
if (suspend_flag && dbs_tuners_ins.music_max_freq && dbs_tuners_ins.music_state) {
// ff: screen is off, music freq is set, and music is playing.
// ff: make sure we haven't exceeded the music freq.
if (this_dbs_info->requested_freq > dbs_tuners_ins.music_max_freq) {
this_dbs_info->requested_freq = dbs_tuners_ins.music_max_freq;
}
} else {
this_dbs_info->requested_freq = dbs_tuners_ins.freq_limit;
}
#else
this_dbs_info->requested_freq = dbs_tuners_ins.freq_limit;
#endif /* ENABLE_MUSIC_LIMITS */
}
#ifdef ENABLE_INPUTBOOSTER
if (flg_ctr_inputboost_punch > 0 && this_dbs_info->requested_freq < dbs_tuners_ins.inputboost_punch_freq) {
// ff: inputbooster punch is active and the the target freq needs to be at least that high
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] inputboost - UP too low - repunched freq to %d, from %d\n", dbs_tuners_ins.inputboost_punch_freq, this_dbs_info->requested_freq);
#endif /* ZZMOOVE_DEBUG */
this_dbs_info->requested_freq = dbs_tuners_ins.inputboost_punch_freq;
}
#endif /* ENABLE_INPUTBOOSTER */
#ifdef ENABLE_INPUTBOOSTER
// ff: check to see if we need to block up cycles, only do it if the screen is on, and typingbooster off
if (dbs_tuners_ins.scaling_up_block_cycles && !suspend_flag && flg_ctr_inputbooster_typingbooster < 1) {
#else
// ff: check to see if we need to block up cycles, only do it if the screen is on, and typingbooster off
if (dbs_tuners_ins.scaling_up_block_cycles && !suspend_flag) {
#endif /* ENABLE_INPUTBOOSTER */
// ff: if we're at or beyond the threshold frequency
if (policy->cur >= dbs_tuners_ins.scaling_up_block_freq) {
if (scaling_up_block_cycles_count < dbs_tuners_ins.scaling_up_block_cycles) {
scaling_up_block_cycles_count++;
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] scaling up BLOCKED #%d - cur freq: %d, target freq: %d\n", scaling_up_block_cycles_count, policy->cur, this_dbs_info->requested_freq);
#endif /* ZZMOOVE_DEBUG */
return;
} else {
scaling_up_block_cycles_count = 0;
}
} else {
if (policy->cur < dbs_tuners_ins.scaling_up_block_freq) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] scaling up RESET #%d - cur freq: %d, target freq: %d\n", scaling_up_block_cycles_count, policy->cur, this_dbs_info->requested_freq);
#endif /* ZZMOOVE_DEBUG */
scaling_up_block_cycles_count = 0;
}
}
}
#ifdef ENABLE_MUSIC_LIMITS
if (dbs_tuners_ins.music_min_freq
&& this_dbs_info->requested_freq <= dbs_tuners_ins.music_min_freq
&& dbs_tuners_ins.music_state
) {
// ff: music is playing and there is a min set. ignore the screen-off max and set this then
this_dbs_info->requested_freq = dbs_tuners_ins.music_min_freq;
}
#endif /* ENABLE_MUSIC_LIMITS */
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] scaling up SET - cur freq: %d, max: %d, new freq: %d\n", policy->cur, policy->max, this_dbs_info->requested_freq);
#endif /* ZZMOOVE_DEBUG */
__cpufreq_driver_target(policy, this_dbs_info->requested_freq,
CPUFREQ_RELATION_H);
// ZZ: Sampling down momentum - calculate momentum and update sampling down factor
if (zz_sampling_down_max_mom != 0 && this_dbs_info->momentum_adder
< dbs_tuners_ins.sampling_down_mom_sens) {
this_dbs_info->momentum_adder++;
dbs_tuners_ins.sampling_down_momentum = (this_dbs_info->momentum_adder
* zz_sampling_down_max_mom) / dbs_tuners_ins.sampling_down_mom_sens;
zz_sampling_down_factor = orig_sampling_down_factor
+ dbs_tuners_ins.sampling_down_momentum;
}
return;
}
#ifdef ENABLE_HOTPLUGGING
// ZZ: block cycles to be able to slow down hotplugging
if (on_cpu == 0) {
if (!dbs_tuners_ins.disable_hotplug && num_online_cpus() != 1 && !hotplug_idle_flag) {
if (unlikely(hplg_down_block_cycles >= zz_hotplug_block_down_cycles)
|| (!hotplug_down_in_progress && zz_hotplug_block_down_cycles == 0)) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] offline_work - %d / %d\n", hplg_down_block_cycles, zz_hotplug_block_down_cycles);
#endif /* ZZMOOVE_DEBUG */
queue_work_on(0, dbs_wq, &hotplug_offline_work);
hplg_down_block_cycles = 0;
}
if (zz_hotplug_block_down_cycles != 0) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove] skipped offline_work - %d / %d\n", hplg_down_block_cycles, zz_hotplug_block_down_cycles);
#endif /* ZZMOOVE_DEBUG */
hplg_down_block_cycles++;
}
}
}
#endif /* ENABLE_HOTPLUGGING */
// ZZ: Sampling down momentum - if momentum is inactive switch to down skip method and if sampling_down_factor is active break out early
if (zz_sampling_down_max_mom == 0 && zz_sampling_down_factor > 1) {
if (++this_dbs_info->down_skip < zz_sampling_down_factor)
return;
this_dbs_info->down_skip = 0;
}
// ZZ: Sampling down momentum - calculate momentum and update sampling down factor
if (zz_sampling_down_max_mom != 0 && this_dbs_info->momentum_adder > 1) {
this_dbs_info->momentum_adder -= 2;
dbs_tuners_ins.sampling_down_momentum = (this_dbs_info->momentum_adder
* zz_sampling_down_max_mom) / dbs_tuners_ins.sampling_down_mom_sens;
zz_sampling_down_factor = orig_sampling_down_factor
+ dbs_tuners_ins.sampling_down_momentum;
}
// ZZ: Sampling rate idle
if (dbs_tuners_ins.sampling_rate_idle != dbs_tuners_ins.sampling_rate
&& max_load < dbs_tuners_ins.sampling_rate_idle_threshold && !suspend_flag
&& dbs_tuners_ins.sampling_rate_current != dbs_tuners_ins.sampling_rate_idle) {
if (sampling_rate_step_down_delay >= dbs_tuners_ins.sampling_rate_idle_delay) {
dbs_tuners_ins.sampling_rate_current = dbs_tuners_ins.sampling_rate_idle;
if (dbs_tuners_ins.sampling_rate_idle_delay != 0)
sampling_rate_step_down_delay = 0;
}
if (dbs_tuners_ins.sampling_rate_idle_delay != 0)
sampling_rate_step_down_delay++;
}
// ZZ: Scaling fastdown threshold (ffolkes)
if (!suspend_flag && dbs_tuners_ins.scaling_fastdown_freq != 0 && policy->cur > dbs_tuners_ins.scaling_fastdown_freq)
scaling_down_threshold = dbs_tuners_ins.scaling_fastdown_down_threshold;
else
scaling_down_threshold = dbs_tuners_ins.down_threshold;
// ff: if the up_threshold was boosted, we need to adjust this, too
if (down_threshold_override && down_threshold_override < scaling_down_threshold) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] DOWN - down_threshold override (from: %d, to: %d)\n", scaling_down_threshold, down_threshold_override);
#endif /* ZZMOOVE_DEBUG */
scaling_down_threshold = down_threshold_override;
}
// Check for frequency decrease
if (max_load < scaling_down_threshold || force_down_scaling) { // ZZ: added force down switch
// ZZ: Sampling down momentum - no longer fully busy, reset rate_mult
this_dbs_info->rate_mult = 1;
// if we cannot reduce the frequency anymore, break out early
#ifdef ENABLE_MUSIC_LIMITS
if (policy->cur == policy->min || (dbs_tuners_ins.music_min_freq && dbs_tuners_ins.music_state && policy->cur == dbs_tuners_ins.music_min_freq))
return;
#else
if (policy->cur == policy->min)
return;
#endif /* ENABLE_MUSIC_LIMITS */
this_dbs_info->requested_freq = zz_get_next_freq(policy->cur, 2, max_load);
#ifdef ENABLE_INPUTBOOSTER
if (flg_ctr_inputboost_punch > 0 && this_dbs_info->requested_freq < dbs_tuners_ins.inputboost_punch_freq) {
// ff: inputbooster punch is active and the the target freq needs to be at least that high
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/dbs_check_cpu] inputboost - DOWN too low - repunched freq to %d, from %d\n", dbs_tuners_ins.inputboost_punch_freq, this_dbs_info->requested_freq);
#endif /* ZZMOOVE_DEBUG */
this_dbs_info->requested_freq = dbs_tuners_ins.inputboost_punch_freq;
}
#endif /* ENABLE_INPUTBOOSTER */
if (dbs_tuners_ins.freq_limit != 0 && this_dbs_info->requested_freq
> dbs_tuners_ins.freq_limit)
this_dbs_info->requested_freq = dbs_tuners_ins.freq_limit;
#ifdef ENABLE_MUSIC_LIMITS
if (dbs_tuners_ins.music_min_freq
&& this_dbs_info->requested_freq <= dbs_tuners_ins.music_min_freq
&& dbs_tuners_ins.music_state
) {
this_dbs_info->requested_freq = dbs_tuners_ins.music_min_freq;
}
#endif /* ENABLE_MUSIC_LIMITS */
__cpufreq_driver_target(policy, this_dbs_info->requested_freq,
CPUFREQ_RELATION_L); // ZZ: changed to relation low
return;
}
}
// ZZ/ff: inputbooster work
#ifdef ENABLE_WORK_RESTARTLOOP
static void zz_restartloop_work(struct work_struct *work)
{
struct cpu_dbs_info_s *dbs_info =
container_of(work, struct cpu_dbs_info_s, work.work);
unsigned int cpu = dbs_info->cpu;
work_restartloop_in_progress = true;
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/zz_restartloop_work] restarting cycle\n");
#endif /* ZZMOOVE_DEBUG */
cancel_delayed_work_sync(&dbs_info->work);
flush_workqueue(dbs_wq);
queue_delayed_work_on(cpu, dbs_wq, &dbs_info->work, 0);
work_restartloop_in_progress = false;
}
#endif /* ENABLE_WORK_RESTARTLOOP */
#ifdef ENABLE_SNAP_THERMAL_SUPPORT
static void tt_reset(void)
{
flg_ctr_tmu_overheating = 0;
tmu_throttle_steps = 0;
ctr_tmu_neutral = 0;
ctr_tmu_falling = 0;
}
// ff: Snapdragon thermal tripping
static void tmu_check_work(struct work_struct * work_tmu_check)
{
struct tsens_device tsens_dev;
long temp = 0;
int tmu_temp_delta = 0;
int tmu_temp_eventdelta = 0;
// ff: get temp
tsens_dev.sensor_num = 1;
tsens_get_temp(&tsens_dev, &temp);
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/thermal] sensor: %d, value: %ld\n", tsens_dev.sensor_num, temp);
#endif /* ZZMOOVE_DEBUG */
tmu_temp_cpu = temp;
// ff: check this first, since 99% of the time we'll stop here
if (tmu_temp_cpu < dbs_tuners_ins.scaling_trip_temp) {
flg_ctr_tmu_overheating = 0;
tt_reset();
tmu_temp_cpu_last = temp;
return;
}
if (tmu_temp_cpu >= 75) {
// ff: emergency mode, drop to min freq
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/thermal] ALERT! high temp: %ld, step throttle: %d (%d mhz)\n", temp, tmu_throttle_steps, system_freq_table[max_scaling_freq_soft].frequency);
#endif /* ZZMOOVE_DEBUG */
tmu_throttle_steps = max_scaling_freq_soft;
return;
} else if (tmu_temp_cpu >= 70) {
// ff: emergency mode, drop to min freq + 4
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/thermal] ALERT! high temp: %ld, step throttle: %d (%d mhz)\n", temp, tmu_throttle_steps, system_freq_table[max_scaling_freq_soft - 4].frequency);
#endif /* ZZMOOVE_DEBUG */
tmu_throttle_steps = (max_scaling_freq_soft - 4);
return;
}
if (flg_ctr_tmu_overheating < 1) {
// ff: first run, not overheating
if (temp >= dbs_tuners_ins.scaling_trip_temp) {
flg_ctr_tmu_overheating = 1;
tmu_throttle_steps = 1;
ctr_tmu_falling = 0;
ctr_tmu_neutral = 0;
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/thermal] TRIPPED - was: %d, now: %d - step throttle: %d (%d mhz)\n",
tmu_temp_cpu_last, tmu_temp_cpu, tmu_throttle_steps, system_freq_table[tmu_throttle_steps].frequency);
#endif /* ZZMOOVE_DEBUG */
}
} else {
// ff: another run of overheating
tmu_temp_delta = (tmu_temp_cpu - tmu_temp_cpu_last);
tmu_temp_eventdelta = (tmu_temp_cpu - dbs_tuners_ins.scaling_trip_temp);
// ff: determine direction
if (tmu_temp_delta > 0) {
// ff: ascending
flg_ctr_tmu_overheating++;
tmu_throttle_steps = flg_ctr_tmu_overheating;
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/thermal] RISING - was: %d, now: %d (delta: %d, eventdelta: %d) - step throttle: %d (%d mhz)\n",
tmu_temp_cpu_last, tmu_temp_cpu, tmu_temp_delta, tmu_temp_eventdelta, tmu_throttle_steps, system_freq_table[tmu_throttle_steps].frequency);
#endif /* ZZMOOVE_DEBUG */
ctr_tmu_falling = 0;
ctr_tmu_neutral = 0;
} else if (tmu_temp_delta < 0) {
// ff: descending
ctr_tmu_falling++;
ctr_tmu_neutral = 0;
if (ctr_tmu_falling > 1 && tmu_temp_cpu <= (dbs_tuners_ins.scaling_trip_temp + 2)) {
ctr_tmu_falling = 0;
// ff: don't go too low
if (flg_ctr_tmu_overheating > max_scaling_freq_soft) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/thermal] fell too low - was: %d, now; %d\n", flg_ctr_tmu_overheating, max_scaling_freq_soft);
#endif /* ZZMOOVE_DEBUG */
flg_ctr_tmu_overheating = max_scaling_freq_soft;
}
flg_ctr_tmu_overheating--;
if (flg_ctr_tmu_overheating < 0) {
flg_ctr_tmu_overheating = 1;
}
tmu_throttle_steps = flg_ctr_tmu_overheating;
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/thermal] FALLING - was: %d, now: %d (delta: %d, eventdelta: %d) - step throttle: %d (%d mhz)\n",
tmu_temp_cpu_last, tmu_temp_cpu, tmu_temp_delta, tmu_temp_eventdelta, tmu_throttle_steps, system_freq_table[tmu_throttle_steps].frequency);
} else {
pr_info("[zzmoove/thermal] FALLING - IGNORING - was: %d, now: %d (delta: %d, eventdelta: %d) - step throttle: %d (%d mhz)\n",
tmu_temp_cpu_last, tmu_temp_cpu, tmu_temp_delta, tmu_temp_eventdelta, tmu_throttle_steps, system_freq_table[tmu_throttle_steps].frequency);
#endif /* ZZMOOVE_DEBUG */
}
} else {
// ff: neutral
ctr_tmu_neutral++;
//ctr_tmu_falling = 0;
if (ctr_tmu_neutral > 2 && tmu_temp_cpu >= (dbs_tuners_ins.scaling_trip_temp + 5)) {
// ff: if it has remained neutral for too long, throttle more
ctr_tmu_neutral = 0;
flg_ctr_tmu_overheating++;
tmu_throttle_steps = flg_ctr_tmu_overheating;
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/thermal] STEADY - now: %d - step throttle: %d (%d mhz)\n", tmu_temp_cpu, tmu_throttle_steps, system_freq_table[tmu_throttle_steps].frequency);
} else {
pr_info("[zzmoove/thermal] STEADY - IGNORING - was: %d, now: %d (delta: %d, eventdelta: %d) - step throttle: %d (%d mhz)\n",
tmu_temp_cpu_last, tmu_temp_cpu, tmu_temp_delta, tmu_temp_eventdelta, tmu_throttle_steps, system_freq_table[tmu_throttle_steps].frequency);
#endif /* ZZMOOVE_DEBUG */
}
}
}
// ff: save the temp for the next loop.
tmu_temp_cpu_last = temp;
}
#endif /* ENABLE_SNAP_THERMAL_SUPPORT */
// ZZ: function for hotplug down work
#ifdef ENABLE_HOTPLUGGING
static void __cpuinit hotplug_offline_work_fn(struct work_struct *work)
{
int cpu; // ZZ: for hotplug down loop
hotplug_down_in_progress = true;
if (dbs_tuners_ins.hotplug_lock > 0)
disable_cores = 1;
if (disable_cores > 0) {
enable_disable_cores();
hotplug_down_in_progress = false;
return;
}
// Yank: added frequency thresholds
for_each_online_cpu(cpu) {
if (likely(cpu_online(cpu) && (cpu)) && cpu != 0
&& cur_load <= hotplug_thresholds[1][cpu-1]
&& (!dbs_tuners_ins.hotplug_min_limit || cpu >= dbs_tuners_ins.hotplug_min_limit)
#ifdef ENABLE_MUSIC_LIMITS
&& (!dbs_tuners_ins.music_state || (dbs_tuners_ins.music_state
&& (!dbs_tuners_ins.music_min_cores || cpu >= dbs_tuners_ins.music_min_cores)))
#endif /* ENABLE_MUSIC_LIMITS */
#ifdef ENABLE_INPUTBOOSTER
&& (!dbs_tuners_ins.hotplug_min_limit_touchbooster || cpu >= dbs_tuners_ins.hotplug_min_limit_touchbooster)
#endif /* ENABLE_INPUTBOOSTER */
&& (hotplug_thresholds_freq[1][cpu-1] == 0
|| cur_freq <= hotplug_thresholds_freq[1][cpu-1]
#ifdef ENABLE_AUTO_ADJUST_FREQ
|| hotplug_freq_threshold_out_of_range[1][cpu-1])
#else
)
#endif /* ENABLE_AUTO_ADJUST_FREQ */
) {
#ifdef ZZMOOVE_DEBUG
#if defined(ENABLE_MUSIC_LIMITS) && defined(ENABLE_AUTO_ADJUST_FREQ)
pr_info("[zzmoove/hotplug_offline_work] turning off cpu: %d, load: %d / %d, min_limit: %d music_min: %d (saved: %d), min_touchbooster: %d, freq: %d / %d, mftl: %d\n",
cpu, cur_load, hotplug_thresholds[1][cpu-1], dbs_tuners_ins.hotplug_min_limit, dbs_tuners_ins.music_min_cores, dbs_tuners_ins.hotplug_min_limit_saved,
dbs_tuners_ins.hotplug_min_limit_touchbooster, cur_freq, hotplug_thresholds_freq[1][cpu-1], hotplug_freq_threshold_out_of_range[1][cpu-1]);
#elif defined(ENABLE_MUSIC_LIMITS) && !defined(ENABLE_AUTO_ADJUST_FREQ)
pr_info("[zzmoove/hotplug_offline_work] turning off cpu: %d, load: %d / %d, min_limit: %d music_min: %d (saved: %d), min_touchbooster: %d, freq: %d, mftl: %d\n",
cpu, cur_load, hotplug_thresholds[1][cpu-1], dbs_tuners_ins.hotplug_min_limit, dbs_tuners_ins.music_min_cores, dbs_tuners_ins.hotplug_min_limit_saved,
dbs_tuners_ins.hotplug_min_limit_touchbooster, cur_freq, hotplug_thresholds_freq[1][cpu-1]);
#elif !defined(ENABLE_MUSIC_LIMITS) && defined(ENABLE_AUTO_ADJUST_FREQ)
pr_info("[zzmoove/hotplug_offline_work] turning off cpu: %d, load: %d / %d, min_limit: %d (saved: %d), min_touchbooster: %d, freq: %d / %d, mftl: %d\n",
cpu, cur_load, hotplug_thresholds[1][cpu-1], dbs_tuners_ins.hotplug_min_limit, dbs_tuners_ins.hotplug_min_limit_saved,
dbs_tuners_ins.hotplug_min_limit_touchbooster, cur_freq, hotplug_thresholds_freq[1][cpu-1], hotplug_freq_threshold_out_of_range[1][cpu-1]);
#elif !defined(ENABLE_MUSIC_LIMITS) && !defined(ENABLE_AUTO_ADJUST_FREQ)
pr_info("[zzmoove/hotplug_offline_work] turning off cpu: %d, load: %d / %d, min_limit: %d (saved: %d), min_touchbooster: %d, freq: %d, mftl: %d\n",
cpu, cur_load, hotplug_thresholds[1][cpu-1], dbs_tuners_ins.hotplug_min_limit, dbs_tuners_ins.hotplug_min_limit_saved,
dbs_tuners_ins.hotplug_min_limit_touchbooster, cur_freq, hotplug_thresholds_freq[1][cpu-1]);
#endif /* defined(ENABLE_MUSIC_LIMITS)... */
#endif /* ZZMOOVE_DEBUG */
#ifdef ENABLE_INPUTBOOSTER
// ff: don't take this cpu offline if it is less than what the typingbooster set
if (flg_ctr_inputbooster_typingbooster > 0 && cpu < dbs_tuners_ins.inputboost_typingbooster_cores) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/hotplug_offline_work] typing booster requested cpu%d on, trying next cpu...\n", cpu);
#endif /* ZZMOOVE_DEBUG */
continue;
}
#endif /* ENABLE_INPUTBOOSTER */
if (dbs_tuners_ins.hotplug_stagger_down) {
// ff: stagger and remove core incrementally
if (cpu < (possible_cpus - 1) && cpu_online(cpu + 1)) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/hotplug_offline_work] higher cpu (%d) is still online, trying next cpu...\n", cpu + 1);
#endif /* ZZMOOVE_DEBUG */
continue;
}
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/hotplug_offline_work] CPU %d OFF\n", cpu);
#endif /* ZZMOOVE_DEBUG */
cpu_down(cpu);
// ff: break after a core removed
hotplug_down_in_progress = false;
return;
} else {
// ff: remove core normally
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/hotplug_offline_work] CPU %d OFF\n", cpu);
#endif /* ZZMOOVE_DEBUG */
cpu_down(cpu);
}
}
}
hotplug_down_in_progress = false;
}
// ZZ: function for hotplug up work
static void __cpuinit hotplug_online_work_fn(struct work_struct *work)
{
int i = 0; // ZZ: for hotplug up loop
hotplug_up_in_progress = true;
#ifdef CONFIG_EXYNOS4_EXPORT_TEMP
if (hotplug_up_temp_block) {
hotplug_up_temp_block = false;
hotplug_up_in_progress = false;
return;
}
#endif /* CONFIG_EXYNOS4_EXPORT_TEMP */
if (dbs_tuners_ins.hotplug_lock > 0)
disable_cores = 3;
/*
* ZZ: hotplug idle flag to enable offline cores on idle to avoid higher/achieve balanced cpu load at idle
* and enable cores flag to enable offline cores on governor stop and at late resume
*/
if (unlikely(hotplug_idle_flag || enable_cores > 0)){
enable_disable_cores();
hotplug_up_in_progress = false;
return;
}
#ifdef ENABLE_INPUTBOOSTER
if (flg_ctr_inputbooster_typingbooster > 0 && num_online_cpus() < dbs_tuners_ins.inputboost_typingbooster_cores) {
for (i = 1; i < num_possible_cpus(); i++) {
if (!cpu_online(i) && i < dbs_tuners_ins.inputboost_typingbooster_cores) {
cpu_up(i);
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/hotplug_online_work_fn/typingbooster] cpu%d forced online\n", i);
#endif /* ZZMOOVE_DEBUG */
}
}
}
#endif /* ENABLE_INPUTBOOSTER */
// Yank: added frequency thresholds
for (i = 1; likely(i < possible_cpus); i++) {
if (!cpu_online(i) && hotplug_thresholds[0][i-1] != 0 && cur_load >= hotplug_thresholds[0][i-1]
&& (!dbs_tuners_ins.hotplug_max_limit || i < dbs_tuners_ins.hotplug_max_limit)
&& (hotplug_thresholds_freq[0][i-1] == 0 || cur_freq >= hotplug_thresholds_freq[0][i-1]
|| boost_hotplug
#ifdef ENABLE_AUTO_ADJUST_FREQ
|| hotplug_freq_threshold_out_of_range[0][i-1])
#else
)
#endif /* ENABLE_AUTO_ADJUST_FREQ */
) {
#ifdef ZZMOOVE_DEBUG
#if defined(ENABLE_MUSIC_LIMITS) && defined(ENABLE_AUTO_ADJUST_FREQ)
pr_info("[zzmoove/hotplug_online_work] turning on cpu: %d, load: %d / %d, min_limit: %d music_min: %d (saved: %d), min_touchbooster: %d, freq: %d / %d, mftl: %d\n",
i, cur_load, hotplug_thresholds[0][i-1], dbs_tuners_ins.hotplug_min_limit, dbs_tuners_ins.music_min_cores, dbs_tuners_ins.hotplug_min_limit_saved,
dbs_tuners_ins.hotplug_min_limit_touchbooster, cur_freq, hotplug_thresholds_freq[0][i-1], hotplug_freq_threshold_out_of_range[0][i-1]);
#elif defined(ENABLE_MUSIC_LIMITS) && !defined(ENABLE_AUTO_ADJUST_FREQ)
pr_info("[zzmoove/hotplug_online_work] turning on cpu: %d, load: %d / %d, min_limit: %d music_min: %d (saved: %d), min_touchbooster: %d, freq: %d, mftl: %d\n",
i, cur_load, hotplug_thresholds[0][i-1], dbs_tuners_ins.hotplug_min_limit, dbs_tuners_ins.music_min_cores, dbs_tuners_ins.hotplug_min_limit_saved,
dbs_tuners_ins.hotplug_min_limit_touchbooster, cur_freq, hotplug_thresholds_freq[0][i-1]);
#elif !defined(ENABLE_MUSIC_LIMITS) && defined(ENABLE_AUTO_ADJUST_FREQ)
pr_info("[zzmoove/hotplug_online_work] turning on cpu: %d, load: %d / %d, min_limit: %d (saved: %d), min_touchbooster: %d, freq: %d / %d, mftl: %d\n",
i, cur_load, hotplug_thresholds[0][i-1], dbs_tuners_ins.hotplug_min_limit, dbs_tuners_ins.hotplug_min_limit_saved,
dbs_tuners_ins.hotplug_min_limit_touchbooster, cur_freq, hotplug_thresholds_freq[0][i-1], hotplug_freq_threshold_out_of_range[0][i-1]);
#elif !defined(ENABLE_MUSIC_LIMITS) && !defined(ENABLE_AUTO_ADJUST_FREQ)
pr_info("[zzmoove/hotplug_online_work] turning on cpu: %d, load: %d / %d, min_limit: %d (saved: %d), min_touchbooster: %d, freq: %d, mftl: %d\n",
i, cur_load, hotplug_thresholds[0][i-1], dbs_tuners_ins.hotplug_min_limit, dbs_tuners_ins.hotplug_min_limit_saved,
dbs_tuners_ins.hotplug_min_limit_touchbooster, cur_freq, hotplug_thresholds_freq[0][i-1]);
#endif /* defined(ENABLE_MUSIC_LIMITS)... */
#endif /* ZZMOOVE_DEBUG */
// ff: stagger and add core incrementally
if (dbs_tuners_ins.hotplug_stagger_up) {
if (i > 1 && !cpu_online(i - 1)) {
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/hotplug_online_work] previous cpu (%d) was not online, aborting work\n", i - 1);
#endif /* ZZMOOVE_DEBUG */
hotplug_up_in_progress = false;
return;
}
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/hotplug_online_work] CPU %d ON\n", i);
#endif /* ZZMOOVE_DEBUG */
cpu_up(i);
// ff: break after a core added
hotplug_up_in_progress = false;
return;
} else {
// ff: add core normally
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/hotplug_online_work] CPU %d ON\n", i);
#endif /* ZZMOOVE_DEBUG */
cpu_up(i);
}
}
}
hotplug_up_in_progress = false;
}
#endif /* ENABLE_HOTPLUGGING */
#ifdef CONFIG_EXYNOS4_EXPORT_TEMP
// ZZ: function for exynos4 CPU temperature reading
static void tmu_read_temperature(struct work_struct * tmu_read_work)
{
cpu_temp = get_exynos4_temperature();
return;
}
#endif /* CONFIG_EXYNOS4_EXPORT_TEMP */
static void do_dbs_timer(struct work_struct *work)
{
struct cpu_dbs_info_s *dbs_info =
container_of(work, struct cpu_dbs_info_s, work.work);
unsigned int cpu = dbs_info->cpu;
#ifdef ENABLE_SNAP_THERMAL_SUPPORT
unsigned int tmu_check_delay = 0;
#endif /* ENABLE_SNAP_THERMAL_SUPPORT */
// We want all CPUs to do sampling nearly on same jiffy
int delay = usecs_to_jiffies(dbs_tuners_ins.sampling_rate_current * dbs_info->rate_mult); // ZZ: Sampling down momentum - added multiplier
#ifdef CONFIG_EXYNOS4_EXPORT_TEMP
// ZZ: start reading of temperature from exynos4 thermal management driver but disable it at suspend
if (dbs_tuners_ins.scaling_block_temp != 0) { // ZZ: only if it is enabled and we are not at suspend
if (!suspend_flag) {
schedule_delayed_work(&tmu_read_work, msecs_to_jiffies(DEF_TMU_READ_DELAY)); // ZZ: start work
temp_reading_started = true; // ZZ: set work started flag
cancel_temp_reading = false; // ZZ: reset cancel flag
} else {
cancel_temp_reading = true; // ZZ: else set cancel flag
}
if (temp_reading_started && cancel_temp_reading) { // ZZ: if work was started and cancel flag was set
cancel_delayed_work(&tmu_read_work); // ZZ: cancel work
cancel_temp_reading = false; // ZZ: reset cancel flag
temp_reading_started = false; // ZZ: reset started flag
}
}
if (dbs_tuners_ins.scaling_block_temp == 0 && temp_reading_started) // ZZ: if temp reading was disabled via sysfs and work was started
cancel_delayed_work(&tmu_read_work); // ZZ: cancel work
#endif /* CONFIG_EXYNOS4_EXPORT_TEMP */
#ifdef ENABLE_SNAP_THERMAL_SUPPORT
if (dbs_tuners_ins.scaling_trip_temp > 0) {
if (!suspend_flag)
tmu_check_delay = DEF_TMU_CHECK_DELAY;
else
tmu_check_delay = DEF_TMU_CHECK_DELAY_SLEEP;
schedule_delayed_work(&work_tmu_check, msecs_to_jiffies(tmu_check_delay));
} else {
tt_reset();
}
#endif /* ENABLE_SNAP_THERMAL_SUPPORT */
delay -= jiffies % delay;
mutex_lock(&dbs_info->timer_mutex);
dbs_check_cpu(dbs_info);
queue_delayed_work_on(cpu, dbs_wq, &dbs_info->work, delay);
mutex_unlock(&dbs_info->timer_mutex);
}
static inline void dbs_timer_init(struct cpu_dbs_info_s *dbs_info)
{
// We want all CPUs to do sampling nearly on same jiffy
int delay = usecs_to_jiffies(dbs_tuners_ins.sampling_rate_current);
delay -= jiffies % delay;
dbs_info->enable = 1;
dbs_info_enabled = true;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,7,0)
INIT_DEFERRABLE_WORK(&dbs_info->work, do_dbs_timer);
#else
INIT_DELAYED_WORK_DEFERRABLE(&dbs_info->work, do_dbs_timer);
#endif /* LINUX_VERSION_CODE... */
queue_delayed_work_on(dbs_info->cpu, dbs_wq, &dbs_info->work, delay);
}
static inline void dbs_timer_exit(struct cpu_dbs_info_s *dbs_info)
{
dbs_info->enable = 0;
dbs_info_enabled = false;
cancel_delayed_work_sync(&dbs_info->work);
#ifdef CONFIG_EXYNOS4_EXPORT_TEMP
cancel_delayed_work(&tmu_read_work); // ZZ: cancel cpu temperature reading
#endif /* CONFIG_EXYNOS4_EXPORT_TEMP */
}
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
// raise sampling rate to SR*multiplier and adjust sampling rate/thresholds/hotplug/scaling/freq limit/freq step on blank screen
#if defined(CONFIG_HAS_EARLYSUSPEND) && !defined(USE_LCD_NOTIFIER)
static void __cpuinit powersave_early_suspend(struct early_suspend *handler)
#elif defined(CONFIG_POWERSUSPEND) && !defined(USE_LCD_NOTIFIER) || defined(CONFIG_POWERSUSPEND) && defined(USE_LCD_NOTIFIER)
static void __cpuinit powersave_suspend(struct power_suspend *handler)
#elif defined(USE_LCD_NOTIFIER)
void zzmoove_suspend(void)
#endif /* defined(CONFIG_HAS_EARLYSUSPEND)... */
{
if (!freq_table_desc && limit_table_start != 0) // ZZ: asc: when entering suspend reset freq table start point to full range in case it
limit_table_start = 0; // was changed for example because of pol min boosts - this is important otherwise
// freq will stuck at soft limit and wont go below anymore!
suspend_flag = true; // ZZ: we want to know if we are at suspend because of things that shouldn't be executed at suspend
sampling_rate_awake = dbs_tuners_ins.sampling_rate_current; // ZZ: save current sampling rate for restore on awake
up_threshold_awake = dbs_tuners_ins.up_threshold; // ZZ: save up threshold for restore on awake
down_threshold_awake = dbs_tuners_ins.down_threshold; // ZZ: save down threhold for restore on awake
zz_sampling_down_max_mom = 0; // ZZ: sampling down momentum - disabled at suspend
smooth_up_awake = dbs_tuners_ins.smooth_up; // ZZ: save smooth up value for restore on awake
fast_scaling_up_awake = dbs_tuners_ins.fast_scaling_up; // Yank: save scaling setting for restore on awake for upscaling
fast_scaling_down_awake = dbs_tuners_ins.fast_scaling_down; // Yank: save scaling setting for restore on awake for downscaling
#ifdef ENABLE_HOTPLUGGING
disable_hotplug_awake = dbs_tuners_ins.disable_hotplug; // ZZ: save hotplug switch state for restore on awake
hotplug1_awake = dbs_tuners_ins.up_threshold_hotplug1; // ZZ: save hotplug1 value for restore on awake
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
hotplug2_awake = dbs_tuners_ins.up_threshold_hotplug2; // ZZ: save hotplug2 value for restore on awake
hotplug3_awake = dbs_tuners_ins.up_threshold_hotplug3; // ZZ: save hotplug3 value for restore on awake
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
hotplug4_awake = dbs_tuners_ins.up_threshold_hotplug4; // ZZ: save hotplug4 value for restore on awake
hotplug5_awake = dbs_tuners_ins.up_threshold_hotplug5; // ZZ: save hotplug5 value for restore on awake
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
hotplug6_awake = dbs_tuners_ins.up_threshold_hotplug6; // ZZ: save hotplug6 value for restore on awake
hotplug7_awake = dbs_tuners_ins.up_threshold_hotplug7; // ZZ: save hotplug7 value for restore on awake
#endif /* (MAX_CORES == 8) */
#endif /* ENABLE_HOTPLUGGING */
sampling_rate_asleep = dbs_tuners_ins.sampling_rate_sleep_multiplier; // ZZ: save sleep multiplier for sleep
up_threshold_asleep = dbs_tuners_ins.up_threshold_sleep; // ZZ: save up threshold for sleep
down_threshold_asleep = dbs_tuners_ins.down_threshold_sleep; // ZZ: save down threshold for sleep
smooth_up_asleep = dbs_tuners_ins.smooth_up_sleep; // ZZ: save smooth up for sleep
fast_scaling_up_asleep = dbs_tuners_ins.fast_scaling_sleep_up; // Yank: save fast scaling for sleep for upscaling
fast_scaling_down_asleep = dbs_tuners_ins.fast_scaling_sleep_down; // Yank: save fast scaling for sleep for downscaling
#ifdef ENABLE_HOTPLUGGING
disable_hotplug_asleep = dbs_tuners_ins.disable_hotplug_sleep; // ZZ: save disable hotplug switch for sleep
#endif /* ENABLE_HOTPLUGGING */
dbs_tuners_ins.sampling_rate_current = dbs_tuners_ins.sampling_rate_idle
* sampling_rate_asleep; // ZZ: set sampling rate for sleep
dbs_tuners_ins.up_threshold = up_threshold_asleep; // ZZ: set up threshold for sleep
dbs_tuners_ins.down_threshold = down_threshold_asleep; // ZZ: set down threshold for sleep
dbs_tuners_ins.smooth_up = smooth_up_asleep; // ZZ: set smooth up for for sleep
dbs_tuners_ins.freq_limit = freq_limit_asleep; // ZZ: set freqency limit for sleep
dbs_tuners_ins.fast_scaling_up = fast_scaling_up_asleep; // Yank: set fast scaling for sleep for upscaling
dbs_tuners_ins.fast_scaling_down = fast_scaling_down_asleep; // Yank: set fast scaling for sleep for downscaling
#ifdef ENABLE_HOTPLUGGING
dbs_tuners_ins.disable_hotplug = disable_hotplug_asleep; // ZZ: set hotplug switch for sleep
#endif /* ENABLE_HOTPLUGGING */
evaluate_scaling_order_limit_range(0, 0, suspend_flag, 0, 0); // ZZ: table order detection and limit optimizations
#ifdef ENABLE_HOTPLUGGING
if (dbs_tuners_ins.disable_hotplug_sleep == 1) { // ZZ: enable all cores at suspend if disable hotplug sleep is set
enable_cores = 1;
queue_work_on(0, dbs_wq, &hotplug_online_work);
}
#endif /* ENABLE_HOTPLUGGING */
if (dbs_tuners_ins.fast_scaling_up > 4) // Yank: set scaling mode
scaling_mode_up = 0; // ZZ: auto fast scaling
else
scaling_mode_up = dbs_tuners_ins.fast_scaling_up; // Yank: fast scaling up only
if (dbs_tuners_ins.fast_scaling_down > 4) // Yank: set scaling mode
scaling_mode_down = 0; // ZZ: auto fast scaling
else
scaling_mode_down = dbs_tuners_ins.fast_scaling_down; // Yank: fast scaling up only
#ifdef ENABLE_HOTPLUGGING
if (likely(dbs_tuners_ins.hotplug_sleep != 0)
#ifdef ENABLE_MUSIC_LIMITS
&& !dbs_tuners_ins.music_state) { // ZZ: if set to 0 or music state is enabled do not touch hotplugging values
#else
) {
#endif /* ENABLE_MUSIC_LIMITS */
if (dbs_tuners_ins.hotplug_sleep == 1) {
dbs_tuners_ins.up_threshold_hotplug1 = 0; // ZZ: set to one core
hotplug_thresholds[0][0] = 0;
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
dbs_tuners_ins.up_threshold_hotplug2 = 0; // ZZ: set to one core
hotplug_thresholds[0][1] = 0;
dbs_tuners_ins.up_threshold_hotplug3 = 0; // ZZ: set to one core
hotplug_thresholds[0][2] = 0;
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
dbs_tuners_ins.up_threshold_hotplug4 = 0; // ZZ: set to one core
hotplug_thresholds[0][3] = 0;
dbs_tuners_ins.up_threshold_hotplug5 = 0; // ZZ: set to one core
hotplug_thresholds[0][4] = 0;
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
dbs_tuners_ins.up_threshold_hotplug6 = 0; // ZZ: set to one core
hotplug_thresholds[0][5] = 0;
dbs_tuners_ins.up_threshold_hotplug7 = 0; // ZZ: set to one core
hotplug_thresholds[0][6] = 0;
#endif /* (MAX_CORES == 8) */
}
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
if (dbs_tuners_ins.hotplug_sleep == 2) {
dbs_tuners_ins.up_threshold_hotplug2 = 0; // ZZ: set to two cores
hotplug_thresholds[0][1] = 0;
dbs_tuners_ins.up_threshold_hotplug3 = 0; // ZZ: set to two cores
hotplug_thresholds[0][2] = 0;
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
dbs_tuners_ins.up_threshold_hotplug4 = 0; // ZZ: set to two cores
hotplug_thresholds[0][3] = 0;
dbs_tuners_ins.up_threshold_hotplug5 = 0; // ZZ: set to two cores
hotplug_thresholds[0][4] = 0;
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
dbs_tuners_ins.up_threshold_hotplug6 = 0; // ZZ: set to two cores
hotplug_thresholds[0][5] = 0;
dbs_tuners_ins.up_threshold_hotplug7 = 0; // ZZ: set to two cores
hotplug_thresholds[0][6] = 0;
#endif /* (MAX_CORES == 8) */
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
}
if (dbs_tuners_ins.hotplug_sleep == 3) {
dbs_tuners_ins.up_threshold_hotplug3 = 0; // ZZ: set to three cores
hotplug_thresholds[0][2] = 0;
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
dbs_tuners_ins.up_threshold_hotplug4 = 0; // ZZ: set to three cores
hotplug_thresholds[0][3] = 0;
dbs_tuners_ins.up_threshold_hotplug5 = 0; // ZZ: set to three cores
hotplug_thresholds[0][4] = 0;
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
dbs_tuners_ins.up_threshold_hotplug6 = 0; // ZZ: set to three cores
hotplug_thresholds[0][5] = 0;
dbs_tuners_ins.up_threshold_hotplug7 = 0; // ZZ: set to three cores
hotplug_thresholds[0][6] = 0;
#endif /* (MAX_CORES == 8) */
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
}
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
if (dbs_tuners_ins.hotplug_sleep == 4) {
dbs_tuners_ins.up_threshold_hotplug4 = 0; // ZZ: set to four cores
hotplug_thresholds[0][3] = 0;
dbs_tuners_ins.up_threshold_hotplug5 = 0; // ZZ: set to four cores
hotplug_thresholds[0][4] = 0;
dbs_tuners_ins.up_threshold_hotplug6 = 0; // ZZ: set to four cores
hotplug_thresholds[0][5] = 0;
dbs_tuners_ins.up_threshold_hotplug7 = 0; // ZZ: set to four cores
hotplug_thresholds[0][6] = 0;
}
if (dbs_tuners_ins.hotplug_sleep == 5) {
dbs_tuners_ins.up_threshold_hotplug5 = 0; // ZZ: set to five cores
hotplug_thresholds[0][4] = 0;
dbs_tuners_ins.up_threshold_hotplug6 = 0; // ZZ: set to five cores
hotplug_thresholds[0][5] = 0;
dbs_tuners_ins.up_threshold_hotplug7 = 0; // ZZ: set to five cores
hotplug_thresholds[0][6] = 0;
}
if (dbs_tuners_ins.hotplug_sleep == 6) {
dbs_tuners_ins.up_threshold_hotplug6 = 0; // ZZ: set to six cores
hotplug_thresholds[0][5] = 0;
dbs_tuners_ins.up_threshold_hotplug7 = 0; // ZZ: set to six cores
hotplug_thresholds[0][6] = 0;
}
if (dbs_tuners_ins.hotplug_sleep == 7) {
dbs_tuners_ins.up_threshold_hotplug7 = 0; // ZZ: set to seven cores
hotplug_thresholds[0][6] = 0;
}
#endif /* (MAX_CORES == 8) */
}
#endif /* ENABLE_HOTPLUGGING */
#ifdef ENABLE_INPUTBOOSTER
// ff: reset some stuff.
flg_ctr_cpuboost = 0;
flg_ctr_inputboost = 0;
flg_ctr_inputboost_punch = 0;
flg_ctr_inputbooster_typingbooster = 0;
#endif /* ENABLE_INPUTBOOSTER */
scaling_up_block_cycles_count = 0;
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/lcd_notifier] Suspend function executed.\n");
#endif /* ZZMOOVE_DEBUG */
}
#if defined(CONFIG_HAS_EARLYSUSPEND) && !defined(USE_LCD_NOTIFIER)
static void __cpuinit powersave_late_resume(struct early_suspend *handler)
#elif defined(CONFIG_POWERSUSPEND) && !defined(USE_LCD_NOTIFIER) || defined(CONFIG_POWERSUSPEND) && defined(USE_LCD_NOTIFIER)
static void __cpuinit powersave_resume(struct power_suspend *handler)
#elif defined(USE_LCD_NOTIFIER)
void zzmoove_resume(void)
#endif /* defined(CONFIG_HAS_EARLYSUSPEND)... */
{
suspend_flag = false; // ZZ: we are resuming so reset supend flag
scaling_mode_up = 4; // ZZ: scale up as fast as possibe
boost_freq = true; // ZZ: and boost freq in addition
#ifdef ENABLE_HOTPLUGGING
if (dbs_tuners_ins.disable_hotplug_sleep == 0) {
enable_cores = 1;
queue_work_on(0, dbs_wq, &hotplug_online_work); // ZZ: enable offline cores to avoid stuttering after resume if hotplugging limit was active
}
#endif /* ENABLE_HOTPLUGGING */
#ifdef ENABLE_INPUTBOOSTER
if (flg_ctr_cpuboost < 5)
flg_ctr_cpuboost = 5;
#endif /* ENABLE_INPUTBOOSTER */
#ifdef ENABLE_WORK_RESTARTLOOP
// ff: immediately call the dbs loop to apply the boost
if (!work_restartloop_in_progress)
queue_work_on(0, dbs_aux_wq, &work_restartloop);
#endif /* ENABLE_WORK_RESTARTLOOP */
#ifdef ENABLE_HOTPLUGGING
if (likely(dbs_tuners_ins.hotplug_sleep != 0)
#ifdef ENABLE_MUSIC_LIMITS
&& !dbs_tuners_ins.music_state) {
#else
) {
#endif /* ENABLE_MUSIC_LIMITS */
dbs_tuners_ins.up_threshold_hotplug1 = hotplug1_awake; // ZZ: restore previous settings
hotplug_thresholds[0][0] = hotplug1_awake;
#if (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8)
dbs_tuners_ins.up_threshold_hotplug2 = hotplug2_awake; // ZZ: restore previous settings
hotplug_thresholds[0][1] = hotplug2_awake;
dbs_tuners_ins.up_threshold_hotplug3 = hotplug3_awake; // ZZ: restore previous settings
hotplug_thresholds[0][2] = hotplug3_awake;
#endif /* (MAX_CORES == 4 || MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 6 || MAX_CORES == 8)
dbs_tuners_ins.up_threshold_hotplug4 = hotplug4_awake; // ZZ: restore previous settings
hotplug_thresholds[0][3] = hotplug4_awake;
dbs_tuners_ins.up_threshold_hotplug5 = hotplug5_awake; // ZZ: restore previous settings
hotplug_thresholds[0][4] = hotplug5_awake;
#endif /* (MAX_CORES == 6 || MAX_CORES == 8) */
#if (MAX_CORES == 8)
dbs_tuners_ins.up_threshold_hotplug6 = hotplug6_awake; // ZZ: restore previous settings
hotplug_thresholds[0][5] = hotplug6_awake;
dbs_tuners_ins.up_threshold_hotplug7 = hotplug7_awake; // ZZ: restore previous settings
hotplug_thresholds[0][6] = hotplug7_awake;
#endif /* (MAX_CORES == 8) */
}
#endif /* ENABLE_HOTPLUGGING */
zz_sampling_down_max_mom = orig_sampling_down_max_mom; // ZZ: Sampling down momentum - restore max value
dbs_tuners_ins.sampling_rate_current = sampling_rate_awake; // ZZ: restore previous settings
dbs_tuners_ins.up_threshold = up_threshold_awake; // ZZ: restore previous settings
dbs_tuners_ins.down_threshold = down_threshold_awake; // ZZ: restore previous settings
dbs_tuners_ins.smooth_up = smooth_up_awake; // ZZ: restore previous settings
dbs_tuners_ins.freq_limit = freq_limit_awake; // ZZ: restore previous settings
dbs_tuners_ins.fast_scaling_up = fast_scaling_up_awake; // Yank: restore previous settings for upscaling
dbs_tuners_ins.fast_scaling_down = fast_scaling_down_awake; // Yank: restore previous settings for downscaling
#ifdef ENABLE_HOTPLUGGING
dbs_tuners_ins.disable_hotplug = disable_hotplug_awake; // ZZ: restore previous settings
#endif /* ENABLE_HOTPLUGGING */
evaluate_scaling_order_limit_range(0, 0, suspend_flag, 0, 0); // ZZ: table order detection and limit optimizations
if (dbs_tuners_ins.fast_scaling_up > 4) // Yank: set scaling mode
scaling_mode_up = 0; // ZZ: auto fast scaling
else
scaling_mode_up = dbs_tuners_ins.fast_scaling_up; // Yank: fast scaling up only
if (dbs_tuners_ins.fast_scaling_down > 4) // Yank: set scaling mode
scaling_mode_down = 0; // ZZ: auto fast scaling
else
scaling_mode_down = dbs_tuners_ins.fast_scaling_down; // Yank: fast scaling up only
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/lcd_notifier] Resume function executed.\n");
#endif /* ZZMOOVE_DEBUG */
}
#if defined(CONFIG_HAS_EARLYSUSPEND) && !defined(USE_LCD_NOTIFIER) && !defined(DISABLE_POWER_MANAGEMENT)
static struct early_suspend __refdata _powersave_early_suspend = {
.suspend = powersave_early_suspend,
.resume = powersave_late_resume,
.level = EARLY_SUSPEND_LEVEL_BLANK_SCREEN,
};
#elif defined(CONFIG_POWERSUSPEND) && defined(USE_LCD_NOTIFIER) && !defined (DISABLE_POWER_MANAGEMENT) || defined(CONFIG_POWERSUSPEND) && !defined(USE_LCD_NOTIFIER) && !defined (DISABLE_POWER_MANAGEMENT)
static struct power_suspend __refdata powersave_powersuspend = {
.suspend = powersave_suspend,
.resume = powersave_resume,
};
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
static int cpufreq_governor_dbs(struct cpufreq_policy *policy,
unsigned int event)
{
unsigned int cpu = policy->cpu;
struct cpu_dbs_info_s *this_dbs_info;
unsigned int j;
int rc;
#if defined(ENABLE_HOTPLUGGING) && !defined(SNAP_NATIVE_HOTPLUGGING)
int i = 0;
#endif /* ENABLE_HOTPLUGGING */
this_dbs_info = &per_cpu(cs_cpu_dbs_info, cpu);
switch (event) {
case CPUFREQ_GOV_START:
if ((!cpu_online(cpu)) || (!policy->cur))
return -EINVAL;
mutex_lock(&dbs_mutex);
for_each_cpu(j, policy->cpus) {
struct cpu_dbs_info_s *j_dbs_info;
j_dbs_info = &per_cpu(cs_cpu_dbs_info, j);
j_dbs_info->cur_policy = policy;
j_dbs_info->prev_cpu_idle = get_cpu_idle_time(j,
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0) || defined(CPU_IDLE_TIME_IN_CPUFREQ) /* ZZ: overrule for sources with backported cpufreq implementation */
&j_dbs_info->prev_cpu_wall, 0);
#else
&j_dbs_info->prev_cpu_wall);
#endif /* LINUX_VERSION_CODE... */
if (dbs_tuners_ins.ignore_nice) {
j_dbs_info->prev_cpu_nice =
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,4,0)
kcpustat_cpu(j).cpustat[CPUTIME_NICE];
#else
kstat_cpu(j).cpustat.nice;
#endif /* LINUX_VERSION_CODE... */
}
j_dbs_info->time_in_idle = get_cpu_idle_time_us(cpu, &j_dbs_info->idle_exit_time); // ZZ: idle exit time handling
}
this_dbs_info->cpu = cpu; // ZZ: initialise the cpu field during governor start
this_dbs_info->rate_mult = 1; // ZZ: sampling down momentum - reset multiplier
this_dbs_info->momentum_adder = 0; // ZZ: sampling down momentum - reset momentum adder
this_dbs_info->down_skip = 0; // ZZ: sampling down - reset down_skip
this_dbs_info->requested_freq = policy->cur;
// ZZ: get freq table, available cpus for hotplugging and optimize/detect scaling range
#ifdef ENABLE_HOTPLUGGING
possible_cpus = num_possible_cpus();
#endif /* ENABLE_HOTPLUGGING */
if (cpu == 0) {
freq_init_count = 0; // ZZ: reset init flag for governor reload
system_freq_table = cpufreq_frequency_get_table(0); // ZZ: update static system frequency table
evaluate_scaling_order_limit_range(1, 0, 0, policy->min, policy->max); // ZZ: table order detection and limit optimizations
}
#if defined(ENABLE_HOTPLUGGING) && !defined(SNAP_NATIVE_HOTPLUGGING)
// ZZ: save default values in threshold array
for (i = 0; i < possible_cpus; i++) {
hotplug_thresholds[0][i] = DEF_FREQUENCY_UP_THRESHOLD_HOTPLUG;
hotplug_thresholds[1][i] = DEF_FREQUENCY_DOWN_THRESHOLD_HOTPLUG;
}
#endif /* ENABLE_HOTPLUGGING */
mutex_init(&this_dbs_info->timer_mutex);
dbs_enable++;
/*
* Start the timerschedule work, when this governor
* is used for first time
*/
if (dbs_enable == 1) {
unsigned int latency;
// policy latency is in nS. Convert it to uS first
latency = policy->cpuinfo.transition_latency / 1000;
if (latency == 0)
latency = 1;
rc = sysfs_create_group(cpufreq_global_kobject,
&dbs_attr_group);
if (rc) {
mutex_unlock(&dbs_mutex);
return rc;
}
/*
* conservative does not implement micro like ondemand
* governor, thus we are bound to jiffes/HZ
*/
min_sampling_rate =
MIN_SAMPLING_RATE_RATIO * jiffies_to_usecs(3);
// Bring kernel and HW constraints together
min_sampling_rate = max(min_sampling_rate,
MIN_LATENCY_MULTIPLIER * latency);
dbs_tuners_ins.sampling_rate_current =
max(min_sampling_rate,
latency * LATENCY_MULTIPLIER);
#ifdef ENABLE_PROFILES_SUPPORT
#if (DEF_PROFILE_NUMBER > 0)
set_profile(DEF_PROFILE_NUMBER);
#endif /* (DEF_PROFILE_NUMBER > 0) */
#endif /* ENABLE_PROFILES_SUPPORT */
// ZZ: Sampling down momentum - set down factor and max momentum
orig_sampling_down_factor = zz_sampling_down_factor;
orig_sampling_down_max_mom = zz_sampling_down_max_mom;
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
sampling_rate_awake = dbs_tuners_ins.sampling_rate
= dbs_tuners_ins.sampling_rate_current;
#else
dbs_tuners_ins.sampling_rate
= dbs_tuners_ins.sampling_rate_current;
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
#if (defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_POWERSUSPEND) && !defined(DISABLE_POWER_MANAGEMENT)) || defined(USE_LCD_NOTIFIER)
up_threshold_awake = dbs_tuners_ins.up_threshold;
down_threshold_awake = dbs_tuners_ins.down_threshold;
smooth_up_awake = dbs_tuners_ins.smooth_up;
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
// ZZ: switch to proportional scaling if we didn't get system freq table
if (!system_freq_table) {
printk(KERN_ERR "[zzmoove] Failed to get system freq table! falling back to proportional scaling!\n");
dbs_tuners_ins.scaling_proportional = 2;
}
cpufreq_register_notifier(
&dbs_cpufreq_notifier_block,
CPUFREQ_TRANSITION_NOTIFIER);
#ifdef ENABLE_INPUTBOOST
if (dbs_tuners_ins.inputboost_cycles) {
rc = input_register_handler(&interactive_input_handler);
if (!rc)
pr_info("[zzmoove/store_inputboost_cycles] inputbooster - registered\n");
else
pr_info("[zzmoove/store_inputboost_cycles] inputbooster - register FAILED\n");
rc = 0;
}
#endif /* ENABLE_INPUTBOOST */
}
mutex_unlock(&dbs_mutex);
dbs_timer_init(this_dbs_info);
#if defined(CONFIG_HAS_EARLYSUSPEND) && !defined(USE_LCD_NOTIFIER) && !defined(DISABLE_POWER_MANAGEMENT)
register_early_suspend(&_powersave_early_suspend);
#elif defined(CONFIG_POWERSUSPEND) && !defined(USE_LCD_NOTIFIER) && !defined(DISABLE_POWER_MANAGEMENT) || defined(CONFIG_POWERSUSPEND) && defined(USE_LCD_NOTIFIER) && !defined(DISABLE_POWER_MANAGEMENT)
if (cpu == 0)
register_power_suspend(&powersave_powersuspend);
#endif /* (defined(CONFIG_HAS_EARLYSUSPEND)... */
break;
case CPUFREQ_GOV_STOP:
/*
* ZZ: enable all cores to avoid cores staying in offline state
* when changing to a non-hotplugging-able governor
*/
#if defined(ENABLE_HOTPLUGGING) && !defined(SNAP_NATIVE_HOTPLUGGING)
if (cpu == 0) {
enable_cores = 1;
queue_work_on(0, dbs_wq, &hotplug_online_work); // ZZ: enable offline cores
}
#endif /* defined(ENABLE_HOTPLUGGING)... */
dbs_timer_exit(this_dbs_info);
this_dbs_info->idle_exit_time = 0; // ZZ: idle exit time handling
mutex_lock(&dbs_mutex);
dbs_enable--;
mutex_destroy(&this_dbs_info->timer_mutex);
/*
* Stop the timerschedule work, when this governor
* is used for the last time
*/
if (dbs_enable == 0) {
#ifdef ENABLE_INPUTBOOST
if (!policy->cpu && dbs_tuners_ins.inputboost_cycles)
input_unregister_handler(&interactive_input_handler);
#endif /* ENABLE_INPUTBOOST */
cpufreq_unregister_notifier(
&dbs_cpufreq_notifier_block,
CPUFREQ_TRANSITION_NOTIFIER);
}
mutex_unlock(&dbs_mutex);
if (!dbs_enable)
sysfs_remove_group(cpufreq_global_kobject,
&dbs_attr_group);
#if defined(CONFIG_HAS_EARLYSUSPEND) && !defined(USE_LCD_NOTIFIER) && !defined(DISABLE_POWER_MANAGEMENT)
unregister_early_suspend(&_powersave_early_suspend);
#elif defined(CONFIG_POWERSUSPEND) && !defined(USE_LCD_NOTIFIER) && !defined(DISABLE_POWER_MANAGEMENT) || defined(CONFIG_POWERSUSPEND) && defined(USE_LCD_NOTIFIER) && !defined(DISABLE_POWER_MANAGEMENT)
if (cpu == 0)
unregister_power_suspend(&powersave_powersuspend);
#endif /* defined(CONFIG_HAS_EARLYSUSPEND)... */
break;
case CPUFREQ_GOV_LIMITS:
// ZZ: save min/max policy only once from core 0 for freq thresholds ajustment
if (cpu == 0) {
pol_max = policy->max;
pol_min = policy->min;
}
mutex_lock(&this_dbs_info->timer_mutex);
if (policy->max < this_dbs_info->cur_policy->cur)
__cpufreq_driver_target(
this_dbs_info->cur_policy,
policy->max, CPUFREQ_RELATION_H);
else if (policy->min > this_dbs_info->cur_policy->cur)
__cpufreq_driver_target(
this_dbs_info->cur_policy,
policy->min, CPUFREQ_RELATION_L);
dbs_check_cpu(this_dbs_info);
mutex_unlock(&this_dbs_info->timer_mutex);
/*
* ZZ: here again table order detection and limit optimizations
* in case max freq has changed after gov start and before
* Limit case due to apply timing issues. now we should be able to
* catch all freq max changes during start of the governor
*/
if (cpu == 0)
evaluate_scaling_order_limit_range(0, 1, suspend_flag, policy->min, policy->max);
#ifdef ENABLE_AUTO_ADJUST_FREQ
// ZZ: do this only on core 0
if (cpu == 0) {
if (old_pol_max == 0) // ZZ: initialize var if we start the first time
old_pol_max = policy->max;
if (dbs_tuners_ins.auto_adjust_freq_thresholds != 0) {
if (old_pol_max != policy->max) {
pol_step = (old_pol_max / 100000) - (policy->max / 100000); // ZZ: truncate and calculate step
pol_step *= 100000; // ZZ: bring it back to kHz
pol_step *= -1; // ZZ: invert for proper addition
} else {
pol_step = 0;
}
old_pol_max = policy->max;
}
adjust_freq_thresholds(pol_step); // ZZ: adjust thresholds
}
#endif /* ENABLE_AUTO_ADJUST_FREQ */
this_dbs_info->time_in_idle
= get_cpu_idle_time_us(cpu, &this_dbs_info->idle_exit_time); // ZZ: idle exit time handling
break;
}
return 0;
}
#if (defined(USE_LCD_NOTIFIER) && !defined(CONFIG_POWERSUSPEND))
// AP: callback handler for lcd notifier
static int zzmoove_lcd_notifier_callback(struct notifier_block *this,
unsigned long event, void *data)
{
switch (event)
{
case LCD_EVENT_OFF_END:
if (!suspend_flag)
zzmoove_suspend();
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/lcd_notifier] Screen switched off.\n");
#endif /* ZZMOOVE_DEBUG */
break;
case LCD_EVENT_ON_START:
if (suspend_flag)
zzmoove_resume();
#ifdef ZZMOOVE_DEBUG
pr_info("[zzmoove/lcd_notifier] Screen switched on.\n");
#endif /* ZZMOOVE_DEBUG */
break;
default:
break;
}
return 0;
}
#endif /* (defined(USE_LCD_NOTIFIER) */
#ifndef CONFIG_CPU_FREQ_DEFAULT_GOV_ZZMOOVE
static
#endif /* CONFIG_CPU_FREQ_DEFAULT_GOV_ZZMOOVE */
struct cpufreq_governor cpufreq_gov_zzmoove = {
.name = "zzmoove",
.governor = cpufreq_governor_dbs,
.max_transition_latency = TRANSITION_LATENCY_LIMIT,
.owner = THIS_MODULE,
};
static int __init cpufreq_gov_dbs_init(void) // ZZ: idle exit time handling
{
unsigned int i;
struct cpu_dbs_info_s *this_dbs_info;
// Initalize per-cpu data:
for_each_possible_cpu(i) {
this_dbs_info = &per_cpu(cs_cpu_dbs_info, i);
this_dbs_info->time_in_idle = 0;
this_dbs_info->idle_exit_time = 0;
}
dbs_wq = alloc_workqueue("zzmoove_dbs_wq", WQ_HIGHPRI, 0);
#ifdef ENABLE_WORK_RESTARTLOOP
dbs_aux_wq = alloc_workqueue("zzmoove_dbs_aux_wq", WQ_HIGHPRI, 0);
if (!dbs_aux_wq) {
printk(KERN_ERR "[zzmoove] Failed to create zzmoove_dbs_aux_wq workqueue!\n");
return -EFAULT;
}
#endif /* ENABLE_WORK_RESTARTLOOP */
if (!dbs_wq) {
printk(KERN_ERR "[zzmoove] Failed to create zzmoove_dbs_wq workqueue!\n");
return -EFAULT;
}
#ifdef ENABLE_WORK_RESTARTLOOP
INIT_WORK(&work_restartloop, zz_restartloop_work);
#endif /* ENABLE_WORK_RESTARTLOOP */
#ifdef ENABLE_HOTPLUGGING
INIT_WORK(&hotplug_offline_work, hotplug_offline_work_fn); // ZZ: init hotplug offline work
INIT_WORK(&hotplug_online_work, hotplug_online_work_fn); // ZZ: init hotplug online work
#endif /* ENABLE_HOTPLUGGING */
#if (defined(USE_LCD_NOTIFIER) && !defined(CONFIG_POWERSUSPEND))
// AP: register callback handler for lcd notifier
zzmoove_lcd_notif.notifier_call = zzmoove_lcd_notifier_callback;
if (lcd_register_client(&zzmoove_lcd_notif) != 0) {
pr_err("%s: Failed to register lcd callback\n", __func__);
return -EFAULT;
}
#endif /* (defined(USE_LCD_NOTIFIER)... */
return cpufreq_register_governor(&cpufreq_gov_zzmoove);
}
static void __exit cpufreq_gov_dbs_exit(void)
{
cpufreq_unregister_governor(&cpufreq_gov_zzmoove);
destroy_workqueue(dbs_wq);
#ifdef ENABLE_WORK_RESTARTLOOP
destroy_workqueue(dbs_aux_wq);
#endif /* ENABLE_WORK_RESTARTLOOP */
#if (defined(USE_LCD_NOTIFIER) && !defined(CONFIG_POWERSUSPEND))
lcd_unregister_client(&zzmoove_lcd_notif);
#endif /* (defined(USE_LCD_NOTIFIER)... */
}
MODULE_AUTHOR("Zane Zaminsky <cyxman@yahoo.com>");
MODULE_DESCRIPTION("'cpufreq_zzmoove' - A dynamic cpufreq governor based "
"on smoove governor from Michael Weingaertner which was originally based on "
"cpufreq_conservative from Alexander Clouter. Optimized for use with Samsung I9300 "
"using a fast scaling and CPU hotplug logic - ported/modified/optimized for I9300 "
"since November 2012 and further improved for exynos and snapdragon platform "
"by ZaneZam,Yank555 and ffolkes in 2013/14/15");
MODULE_LICENSE("GPL");
#ifdef CONFIG_CPU_FREQ_DEFAULT_GOV_ZZMOOVE
fs_initcall(cpufreq_gov_dbs_init);
#else
module_init(cpufreq_gov_dbs_init);
#endif /* CONFIG_CPU_FREQ_DEFAULT_GOV_ZZMOOVE */
module_exit(cpufreq_gov_dbs_exit);
| AndroidGX/SimpleGX-L-5.0.2_BOE2_G901F | drivers/cpufreq/cpufreq_zzmoove.c | C | gpl-2.0 | 410,996 |
<?php
/**
* Aliases for special pages
*
* @file
* @ingroup Extensions
*/
$specialPageAliases = array();
/** English (English) */
$specialPageAliases['en'] = array(
'Vote' => array( 'Vote' ),
);
/** Afrikaans (Afrikaans) */
$specialPageAliases['af'] = array(
'Vote' => array( 'Stem' ),
);
/** Arabic (العربية) */
$specialPageAliases['ar'] = array(
'Vote' => array( 'تصويت' ),
);
/** Egyptian Spoken Arabic (مصرى) */
$specialPageAliases['arz'] = array(
'Vote' => array( 'تصويت' ),
);
/** Assamese (অসমীয়া) */
$specialPageAliases['as'] = array(
'Vote' => array( 'ভোট' ),
);
/** Bosnian (Bosanski) */
$specialPageAliases['bs'] = array(
'Vote' => array( 'Glasaj' ),
);
/** German (Deutsch) */
$specialPageAliases['de'] = array(
'Vote' => array( 'Abstimmen' ),
);
/** Lower Sorbian (Dolnoserbski) */
$specialPageAliases['dsb'] = array(
'Vote' => array( 'Wótgłosowaś' ),
);
/** Divehi (ދިވެހިބަސް) */
$specialPageAliases['dv'] = array(
'Vote' => array( 'ވޯޓް' ),
);
/** Greek (Ελληνικά) */
$specialPageAliases['el'] = array(
'Vote' => array( 'Ψηφοφορία' ),
);
/** Esperanto (Esperanto) */
$specialPageAliases['eo'] = array(
'Vote' => array( 'Voĉdoni' ),
);
/** Spanish (Español) */
$specialPageAliases['es'] = array(
'Vote' => array( 'Votar' ),
);
/** Persian (فارسی) */
$specialPageAliases['fa'] = array(
'Vote' => array( 'رای_دادن' ),
);
/** Finnish (Suomi) */
$specialPageAliases['fi'] = array(
'Vote' => array( 'Äänestys' ),
);
/** French (Français) */
$specialPageAliases['fr'] = array(
'Vote' => array( 'Voter' ),
);
/** Franco-Provençal (Arpetan) */
$specialPageAliases['frp'] = array(
'Vote' => array( 'Votar' ),
);
/** Galician (Galego) */
$specialPageAliases['gl'] = array(
'Vote' => array( 'Votar' ),
);
/** Swiss German (Alemannisch) */
$specialPageAliases['gsw'] = array(
'Vote' => array( 'Abstimme' ),
);
/** Gujarati (ગુજરાતી) */
$specialPageAliases['gu'] = array(
'Vote' => array( 'મત' ),
);
/** Hawaiian (Hawai`i) */
$specialPageAliases['haw'] = array(
'Vote' => array( 'Koho' ),
);
/** Upper Sorbian (Hornjoserbsce) */
$specialPageAliases['hsb'] = array(
'Vote' => array( 'Wothłosować' ),
);
/** Hungarian (Magyar) */
$specialPageAliases['hu'] = array(
'Vote' => array( 'Szavazás' ),
);
/** Interlingua (Interlingua) */
$specialPageAliases['ia'] = array(
'Vote' => array( 'Votar', 'Voto' ),
);
/** Indonesian (Bahasa Indonesia) */
$specialPageAliases['id'] = array(
'Vote' => array( 'Voting', 'Beri_suara', 'BeriSuara' ),
);
/** Italian (Italiano) */
$specialPageAliases['it'] = array(
'Vote' => array( 'Vota' ),
);
/** Japanese (日本語) */
$specialPageAliases['ja'] = array(
'Vote' => array( '投票' ),
);
/** Khmer (ភាសាខ្មែរ) */
$specialPageAliases['km'] = array(
'Vote' => array( 'បោះឆ្នោត' ),
);
/** Korean (한국어) */
$specialPageAliases['ko'] = array(
'Vote' => array( '투표' ),
);
/** Colognian (Ripoarisch) */
$specialPageAliases['ksh'] = array(
'Vote' => array( 'Afstemme', 'Avstemme' ),
);
/** Luxembourgish (Lëtzebuergesch) */
$specialPageAliases['lb'] = array(
'Vote' => array( 'Ofstëmmen' ),
);
/** Lithuanian (Lietuvių) */
$specialPageAliases['lt'] = array(
'Vote' => array( 'Balsuoti' ),
);
/** Macedonian (Македонски) */
$specialPageAliases['mk'] = array(
'Vote' => array( 'Гласање' ),
);
/** Malayalam (മലയാളം) */
$specialPageAliases['ml'] = array(
'Vote' => array( 'വോട്ട്' ),
);
/** Marathi (मराठी) */
$specialPageAliases['mr'] = array(
'Vote' => array( 'मत' ),
);
/** Maltese (Malti) */
$specialPageAliases['mt'] = array(
'Vote' => array( 'Vot' ),
);
/** Mirandese (Mirandés) */
$specialPageAliases['mwl'] = array(
'Vote' => array( 'Botar' ),
);
/** Dutch (Nederlands) */
$specialPageAliases['nl'] = array(
'Vote' => array( 'Stemmen' ),
);
/** Norwegian (bokmål) (Norsk (bokmål)) */
$specialPageAliases['no'] = array(
'Vote' => array( 'Avstemning' ),
);
/** Occitan (Occitan) */
$specialPageAliases['oc'] = array(
'Vote' => array( 'Votar' ),
);
/** Pashto (پښتو) */
$specialPageAliases['ps'] = array(
'Vote' => array( 'رايه ورکول' ),
);
/** Portuguese (Português) */
$specialPageAliases['pt'] = array(
'Vote' => array( 'Votar' ),
);
/** Romanian (Română) */
$specialPageAliases['ro'] = array(
'Vote' => array( 'Votează' ),
);
/** Sanskrit (संस्कृत) */
$specialPageAliases['sa'] = array(
'Vote' => array( 'मत' ),
);
/** Sinhala (සිංහල) */
$specialPageAliases['si'] = array(
'Vote' => array( 'ඡන්දය' ),
);
/** Slovak (Slovenčina) */
$specialPageAliases['sk'] = array(
'Vote' => array( 'Hlasovať' ),
);
/** Albanian (Shqip) */
$specialPageAliases['sq'] = array(
'Vote' => array( 'Voto' ),
);
/** Serbian Cyrillic ekavian (Српски (ћирилица)) */
$specialPageAliases['sr-ec'] = array(
'Vote' => array( 'Гласај' ),
);
/** Sundanese (Basa Sunda) */
$specialPageAliases['su'] = array(
'Vote' => array( 'Milih' ),
);
/** Swedish (Svenska) */
$specialPageAliases['sv'] = array(
'Vote' => array( 'Rösta' ),
);
/** Swahili (Kiswahili) */
$specialPageAliases['sw'] = array(
'Vote' => array( 'PigaKura' ),
);
/** Telugu (తెలుగు) */
$specialPageAliases['te'] = array(
'Vote' => array( 'వోటు' ),
);
/** Thai (ไทย) */
$specialPageAliases['th'] = array(
'Vote' => array( 'โหวต' ),
);
/** Tagalog (Tagalog) */
$specialPageAliases['tl'] = array(
'Vote' => array( 'Bumoto' ),
);
/** Turkish (Türkçe) */
$specialPageAliases['tr'] = array(
'Vote' => array( 'Oyla', 'OyVer', 'OyKullan' ),
);
/** Vèneto (Vèneto) */
$specialPageAliases['vec'] = array(
'Vote' => array( 'Vota' ),
);
/** Simplified Chinese (中文(简体)) */
$specialPageAliases['zh-hans'] = array(
'Vote' => array( '投票' ),
);
/** Traditional Chinese (中文(繁體)) */
$specialPageAliases['zh-hant'] = array(
'Vote' => array( '投票' ),
);
/**
* For backwards compatibility with MediaWiki 1.15 and earlier.
*/
$aliases =& $specialPageAliases; | xuechong87/Moegirlwiki | extensions/Vote/Vote.alias.php | PHP | gpl-2.0 | 6,197 |
<?php
/**
* The template for displaying Search Results pages
*
* @package WordPress
* @subpackage Pinwu
*/
get_header();
$search_query = get_search_query();
?>
<link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/style/products.css"/>
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/products.js"></script>
<!--ListOfProducts-->
<div class="main">
<?php echo pinwu_get_ad_banner() ?>
<div class="products base-clear">
<?php get_sidebar() ?>
<div class="products-right">
<div class="products-list-wrap">
<div class="products-list-result">
<div class="products-list-result-title">
<div class="ti dib-wrap">
<span class="dib"><a class="active">关键字搜索:<?php echo $search_query ?></a></span>
</div>
</div>
<div class="products-info">
<div class="products-info-c">
<!--以下部分为文章内容-->
<div class="news-list">
<ul>
<?php
$args = array(
'posts_per_page' => 20,
'paged' => $paged>1 ? $paged : 1,
's' => $search_query,
);
$posts = query_posts($args);
if (have_posts()){ while(have_posts()) : the_post();
?>
<li>
<a href="<?php the_permalink() ?>" target="_blank"><?php the_title() ?></a>
<span><?php echo get_the_date() ?></span>
</li>
<?php
endwhile;
} else {
echo '没有查询到相关内容';
}
?>
</ul>
</div>
<!--以上部分为文章内容-->
<p>
<?php pingwu_pagin_nav(); ?>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
get_footer();
?> | n3yang/wordpress-pw | content/themes/pinwu/search.php | PHP | gpl-2.0 | 2,912 |
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<!-- Bootstrap and JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
<!-- Font Files -->
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,500,600,700' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700,900' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Roboto+Slab:400,700,300,100' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Roboto+Mono:300,400,100,500,700' rel='stylesheet' type='text/css'>
<!-- StyleSheets -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<link href="css/newStyle.css" rel="stylesheet">
<!-- <link href="css/style.css" rel="stylesheet"> -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
<!-- Core D3 files -->
<script src="js/d3.min.js"></script>
<!-- Extensions or Addons -->
<script src="js/d3-tip.js"></script>
<script src="js/wordCloud.js"></script>
<script src="js/pikaday.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.9.3/lodash.min.js"></script>
<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/3.15/themes/css/cartodb.css" />
<script src="http://libs.cartocdn.com/cartodb.js/v3/3.15/cartodb.js"></script>
<script src="js/compare.js"></script>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header offshift">
<a class="navbar-brand" href="#">
<img alt="Brand" src="assets/wikipediaWBlack.png">
</a>
<p class="navbar-text">Wikipedia Visualizer</p>
</div>
<ul class="nav navbar-nav navbar-right">
<li><a class="navbar-text borderless" href="index.html">Event</a></li>
<!-- <li><a class="navbar-text borderless" href="general.html">General</a></li>
--> <li><a class="navbar-text borderless" href="compare.html"><span class="span-underline">Compare<span></a></li>
</ul>
</div>
</nav>
<div class="container">
<div class="controls">
<label class="input-labels">ARTICLE SELECTOR</label>
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">en<span class="caret"></span></button>
<ul class="scrollable-menu dropdown-menu lang-selector">
<li><a>en</a></li>
<li><a>de</a></li>
<li><a>fr</a></li>
<li><a>nl</a></li>
<li><a>it</a></li>
<li><a>pl</a></li>
<li><a>es</a></li>
<li><a>ru</a></li>
<li><a>ja</a></li>
<li><a>pt</a></li>
<li><a>zh</a></li>
<li><a>sv</a></li>
<li><a>vi</a></li>
<li><a>ca</a></li>
<li><a>fi</a></li>
<li><a>cs</a></li>
<li><a>hu</a></li>
<li><a>ko</a></li>
<li><a>hi</a></li>
</ul>
</div>
<!-- /btn-group -->
<input type="text" class="form-control" name='searchQuery' placeholder='Search Articles' />
</div>
<label class="input-labels">DATES SELECTOR</label>
<div class="input-group col-md-12">
<!-- /btn-group -->
<div class="col-md-5 input-half-one">
<input type="text" class="datepicker form-control" placeholder='Start Date' id="datepicker" />
</div>
<div class="col-md-5 input-half-one">
<input type="text" class="datepicker form-control" placeholder='End Date' id="datepickerTwo">
</div>
<div class="col-md-2">
<button class="btn btn-default input-button button-half-one" id="dateRefresher" type="submit"><i style="margin-left: -6px;" class="fa fa-arrow-right"></i></button>
</div>
</div>
<label class="input-labels">IMAGEURL</label>
<div class="input-group col-md-12">
<!-- /btn-group -->
<div class="col-md-10 input-half-one">
<input type='text' class="form-control" id='imageURL' placeholder='Wikicommons URL' /></input>
</div>
<!--
<div class="col-md-5 input-half-two">
<input type="text" class="datepicker form-control" placeholder='End Date' id="datepickerTwo">
</div> -->
<div class="col-md-2 input-half-two">
<button class="btn btn-default input-button button-half-one" id="imageRefresher" type="submit"><i style=" margin-left: -6px;" class="fa fa-arrow-right"></i></button>
</div>
</div>
<label class="input-labels">POPULAR ARTICLES (EDITS)</label>
<button id="mostEdits" class="btn btn-default input-button button-half-one" onclick="weeklyPedia('Most Edits')" type="submit">All Articles</button>
<button id="mostNewEdits" class="btn btn-default input-button button-half-two" onclick="weeklyPedia('Most New Edits')" type="submit">New Articles</button>
<!--
<label class="input-labels">POPULAR ARTICLES (PAGEVIEWS)</label>
<button class="btn btn-default col-md-12 input-button" type="submit">Most Popular Articles ( Weekly )</button>
-->
<label class="input-labels">RESULTS</label>
<!-- <div class="form-group">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Action <span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div><!-- /btn-group -->
<!-- <label for="exampleInputEmail1">Email address</label>
-->
<!-- <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
</div> -->
<!-- <input type='text' /></input> -->
<!-- <label for="">Select Dates</label>
<br>
<input style="margin-bottom: 40px;" type="text" class="datepicker" placeholder='Start Date' id="datepicker">
-->
<!-- <div class="weeklyPedia">
<p class="weeklyPedia">WeeklyPedia</p>
</div> -->
<div id="suggestionsPane">
<!-- div class="suggestedTitles">
<a nohref="" onclick="weeklyPedia('Most Edits')">
<p>Most Edits</p>
</a>
<a href="#" id="closeMostEdits"><i class="fa fa-times"></i></a>
</div>
<div class="suggestedTitles">
<a nohref="" onclick="weeklyPedia('Most New Edits')">
<p>Most New Edits</p>
</a>
<a href="#" id="closeMostNewEdits"><i class="fa fa-times"></i></a>
</div> -->
<div class="mostEdits"></div>
<div class="mostNewEdits"></div>
</div>
<div class="num_results"></div>
<div id="results_pane">
<div class="searchResults"></div>
</div>
<div id="results_pane2">
<div class="searchResults"></div>
</div>
</div>
<div class="col-md-9">
<div id="selectedArticles" class="col-md-12">
<label style="display: block" class="input-labels">SELECTED ARTICLES</label>
<div class="selectedArticlesContainer" style="float:left"></div>
<!-- <div class="input-group">
-->
<!-- </div>
-->
<div class="col-md-4">
<div style="width: 65px; height: 52px; margin-right: 20px; float: left" id="languageHelper" class="input-group-btn">
<button style="width: 65px; height: 52px;" type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Lang<span class="caret"></span></button>
<ul class="scrollable-menu dropdown-menu lang-selectora">
<!-- <li><a href="">English</a></li>
--> </ul>
</div>
<button style=" float: left; width: 50px;margin-right: 20px; height: 52px;" class="btn btn-default input-button button-half-one" id="staph" type="submit"><i style="margin-left: -6px;" class="fa fa-times"></i></button>
<button style=" width: 50px; height: 52px;" class="btn btn-default input-button button-half-one" id="goGoGo" type="submit"><i style="margin-left: -6px;" class="fa fa-arrow-right"></i></button>
</div>
</div>
<div class="graphs">
<div class="col-md-12">
<div class="graphsControls">
<label class="input-labels-graph">ATTRIBUTION</label>
<div class="btn-group" data-toggle="buttons">
<label id="CCSA" class="btn btn-primary active">
<input type="radio" name="options" autocomplete="off" checked>CC BY
</label>
<label id="CCBYSA" class="btn btn-primary">
<input type="radio" name="options" autocomplete="off">CC BY SA
</label>
<label id="NONE" class="btn btn-primary">
<input type="radio" name="options" id="NONE" autocomplete="off">NONE
</label>
</div>
</div><!--
<div class="graphsControls">
<label class="input-labels-graph">AUTHOR</label>
<input type='text' class="form-control col-md-2" id='imageURL' placeholder='Author Name' /></input>
</div> -->
</div>
<div class="col-md-12">
<h1 class="graphTitle" class="graphHeader"> Weekly Aggregated Edits
<a id="onePop" href="#" data-toggle="popover"><i class="fa fa-info-circle"></i></a></h1>
<div id="oneControls"></div>
<div class="graphPlace" id="one"></div>
</div>
<div class="col-md-12">
<h1 class="graphTitle" class="graphHeader"> Daily Aggregated Edits
<a id="twoPop" href="#" data-toggle="popover" title="Popover Header"><i class="fa fa-info-circle"></i></a></h1>
<div id="twoControls"></div>
<div class="graphPlace" id="two"></div>
</div>
<div class="col-md-12">
<h1 class="graphTitle" class="graphHeader"> Hourly Aggregated Edits
<a id="threePop" href="#" data-toggle="popover" title="Popover Header"><i class="fa fa-info-circle"></i></a></h1>
<div id="threeControls"></div>
<div class="graphPlace" id="three"></div>
</div>
<!--
<div class="col-md-12">
<h1 class="graphTitle" class="graphHeader"> Hourly Aggregated Edits <button class="btn btn-default input-button pngExporter" id="threePngConvertor">Woohoo!</button></h1>
<p class="graphDescription">Since the day the article was created. </p>
<div class="graphPlace" id="three"></div>
</div>
-->
<div class="col-md-12">
<h1 class="graphTitle" class="graphHeader"> PageViews
<a id="fourPop" href="#" data-toggle="popover" title="Popover Header"><i class="fa fa-info-circle"></i></a></h1>
<div id="fourControls"></div>
<div class="graphPlace" id="four"></div>
</div>
<!--
<div class="col-md-12">
<h1 class="graphTitle" class="graphHeader"> Hourly Aggregated Edits
<a id="threePop" href="#" data-toggle="popover" title="Popover Header"><i class="fa fa-info-circle"></i></a></h1>
<div id="threeControls"></div>
<div class="graphPlace" id="three"></div>
</div> -->
<canvas width="960" height="500" style="display:none"></canvas>
</div>
</div>
</div>
</body>
<script>
$(document).ready(function() {
// $('#onePop').popover({
// title: "INFO",
// content: "Some important points to be noted: </br> - This visualization contains the edits only from the English Wikipedia. The edits are aggregated weekly.",
// html: true,
// placement: "right"
// });
// $('#twoPop').popover({
// title: "<h1><strong>HTML</strong> inside <code>the</code> <em>popover</em></h1>",
// content: "Blabla <br> <h2>Cool stuff!</h2>",
// html: true,
// placement: "right"
// });
// $('#threePop').popover({
// title: "<h1><strong>HTML</strong> inside <code>the</code> <em>popover</em></h1>",
// content: "Blabla <br> <h2>Cool stuff!</h2>",
// html: true,
// placement: "right"
// });
// $('#fourPop').popover({
// title: "<h1><strong>HTML</strong> inside <code>the</code> <em>popover</em></h1>",
// content: "Blabla <br> <h2>Cool stuff!</h2>",
// html: true,
// placement: "right"
// });
// $('#fivePop').popover({
// title: "<h1><strong>HTML</strong> inside <code>the</code> <em>popover</em></h1>",
// content: "Blabla <br> <h2>Cool stuff!</h2>",
// html: true,
// placement: "right"
// });
// $('#sixPop').popover({
// title: "<h1><strong>HTML</strong> inside <code>the</code> <em>popover</em></h1>",
// content: "Blabla <br> <h2>Cool stuff!</h2>",
// html: true,
// placement: "right"
// });
// $('#sevenPop').popover({
// title: "<h1><strong>HTML</strong> inside <code>the</code> <em>popover</em></h1>",
// content: "Blabla <br> <h2>Cool stuff!</h2>",
// html: true,
// placement: "right"
// });
// $('#eightPop').popover({
// title: "<h1><strong>HTML</strong> inside <code>the</code> <em>popover</em></h1>",
// content: "Blabla <br> <h2>Cool stuff!</h2>",
// html: true,
// placement: "right"
// });
// $('#ninePop').popover({
// title: "<h1><strong>HTML</strong> inside <code>the</code> <em>popover</em></h1>",
// content: "Blabla <br> <h2>Cool stuff!</h2>",
// html: true,
// placement: "right"
// });
// $('#tenPop').popover({
// title: "<h1><strong>HTML</strong> inside <code>the</code> <em>popover</em></h1>",
// content: "Blabla <br> <h2>Cool stuff!</h2>",
// html: true,
// placement: "right"
// });
});
// This has to be here. Otherwise the datepicker UI wouldn't load!
// The Date Picker thingy. Uses pikaday.js
var picker = new Pikaday({
field: document.getElementById('datepicker'),
firstDay: 1,
minDate: new Date('2000-01-01'),
maxDate: new Date('2020-12-31'),
yearRange: [2000, 2020]
});
var pickerTwo = new Pikaday({
field: document.getElementById('datepickerTwo'),
firstDay: 1,
minDate: new Date('2000-01-01'),
maxDate: new Date('2020-12-31'),
yearRange: [2000, 2020]
});
</script> | wikitrends/wikitrends.github.io | compare.html | HTML | gpl-2.0 | 17,116 |
package org.checkerframework.framework.util.element;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.TargetType;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import org.checkerframework.framework.type.AnnotatedTypeFactory;
import org.checkerframework.framework.type.AnnotatedTypeMirror;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedTypeVariable;
import org.checkerframework.javacutil.ErrorReporter;
/**
* Applies the annotations present for a class type parameter onto an AnnotatedTypeVariable. See
* {@link TypeParamElementAnnotationApplier} for details.
*/
public class ClassTypeParamApplier extends TypeParamElementAnnotationApplier {
public static void apply(
AnnotatedTypeVariable type, Element element, AnnotatedTypeFactory typeFactory) {
new ClassTypeParamApplier(type, element, typeFactory).extractAndApply();
}
/**
* @return true if element represents a type parameter for a class
*/
public static boolean accepts(final AnnotatedTypeMirror type, final Element element) {
return element.getKind() == ElementKind.TYPE_PARAMETER
&& element.getEnclosingElement() instanceof Symbol.ClassSymbol;
}
/**
* The class that holds the type parameter element
*/
private final Symbol.ClassSymbol enclosingClass;
ClassTypeParamApplier(
AnnotatedTypeVariable type, Element element, AnnotatedTypeFactory typeFactory) {
super(type, element, typeFactory);
if (!(element.getEnclosingElement() instanceof Symbol.ClassSymbol)) {
ErrorReporter.errorAbort(
"TypeParameter not enclosed by class? Type( "
+ type
+ " ) "
+ "Element ( "
+ element
+ " ) ");
}
enclosingClass = (Symbol.ClassSymbol) element.getEnclosingElement();
}
/**
* @return TargetType.CLASS_TYPE_PARAMETER
*/
@Override
protected TargetType lowerBoundTarget() {
return TargetType.CLASS_TYPE_PARAMETER;
}
/**
* @return TargetType.CLASS_TYPE_PARAMETER_BOUND
*/
@Override
protected TargetType upperBoundTarget() {
return TargetType.CLASS_TYPE_PARAMETER_BOUND;
}
/**
* @return the index of element in the type parameter list of its enclosing class
*/
@Override
public int getElementIndex() {
return enclosingClass.getTypeParameters().indexOf(element);
}
@Override
protected TargetType[] validTargets() {
return new TargetType[] {TargetType.CLASS_EXTENDS};
}
/**
* @return the raw type attributes of the enclosing class
*/
@Override
protected Iterable<Attribute.TypeCompound> getRawTypeAttributes() {
return enclosingClass.getRawTypeAttributes();
}
@Override
protected boolean isAccepted() {
return accepts(type, element);
}
}
| Jianchu/checker-framework | framework/src/org/checkerframework/framework/util/element/ClassTypeParamApplier.java | Java | gpl-2.0 | 3,118 |
#include <stdio.h>
#define MAXLINE 1000 /* maximum line size */
#define PRINTLONGER 80 /* size of longer lines to print */
int getline(char line[],int maxline);
void copy(char to[], char from[]);
/* print longest line */
main()
{
int len;
char line[MAXLINE];
while( (len = getline(line,MAXLINE)) > 0)
if( len > PRINTLONGER)
printf("%s", line);
return 0;
}
int getline( char s[], int lim)
{
int c, i;
for(i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; i++)
s[i] = c;
if( c == '\n') {
s[i]=c;
i++;
}
s[i]='\0';
return i;
}
| bmkessler/The_C_Programming_Language | chap_1/ex_1-17.c | C | gpl-2.0 | 574 |
#!/bin/bash
# Script to deploy Mean.JS DevStack at Terminal.com
# Cloudlabs, INC. Copyright (C) 2015
#
# 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.
#
# Cloudlabs, INC. - 653 Harrison St, San Francisco, CA 94107.
# http://www.terminal.com - help@terminal.com
INSTALL_PATH="/root"
# Includes
wget https://raw.githubusercontent.com/terminalcloud/apps/master/terlib.sh
source terlib.sh || (echo "cannot get the includes"; exit -1)
install(){
# Basics
pkg_update
system_cleanup
basics_install
# Procedure:
# Install nodejs, npm an mongodb
apt-get -y install nodejs npm mongodb
# Install bower, grunt, express, express generator and Angular
npm install -g bower
npm install -g grunt-cli
npm install -g express
npm install -g express-generator@4
bower install --allow-root angular#1.2.26
# Install Mean.JS
git clone https://github.com/meanjs/mean.git meanjs
npm install
npm install -g yo
npm install -g generator-meanjs
}
show(){
# Get the startup script
wget -q -N https://raw.githubusercontent.com/terminalcloud/apps/master/others/mean_hooks.sh
mkdir -p /CL/hooks/
mv mean_hooks.sh /CL/hooks/startup.sh
# Execute startup script by first to get the common files
chmod 777 /CL/hooks/startup.sh && /CL/hooks/startup.sh
}
if [[ -z $1 ]]; then
install && show
elif [[ $1 == "show" ]]; then
show
else
echo "unknown parameter specified"
fi | terminalcloud/apps | mean_installer.sh | Shell | gpl-2.0 | 2,023 |
import search_duplicated_task
| 3dfxsoftware/cbss-addons | duplicated_tasks/wizard/__init__.py | Python | gpl-2.0 | 30 |
/* kernel/power/wakelock.c
*
* Copyright (C) 2005-2008 Google, 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/module.h>
#include <linux/platform_device.h>
#include <linux/rtc.h>
#include <linux/suspend.h>
#include <linux/syscalls.h> /* sys_sync */
#include <linux/wakelock.h>
#ifdef CONFIG_WAKELOCK_STAT
#include <linux/proc_fs.h>
#endif
#include "power.h"
#if defined(CONFIG_PXA3xx_DVFM)
#include <mach/dvfm.h>
#include <mach/mspm_prof.h>
#endif
enum {
DEBUG_EXIT_SUSPEND = 1U << 0,
DEBUG_WAKEUP = 1U << 1,
DEBUG_SUSPEND = 1U << 2,
DEBUG_EXPIRE = 1U << 3,
DEBUG_WAKE_LOCK = 1U << 4,
};
static int debug_mask = DEBUG_EXIT_SUSPEND | DEBUG_WAKEUP;
module_param_named(debug_mask, debug_mask, int, S_IRUGO | S_IWUSR | S_IWGRP);
#define WAKE_LOCK_TYPE_MASK (0x0f)
#define WAKE_LOCK_INITIALIZED (1U << 8)
#define WAKE_LOCK_ACTIVE (1U << 9)
#define WAKE_LOCK_AUTO_EXPIRE (1U << 10)
#define WAKE_LOCK_PREVENTING_SUSPEND (1U << 11)
static DEFINE_SPINLOCK(list_lock);
static LIST_HEAD(inactive_locks);
static struct list_head active_wake_locks[WAKE_LOCK_TYPE_COUNT];
static int current_event_num;
struct workqueue_struct *suspend_work_queue;
struct wake_lock main_wake_lock;
suspend_state_t requested_suspend_state = PM_SUSPEND_MEM;
static struct wake_lock unknown_wakeup;
#ifdef CONFIG_WAKELOCK_STAT
static struct wake_lock deleted_wake_locks;
static ktime_t last_sleep_time_update;
static int wait_for_wakeup;
int get_expired_time(struct wake_lock *lock, ktime_t *expire_time)
{
struct timespec ts;
struct timespec kt;
struct timespec tomono;
struct timespec delta;
unsigned long seq;
long timeout;
if (!(lock->flags & WAKE_LOCK_AUTO_EXPIRE))
return 0;
do {
seq = read_seqbegin(&xtime_lock);
timeout = lock->expires - jiffies;
if (timeout > 0)
return 0;
kt = current_kernel_time();
tomono = wall_to_monotonic;
} while (read_seqretry(&xtime_lock, seq));
jiffies_to_timespec(-timeout, &delta);
set_normalized_timespec(&ts, kt.tv_sec + tomono.tv_sec - delta.tv_sec,
kt.tv_nsec + tomono.tv_nsec - delta.tv_nsec);
*expire_time = timespec_to_ktime(ts);
return 1;
}
static int print_lock_stat(char *buf, struct wake_lock *lock)
{
int lock_count = lock->stat.count;
int expire_count = lock->stat.expire_count;
ktime_t active_time = ktime_set(0, 0);
ktime_t total_time = lock->stat.total_time;
ktime_t max_time = lock->stat.max_time;
ktime_t prevent_suspend_time = lock->stat.prevent_suspend_time;
if (lock->flags & WAKE_LOCK_ACTIVE) {
ktime_t now, add_time;
int expired = get_expired_time(lock, &now);
if (!expired)
now = ktime_get();
add_time = ktime_sub(now, lock->stat.last_time);
lock_count++;
if (!expired)
active_time = add_time;
else
expire_count++;
total_time = ktime_add(total_time, add_time);
if (lock->flags & WAKE_LOCK_PREVENTING_SUSPEND)
prevent_suspend_time = ktime_add(prevent_suspend_time,
ktime_sub(now, last_sleep_time_update));
if (add_time.tv64 > max_time.tv64)
max_time = add_time;
}
return sprintf(buf, "\"%s\"\t%d\t%d\t%d\t%lld\t%lld\t%lld\t%lld\t"
"%lld\n", lock->name, lock_count, expire_count,
lock->stat.wakeup_count, ktime_to_ns(active_time),
ktime_to_ns(total_time),
ktime_to_ns(prevent_suspend_time), ktime_to_ns(max_time),
ktime_to_ns(lock->stat.last_time));
}
static int wakelocks_read_proc(char *page, char **start, off_t off,
int count, int *eof, void *data)
{
unsigned long irqflags;
struct wake_lock *lock;
int len = 0;
char *p = page;
int type;
spin_lock_irqsave(&list_lock, irqflags);
p += sprintf(p, "name\tcount\texpire_count\twake_count\tactive_since"
"\ttotal_time\tsleep_time\tmax_time\tlast_change\n");
list_for_each_entry(lock, &inactive_locks, link) {
p += print_lock_stat(p, lock);
}
for (type = 0; type < WAKE_LOCK_TYPE_COUNT; type++) {
list_for_each_entry(lock, &active_wake_locks[type], link)
p += print_lock_stat(p, lock);
}
spin_unlock_irqrestore(&list_lock, irqflags);
*start = page + off;
len = p - page;
if (len > off)
len -= off;
else
len = 0;
return len < count ? len : count;
}
static void wake_unlock_stat_locked(struct wake_lock *lock, int expired)
{
ktime_t duration;
ktime_t now;
if (!(lock->flags & WAKE_LOCK_ACTIVE))
return;
if (get_expired_time(lock, &now))
expired = 1;
else
now = ktime_get();
lock->stat.count++;
if (expired)
lock->stat.expire_count++;
duration = ktime_sub(now, lock->stat.last_time);
lock->stat.total_time = ktime_add(lock->stat.total_time, duration);
if (ktime_to_ns(duration) > ktime_to_ns(lock->stat.max_time))
lock->stat.max_time = duration;
lock->stat.last_time = ktime_get();
if (lock->flags & WAKE_LOCK_PREVENTING_SUSPEND) {
duration = ktime_sub(now, last_sleep_time_update);
lock->stat.prevent_suspend_time = ktime_add(
lock->stat.prevent_suspend_time, duration);
lock->flags &= ~WAKE_LOCK_PREVENTING_SUSPEND;
}
}
static void update_sleep_wait_stats_locked(int done)
{
struct wake_lock *lock;
ktime_t now, etime, elapsed, add;
int expired;
now = ktime_get();
elapsed = ktime_sub(now, last_sleep_time_update);
list_for_each_entry(lock, &active_wake_locks[WAKE_LOCK_SUSPEND], link) {
expired = get_expired_time(lock, &etime);
if (lock->flags & WAKE_LOCK_PREVENTING_SUSPEND) {
if (expired)
add = ktime_sub(etime, last_sleep_time_update);
else
add = elapsed;
lock->stat.prevent_suspend_time = ktime_add(
lock->stat.prevent_suspend_time, add);
}
if (done || expired)
lock->flags &= ~WAKE_LOCK_PREVENTING_SUSPEND;
else
lock->flags |= WAKE_LOCK_PREVENTING_SUSPEND;
}
last_sleep_time_update = now;
}
#endif
static void expire_wake_lock(struct wake_lock *lock)
{
#ifdef CONFIG_WAKELOCK_STAT
wake_unlock_stat_locked(lock, 1);
#endif
lock->flags &= ~(WAKE_LOCK_ACTIVE | WAKE_LOCK_AUTO_EXPIRE);
list_del(&lock->link);
list_add(&lock->link, &inactive_locks);
if (debug_mask & (DEBUG_WAKE_LOCK | DEBUG_EXPIRE))
pr_info("expired wake lock %s\n", lock->name);
}
static void print_active_locks(int type)
{
unsigned long irqflags;
struct wake_lock *lock;
BUG_ON(type >= WAKE_LOCK_TYPE_COUNT);
spin_lock_irqsave(&list_lock, irqflags);
list_for_each_entry(lock, &active_wake_locks[type], link) {
if (lock->flags & WAKE_LOCK_AUTO_EXPIRE) {
long timeout = lock->expires - jiffies;
if (timeout <= 0)
pr_info("wake lock %s, expired\n", lock->name);
else
pr_info("active wake lock %s, time left %ld\n",
lock->name, timeout);
} else
pr_info("active wake lock %s\n", lock->name);
}
spin_unlock_irqrestore(&list_lock, irqflags);
}
static long has_wake_lock_locked(int type)
{
struct wake_lock *lock, *n;
long max_timeout = 0;
BUG_ON(type >= WAKE_LOCK_TYPE_COUNT);
list_for_each_entry_safe(lock, n, &active_wake_locks[type], link) {
if (lock->flags & WAKE_LOCK_AUTO_EXPIRE) {
long timeout = lock->expires - jiffies;
if (timeout <= 0)
expire_wake_lock(lock);
else if (timeout > max_timeout)
max_timeout = timeout;
} else
return -1;
}
return max_timeout;
}
long has_wake_lock(int type)
{
long ret;
unsigned long irqflags;
spin_lock_irqsave(&list_lock, irqflags);
ret = has_wake_lock_locked(type);
spin_unlock_irqrestore(&list_lock, irqflags);
return ret;
}
static void suspend(struct work_struct *work)
{
int ret;
int entry_event_num;
if (has_wake_lock(WAKE_LOCK_SUSPEND)) {
if (debug_mask & DEBUG_SUSPEND)
pr_info("suspend: abort suspend\n");
return;
}
entry_event_num = current_event_num;
sys_sync();
if (debug_mask & DEBUG_SUSPEND)
pr_info("suspend: enter suspend\n");
#if defined(CONFIG_PXA3xx_DVFM)
//#if defined(CONFIG_BOARD_LANDMARK) /* sometimes pmu crash when mspm_enable */
#if 0
ret = pm_suspend(requested_suspend_state);
#else
if(mspm_state()) {
mspm_disable();
ret = pm_suspend(requested_suspend_state);
mspm_enable();
} else {
ret = pm_suspend(requested_suspend_state);
}
#endif
#else
ret = pm_suspend(requested_suspend_state);
#endif
if (debug_mask & DEBUG_EXIT_SUSPEND) {
struct timespec ts;
struct rtc_time tm;
getnstimeofday(&ts);
rtc_time_to_tm(ts.tv_sec, &tm);
pr_info("suspend: exit suspend, ret = %d "
"(%d-%02d-%02d %02d:%02d:%02d.%09lu UTC)\n", ret,
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec, ts.tv_nsec);
}
#if 0
if (current_event_num == entry_event_num) {
if (debug_mask & DEBUG_SUSPEND)
printk(KERN_DEBUG"suspend: pm_suspend returned with no event\n");
wake_lock_timeout(&unknown_wakeup, HZ * 5);
}
#else /* Wait 5s anyway, by frank */
wake_lock_timeout(&unknown_wakeup, HZ * 5);
#endif
}
static DECLARE_WORK(suspend_work, suspend);
static void expire_wake_locks(unsigned long data)
{
long has_lock;
unsigned long irqflags;
if (debug_mask & DEBUG_EXPIRE)
pr_info("expire_wake_locks: start\n");
if (debug_mask & DEBUG_SUSPEND)
print_active_locks(WAKE_LOCK_SUSPEND);
spin_lock_irqsave(&list_lock, irqflags);
has_lock = has_wake_lock_locked(WAKE_LOCK_SUSPEND);
if (debug_mask & DEBUG_EXPIRE)
pr_info("expire_wake_locks: done, has_lock %ld\n", has_lock);
if (has_lock == 0)
queue_work(suspend_work_queue, &suspend_work);
spin_unlock_irqrestore(&list_lock, irqflags);
}
static DEFINE_TIMER(expire_timer, expire_wake_locks, 0, 0);
static int power_suspend_late(struct platform_device *pdev, pm_message_t state)
{
int ret = has_wake_lock(WAKE_LOCK_SUSPEND) ? -EAGAIN : 0;
#ifdef CONFIG_WAKELOCK_STAT
wait_for_wakeup = 1;
#endif
if (debug_mask & DEBUG_SUSPEND)
pr_info("power_suspend_late return %d\n", ret);
return ret;
}
static struct platform_driver power_driver = {
.driver.name = "power",
.suspend_late = power_suspend_late,
};
static struct platform_device power_device = {
.name = "power",
};
void wake_lock_init(struct wake_lock *lock, int type, const char *name)
{
unsigned long irqflags = 0;
if (name)
lock->name = name;
BUG_ON(!lock->name);
if (debug_mask & DEBUG_WAKE_LOCK)
pr_info("wake_lock_init name=%s\n", lock->name);
#ifdef CONFIG_WAKELOCK_STAT
lock->stat.count = 0;
lock->stat.expire_count = 0;
lock->stat.wakeup_count = 0;
lock->stat.total_time = ktime_set(0, 0);
lock->stat.prevent_suspend_time = ktime_set(0, 0);
lock->stat.max_time = ktime_set(0, 0);
lock->stat.last_time = ktime_set(0, 0);
#endif
lock->flags = (type & WAKE_LOCK_TYPE_MASK) | WAKE_LOCK_INITIALIZED;
INIT_LIST_HEAD(&lock->link);
spin_lock_irqsave(&list_lock, irqflags);
list_add(&lock->link, &inactive_locks);
spin_unlock_irqrestore(&list_lock, irqflags);
}
EXPORT_SYMBOL(wake_lock_init);
void wake_lock_destroy(struct wake_lock *lock)
{
unsigned long irqflags;
if (debug_mask & DEBUG_WAKE_LOCK)
pr_info("wake_lock_destroy name=%s\n", lock->name);
spin_lock_irqsave(&list_lock, irqflags);
lock->flags &= ~WAKE_LOCK_INITIALIZED;
#ifdef CONFIG_WAKELOCK_STAT
if (lock->stat.count) {
deleted_wake_locks.stat.count += lock->stat.count;
deleted_wake_locks.stat.expire_count += lock->stat.expire_count;
deleted_wake_locks.stat.total_time =
ktime_add(deleted_wake_locks.stat.total_time,
lock->stat.total_time);
deleted_wake_locks.stat.prevent_suspend_time =
ktime_add(deleted_wake_locks.stat.prevent_suspend_time,
lock->stat.prevent_suspend_time);
deleted_wake_locks.stat.max_time =
ktime_add(deleted_wake_locks.stat.max_time,
lock->stat.max_time);
}
#endif
list_del(&lock->link);
spin_unlock_irqrestore(&list_lock, irqflags);
}
EXPORT_SYMBOL(wake_lock_destroy);
static void wake_lock_internal(
struct wake_lock *lock, long timeout, int has_timeout)
{
int type;
unsigned long irqflags;
long expire_in;
spin_lock_irqsave(&list_lock, irqflags);
type = lock->flags & WAKE_LOCK_TYPE_MASK;
BUG_ON(type >= WAKE_LOCK_TYPE_COUNT);
BUG_ON(!(lock->flags & WAKE_LOCK_INITIALIZED));
#ifdef CONFIG_WAKELOCK_STAT
if (type == WAKE_LOCK_SUSPEND && wait_for_wakeup) {
if (debug_mask & DEBUG_WAKEUP)
printk(KERN_DEBUG"wakeup wake lock: %s\n", lock->name);
wait_for_wakeup = 0;
lock->stat.wakeup_count++;
}
if ((lock->flags & WAKE_LOCK_AUTO_EXPIRE) &&
(long)(lock->expires - jiffies) <= 0) {
wake_unlock_stat_locked(lock, 0);
lock->stat.last_time = ktime_get();
}
#endif
if (!(lock->flags & WAKE_LOCK_ACTIVE)) {
lock->flags |= WAKE_LOCK_ACTIVE;
#ifdef CONFIG_WAKELOCK_STAT
lock->stat.last_time = ktime_get();
#endif
}
list_del(&lock->link);
if (has_timeout) {
if (debug_mask & DEBUG_WAKE_LOCK)
pr_info("wake_lock: %s, type %d, timeout %ld.%03lu\n",
lock->name, type, timeout / HZ,
(timeout % HZ) * MSEC_PER_SEC / HZ);
lock->expires = jiffies + timeout;
lock->flags |= WAKE_LOCK_AUTO_EXPIRE;
list_add_tail(&lock->link, &active_wake_locks[type]);
} else {
if (debug_mask & DEBUG_WAKE_LOCK)
pr_info("wake_lock: %s, type %d\n", lock->name, type);
lock->expires = LONG_MAX;
lock->flags &= ~WAKE_LOCK_AUTO_EXPIRE;
list_add(&lock->link, &active_wake_locks[type]);
}
if (type == WAKE_LOCK_SUSPEND) {
current_event_num++;
#ifdef CONFIG_WAKELOCK_STAT
if (lock == &main_wake_lock)
update_sleep_wait_stats_locked(1);
else if (!wake_lock_active(&main_wake_lock))
update_sleep_wait_stats_locked(0);
#endif
if (has_timeout)
expire_in = has_wake_lock_locked(type);
else
expire_in = -1;
if (expire_in > 0) {
if (debug_mask & DEBUG_EXPIRE)
pr_info("wake_lock: %s, start expire timer, "
"%ld\n", lock->name, expire_in);
mod_timer(&expire_timer, jiffies + expire_in);
} else {
if (del_timer(&expire_timer))
if (debug_mask & DEBUG_EXPIRE)
pr_info("wake_lock: %s, stop expire timer\n",
lock->name);
if (expire_in == 0)
queue_work(suspend_work_queue, &suspend_work);
}
}
spin_unlock_irqrestore(&list_lock, irqflags);
}
void wake_lock(struct wake_lock *lock)
{
wake_lock_internal(lock, 0, 0);
}
EXPORT_SYMBOL(wake_lock);
void wake_lock_timeout(struct wake_lock *lock, long timeout)
{
wake_lock_internal(lock, timeout, 1);
}
EXPORT_SYMBOL(wake_lock_timeout);
void wake_lock_comman_timeout(long timeout)
{
wake_lock_timeout(&unknown_wakeup, timeout);
}
void wake_unlock(struct wake_lock *lock)
{
int type;
unsigned long irqflags;
spin_lock_irqsave(&list_lock, irqflags);
type = lock->flags & WAKE_LOCK_TYPE_MASK;
#ifdef CONFIG_WAKELOCK_STAT
wake_unlock_stat_locked(lock, 0);
#endif
if (debug_mask & DEBUG_WAKE_LOCK)
pr_info("wake_unlock: %s\n", lock->name);
lock->flags &= ~(WAKE_LOCK_ACTIVE | WAKE_LOCK_AUTO_EXPIRE);
list_del(&lock->link);
list_add(&lock->link, &inactive_locks);
if (type == WAKE_LOCK_SUSPEND) {
long has_lock = has_wake_lock_locked(type);
if (has_lock > 0) {
if (debug_mask & DEBUG_EXPIRE)
pr_info("wake_unlock: %s, start expire timer, "
"%ld\n", lock->name, has_lock);
mod_timer(&expire_timer, jiffies + has_lock);
} else {
if (del_timer(&expire_timer))
if (debug_mask & DEBUG_EXPIRE)
pr_info("wake_unlock: %s, stop expire "
"timer\n", lock->name);
if (has_lock == 0)
queue_work(suspend_work_queue, &suspend_work);
}
if (lock == &main_wake_lock) {
if (debug_mask & DEBUG_SUSPEND)
print_active_locks(WAKE_LOCK_SUSPEND);
#ifdef CONFIG_WAKELOCK_STAT
update_sleep_wait_stats_locked(0);
#endif
}
}
spin_unlock_irqrestore(&list_lock, irqflags);
}
EXPORT_SYMBOL(wake_unlock);
int wake_lock_active(struct wake_lock *lock)
{
return !!(lock->flags & WAKE_LOCK_ACTIVE);
}
EXPORT_SYMBOL(wake_lock_active);
static int __init wakelocks_init(void)
{
int ret;
int i;
for (i = 0; i < ARRAY_SIZE(active_wake_locks); i++)
INIT_LIST_HEAD(&active_wake_locks[i]);
#ifdef CONFIG_WAKELOCK_STAT
wake_lock_init(&deleted_wake_locks, WAKE_LOCK_SUSPEND,
"deleted_wake_locks");
#endif
wake_lock_init(&main_wake_lock, WAKE_LOCK_SUSPEND, "main");
wake_lock(&main_wake_lock);
wake_lock_init(&unknown_wakeup, WAKE_LOCK_SUSPEND, "unknown_wakeups");
ret = platform_device_register(&power_device);
if (ret) {
pr_err("wakelocks_init: platform_device_register failed\n");
goto err_platform_device_register;
}
ret = platform_driver_register(&power_driver);
if (ret) {
pr_err("wakelocks_init: platform_driver_register failed\n");
goto err_platform_driver_register;
}
suspend_work_queue = create_singlethread_workqueue("suspend");
if (suspend_work_queue == NULL) {
ret = -ENOMEM;
goto err_suspend_work_queue;
}
#ifdef CONFIG_WAKELOCK_STAT
create_proc_read_entry("wakelocks", S_IRUGO, NULL,
wakelocks_read_proc, NULL);
#endif
return 0;
err_suspend_work_queue:
platform_driver_unregister(&power_driver);
err_platform_driver_register:
platform_device_unregister(&power_device);
err_platform_device_register:
wake_lock_destroy(&unknown_wakeup);
wake_lock_destroy(&main_wake_lock);
#ifdef CONFIG_WAKELOCK_STAT
wake_lock_destroy(&deleted_wake_locks);
#endif
return ret;
}
static void __exit wakelocks_exit(void)
{
#ifdef CONFIG_WAKELOCK_STAT
remove_proc_entry("wakelocks", NULL);
#endif
destroy_workqueue(suspend_work_queue);
platform_driver_unregister(&power_driver);
platform_device_unregister(&power_device);
wake_lock_destroy(&unknown_wakeup);
wake_lock_destroy(&main_wake_lock);
#ifdef CONFIG_WAKELOCK_STAT
wake_lock_destroy(&deleted_wake_locks);
#endif
}
core_initcall(wakelocks_init);
module_exit(wakelocks_exit);
| crzyruski/OpenX2-kernel-original | kernel/power/wakelock.c | C | gpl-2.0 | 17,749 |
var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify');
var rename = require('gulp-rename');
var sh = require('shelljs');
var minify = require('gulp-minify');
var argv = require('yargs').argv;
var mid = 0;
for (arg in argv){
if (argv[arg] === true){
mid = parseInt(arg,16); // yeah, counting to f ;)
}
}
var libs= [
"./www/lib/ionic/release/js/ionic.bundle.js",
"./www/lib/moment/min/moment.min.js","./www/lib/angular-moment/angular-moment.min.js","./www/lib/moment/locale/fr.js","./www/lib/moment-timezone/builds/moment-timezone-with-data-2010-2020.min.js","./www/lib/openfb/openfb.js",
"./www/lib/ngstorage/ngStorage.min.js","./www/lib/leaflet/dist/leaflet.js","./www/lib/angular-simple-logger/dist/angular-simple-logger.js","./www/lib/angular-leaflet-directive/dist/angular-leaflet-directive.min.js","./www/lib/ngCordova/dist/ng-cordova.min.js","./www/cordova.js"
//, /* BUGGY */ "./www/lib/ng-walkthrough/ng-walkthrough.js"
]
var paths = {
sass: ['./scss/**/*.scss'],
js: [
'./www/js/*.js','./www/WhatTheFood/shared/*.js','./www/WhatTheFood/shared/**/*.js','./www/WhatTheFood/components/**/*.js'
],
lib: libs,
lib1: libs.slice(0,mid),
mid : libs[mid],
lib2: libs.slice(mid + 1)
};
/*
gulp.task('watch', function() {
gulp.watch(paths.js, ['concat']);
});
*/
gulp.task('dbg', ['concat-lib1','concat-lib2','concat-mid']);
gulp.task('concat-lib1',function(){
return gulp.src(paths.lib1)
.pipe(concat('lib1-bundle.js'))
.pipe(gulp.dest('./www/dist/'));
})
gulp.task('concat-lib2',function(){
return gulp.src(paths.lib2)
.pipe(concat('lib2-bundle.js'))
.pipe(gulp.dest('./www/dist/'));
})
gulp.task('concat-mid',function(){
return gulp.src(paths.mid)
.pipe(concat('mid-bundle.js'))
.pipe(gulp.dest('./www/dist/'));
})
gulp.task('concat', ['concat-src','concat-lib']);
gulp.task('concat-all', ['minify'],function(){
return gulp.src(['./www/dist/lib-bundle-min.js','./www/dist/app-bundle-min.js'])
.pipe(concat('bundle-min.js'))
.pipe(gulp.dest('./www/dist/'));
})
gulp.task('concat-src', function() {
return gulp.src(paths.js)
.pipe(concat('app-bundle.js'))
.pipe(gulp.dest('./www/dist/'));
});
gulp.task('concat-lib', function() {
return gulp.src(paths.lib)
.pipe(concat('lib-bundle.js'))
.pipe(gulp.dest('./www/dist/'));
});
gulp.task('minify', ['concat'],function() {
return gulp.src(['./www/dist/app-bundle.js','./www/dist/lib-bundle.js'])
.pipe(minify({mangle:false}))
.pipe(gulp.dest('./www/dist'));
});
gulp.task('sass', function(done) {
gulp.src('./scss/ionic.app.scss')
.pipe(sass())
.pipe(gulp.dest('./www/css/'))
.pipe(minifyCss({
keepSpecialComments: 0
}))
.pipe(rename({ extname: '.min.css' }))
.pipe(gulp.dest('./www/css/'))
.on('end', done);
});
gulp.task('watch', function() {
gulp.watch(paths.sass, ['sass']);
});
gulp.task('install', ['git-check'], function() {
return bower.commands.install()
.on('log', function(data) {
gutil.log('bower', gutil.colors.cyan(data.id), data.message);
});
});
gulp.task('git-check', function(done) {
if (!sh.which('git')) {
console.log(
' ' + gutil.colors.red('Git is not installed.'),
'\n Git, the version control system, is required to download Ionic.',
'\n Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
'\n Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
);
process.exit(1);
}
done();
});
gulp.task('concat-and-minify', ['concat','minify']);
gulp.task('default', ['concat-and-minify']);
| WhatTheFood/wtfapp-mobileapp | gulpfile.js | JavaScript | gpl-2.0 | 3,781 |
/*
** 2003 September 6
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used for creating, destroying, and populating
** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
** to version 2.8.7, all this code was combined into the vdbe.c source file.
** But that file was getting too big so this subroutines were split out.
**
** $Id: vdbeaux.c,v 1.383 2008/05/13 13:27:34 drh Exp $
*/
#include "sqliteInt.h"
#include <ctype.h>
#include "vdbeInt.h"
/*
** When debugging the code generator in a symbolic debugger, one can
** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
** as they are added to the instruction stream.
*/
#ifdef SQLITE_DEBUG
int sqlite3VdbeAddopTrace = 0;
#endif
/*
** Create a new virtual database engine.
*/
Vdbe *sqlite3VdbeCreate(sqlite3 *db){
Vdbe *p;
p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
if( p==0 ) return 0;
p->db = db;
if( db->pVdbe ){
db->pVdbe->pPrev = p;
}
p->pNext = db->pVdbe;
p->pPrev = 0;
db->pVdbe = p;
p->magic = VDBE_MAGIC_INIT;
return p;
}
/*
** Remember the SQL string for a prepared statement.
*/
void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n){
if( p==0 ) return;
assert( p->zSql==0 );
p->zSql = sqlite3DbStrNDup(p->db, z, n);
}
/*
** Return the SQL associated with a prepared statement
*/
const char *sqlite3_sql(sqlite3_stmt *pStmt){
return ((Vdbe *)pStmt)->zSql;
}
/*
** Swap all content between two VDBE structures.
*/
void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
Vdbe tmp, *pTmp;
char *zTmp;
int nTmp;
tmp = *pA;
*pA = *pB;
*pB = tmp;
pTmp = pA->pNext;
pA->pNext = pB->pNext;
pB->pNext = pTmp;
pTmp = pA->pPrev;
pA->pPrev = pB->pPrev;
pB->pPrev = pTmp;
zTmp = pA->zSql;
pA->zSql = pB->zSql;
pB->zSql = zTmp;
nTmp = pA->nSql;
pA->nSql = pB->nSql;
pB->nSql = nTmp;
}
#ifdef SQLITE_DEBUG
/*
** Turn tracing on or off
*/
void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
p->trace = trace;
}
#endif
/*
** Resize the Vdbe.aOp array so that it contains at least N
** elements.
**
** If an out-of-memory error occurs while resizing the array,
** Vdbe.aOp and Vdbe.nOpAlloc remain unchanged (this is so that
** any opcodes already allocated can be correctly deallocated
** along with the rest of the Vdbe).
*/
static void resizeOpArray(Vdbe *p, int N){
VdbeOp *pNew;
pNew = sqlite3DbRealloc(p->db, p->aOp, N*sizeof(Op));
if( pNew ){
p->nOpAlloc = N;
p->aOp = pNew;
}
}
/*
** Add a new instruction to the list of instructions current in the
** VDBE. Return the address of the new instruction.
**
** Parameters:
**
** p Pointer to the VDBE
**
** op The opcode for this instruction
**
** p1, p2, p3 Operands
**
** Use the sqlite3VdbeResolveLabel() function to fix an address and
** the sqlite3VdbeChangeP4() function to change the value of the P4
** operand.
*/
int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
int i;
VdbeOp *pOp;
i = p->nOp;
assert( p->magic==VDBE_MAGIC_INIT );
if( p->nOpAlloc<=i ){
resizeOpArray(p, p->nOpAlloc ? p->nOpAlloc*2 : 1024/sizeof(Op));
if( p->db->mallocFailed ){
return 0;
}
}
p->nOp++;
pOp = &p->aOp[i];
pOp->opcode = op;
pOp->p5 = 0;
pOp->p1 = p1;
pOp->p2 = p2;
pOp->p3 = p3;
pOp->p4.p = 0;
pOp->p4type = P4_NOTUSED;
p->expired = 0;
#ifdef SQLITE_DEBUG
pOp->zComment = 0;
if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
#endif
#ifdef VDBE_PROFILE
pOp->cycles = 0;
pOp->cnt = 0;
#endif
return i;
}
int sqlite3VdbeAddOp0(Vdbe *p, int op){
return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
}
int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
}
int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
}
/*
** Add an opcode that includes the p4 value as a pointer.
*/
int sqlite3VdbeAddOp4(
Vdbe *p, /* Add the opcode to this VM */
int op, /* The new opcode */
int p1, /* The P1 operand */
int p2, /* The P2 operand */
int p3, /* The P3 operand */
const char *zP4, /* The P4 operand */
int p4type /* P4 operand type */
){
int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
sqlite3VdbeChangeP4(p, addr, zP4, p4type);
return addr;
}
/*
** Create a new symbolic label for an instruction that has yet to be
** coded. The symbolic label is really just a negative number. The
** label can be used as the P2 value of an operation. Later, when
** the label is resolved to a specific address, the VDBE will scan
** through its operation list and change all values of P2 which match
** the label into the resolved address.
**
** The VDBE knows that a P2 value is a label because labels are
** always negative and P2 values are suppose to be non-negative.
** Hence, a negative P2 value is a label that has yet to be resolved.
**
** Zero is returned if a malloc() fails.
*/
int sqlite3VdbeMakeLabel(Vdbe *p){
int i;
i = p->nLabel++;
assert( p->magic==VDBE_MAGIC_INIT );
if( i>=p->nLabelAlloc ){
p->nLabelAlloc = p->nLabelAlloc*2 + 10;
p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
p->nLabelAlloc*sizeof(p->aLabel[0]));
}
if( p->aLabel ){
p->aLabel[i] = -1;
}
return -1-i;
}
/*
** Resolve label "x" to be the address of the next instruction to
** be inserted. The parameter "x" must have been obtained from
** a prior call to sqlite3VdbeMakeLabel().
*/
void sqlite3VdbeResolveLabel(Vdbe *p, int x){
int j = -1-x;
assert( p->magic==VDBE_MAGIC_INIT );
assert( j>=0 && j<p->nLabel );
if( p->aLabel ){
p->aLabel[j] = p->nOp;
}
}
/*
** Loop through the program looking for P2 values that are negative
** on jump instructions. Each such value is a label. Resolve the
** label by setting the P2 value to its correct non-zero value.
**
** This routine is called once after all opcodes have been inserted.
**
** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
**
** This routine also does the following optimization: It scans for
** instructions that might cause a statement rollback. Such instructions
** are:
**
** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
** * OP_Destroy
** * OP_VUpdate
** * OP_VRename
**
** If no such instruction is found, then every Statement instruction
** is changed to a Noop. In this way, we avoid creating the statement
** journal file unnecessarily.
*/
static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
int i;
int nMaxArgs = 0;
Op *pOp;
int *aLabel = p->aLabel;
int doesStatementRollback = 0;
int hasStatementBegin = 0;
for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
u8 opcode = pOp->opcode;
if( opcode==OP_Function ){
if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
}else if( opcode==OP_AggStep
#ifndef SQLITE_OMIT_VIRTUALTABLE
|| opcode==OP_VUpdate
#endif
){
if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
}
if( opcode==OP_Halt ){
if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
doesStatementRollback = 1;
}
}else if( opcode==OP_Statement ){
hasStatementBegin = 1;
}else if( opcode==OP_Destroy ){
doesStatementRollback = 1;
#ifndef SQLITE_OMIT_VIRTUALTABLE
}else if( opcode==OP_VUpdate || opcode==OP_VRename ){
doesStatementRollback = 1;
}else if( opcode==OP_VFilter ){
int n;
assert( p->nOp - i >= 3 );
assert( pOp[-1].opcode==OP_Integer );
n = pOp[-1].p1;
if( n>nMaxArgs ) nMaxArgs = n;
#endif
}
if( sqlite3VdbeOpcodeHasProperty(opcode, OPFLG_JUMP) && pOp->p2<0 ){
assert( -1-pOp->p2<p->nLabel );
pOp->p2 = aLabel[-1-pOp->p2];
}
}
sqlite3_free(p->aLabel);
p->aLabel = 0;
*pMaxFuncArgs = nMaxArgs;
/* If we never rollback a statement transaction, then statement
** transactions are not needed. So change every OP_Statement
** opcode into an OP_Noop. This avoid a call to sqlite3OsOpenExclusive()
** which can be expensive on some platforms.
*/
if( hasStatementBegin && !doesStatementRollback ){
for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
if( pOp->opcode==OP_Statement ){
pOp->opcode = OP_Noop;
}
}
}
}
/*
** Return the address of the next instruction to be inserted.
*/
int sqlite3VdbeCurrentAddr(Vdbe *p){
assert( p->magic==VDBE_MAGIC_INIT );
return p->nOp;
}
/*
** Add a whole list of operations to the operation stack. Return the
** address of the first operation added.
*/
int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
int addr;
assert( p->magic==VDBE_MAGIC_INIT );
if( p->nOp + nOp > p->nOpAlloc ){
resizeOpArray(p, p->nOpAlloc ? p->nOpAlloc*2 : 1024/sizeof(Op));
assert( p->nOp+nOp<=p->nOpAlloc || p->db->mallocFailed );
}
if( p->db->mallocFailed ){
return 0;
}
addr = p->nOp;
if( nOp>0 ){
int i;
VdbeOpList const *pIn = aOp;
for(i=0; i<nOp; i++, pIn++){
int p2 = pIn->p2;
VdbeOp *pOut = &p->aOp[i+addr];
pOut->opcode = pIn->opcode;
pOut->p1 = pIn->p1;
if( p2<0 && sqlite3VdbeOpcodeHasProperty(pOut->opcode, OPFLG_JUMP) ){
pOut->p2 = addr + ADDR(p2);
}else{
pOut->p2 = p2;
}
pOut->p3 = pIn->p3;
pOut->p4type = P4_NOTUSED;
pOut->p4.p = 0;
pOut->p5 = 0;
#ifdef SQLITE_DEBUG
pOut->zComment = 0;
if( sqlite3VdbeAddopTrace ){
sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
}
#endif
}
p->nOp += nOp;
}
return addr;
}
/*
** Change the value of the P1 operand for a specific instruction.
** This routine is useful when a large program is loaded from a
** static array using sqlite3VdbeAddOpList but we want to make a
** few minor changes to the program.
*/
void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
assert( p==0 || p->magic==VDBE_MAGIC_INIT );
if( p && addr>=0 && p->nOp>addr && p->aOp ){
p->aOp[addr].p1 = val;
}
}
/*
** Change the value of the P2 operand for a specific instruction.
** This routine is useful for setting a jump destination.
*/
void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
assert( p==0 || p->magic==VDBE_MAGIC_INIT );
if( p && addr>=0 && p->nOp>addr && p->aOp ){
p->aOp[addr].p2 = val;
}
}
/*
** Change the value of the P3 operand for a specific instruction.
*/
void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
assert( p==0 || p->magic==VDBE_MAGIC_INIT );
if( p && addr>=0 && p->nOp>addr && p->aOp ){
p->aOp[addr].p3 = val;
}
}
/*
** Change the value of the P5 operand for the most recently
** added operation.
*/
void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
assert( p==0 || p->magic==VDBE_MAGIC_INIT );
if( p && p->aOp ){
assert( p->nOp>0 );
p->aOp[p->nOp-1].p5 = val;
}
}
/*
** Change the P2 operand of instruction addr so that it points to
** the address of the next instruction to be coded.
*/
void sqlite3VdbeJumpHere(Vdbe *p, int addr){
sqlite3VdbeChangeP2(p, addr, p->nOp);
}
/*
** If the input FuncDef structure is ephemeral, then free it. If
** the FuncDef is not ephermal, then do nothing.
*/
static void freeEphemeralFunction(FuncDef *pDef){
if( pDef && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
sqlite3_free(pDef);
}
}
/*
** Delete a P4 value if necessary.
*/
static void freeP4(int p4type, void *p3){
if( p3 ){
switch( p4type ){
case P4_REAL:
case P4_INT64:
case P4_MPRINTF:
case P4_DYNAMIC:
case P4_KEYINFO:
case P4_KEYINFO_HANDOFF: {
sqlite3_free(p3);
break;
}
case P4_VDBEFUNC: {
VdbeFunc *pVdbeFunc = (VdbeFunc *)p3;
freeEphemeralFunction(pVdbeFunc->pFunc);
sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
sqlite3_free(pVdbeFunc);
break;
}
case P4_FUNCDEF: {
freeEphemeralFunction((FuncDef*)p3);
break;
}
case P4_MEM: {
sqlite3ValueFree((sqlite3_value*)p3);
break;
}
}
}
}
/*
** Change N opcodes starting at addr to No-ops.
*/
void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
if( p && p->aOp ){
VdbeOp *pOp = &p->aOp[addr];
while( N-- ){
freeP4(pOp->p4type, pOp->p4.p);
memset(pOp, 0, sizeof(pOp[0]));
pOp->opcode = OP_Noop;
pOp++;
}
}
}
/*
** Change the value of the P4 operand for a specific instruction.
** This routine is useful when a large program is loaded from a
** static array using sqlite3VdbeAddOpList but we want to make a
** few minor changes to the program.
**
** If n>=0 then the P4 operand is dynamic, meaning that a copy of
** the string is made into memory obtained from sqlite3_malloc().
** A value of n==0 means copy bytes of zP4 up to and including the
** first null byte. If n>0 then copy n+1 bytes of zP4.
**
** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
** A copy is made of the KeyInfo structure into memory obtained from
** sqlite3_malloc, to be freed when the Vdbe is finalized.
** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
** stored in memory that the caller has obtained from sqlite3_malloc. The
** caller should not free the allocation, it will be freed when the Vdbe is
** finalized.
**
** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
** to a string or structure that is guaranteed to exist for the lifetime of
** the Vdbe. In these cases we can just copy the pointer.
**
** If addr<0 then change P4 on the most recently inserted instruction.
*/
void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
Op *pOp;
assert( p!=0 );
assert( p->magic==VDBE_MAGIC_INIT );
if( p->aOp==0 || p->db->mallocFailed ){
if (n != P4_KEYINFO) {
freeP4(n, (void*)*(char**)&zP4);
}
return;
}
assert( addr<p->nOp );
if( addr<0 ){
addr = p->nOp - 1;
if( addr<0 ) return;
}
pOp = &p->aOp[addr];
freeP4(pOp->p4type, pOp->p4.p);
pOp->p4.p = 0;
if( n==P4_INT32 ){
/* Note: this cast is safe, because the origin data point was an int
** that was cast to a (const char *). */
pOp->p4.i = (int)zP4;
pOp->p4type = n;
}else if( zP4==0 ){
pOp->p4.p = 0;
pOp->p4type = P4_NOTUSED;
}else if( n==P4_KEYINFO ){
KeyInfo *pKeyInfo;
int nField, nByte;
nField = ((KeyInfo*)zP4)->nField;
nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
pKeyInfo = sqlite3_malloc( nByte );
pOp->p4.pKeyInfo = pKeyInfo;
if( pKeyInfo ){
memcpy(pKeyInfo, zP4, nByte);
/* In the current implementation, P4_KEYINFO is only ever used on
** KeyInfo structures that have no aSortOrder component. Elements
** with an aSortOrder always use P4_KEYINFO_HANDOFF. So we do not
** need to bother with duplicating the aSortOrder. */
assert( pKeyInfo->aSortOrder==0 );
#if 0
aSortOrder = pKeyInfo->aSortOrder;
if( aSortOrder ){
pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
}
#endif
pOp->p4type = P4_KEYINFO;
}else{
p->db->mallocFailed = 1;
pOp->p4type = P4_NOTUSED;
}
}else if( n==P4_KEYINFO_HANDOFF ){
pOp->p4.p = (void*)zP4;
pOp->p4type = P4_KEYINFO;
}else if( n<0 ){
pOp->p4.p = (void*)zP4;
pOp->p4type = n;
}else{
if( n==0 ) n = strlen(zP4);
pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
pOp->p4type = P4_DYNAMIC;
}
}
#ifndef NDEBUG
/*
** Change the comment on the the most recently coded instruction.
*/
void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
va_list ap;
assert( p->nOp>0 || p->aOp==0 );
assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
if( p->nOp ){
char **pz = &p->aOp[p->nOp-1].zComment;
va_start(ap, zFormat);
sqlite3_free(*pz);
*pz = sqlite3VMPrintf(p->db, zFormat, ap);
va_end(ap);
}
}
#endif
/*
** Return the opcode for a given address.
*/
VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
assert( p->magic==VDBE_MAGIC_INIT );
assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
return ((addr>=0 && addr<p->nOp)?(&p->aOp[addr]):0);
}
#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
|| defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
/*
** Compute a string that describes the P4 parameter for an opcode.
** Use zTemp for any required temporary buffer space.
*/
static char *displayP4(Op *pOp, char *zTemp, int nTemp){
char *zP4 = zTemp;
assert( nTemp>=20 );
switch( pOp->p4type ){
case P4_KEYINFO: {
int i, j;
KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
i = strlen(zTemp);
for(j=0; j<pKeyInfo->nField; j++){
CollSeq *pColl = pKeyInfo->aColl[j];
if( pColl ){
int n = strlen(pColl->zName);
if( i+n>nTemp-6 ){
memcpy(&zTemp[i],",...",4);
break;
}
zTemp[i++] = ',';
if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
zTemp[i++] = '-';
}
memcpy(&zTemp[i], pColl->zName,n+1);
i += n;
}else if( i+4<nTemp-6 ){
memcpy(&zTemp[i],",nil",4);
i += 4;
}
}
zTemp[i++] = ')';
zTemp[i] = 0;
assert( i<nTemp );
break;
}
case P4_COLLSEQ: {
CollSeq *pColl = pOp->p4.pColl;
sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
break;
}
case P4_FUNCDEF: {
FuncDef *pDef = pOp->p4.pFunc;
sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
break;
}
case P4_INT64: {
sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
break;
}
case P4_INT32: {
sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
break;
}
case P4_REAL: {
sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
break;
}
case P4_MEM: {
Mem *pMem = pOp->p4.pMem;
assert( (pMem->flags & MEM_Null)==0 );
if( pMem->flags & MEM_Str ){
zP4 = pMem->z;
}else if( pMem->flags & MEM_Int ){
sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
}else if( pMem->flags & MEM_Real ){
sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
}
break;
}
#ifndef SQLITE_OMIT_VIRTUALTABLE
case P4_VTAB: {
sqlite3_vtab *pVtab = pOp->p4.pVtab;
sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
break;
}
#endif
default: {
zP4 = pOp->p4.z;
if( zP4==0 ){
zP4 = zTemp;
zTemp[0] = 0;
}
}
}
assert( zP4!=0 );
return zP4;
}
#endif
/*
** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
**
*/
void sqlite3VdbeUsesBtree(Vdbe *p, int i){
int mask;
assert( i>=0 && i<p->db->nDb );
assert( i<sizeof(p->btreeMask)*8 );
mask = 1<<i;
if( (p->btreeMask & mask)==0 ){
p->btreeMask |= mask;
sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
}
}
#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
/*
** Print a single opcode. This routine is used for debugging only.
*/
void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
char *zP4;
char zPtr[50];
static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
if( pOut==0 ) pOut = stdout;
zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
fprintf(pOut, zFormat1, pc,
sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
#ifdef SQLITE_DEBUG
pOp->zComment ? pOp->zComment : ""
#else
""
#endif
);
fflush(pOut);
}
#endif
/*
** Release an array of N Mem elements
*/
static void releaseMemArray(Mem *p, int N, int freebuffers){
if( p && N ){
sqlite3 *db = p->db;
int malloc_failed = db->mallocFailed;
while( N-->0 ){
assert( N<2 || p[0].db==p[1].db );
if( freebuffers ){
sqlite3VdbeMemRelease(p);
}else{
sqlite3VdbeMemReleaseExternal(p);
}
p->flags = MEM_Null;
p++;
}
db->mallocFailed = malloc_failed;
}
}
#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
int sqlite3VdbeReleaseBuffers(Vdbe *p){
int ii;
int nFree = 0;
assert( sqlite3_mutex_held(p->db->mutex) );
for(ii=1; ii<=p->nMem; ii++){
Mem *pMem = &p->aMem[ii];
if( pMem->z && pMem->flags&MEM_Dyn ){
assert( !pMem->xDel );
nFree += sqlite3MallocSize(pMem->z);
sqlite3VdbeMemRelease(pMem);
}
}
return nFree;
}
#endif
#ifndef SQLITE_OMIT_EXPLAIN
/*
** Give a listing of the program in the virtual machine.
**
** The interface is the same as sqlite3VdbeExec(). But instead of
** running the code, it invokes the callback once for each instruction.
** This feature is used to implement "EXPLAIN".
**
** When p->explain==1, each instruction is listed. When
** p->explain==2, only OP_Explain instructions are listed and these
** are shown in a different format. p->explain==2 is used to implement
** EXPLAIN QUERY PLAN.
*/
int sqlite3VdbeList(
Vdbe *p /* The VDBE */
){
sqlite3 *db = p->db;
int i;
int rc = SQLITE_OK;
Mem *pMem = p->pResultSet = &p->aMem[1];
assert( p->explain );
if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
assert( db->magic==SQLITE_MAGIC_BUSY );
assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
/* Even though this opcode does not use dynamic strings for
** the result, result columns may become dynamic if the user calls
** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
*/
releaseMemArray(pMem, p->nMem, 1);
do{
i = p->pc++;
}while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
if( i>=p->nOp ){
p->rc = SQLITE_OK;
rc = SQLITE_DONE;
}else if( db->u1.isInterrupted ){
p->rc = SQLITE_INTERRUPT;
rc = SQLITE_ERROR;
sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(p->rc), (char*)0);
}else{
char *z;
Op *pOp = &p->aOp[i];
if( p->explain==1 ){
pMem->flags = MEM_Int;
pMem->type = SQLITE_INTEGER;
pMem->u.i = i; /* Program counter */
pMem++;
pMem->flags = MEM_Static|MEM_Str|MEM_Term;
pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
assert( pMem->z!=0 );
pMem->n = strlen(pMem->z);
pMem->type = SQLITE_TEXT;
pMem->enc = SQLITE_UTF8;
pMem++;
}
pMem->flags = MEM_Int;
pMem->u.i = pOp->p1; /* P1 */
pMem->type = SQLITE_INTEGER;
pMem++;
pMem->flags = MEM_Int;
pMem->u.i = pOp->p2; /* P2 */
pMem->type = SQLITE_INTEGER;
pMem++;
if( p->explain==1 ){
pMem->flags = MEM_Int;
pMem->u.i = pOp->p3; /* P3 */
pMem->type = SQLITE_INTEGER;
pMem++;
}
if( sqlite3VdbeMemGrow(pMem, 32, 0) ){ /* P4 */
p->db->mallocFailed = 1;
return SQLITE_NOMEM;
}
pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
z = displayP4(pOp, pMem->z, 32);
if( z!=pMem->z ){
sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
}else{
assert( pMem->z!=0 );
pMem->n = strlen(pMem->z);
pMem->enc = SQLITE_UTF8;
}
pMem->type = SQLITE_TEXT;
pMem++;
if( p->explain==1 ){
if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
p->db->mallocFailed = 1;
return SQLITE_NOMEM;
}
pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
pMem->n = 2;
sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
pMem->type = SQLITE_TEXT;
pMem->enc = SQLITE_UTF8;
pMem++;
#ifdef SQLITE_DEBUG
if( pOp->zComment ){
pMem->flags = MEM_Str|MEM_Term;
pMem->z = pOp->zComment;
pMem->n = strlen(pMem->z);
pMem->enc = SQLITE_UTF8;
}else
#endif
{
pMem->flags = MEM_Null; /* Comment */
pMem->type = SQLITE_NULL;
}
}
p->nResColumn = 8 - 5*(p->explain-1);
p->rc = SQLITE_OK;
rc = SQLITE_ROW;
}
return rc;
}
#endif /* SQLITE_OMIT_EXPLAIN */
#ifdef SQLITE_DEBUG
/*
** Print the SQL that was used to generate a VDBE program.
*/
void sqlite3VdbePrintSql(Vdbe *p){
int nOp = p->nOp;
VdbeOp *pOp;
if( nOp<1 ) return;
pOp = &p->aOp[0];
if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
const char *z = pOp->p4.z;
while( isspace(*(u8*)z) ) z++;
printf("SQL: [%s]\n", z);
}
}
#endif
#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
/*
** Print an IOTRACE message showing SQL content.
*/
void sqlite3VdbeIOTraceSql(Vdbe *p){
int nOp = p->nOp;
VdbeOp *pOp;
if( sqlite3IoTrace==0 ) return;
if( nOp<1 ) return;
pOp = &p->aOp[0];
if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
int i, j;
char z[1000];
sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
for(i=0; isspace((unsigned char)z[i]); i++){}
for(j=0; z[i]; i++){
if( isspace((unsigned char)z[i]) ){
if( z[i-1]!=' ' ){
z[j++] = ' ';
}
}else{
z[j++] = z[i];
}
}
z[j] = 0;
sqlite3IoTrace("SQL %s\n", z);
}
}
#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
/*
** Prepare a virtual machine for execution. This involves things such
** as allocating stack space and initializing the program counter.
** After the VDBE has be prepped, it can be executed by one or more
** calls to sqlite3VdbeExec().
**
** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
** VDBE_MAGIC_RUN.
*/
void sqlite3VdbeMakeReady(
Vdbe *p, /* The VDBE */
int nVar, /* Number of '?' see in the SQL statement */
int nMem, /* Number of memory cells to allocate */
int nCursor, /* Number of cursors to allocate */
int isExplain /* True if the EXPLAIN keywords is present */
){
int n;
sqlite3 *db = p->db;
assert( p!=0 );
assert( p->magic==VDBE_MAGIC_INIT );
/* There should be at least one opcode.
*/
assert( p->nOp>0 );
/* Set the magic to VDBE_MAGIC_RUN sooner rather than later. This
* is because the call to resizeOpArray() below may shrink the
* p->aOp[] array to save memory if called when in VDBE_MAGIC_RUN
* state.
*/
p->magic = VDBE_MAGIC_RUN;
/* For each cursor required, also allocate a memory cell. Memory
** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
** the vdbe program. Instead they are used to allocate space for
** Cursor/BtCursor structures. The blob of memory associated with
** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
** stores the blob of memory associated with cursor 1, etc.
**
** See also: allocateCursor().
*/
nMem += nCursor;
/*
** Allocation space for registers.
*/
if( p->aMem==0 ){
int nArg; /* Maximum number of args passed to a user function. */
resolveP2Values(p, &nArg);
/*resizeOpArray(p, p->nOp);*/
assert( nVar>=0 );
if( isExplain && nMem<10 ){
p->nMem = nMem = 10;
}
p->aMem = sqlite3DbMallocZero(db,
nMem*sizeof(Mem) /* aMem */
+ nVar*sizeof(Mem) /* aVar */
+ nArg*sizeof(Mem*) /* apArg */
+ nVar*sizeof(char*) /* azVar */
+ nCursor*sizeof(Cursor*) + 1 /* apCsr */
);
if( !db->mallocFailed ){
p->aMem--; /* aMem[] goes from 1..nMem */
p->nMem = nMem; /* not from 0..nMem-1 */
p->aVar = &p->aMem[nMem+1];
p->nVar = nVar;
p->okVar = 0;
p->apArg = (Mem**)&p->aVar[nVar];
p->azVar = (char**)&p->apArg[nArg];
p->apCsr = (Cursor**)&p->azVar[nVar];
p->nCursor = nCursor;
for(n=0; n<nVar; n++){
p->aVar[n].flags = MEM_Null;
p->aVar[n].db = db;
}
for(n=1; n<=nMem; n++){
p->aMem[n].flags = MEM_Null;
p->aMem[n].db = db;
}
}
}
#ifdef SQLITE_DEBUG
for(n=1; n<p->nMem; n++){
assert( p->aMem[n].db==db );
}
#endif
p->pc = -1;
p->rc = SQLITE_OK;
p->uniqueCnt = 0;
p->returnDepth = 0;
p->errorAction = OE_Abort;
p->explain |= isExplain;
p->magic = VDBE_MAGIC_RUN;
p->nChange = 0;
p->cacheCtr = 1;
p->minWriteFileFormat = 255;
p->openedStatement = 0;
#ifdef VDBE_PROFILE
{
int i;
for(i=0; i<p->nOp; i++){
p->aOp[i].cnt = 0;
p->aOp[i].cycles = 0;
}
}
#endif
}
/*
** Close a VDBE cursor and release all the resources that cursor
** happens to hold.
*/
void sqlite3VdbeFreeCursor(Vdbe *p, Cursor *pCx){
if( pCx==0 ){
return;
}
if( pCx->pCursor ){
sqlite3BtreeCloseCursor(pCx->pCursor);
}
if( pCx->pBt ){
sqlite3BtreeClose(pCx->pBt);
}
#ifndef SQLITE_OMIT_VIRTUALTABLE
if( pCx->pVtabCursor ){
sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
const sqlite3_module *pModule = pCx->pModule;
p->inVtabMethod = 1;
(void)sqlite3SafetyOff(p->db);
pModule->xClose(pVtabCursor);
(void)sqlite3SafetyOn(p->db);
p->inVtabMethod = 0;
}
#endif
if( !pCx->ephemPseudoTable ){
sqlite3_free(pCx->pData);
}
/* memset(pCx, 0, sizeof(Cursor)); */
/* sqlite3_free(pCx->aType); */
/* sqlite3_free(pCx); */
}
/*
** Close all cursors except for VTab cursors that are currently
** in use.
*/
static void closeAllCursorsExceptActiveVtabs(Vdbe *p){
int i;
if( p->apCsr==0 ) return;
for(i=0; i<p->nCursor; i++){
Cursor *pC = p->apCsr[i];
if( pC && (!p->inVtabMethod || !pC->pVtabCursor) ){
sqlite3VdbeFreeCursor(p, pC);
p->apCsr[i] = 0;
}
}
}
/*
** Clean up the VM after execution.
**
** This routine will automatically close any cursors, lists, and/or
** sorters that were left open. It also deletes the values of
** variables in the aVar[] array.
*/
static void Cleanup(Vdbe *p, int freebuffers){
int i;
closeAllCursorsExceptActiveVtabs(p);
for(i=1; i<=p->nMem; i++){
MemSetTypeFlag(&p->aMem[i], MEM_Null);
}
releaseMemArray(&p->aMem[1], p->nMem, freebuffers);
sqlite3VdbeFifoClear(&p->sFifo);
if( p->contextStack ){
for(i=0; i<p->contextStackTop; i++){
sqlite3VdbeFifoClear(&p->contextStack[i].sFifo);
}
sqlite3_free(p->contextStack);
}
p->contextStack = 0;
p->contextStackDepth = 0;
p->contextStackTop = 0;
sqlite3_free(p->zErrMsg);
p->zErrMsg = 0;
p->pResultSet = 0;
}
/*
** Set the number of result columns that will be returned by this SQL
** statement. This is now set at compile time, rather than during
** execution of the vdbe program so that sqlite3_column_count() can
** be called on an SQL statement before sqlite3_step().
*/
void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
Mem *pColName;
int n;
releaseMemArray(p->aColName, p->nResColumn*COLNAME_N, 1);
sqlite3_free(p->aColName);
n = nResColumn*COLNAME_N;
p->nResColumn = nResColumn;
p->aColName = pColName = (Mem*)sqlite3DbMallocZero(p->db, sizeof(Mem)*n );
if( p->aColName==0 ) return;
while( n-- > 0 ){
pColName->flags = MEM_Null;
pColName->db = p->db;
pColName++;
}
}
/*
** Set the name of the idx'th column to be returned by the SQL statement.
** zName must be a pointer to a nul terminated string.
**
** This call must be made after a call to sqlite3VdbeSetNumCols().
**
** If N==P4_STATIC it means that zName is a pointer to a constant static
** string and we can just copy the pointer. If it is P4_DYNAMIC, then
** the string is freed using sqlite3_free() when the vdbe is finished with
** it. Otherwise, N bytes of zName are copied.
*/
int sqlite3VdbeSetColName(Vdbe *p, int idx, int var, const char *zName, int N){
int rc;
Mem *pColName;
assert( idx<p->nResColumn );
assert( var<COLNAME_N );
if( p->db->mallocFailed ) return SQLITE_NOMEM;
assert( p->aColName!=0 );
pColName = &(p->aColName[idx+var*p->nResColumn]);
if( N==P4_DYNAMIC || N==P4_STATIC ){
rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, SQLITE_STATIC);
}else{
rc = sqlite3VdbeMemSetStr(pColName, zName, N, SQLITE_UTF8,SQLITE_TRANSIENT);
}
if( rc==SQLITE_OK && N==P4_DYNAMIC ){
pColName->flags &= (~MEM_Static);
pColName->zMalloc = pColName->z;
}
return rc;
}
/*
** A read or write transaction may or may not be active on database handle
** db. If a transaction is active, commit it. If there is a
** write-transaction spanning more than one database file, this routine
** takes care of the master journal trickery.
*/
static int vdbeCommit(sqlite3 *db){
int i;
int nTrans = 0; /* Number of databases with an active write-transaction */
int rc = SQLITE_OK;
int needXcommit = 0;
/* Before doing anything else, call the xSync() callback for any
** virtual module tables written in this transaction. This has to
** be done before determining whether a master journal file is
** required, as an xSync() callback may add an attached database
** to the transaction.
*/
rc = sqlite3VtabSync(db, rc);
if( rc!=SQLITE_OK ){
return rc;
}
/* This loop determines (a) if the commit hook should be invoked and
** (b) how many database files have open write transactions, not
** including the temp database. (b) is important because if more than
** one database file has an open write transaction, a master journal
** file is required for an atomic commit.
*/
for(i=0; i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( sqlite3BtreeIsInTrans(pBt) ){
needXcommit = 1;
if( i!=1 ) nTrans++;
}
}
/* If there are any write-transactions at all, invoke the commit hook */
if( needXcommit && db->xCommitCallback ){
(void)sqlite3SafetyOff(db);
rc = db->xCommitCallback(db->pCommitArg);
(void)sqlite3SafetyOn(db);
if( rc ){
return SQLITE_CONSTRAINT;
}
}
/* The simple case - no more than one database file (not counting the
** TEMP database) has a transaction active. There is no need for the
** master-journal.
**
** If the return value of sqlite3BtreeGetFilename() is a zero length
** string, it means the main database is :memory:. In that case we do
** not support atomic multi-file commits, so use the simple case then
** too.
*/
if( 0==strlen(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){
for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( pBt ){
rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
}
}
/* Do the commit only if all databases successfully complete phase 1.
** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
** IO error while deleting or truncating a journal file. It is unlikely,
** but could happen. In this case abandon processing and return the error.
*/
for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( pBt ){
rc = sqlite3BtreeCommitPhaseTwo(pBt);
}
}
if( rc==SQLITE_OK ){
sqlite3VtabCommit(db);
}
}
/* The complex case - There is a multi-file write-transaction active.
** This requires a master journal file to ensure the transaction is
** committed atomicly.
*/
#ifndef SQLITE_OMIT_DISKIO
else{
sqlite3_vfs *pVfs = db->pVfs;
int needSync = 0;
char *zMaster = 0; /* File-name for the master journal */
char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
sqlite3_file *pMaster = 0;
i64 offset = 0;
/* Select a master journal file name */
do {
u32 random;
sqlite3_free(zMaster);
sqlite3_randomness(sizeof(random), &random);
zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, random&0x7fffffff);
if( !zMaster ){
return SQLITE_NOMEM;
}
rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS);
}while( rc==1 );
if( rc!=0 ){
rc = SQLITE_IOERR_NOMEM;
}else{
/* Open the master journal. */
rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
);
}
if( rc!=SQLITE_OK ){
sqlite3_free(zMaster);
return rc;
}
/* Write the name of each database file in the transaction into the new
** master journal file. If an error occurs at this point close
** and delete the master journal file. All the individual journal files
** still have 'null' as the master journal pointer, so they will roll
** back independently if a failure occurs.
*/
for(i=0; i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( i==1 ) continue; /* Ignore the TEMP database */
if( sqlite3BtreeIsInTrans(pBt) ){
char const *zFile = sqlite3BtreeGetJournalname(pBt);
if( zFile[0]==0 ) continue; /* Ignore :memory: databases */
if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
needSync = 1;
}
rc = sqlite3OsWrite(pMaster, zFile, strlen(zFile)+1, offset);
offset += strlen(zFile)+1;
if( rc!=SQLITE_OK ){
sqlite3OsCloseFree(pMaster);
sqlite3OsDelete(pVfs, zMaster, 0);
sqlite3_free(zMaster);
return rc;
}
}
}
/* Sync the master journal file. If the IOCAP_SEQUENTIAL device
** flag is set this is not required.
*/
zMainFile = sqlite3BtreeGetDirname(db->aDb[0].pBt);
if( (needSync
&& (0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL))
&& (rc=sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))!=SQLITE_OK) ){
sqlite3OsCloseFree(pMaster);
sqlite3OsDelete(pVfs, zMaster, 0);
sqlite3_free(zMaster);
return rc;
}
/* Sync all the db files involved in the transaction. The same call
** sets the master journal pointer in each individual journal. If
** an error occurs here, do not delete the master journal file.
**
** If the error occurs during the first call to
** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
** master journal file will be orphaned. But we cannot delete it,
** in case the master journal file name was written into the journal
** file before the failure occured.
*/
for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( pBt ){
rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
}
}
sqlite3OsCloseFree(pMaster);
if( rc!=SQLITE_OK ){
sqlite3_free(zMaster);
return rc;
}
/* Delete the master journal file. This commits the transaction. After
** doing this the directory is synced again before any individual
** transaction files are deleted.
*/
rc = sqlite3OsDelete(pVfs, zMaster, 1);
sqlite3_free(zMaster);
zMaster = 0;
if( rc ){
return rc;
}
/* All files and directories have already been synced, so the following
** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
** deleting or truncating journals. If something goes wrong while
** this is happening we don't really care. The integrity of the
** transaction is already guaranteed, but some stray 'cold' journals
** may be lying around. Returning an error code won't help matters.
*/
disable_simulated_io_errors();
sqlite3FaultBeginBenign(SQLITE_FAULTINJECTOR_MALLOC);
for(i=0; i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( pBt ){
sqlite3BtreeCommitPhaseTwo(pBt);
}
}
sqlite3FaultEndBenign(SQLITE_FAULTINJECTOR_MALLOC);
enable_simulated_io_errors();
sqlite3VtabCommit(db);
}
#endif
return rc;
}
/*
** This routine checks that the sqlite3.activeVdbeCnt count variable
** matches the number of vdbe's in the list sqlite3.pVdbe that are
** currently active. An assertion fails if the two counts do not match.
** This is an internal self-check only - it is not an essential processing
** step.
**
** This is a no-op if NDEBUG is defined.
*/
#ifndef NDEBUG
static void checkActiveVdbeCnt(sqlite3 *db){
Vdbe *p;
int cnt = 0;
p = db->pVdbe;
while( p ){
if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
cnt++;
}
p = p->pNext;
}
assert( cnt==db->activeVdbeCnt );
}
#else
#define checkActiveVdbeCnt(x)
#endif
/*
** For every Btree that in database connection db which
** has been modified, "trip" or invalidate each cursor in
** that Btree might have been modified so that the cursor
** can never be used again. This happens when a rollback
*** occurs. We have to trip all the other cursors, even
** cursor from other VMs in different database connections,
** so that none of them try to use the data at which they
** were pointing and which now may have been changed due
** to the rollback.
**
** Remember that a rollback can delete tables complete and
** reorder rootpages. So it is not sufficient just to save
** the state of the cursor. We have to invalidate the cursor
** so that it is never used again.
*/
static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
int i;
for(i=0; i<db->nDb; i++){
Btree *p = db->aDb[i].pBt;
if( p && sqlite3BtreeIsInTrans(p) ){
sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
}
}
}
/*
** This routine is called the when a VDBE tries to halt. If the VDBE
** has made changes and is in autocommit mode, then commit those
** changes. If a rollback is needed, then do the rollback.
**
** This routine is the only way to move the state of a VM from
** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
** call this on a VM that is in the SQLITE_MAGIC_HALT state.
**
** Return an error code. If the commit could not complete because of
** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
** means the close did not happen and needs to be repeated.
*/
int sqlite3VdbeHalt(Vdbe *p){
sqlite3 *db = p->db;
int i;
int (*xFunc)(Btree *pBt) = 0; /* Function to call on each btree backend */
int isSpecialError; /* Set to true if SQLITE_NOMEM or IOERR */
/* This function contains the logic that determines if a statement or
** transaction will be committed or rolled back as a result of the
** execution of this virtual machine.
**
** If any of the following errors occur:
**
** SQLITE_NOMEM
** SQLITE_IOERR
** SQLITE_FULL
** SQLITE_INTERRUPT
**
** Then the internal cache might have been left in an inconsistent
** state. We need to rollback the statement transaction, if there is
** one, or the complete transaction if there is no statement transaction.
*/
if( p->db->mallocFailed ){
p->rc = SQLITE_NOMEM;
}
closeAllCursorsExceptActiveVtabs(p);
if( p->magic!=VDBE_MAGIC_RUN ){
return SQLITE_OK;
}
checkActiveVdbeCnt(db);
/* No commit or rollback needed if the program never started */
if( p->pc>=0 ){
int mrc; /* Primary error code from p->rc */
/* Lock all btrees used by the statement */
sqlite3BtreeMutexArrayEnter(&p->aMutex);
/* Check for one of the special errors */
mrc = p->rc & 0xff;
isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
|| mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
if( isSpecialError ){
/* This loop does static analysis of the query to see which of the
** following three categories it falls into:
**
** Read-only
** Query with statement journal
** Query without statement journal
**
** We could do something more elegant than this static analysis (i.e.
** store the type of query as part of the compliation phase), but
** handling malloc() or IO failure is a fairly obscure edge case so
** this is probably easier. Todo: Might be an opportunity to reduce
** code size a very small amount though...
*/
int notReadOnly = 0;
int isStatement = 0;
assert(p->aOp || p->nOp==0);
for(i=0; i<p->nOp; i++){
switch( p->aOp[i].opcode ){
case OP_Transaction:
notReadOnly |= p->aOp[i].p2;
break;
case OP_Statement:
isStatement = 1;
break;
}
}
/* If the query was read-only, we need do no rollback at all. Otherwise,
** proceed with the special handling.
*/
if( notReadOnly || mrc!=SQLITE_INTERRUPT ){
if( p->rc==SQLITE_IOERR_BLOCKED && isStatement ){
xFunc = sqlite3BtreeRollbackStmt;
p->rc = SQLITE_BUSY;
} else if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && isStatement ){
xFunc = sqlite3BtreeRollbackStmt;
}else{
/* We are forced to roll back the active transaction. Before doing
** so, abort any other statements this handle currently has active.
*/
invalidateCursorsOnModifiedBtrees(db);
sqlite3RollbackAll(db);
db->autoCommit = 1;
}
}
}
/* If the auto-commit flag is set and this is the only active vdbe, then
** we do either a commit or rollback of the current transaction.
**
** Note: This block also runs if one of the special errors handled
** above has occured.
*/
if( db->autoCommit && db->activeVdbeCnt==1 ){
if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
/* The auto-commit flag is true, and the vdbe program was
** successful or hit an 'OR FAIL' constraint. This means a commit
** is required.
*/
int rc = vdbeCommit(db);
if( rc==SQLITE_BUSY ){
sqlite3BtreeMutexArrayLeave(&p->aMutex);
return SQLITE_BUSY;
}else if( rc!=SQLITE_OK ){
p->rc = rc;
sqlite3RollbackAll(db);
}else{
sqlite3CommitInternalChanges(db);
}
}else{
sqlite3RollbackAll(db);
}
}else if( !xFunc ){
if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
if( p->openedStatement ){
xFunc = sqlite3BtreeCommitStmt;
}
}else if( p->errorAction==OE_Abort ){
xFunc = sqlite3BtreeRollbackStmt;
}else{
invalidateCursorsOnModifiedBtrees(db);
sqlite3RollbackAll(db);
db->autoCommit = 1;
}
}
/* If xFunc is not NULL, then it is one of sqlite3BtreeRollbackStmt or
** sqlite3BtreeCommitStmt. Call it once on each backend. If an error occurs
** and the return code is still SQLITE_OK, set the return code to the new
** error value.
*/
assert(!xFunc ||
xFunc==sqlite3BtreeCommitStmt ||
xFunc==sqlite3BtreeRollbackStmt
);
for(i=0; xFunc && i<db->nDb; i++){
int rc;
Btree *pBt = db->aDb[i].pBt;
if( pBt ){
rc = xFunc(pBt);
if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
p->rc = rc;
sqlite3SetString(&p->zErrMsg, 0);
}
}
}
/* If this was an INSERT, UPDATE or DELETE and the statement was committed,
** set the change counter.
*/
if( p->changeCntOn && p->pc>=0 ){
if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
sqlite3VdbeSetChanges(db, p->nChange);
}else{
sqlite3VdbeSetChanges(db, 0);
}
p->nChange = 0;
}
/* Rollback or commit any schema changes that occurred. */
if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
sqlite3ResetInternalSchema(db, 0);
db->flags = (db->flags | SQLITE_InternChanges);
}
/* Release the locks */
sqlite3BtreeMutexArrayLeave(&p->aMutex);
}
/* We have successfully halted and closed the VM. Record this fact. */
if( p->pc>=0 ){
db->activeVdbeCnt--;
}
p->magic = VDBE_MAGIC_HALT;
checkActiveVdbeCnt(db);
if( p->db->mallocFailed ){
p->rc = SQLITE_NOMEM;
}
return SQLITE_OK;
}
/*
** Each VDBE holds the result of the most recent sqlite3_step() call
** in p->rc. This routine sets that result back to SQLITE_OK.
*/
void sqlite3VdbeResetStepResult(Vdbe *p){
p->rc = SQLITE_OK;
}
/*
** Clean up a VDBE after execution but do not delete the VDBE just yet.
** Write any error messages into *pzErrMsg. Return the result code.
**
** After this routine is run, the VDBE should be ready to be executed
** again.
**
** To look at it another way, this routine resets the state of the
** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
** VDBE_MAGIC_INIT.
*/
int sqlite3VdbeReset(Vdbe *p, int freebuffers){
sqlite3 *db;
db = p->db;
/* If the VM did not run to completion or if it encountered an
** error, then it might not have been halted properly. So halt
** it now.
*/
(void)sqlite3SafetyOn(db);
sqlite3VdbeHalt(p);
(void)sqlite3SafetyOff(db);
/* If the VDBE has be run even partially, then transfer the error code
** and error message from the VDBE into the main database structure. But
** if the VDBE has just been set to run but has not actually executed any
** instructions yet, leave the main database error information unchanged.
*/
if( p->pc>=0 ){
if( p->zErrMsg ){
sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,sqlite3_free);
db->errCode = p->rc;
p->zErrMsg = 0;
}else if( p->rc ){
sqlite3Error(db, p->rc, 0);
}else{
sqlite3Error(db, SQLITE_OK, 0);
}
}else if( p->rc && p->expired ){
/* The expired flag was set on the VDBE before the first call
** to sqlite3_step(). For consistency (since sqlite3_step() was
** called), set the database error in this case as well.
*/
sqlite3Error(db, p->rc, 0);
sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, sqlite3_free);
p->zErrMsg = 0;
}
/* Reclaim all memory used by the VDBE
*/
Cleanup(p, freebuffers);
/* Save profiling information from this VDBE run.
*/
#ifdef VDBE_PROFILE
{
FILE *out = fopen("vdbe_profile.out", "a");
if( out ){
int i;
fprintf(out, "---- ");
for(i=0; i<p->nOp; i++){
fprintf(out, "%02x", p->aOp[i].opcode);
}
fprintf(out, "\n");
for(i=0; i<p->nOp; i++){
fprintf(out, "%6d %10lld %8lld ",
p->aOp[i].cnt,
p->aOp[i].cycles,
p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
);
sqlite3VdbePrintOp(out, i, &p->aOp[i]);
}
fclose(out);
}
}
#endif
p->magic = VDBE_MAGIC_INIT;
p->aborted = 0;
return p->rc & db->errMask;
}
/*
** Clean up and delete a VDBE after execution. Return an integer which is
** the result code. Write any error message text into *pzErrMsg.
*/
int sqlite3VdbeFinalize(Vdbe *p){
int rc = SQLITE_OK;
if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
rc = sqlite3VdbeReset(p, 1);
assert( (rc & p->db->errMask)==rc );
}else if( p->magic!=VDBE_MAGIC_INIT ){
return SQLITE_MISUSE;
}
releaseMemArray(&p->aMem[1], p->nMem, 1);
sqlite3VdbeDelete(p);
return rc;
}
/*
** Call the destructor for each auxdata entry in pVdbeFunc for which
** the corresponding bit in mask is clear. Auxdata entries beyond 31
** are always destroyed. To destroy all auxdata entries, call this
** routine with mask==0.
*/
void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
int i;
for(i=0; i<pVdbeFunc->nAux; i++){
struct AuxData *pAux = &pVdbeFunc->apAux[i];
if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
if( pAux->xDelete ){
pAux->xDelete(pAux->pAux);
}
pAux->pAux = 0;
}
}
}
/*
** Delete an entire VDBE.
*/
void sqlite3VdbeDelete(Vdbe *p){
int i;
if( p==0 ) return;
Cleanup(p, 1);
if( p->pPrev ){
p->pPrev->pNext = p->pNext;
}else{
assert( p->db->pVdbe==p );
p->db->pVdbe = p->pNext;
}
if( p->pNext ){
p->pNext->pPrev = p->pPrev;
}
if( p->aOp ){
Op *pOp = p->aOp;
for(i=0; i<p->nOp; i++, pOp++){
freeP4(pOp->p4type, pOp->p4.p);
#ifdef SQLITE_DEBUG
sqlite3_free(pOp->zComment);
#endif
}
sqlite3_free(p->aOp);
}
releaseMemArray(p->aVar, p->nVar, 1);
sqlite3_free(p->aLabel);
if( p->aMem ){
sqlite3_free(&p->aMem[1]);
}
releaseMemArray(p->aColName, p->nResColumn*COLNAME_N, 1);
sqlite3_free(p->aColName);
sqlite3_free(p->zSql);
p->magic = VDBE_MAGIC_DEAD;
sqlite3_free(p);
}
/*
** If a MoveTo operation is pending on the given cursor, then do that
** MoveTo now. Return an error code. If no MoveTo is pending, this
** routine does nothing and returns SQLITE_OK.
*/
int sqlite3VdbeCursorMoveto(Cursor *p){
if( p->deferredMoveto ){
int res, rc;
#ifdef SQLITE_TEST
extern int sqlite3_search_count;
#endif
assert( p->isTable );
rc = sqlite3BtreeMoveto(p->pCursor, 0, 0, p->movetoTarget, 0, &res);
if( rc ) return rc;
*p->pIncrKey = 0;
p->lastRowid = keyToInt(p->movetoTarget);
p->rowidIsValid = res==0;
if( res<0 ){
rc = sqlite3BtreeNext(p->pCursor, &res);
if( rc ) return rc;
}
#ifdef SQLITE_TEST
sqlite3_search_count++;
#endif
p->deferredMoveto = 0;
p->cacheStatus = CACHE_STALE;
}
return SQLITE_OK;
}
/*
** The following functions:
**
** sqlite3VdbeSerialType()
** sqlite3VdbeSerialTypeLen()
** sqlite3VdbeSerialRead()
** sqlite3VdbeSerialLen()
** sqlite3VdbeSerialWrite()
**
** encapsulate the code that serializes values for storage in SQLite
** data and index records. Each serialized value consists of a
** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
** integer, stored as a varint.
**
** In an SQLite index record, the serial type is stored directly before
** the blob of data that it corresponds to. In a table record, all serial
** types are stored at the start of the record, and the blobs of data at
** the end. Hence these functions allow the caller to handle the
** serial-type and data blob seperately.
**
** The following table describes the various storage classes for data:
**
** serial type bytes of data type
** -------------- --------------- ---------------
** 0 0 NULL
** 1 1 signed integer
** 2 2 signed integer
** 3 3 signed integer
** 4 4 signed integer
** 5 6 signed integer
** 6 8 signed integer
** 7 8 IEEE float
** 8 0 Integer constant 0
** 9 0 Integer constant 1
** 10,11 reserved for expansion
** N>=12 and even (N-12)/2 BLOB
** N>=13 and odd (N-13)/2 text
**
** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
** of SQLite will not understand those serial types.
*/
/*
** Return the serial-type for the value stored in pMem.
*/
u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
int flags = pMem->flags;
int n;
if( flags&MEM_Null ){
return 0;
}
if( flags&MEM_Int ){
/* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
# define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
i64 i = pMem->u.i;
u64 u;
if( file_format>=4 && (i&1)==i ){
return 8+i;
}
u = i<0 ? -i : i;
if( u<=127 ) return 1;
if( u<=32767 ) return 2;
if( u<=8388607 ) return 3;
if( u<=2147483647 ) return 4;
if( u<=MAX_6BYTE ) return 5;
return 6;
}
if( flags&MEM_Real ){
return 7;
}
assert( flags&(MEM_Str|MEM_Blob) );
n = pMem->n;
if( flags & MEM_Zero ){
n += pMem->u.i;
}
assert( n>=0 );
return ((n*2) + 12 + ((flags&MEM_Str)!=0));
}
/*
** Return the length of the data corresponding to the supplied serial-type.
*/
int sqlite3VdbeSerialTypeLen(u32 serial_type){
if( serial_type>=12 ){
return (serial_type-12)/2;
}else{
static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
return aSize[serial_type];
}
}
/*
** If we are on an architecture with mixed-endian floating
** points (ex: ARM7) then swap the lower 4 bytes with the
** upper 4 bytes. Return the result.
**
** For most architectures, this is a no-op.
**
** (later): It is reported to me that the mixed-endian problem
** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
** that early versions of GCC stored the two words of a 64-bit
** float in the wrong order. And that error has been propagated
** ever since. The blame is not necessarily with GCC, though.
** GCC might have just copying the problem from a prior compiler.
** I am also told that newer versions of GCC that follow a different
** ABI get the byte order right.
**
** Developers using SQLite on an ARM7 should compile and run their
** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
** enabled, some asserts below will ensure that the byte order of
** floating point values is correct.
**
** (2007-08-30) Frank van Vugt has studied this problem closely
** and has send his findings to the SQLite developers. Frank
** writes that some Linux kernels offer floating point hardware
** emulation that uses only 32-bit mantissas instead of a full
** 48-bits as required by the IEEE standard. (This is the
** CONFIG_FPE_FASTFPE option.) On such systems, floating point
** byte swapping becomes very complicated. To avoid problems,
** the necessary byte swapping is carried out using a 64-bit integer
** rather than a 64-bit float. Frank assures us that the code here
** works for him. We, the developers, have no way to independently
** verify this, but Frank seems to know what he is talking about
** so we trust him.
*/
#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
static u64 floatSwap(u64 in){
union {
u64 r;
u32 i[2];
} u;
u32 t;
u.r = in;
t = u.i[0];
u.i[0] = u.i[1];
u.i[1] = t;
return u.r;
}
# define swapMixedEndianFloat(X) X = floatSwap(X)
#else
# define swapMixedEndianFloat(X)
#endif
/*
** Write the serialized data blob for the value stored in pMem into
** buf. It is assumed that the caller has allocated sufficient space.
** Return the number of bytes written.
**
** nBuf is the amount of space left in buf[]. nBuf must always be
** large enough to hold the entire field. Except, if the field is
** a blob with a zero-filled tail, then buf[] might be just the right
** size to hold everything except for the zero-filled tail. If buf[]
** is only big enough to hold the non-zero prefix, then only write that
** prefix into buf[]. But if buf[] is large enough to hold both the
** prefix and the tail then write the prefix and set the tail to all
** zeros.
**
** Return the number of bytes actually written into buf[]. The number
** of bytes in the zero-filled tail is included in the return value only
** if those bytes were zeroed in buf[].
*/
int sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
int len;
/* Integer and Real */
if( serial_type<=7 && serial_type>0 ){
u64 v;
int i;
if( serial_type==7 ){
assert( sizeof(v)==sizeof(pMem->r) );
memcpy(&v, &pMem->r, sizeof(v));
swapMixedEndianFloat(v);
}else{
v = pMem->u.i;
}
len = i = sqlite3VdbeSerialTypeLen(serial_type);
assert( len<=nBuf );
while( i-- ){
buf[i] = (v&0xFF);
v >>= 8;
}
return len;
}
/* String or blob */
if( serial_type>=12 ){
assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.i:0)
== sqlite3VdbeSerialTypeLen(serial_type) );
assert( pMem->n<=nBuf );
len = pMem->n;
memcpy(buf, pMem->z, len);
if( pMem->flags & MEM_Zero ){
len += pMem->u.i;
if( len>nBuf ){
len = nBuf;
}
memset(&buf[pMem->n], 0, len-pMem->n);
}
return len;
}
/* NULL or constants 0 or 1 */
return 0;
}
/*
** Deserialize the data blob pointed to by buf as serial type serial_type
** and store the result in pMem. Return the number of bytes read.
*/
int sqlite3VdbeSerialGet(
const unsigned char *buf, /* Buffer to deserialize from */
u32 serial_type, /* Serial type to deserialize */
Mem *pMem /* Memory cell to write value into */
){
switch( serial_type ){
case 10: /* Reserved for future use */
case 11: /* Reserved for future use */
case 0: { /* NULL */
pMem->flags = MEM_Null;
break;
}
case 1: { /* 1-byte signed integer */
pMem->u.i = (signed char)buf[0];
pMem->flags = MEM_Int;
return 1;
}
case 2: { /* 2-byte signed integer */
pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
pMem->flags = MEM_Int;
return 2;
}
case 3: { /* 3-byte signed integer */
pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
pMem->flags = MEM_Int;
return 3;
}
case 4: { /* 4-byte signed integer */
pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
pMem->flags = MEM_Int;
return 4;
}
case 5: { /* 6-byte signed integer */
u64 x = (((signed char)buf[0])<<8) | buf[1];
u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
x = (x<<32) | y;
pMem->u.i = *(i64*)&x;
pMem->flags = MEM_Int;
return 6;
}
case 6: /* 8-byte signed integer */
case 7: { /* IEEE floating point */
u64 x;
u32 y;
#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
/* Verify that integers and floating point values use the same
** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
** defined that 64-bit floating point values really are mixed
** endian.
*/
static const u64 t1 = ((u64)0x3ff00000)<<32;
static const double r1 = 1.0;
u64 t2 = t1;
swapMixedEndianFloat(t2);
assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
#endif
x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
x = (x<<32) | y;
if( serial_type==6 ){
pMem->u.i = *(i64*)&x;
pMem->flags = MEM_Int;
}else{
assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
swapMixedEndianFloat(x);
memcpy(&pMem->r, &x, sizeof(x));
pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
}
return 8;
}
case 8: /* Integer 0 */
case 9: { /* Integer 1 */
pMem->u.i = serial_type-8;
pMem->flags = MEM_Int;
return 0;
}
default: {
int len = (serial_type-12)/2;
pMem->z = (char *)buf;
pMem->n = len;
pMem->xDel = 0;
if( serial_type&0x01 ){
pMem->flags = MEM_Str | MEM_Ephem;
}else{
pMem->flags = MEM_Blob | MEM_Ephem;
}
return len;
}
}
return 0;
}
/*
** Given the nKey-byte encoding of a record in pKey[], parse the
** record into a UnpackedRecord structure. Return a pointer to
** that structure.
**
** The calling function might provide szSpace bytes of memory
** space at pSpace. This space can be used to hold the returned
** VDbeParsedRecord structure if it is large enough. If it is
** not big enough, space is obtained from sqlite3_malloc().
**
** The returned structure should be closed by a call to
** sqlite3VdbeDeleteUnpackedRecord().
*/
UnpackedRecord *sqlite3VdbeRecordUnpack(
KeyInfo *pKeyInfo, /* Information about the record format */
int nKey, /* Size of the binary record */
const void *pKey, /* The binary record */
void *pSpace, /* Space available to hold resulting object */
int szSpace /* Size of pSpace[] in bytes */
){
const unsigned char *aKey = (const unsigned char *)pKey;
UnpackedRecord *p;
int nByte;
int i, idx, d;
u32 szHdr;
Mem *pMem;
assert( sizeof(Mem)>sizeof(*p) );
nByte = sizeof(Mem)*(pKeyInfo->nField+2);
if( nByte>szSpace ){
p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
if( p==0 ) return 0;
p->needFree = 1;
}else{
p = pSpace;
p->needFree = 0;
}
p->pKeyInfo = pKeyInfo;
p->nField = pKeyInfo->nField + 1;
p->needDestroy = 1;
p->aMem = pMem = &((Mem*)p)[1];
idx = getVarint32(aKey, szHdr);
d = szHdr;
i = 0;
while( idx<szHdr && i<p->nField ){
u32 serial_type;
idx += getVarint32( aKey+idx, serial_type);
if( d>=nKey && sqlite3VdbeSerialTypeLen(serial_type)>0 ) break;
pMem->enc = pKeyInfo->enc;
pMem->db = pKeyInfo->db;
pMem->flags = 0;
pMem->zMalloc = 0;
d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
pMem++;
i++;
}
p->nField = i;
return (void*)p;
}
/*
** This routine destroys a UnpackedRecord object
*/
void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
if( p ){
if( p->needDestroy ){
int i;
Mem *pMem;
for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
if( pMem->zMalloc ){
sqlite3VdbeMemRelease(pMem);
}
}
}
if( p->needFree ){
sqlite3_free(p);
}
}
}
/*
** This function compares the two table rows or index records
** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
** or positive integer if {nKey1, pKey1} is less than, equal to or
** greater than pPKey2. The {nKey1, pKey1} key must be a blob
** created by th OP_MakeRecord opcode of the VDBE. The pPKey2
** key must be a parsed key such as obtained from
** sqlite3VdbeParseRecord.
**
** Key1 and Key2 do not have to contain the same number of fields.
** But if the lengths differ, Key2 must be the shorter of the two.
**
** Historical note: In earlier versions of this routine both Key1
** and Key2 were blobs obtained from OP_MakeRecord. But we found
** that in typical use the same Key2 would be submitted multiple times
** in a row. So an optimization was added to parse the Key2 key
** separately and submit the parsed version. In this way, we avoid
** parsing the same Key2 multiple times in a row.
*/
int sqlite3VdbeRecordCompare(
int nKey1, const void *pKey1,
UnpackedRecord *pPKey2
){
u32 d1; /* Offset into aKey[] of next data element */
u32 idx1; /* Offset into aKey[] of next header element */
u32 szHdr1; /* Number of bytes in header */
int i = 0;
int nField;
int rc = 0;
const unsigned char *aKey1 = (const unsigned char *)pKey1;
KeyInfo *pKeyInfo;
Mem mem1;
pKeyInfo = pPKey2->pKeyInfo;
mem1.enc = pKeyInfo->enc;
mem1.db = pKeyInfo->db;
mem1.flags = 0;
mem1.zMalloc = 0;
idx1 = getVarint32(aKey1, szHdr1);
d1 = szHdr1;
nField = pKeyInfo->nField;
while( idx1<szHdr1 && i<pPKey2->nField ){
u32 serial_type1;
/* Read the serial types for the next element in each key. */
idx1 += getVarint32( aKey1+idx1, serial_type1 );
if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
/* Extract the values to be compared.
*/
d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
/* Do the comparison
*/
rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
i<nField ? pKeyInfo->aColl[i] : 0);
if( rc!=0 ){
break;
}
i++;
}
if( mem1.zMalloc ) sqlite3VdbeMemRelease(&mem1);
/* One of the keys ran out of fields, but all the fields up to that point
** were equal. If the incrKey flag is true, then the second key is
** treated as larger.
*/
if( rc==0 ){
if( pKeyInfo->incrKey ){
rc = -1;
}else if( !pKeyInfo->prefixIsEqual ){
if( d1<nKey1 ){
rc = 1;
}
}
}else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
&& pKeyInfo->aSortOrder[i] ){
rc = -rc;
}
return rc;
}
/*
** The argument is an index entry composed using the OP_MakeRecord opcode.
** The last entry in this record should be an integer (specifically
** an integer rowid). This routine returns the number of bytes in
** that integer.
*/
int sqlite3VdbeIdxRowidLen(const u8 *aKey){
u32 szHdr; /* Size of the header */
u32 typeRowid; /* Serial type of the rowid */
(void)getVarint32(aKey, szHdr);
(void)getVarint32(&aKey[szHdr-1], typeRowid);
return sqlite3VdbeSerialTypeLen(typeRowid);
}
/*
** pCur points at an index entry created using the OP_MakeRecord opcode.
** Read the rowid (the last field in the record) and store it in *rowid.
** Return SQLITE_OK if everything works, or an error code otherwise.
*/
int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
i64 nCellKey = 0;
int rc;
u32 szHdr; /* Size of the header */
u32 typeRowid; /* Serial type of the rowid */
u32 lenRowid; /* Size of the rowid */
Mem m, v;
sqlite3BtreeKeySize(pCur, &nCellKey);
if( nCellKey<=0 ){
return SQLITE_CORRUPT_BKPT;
}
m.flags = 0;
m.db = 0;
m.zMalloc = 0;
rc = sqlite3VdbeMemFromBtree(pCur, 0, nCellKey, 1, &m);
if( rc ){
return rc;
}
(void)getVarint32((u8*)m.z, szHdr);
(void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
*rowid = v.u.i;
sqlite3VdbeMemRelease(&m);
return SQLITE_OK;
}
/*
** Compare the key of the index entry that cursor pC is point to against
** the key string in pKey (of length nKey). Write into *pRes a number
** that is negative, zero, or positive if pC is less than, equal to,
** or greater than pKey. Return SQLITE_OK on success.
**
** pKey is either created without a rowid or is truncated so that it
** omits the rowid at the end. The rowid at the end of the index entry
** is ignored as well.
*/
int sqlite3VdbeIdxKeyCompare(
Cursor *pC, /* The cursor to compare against */
UnpackedRecord *pUnpacked,
int nKey, const u8 *pKey, /* The key to compare */
int *res /* Write the comparison result here */
){
i64 nCellKey = 0;
int rc;
BtCursor *pCur = pC->pCursor;
int lenRowid;
Mem m;
UnpackedRecord *pRec;
char zSpace[200];
sqlite3BtreeKeySize(pCur, &nCellKey);
if( nCellKey<=0 ){
*res = 0;
return SQLITE_OK;
}
m.db = 0;
m.flags = 0;
m.zMalloc = 0;
rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, nCellKey, 1, &m);
if( rc ){
return rc;
}
lenRowid = sqlite3VdbeIdxRowidLen((u8*)m.z);
if( !pUnpacked ){
pRec = sqlite3VdbeRecordUnpack(pC->pKeyInfo, nKey, pKey,
zSpace, sizeof(zSpace));
}else{
pRec = pUnpacked;
}
if( pRec==0 ){
return SQLITE_NOMEM;
}
*res = sqlite3VdbeRecordCompare(m.n-lenRowid, m.z, pRec);
if( !pUnpacked ){
sqlite3VdbeDeleteUnpackedRecord(pRec);
}
sqlite3VdbeMemRelease(&m);
return SQLITE_OK;
}
/*
** This routine sets the value to be returned by subsequent calls to
** sqlite3_changes() on the database handle 'db'.
*/
void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
assert( sqlite3_mutex_held(db->mutex) );
db->nChange = nChange;
db->nTotalChange += nChange;
}
/*
** Set a flag in the vdbe to update the change counter when it is finalised
** or reset.
*/
void sqlite3VdbeCountChanges(Vdbe *v){
v->changeCntOn = 1;
}
/*
** Mark every prepared statement associated with a database connection
** as expired.
**
** An expired statement means that recompilation of the statement is
** recommend. Statements expire when things happen that make their
** programs obsolete. Removing user-defined functions or collating
** sequences, or changing an authorization function are the types of
** things that make prepared statements obsolete.
*/
void sqlite3ExpirePreparedStatements(sqlite3 *db){
Vdbe *p;
for(p = db->pVdbe; p; p=p->pNext){
p->expired = 1;
}
}
/*
** Return the database associated with the Vdbe.
*/
sqlite3 *sqlite3VdbeDb(Vdbe *v){
return v->db;
}
| ZHAW-INES/rioxo-uClinux-dist | lib/sqlite/sqlite-3.5.9/src/vdbeaux.c | C | gpl-2.0 | 72,237 |
package sKits.cmds;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import sKits.main.sKitmain;
public class SoupCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(!(sender instanceof Player)) {
return false;
}
final Player player = (Player) sender;
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 120, 3));
player.addPotionEffect(new PotionEffect(PotionEffectType.WEAKNESS, 120, 3));
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 120, 3));
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(sKitmain.inst, new Runnable() {
@Override
public void run() {
// private int i=0;
// for (i=0; i++; i<9)
player.getInventory().addItem(new ItemStack(Material.MUSHROOM_SOUP, 1));
player.sendMessage(ChatColor.DARK_GREEN + "You have been given some soup!");
}
}, 100L);
return true;
}
}
| jaypeeteeB/sKits | src/sKits/cmds/SoupCommand.java | Java | gpl-2.0 | 1,325 |
/* Copyright 2007 - 2010 YOOtheme GmbH, YOOtheme Proprietary Use License (http://www.yootheme.com/license) */
var Warp=Warp||{};
Warp.Spotlight=new Class({initialize:function(f,c){var a=this;this.setOptions({effect:"fade",effectOptions:{duration:10}},c);this.element=$(f);this.slides=this.element.getChildren();this.slides.each(function(d){var b=new Element("div");b.adopt(d);a.element.adopt(b)});this.slides=this.element.getChildren();this.slides.each(function(d,b){d.setStyles({position:"absolute",width:"100%",visibility:b==0?"visible":"hidden"}).addClass("spotlight"+b)});this.element.setStyles({position:"relative",overflow:"hidden",
height:a.slides[0].getSize().size.y});this.element.addEvents({mouseenter:function(){a.fx.stop();switch(a.options.effect){case "right":a.slides[1].setStyles({right:a.slides[1].getSize().size.x*-1,visibility:"visible"});a.fx.start({right:[a.slides[1].getSize().size.x*-1,0]});break;case "left":a.slides[1].setStyles({left:a.slides[1].getSize().size.x*-1,visibility:"visible"});a.fx.start({left:[a.slides[1].getSize().size.x*-1,0]});break;case "top":a.slides[1].setStyles({left:0,top:a.slides[1].getSize().size.y*
-1,visibility:"visible"});a.fx.start({top:[a.slides[1].getSize().size.y*-1,0]});break;case "bottom":a.slides[1].setStyles({left:0,bottom:a.slides[1].getSize().size.y*-1,visibility:"visible"});a.fx.start({bottom:[a.slides[1].getSize().size.y*-1,0]});break;default:a.fx.start({opacity:[0,1]})}},mouseleave:function(){a.fx.stop();switch(a.options.effect){case "right":a.fx.start({right:[0,a.slides[1].getSize().size.x*-1]});break;case "left":a.fx.start({left:[0,a.slides[1].getSize().size.x*-1]});break;case "top":a.fx.start({top:[0,
a.slides[1].getSize().size.y*-1]});break;case "bottom":a.fx.start({bottom:[0,a.slides[1].getSize().size.y*-1]});break;default:a.fx.start({opacity:[1,0]})}}});this.fx=new Fx.Styles(this.slides[1],this.options.effectOptions)}});Warp.Spotlight.implement(new Options);
Warp.Spotlight.attach=function(f,c){c=c||{};c=$extend({right:300,left:300,top:300,bottom:300,fade:300},c);document.getElements(f).each(function(a){var d="fade",b=c[d];String(a.getProperty("class")).split(" ").each(function(e){if(["right","left","top","bottom","fade"].contains(e)){d=e;b=c[d]}if(e.test("duration-"))b=e.split("-")[1].toInt()});new Warp.Spotlight(a,{effect:d,effectOptions:{duration:b}})})};
| foxbei/joomla15 | templates/yoo_scoop/warp/systems/joomla.1.5/js/spotlight.js | JavaScript | gpl-2.0 | 2,355 |
#tml_ajax_overlay {
position: fixed;
z-index: 10000;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #000;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
filter: alpha(opacity=0);
-moz-opacity: 0;
opacity: 0;
}
#tml_ajax_window {
width: 400px;
position: fixed;
background: #ffffff;
z-index: 10002;
color: #000;
text-align: left;
top: 50%;
left: 50%;
display: none;
-moz-box-shadow: rgba(0,0,0,1) 0 4px 30px;
-webkit-box-shadow: rgba(0,0,0,1) 0 4px 30px;
-khtml-box-shadow: rgba(0,0,0,1) 0 4px 30px;
box-shadow: rgba(0,0,0,1) 0 4px 30px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
-khtml-border-radius: 10px;
border-radius: 10px;
}
#tml_ajax_content{
clear: both;
padding: 15px;
overflow: auto;
text-align: left;
}
#tml_ajax_content h2 {
font-size: 1.5em;
margin: 0 0 10px;
}
#tml_ajax_content input[type="text"],
#tml_ajax_content input[type="password"],
#tml_ajax_content input[type="submit"] {
width: 100%;
padding: 5px;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
#tml_ajax_content p {
margin: 5px 0;
}
#tml_ajax_content ul {
margin: 5px 0;
list-style-position: inside;
}
#tml_ajax_content li {
margin: 5px 0;
}
#tml_ajax_content .tml-user-avatar {
float: left;
}
#tml_ajax_content .tml-user-links {
float: left;
margin: 0 0 0 10px;
}
| olek1984/dremboard | wp-content/plugins/theme-my-login/modules/ajax/css/ajax.css | CSS | gpl-2.0 | 1,440 |
require 'test_helper'
class EventsControllerTest < ActionController::TestCase
setup do
@event = events(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:events)
end
test "should get new" do
get :new
assert_response :success
end
test "should create event" do
assert_difference('Event.count') do
post :create, event: { eventdatetime: @event.eventdatetime, eventduration: @event.eventduration, opponentid: @event.opponentid, teamid: @event.teamid, type: @event.type, venueid: @event.venueid }
end
assert_redirected_to event_path(assigns(:event))
end
test "should show event" do
get :show, id: @event
assert_response :success
end
test "should get edit" do
get :edit, id: @event
assert_response :success
end
test "should update event" do
patch :update, id: @event, event: { eventdatetime: @event.eventdatetime, eventduration: @event.eventduration, opponentid: @event.opponentid, teamid: @event.teamid, type: @event.type, venueid: @event.venueid }
assert_redirected_to event_path(assigns(:event))
end
test "should destroy event" do
assert_difference('Event.count', -1) do
delete :destroy, id: @event
end
assert_redirected_to events_path
end
end
| mpwalsh8/accmobilewebapp | test/controllers/events_controller_test.rb | Ruby | gpl-2.0 | 1,312 |
<?php
//
// +----------------------------------------------------------------------+
// |zen-cart Open Source E-commerce |
// +----------------------------------------------------------------------+
// | Copyright (c) 2003 The zen-cart developers |
// | |
// | http://www.zen-cart.com/index.php |
// | |
// | Portions Copyright (c) 2003 osCommerce |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the GPL license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available through the world-wide-web at the following url: |
// | http://www.zen-cart.com/license/2_0.txt. |
// | If you did not receive a copy of the zen-cart license and are unable |
// | to obtain it through the world-wide-web, please send a note to |
// | license@zen-cart.com so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// $Id: moneyorder.php 1969 2005-09-13 06:57:21Z drbyte $
//
define('MODULE_PAYMENT_MONEYORDER_TEXT_TITLE', 'Virement Bancaire');
define('MODULE_PAYMENT_MONEYORDER_TEXT_DESCRIPTION', '
<br /><hr>
Veuillez faire un virement du montant de la commande ttc aux coordonnées bancaires ci-dessous :<br /><br />
Bénéficaire : Sarl HPL Domiciliation : BP RIVES PARIS-LAMARQ<br />
CODE ETABLISSEMENT : 10207<br />
CODE GUICHET : 00203<br />
N° DE COMPTE : 21219603828 CLE RIB : 36<br />
<br /><br />
Pour les virements de l\'étranger :<br />
IBAN : FR76 1020 7002 0321 2196 0382 836<br />
BIC : CCBPFRPPMTG<br />
<br />
<hr>' . 'Votre commande ne sera envoyée qu\'à
réception du règlement et de sa validation par notre banque.');
define('MODULE_PAYMENT_MONEYORDER_TEXT_EMAIL_FOOTER', MODULE_PAYMENT_MONEYORDER_TEXT_DESCRIPTION );
?>
| fvaron/zencart_fr | includes/languages/french/modules/payment/moneyorder_hpl.php | PHP | gpl-2.0 | 2,165 |
/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*-
this file is part of rcssserver3D
Fri May 9 2003
Copyright (C) 2002,2003 Koblenz University
Copyright (C) 2003 RoboCup Soccer Server 3D Maintenance Group
$Id$
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <oxygen/physicsserver/staticbody.h>
#include <oxygen/physicsserver/int/staticbodyint.h>
using namespace oxygen;
using namespace boost;
boost::shared_ptr<StaticBodyInt> StaticBody::mStaticBodyImp;
StaticBody::StaticBody() : Body(){
}
StaticBody::~StaticBody(){
}
void StaticBody::OnLink()
{
if (mStaticBodyImp.get() == 0)
mStaticBodyImp = dynamic_pointer_cast<StaticBodyInt>
(GetCore()->New("StaticBodyImp"));
}
| xuyuan/spark-spl-release | lib/oxygen/physicsserver/staticbody.cpp | C++ | gpl-2.0 | 1,337 |
/* This file is part of the KDE project
Copyright (C) 2003-2012 Jarosław Staniek <staniek@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef KEXIDB_QUERYSCHEMA_H
#define KEXIDB_QUERYSCHEMA_H
#include <QVector>
#include <QString>
#include <QHash>
#include <QList>
#include <QByteArray>
#include "fieldlist.h"
#include "schemadata.h"
#include "tableschema.h"
#include "relationship.h"
namespace KexiDB
{
class Connection;
class QueryAsterisk;
class QuerySchemaPrivate;
class QuerySchemaParameter;
typedef QList<QuerySchemaParameter> QuerySchemaParameterList;
//! @short Helper class that assigns additional information for the column in a query
/*! The following information is assigned:
- alias
- visibility
QueryColumnInfo::Vector is created and returned by QuerySchema::fieldsExpanded().
It is efficiently cached within the QuerySchema object.
*/
class CALLIGRADB_EXPORT QueryColumnInfo
{
public:
typedef QVector<QueryColumnInfo*> Vector;
typedef QList<QueryColumnInfo*> List;
typedef QList<QueryColumnInfo*>::ConstIterator ListIterator;
QueryColumnInfo(Field *f, const QByteArray& _alias, bool _visible, QueryColumnInfo *foreignColumn = 0);
~QueryColumnInfo();
//! \return alias if it is not empty, field's name otherwise.
inline QByteArray aliasOrName() const {
if (alias.isEmpty()) {
return field->name().toLatin1();
} else {
return QByteArray((const char*)alias);
}
}
//! \return field's caption if it is not empty, field's alias otherwise.
//! If alias is also empty - returns field's name.
inline QString captionOrAliasOrName() const {
return field->caption().isEmpty() ? QString(aliasOrName()) : field->caption();
}
Field *field;
QByteArray alias;
/*! \return index of column with visible lookup value within the 'fields expanded' vector.
-1 means no visible lookup value is available because there is no lookup for the column defined.
Cached for efficiency as we use this information frequently.
@see LookupFieldSchema::visibleVolumn() */
inline int indexForVisibleLookupValue() const {
return m_indexForVisibleLookupValue;
}
/*! Sets index of column with visible lookup value within the 'fields expanded' vector. */
inline void setIndexForVisibleLookupValue(int index) {
m_indexForVisibleLookupValue = index;
}
//! \return non-0 if this column is a visible column for other column
QueryColumnInfo *foreignColumn() const {
return m_foreignColumn;
}
/*! \return string for debugging purposes. */
QString debugString() const;
//! true if this column is visible to the user (and its data is fetched by the engine)
bool visible;
private:
/*! Index of column with visible lookup value within the 'fields expanded' vector.
@see indexForVisibleLookupValue() */
int m_indexForVisibleLookupValue;
//! Non-0 if this column is a visible column for \a m_foreignColumn
QueryColumnInfo *m_foreignColumn;
};
//! @short KexiDB::OrderByColumn provides information about a single query column used for sorting
/*! The column can be expression or table field. */
class CALLIGRADB_EXPORT OrderByColumn
{
public:
typedef QList<OrderByColumn*>::ConstIterator ListConstIterator;
OrderByColumn();
explicit OrderByColumn(QueryColumnInfo& column, bool ascending = true, int pos = -1);
//! Like above but used when the field \a field is not present on the list of columns.
//! (e.g. SELECT a FROM t ORDER BY b; where T is a table with fields (a,b)).
explicit OrderByColumn(Field& field, bool ascending = true);
~OrderByColumn();
/*! @return copy of this OrderByColumn object.
In @a fromQuery and @a toQuery is needed if column() is assigned to this info.
Then, column info within @a toQuery will be assigned to the new OrderByColumn object,
corresponding to column() from "this" OrderByColumn object. */
OrderByColumn* copy(QuerySchema* fromQuery, QuerySchema* toQuery) const;
//! A column to sort.
inline QueryColumnInfo* column() const {
return m_column;
}
/*! A helper for column() that allows you to know that sorting column
was defined by providing its position. -1 by default.
Example query: SELECT a, b FROM T ORDER BY 2 */
inline int position() const {
return m_pos;
}
//! A field to sort, used only in case when the second constructor was used.
inline Field *field() const {
return m_field;
}
//! \return true if ascending sorting should be performed (the default).
inline bool ascending() const {
return m_ascending;
}
//! \return true if this column is thesame as \a col
bool operator== (const OrderByColumn& col) const {
return m_column == col.m_column && m_field == col.m_field
&& m_ascending == col.m_ascending;
}
/*! \return string for debugging purposes. */
QString debugString() const;
/*! \return a string like "name ASC" usable for building a SQL statement.
If \a includeTableNames is true (the default) field is output in a form
of "tablename.fieldname" (but only if fieldname is not a name of alias).
\a drv and \a identifierEscaping are used for escaping the table and field identifiers. */
QString toSQLString(bool includeTableName = true,
const Driver *drv = 0, int identifierEscaping = Driver::EscapeDriver | Driver::EscapeAsNecessary) const;
protected:
//! Column to sort
QueryColumnInfo* m_column; //!< 0 if m_field is non-0.
int m_pos; //!< A helper for m_column that allows to know that sorting column
//!< was defined by providing its position. -1 by default.
//!< e.g. SELECT a, b FROM T ORDER BY 2
Field* m_field; //!< Used only in case when the second contructor is used.
bool m_ascending; //!< true if ascending sorting should be performed (the default).
};
//! A base for KexiDB::OrderByColumnList
typedef QList<OrderByColumn*> OrderByColumnListBase;
//! @short KexiDB::OrderByColumnList provides list of sorted columns for a query schema
class CALLIGRADB_EXPORT OrderByColumnList : protected OrderByColumnListBase
{
public:
/*! Constructs empty list of ordered columns. */
OrderByColumnList();
/*! A copy constructor. */
OrderByColumnList(const OrderByColumnList& other,
QuerySchema* fromQuery, QuerySchema* toQuery);
~OrderByColumnList();
class CALLIGRADB_EXPORT const_iterator : public OrderByColumnListBase::const_iterator
{
public:
inline const_iterator()
: OrderByColumnListBase::const_iterator() {}
inline const_iterator(const OrderByColumnListBase::const_iterator &o)
: OrderByColumnListBase::const_iterator(o) {}
};
class CALLIGRADB_EXPORT iterator : public OrderByColumnListBase::iterator
{
public:
inline iterator()
: OrderByColumnListBase::iterator() {}
inline iterator(const OrderByColumnListBase::iterator &o)
: OrderByColumnListBase::iterator(o) {}
};
/*! Appends multiple fields for sorting. \a querySchema
is used to find appropriate field or alias name.
\return false if there is at least one name for which a field or alias name does not exist
(all the newly appended fields are removed in this case) */
bool appendFields(QuerySchema& querySchema,
const QString& field1, bool ascending1 = true,
const QString& field2 = QString(), bool ascending2 = true,
const QString& field3 = QString(), bool ascending3 = true,
const QString& field4 = QString(), bool ascending4 = true,
const QString& field5 = QString(), bool ascending5 = true);
/*! Appends column \a columnInfo. Ascending sorting is set is \a ascending is true. */
void appendColumn(QueryColumnInfo& columnInfo, bool ascending = true);
/*! Appends a field \a field. Ascending sorting is set is \a ascending is true.
Read documentation of \ref OrderByColumn(const Field& field, bool ascending = true)
for more info. */
void appendField(Field& field, bool ascending = true);
/*! Appends field with a name \a field. Ascending sorting is set is \a ascending is true.
\return true on successful appending, and false if there is no such field or alias
name in the \a querySchema. */
bool appendField(QuerySchema& querySchema, const QString& fieldName,
bool ascending = true);
/*! Appends a column that is at position \a pos (counted from 0).
\return true on successful adding and false if there is no such position \a pos. */
bool appendColumn(QuerySchema& querySchema, bool ascending = true, int pos = -1);
/*! \return true if the list is empty. */
bool isEmpty() const {
return OrderByColumnListBase::isEmpty();
}
/*! \return number of elements of the list. */
uint count() const {
return OrderByColumnListBase::count();
}
/*! Removes all elements from the list (deletes them). */
void clear();
iterator begin() {
return OrderByColumnListBase::begin();
}
iterator end() {
return OrderByColumnListBase::end();
}
const_iterator constBegin() const {
return OrderByColumnListBase::constBegin();
}
const_iterator constEnd() const {
return OrderByColumnListBase::constEnd();
}
/*! \return string for debugging purposes. */
QString debugString() const;
/*! \return a string like "name ASC, 2 DESC" usable for building a SQL statement.
If \a includeTableNames is true (the default) fields are output in a form
of "tablename.fieldname".
\a drv and \a identifierEscaping are used for escaping the table and field identifiers. */
QString toSQLString(bool includeTableNames = true,
const Driver *drv = 0, int identifierEscaping = Driver::EscapeDriver | Driver::EscapeAsNecessary) const;
};
//! @short KexiDB::QuerySchema provides information about database query
/*! The query that can be executed using KexiDB-compatible SQL database engine
or used as an introspection tool. KexiDB parser builds QuerySchema objects
by parsing SQL statements. */
class CALLIGRADB_EXPORT QuerySchema : public FieldList, public SchemaData
{
public:
/*! Creates empty query object (without columns). */
QuerySchema();
/*! Creates query schema object that is equivalent to "SELECT * FROM table"
sql command. Schema of \a table is used to contruct this query --
it is defined by just adding all the fields to the query in natural order.
To avoid problems (e.g. with fields added outside of Kexi using ALTER TABLE)
we do not use "all-tables query asterisk" (see QueryAsterisk) item to achieve
this effect.
Properties such as the name and caption of the query are inherited
from table schema.
We consider that query schema based on \a table is not (a least yet) stored
in a system table, so query connection is set to NULL
(even if \a tableSchema's connection is not NULL).
Id of the created query is set to 0. */
explicit QuerySchema(TableSchema& tableSchema);
/*! Copy constructor. Creates deep copy of \a querySchema.
QueryAsterisk objects are deeply copied while only pointers to Field objects are copied. */
QuerySchema(const QuerySchema& querySchema);
virtual ~QuerySchema();
/*! Inserts \a field to the columns list at \a position.
Inserted field will not be owned by this QuerySchema object,
but still by corresponding TableSchema.
As \a field object you can also pass KexiDB::QueryAsterisk,
(see QueryAsterisk class description).
Note: After inserting a field, corresponding table will be automatically
added to query's tables list if it is not present there (see tables()).
Field must have its table assigned.
Added field will be visible. Use insertField(position, field, false)
to add invisible field.
*/
virtual FieldList& insertField(uint position, Field *field);
/* Like above method, but you can also set column's visibility.
New column is not bound explicitly to any table.
*/
FieldList& insertField(uint position, Field *field, bool visible);
/* Like above method, but you can also explicitly bound the new column
to specific position on tables list.
If \a visible is true (the default), the field will be visible.
If bindToTable==-1, no particular table should be bound.
@see tableBoundToColumn(uint columnPosition) */
FieldList& insertField(uint position, Field *field,
int bindToTable, bool visible = true);
/*! Adds \a field to the columns list.
If \a visible is true (the default), the field will be visible.
\sa insertField() */
FieldList& addField(Field* field, bool visible = true);
/*! Adds \a field to the columns list. Also binds to a table
at \a bindToTable position. Use bindToTable==-1 if no table should be bound.
If \a visible is true (the default), the field will be visible.
\sa insertField()
\sa tableBoundToColumn(uint columnPosition)
*/
FieldList& addField(Field* field, int bindToTable,
bool visible = true);
/*! Removes field from the columns list. Use with care. */
virtual bool removeField(Field *field);
/*! Adds a field built on top of \a expr expression.
This creates a new Field object and adds it to the query schema using addField(). */
FieldList& addExpression(BaseExpr* expr, bool visible = true);
/*! \return visibility flag for column at \a position.
By default column is visible. */
bool isColumnVisible(uint position) const;
//! Sets visibility flag for column at \a position to \a v.
void setColumnVisible(uint position, bool v);
/*! Adds \a asterisk at the and of columns list. */
FieldList& addAsterisk(QueryAsterisk *asterisk, bool visible = true);
/*! Removes all columns and their aliases from the columns list,
removes all tables and their aliases from the tables list within this query.
Sets master table information to NULL.
Does not destroy any objects though. Clears name and all other properties.
\sa FieldList::clear() */
virtual void clear();
/*! \return string for debugging purposes. */
virtual QString debugString() const;
/*! If query was created using a connection,
returns this connection object, otherwise NULL. */
Connection* connection() const;
/*! \return table that is master to this query.
All potentially-editable columns within this query belong just to this table.
This method also can return NULL if there are no tables at all,
or if previously assigned master table schema has been removed
with removeTable().
Every query that has at least one table defined, should have
assigned a master table.
If no master table is assigned explicitly but this method there is only
one table used for this query even if there are table aliases,
a single table is returned here.
(e.g. "T" table is returned for "SELECT T1.A, T2.B FROM T T1, T T2" statement). */
TableSchema* masterTable() const;
/*! Sets master table of this query to \a table.
This table should be also added to query's tables list
using addTable(). If \a table equals NULL, nothing is performed.
\sa masterTable() */
void setMasterTable(TableSchema *table);
/*! \return list of tables used in a query.
This also includes master table.
\sa masterTable() */
TableSchema::List* tables() const;
/*! Adds \a table schema as one of tables used in a query.
if \a alias is not empty, it will be assigned to this table
using setTableAlias(position, alias)
*/
void addTable(TableSchema *table, const QByteArray& alias = QByteArray());
/*! Removes \a table schema from this query.
This does not destroy \a table object but only takes it out of the list.
If this table was master for the query, master table information is also
invalidated. */
void removeTable(TableSchema *table);
/*! \return table with name \a tableName or 0 if this query has no such table. */
TableSchema* table(const QString& tableName) const;
/*! \return true if the query uses \a table. */
bool contains(TableSchema *table) const;
/*! Convenience function.
\return table field by searching through all tables in this query.
The field does not need to be included on the list of query columns.
Similarly, query aliases are not taken into account.
\a tableOrTableAndFieldName string may contain table name and field name
with '.' character between them, e.g. "mytable.myfield".
This is recommended way to avoid ambiguity.
0 is returned if the query has no such
table defined of the table has no such field defined.
If you do not provide a table name, the first field found is returned.
QuerySchema::table("mytable")->field("myfield") could be
alternative for findTableField("mytable.myfield") but it can crash
if "mytable" is not defined in the query.
@see KexiDB::splitToTableAndFieldParts()
*/
Field* findTableField(const QString &tableOrTableAndFieldName) const;
/*! \return alias of a column at \a position or null string
If there is no alias for this column
or if there is no such column within the query defined.
If the column is an expression and has no alias defined,
a new unique alias will be generated automatically on this call.
*/
QByteArray columnAlias(uint position) const;
/*! Provided for convenience.
\return true if a column at \a position has non empty alias defined
within the query.
If there is no alias for this column,
or if there is no such column in the query defined, false is returned. */
bool hasColumnAlias(uint position) const;
/*! Sets \a alias for a column at \a position, within the query.
Passing empty string to \a alias clears alias for a given column. */
void setColumnAlias(uint position, const QByteArray& alias);
/*! \return a table position (within FROM section),
that is bound to column at \a columnPosition (within SELECT section).
This information can be used to find if there is alias defined for
a table that is referenced by a given column.
For example, for "SELECT t2.id FROM table1 t1, table2 t2" query statement,
columnBoundToTable(0) returns 1, what means that table at position 1
(within FROM section) is bound to column at position 0, so we can
now call tableAlias(1) to see if we have used alias for this column (t2.d)
or just a table name (table2.d).
These checkings are performed e.g. by Connection::queryStatement()
to construct a statement string maximally identical to originally
defined query statement.
-1 is returned if:
- \a columnPosition is out of range (i.e. < 0 or >= fieldCount())
- a column at \a columnPosition is not bound to any table (i.e.
no database field is used for this column,
e.g. "1" constant for "SELECT 1 from table" query statement)
*/
int tableBoundToColumn(uint columnPosition) const;
/*! \return alias of a table at \a position (within FROM section)
or null string if there is no alias for this table
or if there is no such table within the query defined. */
QByteArray tableAlias(uint position) const;
/*! \return table position (within FROM section) that has attached
alias \a name.
If there is no such alias, -1 is returned.
Only first table's position attached for this alias is returned.
It is not especially bad, since aliases rarely can be duplicated,
what leads to ambiguity.
Duplicated aliases are only allowed for trivial queries that have
no database fields used within their columns,
e.g. "SELECT 1 from table1 t, table2 t" is ok
but "SELECT t.id from table1 t, table2 t" is not.
*/
int tablePositionForAlias(const QByteArray& name) const;
/*! \return table position (within FROM section) for \a tableName.
-1 is returend if there's no such table declared in the FROM section.
\sa tablePositions()
*/
int tablePosition(const QString& tableName) const;
/*! \return a list of all \a tableName table occurrences (within FROM section).
E.g. for "SELECT * FROM table t, table t2" [0, 1] list is returned.
Empty list is returned there's no such table declared
in the FROM section at all.
\sa tablePosition()
*/
QList<int> tablePositions(const QString& tableName) const;
/*! Provided for convenience.
\return true if a table at \a position (within FROM section of the query)
has non empty alias defined.
If there is no alias for this table,
or if there is no such table in the query defined, false is returned. */
bool hasTableAlias(uint position) const;
/*! \return column position that has defined alias \a name.
If there is no such alias, -1 is returned. */
int columnPositionForAlias(const QByteArray& name) const;
/*! Sets \a alias for a table at \a position (within FROM section
of the query).
Passing empty sting to \a alias clears alias for a given table
(only for specified \a position). */
void setTableAlias(uint position, const QByteArray& alias);
/*! \return a list of relationships defined for this query */
Relationship::List* relationships() const;
/*! Adds a new relationship defined by \a field1 and \a field2.
Both fields should belong to two different tables of this query.
This is convenience function useful for a typical cases.
It automatically creates Relationship object for this query.
If one of the fields are primary keys, it will be detected
and appropriate master-detail relation will be established.
This functiuon does nothing if the arguments are invalid. */
Relationship* addRelationship(Field *field1, Field *field2);
/*! \return list of QueryAsterisk objects defined for this query */
Field::List* asterisks() const;
/*! \return field for \a identifier or 0 if no field for this name
was found within the query. fieldsExpanded() method is used
to lookup expanded list of the query fields, so queries with asterisks
are processed well.
If a field has alias defined, name is not taken into account,
but only its alias. If a field has no alias:
- field's name is checked
- field's table and field's name are checked in a form of "tablename.fieldname",
so you can provide \a identifier in this form to avoid ambiguity.
If there are more than one fields with the same name equal to \a identifier,
first-found is returned (checking is performed from first to last query field).
Structures needed to compute result of this method are cached,
so only first usage costs o(n) - another usages cost o(1).
Example:
Let query be defined by "SELECT T.B AS X, T.* FROM T" statement and let T
be table containing fields A, B, C.
Expanded list of columns for the query is: T.B AS X, T.A, T.B, T.C.
- Calling field("B") will return a pointer to third query column (not the first,
because it is covered by "X" alias). Additionally, calling field("X")
will return the same pointer.
- Calling field("T.A") will return the same pointer as field("A").
*/
virtual Field* field(const QString& name, bool expanded);
/*! This is overloaded method Field* field(const QString& name, bool expanded)
with expanded = true. This method is also a product of inheritance from FieldList. */
inline virtual Field* field(const QString& name) {
return field(name, true);
}
/*! \return field id or NULL if there is no such a field. */
inline Field* field(uint id) {
return FieldList::field(id);
}
/*! Like QuerySchema::field(const QString& name) but returns not only Field
object for \a identifier but entire QueryColumnInfo object.
\a identifier can be:
- a fieldname
- an aliasname
- a tablename.fieldname
- a tablename.aliasname
Note that if there are two occurrrences of the same name,
only the first is accessible using this method. For instance,
calling columnInfo("name") for "SELECT t1.name, t2.name FROM t1, t2" statement
will only return the column related to t1.name and not t2.name, so you'll need to
explicitly specify "t2.name" as the identifier to get the second column. */
QueryColumnInfo* columnInfo(const QString& identifier, bool expanded = true);
/*! Options used in fieldsExpanded(). */
enum FieldsExpandedOptions {
Default, //!< All fields are returned even if duplicated
Unique, //!< Unique list of fields is returned
WithInternalFields, //!< Like Default but internal fields (for lookup) are appended
WithInternalFieldsAndRowID //!< Like WithInternalFields but RowID (big int type) field
//!< is appended after internal fields
};
/*! \return fully expanded list of fields.
QuerySchema::fields() returns vector of fields used for the query columns,
but in a case when there are asterisks defined for the query,
it does not expand QueryAsterisk objects to field lists but return every
asterisk as-is.
This could be inconvenient when you need just a fully expanded list of fields,
so this method does the work for you.
If \a options is Unique, each field is returned in the vector only once
(first found field is selected).
Note however, that the same field can be returned more than once if it has attached
a different alias.
For example, let t be TABLE( a, b ) and let query be defined
by "SELECT *, a AS alfa FROM t" statement. Both fieldsExpanded(Default)
and fieldsExpanded(Unique) will return [ a, b, a (alfa) ] list.
On the other hand, for query defined by "SELECT *, a FROM t" statement,
fieldsExpanded(Default) will return [ a, b, a ] list while
fieldsExpanded(Unique) will return [ a, b ] list.
If \a options is WithInternalFields or WithInternalFieldsAndRowID,
additional internal fields are also appended to the vector.
If \a options is WithInternalFieldsAndRowID,
one fake BigInteger column is appended to make space for ROWID column used
by KexiDB::Cursor implementations. For example, let persons be TABLE( surname, city_id ),
let city_number reference cities.is in TABLE cities( id, name ) and let query q be defined
by "SELECT * FROM t" statement. If we want to display persons' city names instead of city_id's.
To do this, cities.name has to be retrieved as well, so the following statement should be used:
"SELECT * FROM persons, cities.name LEFT OUTER JOIN cities ON persons.city_id=cities.id".
Thus, calling fieldsExpanded(WithInternalFieldsAndRowID) will return 4 elements instead of 2:
persons.surname, persons.city_id, cities.name, {ROWID}. The {ROWID} item is the placeholder
used for fetching ROWID by KexiDB cursors.
By default, all fields are returned in the vector even
if there are multiple occurrences of one or more (options == Default).
Note: You should assign the resulted vector in your space - it will be shared
and implicity copied on any modification.
This method's result is cached by QuerySchema object.
@todo js: UPDATE CACHE!
*/
QueryColumnInfo::Vector fieldsExpanded(FieldsExpandedOptions options = Default);
/*! \return list of fields internal fields used for lookup columns. */
QueryColumnInfo::Vector internalFields();
/*! \return info for expanded of internal field at index \a index.
The returned field can be either logical or internal (for lookup),
the latter case is true if \a index >= fieldsExpanded().count().
Equivalent of QuerySchema::fieldsExpanded(WithInternalFields).at(index). */
QueryColumnInfo* expandedOrInternalField(uint index);
/*! Options used in columnsOrder(). */
enum ColumnsOrderOptions {
UnexpandedList, //!< A map for unexpanded list is created
UnexpandedListWithoutAsterisks, //!< A map for unexpanded list is created, with asterisks skipped
ExpandedList //!< A map for expanded list is created
};
/*! \return a hash for fast lookup of query columns' order.
- If \a options is UnexpandedList, each QueryColumnInfo pointer is mapped to the index
within (unexpanded) list of fields, i.e. "*" or "table.*" asterisks are considered
to be single items.
- If \a options is UnexpandedListWithoutAsterisks, each QueryColumnInfo pointer
is mapped to the index within (unexpanded) list of columns that come from asterisks
like "*" or "table.*" are not included in the map at all.
- If \a options is ExpandedList (the default) this method provides is exactly opposite
information compared to vector returned by fieldsExpanded().
This method's result is cached by the QuerySchema object.
Note: indices of internal fields (see internalFields()) are also returned
here - in this case the index is counted as a sum of size(e) + i (where "e" is
the list of expanded fields and i is the column index within internal fields list).
This feature is used eg. at the end of Connection::updateRow() where need indices of
fields (including internal) to update all the values in memory.
Example use: let t be table (int id, name text, surname text) and q be query
defined by a statement "select * from t".
- columnsOrder(ExpandedList) will return the following map: QueryColumnInfo(id)->0,
QueryColumnInfo(name)->1, QueryColumnInfo(surname)->2.
- columnsOrder(UnexpandedList) will return the following map: QueryColumnInfo(id)->0,
QueryColumnInfo(name)->0, QueryColumnInfo(surname)->0 because the column
list is not expanded. This way you can use the returned index to get Field*
pointer using field(uint) method of FieldList superclass.
- columnsOrder(UnexpandedListWithoutAsterisks) will return the following map:
QueryColumnInfo(id)->0,
*/
QHash<QueryColumnInfo*, int> columnsOrder(ColumnsOrderOptions options = ExpandedList);
/*! \return table describing order of primary key (PKEY) fields within the query.
Indexing is performed against vector returned by fieldsExpanded().
It is usable for e.g. Conenction::updateRow(), when we need
to locate each primary key's field in a constant time.
Returned vector is owned and cached by QuerySchema object. When you assign it,
it is implicity shared. Its size is equal to number of primary key
fields defined for master table (masterTable()->primaryKey()->fieldCount()).
Each element of the returned vector:
- can belong to [0..fieldsExpanded().count()-1] if there is such
primary key's field in the fieldsExpanded() list.
- can be equal to -1 if there is no such primary key's field
in the fieldsExpanded() list.
If there are more than one primary key's field included in the query,
only first-found column (oin the fieldsExpanded() list) for each pkey's field is included.
Returns empty vector if there is no master table or no master table's pkey.
@see example for pkeyFieldsCount().
@todo js: UPDATE CACHE!
*/
QVector<int> pkeyFieldsOrder();
/*! \return number of master table's primary key fields included in this query.
This method is useful to quickly check whether the vector returned by pkeyFieldsOrder()
if filled completely.
User e.g. in Connection::updateRow() to check if entire primary
key information is specified.
Examples: let table T has (ID1 INTEGER, ID2 INTEGER, A INTEGER) fields,
and let (ID1, ID2) is T's primary key.
-# The query defined by "SELECT * FROM T" statement contains all T's
primary key's fields as T is the master table, and thus pkeyFieldsCount()
will return 2 (both primary key's fields are in the fieldsExpanded() list),
and pkeyFieldsOrder() will return vector {0, 1}.
-# The query defined by "SELECT A, ID2 FROM T" statement, and thus pkeyFieldsCount()
will return 1 (only one primary key's field is in the fieldsExpanded() list),
and pkeyFieldsOrder() will return vector {-1, 1}, as second primary key's field
is at position #1 and first field is not specified at all within the query.
*/
uint pkeyFieldsCount();
/*! \return a list of field information for all auto-incremented fields
from master table of this query. This result is cached for efficiency.
fieldsExpanded() is used for that.
*/
QueryColumnInfo::List* autoIncrementFields();
/*! \return a preset statement (if any). */
QString statement() const;
/*! Forces a query statement (i.e. no statement is composed from QuerySchema's content) */
void setStatement(const QString &s);
/*! \return a string that is a result of concatenating all column names
for \a infolist, with "," between each one.
This is usable e.g. as argument like "field1,field2"
for "INSERT INTO (xxx) ..". The result of this method is effectively cached,
and it is invalidated when set of fields changes (e.g. using clear()
or addField()).
This method is similar to FieldList::sqlFieldsList() it just uses
QueryColumnInfo::List instead of Field::List.
*/
static QString sqlColumnsList(QueryColumnInfo::List* infolist, const Driver *driver);
/*! \return cached sql list created using sqlColumnsList() on a list returned
by autoIncrementFields(). */
QString autoIncrementSQLFieldsList(const Driver *driver);
/*! Sets a WHERE expression \a exp. It will be owned by this query,
so you can forget about it. Previously set WHERE expression will be deleted.
You can pass 0 to remove expresssion. */
void setWhereExpression(BaseExpr *expr);
/*! \return WHERE expression or 0 if this query has no WHERE expression */
BaseExpr *whereExpression() const;
/*! Adds a part to WHERE expression.
Simplifies creating of WHERE expression, if used instead
of setWhereExpression(BaseExpr *expr). */
void addToWhereExpression(KexiDB::Field *field, const QVariant& value, int relation = '=');
/*! Sets a list of columns for ORDER BY section of the query.
Each name on the list must be a field or alias present within the query
and must not be covered by aliases. If one or more names cannot be found
within the query, the method will have no effect.
Any previous ORDER BY settings will be removed.
Note that this information is cleared whenever you call methods that
modify list of columns (QueryColumnInfo), i.e. insertFiled(),
addField(), removeField(), addExpression(), etc.
(because OrderByColumn items can point to a QueryColumnInfo that's removed by these
methods), so you should use setOrderByColumnList() method after the query
is completely built. */
void setOrderByColumnList(const OrderByColumnList& list);
/*! \return a list of columns listed in ORDER BY section of the query.
Read notes for \ref setOrderByColumnList(). */
OrderByColumnList& orderByColumnList() const;
/*! \return query schema parameters. These are taked from the WHERE section
(a tree of expression items). */
QuerySchemaParameterList parameters();
protected:
void init();
void computeFieldsExpanded();
QuerySchemaPrivate * const d;
friend class Connection;
friend class QuerySchemaPrivate;
};
//! @short KexiDB::QueryAsterisk class encapsulates information about single asterisk in query definition
/*! There are two types of query asterisks:
1. "Single-table" asterisk, that references all fields of given table used
in the query.
Example SQL statement:
\code
SELECT staff.*, cars.model from staff, cars WHERE staff.car = cars.number;
\endcode
The "staff.*" element is our "single-table" asterisk;
this tells us that we want to get all fields of table "staff".
2. "All-tables" asterisk, that references all fields of all tables used in the query.
Example SQL statement:
\code
SELECT * from staff, cars WHERE staff.car = cars.number;
\endcode
The "*" is our "all-tables" asterisk;
this tells us that we want to get all fields of all used tables (here: "staff" and "cars").
There can be many asterisks of 1st type defined for given single query.
There can be one asterisk of 2nd type defined for given single query.
*/
class CALLIGRADB_EXPORT QueryAsterisk : public Field
{
public:
/*! Constructs query asterisk definition object.
Pass table schema to \a table if this asterisk should be
of type "single-table", otherwise (if you want to define
"all-tables" type asterisk), omit this parameter.
QueryAsterisk objects are owned by QuerySchema object
(not by TableSchema object like for ordinary Field objects)
for that the QueryAsterisk object was added (using QuerySchema::addField()).
*/
explicit QueryAsterisk(QuerySchema *query, TableSchema *table = 0);
QueryAsterisk(const QueryAsterisk& asterisk);
virtual ~QueryAsterisk();
/*! \return Query object for that this asterisk object is defined */
QuerySchema *query() const {
return static_cast<QuerySchema*>(m_parent);
}
/*! \return Table schema for this asterisk
if it has "single-table" type (1st type)
or NULL if it has "all-tables" type (2nd type) defined. */
virtual TableSchema* table() const {
return m_table;
}
/*! Sets table schema for this asterisk.
\a table may be NULL - then the asterisk becames "all-tables" type asterisk. */
virtual void setTable(TableSchema *table);
/*! This is convenience method that returns true
if the asterisk has "all-tables" type (2nd type).*/
bool isSingleTableAsterisk() const {
return m_table != NULL;
}
/*! This is convenience method that returns true
if the asterisk has "single-tables" type (2nd type).*/
bool isAllTableAsterisk() const {
return m_table == NULL;
}
/*! \return String for debugging purposes. */
virtual QString debugString() const;
protected:
//! \return a deep copy of this object. Used in FieldList(const FieldList& fl).
virtual Field* copy() const;
/*! Table schema for this asterisk */
TableSchema* m_table;
friend class QuerySchema;
};
} //namespace KexiDB
#endif
| abhishekmurthy/Calligra | libs/db/queryschema.h | C | gpl-2.0 | 39,898 |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add('resize', {
init:function (editor) {
var config = editor.config;
// Resize in the same direction of chrome,
// which is identical to dir of editor element. (#6614)
var resizeDir = editor.element.getDirection(1);
!config.resize_dir && ( config.resize_dir = 'both' );
( config.resize_maxWidth == undefined ) && ( config.resize_maxWidth = 3000 );
( config.resize_maxHeight == undefined ) && ( config.resize_maxHeight = 3000 );
( config.resize_minWidth == undefined ) && ( config.resize_minWidth = 750 );
( config.resize_minHeight == undefined ) && ( config.resize_minHeight = 250 );
if (config.resize_enabled !== false) {
var container = null, origin, startSize, resizeHorizontal = ( config.resize_dir == 'both' || config.resize_dir == 'horizontal' ) && ( config.resize_minWidth != config.resize_maxWidth ), resizeVertical = ( config.resize_dir == 'both' || config.resize_dir == 'vertical' ) && ( config.resize_minHeight != config.resize_maxHeight );
function dragHandler(evt) {
var dx = evt.data.$.screenX - origin.x, dy = evt.data.$.screenY - origin.y, width = startSize.width, height = startSize.height, internalWidth = width + dx * ( resizeDir == 'rtl' ? -1 : 1 ), internalHeight = height + dy;
if (resizeHorizontal) {
width = Math.max(config.resize_minWidth, Math.min(internalWidth, config.resize_maxWidth));
}
if (resizeVertical) {
height = Math.max(config.resize_minHeight, Math.min(internalHeight, config.resize_maxHeight));
}
editor.resize(width, height);
}
function dragEndHandler(evt) {
CKEDITOR.document.removeListener('mousemove', dragHandler);
CKEDITOR.document.removeListener('mouseup', dragEndHandler);
if (editor.document) {
editor.document.removeListener('mousemove', dragHandler);
editor.document.removeListener('mouseup', dragEndHandler);
}
}
var mouseDownFn = CKEDITOR.tools.addFunction(function ($event) {
if (!container) {
container = editor.getResizable();
}
startSize = { width:container.$.offsetWidth || 0, height:container.$.offsetHeight || 0 };
origin = { x:$event.screenX, y:$event.screenY };
config.resize_minWidth > startSize.width && ( config.resize_minWidth = startSize.width );
config.resize_minHeight > startSize.height && ( config.resize_minHeight = startSize.height );
CKEDITOR.document.on('mousemove', dragHandler);
CKEDITOR.document.on('mouseup', dragEndHandler);
if (editor.document) {
editor.document.on('mousemove', dragHandler);
editor.document.on('mouseup', dragEndHandler);
}
});
editor.on('destroy', function () {
CKEDITOR.tools.removeFunction(mouseDownFn);
});
editor.on('themeSpace', function (event) {
if (event.data.space == 'bottom') {
var direction = '';
if (resizeHorizontal && !resizeVertical) {
direction = ' cke_resizer_horizontal';
}
if (!resizeHorizontal && resizeVertical) {
direction = ' cke_resizer_vertical';
}
var resizerHtml = '<div' + ' class="cke_resizer' + direction + ' cke_resizer_' + resizeDir + '"' + ' title="' + CKEDITOR.tools.htmlEncode(editor.lang.resize) + '"' + ' onmousedown="CKEDITOR.tools.callFunction(' + mouseDownFn + ', event)"' + '></div>';
// Always sticks the corner of botttom space.
resizeDir == 'ltr' && direction == 'ltr' ? event.data.html += resizerHtml : event.data.html = resizerHtml + event.data.html;
}
}, editor, null, 100);
}
}
});
/**
* The minimum editor width, in pixels, when resizing the editor interface by using the resize handle.
* Note: It falls back to editor's actual width if it is smaller than the default value.
* @name CKEDITOR.config.resize_minWidth
* @type Number
* @default 750
* @example
* config.resize_minWidth = 500;
*/
/**
* The minimum editor height, in pixels, when resizing the editor interface by using the resize handle.
* Note: It falls back to editor's actual height if it is smaller than the default value.
* @name CKEDITOR.config.resize_minHeight
* @type Number
* @default 250
* @example
* config.resize_minHeight = 600;
*/
/**
* The maximum editor width, in pixels, when resizing the editor interface by using the resize handle.
* @name CKEDITOR.config.resize_maxWidth
* @type Number
* @default 3000
* @example
* config.resize_maxWidth = 750;
*/
/**
* The maximum editor height, in pixels, when resizing the editor interface by using the resize handle.
* @name CKEDITOR.config.resize_maxHeight
* @type Number
* @default 3000
* @example
* config.resize_maxHeight = 600;
*/
/**
* Whether to enable the resizing feature. If this feature is disabled, the resize handle will not be visible.
* @name CKEDITOR.config.resize_enabled
* @type Boolean
* @default true
* @example
* config.resize_enabled = false;
*/
/**
* The dimensions for which the editor resizing is enabled. Possible values
* are <code>both</code>, <code>vertical</code>, and <code>horizontal</code>.
* @name CKEDITOR.config.resize_dir
* @type String
* @default 'both'
* @since 3.3
* @example
* config.resize_dir = 'vertical';
*/
| xgrommx/svadba | sites/all/modules/ckeditor/ckeditor/_source/plugins/resize/plugin.js | JavaScript | gpl-2.0 | 5,661 |
<?php
/* @author Armande Bayanes
* */
class Custom_StoreCredit_Adminhtml_StorecreditController extends Mage_Adminhtml_Controller_Action {
protected function _initAction() {
$this->loadLayout()
->_setActiveMenu('storecredit/items')
->_addBreadcrumb(Mage::helper('adminhtml')->__('Items Manager'), Mage::helper('adminhtml')->__('Item Manager'));
return $this;
}
public function indexAction() {
$this->_initAction()
->renderLayout();
}
public function editAction() {
$id = $this->getRequest()->getParam('id');
$customer = Mage::getModel("customer/customer")->load($id);
if($customer->getId()) {
$storecredit = Mage::getModel('storecredit/storecredit')->getCollection();
$storecredit->getSelect()->where("customer_id = '" . $customer->getId() . "'");
$sc = $storecredit->toArray();
$sc = $sc['items'][0];
if(! empty($sc)) $customer->addData($sc);
Mage::register('storecredit_data', $customer);
$this->loadLayout();
$this->_setActiveMenu('storecredit/items');
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item Manager'), Mage::helper('adminhtml')->__('Item Manager'));
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item News'), Mage::helper('adminhtml')->__('Item News'));
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->_addContent($this->getLayout()->createBlock('storecredit/adminhtml_storecredit_edit'))
->_addLeft($this->getLayout()->createBlock('storecredit/adminhtml_storecredit_edit_tabs'));
$this->renderLayout();
}
}
public function newAction() {
$this->_forward('edit');
}
public function saveAction() {
$customer_id = (int) $this->getRequest()->getParam('id');
if(($data = $this->getRequest()->getPost()) && $customer_id > 0) {
/* 0 = Admin store
* 1 = Default store
* */
$store_id = Mage::app()->getStore()->getId();
$resource = Mage::getSingleton('core/resource');
$write = $resource->getConnection('core_write');
$read = $resource->getConnection('core_read');
$data['credit_value'] = (float) $data['credit_value'];
$sql = "SELECT storecredit_id FROM storecredit WHERE customer_id='" . $customer_id . "'";
if(! $read->fetchOne($sql)) $sql = "INSERT INTO storecredit SET store_id='" . $store_id . "',customer_id='" . $customer_id . "',credit_earned='" . $data['credit_value'] . "',credit_remaining='" . $data['credit_value'] . "',created_time=NOW()";
else $sql = "UPDATE storecredit SET credit_earned=credit_earned+" . $data['credit_value'] . ",credit_remaining=credit_remaining+" . $data['credit_value'] . ",update_time=NOW() WHERE customer_id='" . $customer_id . "'";
$write->query($sql);
$sql = "INSERT INTO storecredit_history(customer_id,credit,description,created) VALUES(:customer_id,:credit,:description,NOW())";
$binds = array(
'customer_id' => $customer_id,
'credit' => $data['credit_value'],
'description' => $data['credit_description']
); $write->query($sql, $binds);
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('storecredit')->__('Item was successfully saved'));
Mage::getSingleton('adminhtml/session')->setFormData(false);
if($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', array('id' => $customer_id));
return;
}
$this->_redirect('*/*/');
return;
}
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('storecredit')->__('Unable to find item to save'));
$this->_redirect('*/*/');
}
public function massDeleteAction() {
$storecreditsIds = $this->getRequest()->getParam('storecredit');
if(! is_array($storecreditsIds)) {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select item(s)'));
} else {
try {
foreach ($storecreditsIds as $storecreditsId) {
$storecredits = Mage::getModel('storecredit/storecredit')->load($storecreditsId);
$storecredits->delete();
}
Mage::getSingleton('adminhtml/session')->addSuccess(
Mage::helper('adminhtml')->__(
'Total of %d record(s) were successfully deleted', count($storecreditsIds)
)
);
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
}
}
$this->_redirect('*/*/index');
}
public function massStatusAction() {
$storecreditsIds = $this->getRequest()->getParam('storecredit');
if(! is_array($storecreditsIds)) {
Mage::getSingleton('adminhtml/session')->addError($this->__('Please select item(s)'));
} else {
try {
foreach ($storecreditsIds as $storecreditsId) {
$storecredits = Mage::getSingleton('storecredit/storecredit')
->load($storecreditsId)
->setStatus($this->getRequest()->getParam('status'))
->setIsMassupdate(true)
->save();
}
$this->_getSession()->addSuccess(
$this->__('Total of %d record(s) were successfully updated', count($storecreditsIds))
);
} catch (Exception $e) {
$this->_getSession()->addError($e->getMessage());
}
}
$this->_redirect('*/*/index');
}
public function exportCsvAction() {
$fileName = 'storecredits.csv';
$content = $this->getLayout()->createBlock('storecredit/adminhtml_storecredit_grid')
->getCsv();
$this->_sendUploadResponse($fileName, $content);
}
public function exportXmlAction() {
$fileName = 'storecredit.xml';
$content = $this->getLayout()->createBlock('storecredit/adminhtml_storecredit_grid')
->getXml();
$this->_sendUploadResponse($fileName, $content);
}
protected function _sendUploadResponse($fileName, $content, $contentType='application/octet-stream') {
$response = $this->getResponse();
$response->setHeader('HTTP/1.1 200 OK','');
$response->setHeader('Pragma', 'public', true);
$response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true);
$response->setHeader('Content-Disposition', 'attachment; filename='.$fileName);
$response->setHeader('Last-Modified', date('r'));
$response->setHeader('Accept-Ranges', 'bytes');
$response->setHeader('Content-Length', strlen($content));
$response->setHeader('Content-type', $contentType);
$response->setBody($content);
$response->sendResponse();
die;
}
} | R-MAN-D/magento-custom-discount-store-credit-module | app/code/local/Custom/StoreCredit/controllers/Adminhtml/StorecreditController.php | PHP | gpl-2.0 | 7,341 |
#ifndef __XFS_ARCH_H__
#define __XFS_ARCH_H__
#ifndef XFS_BIG_INUMS
# error XFS_BIG_INUMS must be defined true or false
#endif
#ifdef __KERNEL__
#include <asm/byteorder.h>
#ifdef __BIG_ENDIAN
#define XFS_NATIVE_HOST 1
#else
#undef XFS_NATIVE_HOST
#endif
#else /* __KERNEL__ */
#if __BYTE_ORDER == __BIG_ENDIAN
#define XFS_NATIVE_HOST 1
#else
#undef XFS_NATIVE_HOST
#endif
#ifdef XFS_NATIVE_HOST
#define cpu_to_be16(val) ((__force __be16)(__u16)(val))
#define cpu_to_be32(val) ((__force __be32)(__u32)(val))
#define cpu_to_be64(val) ((__force __be64)(__u64)(val))
#define be16_to_cpu(val) ((__force __u16)(__be16)(val))
#define be32_to_cpu(val) ((__force __u32)(__be32)(val))
#define be64_to_cpu(val) ((__force __u64)(__be64)(val))
#else
#define cpu_to_be16(val) ((__force __be16)__swab16((__u16)(val)))
#define cpu_to_be32(val) ((__force __be32)__swab32((__u32)(val)))
#define cpu_to_be64(val) ((__force __be64)__swab64((__u64)(val)))
#define be16_to_cpu(val) (__swab16((__force __u16)(__be16)(val)))
#define be32_to_cpu(val) (__swab32((__force __u32)(__be32)(val)))
#define be64_to_cpu(val) (__swab64((__force __u64)(__be64)(val)))
#endif
static inline void be16_add_cpu(__be16 *a, __s16 b)
{
*a = cpu_to_be16(be16_to_cpu(*a) + b);
}
static inline void be32_add_cpu(__be32 *a, __s32 b)
{
*a = cpu_to_be32(be32_to_cpu(*a) + b);
}
static inline void be64_add_cpu(__be64 *a, __s64 b)
{
*a = cpu_to_be64(be64_to_cpu(*a) + b);
}
#endif /* __KERNEL__ */
#define INT_GET_UNALIGNED_16_BE(pointer) \
((__u16)((((__u8*)(pointer))[0] << 8) | (((__u8*)(pointer))[1])))
#define INT_SET_UNALIGNED_16_BE(pointer,value) \
{ \
((__u8*)(pointer))[0] = (((value) >> 8) & 0xff); \
((__u8*)(pointer))[1] = (((value) ) & 0xff); \
}
#define XFS_GET_DIR_INO4(di) \
(((__u32)(di).i[0] << 24) | ((di).i[1] << 16) | ((di).i[2] << 8) | ((di).i[3]))
#define XFS_PUT_DIR_INO4(from, di) \
do { \
(di).i[0] = (((from) & 0xff000000ULL) >> 24); \
(di).i[1] = (((from) & 0x00ff0000ULL) >> 16); \
(di).i[2] = (((from) & 0x0000ff00ULL) >> 8); \
(di).i[3] = ((from) & 0x000000ffULL); \
} while (0)
#define XFS_DI_HI(di) \
(((__u32)(di).i[1] << 16) | ((di).i[2] << 8) | ((di).i[3]))
#define XFS_DI_LO(di) \
(((__u32)(di).i[4] << 24) | ((di).i[5] << 16) | ((di).i[6] << 8) | ((di).i[7]))
#define XFS_GET_DIR_INO8(di) \
(((xfs_ino_t)XFS_DI_LO(di) & 0xffffffffULL) | \
((xfs_ino_t)XFS_DI_HI(di) << 32))
#define XFS_PUT_DIR_INO8(from, di) \
do { \
(di).i[0] = 0; \
(di).i[1] = (((from) & 0x00ff000000000000ULL) >> 48); \
(di).i[2] = (((from) & 0x0000ff0000000000ULL) >> 40); \
(di).i[3] = (((from) & 0x000000ff00000000ULL) >> 32); \
(di).i[4] = (((from) & 0x00000000ff000000ULL) >> 24); \
(di).i[5] = (((from) & 0x0000000000ff0000ULL) >> 16); \
(di).i[6] = (((from) & 0x000000000000ff00ULL) >> 8); \
(di).i[7] = ((from) & 0x00000000000000ffULL); \
} while (0)
#endif /* __XFS_ARCH_H__ */
| luckasfb/OT_903D-kernel-2.6.35.7 | kernel/fs/xfs/xfs_arch.h | C | gpl-2.0 | 2,913 |
# /////////////////////////////////////////////////////////////////////
# This file is a part of the BSTools package
# written by Przemyslaw Kiciak
# /////////////////////////////////////////////////////////////////////
# (C) Copyright by Przemyslaw Kiciak, 2005, 2014
# this package is distributed under the terms of the
# Lesser GNU Public License, see the file COPYING.LIB
# /////////////////////////////////////////////////////////////////////
HOME = /home/przemek
SRCDIR = .
INCDIR = ../../include
LIBDIR = ../../lib
include ../../options.mak
INCLUDES = $(INCDIR)/pkvaria.h $(INCDIR)/pkvthreads.h \
$(INCDIR)/pkgeom.h $(INCDIR)/pkgeomf.h $(INCDIR)/pkgeomd.h \
$(INCDIR)/multibs.h $(INCDIR)/multibsf.h $(INCDIR)/multibsd.h \
$(INCDIR)/raybez.h $(INCDIR)/raybezf.h $(INCDIR)/raybezd.h \
$(SRCDIR)/raybezprivatef.h $(SRCDIR)/raybezprivated.h \
$(SRCDIR)/raybezprivate.h
OBJECTS = rayboxf.o rayrboxf.o raybezptreef.o raybezf.o \
rayrbezptreef.o rayrbezf.o raybezctreef.o \
raybezcoffsetf.o rayrbezcoffsetf.o rayrbezctreef.o rayboxtestf.o \
rayboxd.o rayrboxd.o raybezptreed.o raybezd.o \
rayrbezptreed.o rayrbezd.o raybezctreed.o \
raybezcoffsetd.o rayrbezcoffsetd.o rayrbezctreed.o rayboxtestd.o \
raypthreads.o rbezintersf.o rbezintersd.o \
raybezconvhtest2f.o raybezconvhtest2d.o \
rbshomotopyf.o rbshomotopyd.o \
raybezphpointsf.o raybezphpointsd.o \
raybezconvhtest1f.o raybezconvhtest1d.o \
raybezchpointsf.o raybezchpointsd.o \
rayrbezchpointsf.o rayrbezchpointsd.o \
rayrbezphpointsf.o rayrbezphpointsd.o
TARGET = $(LIBDIR)/libraybez.a
default: $(TARGET)
$(TARGET): $(OBJECTS)
$(AR) $(ARFLAGS) $(TARGET) $(OBJECTS)
.c.o:
$(CC) $(CFLAGS) -I$(INCDIR) -c $< -o $*.o
raypthreads.o: raypthreads.c $(INCLUDES)
raybezchpointsf.o: raybezchpointsf.c $(INCLUDES)
raybezcoffsetf.o: raybezcoffsetf.c $(INCLUDES)
raybezconvhtest1f.o: raybezconvhtest1f.c $(INCLUDES)
raybezconvhtest2f.o: raybezconvhtest2f.c $(INCLUDES)
raybezctreef.o: raybezctreef.c $(INCLUDES)
raybezf.o: raybezf.c $(INCLUDES)
raybezphpointsf.o: raybezphpointsf.c $(INCLUDES)
raybezptreef.o: raybezptreef.c $(INCLUDES)
rayboxf.o: rayboxf.c $(INCLUDES)
rayboxtestf.o: rayboxtestf.c $(INCLUDES)
rayrbezchpointsf.o: rayrbezchpointsf.c $(INCLUDES)
rayrbezcoffsetf.o: rayrbezcoffsetf.c $(INCLUDES)
rayrbezctreef.o: rayrbezctreef.c $(INCLUDES)
rayrbezf.o: rayrbezf.c $(INCLUDES)
rayrbezphpointsf.o: rayrbezphpointsf.c $(INCLUDES)
rayrbezptreef.o: rayrbezptreef.c $(INCLUDES)
rayrboxf.o: rayrboxf.c $(INCLUDES)
rbezintersf.o: rbezintersf.c $(INCLUDES)
rbshomotopyf.o: rbshomotopyf.c $(INCLUDES)
raybezchpointsd.o: raybezchpointsd.c $(INCLUDES)
raybezcoffsetd.o: raybezcoffsetd.c $(INCLUDES)
raybezconvhtest1d.o: raybezconvhtest1d.c $(INCLUDES)
raybezconvhtest2d.o: raybezconvhtest2d.c $(INCLUDES)
raybezctreed.o: raybezctreed.c $(INCLUDES)
raybezd.o: raybezd.c $(INCLUDES)
raybezphpointsd.o: raybezphpointsd.c $(INCLUDES)
raybezptreed.o: raybezptreed.c $(INCLUDES)
rayboxd.o: rayboxd.c $(INCLUDES)
rayboxtestd.o: rayboxtestd.c $(INCLUDES)
rayrbezchpointsd.o: rayrbezchpointsd.c $(INCLUDES)
rayrbezcoffsetd.o: rayrbezcoffsetd.c $(INCLUDES)
rayrbezctreed.o: rayrbezctreed.c $(INCLUDES)
rayrbezd.o: rayrbezd.c $(INCLUDES)
rayrbezphpointsd.o: rayrbezphpointsd.c $(INCLUDES)
rayrbezptreed.o: rayrbezptreed.c $(INCLUDES)
rayrboxd.o: rayrboxd.c $(INCLUDES)
rbezintersd.o: rbezintersd.c $(INCLUDES)
rbshomotopyd.o: rbshomotopyd.c $(INCLUDES)
clean:
rm -f $(OBJECTS)
mrproper:
rm -f $(OBJECTS)
rm -f $(TARGET)
| radek-p/BSTools | src/raybez/Makefile | Makefile | gpl-2.0 | 3,513 |
-- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.controller.freifunk.freifunk", package.seeall)
function index()
local uci = require "luci.model.uci".cursor()
local page
-- Frontend
page = node("public")
page.title = _("Public")
page.target = alias("public", "freifunk")
page.order = 5
page.setuser = "nobody"
page.setgroup = "nogroup"
page.i18n = "public"
page.index = true
page = node("public", "freifunk")
page.title = _("Freifunk")
page.target = alias("public", "freifunk", "index")
page.order = 5
page.setuser = "nobody"
page.setgroup = "nogroup"
page.i18n = "freifunk"
page.index = true
page = node("public", "freifunk", "index")
page.target = template("freifunk/index")
page.title = _("Overview")
page.order = 10
page.indexignore = true
page = node("public", "freifunk", "contact")
page.target = template("freifunk/contact")
page.title = _("Contact")
page.order = 15
page = node("public", "freifunk", "status")
page.target = template("freifunk/public_status")
page.title = _("Status")
page.order = 20
page.i18n = "base"
page.setuser = false
page.setgroup = false
entry({"public", "freifunk", "status.json"}, call("jsonstatus"))
entry({"public", "freifunk", "status", "zeroes"}, call("zeroes"), "Testdownload")
if nixio.fs.access("/usr/sbin/luci-splash") then
assign({"public", "freifunk", "status", "splash"}, {"splash", "publicstatus"}, _("Splash"), 40)
end
-- backend
entry({"admin", "freifunk"}, alias("admin", "freifunk", "index"), _("Freifunk"), 5)
page = node("admin", "freifunk")
page.target = template("freifunk/adminindex")
page.title = _("Freifunk")
page.order = 5
page = node("admin", "freifunk", "basics")
page.target = cbi("freifunk/basics")
page.title = _("Basic Settings")
page.order = 5
page = node("admin", "freifunk", "basics", "profile")
page.target = cbi("freifunk/profile")
page.title = _("Profile")
page.order = 10
page = node("admin", "freifunk", "basics", "profile_expert")
page.target = form("freifunk/profile_expert")
page.title = _("Profile (Expert)")
page.order = 20
page = node("admin", "freifunk", "Index-Page")
page.target = cbi("freifunk/user_index")
page.title = _("Index Page")
page.order = 50
page = node("admin", "freifunk", "contact")
page.target = cbi("freifunk/contact")
page.title = _("Contact")
page.order = 15
entry({"admin", "freifunk", "profile_error"}, template("freifunk/profile_error"))
end
function zeroes()
local string = require "string"
local http = require "luci.http"
local zeroes = string.rep(string.char(0), 8192)
local cnt = 0
local lim = 1024 * 1024 * 1024
http.prepare_content("application/x-many-zeroes")
while cnt < lim do
http.write(zeroes)
cnt = cnt + #zeroes
end
end
function jsonstatus()
local root = {}
local sys = require "luci.sys"
local uci = require "luci.model.uci"
local util = require "luci.util"
local http = require "luci.http"
local json = require "luci.json"
local ltn12 = require "luci.ltn12"
local version = require "luci.version"
local webadmin = require "luci.tools.webadmin"
local cursor = uci.cursor_state()
local ffzone = webadmin.firewall_find_zone("freifunk")
local ffznet = ffzone and cursor:get("firewall", ffzone, "network")
local ffwifs = ffznet and util.split(ffznet, " ") or {}
local sysinfo = util.ubus("system", "info") or { }
local boardinfo = util.ubus("system", "board") or { }
local loads = sysinfo.load or { 0, 0, 0 }
local memory = sysinfo.memory or {
total = 0,
free = 0,
shared = 0,
buffered = 0
}
local swap = sysinfo.swap or {
total = 0,
free = 0
}
root.protocol = 1
root.system = {
uptime = { sysinfo.uptime or 0 },
loadavg = { loads[1] / 65535.0, loads[2] / 65535.0, loads[3] / 65535.0 },
sysinfo = {
boardinfo.system or "?",
boardinfo.model or "?",
memory.total,
0, -- former cached memory
memory.buffered,
memory.free,
0, -- former bogomips
swap.total,
0, -- former cached swap
swap.free
},
hostname = boardinfo.hostname
}
root.firmware = {
luciname=version.luciname,
luciversion=version.luciversion,
distname=version.distname,
distversion=version.distversion
}
root.freifunk = {}
cursor:foreach("freifunk", "public", function(s)
root.freifunk[s[".name"]] = s
end)
cursor:foreach("system", "system", function(s)
root.geo = {
latitude = s.latitude,
longitude = s.longitude
}
end)
root.network = {}
root.wireless = {devices = {}, interfaces = {}, status = {}}
local wifs = root.wireless.interfaces
for _, vif in ipairs(ffwifs) do
root.network[vif] = cursor:get_all("network", vif)
root.wireless.devices[vif] = cursor:get_all("wireless", vif)
cursor:foreach("wireless", "wifi-iface", function(s)
if s.device == vif and s.network == vif then
wifs[#wifs+1] = s
if s.ifname then
local iwinfo = luci.sys.wifi.getiwinfo(s.ifname)
if iwinfo then
root.wireless.status[s.ifname] = { }
local _, f
for _, f in ipairs({
"channel", "txpower", "bitrate", "signal", "noise",
"quality", "quality_max", "mode", "ssid", "bssid", "encryption", "ifname"
}) do
root.wireless.status[s.ifname][f] = iwinfo[f]
end
end
end
end
end)
end
http.prepare_content("application/json")
ltn12.pump.all(json.Encoder(root):source(), http.write)
end
| stargieg/luci2-ffwizard | luci-mod-freifunk/luasrc/controller/freifunk/freifunk.lua | Lua | gpl-2.0 | 5,574 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>LibOFX: OfxDummyContainer Class Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.4.6 -->
<div class="tabs">
<ul>
<li><a href="main.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li id="current"><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul></div>
<div class="tabs">
<ul>
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Data Fields</span></a></li>
</ul></div>
<h1>OfxDummyContainer Class Reference</h1><!-- doxytag: class="OfxDummyContainer" --><!-- doxytag: inherits="OfxGenericContainer,OfxGenericContainer" --><p>Inheritance diagram for OfxDummyContainer:
<p><center><img src="classOfxDummyContainer.png" usemap="#OfxDummyContainer_map" border="0" alt=""></center>
<map name="OfxDummyContainer_map">
<area href="classOfxGenericContainer.html" alt="OfxGenericContainer" shape="rect" coords="0,0,132,24">
<area href="classOfxGenericContainer.html" alt="OfxGenericContainer" shape="rect" coords="142,0,274,24">
</map>
<hr><a name="_details"></a><h2>Detailed Description</h2>
A container to holds OFX SGML elements that LibOFX knows nothing about.
<p>
The <a class="el" href="classOfxDummyContainer.html">OfxDummyContainer</a> is used for elements (not data elements) that are not recognised. Note that recognised objects may very well be a children of an <a class="el" href="classOfxDummyContainer.html">OfxDummyContainer</a>.
<p>
<p>
Definition at line <a class="el" href="ofx__containers_8hh-source.html#l00075">75</a> of file <a class="el" href="ofx__containers_8hh-source.html">ofx_containers.hh</a>.<table border="0" cellpadding="0" cellspacing="0">
<tr><td></td></tr>
<tr><td colspan="2"><br><h2>Public Member Functions</h2></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="26ed2ce0842ca533c80432080bb5d686"></a><!-- doxytag: member="OfxDummyContainer::OfxDummyContainer" ref="26ed2ce0842ca533c80432080bb5d686" args="(LibofxContext *p_libofx_context, OfxGenericContainer *para_parentcontainer, string para_tag_identifier)" -->
</td><td class="memItemRight" valign="bottom"><a class="el" href="classOfxDummyContainer.html#26ed2ce0842ca533c80432080bb5d686">OfxDummyContainer</a> (<a class="el" href="classLibofxContext.html">LibofxContext</a> *p_libofx_context, <a class="el" href="classOfxGenericContainer.html">OfxGenericContainer</a> *para_parentcontainer, string para_tag_identifier)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="classOfxDummyContainer.html#557663847ca8cf3d030d5d287bde4e02">add_attribute</a> (const string identifier, const string value)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Add data to a container object. <a href="#557663847ca8cf3d030d5d287bde4e02"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="26ed2ce0842ca533c80432080bb5d686"></a><!-- doxytag: member="OfxDummyContainer::OfxDummyContainer" ref="26ed2ce0842ca533c80432080bb5d686" args="(LibofxContext *p_libofx_context, OfxGenericContainer *para_parentcontainer, string para_tag_identifier)" -->
</td><td class="memItemRight" valign="bottom"><b>OfxDummyContainer</b> (<a class="el" href="classLibofxContext.html">LibofxContext</a> *p_libofx_context, <a class="el" href="classOfxGenericContainer.html">OfxGenericContainer</a> *para_parentcontainer, string para_tag_identifier)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="classOfxDummyContainer.html#557663847ca8cf3d030d5d287bde4e02">add_attribute</a> (const string identifier, const string value)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Add data to a container object. <a href="#557663847ca8cf3d030d5d287bde4e02"></a><br></td></tr>
</table>
<hr><h2>Member Function Documentation</h2>
<a class="anchor" name="557663847ca8cf3d030d5d287bde4e02"></a><!-- doxytag: member="OfxDummyContainer::add_attribute" ref="557663847ca8cf3d030d5d287bde4e02" args="(const string identifier, const string value)" --><p>
<table class="mdTable" cellpadding="2" cellspacing="0">
<tr>
<td class="mdRow">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="md" nowrap valign="top">void OfxDummyContainer::add_attribute </td>
<td class="md" valign="top">( </td>
<td class="md" nowrap valign="top">const string </td>
<td class="mdname" nowrap> <em>identifier</em>, </td>
</tr>
<tr>
<td class="md" nowrap align="right"></td>
<td class="md"></td>
<td class="md" nowrap>const string </td>
<td class="mdname" nowrap> <em>value</em></td>
</tr>
<tr>
<td class="md"></td>
<td class="md">) </td>
<td class="md" colspan="2"><code> [virtual]</code></td>
</tr>
</table>
</td>
</tr>
</table>
<table cellspacing="5" cellpadding="0" border="0">
<tr>
<td>
</td>
<td>
<p>
Add data to a container object.
<p>
Must be called once completed parsing an OFX SGML data element. The parent container should know what to do with it. <dl compact><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>identifier</em> </td><td>The name of the data element </td></tr>
<tr><td valign="top"></td><td valign="top"><em>value</em> </td><td>The concatenated string of the data </td></tr>
</table>
</dl>
<p>
Reimplemented from <a class="el" href="classOfxGenericContainer.html#e759f97dafd5f7cc55467d9b1de50159">OfxGenericContainer</a>. </td>
</tr>
</table>
<a class="anchor" name="557663847ca8cf3d030d5d287bde4e02"></a><!-- doxytag: member="OfxDummyContainer::add_attribute" ref="557663847ca8cf3d030d5d287bde4e02" args="(const string identifier, const string value)" --><p>
<table class="mdTable" cellpadding="2" cellspacing="0">
<tr>
<td class="mdRow">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="md" nowrap valign="top">void OfxDummyContainer::add_attribute </td>
<td class="md" valign="top">( </td>
<td class="md" nowrap valign="top">const string </td>
<td class="mdname" nowrap> <em>identifier</em>, </td>
</tr>
<tr>
<td class="md" nowrap align="right"></td>
<td class="md"></td>
<td class="md" nowrap>const string </td>
<td class="mdname" nowrap> <em>value</em></td>
</tr>
<tr>
<td class="md"></td>
<td class="md">) </td>
<td class="md" colspan="2"><code> [virtual]</code></td>
</tr>
</table>
</td>
</tr>
</table>
<table cellspacing="5" cellpadding="0" border="0">
<tr>
<td>
</td>
<td>
<p>
Add data to a container object.
<p>
Must be called once completed parsing an OFX SGML data element. The parent container should know what to do with it. <dl compact><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>identifier</em> </td><td>The name of the data element </td></tr>
<tr><td valign="top"></td><td valign="top"><em>value</em> </td><td>The concatenated string of the data </td></tr>
</table>
</dl>
<p>
Reimplemented from <a class="el" href="classOfxGenericContainer.html#e759f97dafd5f7cc55467d9b1de50159">OfxGenericContainer</a>.
<p>
Definition at line <a class="el" href="ofx__containers__misc_8cpp-source.html#l00047">47</a> of file <a class="el" href="ofx__containers__misc_8cpp-source.html">ofx_containers_misc.cpp</a>. </td>
</tr>
</table>
<hr>The documentation for this class was generated from the following files:<ul>
<li><a class="el" href="ofx__containers_8hh-source.html">ofx_containers.hh</a><li><a class="el" href="fx-0_88_82_2lib_2ofx__containers_8hh-source.html">fx-0.8.2/lib/ofx_containers.hh</a><li><a class="el" href="ofx__containers__misc_8cpp-source.html">ofx_containers_misc.cpp</a><li><a class="el" href="fx-0_88_82_2lib_2ofx__containers__misc_8cpp-source.html">fx-0.8.2/lib/ofx_containers_misc.cpp</a></ul>
<hr size="1"><address style="align: right;"><small>Generated on Fri Aug 25 13:25:23 2006 for LibOFX by
<a href="http://www.doxygen.org/index.html">
<img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.4.6 </small></address>
</body>
</html>
| tectronics/cashbox | libofx/libofx-0.8.2/doc/html/classOfxDummyContainer.html | HTML | gpl-2.0 | 9,187 |
package it.unibas.freesbee.ge.web.modello;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class Utente {
private Log logger = LogFactory.getLog(this.getClass());
private String nomeUtente = "admin";
private String password = "admin";
private String ruolo;
private boolean autenticato;
public static final String AMMINISTRATORE = "amministratore";
public static final String UTENTE_GENERICO = "utente_generico";
public String getNomeUtente() {
return nomeUtente;
}
public void setNomeUtente(String nomeUtente) {
this.nomeUtente = nomeUtente;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRuolo() {
return ruolo;
}
public void setRuolo(String ruolo) {
this.ruolo = ruolo;
}
public boolean isAutenticato() {
return autenticato;
}
public void setAutenticato(boolean autenticato) {
this.autenticato = autenticato;
}
public void verifica(String password){
String hashPasswordFornita = md5hash(password);
if (this.getPassword().equals(hashPasswordFornita)) {
this.setAutenticato(true);
} else {
this.setAutenticato(false);
}
}
public String md5hash(String password) {
String hashString = null;
try {
java.security.MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
byte[] hash = digest.digest(password.getBytes());
hashString = "";
for (int i = 0; i < hash.length; i++) {
hashString += Integer.toHexString(
(hash[i] & 0xFF) | 0x100
).toLowerCase().substring(1,3);
}
} catch (java.security.NoSuchAlgorithmException e) {
logger.error(e);
}
return hashString;
}
}
| donatellosantoro/freESBee | freesbeeWebGE/src/it/unibas/freesbee/ge/web/modello/Utente.java | Java | gpl-2.0 | 2,071 |
// -*- mode:objc -*-
// $Id: Tree.h,v 1.4 2008-09-18 18:03:05 yfabian Exp $
//
/*
** Tree.h
**
** Copyright (c) 2002-2004
**
** Author: Ujwal S. Setlur
**
** Project: iTerm
**
** Description: Headertree structure for bookmarks.
** Adapted from Apple's example code.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#import <Foundation/Foundation.h>
@interface NSArray (MyExtensions)
- (BOOL)containsObjectIdenticalTo: (id)object;
@end
@interface NSMutableArray (MyExtensions)
- (void) insertObjectsFromArray:(NSArray *)array atIndex:(int)index;
@end
@interface TreeNode : NSObject
{
TreeNode *nodeParent;
BOOL isLeaf;
NSMutableArray *nodeChildren;
NSMutableDictionary *nodeData;
}
+ (id) treeFromDictionary:(NSDictionary*)dict;
- (id) initWithData:(NSDictionary *)data parent:(TreeNode*)parent children:(NSArray*)children;
- (id) initFromDictionary:(NSDictionary*)dict;
- (NSDictionary *) dictionary;
- (void)setNodeData:(NSDictionary *)data;
- (NSDictionary *) nodeData;
- (void)setNodeParent:(TreeNode*)parent;
- (TreeNode*)nodeParent;
- (BOOL) isLeaf;
- (void) setIsLeaf: (BOOL) flag;
- (BOOL)isGroup;
- (void)insertChild:(TreeNode*)child atIndex:(int)index;
- (void)insertChildren:(NSArray*)children atIndex:(int)index;
- (void)removeChild:(TreeNode*)child;
- (void)removeFromParent;
- (int)indexOfChild:(TreeNode*)child;
- (int)indexOfChildIdenticalTo:(TreeNode*)child;
- (int)numberOfChildren;
- (NSArray*)children;
- (TreeNode*)firstChild;
- (TreeNode*)lastChild;
- (TreeNode*)childAtIndex:(int)index;
- (BOOL)isDescendantOfNode:(TreeNode*)node;
// returns YES if 'node' is an ancestor.
- (BOOL)isDescendantOfNodeInArray:(NSArray*)nodes;
// returns YES if any 'node' in the array 'nodes' is an ancestor of ours.
- (void)recursiveSortChildren;
// sort children using the compare: method in TreeNodeData
- (NSComparisonResult) compare: (id) comparator;
- (int) indexForNode: (id) node;
- (id) nodeForIndex: (int) index;
// Returns the minimum nodes from 'allNodes' required to cover the nodes in 'allNodes'.
// This methods returns an array containing nodes from 'allNodes' such that no node in
// the returned array has an ancestor in the returned array.
+ (NSArray *)minimumNodeCoverFromNodesInArray: (NSArray *)allNodes;
@end
| lewellyn/iTerm | Headers/iTerm/Tree.h | C | gpl-2.0 | 2,978 |
/*
* Copyright 1999,2000,2004 The Apache Software Foundation.
*
* 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 org.apache.wml;
/**
* <p>The interface is modeled after DOM1 Spec for HTML from W3C.
* The DTD used in this DOM model is from
* <a href="http://www.wapforum.org/DTD/wml_1.1.xml">
* http://www.wapforum.org/DTD/wml_1.1.xml</a></p>
*
* <p>'big' element renders the text with big font
* (Section 11.8.1, WAP WML Version 16-Jun-1999)</p>
*
* @version $Id: WMLBigElement.java,v 1.2 2004/02/24 23:34:05 mrglavas Exp $
* @author <a href="mailto:david@topware.com.tw">David Li</a>
*/
public interface WMLBigElement extends WMLElement {
/**
* 'xml:lang' specifics the natural or formal language in which
* the document is written.
* (Section 8.8, WAP WML Version 16-Jun-1999)
*/
public void setXmlLang(String newValue);
public String getXmlLang();
}
| BIORIMP/biorimp | BIO-RIMP/test_data/code/xerces/src/org/apache/wml/WMLBigElement.java | Java | gpl-2.0 | 1,426 |
import Globals
from Products.ZenModel.ZenPack import ZenPack as ZenPackBase
from Products.ZenUtils.Utils import unused, zenPath
import os
unused(Globals)
_plugins = [
'rig_host_app_transform1.py',
'copy_server_config_file.sh',
]
class ZenPack(ZenPackBase):
def install(self, app):
super(ZenPack, self).install(app)
self.symlink_plugins()
def symlink_plugins(self):
libexec = os.path.join(os.environ.get('ZENHOME'), 'libexec')
if not os.path.isdir(libexec):
# Stack installs might not have a \$ZENHOME/libexec directory.
os.mkdir(libexec)
# Now get the path to the file in the ZenPack's libexec directory
filepath = __file__ # Get path to this file
(zpdir, tail) = os.path.split(filepath)
zp_libexec_dir = os.path.join(zpdir,'libexec')
for plugin in _plugins:
plugin_path = zenPath('libexec', plugin)
zp_plugin_path = os.path.join(zp_libexec_dir, plugin)
#os.system('ln -sf "%s" "%s"' % (self.path(plugin), plugin_path))
os.system('ln -sf "%s" "%s"' % (zp_plugin_path, plugin_path))
os.system('chmod 0755 %s' % plugin_path)
def remove_plugin_symlinks(self):
for plugin in _plugins:
os.system('rm -f "%s"' % zenPath('libexec', plugin))
def remove(self, app, leaveObjects=False):
if not leaveObjects:
self.remove_plugin_symlinks()
super(ZenPack, self).remove(app, leaveObjects=leaveObjects)
| jcurry/ZenPacks.Markit.RigHost | ZenPacks/Markit/RigHost/__init__.py | Python | gpl-2.0 | 1,531 |
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>satellite_tools.sync_handlers.ChannelContainer</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<th class="navbar" width="100%"></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
<a href="satellite_tools-module.html">Package satellite_tools</a> ::
<a href="satellite_tools.sync_handlers-module.html">Module sync_handlers</a> ::
Class ChannelContainer
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="satellite_tools.sync_handlers.ChannelContainer-class.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<!-- ==================== CLASS DESCRIPTION ==================== -->
<h1 class="epydoc">Class ChannelContainer</h1><p class="nomargin-top"><span class="codelink"><a href="satellite_tools.sync_handlers-pysrc.html#ChannelContainer">source code</a></span></p>
<center>
</center>
<hr />
<!-- ==================== INSTANCE METHODS ==================== -->
<a name="section-InstanceMethods"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Instance Methods</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-InstanceMethods"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="satellite_tools.sync_handlers.ChannelContainer-class.html#endItemCallback" class="summary-sig-name">endItemCallback</a>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="satellite_tools.sync_handlers-pysrc.html#ChannelContainer.endItemCallback">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="satellite_tools.sync_handlers.ChannelContainer-class.html#endContainerCallback" class="summary-sig-name">endContainerCallback</a>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="satellite_tools.sync_handlers-pysrc.html#ChannelContainer.endContainerCallback">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code><a href="satellite_tools.xmlSource.ContainerHandler-class.html">xmlSource.ContainerHandler</a></code></b>:
<code><a href="satellite_tools.xmlSource.ContainerHandler-class.html#__init__">__init__</a></code>,
<code><a href="satellite_tools.xmlSource.ContainerHandler-class.html#characters">characters</a></code>,
<code><a href="satellite_tools.xmlSource.ContainerHandler-class.html#clearLastItem">clearLastItem</a></code>,
<code><a href="satellite_tools.xmlSource.ContainerHandler-class.html#endElement">endElement</a></code>,
<code><a href="satellite_tools.xmlSource.ContainerHandler-class.html#getLastItem">getLastItem</a></code>,
<code><a href="satellite_tools.xmlSource.ContainerHandler-class.html#postprocessItem">postprocessItem</a></code>,
<code><a href="satellite_tools.xmlSource.ContainerHandler-class.html#reset">reset</a></code>,
<code><a href="satellite_tools.xmlSource.ContainerHandler-class.html#startElement">startElement</a></code>
</p>
</td>
</tr>
</table>
<!-- ==================== CLASS VARIABLES ==================== -->
<a name="section-ClassVariables"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Class Variables</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-ClassVariables"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code><a href="satellite_tools.xmlSource.ChannelContainer-class.html">xmlSource.ChannelContainer</a></code></b>:
<code><a href="satellite_tools.xmlSource.ChannelContainer-class.html#container_name">container_name</a></code>
</p>
</td>
</tr>
</table>
<!-- ==================== METHOD DETAILS ==================== -->
<a name="section-MethodDetails"></a>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Method Details</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-MethodDetails"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
</table>
<a name="endItemCallback"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">endItemCallback</span>(<span class="sig-arg">self</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="satellite_tools.sync_handlers-pysrc.html#ChannelContainer.endItemCallback">source code</a></span>
</td>
</tr></table>
<dl class="fields">
<dt>Overrides:
<a href="satellite_tools.xmlSource.ContainerHandler-class.html#endItemCallback">xmlSource.ContainerHandler.endItemCallback</a>
</dt>
</dl>
</td></tr></table>
</div>
<a name="endContainerCallback"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">endContainerCallback</span>(<span class="sig-arg">self</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="satellite_tools.sync_handlers-pysrc.html#ChannelContainer.endContainerCallback">source code</a></span>
</td>
</tr></table>
<dl class="fields">
<dt>Overrides:
<a href="satellite_tools.xmlSource.ContainerHandler-class.html#endContainerCallback">xmlSource.ContainerHandler.endContainerCallback</a>
</dt>
</dl>
</td></tr></table>
</div>
<br />
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<th class="navbar" width="100%"></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0.1 on Tue Nov 2 13:02:50 2010
</td>
<td align="right" class="footer">
<a target="mainFrame" href="http://epydoc.sourceforge.net"
>http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
// -->
</script>
</body>
</html>
| colloquium/spacewalk | documentation/python-doc/satellite_tools.sync_handlers.ChannelContainer-class.html | HTML | gpl-2.0 | 10,364 |
** This project is no longer maintained as its being ported to C **
JGOOSE
======
JGOOSE is an open-source Java library (released under GPL version 2) for the manipulation of IEC-61850 based GOOSE (Ed1) traffic. Its design objectives are to demonstrate a proof-of-concept implementation of a portable, simple to use/extend, and, according to its initial motivation: useful in the context of GOOSE simulation and traffic dataset generation. JGOOSE is intended to provide a framework for GOOSE traffic generation using the JNETPCAP libraries.
JGOOSE is still under development and not intended for use in production systems
| kushfj/JGOOSE | README.md | Markdown | gpl-2.0 | 625 |
<?php
/*
View: houseCouponThisMonth
Columns:
card_no int
upc varchar
quantity float
Depends on:
dlog_90_view (view)
Use:
List of custom coupons redeemed, per member
*/
$CREATE['trans.houseCouponThisMonth'] = "
CREATE VIEW houseCouponThisMonth AS
SELECT card_no,upc,sum(quantity) as quantity FROM
dlog_90_view
WHERE upc LIKE '00499999%'
AND ".$con->monthdiff($con->now(),'tdate')."=0
GROUP BY card_no,upc
";
?>
| joelbrock/PFC_CORE | fannie/install/sql/trans/houseCouponThisMonth.php | PHP | gpl-2.0 | 425 |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace Logica
{
public class UltCbtesAutorizados
{
Datos.UltCbtesAutorizados objDatosUltNroCbtes = new Datos.UltCbtesAutorizados();
/// <summary>
/// Delega a la Capa de Datos Agregar un Ultimo Cbte Autorizado a la B.D.
/// </summary>
/// <param name="pUltNroCbte"></param>
public void Agregar(Entidades.UltCbtesAutorizados pUltNroCbte)
{
objDatosUltNroCbtes.Agregar(pUltNroCbte);
}
/// <summary>
/// Delega a la Capa de Datos devolver todos los Ulimos Nros de Cbtes de la B.D.
/// </summary>
/// <returns></returns>
public DataTable TraerTodos()
{
DataTable dt = new DataTable();
dt = objDatosUltNroCbtes.TraerTodos();
return dt;
}
/// <summary>
/// Delega a la Capa de Datos Borrar todos los Ultimos Nros de Cbtes a la B.D.
/// </summary>
public void BorrarTodos()
{
objDatosUltNroCbtes.BorrarTodos();
}
/// <summary>
/// Delega a la Capa de Datos devolver el Ulimo Nro de Cbte de la B.D.
/// </summary>
/// <returns>Ultimo Nro Cbte</returns>
public long TraerUltNro(int pPtoVenta, int pTipoCbte)
{
long UltNroCbte = 0;
UltNroCbte = objDatosUltNroCbtes.TraerUltNro(pPtoVenta, pTipoCbte);
return UltNroCbte;
}
}
}
| fedepazw/OpenReceArg | Logica/UltCbtesAutorizados.cs | C# | gpl-2.0 | 1,567 |
<?php
/**
* Custom functions that act independently of the theme templates
*
* Eventually, some of the functionality here could be replaced by core features
*/
/* ========================= Blog utils section ============================== */
/* PRE_QUERY - add filter to main query */
add_filter('posts_where', 'filter_where');
function filter_where($where = '') {
global $wpdb;
if (is_admin()) return $where;
// Disable posts with future date
$where .= " AND ({$wpdb->posts}.post_date <= '" . date('Y-m-d 23:59:59') . "' OR {$wpdb->posts}.post_date_gmt <= '" . date('Y-m-d 23:59:59') . "')";
return $where;
}
// Return template page id
function getTemplatePageId($type) {
if (!in_array($type, array('video', 'gallery'))) $type = 'blog';
$posts = getPostsByMetaValue('_wp_page_template', 'template-' . $type . '.php', ARRAY_A);
return count($posts)>0 ? $posts[0]['post_id'] : 0;
}
// Return any type categories objects by post id
function getCategoriesByPostId($post_id = 0, $cat_types = false) {
global $theme_post_types;
if (!$cat_types) {
$cat_types = array();
foreach ($theme_post_types as $type)
$cat_types[] = $type['category'];
}
return getTaxonomiesByPostId($post_id, $cat_types);
}
// Return tags objects by post id
function getTagsByPostId($post_id = 0) {
return getTaxonomiesByPostId($post_id, array('post_tag'));
}
// Return taxonomies objects by post id
function getTaxonomiesByPostId($post_id = 0, $tax_types = array('post_format')) {
global $wpdb, $wp_query;
if (!$post_id) $post_id = $wp_query->current_post>=0 ? get_the_ID() : $wp_query->post->ID;
$sql = "SELECT terms.*, tax.taxonomy, tax.parent, tax.count"
. " FROM $wpdb->term_relationships AS rel"
. " LEFT JOIN {$wpdb->term_taxonomy} AS tax ON rel.term_taxonomy_id=tax.term_taxonomy_id"
. " LEFT JOIN {$wpdb->terms} AS terms ON tax.term_id=terms.term_id"
. " WHERE rel.object_id = {$post_id}"
. " AND tax.taxonomy IN ('" . join("','", $tax_types) . "')";
$taxes = $wpdb->get_results($sql, ARRAY_A);
for ($i=0; $i<count($taxes); $i++) {
$taxes[$i]['link'] = get_term_link($taxes[$i]['slug'], $taxes[$i]['taxonomy']);
}
return $taxes;
}
// Return taxonomies objects by post type
function getTaxonomiesByPostType($post_types = array('post'), $tax_types = array('post_format')) {
global $wpdb, $wp_query;
if (!$post_types) $post_types = array('post');
$sql = "SELECT terms.*, tax.taxonomy, tax.parent, tax.count, posts.post_type"
. " FROM $wpdb->term_relationships AS rel"
. " LEFT JOIN {$wpdb->term_taxonomy} AS tax ON rel.term_taxonomy_id=tax.term_taxonomy_id"
. " LEFT JOIN {$wpdb->terms} AS terms ON tax.term_id=terms.term_id"
. " LEFT JOIN {$wpdb->posts} AS posts ON rel.object_id=posts.id"
. " WHERE posts.post_type IN ('" . join("','", $post_types) . "')"
. " AND tax.taxonomy IN ('" . join("','", $tax_types) . "')"
. " ORDER BY terms.name";
$taxes = $wpdb->get_results($sql, ARRAY_A);
$result = array();
$used = array();
$res_count = 0;
for ($i=0; $i<count($taxes); $i++) {
$link = get_term_link($taxes[$i]['slug'], $taxes[$i]['taxonomy']);
$k = $taxes[$i]['post_type'].$taxes[$i]['slug'];
$idx = isset($used[$k]) ? $used[$k] : -1;
if ($idx == -1) {
$used[$k] = $res_count;
$result[$res_count] = $taxes[$i];
$result[$res_count]['link'] = $link;
$result[$res_count]['count'] = 1;
$res_count++;
} else
$result[$idx]['count']++;
}
return $result;
}
// Return breadcrumbs path
function showBreadcrumbs($args=array()) {
global $wp_query;
$args = array_merge(array(
'home' => '', // Home page title (if empty - not showed)
'home_url' => '', // Home page url
'show_all_photo_video' => false, // Add "All photos" (All videos) before categories list
'show_all_posts' => false, // Add "All posts" at start
'truncate_title' => 0, // Truncate all titles to this length (if 0 - no truncate)
'truncate_add' => '...', // Append truncated title with this string
'echo' => true // If true - show on page, else - only return value
), is_array($args) ? $args : array( 'home' => $args ));
$rez = '';
$rez2 = '';
$all_link = $all_format = '';
$type = getBlogType();
$title = getShortString(getBlogTitle(), $args['truncate_title'], $args['truncate_add']);
$cat = '';
$parentTax = '';
if ( !in_array($type, array('home', 'frontpage')) ) {
$need_reset = true;
$parent = 0;
$post_id = 0;
if ($type == 'page' || $type == 'attachment') {
$pageParentID = isset($wp_query->post->post_parent) ? $wp_query->post->post_parent : 0;
$post_id = $type == 'page' ? (isset($wp_query->post->ID) ? $wp_query->post->ID : 0) : $pageParentID;
while ($pageParentID > 0) {
$pageParent = get_post($pageParentID);
$rez2 = '<li class="cat_post"><a href="' . get_permalink($pageParent->ID) . '">' . getShortString($pageParent->post_title, $args['truncate_title'], $args['truncate_add']) . '</a></li>' . $rez2;
if (($pageParentID = $pageParent->post_parent) > 0) $page_id = $pageParentID;
}
} else if ($type=='single')
$post_id = isset($wp_query->post->ID) ? $wp_query->post->ID : 0;
$depth = 0;
do {
if ($depth++ == 0) {
if (in_array($type, array('single', 'attachment'))) {
if ($args['show_all_photo_video']) {
$post_format = get_post_format($post_id);
if ($post_format == 'video' && ($video_id = getTemplatePageId($post_format)) > 0) {
$all_link = get_permalink($video_id);
$all_format = __('Videos', 'wpspace');
} else if ($post_format == 'gallery' && ($gallery_id = getTemplatePageId($post_format)) > 0) {
$all_link = get_permalink($gallery_id);
$all_format = __('Galleries', 'wpspace');
}
}
$cats = getCategoriesByPostId( $post_id );
$cat = $cats ? $cats[0] : false;
if ($cat) {
$cat_link = get_term_link($cat['slug'], $cat['taxonomy']);
$rez2 = '<li class="cat_post"><a href="' . $cat_link . '">' . getShortString($cat['name'], $args['truncate_title'], $args['truncate_add']) . '</a></li>' . $rez2;
} else {
$post_type = get_post_type($post_id);
$parentTax = 'category' . ($post_type == 'post' ? '' : '_' . $post_type);
}
} else if ( $type == 'category' ) {
$cat = get_term_by( 'id', get_query_var( 'cat' ), 'category', ARRAY_A);
} else if ( $type == 'resume' && get_query_var( 'category_resume' ) != '' ) {
$cat = get_term_by( 'slug', get_query_var( 'category_resume' ), 'category_resume', ARRAY_A);
} else if ( $type == 'portfolio' && get_query_var( 'category_portfolio' ) != '' ) {
$cat = get_term_by( 'slug', get_query_var( 'category_portfolio' ), 'category_portfolio', ARRAY_A);
}
if ($cat) {
$parent = $cat['parent'];
$parentTax = $cat['taxonomy'];
}
}
if ($parent) {
$cat = get_term_by( 'id', $parent, $parentTax, ARRAY_A);
if ($cat) {
$cat_link = get_term_link($cat['slug'], $cat['taxonomy']);
$rez2 = '<li class="cat_parent"><a href="' . $cat_link . '">' . getShortString($cat['name'], $args['truncate_title'], $args['truncate_add']) . '</a></li>' . $rez2;
$parent = $cat['parent'];
}
}
if (!$all_link && $args['show_all_posts'] && ($blog_id = getTemplatePageId($type)) > 0) {
$all_link = get_permalink($blog_id);
if ($type == 'resume' || $parentTax == 'category_resume') {
$all_format = __( 'Resume', 'wpspace');
$all_link .= (my_strpos($all_link, '?')===false ? '?' : '&').'rsm=1';
} else if ($type == 'portfolio' || $parentTax == 'category_portfolio') {
$all_format = __( 'Portfolio', 'wpspace');
$all_link .= (my_strpos($all_link, '?')===false ? '?' : '&').'prt=1';
} else {
$all_format = __( 'Posts', 'wpspace');
}
}
} while ($parent);
}
$rez .= '<ul class="breadcrumbs">'
. (isset($args['home']) && $args['home']!='' ? '<li class="home"><a href="' . ($args['home_url'] ? $args['home_url'] : home_url()) . '">' . $args['home'] . '</a></li>' : '')
. ($all_link && !in_array(my_strtolower($title), array('text', 'all portfolio', 'all resume')) ? '<li class="all"><a href="' . $all_link . '">' . sprintf( __( 'All %s', 'wpspace' ), $all_format ) . '</a></li>' : '' )
. $rez2
. ($title ? '<li class="current">' . $title . '</li>' : '')
. '</ul>';
if ($args['echo']) echo $rez;
return $rez;
}
// Return blog records type
function getBlogType($query=null) {
global $wp_query;
if ( $query===null ) $query = $wp_query;
$is_resume = isset($query->query_vars['category_resume']) || isset($_REQUEST['rsm']);
$is_portfolio = isset($query->query_vars['category_portfolio']) || isset($_REQUEST['prt']);
$page = '';
if (isset($query->queried_object) && isset($query->queried_object->post_type) && $query->queried_object->post_type=='page')
$page = get_post_meta($query->queried_object_id, '_wp_page_template', true);
else if (isset($query->query_vars['page_id']))
$page = get_post_meta($query->query_vars['page_id'], '_wp_page_template', true);
else if (isset($query->queried_object) && isset($query->queried_object->taxonomy))
$page = $query->queried_object->taxonomy;
if ( $is_resume || $page == 'category_resume' || $page == 'template-resume.php') // || is_page_template( 'template-resume.php' ) )
return 'resume';
else if ( $is_portfolio || $page == 'category_portfolio' || $page == 'template-portfolio.php') // || is_page_template( 'template-portfolio.php' ) )
return 'portfolio';
else if ( $page == 'template-video.php') // || is_page_template( 'template-video.php' ) )
return 'video';
else if ( $page == 'template-gallery.php') // || is_page_template( 'template-gallery.php' ) )
return 'gallery';
else if ( $page == 'template-blog.php') // || is_page_template( 'template-blog.php' ) )
return 'blog';
else if ( $query && $query->is_404()) // || is_404() ) // -------------- 404 error page
return 'error';
else if ( $query && $query->is_search()) // || is_search() ) // -------------- Search results
return 'search';
else if ( $query && $query->is_day()) // || is_day() ) // -------------- Archives daily
return 'archives';
else if ( $query && $query->is_month()) // || is_month() ) // -------------- Archives monthly
return 'archives';
else if ( $query && $query->is_year()) // || is_year() ) // -------------- Archives year
return 'archives';
else if ( $query && $query->is_category()) // || is_category() ) // -------------- Category
return 'category';
else if ( $query && $query->is_tag()) // || is_tag() ) // -------------- Tag posts
return 'tag';
else if ( $query && $query->is_author()) // || is_author() ) // -------------- Author page
return 'author';
else if ( $query && $query->is_attachment()) // || is_attachment() )
return 'attachment';
else if ( $query && $query->is_single()) // || is_single() ) // -------------- Single post
return 'single';
else if ( $query && $query->is_page()) // || is_page() )
return 'page';
else // -------------- Home page
return 'home';
}
// Return blog title
function getBlogTitle() {
global $wp_query;
$is_resume = isset($wp_query->query_vars['category_resume']) || isset($_REQUEST['rsm']);
$is_portfolio = isset($wp_query->query_vars['category_portfolio']) || isset($_REQUEST['prt']);
$page = $slug = '';
if (isset($wp_query->queried_object) && isset($wp_query->queried_object->post_type) && $wp_query->queried_object->post_type=='page')
$page = get_post_meta($wp_query->queried_object_id, '_wp_page_template', true);
else if (isset($wp_query->query_vars['page_id']))
$page = get_post_meta($wp_query->query_vars['page_id'], '_wp_page_template', true);
else if (isset($wp_query->queried_object) && isset($wp_query->queried_object->taxonomy))
$page = $slug = $wp_query->queried_object->taxonomy;
if ( $is_resume || $page == 'category_resume' || $page == 'template-resume.php' || is_page_template( 'template-resume.php' ) )
return sprintf( __( '%s', 'wpspace' ), $slug!='' || isset($wp_query->query_vars['category_resume']) ? single_term_title('', false) : __('All Resume', 'wpspace') );
else if ( $is_portfolio || $page == 'category_portfolio' || $page == 'template-portfolio.php' || is_page_template( 'template-portfolio.php' ) )
return sprintf( __( '%s', 'wpspace' ), $slug!='' || isset($wp_query->query_vars['category_portfolio']) ? single_term_title('', false) : __('All Portfolio', 'wpspace') );
else if ( $page == 'template-video.php' || is_page_template( 'template-video.php' ) )
return __( 'All Videos', 'wpspace' );
else if ( $page == 'template-gallery.php' || is_page_template( 'template-gallery.php' ) )
return __( 'All Photos', 'wpspace' );
else if ( $page == 'template-blog.php' || is_page_template( 'template-blog.php' ) )
return __( 'any text', 'wpspace' );
else if ( is_author() ) // -------------- Author page
return __('Author page', 'wpspace');
else if ( is_404() ) // -------------- 404 error page
return __('URL not found', 'wpspace');
else if ( is_search() ) // -------------- Search results
return sprintf( __( 'Search Results for: %s', 'wpspace' ), get_search_query() );
else if ( is_day() ) // -------------- Archives daily
return sprintf( __( 'Daily Archives: %s', 'wpspace' ), get_the_date() );
else if ( is_month() ) // -------------- Archives monthly
return sprintf( __( 'Monthly Archives: %s', 'wpspace' ), get_the_date( 'F Y' ) );
else if ( is_year() ) // -------------- Archives year
return sprintf( __( 'Yearly Archives: %s', 'wpspace' ), get_the_date( 'Y' ) );
else if ( is_category() ) // -------------- Category
return sprintf( __( '%s', 'wpspace' ), single_cat_title( '', false ) );
else if ( is_tag() ) // -------------- Tag page
return sprintf( __( 'Tag: %s', 'wpspace' ), single_tag_title( '', false ) );
else if ( is_attachment() ) // -------------- Attachment page
return sprintf( __( 'Attachment: %s', 'wpspace' ), getPostTitle());
else if ( is_single() ) // -------------- Single post
return getPostTitle();
else if ( is_page() )
//return $wp_query->post->post_title;
return getPostTitle();
else // -------------- Unknown pages - as homepage
return get_bloginfo('name', 'raw');
}
// Show pages links below list or single page
function showPagination($args=array()) {
$args = array_merge(array(
'offset' => 0, // Offset to first showed record
'id' => 'nav_pages', // Name of 'id' attribute
'class' => 'nav_pages' // Name of 'class' attribute
), is_array($args) ? $args
: (is_int($args) ? array( 'offset' => $args ) // If send number parameter - use it as offset
: array( 'id' => $args, 'class' => $args ))); // If send string parameter - use it as 'id' and 'class' name
global $wp_query;
echo "<div id=\"{$args['id']}\" class=\"{$args['class']}\">";
if (function_exists('wp_pagenavi') && !is_single()) {
echo wp_pagenavi('', '', $args['offset']);
$pageNumber = get_query_var('paged') ? get_query_var('paged') : 1;
$maxNumPages = ceil(($wp_query->found_posts - $args['offset']) / get_query_var('posts_per_page')); //$wp_query->max_num_pages;
if ($maxNumPages > 1) {
?>
<div class="page_x_of_y"><?php printf(__('Page <span>%s</span> of <span>%s</span>', 'wpspace'), $pageNumber, $maxNumPages); ?></div>
<?php
}
} else {
showSinglePageNav( 'nav-below' );
}
echo "</div>";
}
// Single page nav or used if no pagenavi
function showSinglePageNav( $nav_id ) {
global $wp_query, $post;
// Don't print empty markup on single pages if there's nowhere to navigate.
if ( is_single() ) {
$previous = ( is_attachment() ) ? get_post( $post->post_parent ) : get_adjacent_post( false, '', true );
$next = get_adjacent_post( false, '', false );
if ( ! $next && ! $previous )
return;
}
// Don't print empty markup in archives if there's only one page.
if ( $wp_query->max_num_pages < 2 && ( is_home() || is_archive() || is_search() ) )
return;
$nav_class = ( is_single() ) ? 'navigation-post' : 'navigation-paging';
?>
<nav role="navigation" id="<?php echo esc_attr( $nav_id ); ?>" class="<?php echo $nav_class; ?>">
<h1 class="screen-reader-text"><?php _e( 'Post navigation', 'wpspace' ); ?></h1>
<?php if ( is_single() ) : // navigation links for single posts ?>
<?php previous_post_link( '<div class="nav-previous">%link</div>', '<span class="meta-nav">' . _x( '←', 'Previous post link', 'wpspace' ) . '</span> %title' ); ?>
<?php next_post_link( '<div class="nav-next">%link</div>', '%title <span class="meta-nav">' . _x( '→', 'Next post link', 'wpspace' ) . '</span>' ); ?>
<?php elseif ( $wp_query->max_num_pages > 1 && ( is_home() || is_archive() || is_search() ) ) : // navigation links for home, archive, and search pages ?>
<?php if ( get_next_posts_link() ) : ?>
<div class="nav-previous"><?php next_posts_link( __( '<span class="meta-nav">←</span> Older posts', 'wpspace' ) ); ?></div>
<?php endif; ?>
<?php if ( get_previous_posts_link() ) : ?>
<div class="nav-next"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">→</span>', 'wpspace' ) ); ?></div>
<?php endif; ?>
<?php endif; ?>
</nav>
<?php
}
// Get our wp_nav_menu() fallback, wp_page_menu(), to show a home link.
add_filter( 'wp_page_menu_args', '_wp_utils_page_menu_args' );
function _wp_utils_page_menu_args( $args ) {
$args['show_home'] = true;
return $args;
}
// Adds custom classes to the array of body classes.
add_filter( 'body_class', '_wp_utils_body_classes' );
function _wp_utils_body_classes( $classes ) {
// Adds a class of group-blog to blogs with more than 1 published author
if ( is_multi_author() ) {
$classes[] = 'group-blog';
}
return $classes;
}
// Filters wp_title to print a neat <title> tag based on what is being viewed.
add_filter( 'wp_title', '_wp_utils_wp_title', 10, 2 );
function _wp_utils_wp_title( $title, $sep ) {
global $page, $paged;
if ( is_feed() ) return $title;
// Add the blog name
$title .= get_bloginfo( 'name' );
// Add the blog description for the home/front page.
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) )
$title .= " $sep $site_description";
// Add a page number if necessary:
if ( $paged >= 2 || $page >= 2 )
$title .= " $sep " . sprintf( __( 'Page %s', 'wpspace' ), max( $paged, $page ) );
return $title;
}
/* ========================= Post utilities section ============================== */
// Return custom_page_heading (if set), else - post title
function getPostTitle($id = 0, $maxlength = 0, $add='...') {
global $wp_query;
if (!$id) $id = $wp_query->current_post>=0 ? get_the_ID() : $wp_query->post->ID;
$title = get_post_meta($id, 'custom_page_heading', true);
if (!$title)
$title = get_the_title($id);
if ($maxlength > 0) $title = getShortString($title, $maxlength, $add);
return $title;
}
// Return custom_page_description (if set), else - post excerpt (if set), else - trimmed content
function getPostDescription($maxlength = 0, $add='...') {
global $wp_query;
$id = $wp_query->current_post>=0 ? get_the_ID() : $wp_query->post->ID;
if (post_password_required($id)) {
$descr = __('This post is password protected. To view it please enter your password inside the post.', 'wpspace');
} else {
$descr = get_post_meta($id, 'custom_page_description', true);
if (!$descr) {
$descr = get_the_excerpt();
$descr = trim(str_replace('[...]', '', $descr));
}
if (!$descr) {
$descr = get_the_content('', true);
}
if ($maxlength > 0) $descr = getShortString($descr, $maxlength, $add);
}
return $descr;
}
//Return Post Views Count on Posts Without Any Plugin in WordPress
function getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0 ";
}
return $count;
}
//Set Post Views Count
function setPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}
// Return posts by meta_value
function getPostsByMetaValue($meta_key, $meta_value, $return_format=OBJECT) {
global $wpdb;
$where = array();
if ($meta_key) $where[] = 'meta_key="' . $meta_key . '"';
if ($meta_value) $where[] = 'meta_value="' . $meta_value . '"';
$whereStr = count($where) ? 'WHERE '.join(' AND ', $where) : '';
$posts = $wpdb->get_results("SELECT * FROM {$wpdb->postmeta} {$whereStr}", $return_format);
return $posts;
}
/* ========================= User profile section ============================== */
$user_social_list = array(
'twitter' => 'Twitter',
'facebook' => 'Facebook',
'dribbble' => 'Dribbble',
'pinterest' => 'Pinterest',
'linkedin' => 'LinkedIn',
'rss' => 'Feed RSS',
'gplus' => 'Google+',
'tumblr' => 'Tumblr',
'behance' => 'Behance'
);
$share_social_list = array(
'twitter' => "https://twitter.com/share?text={title}&counturl={link}&url={link}",
'facebook' => "http://www.facebook.com/share.php?u={link}",
'pinterest' => "javascript:void((function(d){var%20e=d.createElement('script');e.setAttribute('type','text/javascript');e.setAttribute('charset','UTF-8');e.setAttribute('src','//assets.pinterest.com/js/pinmarklet.js?r='+Math.random()*99999999);d.body.appendChild(e)})(document));",
'gplus' => "https://plusone.google.com/_/+1/confirm?url={link}"
);
// Return (and show) user profiles links
function showUserSocialLinks($args) {
$args = array_merge(array(
'id' => 'author_social_profile', // ul tag's id
'class' => 'author_social_profile', // ul tag's class
'author_id' => 0, // author's ID
'icon_size' => '', // icon size (if not empty - append after icon part: icon-big-twitter)
'allowed' => array(), // list of allowed social
'echo' => true // if true - show on page, else - only return as string
), is_array($args) ? $args
: array('author_id' => $args)); // If send one number parameter - use it as author's ID
global $user_social_list;
$tpl_dir = get_template_directory_uri();
$output = '';
if (count($args['allowed'])==0) $args['allowed'] = array_keys($user_social_list);
foreach ($args['allowed'] as $s) {
if (array_key_exists($s, $user_social_list)) {
$link = get_the_author_meta('user_' . $s, $args['author_id']);
if ($link) {
$icon = $tpl_dir . '/images/icon-' . ($args['icon_size'] ? $args['icon_size'] . '-' : '') . $s . '.png';
$output .= '<li><a href="' . $link . '" class="link_' . $s . '"><img src="' . $icon . '" class="icon_' . $s . '" alt="' . $s . '" /></a></li>';
}
}
}
if ($output) $output = '<ul id="' . $args['id'] . '" class="' . $args['class'] . '">' . $output . '</ul>';
if ($args['echo']) echo $output;
return $output;
}
// Return (and show) share social links
function showShareSocialLinks($args) {
$args = array_merge(array(
'id' => 'post_social_share', // ul tag's id
'class' => 'post_social_share', // ul tag's class
'post_id' => 0, // post ID
'post_link' => '', // post link
'post_title' => '', // post title
'icon_size' => '', // icon size (if not empty - append to end of icon name: icon-big-twitter
'allowed' => array(), // list of allowed social
'echo' => true // if true - show on page, else - only return as string
), $args);
global $share_social_list;
$tpl_dir = get_template_directory_uri();
$output = '';
if (count($args['allowed'])==0) $args['allowed'] = array_keys($share_social_list);
foreach ($args['allowed'] as $s) {
if (array_key_exists($s, $share_social_list)) {
$link = str_replace(array('{id}', '{link}', '{title}'), array($args['post_id'], $args['post_link'], $args['post_title']), $share_social_list[$s]);
$icon = $tpl_dir . '/images/icon-' . ($args['icon_size'] ? $args['icon_size'] . '-' : '') . $s . '.png';
$output .= '<li><a href="' . $link . '" class="link-' . $s . '" target="_black"><img src="' . $icon . '" class="icon_' . $s . '" alt="' . $s . '" /></a></li>';
}
}
if ($output) $output = '<ul id="' . $args['id'] . '" class="' . $args['class'] . '">' . $output . '</ul>';
if ($args['echo']) echo $output;
return $output;
}
// show additional fields
add_action( 'show_user_profile', 'my_show_extra_profile_fields' );
add_action( 'edit_user_profile', 'my_show_extra_profile_fields' );
function my_show_extra_profile_fields( $user ) {
global $user_social_list;
?>
<h3>Social links</h3>
<table class="form-table">
<?php
foreach ($user_social_list as $name=>$title) {
?>
<tr>
<th><label for="<?php echo $name; ?>"><?php echo $title; ?>:</label></th>
<td><input type="text" name="user_<?php echo $name; ?>" id="user_<?php echo $name; ?>" size="55" value="<?php echo esc_attr(get_the_author_meta('user_'.$name, $user->ID)); ?>" />
<span class="description">Please, enter your <?php echo $title; ?> link</span>
</td>
</tr>
<?php
}
?>
</table>
<?php
}
// Save / update additional fields
add_action( 'personal_options_update', 'my_save_extra_profile_fields' );
add_action( 'edit_user_profile_update', 'my_save_extra_profile_fields' );
function my_save_extra_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) )
return false;
global $user_social_list;
foreach ($user_social_list as $name=>$title)
update_user_meta( $user_id, 'user_'.$name, $_POST['user_'.$name] );
}
/*
function twitter_followers($account) {
$tw = get_transient("twitterfollowers");
if ($tw !== false) return $tw;
$tw = '?';
$url = 'https://twitter.com/users/show/'.$account;
$headers = get_headers($url);
if (my_strpos($headers[0], '200')) {
$xml = file_get_contents($url);
preg_match('/followers_count>(.*)</', $xml, $match);
if ($match[1] !=0 ) {
$tw = $match[1];
set_transient("twitterfollowers", $tw, 60*60);
}
}
return $tw;
}
function facebook_likes($account) {
$fb = get_transient("facebooklikes");
if ($fb !== false) return $fb;
$fb = '?';
$url = 'http://graph.facebook.com/'.$account;
$headers = get_headers($url);
if (my_strpos($headers[0], '200')) {
$json = file_get_contents($url);
$rez = json_decode($json, true);
if (isset($rez['likes']) ) {
$fb = $rez['likes'];
set_transient("facebooklikes", $fb, 60*60);
}
}
return $fb;
}
function feedburner_counter($account) {
$rss = get_transient("feedburnercounter");
if ($rss !== false) return $rss;
$rss = '?';
$url = 'http://feedburner.google.com/api/awareness/1.0/GetFeedData?uri='.$account;
$headers = get_headers($url);
if (my_strpos($headers[0], '200')) {
$xml = file_get_contents($url);
preg_match('/circulation="(\d+)"/', $xml, $match);
if ($match[1] != 0) {
$rss = $match[1];
set_transient("feedburnercounter", $rss, 60*60);
}
}
return $rss;
}
*/
/* ========================= Admin section ============================== */
// Add categories (taxonomies) filter for custom posts types
add_action( 'restrict_manage_posts', 'admin_taxonomy_filter' );
function admin_taxonomy_filter() {
global $typenow;
if ($typenow == 'post') $taxes = array();
else if ($typenow == 'resume') $taxes = array('category_resume');
else if ($typenow == 'portfolio') $taxes = array('category_portfolio');
else return;
if (get_theme_option('admin_add_filters')=='1') {
$taxes[] = 'post_format';
$taxes[] = 'post_tag';
}
$i = 0;
foreach ($taxes as $tax) {
$i++;
$tax_obj = get_taxonomy($tax);
$terms = getTaxonomiesByPostType(array($typenow), array($tax)); //$i==1 ? get_terms($tax) : getTaxonomiesByPostType(array($typenow), array($tax));
if (count($terms) > 0) {
$tax_name = my_strtolower($tax_obj->labels->name);
$tax = str_replace(array('post_tag'), array('tag'), $tax);
echo "<select name='$tax' id='$tax' class='postform'>";
echo "<option value=''>All $tax_name</option>";
foreach ($terms as $term) {
$slug = is_object($term) ? $term->slug : $term['slug'];
$name = is_object($term) ? $term->name : $term['name'];
$count = is_object($term) ? $term->count : $term['count'];
echo '<option value='. $slug . ($_GET[$tax] == $slug ? ' selected="selected"' : '') . '>' . str_replace(array('post-format-'), array(''), $name) . ' (' . $count .')</option>';
}
echo "</select>";
}
}
}
/* ========================= Other functions section ============================== */
// Return calendar with allowed posts types
function get_theme_calendar($initial = true, $echo = true, $allowed_types = array('post', 'news', 'reviews')) {
global $wpdb, $m, $monthnum, $year, $wp_locale, $posts;
$cache = array();
$key = md5( $m . $monthnum . $year );
if ( $cache = wp_cache_get( 'get_calendar', 'calendar' ) ) {
if ( is_array($cache) && isset( $cache[ $key ] ) ) {
if ( $echo ) {
echo apply_filters( 'get_calendar', $cache[$key] );
return;
} else {
return apply_filters( 'get_calendar', $cache[$key] );
}
}
}
if ( !is_array($cache) )
$cache = array();
// Quick check. If we have no posts at all, abort!
if ( !$posts ) {
$gotsome = $wpdb->get_var("SELECT 1 as test FROM $wpdb->posts WHERE post_type IN ('" . join("', '", $allowed_types) . "') AND post_status = 'publish' LIMIT 1");
if ( !$gotsome ) {
$cache[ $key ] = '';
wp_cache_set( 'get_calendar', $cache, 'calendar' );
return;
}
}
if ( isset($_GET['w']) )
$w = ''.intval($_GET['w']);
// week_begins = 0 stands for Sunday
$week_begins = intval(get_option('start_of_week'));
// Let's figure out when we are
if ( !empty($monthnum) && !empty($year) ) {
$thismonth = ''.zeroise(intval($monthnum), 2);
$thisyear = ''.intval($year);
} elseif ( !empty($w) ) {
// We need to get the month from MySQL
$thisyear = ''.intval(my_substr($m, 0, 4));
$d = (($w - 1) * 7) + 6; //it seems MySQL's weeks disagree with PHP's
$thismonth = $wpdb->get_var("SELECT DATE_FORMAT((DATE_ADD('{$thisyear}0101', INTERVAL $d DAY) ), '%m')");
} elseif ( !empty($m) ) {
$thisyear = ''.intval(my_substr($m, 0, 4));
if ( my_strlen($m) < 6 )
$thismonth = '01';
else
$thismonth = ''.zeroise(intval(my_substr($m, 4, 2)), 2);
} else {
$thisyear = gmdate('Y', current_time('timestamp'));
$thismonth = gmdate('m', current_time('timestamp'));
}
$unixmonth = mktime(0, 0 , 0, $thismonth, 1, $thisyear);
$last_day = date('t', $unixmonth);
// Get the next and previous month and year with at least one post
$previous = $wpdb->get_row("SELECT MONTH(post_date) AS month, YEAR(post_date) AS year
FROM $wpdb->posts
WHERE post_date < '$thisyear-$thismonth-01'
AND post_type IN ('" . join("', '", $allowed_types) . "') AND post_status = 'publish'
ORDER BY post_date DESC
LIMIT 1");
$next = $wpdb->get_row("SELECT MONTH(post_date) AS month, YEAR(post_date) AS year
FROM $wpdb->posts
WHERE post_date > '$thisyear-$thismonth-{$last_day} 23:59:59' AND post_date_gmt > '$thisyear-$thismonth-{$last_day} 23:59:59'
AND post_type IN ('" . join("', '", $allowed_types) . "') AND post_status = 'publish'
ORDER BY post_date ASC
LIMIT 1");
/* translators: Calendar caption: 1: month name, 2: 4-digit year */
$calendar_caption = _x('%1$s %2$s', 'calendar caption', 'wpspace');
$calendar_output = '<table id="wp-calendar">
<caption>' . sprintf($calendar_caption, $wp_locale->get_month($thismonth), date('Y', $unixmonth)) . '</caption>
<thead>
<tr>';
$myweek = array();
for ( $wdcount=0; $wdcount<=6; $wdcount++ ) {
$myweek[] = $wp_locale->get_weekday(($wdcount+$week_begins)%7);
}
foreach ( $myweek as $wd ) {
$day_name = (true == $initial) ? $wp_locale->get_weekday_initial($wd) : $wp_locale->get_weekday_abbrev($wd);
$wd = esc_attr($wd);
$calendar_output .= "\n\t\t<th scope=\"col\" title=\"$wd\">$day_name</th>";
}
$calendar_output .= '
</tr>
</thead>
<tfoot>
<tr>';
if ( $previous ) {
$calendar_output .= "\n\t\t".'<td colspan="3" id="prev"><a href="' . get_month_link($previous->year, $previous->month) . '" title="' . esc_attr( sprintf(__('View posts for %1$s %2$s', 'wpspace'), $wp_locale->get_month($previous->month), date('Y', mktime(0, 0 , 0, $previous->month, 1, $previous->year)))) . '">« ' . $wp_locale->get_month_abbrev($wp_locale->get_month($previous->month)) . '</a></td>';
} else {
$calendar_output .= "\n\t\t".'<td colspan="3" id="prev" class="pad"> </td>';
}
$calendar_output .= "\n\t\t".'<td class="pad"> </td>';
if ( $next && ($next->year.'-'.$next->month <= date('Y-m'))) {
$calendar_output .= "\n\t\t".'<td colspan="3" id="next"><a href="' . get_month_link($next->year, $next->month) . '" title="' . esc_attr( sprintf(__('View posts for %1$s %2$s', 'wpspace'), $wp_locale->get_month($next->month), date('Y', mktime(0, 0 , 0, $next->month, 1, $next->year))) ) . '">' . $wp_locale->get_month_abbrev($wp_locale->get_month($next->month)) . ' »</a></td>';
} else {
$calendar_output .= "\n\t\t".'<td colspan="3" id="next" class="pad"> </td>';
}
$calendar_output .= '
</tr>
</tfoot>
<tbody>
<tr>';
// Get days with posts
$dayswithposts = $wpdb->get_results("SELECT DISTINCT DAYOFMONTH(post_date)
FROM $wpdb->posts WHERE (post_date >= '{$thisyear}-{$thismonth}-01 00:00:00' OR post_date_gmt >= '{$thisyear}-{$thismonth}-01 00:00:00')
AND post_type IN ('" . join("', '", $allowed_types) . "') AND post_status = 'publish'
AND (post_date <= '{$thisyear}-{$thismonth}-{$last_day} 23:59:59' OR post_date_gmt <= '{$thisyear}-{$thismonth}-{$last_day} 23:59:59')", ARRAY_N);
if ( $dayswithposts ) {
foreach ( (array) $dayswithposts as $daywith ) {
$daywithpost[] = $daywith[0];
}
} else {
$daywithpost = array();
}
if (my_strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false || stripos($_SERVER['HTTP_USER_AGENT'], 'camino') !== false || stripos($_SERVER['HTTP_USER_AGENT'], 'safari') !== false)
$ak_title_separator = "\n";
else
$ak_title_separator = ', ';
$ak_titles_for_day = array();
$ak_post_titles = $wpdb->get_results("SELECT ID, post_title, DAYOFMONTH(post_date) as dom "
."FROM $wpdb->posts "
."WHERE (post_date >= '{$thisyear}-{$thismonth}-01 00:00:00' OR post_date_gmt >= '{$thisyear}-{$thismonth}-01 00:00:00') "
."AND (post_date <= '{$thisyear}-{$thismonth}-{$last_day} 23:59:59' OR post_date_gmt <= '{$thisyear}-{$thismonth}-{$last_day} 23:59:59') "
."AND post_type IN ('" . join("', '", $allowed_types) . "') AND post_status = 'publish'"
);
if ( $ak_post_titles ) {
foreach ( (array) $ak_post_titles as $ak_post_title ) {
$post_title = esc_attr( apply_filters( 'the_title', $ak_post_title->post_title, $ak_post_title->ID ) );
if ( empty($ak_titles_for_day['day_'.$ak_post_title->dom]) )
$ak_titles_for_day['day_'.$ak_post_title->dom] = '';
if ( empty($ak_titles_for_day["$ak_post_title->dom"]) ) // first one
$ak_titles_for_day["$ak_post_title->dom"] = $post_title;
else
$ak_titles_for_day["$ak_post_title->dom"] .= $ak_title_separator . $post_title;
}
}
// See how much we should pad in the beginning
$pad = calendar_week_mod(date('w', $unixmonth)-$week_begins);
if ( 0 != $pad )
$calendar_output .= "\n\t\t".'<td colspan="'. esc_attr($pad) .'" class="pad"> </td>';
$daysinmonth = intval(date('t', $unixmonth));
for ( $day = 1; $day <= $daysinmonth; ++$day ) {
if ( isset($newrow) && $newrow )
$calendar_output .= "\n\t</tr>\n\t<tr>\n\t\t";
$newrow = false;
if ( $day == gmdate('j', current_time('timestamp')) && $thismonth == gmdate('m', current_time('timestamp')) && $thisyear == gmdate('Y', current_time('timestamp')) )
$calendar_output .= '<td id="today">';
else
$calendar_output .= '<td>';
if ( in_array($day, $daywithpost) ) // any posts today?
$calendar_output .= '<a href="' . get_day_link( $thisyear, $thismonth, $day ) . '" title="' . esc_attr( $ak_titles_for_day[ $day ] ) . "\">$day</a>";
else
$calendar_output .= $day;
$calendar_output .= '</td>';
if ( 6 == calendar_week_mod(date('w', mktime(0, 0 , 0, $thismonth, $day, $thisyear))-$week_begins) )
$newrow = true;
}
$pad = 7 - calendar_week_mod(date('w', mktime(0, 0 , 0, $thismonth, $day, $thisyear))-$week_begins);
if ( $pad != 0 && $pad != 7 )
$calendar_output .= "\n\t\t".'<td class="pad" colspan="'. esc_attr($pad) .'"> </td>';
$calendar_output .= "\n\t</tr>\n\t</tbody>\n\t</table>";
$cache[ $key ] = $calendar_output;
wp_cache_set( 'get_calendar', $cache, 'calendar' );
if ( $echo )
echo apply_filters( 'get_calendar', $calendar_output );
else
return apply_filters( 'get_calendar', $calendar_output );
}
// Decorate 'read more...' link
function decorateMoreLink($text, $tag_start='<div class="readmore">', $tag_end='</div>') {
//return preg_replace('/(<a[^>]+class="more-link"[^>]*>[^<]*<\\/a>)/', "{$tag_start}\${1}{$tag_end}", $text);
$rez = $text;
if (($pos = my_strpos($text, ' class="more-link"><span class="readmore">'))!==false) {
$i = $pos-1;
while ($i > 0) {
if (my_substr($text, $i, 3) == '<a ') {
if (($pos = my_strpos($text, '</span></a>', $pos))!== false) {
$pos += 11;
$start = my_substr($text, $i-4, 4) == '<p> ' ? $i-4 : (my_substr($text, $i-3, 3) == '<p>' ? $i-3 : $i);
$end = my_substr($text, $pos, 4) == '</p>' ? $pos+4 : $pos;
$rez = my_substr($text, 0, $start) . $tag_start . my_substr($text, $i, $pos-$i) . $tag_end . my_substr($text, $end);
break;
}
}
$i--;
}
}
return $rez;
}
/* ========================= Aqua resizer wrapper ============================== */
function getResizedImageTag( $url, $w=null, $h=null, $c=null, $u=true ) {
if (is_object($url)) $alt = getPostTitle( $url->ID );
else if ((int) $url > 0) $alt = getPostTitle( $url );
else $alt = basename($url);
$url = getResizedImageURL($url, $w, $h, $c, $u);
if ($url != '') {
if (($url_dir = getUploadsDirFromURL($url)) !== false)
$size = @getimagesize($url_dir);
else
$size = false;
return '<img class="wp-post-image" ' . ($size!==false && isset($size[3]) ? $size[3] : '') . ' alt="' . $alt . '" src="' . $url . '">';
} else
return '';
//return $url!='' ? ('<img class="wp-post-image"' . ($w ? ' width="'.$w.'"' : '') . ($h ? ' height="' . $h . '"' : '') . ' alt="' . $alt . '" src="' . $url . '">') : '';
}
function getResizedImageURL( $url, $w=null, $h=null, $c=null, $u=true ) {
if (is_object($url)) $url = wp_get_attachment_url( get_post_thumbnail_id( $url->ID ));
else if ((int) $url > 0) $url = wp_get_attachment_url( get_post_thumbnail_id( $url ));
else $url = trim(chop($url));
if ($url != '') {
if ($c === null) $c = true; //$c = get_option('thumbnail_crop')==1;
if ( ! ($new_url = aq_resize( $url, $w, $h, $c, true, $u)) ) {
if (false)
$new_url = get_the_post_thumbnail($url, array($w, $h));
else
$new_url = $url;
}
} else $new_url = '';
return $new_url;
}
function getUploadsDirFromURL($url) {
$upload_info = wp_upload_dir();
$upload_dir = $upload_info['basedir'];
$upload_url = $upload_info['baseurl'];
$http_prefix = "http://";
$https_prefix = "https://";
if (!strncmp($url,$https_prefix,my_strlen($https_prefix))){ //if url begins with https:// make $upload_url begin with https:// as well
$upload_url = str_replace($http_prefix, $https_prefix, $upload_url);
} else if (!strncmp($url,$http_prefix,my_strlen($http_prefix))){ //if url begins with http:// make $upload_url begin with http:// as well
$upload_url = str_replace($https_prefix, $http_prefix, $upload_url);
}
// Check if $img_url is local.
if ( false === my_strpos( $url, $upload_url ) ) return false;
// Define path of image.
$rel_path = str_replace( $upload_url, '', $url );
$img_path = $upload_dir . $rel_path;
return $img_path;
}
// Return custom sidebars list, prepended default and main sidebars item (if need)
function getSidebarsList($sidebars = array("As in Site Options|default", "Main sidebar|sidebar-blog")) {
$cnt = get_theme_option('sidebars_count');
for ($i=1; $i<=$cnt; $i++) {
$sidebars[] = 'Custom sidebar '.$i.'|sidebar-custom-'.$i;
}
return $sidebars;
}
// Prepare minth names in date for translation
function prepareDateForTranslation($dt) {
return str_replace(
array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December',
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'),
array(
__('January', 'themerex'),
__('February', 'themerex'),
__('March', 'themerex'),
__('April', 'themerex'),
__('May', 'themerex'),
__('June', 'themerex'),
__('July', 'themerex'),
__('August', 'themerex'),
__('September', 'themerex'),
__('October', 'themerex'),
__('November', 'themerex'),
__('December', 'themerex'),
__('Jan', 'themerex'),
__('Feb', 'themerex'),
__('Mar', 'themerex'),
__('Apr', 'themerex'),
__('May', 'themerex'),
__('Jun', 'themerex'),
__('Jul', 'themerex'),
__('Aug', 'themerex'),
__('Sep', 'themerex'),
__('Oct', 'themerex'),
__('Nov', 'themerex'),
__('Dec', 'themerex'),
),
$dt);
}
?> | srrdvd/cv | wp-content/themes/cv/includes/_wp_utils.php | PHP | gpl-2.0 | 41,455 |
<?php
$a = $_GET['a'];
$conexion= new mysqli("localhost","root","tr15t4n14","padron_beneficiarios");
$conexion->query("SET NAMES utf8");
$consulta = "SELECT * FROM caracteristicas_apoyo WHERE id_tipo_apoyo = '$a'";
$ex_consulta = $conexion->query($consulta);
$opciones = "<option value='0'> -Seleccione- </option>";
while($r=$ex_consulta->fetch_assoc()){
$opciones.="<option value='".$r['id_caracteristica']."'>".$r['caracteristica']."</option>";
}
$return = "<div id='caracteristica_apoyo'>
<label for='perfil_s' class='control-label col-xs-2'>Caracteristica del apoyo</label>
<div class='col-xs-6'>
<select name='tipo_apoyo' id='tipo_apoyo' class='form-control'>".$opciones."</select>
</div></div>";
echo $return;
?>
| kailIII/sipub | modulos/getapoyos.php | PHP | gpl-2.0 | 722 |
#!/usr/bin/python
import piksemel
import os
def updateGConf (filepath, remove=False):
parse = piksemel.parse (filepath)
schemaList = list()
for xmlfile in parse.tags ("File"):
path = xmlfile.getTagData ("Path")
# Only interested in /etc/gconf/schemas
if "etc/gconf/schemas" in path:
schemaList.append ("/%s" % path)
if len(schemaList) > 0:
os.environ['GCONF_CONFIG_SOURCE'] = 'xml:merged:/etc/gconf/gconf.xml.defaults'
operation = "--makefile-uninstall-rule" if remove else "--makefile-install-rule"
cmd = "/usr/bin/gconftool-2 %s %s" % (operation, " ".join(schemaList))
os.system (cmd)
def setupPackage (metapath, filepath):
updateGConf (filepath)
def postCleanupPackage (metapath, filepath):
updateGConf (filepath)
| richard-fisher/repository | desktop/gnome/core/gconf/comar/packageHandler.py | Python | gpl-2.0 | 816 |
<html>
<head>
<meta charset="UTF-8" name="viewport" content="width=device-width" />
<title>Check der Klassenlisten @ Sporttage-Kepler</title>
</head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 3px;
}
</style>
<body>
<h1>Eingaben überprüfen</h1>
<b> BITTE ALLES NOCHMALS KONTROLLIEREN!!! </b> <br>
KEINE LEERZEICHEN benutzen!
DU bist kurz vor dem FINALEN Eintragen in die DATENBANK!<br> <br>
<b><font color="#FF0000"> <h2> HINWEISE: </h2> <br>
Bitte nochmals alle Namen auf korrekte Rechtschreibung überprüfen, dies kann das Programm naturlich nicht selbst kontrollieren! <br>
Bitte Doppelnamen mit Bindestrich '-' und nicht mit Leerzeile eingeben! <br>
</font></b>
<br>
<?php
$badmintonAnzahlTeams=$_POST['badmintonAnzahlTeams']; //anzahl badminton teams
$AnzahlSpielerMannschaft=$_POST['AnzahlSpielerMannschaft']; //spieler/mannschaftssportart team
$anzahlTeams = $_POST['anzahlTeams'];
/*for ($i=0; $i < count($anzahlTeams); $i++) {
echo $anzahlTeams[$i];
} */
//klasse speichern
$klasse = $_POST['klasse'];
//k1 speichern
$k1 = $_POST['k1'];
if (strpos($klasse,'10') !== false || $k1 == "k1" || strpos($klasse,'K1') !== false || strpos($klasse,'K2') !== false) {
$stufenListe = "Mannschaften_OS";
} else if (strpos($klasse,'7') !== false || strpos($klasse,'8') !== false || strpos($klasse,'9') !== false || strpos($klasse,'A1') !== false) {
$stufenListe = "Mannschaften_MS";
} else if (strpos($klasse,'5') !== false || strpos($klasse,'6') !== false) {
$stufenListe = "Mannschaften_US";
}
//$badmintonAnzahlTeams=10; //anzahl badminton teams
//$AnzahlSpielerMannschaft=9; //spieler/mannschaftssportart team
/* $anzahlTeams = array(
0 => 2, //FB
1 => 1, //BB
2 => 1, //FT
3 => 1, //VB
4 => 1, //ST
);*/
$anzahlTeamsGesamt=0;
for ($i=0; $i<count($anzahlTeams); $i++) {
for ($a=0; $a<$anzahlTeams[$i]; $a++) {
$anzahlTeamsGesamt++;
}
}
$teamGroesse = array( //teamgroesse fürs checken
0 => '6', //FB
1 => '6', //BB
2 => '0', //FT
3 => '6', //VB
4 => '4', //ST
// 5 => '2', //BM
// 6 => '2', //TT
);
$nameDB = array(
0 => 'fb', //FB
1 => 'bb', //BB
2 => 'ft', //FT
3 => 'vb', //VB
4 => 'st', //ST
);
$nameVoll = array(
0 => 'Fußball Team', //FB
1 => 'Basketball Team', //BB
2 => 'Fahrradtour', //FT
3 => 'Volleyball Team', //VB
4 => 'Staffellauf Team', //ST
);
$neueArrayLaenge=0;
for ($i=0; $i<count($anzahlTeams); $i++) { //für alle Teams
for ($a=1; $a<$anzahlTeams[$i]+1; $a++) {
$teamNummer = $a;
//vornamen teil
$sportartenName[$neueArrayLaenge] = $nameDB[$i] . $teamNummer . '_v'; //array mit fb1_v etc
$sportartenVollerName[$neueArrayLaenge]= $nameVoll[$i] . ' ' . $teamNummer ; //array fürs echo, ausgeschrieben
$sportartenTeamGroesse[$neueArrayLaenge] = $teamGroesse[$i];
/* echo 'Nr. ' . $neueArrayLaenge . ' Team: ' . $sportartenName[$neueArrayLaenge] . '<br>';
echo 'Nr. ' . $neueArrayLaenge . ' Team: ' . $sportartenVollerName[$neueArrayLaenge] . '<br>'; */
$neueArrayLaenge++;
//nachnamen teil
$sportartenName[$neueArrayLaenge]= $nameDB[$i] . $teamNummer . '_n';
$sportartenVollerName[$neueArrayLaenge]= $nameVoll[$i] . ' ' . $teamNummer;
$sportartenTeamGroesse[$neueArrayLaenge] = $teamGroesse[$i];
/* echo 'Nr. ' . $neueArrayLaenge . ' Team: ' . $sportartenName[$neueArrayLaenge] . '<br>';
echo 'Nr. ' . $neueArrayLaenge . ' Team: ' . $sportartenVollerName[$neueArrayLaenge] . '<br>'; */
$neueArrayLaenge++;
}
}
$zweierTeamsName = array (
0 => 'bm_v',
1 => 'Badminton Teams',
2 => 'bm_n',
3 => 'Badminton Teams',
4 => 'tt_v',
5 => 'Tischtennis Teams',
6 => 'tt_n',
7 => 'Tischtennis Teams',
);
for ($i=0; $i < count($zweierTeamsName); $i+=2) {
$sportartenName[$neueArrayLaenge]= $zweierTeamsName[$i];
$sportartenVollerName[$neueArrayLaenge]= $zweierTeamsName[$i+1];
// $sportartenTeamGroesse[$neueArrayLaenge] = $teamGroesse[5]; //teamgrösse bm hard coded
$neueArrayLaenge++;
}
//array für alle teamnamen anlegen
$neueArrayLaenge=0;
for ($i=0; $i<count($anzahlTeams); $i++) { //für alle Teams
for ($a=1; $a<$anzahlTeams[$i]+1; $a++) {
$teamNummer = $a;
$sportartenVollerNameEinzeln[$neueArrayLaenge] = $nameVoll[$i] . ' ' . $teamNummer; //array mit Fußball Team 1 etc.
$neueArrayLaenge++;
}
}
//läd die werte aus $_POST von sporttage.php in sportarten1 an der richtigen stelle
for ($i=0; $i < count($sportartenName); $i++ ) {
$sportarten1[$i] = $_POST[$sportartenName[$i]];
}
if ($k1=='k1') {
if (strpos($klasse,'D') !== false) {
$k1 = 'checked'; //wenn k1 gecheckt war soll es wieder gecheckt werden
} else {
echo '<b><font color="#FF0000"> Achtung: K1 falsch eingetragen</font> </b><br>'; //deutschkurs angabe fehlt
}
} else {
$k1='';
}
//******************EINGABEN PRÜFEN******************************************************************************************************************
//prüfen, ob bei den mannschaftssportarten ein fehler/problem vorhanden ist
for ($sportart=0; $sportart<count($sportartenName)-4; $sportart+=2) {
$namenZaehler=0; //zaehler erstellen
$nameFehlt=0;
for($i = 0; $i < count($sportarten1[$sportart]); $i++) {
if ($sportarten1[$sportart][$i] != '' && $sportarten1[$sportart+1][$i] != '') {
$namenZaehler++; //zaehler+1 je mannschaftsteam
}
if ($sportarten1[$sportart][$i] != '' xor $sportarten1[$sportart+1][$i] != '') {
$nameFehlt=true; //true, wennn es einen unvollständigen namen gibt
}
}
//echo 'sportart: ' . $sportart . ' teamgroesse: ' . $sportartenTeamGroesse[$sportart];
if ($stufenListe=="Mannschaften_US" && strpos($sportartenVollerName[$sportart],'Volleyball') !== false && $namenZaehler != 0) {
echo '<b><font color="#FF0000"> Achtung: es gibt kein Volleyball in der Unterstufe!!!</font> </b><br>';
break;
}
if (strpos($sportartenVollerName[$sportart],'Fahrradtour') == false && (($namenZaehler>0 && $namenZaehler < $sportartenTeamGroesse[$sportart]) || ($nameFehlt==true))) {
echo '<b><font color="#FF0000"> Achtung: zu wenig Schüler in ' . $sportartenVollerName[$sportart] . ' (' . $sportartenVollerName[$sportart] . ' braucht mind ' . $sportartenTeamGroesse[$sportart] . ') oder ein Vor- oder Nachname fehlt!</font> </b><br>';
}
$nameFehlt=false;
}
for ($sportart=(count($sportartenName)-4); $sportart<count($sportartenName); $sportart+=2) {
//echo $sportart;
$mannschaftsNummer=0;
for($i = 1; $i < count($sportarten1[$sportart]); $i+=2) {
$mannschaftsNummer++;
if (($sportarten1[$sportart][$i] != '' xor $sportarten1[$sportart+1][$i] != '') or ($sportarten1[$sportart][$i-1] != '' xor $sportarten1[$sportart+1][$i-1] != '')) {
if ($sportart==(count($sportartenName)-4)) {
echo '<b><font color="#FF0000"> Achtung: ein oder mehrere Vor- oder Nachname/-n fehlt/fehlen in Badminton Team ' . $mannschaftsNummer . '!</font> </b><br>';
}
if ($sportart==(count($sportartenName)-2)) {
echo '<b><font color="#FF0000"> Achtung: ein oder mehrere Vor- oder Nachname/-n fehlt/fehlen in Tischtennis Team ' . $mannschaftsNummer . '!</font> </b><br>';
}
}
if (($sportarten1[$sportart][$i] != '' or $sportarten1[$sportart+1][$i] != '') xor ($sportarten1[$sportart][$i-1] != '' or $sportarten1[$sportart+1][$i-1] != '')) {
if ($sportart==(count($sportartenName)-4)) {
echo '<b><font color="#FF0000"> Achtung: ein Name fehlt in Badminton Team ' . $mannschaftsNummer . '! (Badminton braucht genau 2 Personen pro Team)</font> </b><br>';
}
if ($sportart==(count($sportartenName)-2)) {
echo '<b><font color="#FF0000"> Achtung: ein Name fehlt in Tischtennis Team ' . $mannschaftsNummer . '! (Tischtennis braucht genau 2 Personen pro Team) </font> </b><br>';
}
}
}
}
//*************************TABINDEX*********************************************************************
$anzahlSpaltenOhneBM = 0;
$currentTabIndex=0;
//echo '18= ' . (count($sportarten1[0])*2) . '<br>';
for (; $anzahlSpaltenOhneBM <= ($anzahlTeamsGesamt*2); $anzahlSpaltenOhneBM+=2) {
//echo "spalten " . $anzahlSpaltenOhneBM . '<br>';
$tabindex[$anzahlSpaltenOhneBM] = $currentTabIndex +1 ;
$tabindex[$anzahlSpaltenOhneBM+1] = $currentTabIndex +2;
$currentTabIndex += (count($sportarten1[0])*2);
}
$currentTabIndex-=(count($sportarten1[0])) -2;
//bm übernimmt die werte von staffellauf und zählt weiter, für die tt zeile müssen wir wissen, bis wieviel die bm zeilen zählen
//das wird hier gespeichert und später abgerufen
$tabindex[$anzahlSpaltenOhneBM] = $currentTabIndex + ($badmintonAnzahlTeams*4); //TT v
$tabindex[$anzahlSpaltenOhneBM+1] = $currentTabIndex + ($badmintonAnzahlTeams*4) + 1; //TT n
//tabindex ehrhöhen, sodass tabelle erst bei 3 beginnt (für k1 feld=1 und klasse feld=2)
for ($i=0; $i < count($tabindex); $i++) {
//echo 'tabindex von ' . $i . ' ist: ' . $tabindex[$i] . '<br> ';
$tabindex[$i]+=2;
}
//***********checkOverride*******************************+
$checkPassBox = $_POST['checkPassBox'];
$checkPassText = $_POST['checkPassText'];
if (($checkPassBox == '1') && ($checkPassText == 'FORCE_OVERRIDE')) { //kommandos zum überspringen von check (z.B. falls andere Teamgröße abgesprochen wurde)
$formAction='submit.php';
echo '<h1><b><font color="#FF0000"> Achtung Check-OVERRIDE: Wenn jetzt Fehler in der Tabelle stehen werden sie DIREKT in die Datenbank geschrieben!!! <br> Nur mit Absprache benutzen! </font> </b></h1><br>';
} else {
$formAction = 'errorCheck.php';
}
//******************************TABELLE BAUEN UND AUSFÜLLEN***************************************************************************************************************
?>
<br>
Klasse eingeben:
<form action="<?= $formAction ?>" method="post">
<input type="checkbox" name="k1" value="k1" <?= $k1 ?> tabindex=1> K1 <br>
<input type="text" name="klasse" required="required" value="<?= $klasse ?> " size="3" maxlength="3" tabindex=2/>
<table>
<!-- Fußball 1 + 2 & Fahrradtour & BB -->
<?php
$anzahlMannschaftZeilen = ceil($anzahlTeamsGesamt)/3; //3 mannschaften pro zeile, bm und tt zählen nicht
//echo "anzahl mannschaft zeilen: " . $anzahlMannschaftZeilen;
$mannschaftZeile=0; //zeile, in der mannschaften stehen
$mannschaftSpalte=0; //spalten, in denen mannschaften stehen != spalte mit vor und nachnamen, max größe = mannschaftenProZeile
$mannschaftenProZeile=3; //s.o.
$spalte=0; //spalte für die textfelder
$multiMannschaftSportart=0; //zähler für die mannschaften mit mehr als einem team pro zeile
//***************************TABELLE BAUEN********************************************************************
for (; $mannschaftZeile < $anzahlMannschaftZeilen; $mannschaftZeile++) {
//anzahl mannschaften in dieser zeile ausrechnen, für später
$mannschaftenDieseZeile = (count($sportartenVollerNameEinzeln))%($mannschaftenProZeile);
//echo ' count voller name: ' . (count($sportartenVollerName)/2) . ' mannschaft/zeile ' . ($mannschaftenProZeile) . '<br>';
//echo " diese zeile " . $mannschaftenDieseZeile . '<br>';
if ($mannschaftZeile < ($anzahlMannschaftZeilen-1) || $mannschaftenDieseZeile==0) {
$mannschaftenDieseZeile=3;
}
//**********überschrift bauen******************+
echo '<tr>' . " \n"; //es müssen " sein, damit er eine neue seite für den seitenquelltext einfügt
$oldMannschaftSpalte=$mannschaftSpalte; //spaltenanzahl von vorher speichern, für die länge der for schleife wichtig
$multiMannschaftSportart=0; //für jede zeile von vorn, gibt an, ob eine sportarten mehrere mannschaften in dieser zeile hat
for (; $mannschaftSpalte<($oldMannschaftSpalte+($mannschaftenProZeile-$multiMannschaftSportart)); $mannschaftSpalte++) { //for schleife soll 3 spalten ausgeben, ob es mehrere teams/sportart gibt beeinflusst die berechnung
echo '<td colspan="2"> ' . $sportartenVollerNameEinzeln[$mannschaftSpalte] . " \n"; //human readable mannschaftsnamen eintragen, 2 spalten da es vor und nachname gibt
}
echo "</tr> \n"; //zeilenende einfügen
echo '<tr>' . " \n"; //es müssen " sein, damit er eine neue seite für den seitenquelltext einfügt
for ($i=0; ($i<$mannschaftenProZeile) && $i<$mannschaftenDieseZeile; $i++) { //"vorname" und "nachname" einfügen
echo '<td> <b>Vorname' . " \n";
echo '<td> <b>Nachname' . " \n";
}
echo "</tr> \n";
//*********textfelder bauen***********
$oldSpalte=$spalte; //spaltenanzahl von vorher speichern, für die länge der for schleife wichtig
//die länge hängt mit der länge von anzahlspieler/mannschaft zusammen
for($zeile = 0; $zeile<count($sportarten1[0]); $zeile++) { //zeilenweise durch die tabelle
echo "<tr> \n"; //neue reihe erstellen
for($spalte=$oldSpalte ; ($spalte<$oldSpalte+($mannschaftenProZeile*2)) && ($spalte < (count($sportartenName)-4)); $spalte++) { //in jeder spalte die richtige mannschaft einfügen
//richtigen namen gemäß spalte wählen und richtige daten nach spalte und zeile
echo "<td> <input type=\"text\" name=\"" . $sportartenName[$spalte] . "[]\" value=\"" . $sportarten1[$spalte][$zeile] . "\" tabindex=" . $tabindex[$spalte] . " size=\"20\" maxlength=\"20\" /> \n";
//tabindex der spalte wird um zwei erhöht, da nach 22 (v) 23 (n) und danach dann wieder 24 (v) folgt
$tabindex[$spalte]+=2; //tabindexwert um 2 erhöhen für schönes eintippen
}
echo "</tr> \n"; //row beenden
}
}
?>
<tr>
<td colspan="8">
</tr>
<td colspan="2"> Badminton
<td colspan="2"> Tischtennis
<!-- <td colspan="2"> Staffellauf -->
</tr>
<tr>
<td> <b>Vorname
<td> <b>Nachname
<td> <b>Vorname
<td> <b>Nachname
<!--
<td> <b>Vorname
<td> <b>Nachname -->
</tr>
<?php
// $tabindex = array(1, 2, 19, 20, 37, 38, 55, 56);
//echo $tabindex[1];
$teamzaehler = 0; //zaehler für das einzutragende team alle 3 zeilen
$eintragZeile = 0; //zeile, in der ein textfeld ist (anzahl beginnend bei 0 und spieler1 von team1)
for($zeile = 0; $zeile < (((count($sportarten1[(count($sportarten1)-4)])/2))*3); $zeile++) {
$teamRow=0; //zeile in der ein teamname steht
$eintragZeile++;
echo "<tr> \n";
if ($zeile%3 == 0) { //team zeile (jede 3.)
$teamzaehler++;
echo "<td colspan=\"2\" style=\"text-align:center\"> Team " . $teamzaehler . "\n";
echo "<td colspan=\"2\" style=\"text-align:center\"> Team " . $teamzaehler . "\n";
$eintragZeile--;
$teamRow=1;
}
for($spalte = $anzahlTeamsGesamt*2; $spalte<($anzahlTeamsGesamt*2)+4; $spalte++) {
//echo "in der for schleife";
// echo $zeile%3;
if ($teamRow) {
break;
//$teamRow=0;
} else {
//echo $eintragZeile-1;
echo "<td> <input type=\"text\" name=\"" . $sportartenName[$spalte] . "[]\" value=\"" . $sportarten1[$spalte][$eintragZeile-1] . "\" tabindex=" . $tabindex[$spalte] . " size=\"20\" maxlength=\"20\" /> \n";
$tabindex[$spalte]+=2; //tabindexwert um 2 erhöhen für schönes eintippen
}
}
echo "</tr> \n";
}
?>
</table>
<!--- mannschaftsgrößen etc übergeben: -->
<input type="hidden" name="badmintonAnzahlTeams" value=" <?= $badmintonAnzahlTeams?>">
<input type="hidden" name="AnzahlSpielerMannschaft" value=" <?= $AnzahlSpielerMannschaft?>">
<?php
for ($i=0; $i < count($anzahlTeams); $i++) {
echo '<input type="hidden" name="anzahlTeams[]" value="' . $anzahlTeams[$i] . '">';
}
?>
<input type="hidden" name="debug" value="<?= $_POST['debug'] ?>">
<br>
<input type="checkbox" name="checkPassBox" value="1" >
<input type="text" name="checkPassText" /> Felder zum umgehen vom Check, nur in ausgewählten Fällen benutzen! <br>
Funktion bei Daniel/Sandesh erfragen. DEVELOPMENT PURPOSES ONLY. <br>
<br> Du bist sicher, dass alles stimmt? <br>
<input type="submit" name="submit" value="Alles Richtig?">
</form>
<br>
</body>
</html>
| dbahn25/SporttagePlaner | web/check.php | PHP | gpl-2.0 | 16,617 |
/** @format */
/**
* External dependencies
*/
import { compact, isEqual } from 'lodash';
/**
* Internal dependencies
*/
import { createReducer } from 'state/utils';
import {
WOOCOMMERCE_PRODUCT_CATEGORY_CREATE,
WOOCOMMERCE_PRODUCT_CATEGORY_UPDATE,
WOOCOMMERCE_PRODUCT_CATEGORY_EDIT,
WOOCOMMERCE_PRODUCT_CATEGORY_EDIT_CLEAR,
WOOCOMMERCE_PRODUCT_CATEGORY_UPDATED,
} from 'woocommerce/state/action-types';
import { getBucket } from '../helpers';
export default createReducer( null, {
[ WOOCOMMERCE_PRODUCT_CATEGORY_EDIT ]: editProductCategoryAction,
[ WOOCOMMERCE_PRODUCT_CATEGORY_EDIT_CLEAR ]: clearEditsAction,
[ WOOCOMMERCE_PRODUCT_CATEGORY_UPDATED ]: productCategoryUpdatedAction,
} );
function productCategoryUpdatedAction( edits, action ) {
const { originatingAction } = action;
if ( WOOCOMMERCE_PRODUCT_CATEGORY_CREATE === originatingAction.type ) {
const prevCategoryId = originatingAction.category.id;
const prevEdits = edits || {};
const prevCreates = prevEdits.creates || [];
const newCreates = compact(
prevCreates.map( category => {
if ( isEqual( prevCategoryId, category.id ) ) {
// Remove this create, it's no longer needed.
return undefined;
}
return category;
} )
);
return {
...prevEdits,
creates: newCreates.length ? newCreates : undefined,
};
}
if ( WOOCOMMERCE_PRODUCT_CATEGORY_UPDATE === originatingAction.type ) {
const prevCategoryId = originatingAction.category.id;
const prevEdits = edits || {};
const prevUpdates = prevEdits.updates || [];
const newUpdates = compact(
prevUpdates.map( category => {
if ( isEqual( prevCategoryId, category.id ) ) {
return undefined;
}
return category;
} )
);
return {
...prevEdits,
updates: newUpdates.length ? newUpdates : undefined,
};
}
// TODO: Add support for delete.
return edits;
}
function clearEditsAction() {
return null;
}
function editProductCategoryAction( edits, action ) {
const { category, data } = action;
const prevEdits = edits || {};
const bucket = getBucket( category );
const newArray = editProductCategory( prevEdits[ bucket ], category, data );
return {
...prevEdits,
[ bucket ]: newArray,
currentlyEditingId: category.id,
};
}
function editProductCategory( array, category, data ) {
const prevArray = array || [];
let found = false;
// Look for this object in the appropriate create or edit array first.
const newArray = compact(
prevArray.map( c => {
if ( isEqual( category.id, c.id ) ) {
found = true;
// If data is null, remove this edit, otherwise update the edit data.
return data ? { ...c, ...data } : undefined;
}
return c;
} )
);
if ( ! found ) {
// update or create not already in edit state, so add it now.
newArray.push( { id: category.id, ...data } );
}
return newArray;
}
| Automattic/woocommerce-connect-client | client/extensions/woocommerce/state/ui/product-categories/edits-reducer.js | JavaScript | gpl-2.0 | 2,847 |
/**
*****************************************************************************
@example receive.c
@brief receive data packets and write content of packet on SD card
and send via uart with RSSI
Note that VAR_LENGTH must have the same value in transmit.c and receive.c
@version V1.0 initialization
@author Peter Soltys
@date July 2015
@par Revision History:
- V1.0, July 2015 : initial version.
All files for ADuCRF101 provided by ADI, including this file, are
provided as is without warranty of any kind, either expressed or implied.
The user assumes any and all risk from the use of this code.
It is the responsibility of the person integrating this code into an application
to ensure that the resulting application performs as required and is safe.
**/
#include "include.h"
#include "SD_SPI/ff.h"
#define VAR_LENGTH 1
unsigned char Buffer[255];
RIE_U8 PktLen;
RIE_S8 RSSI;
RIE_Responses RIE_Response = RIE_Success;
FATFS FatFs;
FIL fil; /* File object */
FRESULT fr; /* FatFs return code */
int i,j;
void Delay(void)
{
volatile int iDelay = 0x1FFFF;
while (iDelay--);
}
/*
*inicializovanie uart portu
* rychlost 19200 baud
* 8 bitov
* jeden stop bit
* vystup port P1.0\P1.1
*/
void uart_init(void){
UrtLinCfg(0,19200,COMLCR_WLS_8BITS,COMLCR_STOP_DIS);
DioCfg(pADI_GP1,0x9); // UART functionality on P1.0\P1.1
}
/*
* inicializovanie portu na ktorom je pripojena user specified led
*/
void led_init(void){
// P4.2 as output
DioCfg(pADI_GP4,0x10);
DioOen(pADI_GP4, BIT2);
}
/*
* function for initialise the Radio
*/
void Radio_init(void){
// Initialise the Radio
if (RIE_Response == RIE_Success)
RIE_Response = RadioInit(DR_38_4kbps_Dev20kHz);
// Set the Frequency to operate at 915 MHz
if (RIE_Response == RIE_Success)
RIE_Response = RadioSetFrequency(915000000);
}
/*
* function receive one packet from radio
*/
void Radio_recieve(void){//pocka na prijatie jedneho paketu
if (RIE_Response == RIE_Success)
{
if (VAR_LENGTH)
RIE_Response = RadioRxPacketVariableLen();
else
RIE_Response = RadioRxPacketFixedLen(12);
//printf("waiting for a packet\n");
}
if (RIE_Response == RIE_Success)
{
while (!RadioRxPacketAvailable());
}
if (RIE_Response == RIE_Success)
RIE_Response = RadioRxPacketRead(sizeof(Buffer),
&PktLen,
Buffer,
&RSSI);
}
/*
* parameter str [out] return name of text file
* example "signal.txt"
*/
void get_txt_name(char * str){
int len=3;
while(1){
Radio_recieve();//cakanie na prijatie nazvu suboru
if (RIE_Response == RIE_Success)
{
if(Buffer[0]=='#'){
if(Buffer[1]=='@'){
if(Buffer[2]=='#'){
while(Buffer[len]!='\0'){
str[len-3]=Buffer[len];
len++;
}
break;
}
}
}
}
}
}
/*
* inicializovanie karty vytvorenie textoveho suboru signal.txt
* s nalogovanymi hodnotamy urovni signalu meranych pri prime
*/
void SD_init(void){
char str[30];
fr=f_mount(&FatFs, "", 0);//inicializacia SD karty
printf("inicializujem kartu");
if(fr)printf("chyba pri inicializacii karty (alebo SPI) %d \n",fr);
//vytvorenie textoveho suboru
get_txt_name(str);//pocka na prijatie paketu s nazvom suboru
fr = f_open(&fil, str , FA_WRITE|FA_CREATE_ALWAYS);
printf("vytvaram subor %s",str);
if(fr)printf("chyba pri vytvarani suboru %d \n",fr);
Radio_recieve();//cakanie na prijatie hlavicky suboru
fr = f_printf(&fil,"%s",Buffer);//hlavicka v txt subore
}
int main(void)
{
WdtGo(T3CON_ENABLE_DIS);//stop watch-dog
uart_init();
led_init();
Radio_init();//inicializuje radio prenos
SD_init();//nacita kartu a vytvori subor prijaty cez radio prenos
for(i=0;i<29;i++){
Radio_recieve();//pocka na prijatie jedneho paketu
if (RIE_Response == RIE_Success)
{
printf("\n\r-> %s \n@ RSSI %d ",Buffer,(int)RSSI);
fr = f_printf(&fil,"\n\r-> %s \n@ RSSI %d \n",Buffer,(int)RSSI);
}
else
{
printf("\n\r-> ERROR");
fr = f_printf(&fil,"\n\r-> ERROR");
}
}
RIE_Response = RadioTerminateRadioOp();
fr=f_close(&fil);//koiec zapisu na kartu
printf("\nzatvaram\n");
if(fr)printf("chyba pri zatvarani suboru %d\n",fr);
while (1)//ukonceny zapis
{
DioTgl(pADI_GP4,BIT2);
Delay();
}
}
| petersoltys/Time-multiplex-ADuc-RF101 | src/Receive.c | C | gpl-2.0 | 4,388 |
<?php
/**
* File contains: eZ\Publish\Core\Repository\Tests\Service\Integration\Legacy\NameSchemaTest class
*
* @copyright Copyright (C) 1999-2014 eZ Systems AS. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
* @version //autogentag//
*/
namespace eZ\Publish\Core\Repository\Tests\Service\Integration\Legacy;
use eZ\Publish\Core\Repository\Tests\Service\Integration\NameSchemaBase as BaseNameSchemaTest;
/**
* Test case for NameSchema Service using Legacy storage class
*/
class NameSchemaTest extends BaseNameSchemaTest
{
protected function getRepository()
{
return Utils::getRepository();
}
}
| glye/ezpublish-kernel | eZ/Publish/Core/Repository/Tests/Service/Integration/Legacy/NameSchemaTest.php | PHP | gpl-2.0 | 681 |
#include"stdlib.h"
#include"stdio.h"
//////you can use stack to storage different type of data/////
#define ElemType int
struct stackNode{
ElemType data;
stackNode* next;
};
struct stack{
stackNode* top;
};
/////do the initialization//////
void initStack(stack &s){
s.top = NULL;
}
bool empty(stack s){
if(s.top)
return false;
return true;
}
ElemType top(stack s){
return s.top->data;
}
void push(stack &s, ElemType data_){
stackNode* newNode = (stackNode*)malloc(sizeof(stackNode));
newNode->data = data_;
newNode->next = s.top;
s.top = newNode;
}
void pop(stack &s){
stackNode* temp = s.top;
s.top = s.top->next;
free(temp);
}
void destroy(stack &s){
stackNode* temp;
while(s.top){
temp = s.top;
s.top = s.top->next;
free(temp);
}
}
/////now this is the test/////
int main(){
// #undef ElemType
// #define ElemType char
stack s;
initStack(s);
push(s,3);
printf("%d \n",top(s));
// pop(s);
if(empty(s))
printf("The stack is empty! \n");
else
printf("The stack is not empty! \n");
return 1;
} | smileboywtu/C-projects | c-datestructure/stack/Linkstack/PrimaryStack/stack.cpp | C++ | gpl-2.0 | 1,039 |
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Language.h"
#include "WorldPacket.h"
#include "Common.h"
#include "ObjectMgr.h"
#include "TicketMgr.h"
#include "Player.h"
#include "World.h"
#include "WorldSession.h"
#include "Util.h"
void WorldSession::HandleGMTicketCreateOpcode(WorldPacket & recv_data)
{
// Don't accept tickets if the ticket queue is disabled. (Ticket UI is greyed out but not fully dependable)
if (sTicketMgr->GetStatus() == GMTICKET_QUEUE_STATUS_DISABLED)
return;
if (GetPlayer()->getLevel() < sWorld->getIntConfig(CONFIG_TICKET_LEVEL_REQ))
{
SendNotification(GetTrinityString(LANG_TICKET_REQ), sWorld->getIntConfig(CONFIG_TICKET_LEVEL_REQ));
return;
}
if (sTicketMgr->GetGMTicketByPlayer(GetPlayer()->GetGUID()))
{
WorldPacket data(SMSG_GMTICKET_CREATE, 4);
data << uint32(GMTICKET_RESPONSE_FAILURE); // You already have GM ticket
SendPacket(&data);
return;
}
uint32 map, unk1;
uint8 needResponse; // ignored
float x, y, z;
std::string ticketText, ticketText2;
SendQueryTimeResponse();
recv_data >> map;
recv_data >> x;
recv_data >> y;
recv_data >> z;
recv_data >> ticketText;
recv_data >> unk1; // not sure what this is... replyTo?
recv_data >> needResponse; // always 1/0 -- not sure what retail does with this
GM_Ticket *ticket = new GM_Ticket;
ticket->name = GetPlayer()->GetName();
ticket->guid = sTicketMgr->GenerateGMTicketId();
ticket->playerGuid = GetPlayer()->GetGUID();
ticket->message = ticketText;
ticket->createtime = time(NULL);
ticket->map = map;
ticket->pos_x = x;
ticket->pos_y = y;
ticket->pos_z = z;
ticket->timestamp = time(NULL);
ticket->closed = 0;
ticket->assignedToGM = 0;
ticket->comment = "";
ticket->completed = false;
ticket->escalated = TICKET_UNASSIGNED;
ticket->response = "";
sTicketMgr->AddOrUpdateGMTicket(*ticket, true);
WorldPacket data(SMSG_GMTICKET_CREATE, 4);
data << uint32(GMTICKET_RESPONSE_SUCCESS);
SendPacket(&data);
sWorld->SendGMText(LANG_COMMAND_TICKETNEW, GetPlayer()->GetName(), ticket->guid);
}
void WorldSession::HandleGMTicketUpdateOpcode(WorldPacket & recv_data)
{
std::string message;
recv_data >> message;
GM_Ticket *ticket = sTicketMgr->GetGMTicketByPlayer(GetPlayer()->GetGUID());
if (!ticket)
{
WorldPacket data(SMSG_GMTICKET_UPDATETEXT, 4);
data << uint32(GMTICKET_RESPONSE_FAILURE);
SendPacket(&data);
return;
}
ticket->message = message;
ticket->timestamp = time(NULL);
sTicketMgr->AddOrUpdateGMTicket(*ticket);
WorldPacket data(SMSG_GMTICKET_UPDATETEXT, 4);
data << uint32(GMTICKET_RESPONSE_SUCCESS);
SendPacket(&data);
sWorld->SendGMText(LANG_COMMAND_TICKETUPDATED, GetPlayer()->GetName(), ticket->guid);
}
void WorldSession::HandleGMTicketDeleteOpcode(WorldPacket & /*recv_data*/)
{
GM_Ticket* ticket = sTicketMgr->GetGMTicketByPlayer(GetPlayer()->GetGUID());
if (ticket)
{
WorldPacket data(SMSG_GMTICKET_DELETETICKET, 4);
data << uint32(GMTICKET_RESPONSE_TICKET_DELETED);
SendPacket(&data);
sWorld->SendGMText(LANG_COMMAND_TICKETPLAYERABANDON, GetPlayer()->GetName(), ticket->guid);
sTicketMgr->RemoveGMTicket(ticket, GetPlayer()->GetGUID(), false);
SendGMTicketGetTicket(GMTICKET_STATUS_DEFAULT, NULL);
}
}
void WorldSession::HandleGMTicketGetTicketOpcode(WorldPacket & /*recv_data*/)
{
SendQueryTimeResponse();
if (GM_Ticket *ticket = sTicketMgr->GetGMTicketByPlayer(GetPlayer()->GetGUID()))
{
if (ticket->completed)
SendGMTicketResponse(ticket);
else
SendGMTicketGetTicket(GMTICKET_STATUS_HASTEXT, ticket->message.c_str(), ticket);
}
else
SendGMTicketGetTicket(GMTICKET_STATUS_DEFAULT, NULL);
}
void WorldSession::HandleGMTicketSystemStatusOpcode(WorldPacket & /*recv_data*/)
{
WorldPacket data(SMSG_GMTICKET_SYSTEMSTATUS, 4);
// Note: This only disables the ticket UI at client side and is not fully reliable
// are we sure this is a uint32? Should ask Zor
data << uint32(sTicketMgr->GetStatus() ? GMTICKET_QUEUE_STATUS_ENABLED : GMTICKET_QUEUE_STATUS_DISABLED);
SendPacket(&data);
}
void WorldSession::SendGMTicketGetTicket(uint32 status, char const* text, GM_Ticket *ticket /* = NULL */)
{
int len = text ? strlen(text) : 0;
WorldPacket data(SMSG_GMTICKET_GETTICKET, (4+4+((status == GMTICKET_STATUS_HASTEXT) ? (len+1+4+4+4+1+1) : 0)));
data << uint32(status); // standard 0x0A, 0x06 if text present
data << uint32(1); // g_HasActiveGMTicket -- not a flag
if (status == GMTICKET_STATUS_HASTEXT)
{
data << text; // ticket text
data << uint8(0x7); // ticket category; why is this hardcoded? does it make a diff re: client?
// we've got the easy stuff done by now.
// Now we need to go through the client logic for displaying various levels of ticket load
if (ticket)
{
// get ticketage, but it's stored in seconds so we have to do it in days
float ticketAge = (float)time(NULL) - (float)ticket->timestamp;
ticketAge /= DAY;
data << float(ticketAge); // ticketAge (days)
if (GM_Ticket *oldestTicket = sTicketMgr->GetOldestOpenGMTicket())
{
// get ticketage, but it's stored in seconds so we have to do it in days
float oldestTicketAge = (float)time(NULL) - (float)oldestTicket->timestamp;
oldestTicketAge /= DAY;
data << float(oldestTicketAge);
}
else
data << float(0);
// I am not sure how blizzlike this is, and we don't really have a way to find out
int64 lastChange = int64(sTicketMgr->GetLastChange());
float timeDiff = float(int64(time(NULL)) - lastChange);
timeDiff /= DAY;
data << float(timeDiff);
data << uint8(std::min(ticket->escalated, uint8(TICKET_IN_ESCALATION_QUEUE))); // escalated data
data << uint8(ticket->viewed ? GMTICKET_OPENEDBYGM_STATUS_OPENED : GMTICKET_OPENEDBYGM_STATUS_NOT_OPENED); // whether or not it has been viewed
}
else
{
// we can't actually get any numbers here...
data << float(0);
data << float(0);
data << float(1);
data << uint8(0);
data << uint8(0);
}
}
SendPacket(&data);
}
void WorldSession::SendGMTicketResponse(GM_Ticket *ticket)
{
if (!ticket)
return;
WorldPacket data(SMSG_GMRESPONSE_RECEIVED);
data << uint32(1); // unk? Zor says "hasActiveTicket"
data << uint32(0); // can-edit - always 1 or 0, not flags
data << ticket->message.c_str();
data << ticket->response.c_str();
for (int8 j = 0; j < 3; j++)
data << uint8(0); // 3 null strings
SendPacket(&data);
}
void WorldSession::HandleGMSurveySubmit(WorldPacket& recv_data)
{
uint64 nextSurveyID = sTicketMgr->GetNextSurveyID();
// just put the survey into the database
std::ostringstream ss;
uint32 mainSurvey; // GMSurveyCurrentSurvey.dbc, column 1 (all 9) ref to GMSurveySurveys.dbc
recv_data >> mainSurvey;
ss << "INSERT INTO gm_surveys (player, surveyid, mainSurvey, overall_comment, timestamp) VALUES (";
ss << GetPlayer()->GetGUID() << ", ";
ss << uint32(nextSurveyID) << ", ";
ss << mainSurvey << ", ";
// sub_survey1, r1, comment1, sub_survey2, r2, comment2, sub_survey3, r3, comment3, sub_survey4, r4, comment4, sub_survey5, r5, comment5, sub_survey6, r6, comment6, sub_survey7, r7, comment7, sub_survey8, r8, comment8, sub_survey9, r9, comment9, sub_survey10, r10, comment10,
for (uint8 i = 0; i < 10; i++)
{
std::ostringstream os;
os << "INSERT INTO gm_subsurveys (surveyid, subsurveyid, rank, comment) VALUES (";
uint32 subSurveyId; // ref to i'th GMSurveySurveys.dbc field (all fields in that dbc point to fields in GMSurveyQuestions.dbc)
recv_data >> subSurveyId;
if(!subSurveyId)
break;
uint8 rank; // probably some sort of ref to GMSurveyAnswers.dbc
std::string comment; // comment ("Usage: GMSurveyAnswerSubmit(question, rank, comment)")
recv_data >> rank;
recv_data >> comment;
os << uint32(nextSurveyID) << " ";
os << subSurveyId << ", ";
os << uint16(rank) << ", '";
CharacterDatabase.escape_string(comment);
os << comment << "');";
CharacterDatabase.PExecute(os.str().c_str());
}
std::string comment; // just a guess
recv_data >> comment;
CharacterDatabase.escape_string(comment);
ss << "'" << comment << "', ";
ss << int64(time_t(NULL)) << ");";
CharacterDatabase.PExecute(ss.str().c_str());
}
void WorldSession::HandleReportLag(WorldPacket& recv_data)
{
// just put the lag report into the database...
// can't think of anything else to do with it
uint32 lagType, mapId;
float x, y, z;
recv_data >> lagType;
recv_data >> mapId;
recv_data >> x;
recv_data >> y;
recv_data >> z;
// build and execute query
std::ostringstream os;
os << "INSERT INTO lag_reports (player, lag_type, map, posX, posY, posZ) VALUES (";
os << GetPlayer()->GetGUID() << ", ";
os << lagType << ", ";
os << mapId << ", ";
os << x << ", ";
os << y << ", ";
os << z << ");";
CharacterDatabase.Execute(os.str().c_str());
}
void WorldSession::HandleGMResponseResolve(WorldPacket& /*recvPacket*/)
{
// empty packet
GM_Ticket* ticket = sTicketMgr->GetGMTicketByPlayer(GetPlayer()->GetGUID());
if (ticket)
{
uint8 getSurvey = 0;
if ((float)rand_chance() < sWorld->getFloatConfig(CONFIG_CHANCE_OF_GM_SURVEY))
getSurvey = 1;
WorldPacket data(SMSG_GMRESPONSE_STATUS_UPDATE, 4);
data << uint8(getSurvey);
SendPacket(&data);
WorldPacket data2(SMSG_GMTICKET_DELETETICKET, 4);
data2 << uint32(GMTICKET_RESPONSE_TICKET_DELETED);
SendPacket(&data2);
sTicketMgr->RemoveGMTicket(ticket, GetPlayer()->GetGUID(), true);
SendGMTicketGetTicket(GMTICKET_STATUS_DEFAULT, NULL);
}
}
| Gamerzon94/wowrean-emu | src/server/game/Server/Protocol/Handlers/TicketHandler.cpp | C++ | gpl-2.0 | 11,251 |
daumenkivy-web
==============
Website for the daumenkivy app.
| antrew/daumenkivy-web | README.md | Markdown | gpl-2.0 | 63 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_stream_socket::message_peek</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../basic_stream_socket.html" title="basic_stream_socket">
<link rel="prev" href="message_out_of_band.html" title="basic_stream_socket::message_out_of_band">
<link rel="next" href="native.html" title="basic_stream_socket::native">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="message_out_of_band.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_stream_socket.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="native.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_asio.reference.basic_stream_socket.message_peek"></a><a class="link" href="message_peek.html" title="basic_stream_socket::message_peek">basic_stream_socket::message_peek</a>
</h4></div></div></div>
<p>
<span class="emphasis"><em>Inherited from socket_base.</em></span>
</p>
<p>
<a class="indexterm" name="id1215677"></a>
Peek at incoming data without removing it
from the input queue.
</p>
<pre class="programlisting"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">int</span> <span class="identifier">message_peek</span> <span class="special">=</span> <span class="identifier">implementation_defined</span><span class="special">;</span>
</pre>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2011 Christopher
M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="message_out_of_band.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_stream_socket.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="native.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| geodynamics/gale | boost/doc/html/boost_asio/reference/basic_stream_socket/message_peek.html | HTML | gpl-2.0 | 3,542 |
package main.list.structure;
/** Created by martin on 29.7.13. */
public class BasketListItem extends CommonListItem {
private static final long serialVersionUID = -2824687856810769231L;
protected double price;
protected boolean buyed;
public BasketListItem(String name, double price) {
this(name, price, false);
}
public BasketListItem(String name, double price, boolean buyed) {
super(name, "");
this.price = (price < 0.0) ? 0.0 : price;
this.buyed = buyed;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public boolean isBuyed() {
return buyed;
}
public void setBuyed(boolean buyed) {
this.buyed = buyed;
}
@Override
public int getSubItemCount() {
return -1;
}
}
| marty-cz/desktop-basket | src/main/list/structure/BasketListItem.java | Java | gpl-2.0 | 805 |
import { translate } from 'i18n-calypso';
import { registerHandlers } from 'calypso/state/data-layer/handler-registry';
import { bypassDataLayer } from 'calypso/state/data-layer/utils';
import { http } from 'calypso/state/data-layer/wpcom-http/actions';
import { dispatchRequest } from 'calypso/state/data-layer/wpcom-http/utils';
import { errorNotice } from 'calypso/state/notices/actions';
import { READER_UNSUBSCRIBE_TO_NEW_POST_NOTIFICATIONS } from 'calypso/state/reader/action-types';
import { subscribeToNewPostNotifications } from 'calypso/state/reader/follows/actions';
const noop = () => {};
export function fromApi( response ) {
const isUnsubscribed = !! ( response && response.subscribed === false );
if ( ! isUnsubscribed ) {
throw new Error(
`Unsubscription from new post notifications failed with response: ${ JSON.stringify(
response
) }`
);
}
return response;
}
export function requestNotificationUnsubscription( action ) {
return http(
{
method: 'POST',
apiNamespace: 'wpcom/v2',
path: `/read/sites/${ action.payload.blogId }/notification-subscriptions/delete`,
body: {}, // have to have an empty body to make wpcom-http happy
},
action
);
}
export function receiveNotificationUnsubscriptionError( action ) {
return [
errorNotice(
translate( 'Sorry, we had a problem unsubscribing you from notifications. Please try again.' )
),
bypassDataLayer( subscribeToNewPostNotifications( action.payload.blogId ) ),
];
}
registerHandlers( 'state/data-layer/wpcom/read/sites/notification-subscriptions/delete/index.js', {
[ READER_UNSUBSCRIBE_TO_NEW_POST_NOTIFICATIONS ]: [
dispatchRequest( {
fetch: requestNotificationUnsubscription,
onSuccess: noop,
onError: receiveNotificationUnsubscriptionError,
fromApi,
} ),
],
} );
| Automattic/wp-calypso | client/state/data-layer/wpcom/read/sites/notification-subscriptions/delete/index.js | JavaScript | gpl-2.0 | 1,802 |
/* This file is part of KGraphViewer.
Copyright (C) 2005-2007 Gael de Chalendar <kleag@free.fr>
KGraphViewer 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.
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
*/
/* This file was callgraphview.cpp, part of KCachegrind.
Copyright (C) 2003 Josef Weidendorfer <Josef.Weidendorfer@gmx.de>
KCachegrind 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.
*/
/*
* Callgraph View
*/
#include "canvasnode.h"
#include "dotgraphview.h"
#include "graphnode.h"
#include "dotdefaults.h"
#include "dot2qtconsts.h"
#include "FontsCache.h"
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <QGraphicsScene>
#include <QMatrix>
#include <QPainter>
#include <QStyle>
#include <QPolygonF>
#include <QPixmap>
///#include <kdebug.h>
///#include <klocale.h>
///namespace KGraphViewer
///{
CanvasNode::CanvasNode(DotGraphView* v,
GraphNode* s,
QGraphicsScene* c,
QGraphicsItem* parent)
: CanvasElement(v,(GraphElement*)s, c, parent)
{
///kDebug() << s->id();
connect(s,SIGNAL(changed()),this,SLOT(modelChanged()));
QString tipStr;
QString id = s->id();
QString label = s->label();
tipStr = QString("id='%1'\nlabel='%2'").arg(id).arg(label);
// kDebug() << "CanvasEllipseNode setToolTip " << tipStr;
setToolTip(tipStr);
}
// CanvasHtmlNode::CanvasHtmlNode(
// DotGraphView* v,
// GraphNode* n,
// const DotRenderOp& dro,
// const DotRenderOpVec& dros,
// QGraphicsScene* c,
// double scaleX, double scaleY,
// int xMargin, int yMargin, int gh,
// int wdhcf, int hdvcf
// )
// : KHTMLPart(v->viewport()), CanvasNode(v, n)
// {
// m_renderOperations = dros;
// // kDebug() << "Creating "<<node()->id()<<" CanvasHtmlNode for" << n
// // << " with label '" << n->label() << "'";
//
// QString myHTMLCode = n->label();
// myHTMLCode = myHTMLCode.mid(1, myHTMLCode.length() - 2);
// // kDebug() << "HTML = " << myHTMLCode;
// begin(KUrl(QString("file:") + QDir::currentPath() + "/index.html"));
// setAutoloadImages(true);
// write(myHTMLCode);
// kDebug() << "HTML written.";
// end();
// setStatusMessagesEnabled (false);
// // view()->setFrameShape ( QFrame::NoFrame );
// // view()->setFrameShadow ( QFrame::Plain );
// // view()->setLineWidth ( 0 );
// // view()->setMidLineWidth ( 0 );
// // view()->setHScrollBarMode ( Q3ScrollView::AlwaysOff );
// // view()->setVScrollBarMode ( Q3ScrollView::AlwaysOff );
// view()->setMarginWidth(0);
// view()->setMarginHeight(0);
// m_zoomFactor = m_view->zoom();
// view()->part()->setZoomFactor(int(m_zoomFactor*100));
// view()->move(int(n->x()*scaleX*m_zoomFactor), int((gh-n->y())*scaleY*m_zoomFactor));
// view()->setMinimumSize(int(n->w()*scaleX),int(n->h()*scaleY*m_zoomFactor));
// view()->setMaximumSize(int(n->w()*scaleX),int(n->h()*scaleY*m_zoomFactor));
// view()->adjustSize();
// KHTMLPart::show();
// CanvasHtmlNode::connect(v, SIGNAL(contentsMoving ( int, int)), this, SLOT(move(int, int)));
// CanvasHtmlNode::connect(v, SIGNAL(zoomed (double)), this, SLOT(zoomed(double)));
// }
//
// CanvasHtmlNode::~CanvasHtmlNode()
// {
// KHTMLPart::hide();
// }
//
// // void CanvasHtmlNode::paint(QPainter& p)
// // {
// // view()->drawContents(&p);
// // }
//
// void CanvasHtmlNode::move(int x, int y)
// {
// // kDebug() << "CanvasHtmlNode::move("<<x<<", "<<y<<")";
// m_xMovedTo = x; m_yMovedTo = y;
// view()->move(int((node()->x())*m_scaleX*m_zoomFactor - m_xMovedTo), int((m_gh-node()->y())*m_scaleY*m_zoomFactor) - m_yMovedTo);
// // view()->move(int(x*m_scaleX), int((m_gh-y)*m_scaleY));
// }
//
// void CanvasHtmlNode::zoomed(double factor)
// {
// m_zoomFactor = factor;
// view()->part()->setZoomFactor(int(factor*100));
// view()->move(int(node()->x()*m_scaleX*m_zoomFactor - m_xMovedTo), int((m_gh-node()->y())*m_scaleY*m_zoomFactor - m_yMovedTo));
// view()->setMinimumSize(int(node()->w()*m_scaleX*m_zoomFactor),int(node()->h()*m_scaleY*m_zoomFactor));
// view()->setMaximumSize(int(node()->w()*m_scaleX*m_zoomFactor),int(node()->h()*m_scaleY*m_zoomFactor));
// view()->adjustSize();
// }
///}
//#include "canvasnode.moc"
| tonytheodore/tora | extlibs/libermodel/canvasnode.cpp | C++ | gpl-2.0 | 5,268 |
/*
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "LogWorker.h"
LogWorker::LogWorker()
: m_queue(HIGH_WATERMARK, LOW_WATERMARK)
{
ACE_Task_Base::activate(THR_NEW_LWP | THR_JOINABLE | THR_INHERIT_SCHED, 1);
}
LogWorker::~LogWorker()
{
m_queue.deactivate();
wait();
}
int LogWorker::enqueue(LogOperation* op)
{
return m_queue.enqueue(op);
}
int LogWorker::svc()
{
while (1)
{
LogOperation* request;
if (m_queue.dequeue(request) == -1)
break;
request->call();
delete request;
}
return 0;
}
| powerzilly/trinitycore | src/server/shared/Logging/LogWorker.cpp | C++ | gpl-2.0 | 1,306 |
# include <bits/stdc++.h>
typedef long long int lli;
using namespace std;
int a, b, c;
int rm(int x) {
int ret = 0;
int p = 1;
while (x > 0) {
if (x%10!=0) ret = ret + x%10 * p, p*=10;
x /= 10;
}
return ret;
}
int main()
{
cin >> a >> b; c = a + b;
if (rm(a) + rm(b) == rm(c)) cout << "YES" << endl;
else cout << "NO" << endl;
return 0;
}
| fyh/training | codeforces/#67/a.cpp | C++ | gpl-2.0 | 396 |
class User
include Queryable
scope :artists, ->{ includes(:avatar).where('creations_count > 0') }
scope :search_by, ->(query) { query.blank? ? all : where('upper(users.name) LIKE :query OR upper(users.email) LIKE :query', query: "#{query.upcase}%") }
scope :oldest, ->{ order(created_at: :asc) }
scope :newest, ->{ order(created_at: :desc) }
scope :by_cakes, ->{ order(creations_count: :desc) }
class Repository < SimpleDelegator
def initialize(connection = User)
@connection = connection
super(connection)
end
def ordered
connection.order(creations_count: :desc)
end
def search_with(params)
filter_by(search_filters_for(params))
end
private
attr_reader :connection
def search_filters_for(params)
query_builder_for(params) do |builder|
builder.if_present(:artists) do |relation, _|
relation.artists
end
builder.if_present(:q) do |relation, search_term|
relation.search_by(search_term)
end
builder.if_present(:sort) do |relation, direction|
case direction.try(:downcase)
when 'oldest'
relation.oldest
when 'newest'
relation.newest
else
relation.by_cakes
end
end
builder.if_missing(:sort) do |relation, direction|
relation.order(creations_count: :desc)
end
end
end
end
end
| cakeside/cakeside | app/models/user/repository.rb | Ruby | gpl-2.0 | 1,449 |
__author__ = 'Stephanie'
from ODMconnection import dbconnection
from readSensors import readSensors
from updateSensors import updateSensors
from createSensors import createSensors
from deleteSensors import deleteSensors
__all__ = [
'readSensors',
'updateSensors',
'createSensors',
'deleteSensors',
] | Castronova/EMIT | api_old/ODM2/Sensors/services/__init__.py | Python | gpl-2.0 | 319 |
/*
* Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
*
* Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Object.h"
#include "Player.h"
#include "BattleGround.h"
#include "Creature.h"
#include "MapManager.h"
#include "Language.h"
#include "Chat.h"
#include "SpellAuras.h"
#include "ArenaTeam.h"
#include "World.h"
#include "Util.h"
BattleGround::BattleGround()
{
m_TypeID = 0;
m_InstanceID = 0;
m_Status = 0;
m_EndTime = 0;
m_LastResurrectTime = 0;
m_Queue_type = MAX_BATTLEGROUND_QUEUES;
m_InvitedAlliance = 0;
m_InvitedHorde = 0;
m_ArenaType = 0;
m_IsArena = false;
m_Winner = 2;
m_StartTime = 0;
m_Events = 0;
m_IsRated = false;
m_BuffChange = false;
m_Name = "";
m_LevelMin = 0;
m_LevelMax = 0;
m_InBGFreeSlotQueue = false;
m_SetDeleteThis = false;
m_MaxPlayersPerTeam = 0;
m_MaxPlayers = 0;
m_MinPlayersPerTeam = 0;
m_MinPlayers = 0;
m_MapId = 0;
m_TeamStartLocX[BG_TEAM_ALLIANCE] = 0;
m_TeamStartLocX[BG_TEAM_HORDE] = 0;
m_TeamStartLocY[BG_TEAM_ALLIANCE] = 0;
m_TeamStartLocY[BG_TEAM_HORDE] = 0;
m_TeamStartLocZ[BG_TEAM_ALLIANCE] = 0;
m_TeamStartLocZ[BG_TEAM_HORDE] = 0;
m_TeamStartLocO[BG_TEAM_ALLIANCE] = 0;
m_TeamStartLocO[BG_TEAM_HORDE] = 0;
m_ArenaTeamIds[BG_TEAM_ALLIANCE] = 0;
m_ArenaTeamIds[BG_TEAM_HORDE] = 0;
m_ArenaTeamRatingChanges[BG_TEAM_ALLIANCE] = 0;
m_ArenaTeamRatingChanges[BG_TEAM_HORDE] = 0;
m_BgRaids[BG_TEAM_ALLIANCE] = NULL;
m_BgRaids[BG_TEAM_HORDE] = NULL;
m_PlayersCount[BG_TEAM_ALLIANCE] = 0;
m_PlayersCount[BG_TEAM_HORDE] = 0;
m_PrematureCountDown = false;
m_PrematureCountDown = 0;
m_HonorMode = BG_NORMAL;
}
BattleGround::~BattleGround()
{
// remove objects and creatures
// (this is done automatically in mapmanager update, when the instance is reset after the reset time)
int size = m_BgCreatures.size();
for(int i = 0; i < size; ++i)
{
DelCreature(i);
}
size = m_BgObjects.size();
for(int i = 0; i < size; ++i)
{
DelObject(i);
}
if(GetInstanceID())
{
WorldDatabase.PExecute("DELETE FROM creature_respawn WHERE instance = '%u'",GetInstanceID());
WorldDatabase.PExecute("DELETE FROM gameobject_respawn WHERE instance = '%u'",GetInstanceID());
CharacterDatabase.PExecute("DELETE FROM instance WHERE id = '%u'",GetInstanceID());
}
sBattleGroundMgr.RemoveBattleGround(GetInstanceID());
// unload map
if(Map * map = MapManager::Instance().FindMap(GetMapId(), GetInstanceID()))
if(map->IsBattleGroundOrArena())
((BattleGroundMap*)map)->SetUnload();
// remove from bg free slot queue
this->RemoveFromBGFreeSlotQueue();
}
void BattleGround::Update(time_t diff)
{
if(!GetPlayersSize() && !GetRemovedPlayersSize() && !GetReviveQueueSize())
//BG is empty
return;
m_StartTime += diff;
// WorldPacket data;
if(GetRemovedPlayersSize())
{
for(std::map<uint64, uint8>::iterator itr = m_RemovedPlayers.begin(); itr != m_RemovedPlayers.end(); ++itr)
{
Player *plr = objmgr.GetPlayer(itr->first);
switch(itr->second)
{
//following code is handled by event:
/*case 0:
sBattleGroundMgr.m_BattleGroundQueues[GetTypeID()].RemovePlayer(itr->first);
//RemovePlayerFromQueue(itr->first);
if(plr)
{
sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, this, plr->GetTeam(), plr->GetBattleGroundQueueIndex(m_TypeID), STATUS_NONE, 0, 0);
plr->GetSession()->SendPacket(&data);
}
break;*/
case 1: // currently in bg and was removed from bg
if(plr)
RemovePlayerAtLeave(itr->first, true, true);
else
RemovePlayerAtLeave(itr->first, false, false);
break;
case 2: // revive queue
RemovePlayerFromResurrectQueue(itr->first);
break;
default:
sLog.outError("BattleGround: Unknown remove player case!");
}
}
m_RemovedPlayers.clear();
}
// remove offline players from bg after 5 minutes
if(GetPlayersSize())
{
for(std::map<uint64, BattleGroundPlayer>::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr)
{
Player *plr = objmgr.GetPlayer(itr->first);
itr->second.LastOnlineTime += diff;
if(plr)
itr->second.LastOnlineTime = 0; // update last online time
else
if(itr->second.LastOnlineTime >= MAX_OFFLINE_TIME)
m_RemovedPlayers[itr->first] = 1; // add to remove list (BG)
}
}
m_LastResurrectTime += diff;
if (m_LastResurrectTime >= RESURRECTION_INTERVAL)
{
if(GetReviveQueueSize())
{
for(std::map<uint64, std::vector<uint64> >::iterator itr = m_ReviveQueue.begin(); itr != m_ReviveQueue.end(); ++itr)
{
Creature *sh = NULL;
for(std::vector<uint64>::iterator itr2 = (itr->second).begin(); itr2 != (itr->second).end(); ++itr2)
{
Player *plr = objmgr.GetPlayer(*itr2);
if(!plr)
continue;
if (!sh)
{
sh = ObjectAccessor::GetCreature(*plr, itr->first);
// only for visual effect
if (sh)
sh->CastSpell(sh, SPELL_SPIRIT_HEAL, true); // Spirit Heal, effect 117
}
plr->CastSpell(plr, SPELL_RESURRECTION_VISUAL, true); // Resurrection visual
m_ResurrectQueue.push_back(*itr2);
}
(itr->second).clear();
}
m_ReviveQueue.clear();
m_LastResurrectTime = 0;
}
else
// queue is clear and time passed, just update last resurrection time
m_LastResurrectTime = 0;
}
else if (m_LastResurrectTime > 500) // Resurrect players only half a second later, to see spirit heal effect on NPC
{
for(std::vector<uint64>::iterator itr = m_ResurrectQueue.begin(); itr != m_ResurrectQueue.end(); ++itr)
{
Player *plr = objmgr.GetPlayer(*itr);
if(!plr)
continue;
plr->ResurrectPlayer(1.0f);
plr->CastSpell(plr, SPELL_SPIRIT_HEAL_MANA, true);
ObjectAccessor::Instance().ConvertCorpseForPlayer(*itr);
}
m_ResurrectQueue.clear();
}
// if less then minimum players are in on one side, then start premature finish timer
if(GetStatus() == STATUS_IN_PROGRESS && !isArena() && sBattleGroundMgr.GetPrematureFinishTime() && (GetPlayersCountByTeam(ALLIANCE) < GetMinPlayersPerTeam() || GetPlayersCountByTeam(HORDE) < GetMinPlayersPerTeam()))
{
if(!m_PrematureCountDown)
{
m_PrematureCountDown = true;
m_PrematureCountDownTimer = sBattleGroundMgr.GetPrematureFinishTime();
SendMessageToAll(LANG_BATTLEGROUND_PREMATURE_FINISH_WARNING);
}
else if(m_PrematureCountDownTimer < diff)
{
// time's up!
EndBattleGround(0); // noone wins
m_PrematureCountDown = false;
}
else
{
uint32 newtime = m_PrematureCountDownTimer - diff;
// announce every minute
if(m_PrematureCountDownTimer != sBattleGroundMgr.GetPrematureFinishTime() && newtime / 60000 != m_PrematureCountDownTimer / 60000)
SendMessageToAll(LANG_BATTLEGROUND_PREMATURE_FINISH_WARNING);
m_PrematureCountDownTimer = newtime;
}
}
else if (m_PrematureCountDown)
m_PrematureCountDown = false;
if(GetStatus() == STATUS_WAIT_LEAVE)
{
// remove all players from battleground after 2 minutes
m_EndTime += diff;
if(m_EndTime >= TIME_TO_AUTOREMOVE) // 2 minutes
{
for(std::map<uint64, BattleGroundPlayer>::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr)
{
m_RemovedPlayers[itr->first] = 1; // add to remove list (BG)
}
// do not change any battleground's private variables
}
}
}
void BattleGround::SetTeamStartLoc(uint32 TeamID, float X, float Y, float Z, float O)
{
uint8 idx = GetTeamIndexByTeamId(TeamID);
m_TeamStartLocX[idx] = X;
m_TeamStartLocY[idx] = Y;
m_TeamStartLocZ[idx] = Z;
m_TeamStartLocO[idx] = O;
}
void BattleGround::SendPacketToAll(WorldPacket *packet)
{
for(std::map<uint64, BattleGroundPlayer>::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr)
{
Player *plr = objmgr.GetPlayer(itr->first);
if(plr)
plr->GetSession()->SendPacket(packet);
else
sLog.outError("BattleGround: Player " I64FMTD " not found!", itr->first);
}
}
void BattleGround::SendPacketToTeam(uint32 TeamID, WorldPacket *packet, Player *sender, bool self)
{
for(std::map<uint64, BattleGroundPlayer>::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr)
{
Player *plr = objmgr.GetPlayer(itr->first);
if(!plr)
{
sLog.outError("BattleGround: Player " I64FMTD " not found!", itr->first);
continue;
}
if(!self && sender == plr)
continue;
uint32 team = itr->second.Team;//GetPlayerTeam(plr->GetGUID());
if(!team) team = plr->GetTeam();
if(team == TeamID)
plr->GetSession()->SendPacket(packet);
}
}
void BattleGround::PlaySoundToAll(uint32 SoundID)
{
WorldPacket data;
sBattleGroundMgr.BuildPlaySoundPacket(&data, SoundID);
SendPacketToAll(&data);
}
void BattleGround::PlaySoundToTeam(uint32 SoundID, uint32 TeamID)
{
WorldPacket data;
for(std::map<uint64, BattleGroundPlayer>::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr)
{
Player *plr = objmgr.GetPlayer(itr->first);
if(!plr)
{
sLog.outError("BattleGround: Player " I64FMTD " not found!", itr->first);
continue;
}
uint32 team = itr->second.Team;//GetPlayerTeam(plr->GetGUID());
if(!team) team = plr->GetTeam();
if(team == TeamID)
{
sBattleGroundMgr.BuildPlaySoundPacket(&data, SoundID);
plr->GetSession()->SendPacket(&data);
}
}
}
void BattleGround::CastSpellOnTeam(uint32 SpellID, uint32 TeamID)
{
for(std::map<uint64, BattleGroundPlayer>::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr)
{
Player *plr = objmgr.GetPlayer(itr->first);
if(!plr)
{
sLog.outError("BattleGround: Player " I64FMTD " not found!", itr->first);
continue;
}
uint32 team = itr->second.Team;//GetPlayerTeam(plr->GetGUID());
if(!team) team = plr->GetTeam();
if(team == TeamID)
plr->CastSpell(plr, SpellID, true);
}
}
void BattleGround::YellToAll(Creature* creature, const char* text, uint32 language)
{
for(std::map<uint64, BattleGroundPlayer>::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr)
{
WorldPacket data(SMSG_MESSAGECHAT, 200);
Player *plr = objmgr.GetPlayer(itr->first);
if(!plr)
{
sLog.outError("BattleGround: Player " I64FMTD " not found!", itr->first);
continue;
}
creature->BuildMonsterChat(&data,CHAT_MSG_MONSTER_YELL,text,language,creature->GetName(),itr->first);
plr->GetSession()->SendPacket(&data);
}
}
void BattleGround::RewardHonorToTeam(uint32 Honor, uint32 TeamID)
{
for(std::map<uint64, BattleGroundPlayer>::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr)
{
Player *plr = objmgr.GetPlayer(itr->first);
if(!plr)
{
sLog.outError("BattleGround: Player " I64FMTD " not found!", itr->first);
continue;
}
uint32 team = itr->second.Team;//GetPlayerTeam(plr->GetGUID());
if(!team) team = plr->GetTeam();
if(team == TeamID)
UpdatePlayerScore(plr, SCORE_BONUS_HONOR, Honor);
}
}
void BattleGround::RewardReputationToTeam(uint32 faction_id, uint32 Reputation, uint32 TeamID)
{
FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction_id);
if(!factionEntry)
return;
for(std::map<uint64, BattleGroundPlayer>::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr)
{
Player *plr = objmgr.GetPlayer(itr->first);
if(!plr)
{
sLog.outError("BattleGround: Player " I64FMTD " not found!", itr->first);
continue;
}
uint32 team = itr->second.Team;//GetPlayerTeam(plr->GetGUID());
if(!team) team = plr->GetTeam();
if(team == TeamID)
plr->ModifyFactionReputation(factionEntry, Reputation);
}
}
void BattleGround::UpdateWorldState(uint32 Field, uint32 Value)
{
WorldPacket data;
sBattleGroundMgr.BuildUpdateWorldStatePacket(&data, Field, Value);
SendPacketToAll(&data);
}
void BattleGround::UpdateWorldStateForPlayer(uint32 Field, uint32 Value, Player *Source)
{
WorldPacket data;
sBattleGroundMgr.BuildUpdateWorldStatePacket(&data, Field, Value);
Source->GetSession()->SendPacket(&data);
}
void BattleGround::EndBattleGround(uint32 winner)
{
this->RemoveFromBGFreeSlotQueue();
uint32 almost_winning_team = HORDE;
ArenaTeam * winner_arena_team = NULL;
ArenaTeam * loser_arena_team = NULL;
uint32 loser_rating = 0;
uint32 winner_rating = 0;
WorldPacket data;
Player *Source = NULL;
const char *winmsg = "";
if(winner == ALLIANCE)
{
if(isBattleGround())
winmsg = GetTrinityString(LANG_BG_A_WINS);
else
winmsg = GetTrinityString(LANG_ARENA_GOLD_WINS);
PlaySoundToAll(SOUND_ALLIANCE_WINS); // alliance wins sound
SetWinner(WINNER_ALLIANCE);
}
else if(winner == HORDE)
{
if(isBattleGround())
winmsg = GetTrinityString(LANG_BG_H_WINS);
else
winmsg = GetTrinityString(LANG_ARENA_GREEN_WINS);
PlaySoundToAll(SOUND_HORDE_WINS); // horde wins sound
SetWinner(WINNER_HORDE);
}
else
{
SetWinner(3);
}
SetStatus(STATUS_WAIT_LEAVE);
m_EndTime = 0;
// arena rating calculation
if(isArena() && isRated())
{
if(winner == ALLIANCE)
{
winner_arena_team = objmgr.GetArenaTeamById(GetArenaTeamIdForTeam(ALLIANCE));
loser_arena_team = objmgr.GetArenaTeamById(GetArenaTeamIdForTeam(HORDE));
}
else if(winner == HORDE)
{
winner_arena_team = objmgr.GetArenaTeamById(GetArenaTeamIdForTeam(HORDE));
loser_arena_team = objmgr.GetArenaTeamById(GetArenaTeamIdForTeam(ALLIANCE));
}
if(winner_arena_team && loser_arena_team)
{
loser_rating = loser_arena_team->GetStats().rating;
winner_rating = winner_arena_team->GetStats().rating;
int32 winner_change = winner_arena_team->WonAgainst(loser_rating);
int32 loser_change = loser_arena_team->LostAgainst(winner_rating);
sLog.outDebug("--- Winner rating: %u, Loser rating: %u, Winner change: %u, Losser change: %u ---", winner_rating, loser_rating, winner_change, loser_change);
if(winner == ALLIANCE)
{
SetArenaTeamRatingChangeForTeam(ALLIANCE, winner_change);
SetArenaTeamRatingChangeForTeam(HORDE, loser_change);
}
else
{
SetArenaTeamRatingChangeForTeam(HORDE, winner_change);
SetArenaTeamRatingChangeForTeam(ALLIANCE, loser_change);
}
sLog.outArena("Arena match Type: %u for Team1Id: %u - Team2Id: %u ended. WinnerTeamId: %u. RatingChange: %i.", m_ArenaType, m_ArenaTeamIds[BG_TEAM_ALLIANCE], m_ArenaTeamIds[BG_TEAM_HORDE], winner_arena_team->GetId(), winner_change);
}
else
{
SetArenaTeamRatingChangeForTeam(ALLIANCE, 0);
SetArenaTeamRatingChangeForTeam(HORDE, 0);
}
}
if(!isArena()){
if(m_score[GetTeamIndexByTeamId(ALLIANCE)] == m_score[GetTeamIndexByTeamId(HORDE)])
almost_winning_team = 0; //no real winner
if(m_score[GetTeamIndexByTeamId(ALLIANCE)] > m_score[GetTeamIndexByTeamId(HORDE)])
almost_winning_team = ALLIANCE;
}
for(std::map<uint64, BattleGroundPlayer>::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr)
{
Player *plr = objmgr.GetPlayer(itr->first);
if(!plr)
{
sLog.outError("BattleGround: Player " I64FMTD " not found!", itr->first);
continue;
}
// should remove spirit of redemption
if(plr->HasAuraType(SPELL_AURA_SPIRIT_OF_REDEMPTION))
plr->RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT);
if(!plr->isAlive())
{
plr->ResurrectPlayer(1.0f);
plr->SpawnCorpseBones();
}
uint32 team = itr->second.Team;
if(!team) team = plr->GetTeam();
// per player calculation
if(isArena() && isRated() && winner_arena_team && loser_arena_team)
{
if(team == winner)
winner_arena_team->MemberWon(plr,loser_rating);
else
loser_arena_team->MemberLost(plr,winner_rating);
}
if(team == winner)
{
if(!Source)
Source = plr;
RewardMark(plr,ITEM_WINNER_COUNT);
UpdatePlayerScore(plr, SCORE_BONUS_HONOR, 20);
RewardQuest(plr);
}
else if(winner !=0)
{
RewardMark(plr,ITEM_LOSER_COUNT);
}
else if(winner == 0)
{
if(sWorld.getConfig(CONFIG_PREMATURE_BG_REWARD)) // We're feeling generous, giving rewards to people who not earned them ;)
{ //nested ifs for the win! its boring writing that, forgive me my unfunniness
if(almost_winning_team == team) //player's team had more points
RewardMark(plr,ITEM_WINNER_COUNT);
else
RewardMark(plr,ITEM_LOSER_COUNT); // if scores were the same, each team gets 1 mark.
}
}
plr->CombatStopWithPets(true);
BlockMovement(plr);
sBattleGroundMgr.BuildPvpLogDataPacket(&data, this);
plr->GetSession()->SendPacket(&data);
uint32 bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(GetTypeID(), GetArenaType());
sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, this, plr->GetTeam(), plr->GetBattleGroundQueueIndex(bgQueueTypeId), STATUS_IN_PROGRESS, TIME_TO_AUTOREMOVE, GetStartTime());
plr->GetSession()->SendPacket(&data);
}
if(isArena() && isRated() && winner_arena_team && loser_arena_team)
{
// update arena points only after increasing the player's match count!
//obsolete: winner_arena_team->UpdateArenaPointsHelper();
//obsolete: loser_arena_team->UpdateArenaPointsHelper();
// save the stat changes
winner_arena_team->SaveToDB();
loser_arena_team->SaveToDB();
// send updated arena team stats to players
// this way all arena team members will get notified, not only the ones who participated in this match
winner_arena_team->NotifyStatsChanged();
loser_arena_team->NotifyStatsChanged();
sLog.outDebug("Rated arena match between %s and %s finished, winner: %s", loser_arena_team->GetName().c_str(),winner_arena_team->GetName().c_str(),winner_arena_team->GetName().c_str());
}
// inform invited players about the removal
sBattleGroundMgr.m_BattleGroundQueues[sBattleGroundMgr.BGQueueTypeId(GetTypeID(), GetArenaType())].BGEndedRemoveInvites(this);
if(Source)
{
ChatHandler(Source).FillMessageData(&data, CHAT_MSG_BG_SYSTEM_NEUTRAL, LANG_UNIVERSAL, Source->GetGUID(), winmsg);
SendPacketToAll(&data);
}
}
uint32 BattleGround::GetBattlemasterEntry() const
{
switch(GetTypeID())
{
case BATTLEGROUND_AV: return 15972;
case BATTLEGROUND_WS: return 14623;
case BATTLEGROUND_AB: return 14879;
case BATTLEGROUND_EY: return 22516;
case BATTLEGROUND_NA: return 20200;
default: return 0;
}
}
void BattleGround::RewardMark(Player *plr,uint32 count)
{
// 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
if(plr->GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
return;
if(!plr || !count)
return;
BattleGroundMarks mark;
switch(GetTypeID())
{
case BATTLEGROUND_AV:
mark = ITEM_AV_MARK_OF_HONOR;
break;
case BATTLEGROUND_WS:
mark = ITEM_WS_MARK_OF_HONOR;
break;
case BATTLEGROUND_AB:
mark = ITEM_AB_MARK_OF_HONOR;
break;
case BATTLEGROUND_EY:
mark = ITEM_EY_MARK_OF_HONOR;
break;
default:
return;
}
if ( objmgr.GetItemPrototype( mark ) )
{
ItemPosCountVec dest;
uint32 no_space_count = 0;
uint8 msg = plr->CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, mark, count, &no_space_count );
if( msg != EQUIP_ERR_OK ) // convert to possible store amount
count -= no_space_count;
if(!dest.empty()) // can add some
if(Item* item = plr->StoreNewItem( dest, mark, true, 0))
plr->SendNewItem(item,count,false,true);
if(no_space_count > 0)
SendRewardMarkByMail(plr,mark,no_space_count);
}
}
void BattleGround::SendRewardMarkByMail(Player *plr,uint32 mark, uint32 count)
{
uint32 bmEntry = GetBattlemasterEntry();
if(!bmEntry)
return;
ItemPrototype const* markProto = objmgr.GetItemPrototype(mark);
if(!markProto)
return;
if(Item* markItem = Item::CreateItem(mark,count,plr))
{
// save new item before send
markItem->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
// item
MailItemsInfo mi;
mi.AddItem(markItem->GetGUIDLow(), markItem->GetEntry(), markItem);
// subject: item name
std::string subject = markProto->Name1;
int loc_idx = plr->GetSession()->GetSessionDbLocaleIndex();
if ( loc_idx >= 0 )
if(ItemLocale const *il = objmgr.GetItemLocale(markProto->ItemId))
if (il->Name.size() > size_t(loc_idx) && !il->Name[loc_idx].empty())
subject = il->Name[loc_idx];
// text
std::string textFormat = plr->GetSession()->GetTrinityString(LANG_BG_MARK_BY_MAIL);
char textBuf[300];
snprintf(textBuf,300,textFormat.c_str(),GetName(),GetName());
uint32 itemTextId = objmgr.CreateItemText( textBuf );
WorldSession::SendMailTo(plr, MAIL_CREATURE, MAIL_STATIONERY_NORMAL, bmEntry, plr->GetGUIDLow(), subject, itemTextId , &mi, 0, 0, MAIL_CHECK_MASK_NONE);
}
}
void BattleGround::RewardQuest(Player *plr)
{
// 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
if(plr->GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
return;
uint32 quest;
switch(GetTypeID())
{
case BATTLEGROUND_AV:
quest = SPELL_AV_QUEST_REWARD;
break;
case BATTLEGROUND_WS:
quest = SPELL_WS_QUEST_REWARD;
break;
case BATTLEGROUND_AB:
quest = SPELL_AB_QUEST_REWARD;
break;
case BATTLEGROUND_EY:
quest = SPELL_EY_QUEST_REWARD;
break;
default:
return;
}
plr->CastSpell(plr, quest, true);
}
void BattleGround::BlockMovement(Player *plr)
{
plr->SetClientControl(plr, 0); // movement disabled NOTE: the effect will be automatically removed by client when the player is teleported from the battleground, so no need to send with uint8(1) in RemovePlayerAtLeave()
}
void BattleGround::RemovePlayerAtLeave(uint64 guid, bool Transport, bool SendPacket)
{
uint32 team = GetPlayerTeam(guid);
bool participant = false;
// Remove from lists/maps
std::map<uint64, BattleGroundPlayer>::iterator itr = m_Players.find(guid);
if(itr != m_Players.end())
{
UpdatePlayersCountByTeam(team, true); // -1 player
m_Players.erase(itr);
// check if the player was a participant of the match, or only entered through gm command (goname)
participant = true;
}
std::map<uint64, BattleGroundScore*>::iterator itr2 = m_PlayerScores.find(guid);
if(itr2 != m_PlayerScores.end())
{
delete itr2->second; // delete player's score
m_PlayerScores.erase(itr2);
}
RemovePlayerFromResurrectQueue(guid);
Player *plr = objmgr.GetPlayer(guid);
// should remove spirit of redemption
if(plr && plr->HasAuraType(SPELL_AURA_SPIRIT_OF_REDEMPTION))
plr->RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT);
if(plr && !plr->isAlive()) // resurrect on exit
{
plr->ResurrectPlayer(1.0f);
plr->SpawnCorpseBones();
}
RemovePlayer(plr, guid); // BG subclass specific code
DecreaseInvitedCount(team);
if(plr)
{
plr->ClearAfkReports();
if(participant) // if the player was a match participant, remove auras, calc rating, update queue
{
if(!team) team = plr->GetTeam();
uint32 bgTypeId = GetTypeID();
uint32 bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(GetTypeID(), GetArenaType());
// if arena, remove the specific arena auras
if(isArena())
{
plr->RemoveArenaAuras(true); // removes debuffs / dots etc., we don't want the player to die after porting out
bgTypeId=BATTLEGROUND_AA; // set the bg type to all arenas (it will be used for queue refreshing)
// summon old pet if there was one and there isn't a current pet
if(!plr->GetPet() && plr->GetTemporaryUnsummonedPetNumber())
{
Pet* NewPet = new Pet;
if(!NewPet->LoadPetFromDB(plr, 0, (plr)->GetTemporaryUnsummonedPetNumber(), true))
delete NewPet;
(plr)->SetTemporaryUnsummonedPetNumber(0);
}
if(isRated() && GetStatus() == STATUS_IN_PROGRESS)
{
//left a rated match while the encounter was in progress, consider as loser
ArenaTeam * winner_arena_team = 0;
ArenaTeam * loser_arena_team = 0;
if(team == HORDE)
{
winner_arena_team = objmgr.GetArenaTeamById(GetArenaTeamIdForTeam(ALLIANCE));
loser_arena_team = objmgr.GetArenaTeamById(GetArenaTeamIdForTeam(HORDE));
}
else
{
winner_arena_team = objmgr.GetArenaTeamById(GetArenaTeamIdForTeam(HORDE));
loser_arena_team = objmgr.GetArenaTeamById(GetArenaTeamIdForTeam(ALLIANCE));
}
if(winner_arena_team && loser_arena_team)
{
loser_arena_team->MemberLost(plr,winner_arena_team->GetRating());
}
}
}
WorldPacket data;
if(SendPacket)
{
sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, this, team, plr->GetBattleGroundQueueIndex(bgQueueTypeId), STATUS_NONE, 0, 0);
plr->GetSession()->SendPacket(&data);
}
// this call is important, because player, when joins to battleground, this method is not called, so it must be called when leaving bg
plr->RemoveBattleGroundQueueId(bgQueueTypeId);
//we should update battleground queue, but only if bg isn't ending
if (GetQueueType() < MAX_BATTLEGROUND_QUEUES)
sBattleGroundMgr.m_BattleGroundQueues[bgQueueTypeId].Update(bgTypeId, GetQueueType());
Group * group = plr->GetGroup();
// remove from raid group if exist
if(group && group == GetBgRaid(team))
{
if(!group->RemoveMember(guid, 0)) // group was disbanded
{
SetBgRaid(team, NULL);
delete group;
}
}
// Let others know
sBattleGroundMgr.BuildPlayerLeftBattleGroundPacket(&data, plr);
SendPacketToTeam(team, &data, plr, false);
}
// Do next only if found in battleground
plr->SetBattleGroundId(0); // We're not in BG.
// reset destination bg team
plr->SetBGTeam(0);
if(Transport)
{
plr->TeleportTo(plr->GetBattleGroundEntryPointMap(), plr->GetBattleGroundEntryPointX(), plr->GetBattleGroundEntryPointY(), plr->GetBattleGroundEntryPointZ(), plr->GetBattleGroundEntryPointO());
}
// Log
sLog.outDetail("BATTLEGROUND: Removed player %s from BattleGround.", plr->GetName());
}
if(!GetPlayersSize() && !GetInvitedCount(HORDE) && !GetInvitedCount(ALLIANCE))
{
// if no players left AND no invitees left, set this bg to delete in next update
// direct deletion could cause crashes
m_SetDeleteThis = true;
// return to prevent addition to freeslotqueue
return;
}
// a player exited the battleground, so there are free slots. add to queue
this->AddToBGFreeSlotQueue();
}
// this method is called when no players remains in battleground
void BattleGround::Reset()
{
SetQueueType(MAX_BATTLEGROUND_QUEUES);
SetWinner(WINNER_NONE);
SetStatus(STATUS_WAIT_QUEUE);
SetStartTime(0);
SetEndTime(0);
SetLastResurrectTime(0);
SetArenaType(0);
SetRated(false);
m_Events = 0;
if (m_InvitedAlliance > 0 || m_InvitedHorde > 0)
sLog.outError("BattleGround system ERROR: bad counter, m_InvitedAlliance: %d, m_InvitedHorde: %d", m_InvitedAlliance, m_InvitedHorde);
m_InvitedAlliance = 0;
m_InvitedHorde = 0;
m_InBGFreeSlotQueue = false;
m_Players.clear();
m_PlayerScores.clear();
// reset BGSubclass
ResetBGSubclass();
}
void BattleGround::StartBattleGround()
{
///this method should spawn spirit guides and so on
SetStartTime(0);
SetLastResurrectTime(0);
if(m_IsRated)
sLog.outArena("Arena match type: %u for Team1Id: %u - Team2Id: %u started.", m_ArenaType, m_ArenaTeamIds[BG_TEAM_ALLIANCE], m_ArenaTeamIds[BG_TEAM_HORDE]);
}
void BattleGround::AddPlayer(Player *plr)
{
// score struct must be created in inherited class
uint64 guid = plr->GetGUID();
uint32 team = plr->GetBGTeam();
BattleGroundPlayer bp;
bp.LastOnlineTime = 0;
bp.Team = team;
// Add to list/maps
m_Players[guid] = bp;
UpdatePlayersCountByTeam(team, false); // +1 player
WorldPacket data;
sBattleGroundMgr.BuildPlayerJoinedBattleGroundPacket(&data, plr);
SendPacketToTeam(team, &data, plr, false);
// add arena specific auras
if(isArena())
{
plr->RemoveArenaSpellCooldowns();
plr->RemoveArenaAuras();
plr->RemoveAllEnchantments(TEMP_ENCHANTMENT_SLOT, true);
if(team == ALLIANCE) // gold
{
if(plr->GetTeam() == HORDE)
plr->CastSpell(plr, SPELL_HORDE_GOLD_FLAG,true);
else
plr->CastSpell(plr, SPELL_ALLIANCE_GOLD_FLAG,true);
}
else // green
{
if(plr->GetTeam() == HORDE)
plr->CastSpell(plr, SPELL_HORDE_GREEN_FLAG,true);
else
plr->CastSpell(plr, SPELL_ALLIANCE_GREEN_FLAG,true);
}
plr->DestroyConjuredItems(true);
Pet* pet = plr->GetPet();
if(pet)
{
if(pet->getPetType() == SUMMON_PET || pet->getPetType() == HUNTER_PET)
{
(plr)->SetTemporaryUnsummonedPetNumber(pet->GetCharmInfo()->GetPetNumber());
(plr)->SetOldPetSpell(pet->GetUInt32Value(UNIT_CREATED_BY_SPELL));
}
(plr)->RemovePet(NULL,PET_SAVE_NOT_IN_SLOT);
}
else
(plr)->SetTemporaryUnsummonedPetNumber(0);
if(GetStatus() == STATUS_WAIT_JOIN) // not started yet
{
plr->CastSpell(plr, SPELL_ARENA_PREPARATION, true);
plr->SetHealth(plr->GetMaxHealth());
plr->SetPower(POWER_MANA, plr->GetMaxPower(POWER_MANA));
}
}
else
{
if(GetStatus() == STATUS_WAIT_JOIN) // not started yet
plr->CastSpell(plr, SPELL_PREPARATION, true); // reduces all mana cost of spells.
}
// Log
sLog.outDetail("BATTLEGROUND: Player %s joined the battle.", plr->GetName());
}
/* This method should be called only once ... it adds pointer to queue */
void BattleGround::AddToBGFreeSlotQueue()
{
// make sure to add only once
if(!m_InBGFreeSlotQueue)
{
sBattleGroundMgr.BGFreeSlotQueue[m_TypeID].push_front(this);
m_InBGFreeSlotQueue = true;
}
}
/* This method removes this battleground from free queue - it must be called when deleting battleground - not used now*/
void BattleGround::RemoveFromBGFreeSlotQueue()
{
// set to be able to re-add if needed
m_InBGFreeSlotQueue = false;
// uncomment this code when battlegrounds will work like instances
for (std::deque<BattleGround*>::iterator itr = sBattleGroundMgr.BGFreeSlotQueue[m_TypeID].begin(); itr != sBattleGroundMgr.BGFreeSlotQueue[m_TypeID].end(); ++itr)
{
if ((*itr)->GetInstanceID() == m_InstanceID)
{
sBattleGroundMgr.BGFreeSlotQueue[m_TypeID].erase(itr);
return;
}
}
}
// get the number of free slots for team
// works in similar way that HasFreeSlotsForTeam did, but this is needed for join as group
uint32 BattleGround::GetFreeSlotsForTeam(uint32 Team) const
{
//if BG is starting ... invite anyone
if (GetStatus() == STATUS_WAIT_JOIN)
return (GetInvitedCount(Team) < GetMaxPlayersPerTeam()) ? GetMaxPlayersPerTeam() - GetInvitedCount(Team) : 0;
//if BG is already started .. do not allow to join too much players of one faction
uint32 otherTeam;
uint32 otherIn;
if (Team == ALLIANCE)
{
otherTeam = GetInvitedCount(HORDE);
otherIn = GetPlayersCountByTeam(HORDE);
}
else
{
otherTeam = GetInvitedCount(ALLIANCE);
otherIn = GetPlayersCountByTeam(ALLIANCE);
}
if (GetStatus() == STATUS_IN_PROGRESS)
{
// difference based on ppl invited (not necessarily entered battle)
// default: allow 0
uint32 diff = 0;
// allow join one person if the sides are equal (to fill up bg to minplayersperteam)
if (otherTeam == GetInvitedCount(Team))
diff = 1;
// allow join more ppl if the other side has more players
else if(otherTeam > GetInvitedCount(Team))
diff = otherTeam - GetInvitedCount(Team);
// difference based on max players per team (don't allow inviting more)
uint32 diff2 = (GetInvitedCount(Team) < GetMaxPlayersPerTeam()) ? GetMaxPlayersPerTeam() - GetInvitedCount(Team) : 0;
// difference based on players who already entered
// default: allow 0
uint32 diff3 = 0;
// allow join one person if the sides are equal (to fill up bg minplayersperteam)
if (otherIn == GetPlayersCountByTeam(Team))
diff3 = 1;
// allow join more ppl if the other side has more players
else if (otherIn > GetPlayersCountByTeam(Team))
diff3 = otherIn - GetPlayersCountByTeam(Team);
// or other side has less than minPlayersPerTeam
else if (GetInvitedCount(Team) <= GetMinPlayersPerTeam())
diff3 = GetMinPlayersPerTeam() - GetInvitedCount(Team) + 1;
// return the minimum of the 3 differences
// min of diff and diff 2
diff = diff < diff2 ? diff : diff2;
// min of diff, diff2 and diff3
return diff < diff3 ? diff : diff3 ;
}
return 0;
}
bool BattleGround::HasFreeSlots() const
{
return GetPlayersSize() < GetMaxPlayers();
}
void BattleGround::UpdatePlayerScore(Player *Source, uint32 type, uint32 value)
{
//this procedure is called from virtual function implemented in bg subclass
std::map<uint64, BattleGroundScore*>::iterator itr = m_PlayerScores.find(Source->GetGUID());
if(itr == m_PlayerScores.end()) // player not found...
return;
switch(type)
{
case SCORE_KILLING_BLOWS: // Killing blows
itr->second->KillingBlows += value;
break;
case SCORE_DEATHS: // Deaths
itr->second->Deaths += value;
break;
case SCORE_HONORABLE_KILLS: // Honorable kills
itr->second->HonorableKills += value;
break;
case SCORE_BONUS_HONOR: // Honor bonus
// do not add honor in arenas
if(isBattleGround())
{
// reward honor instantly
if(Source->RewardHonor(NULL, 1, value))
itr->second->BonusHonor += value;
}
break;
//used only in EY, but in MSG_PVP_LOG_DATA opcode
case SCORE_DAMAGE_DONE: // Damage Done
itr->second->DamageDone += value;
break;
case SCORE_HEALING_DONE: // Healing Done
itr->second->HealingDone += value;
break;
default:
sLog.outError("BattleGround: Unknown player score type %u", type);
break;
}
}
void BattleGround::AddPlayerToResurrectQueue(uint64 npc_guid, uint64 player_guid)
{
m_ReviveQueue[npc_guid].push_back(player_guid);
Player *plr = objmgr.GetPlayer(player_guid);
if(!plr)
return;
plr->CastSpell(plr, SPELL_WAITING_FOR_RESURRECT, true);
SpellEntry const *spellInfo = sSpellStore.LookupEntry( SPELL_WAITING_FOR_RESURRECT );
if(spellInfo)
{
Aura *Aur = CreateAura(spellInfo, 0, NULL, plr);
plr->AddAura(Aur);
}
}
void BattleGround::RemovePlayerFromResurrectQueue(uint64 player_guid)
{
for(std::map<uint64, std::vector<uint64> >::iterator itr = m_ReviveQueue.begin(); itr != m_ReviveQueue.end(); ++itr)
{
for(std::vector<uint64>::iterator itr2 =(itr->second).begin(); itr2 != (itr->second).end(); ++itr2)
{
if(*itr2 == player_guid)
{
(itr->second).erase(itr2);
Player *plr = objmgr.GetPlayer(player_guid);
if(!plr)
return;
plr->RemoveAurasDueToSpell(SPELL_WAITING_FOR_RESURRECT);
return;
}
}
}
}
bool BattleGround::AddObject(uint32 type, uint32 entry, float x, float y, float z, float o, float rotation0, float rotation1, float rotation2, float rotation3, uint32 respawnTime)
{
Map * map = MapManager::Instance().FindMap(GetMapId(),GetInstanceID());
if(!map)
return false;
// must be created this way, adding to godatamap would add it to the base map of the instance
// and when loading it (in go::LoadFromDB()), a new guid would be assigned to the object, and a new object would be created
// so we must create it specific for this instance
GameObject * go = new GameObject;
if(!go->Create(objmgr.GenerateLowGuid(HIGHGUID_GAMEOBJECT),entry, map,x,y,z,o,rotation0,rotation1,rotation2,rotation3,100,1))
{
sLog.outErrorDb("Gameobject template %u not found in database! BattleGround not created!", entry);
sLog.outError("Cannot create gameobject template %u! BattleGround not created!", entry);
delete go;
return false;
}
/*
uint32 guid = go->GetGUIDLow();
// without this, UseButtonOrDoor caused the crash, since it tried to get go info from godata
// iirc that was changed, so adding to go data map is no longer required if that was the only function using godata from GameObject without checking if it existed
GameObjectData& data = objmgr.NewGOData(guid);
data.id = entry;
data.mapid = GetMapId();
data.posX = x;
data.posY = y;
data.posZ = z;
data.orientation = o;
data.rotation0 = rotation0;
data.rotation1 = rotation1;
data.rotation2 = rotation2;
data.rotation3 = rotation3;
data.spawntimesecs = respawnTime;
data.spawnMask = 1;
data.animprogress = 100;
data.go_state = 1;
*/
// add to world, so it can be later looked up from HashMapHolder
map->Add(go);
m_BgObjects[type] = go->GetGUID();
return true;
}
//some doors aren't despawned so we cannot handle their closing in gameobject::update()
//it would be nice to correctly implement GO_ACTIVATED state and open/close doors in gameobject code
void BattleGround::DoorClose(uint32 type)
{
GameObject *obj = HashMapHolder<GameObject>::Find(m_BgObjects[type]);
if(obj)
{
//if doors are open, close it
if( obj->getLootState() == GO_ACTIVATED && !obj->GetGoState() )
{
//change state to allow door to be closed
obj->SetLootState(GO_READY);
obj->UseDoorOrButton(RESPAWN_ONE_DAY);
}
}
else
{
sLog.outError("BattleGround: Door object not found (cannot close doors)");
}
}
void BattleGround::DoorOpen(uint32 type)
{
GameObject *obj = HashMapHolder<GameObject>::Find(m_BgObjects[type]);
if(obj)
{
//change state to be sure they will be opened
obj->SetLootState(GO_READY);
obj->UseDoorOrButton(RESPAWN_ONE_DAY);
}
else
{
sLog.outError("BattleGround: Door object not found! - doors will be closed.");
}
}
GameObject* BattleGround::GetBGObject(uint32 type)
{
GameObject *obj = HashMapHolder<GameObject>::Find(m_BgObjects[type]);
if(!obj)
sLog.outError("couldn't get gameobject %i",type);
return obj;
}
Creature* BattleGround::GetBGCreature(uint32 type)
{
Creature *creature = HashMapHolder<Creature>::Find(m_BgCreatures[type]);
if(!creature)
sLog.outError("couldn't get creature %i",type);
return creature;
}
void BattleGround::SpawnBGObject(uint32 type, uint32 respawntime)
{
Map * map = MapManager::Instance().FindMap(GetMapId(),GetInstanceID());
if(!map)
return;
if( respawntime == 0 )
{
GameObject *obj = HashMapHolder<GameObject>::Find(m_BgObjects[type]);
if(obj)
{
//we need to change state from GO_JUST_DEACTIVATED to GO_READY in case battleground is starting again
if( obj->getLootState() == GO_JUST_DEACTIVATED )
obj->SetLootState(GO_READY);
obj->SetRespawnTime(0);
map->Add(obj);
}
}
else
{
GameObject *obj = HashMapHolder<GameObject>::Find(m_BgObjects[type]);
if(obj)
{
map->Add(obj);
obj->SetRespawnTime(respawntime);
obj->SetLootState(GO_JUST_DEACTIVATED);
}
}
}
Creature* BattleGround::AddCreature(uint32 entry, uint32 type, uint32 teamval, float x, float y, float z, float o, uint32 respawntime)
{
Map * map = MapManager::Instance().FindMap(GetMapId(),GetInstanceID());
if(!map)
return NULL;
Creature* pCreature = new Creature;
if (!pCreature->Create(objmgr.GenerateLowGuid(HIGHGUID_UNIT), map, entry, teamval))
{
sLog.outError("Can't create creature entry: %u",entry);
delete pCreature;
return NULL;
}
pCreature->Relocate(x, y, z, o);
if(!pCreature->IsPositionValid())
{
sLog.outError("ERROR: Creature (guidlow %d, entry %d) not added to battleground. Suggested coordinates isn't valid (X: %f Y: %f)",pCreature->GetGUIDLow(),pCreature->GetEntry(),pCreature->GetPositionX(),pCreature->GetPositionY());
delete pCreature;
return NULL;
}
pCreature->SetHomePosition(x, y, z, o);
pCreature->AIM_Initialize();
//pCreature->SetDungeonDifficulty(0);
map->Add(pCreature);
m_BgCreatures[type] = pCreature->GetGUID();
return pCreature;
}
/*
void BattleGround::SpawnBGCreature(uint32 type, uint32 respawntime)
{
Map * map = MapManager::Instance().FindMap(GetMapId(),GetInstanceId());
if(!map)
return false;
if(respawntime == 0)
{
Creature *obj = HashMapHolder<Creature>::Find(m_BgCreatures[type]);
if(obj)
{
//obj->Respawn(); // bugged
obj->SetRespawnTime(0);
objmgr.SaveCreatureRespawnTime(obj->GetGUIDLow(), GetInstanceID(), 0);
map->Add(obj);
}
}
else
{
Creature *obj = HashMapHolder<Creature>::Find(m_BgCreatures[type]);
if(obj)
{
obj->setDeathState(DEAD);
obj->SetRespawnTime(respawntime);
map->Add(obj);
}
}
}
*/
bool BattleGround::DelCreature(uint32 type)
{
if(!m_BgCreatures[type])
return true;
Creature *cr = HashMapHolder<Creature>::Find(m_BgCreatures[type]);
if(!cr)
{
sLog.outError("Can't find creature guid: %u",GUID_LOPART(m_BgCreatures[type]));
return false;
}
//TODO: only delete creature after not in combat
cr->CleanupsBeforeDelete();
cr->AddObjectToRemoveList();
m_BgCreatures[type] = 0;
return true;
}
bool BattleGround::DelObject(uint32 type)
{
if(!m_BgObjects[type])
return true;
GameObject *obj = HashMapHolder<GameObject>::Find(m_BgObjects[type]);
if(!obj)
{
sLog.outError("Can't find gobject guid: %u",GUID_LOPART(m_BgObjects[type]));
return false;
}
obj->SetRespawnTime(0); // not save respawn time
obj->Delete();
m_BgObjects[type] = 0;
return true;
}
bool BattleGround::AddSpiritGuide(uint32 type, float x, float y, float z, float o, uint32 team)
{
uint32 entry = 0;
if(team == ALLIANCE)
entry = 13116;
else
entry = 13117;
Creature* pCreature = AddCreature(entry,type,team,x,y,z,o);
if(!pCreature)
{
sLog.outError("Can't create Spirit guide. BattleGround not created!");
EndNow();
return false;
}
pCreature->setDeathState(DEAD);
pCreature->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, pCreature->GetGUID());
// aura
pCreature->SetUInt32Value(UNIT_FIELD_AURA, SPELL_SPIRIT_HEAL_CHANNEL);
pCreature->SetUInt32Value(UNIT_FIELD_AURAFLAGS, 0x00000009);
pCreature->SetUInt32Value(UNIT_FIELD_AURALEVELS, 0x0000003C);
pCreature->SetUInt32Value(UNIT_FIELD_AURAAPPLICATIONS, 0x000000FF);
// casting visual effect
pCreature->SetUInt32Value(UNIT_CHANNEL_SPELL, SPELL_SPIRIT_HEAL_CHANNEL);
// correct cast speed
pCreature->SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
//pCreature->CastSpell(pCreature, SPELL_SPIRIT_HEAL_CHANNEL, true);
return true;
}
void BattleGround::SendMessageToAll(char const* text)
{
WorldPacket data;
ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_BG_SYSTEM_NEUTRAL, LANG_UNIVERSAL, NULL, 0, text, NULL);
SendPacketToAll(&data);
}
void BattleGround::SendMessageToAll(int32 entry)
{
char const* text = GetTrinityString(entry);
WorldPacket data;
ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_BG_SYSTEM_NEUTRAL, LANG_UNIVERSAL, NULL, 0, text, NULL);
SendPacketToAll(&data);
}
void BattleGround::EndNow()
{
RemoveFromBGFreeSlotQueue();
SetStatus(STATUS_WAIT_LEAVE);
SetEndTime(TIME_TO_AUTOREMOVE);
// inform invited players about the removal
sBattleGroundMgr.m_BattleGroundQueues[sBattleGroundMgr.BGQueueTypeId(GetTypeID(), GetArenaType())].BGEndedRemoveInvites(this);
}
// Battleground messages are localized using the dbc lang, they are not client language dependent
const char *BattleGround::GetTrinityString(int32 entry)
{
// FIXME: now we have different DBC locales and need localized message for each target client
return objmgr.GetTrinityStringForDBCLocale(entry);
}
/*
important notice:
buffs aren't spawned/despawned when players captures anything
buffs are in their positions when battleground starts
*/
void BattleGround::HandleTriggerBuff(uint64 const& go_guid)
{
GameObject *obj = HashMapHolder<GameObject>::Find(go_guid);
if(!obj || obj->GetGoType() != GAMEOBJECT_TYPE_TRAP || !obj->isSpawned())
return;
//change buff type, when buff is used:
int32 index = m_BgObjects.size() - 1;
while (index >= 0 && m_BgObjects[index] != go_guid)
index--;
if (index < 0)
{
sLog.outError("BattleGround (Type: %u) has buff gameobject (Guid: %u Entry: %u Type:%u) but it hasn't that object in its internal data",GetTypeID(),GUID_LOPART(go_guid),obj->GetEntry(),obj->GetGoType());
return;
}
//randomly select new buff
uint8 buff = urand(0, 2);
uint32 entry = obj->GetEntry();
if( m_BuffChange && entry != Buff_Entries[buff] )
{
//despawn current buff
SpawnBGObject(index, RESPAWN_ONE_DAY);
//set index for new one
for (uint8 currBuffTypeIndex = 0; currBuffTypeIndex < 3; ++currBuffTypeIndex)
if( entry == Buff_Entries[currBuffTypeIndex] )
{
index -= currBuffTypeIndex;
index += buff;
}
}
SpawnBGObject(index, BUFF_RESPAWN_TIME);
}
void BattleGround::HandleKillPlayer( Player *player, Player *killer )
{
//keep in mind that for arena this will have to be changed a bit
// add +1 deaths
UpdatePlayerScore(player, SCORE_DEATHS, 1);
// add +1 kills to group and +1 killing_blows to killer
if( killer )
{
UpdatePlayerScore(killer, SCORE_HONORABLE_KILLS, 1);
UpdatePlayerScore(killer, SCORE_KILLING_BLOWS, 1);
for(std::map<uint64, BattleGroundPlayer>::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr)
{
Player *plr = objmgr.GetPlayer(itr->first);
if(!plr || plr == killer)
continue;
if( plr->GetTeam() == killer->GetTeam() && plr->IsAtGroupRewardDistance(player) )
UpdatePlayerScore(plr, SCORE_HONORABLE_KILLS, 1);
}
}
// to be able to remove insignia -- ONLY IN BattleGrounds
if( !isArena() )
player->SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE );
}
// return the player's team based on battlegroundplayer info
// used in same faction arena matches mainly
uint32 BattleGround::GetPlayerTeam(uint64 guid)
{
std::map<uint64, BattleGroundPlayer>::const_iterator itr = m_Players.find(guid);
if(itr!=m_Players.end())
return itr->second.Team;
return 0;
}
bool BattleGround::IsPlayerInBattleGround(uint64 guid)
{
std::map<uint64, BattleGroundPlayer>::const_iterator itr = m_Players.find(guid);
if(itr!=m_Players.end())
return true;
return false;
}
void BattleGround::PlayerRelogin(uint64 guid)
{
if(GetStatus() != STATUS_WAIT_LEAVE)
return;
Player *plr = objmgr.GetPlayer(guid);
if(!plr)
{
sLog.outError("BattleGround: Player " I64FMTD " not found!", guid);
return;
}
WorldPacket data;
uint32 bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(GetTypeID(), GetArenaType());
BlockMovement(plr);
sBattleGroundMgr.BuildPvpLogDataPacket(&data, this);
plr->GetSession()->SendPacket(&data);
sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, this, plr->GetTeam(), plr->GetBattleGroundQueueIndex(bgQueueTypeId), STATUS_IN_PROGRESS, TIME_TO_AUTOREMOVE, GetStartTime());
plr->GetSession()->SendPacket(&data);
}
uint32 BattleGround::GetAlivePlayersCountByTeam(uint32 Team) const
{
int count = 0;
for(std::map<uint64, BattleGroundPlayer>::const_iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr)
{
if(itr->second.Team == Team)
{
Player * pl = objmgr.GetPlayer(itr->first);
if(pl && pl->isAlive())
++count;
}
}
return count;
}
void BattleGround::SetHoliday(bool is_holiday)
{
if(is_holiday)
m_HonorMode = BG_HOLIDAY;
else
m_HonorMode = BG_NORMAL;
}
int32 BattleGround::GetObjectType(uint64 guid)
{
for(uint32 i = 0;i <= m_BgObjects.size(); i++)
if(m_BgObjects[i] == guid)
return i;
sLog.outError("BattleGround: cheating? a player used a gameobject which isnt supposed to be a usable object!");
return -1;
}
void BattleGround::HandleKillUnit(Creature *creature, Player *killer)
{
}
// This method should be called when player logs out from running battleground
void BattleGround::EventPlayerLoggedOut(Player* player)
{
if( GetStatus() == STATUS_IN_PROGRESS )
{
if( isBattleGround() )
EventPlayerDroppedFlag(player);
}
if( isArena() )
player->LeaveBattleground();
} | aedansilver/Proyecto-TBC | src/game/BattleGround.cpp | C++ | gpl-2.0 | 55,710 |
<?php
require_once __DIR__ . '/../config.inc.php';
require_once __DIR__ . '/../classes/constants.php';
// How to enable local tandem external function in Moodle [admin required]:
// 1. Enable web services
// 2. Enable protocols At least one protocol should be enabled. For security reasons, only protocols that are to be used should be enabled.
// 3. Create a specific user A web services user is required to represent the system controlling Moodle.
// 4. Check user capability The user should have appropriate capabilities according to the protocols used, for example webservice/rest:use, webservice/soap:use.
// To achieve this, create a web services role with protocol capabilities allowed and assign it to the web services user as a system role.
// Assign system role to the new user in Users > Permissions > Assign system roles
// 5. Select a service A service is a set of web service functions. You will allow the user to access to a new service.
// On the Add service page check 'Enable' and 'Authorised users' options. Select 'No required capability'.
// 6. Add functions Select required functions for the newly created service.
// 7. Select a specific user Add the web services user as an authorised user.
// 8. Create a token for a user Create a token for the web services user.
// 9. Disable developer documentation Detailed web services documentation is available for enabled protocols.
// 10. Test the service Simulate external access to the service using any test client.
// Use an enabled protocol with token authentication.
// WARNING: The functions that you test WILL BE EXECUTED, so be careful what you choose to test!
class MoodleServicesConsumer {
/**
* Dashboard > Site administration > Plugins > Web services > External services > Functions > Add functions to the service "Tandem Services"
* @param $courseId
* @return array|bool
*/
public static function last_access_moodle($courseId) {
/** @var SimpleXMLElement $xml */
list($xml, $err) = self::post_moodle_request('local_tandem_get_last_access_info', [
'courseid' => $courseId
]);
if ($err) {
return false;
}
$usersaccessinfo = array();
if (!empty($xml->SINGLE->KEY[0]->MULTIPLE->SINGLE)) {
foreach($xml->SINGLE->KEY[0]->MULTIPLE->SINGLE as $xml2) {
$usersaccessinfo[] = array(
'last_access' => (string) $xml2->KEY[0]->VALUE,
'firstname' => (string) $xml2->KEY[1]->VALUE,
'lastname' => (string) $xml2->KEY[2]->VALUE,
'email' => (string) $xml2->KEY[3]->VALUE,
);
}
}
return $usersaccessinfo;
}
/**
* @param string $useremail
* @param int $courseid
* @return bool[]|false
*/
public static function get_user_survey_status($useremail, $courseid) {
list($xml, $err) = self::post_moodle_request('local_tandem_get_user_survey_status', [
'useremail' => $useremail,
'courseid' => $courseid
]);
if ($err) {
return false;
}
$presurveycompleted = ('1' === (string) $xml->SINGLE->KEY[0]->SINGLE->KEY[0]->VALUE);
$postsurveycompleted = ('1' === (string) $xml->SINGLE->KEY[0]->SINGLE->KEY[1]->VALUE);
return [
'presurveycompleted' => $presurveycompleted,
'postsurveycompleted' => $postsurveycompleted,
];
}
/**
* @param string $functionname
* @param array $data
* @return SimpleXMLElement[]|false[]
*/
private static function post_moodle_request($functionname, $data) {
// Moodle external service settings
$token = MOODLE_EXTERNAL_SERVICES_TOKEN;
$domainname = MOODLE_EXTERNAL_SERVICES_DOMAIN;
$protocol = MOODLE_EXTERNAL_SERVICES_PROTOCOL;
// Request settings
$moodleurl = "$domainname/webservice/$protocol/server.php?wstoken=$token&wsfunction=$functionname";
$postfields = ['data' => $data];
// Do request
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $moodleurl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => http_build_query($postfields),
CURLOPT_HTTPHEADER => ['Cache-Control: no-cache', 'Content-Type: application/x-www-form-urlencoded'],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$xml = false;
if (!$err) {
$xml = simplexml_load_string(trim($response), 'SimpleXMLElement', LIBXML_NOCDATA);
}
return array($xml, $err);
}
}
| UOC/Tandem | src/classes/moodleServicesConsumer.php | PHP | gpl-2.0 | 5,233 |
/*
* syscalls.h - Linux syscall interfaces (non-arch-specific)
*
* Copyright (c) 2004 Randy Dunlap
* Copyright (c) 2004 Open Source Development Labs
*
* This file is released under the GPLv2.
* See the file COPYING for more details.
*/
#ifndef _LINUX_SYSCALLS_H
#define _LINUX_SYSCALLS_H
struct epoll_event;
struct iattr;
struct inode;
struct iocb;
struct io_event;
struct iovec;
struct itimerspec;
struct itimerval;
struct kexec_segment;
struct linux_dirent;
struct linux_dirent64;
struct list_head;
struct mmap_arg_struct;
struct msgbuf;
struct msghdr;
struct mmsghdr;
struct msqid_ds;
struct new_utsname;
struct nfsctl_arg;
struct __old_kernel_stat;
struct oldold_utsname;
struct old_utsname;
struct pollfd;
struct rlimit;
struct rlimit64;
struct rusage;
struct sched_param;
struct sel_arg_struct;
struct semaphore;
struct sembuf;
struct shmid_ds;
struct sockaddr;
struct stat;
struct stat64;
struct statfs;
struct statfs64;
struct __sysctl_args;
struct sysinfo;
struct timespec;
struct timeval;
struct timex;
struct timezone;
struct tms;
struct utimbuf;
struct mq_attr;
struct compat_stat;
struct compat_timeval;
struct robust_list_head;
struct getcpu_cache;
struct old_linux_dirent;
struct perf_event_attr;
struct file_handle;
struct sigaltstack;
struct timetable;
#include <linux/types.h>
#include <linux/aio_abi.h>
#include <linux/capability.h>
#include <linux/signal.h>
#include <linux/list.h>
#include <linux/bug.h>
#include <linux/sem.h>
#include <asm/siginfo.h>
#include <linux/unistd.h>
#include <linux/quota.h>
#include <linux/key.h>
#include <trace/syscall.h>
/*
* __MAP - apply a macro to syscall arguments
* __MAP(n, m, t1, a1, t2, a2, ..., tn, an) will expand to
* m(t1, a1), m(t2, a2), ..., m(tn, an)
* The first argument must be equal to the amount of type/name
* pairs given. Note that this list of pairs (i.e. the arguments
* of __MAP starting at the third one) is in the same format as
* for SYSCALL_DEFINE<n>/COMPAT_SYSCALL_DEFINE<n>
*/
#define __MAP0(m,...)
#define __MAP1(m,t,a) m(t,a)
#define __MAP2(m,t,a,...) m(t,a), __MAP1(m,__VA_ARGS__)
#define __MAP3(m,t,a,...) m(t,a), __MAP2(m,__VA_ARGS__)
#define __MAP4(m,t,a,...) m(t,a), __MAP3(m,__VA_ARGS__)
#define __MAP5(m,t,a,...) m(t,a), __MAP4(m,__VA_ARGS__)
#define __MAP6(m,t,a,...) m(t,a), __MAP5(m,__VA_ARGS__)
#define __MAP(n,...) __MAP##n(__VA_ARGS__)
#define __SC_DECL(t, a) t a
#define __TYPE_IS_LL(t) (__same_type((t)0, 0LL) || __same_type((t)0, 0ULL))
#define __SC_LONG(t, a) __typeof(__builtin_choose_expr(__TYPE_IS_LL(t), 0LL, 0L)) a
#define __SC_CAST(t, a) (t) a
#define __SC_ARGS(t, a) a
#define __SC_TEST(t, a) (void)BUILD_BUG_ON_ZERO(!__TYPE_IS_LL(t) && sizeof(t) > sizeof(long))
#ifdef CONFIG_FTRACE_SYSCALLS
#define __SC_STR_ADECL(t, a) #a
#define __SC_STR_TDECL(t, a) #t
extern struct ftrace_event_class event_class_syscall_enter;
extern struct ftrace_event_class event_class_syscall_exit;
extern struct trace_event_functions enter_syscall_print_funcs;
extern struct trace_event_functions exit_syscall_print_funcs;
#define SYSCALL_TRACE_ENTER_EVENT(sname) \
static struct syscall_metadata __syscall_meta_##sname; \
static struct ftrace_event_call __used \
event_enter_##sname = { \
.name = "sys_enter"#sname, \
.class = &event_class_syscall_enter, \
.event.funcs = &enter_syscall_print_funcs, \
.data = (void *)&__syscall_meta_##sname,\
.flags = TRACE_EVENT_FL_CAP_ANY, \
}; \
static struct ftrace_event_call __used \
__attribute__((section("_ftrace_events"))) \
*__event_enter_##sname = &event_enter_##sname;
#define SYSCALL_TRACE_EXIT_EVENT(sname) \
static struct syscall_metadata __syscall_meta_##sname; \
static struct ftrace_event_call __used \
event_exit_##sname = { \
.name = "sys_exit"#sname, \
.class = &event_class_syscall_exit, \
.event.funcs = &exit_syscall_print_funcs, \
.data = (void *)&__syscall_meta_##sname,\
.flags = TRACE_EVENT_FL_CAP_ANY, \
}; \
static struct ftrace_event_call __used \
__attribute__((section("_ftrace_events"))) \
*__event_exit_##sname = &event_exit_##sname;
#define SYSCALL_METADATA(sname, nb, ...) \
static const char *types_##sname[] = { \
__MAP(nb,__SC_STR_TDECL,__VA_ARGS__) \
}; \
static const char *args_##sname[] = { \
__MAP(nb,__SC_STR_ADECL,__VA_ARGS__) \
}; \
SYSCALL_TRACE_ENTER_EVENT(sname); \
SYSCALL_TRACE_EXIT_EVENT(sname); \
static struct syscall_metadata __used \
__syscall_meta_##sname = { \
.name = "sys"#sname, \
.syscall_nr = -1, /* Filled in at boot */ \
.nb_args = nb, \
.types = nb ? types_##sname : NULL, \
.args = nb ? args_##sname : NULL, \
.enter_event = &event_enter_##sname, \
.exit_event = &event_exit_##sname, \
.enter_fields = LIST_HEAD_INIT(__syscall_meta_##sname.enter_fields), \
}; \
static struct syscall_metadata __used \
__attribute__((section("__syscalls_metadata"))) \
*__p_syscall_meta_##sname = &__syscall_meta_##sname;
#else
#define SYSCALL_METADATA(sname, nb, ...)
#endif
#define SYSCALL_DEFINE0(sname) \
SYSCALL_METADATA(_##sname, 0); \
asmlinkage long sys_##sname(void)
#define SYSCALL_DEFINE1(name, ...) SYSCALL_DEFINEx(1, _##name, __VA_ARGS__)
#define SYSCALL_DEFINE2(name, ...) SYSCALL_DEFINEx(2, _##name, __VA_ARGS__)
#define SYSCALL_DEFINE3(name, ...) SYSCALL_DEFINEx(3, _##name, __VA_ARGS__)
#define SYSCALL_DEFINE4(name, ...) SYSCALL_DEFINEx(4, _##name, __VA_ARGS__)
#define SYSCALL_DEFINE5(name, ...) SYSCALL_DEFINEx(5, _##name, __VA_ARGS__)
#define SYSCALL_DEFINE6(name, ...) SYSCALL_DEFINEx(6, _##name, __VA_ARGS__)
#define SYSCALL_DEFINEx(x, sname, ...) \
SYSCALL_METADATA(sname, x, __VA_ARGS__) \
__SYSCALL_DEFINEx(x, sname, __VA_ARGS__)
#define __PROTECT(...) asmlinkage_protect(__VA_ARGS__)
#define __SYSCALL_DEFINEx(x, name, ...) \
asmlinkage long sys##name(__MAP(x,__SC_DECL,__VA_ARGS__)); \
static inline long SYSC##name(__MAP(x,__SC_DECL,__VA_ARGS__)); \
asmlinkage long SyS##name(__MAP(x,__SC_LONG,__VA_ARGS__)) \
{ \
long ret = SYSC##name(__MAP(x,__SC_CAST,__VA_ARGS__)); \
__MAP(x,__SC_TEST,__VA_ARGS__); \
__PROTECT(x, ret,__MAP(x,__SC_ARGS,__VA_ARGS__)); \
return ret; \
} \
SYSCALL_ALIAS(sys##name, SyS##name); \
static inline long SYSC##name(__MAP(x,__SC_DECL,__VA_ARGS__))
asmlinkage long sys_time(time_t __user *tloc);
asmlinkage long sys_stime(time_t __user *tptr);
asmlinkage long sys_gettimeofday(struct timeval __user *tv,
struct timezone __user *tz);
asmlinkage long sys_settimeofday(struct timeval __user *tv,
struct timezone __user *tz);
asmlinkage long sys_adjtimex(struct timex __user *txc_p);
asmlinkage long sys_times(struct tms __user *tbuf);
asmlinkage long sys_gettid(void);
asmlinkage long sys_nanosleep(struct timespec __user *rqtp, struct timespec __user *rmtp);
asmlinkage long sys_alarm(unsigned int seconds);
asmlinkage long sys_getpid(void);
asmlinkage long sys_getppid(void);
asmlinkage long sys_getuid(void);
asmlinkage long sys_geteuid(void);
asmlinkage long sys_getgid(void);
asmlinkage long sys_getegid(void);
asmlinkage long sys_getresuid(uid_t __user *ruid, uid_t __user *euid, uid_t __user *suid);
asmlinkage long sys_getresgid(gid_t __user *rgid, gid_t __user *egid, gid_t __user *sgid);
asmlinkage long sys_getpgid(pid_t pid);
asmlinkage long sys_getpgrp(void);
asmlinkage long sys_getsid(pid_t pid);
asmlinkage long sys_getgroups(int gidsetsize, gid_t __user *grouplist);
asmlinkage long sys_setregid(gid_t rgid, gid_t egid);
asmlinkage long sys_setgid(gid_t gid);
asmlinkage long sys_setreuid(uid_t ruid, uid_t euid);
asmlinkage long sys_setuid(uid_t uid);
asmlinkage long sys_setresuid(uid_t ruid, uid_t euid, uid_t suid);
asmlinkage long sys_setresgid(gid_t rgid, gid_t egid, gid_t sgid);
asmlinkage long sys_setfsuid(uid_t uid);
asmlinkage long sys_setfsgid(gid_t gid);
asmlinkage long sys_setpgid(pid_t pid, pid_t pgid);
asmlinkage long sys_setsid(void);
asmlinkage long sys_setgroups(int gidsetsize, gid_t __user *grouplist);
asmlinkage long sys_acct(const char __user *name);
asmlinkage long sys_capget(cap_user_header_t header,
cap_user_data_t dataptr);
asmlinkage long sys_capset(cap_user_header_t header,
const cap_user_data_t data);
asmlinkage long sys_personality(unsigned int personality);
asmlinkage long sys_sigpending(old_sigset_t __user *set);
asmlinkage long sys_sigprocmask(int how, old_sigset_t __user *set,
old_sigset_t __user *oset);
asmlinkage long sys_sigaltstack(const struct sigaltstack __user *uss,
struct sigaltstack __user *uoss);
asmlinkage long sys_getitimer(int which, struct itimerval __user *value);
asmlinkage long sys_setitimer(int which,
struct itimerval __user *value,
struct itimerval __user *ovalue);
asmlinkage long sys_timer_create(clockid_t which_clock,
struct sigevent __user *timer_event_spec,
timer_t __user * created_timer_id);
asmlinkage long sys_timer_gettime(timer_t timer_id,
struct itimerspec __user *setting);
asmlinkage long sys_timer_getoverrun(timer_t timer_id);
asmlinkage long sys_timer_settime(timer_t timer_id, int flags,
const struct itimerspec __user *new_setting,
struct itimerspec __user *old_setting);
asmlinkage long sys_timer_delete(timer_t timer_id);
asmlinkage long sys_clock_settime(clockid_t which_clock,
const struct timespec __user *tp);
asmlinkage long sys_clock_gettime(clockid_t which_clock,
struct timespec __user *tp);
asmlinkage long sys_clock_adjtime(clockid_t which_clock,
struct timex __user *tx);
asmlinkage long sys_clock_getres(clockid_t which_clock,
struct timespec __user *tp);
asmlinkage long sys_clock_nanosleep(clockid_t which_clock, int flags,
const struct timespec __user *rqtp,
struct timespec __user *rmtp);
asmlinkage long sys_nice(int increment);
asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
struct sched_param __user *param);
asmlinkage long sys_sched_setparam(pid_t pid,
struct sched_param __user *param);
asmlinkage long sys_sched_getscheduler(pid_t pid);
asmlinkage long sys_sched_getparam(pid_t pid,
struct sched_param __user *param);
asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
unsigned long __user *user_mask_ptr);
asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
unsigned long __user *user_mask_ptr);
asmlinkage long sys_sched_yield(void);
asmlinkage long sys_sched_get_priority_max(int policy);
asmlinkage long sys_sched_get_priority_min(int policy);
asmlinkage long sys_sched_rr_get_interval(pid_t pid,
struct timespec __user *interval);
asmlinkage long sys_setpriority(int which, int who, int niceval);
asmlinkage long sys_getpriority(int which, int who);
asmlinkage long sys_shutdown(int, int);
asmlinkage long sys_reboot(int magic1, int magic2, unsigned int cmd,
void __user *arg);
asmlinkage long sys_restart_syscall(void);
asmlinkage long sys_kexec_load(unsigned long entry, unsigned long nr_segments,
struct kexec_segment __user *segments,
unsigned long flags);
asmlinkage long sys_exit(int error_code);
asmlinkage long sys_exit_group(int error_code);
asmlinkage long sys_wait4(pid_t pid, int __user *stat_addr,
int options, struct rusage __user *ru);
asmlinkage long sys_waitid(int which, pid_t pid,
struct siginfo __user *infop,
int options, struct rusage __user *ru);
asmlinkage long sys_waitpid(pid_t pid, int __user *stat_addr, int options);
asmlinkage long sys_set_tid_address(int __user *tidptr);
asmlinkage long sys_futex(u32 __user *uaddr, int op, u32 val,
struct timespec __user *utime, u32 __user *uaddr2,
u32 val3);
asmlinkage long sys_init_module(void __user *umod, unsigned long len,
const char __user *uargs);
asmlinkage long sys_delete_module(const char __user *name_user,
unsigned int flags);
#ifdef CONFIG_OLD_SIGSUSPEND
asmlinkage long sys_sigsuspend(old_sigset_t mask);
#endif
#ifdef CONFIG_OLD_SIGSUSPEND3
asmlinkage long sys_sigsuspend(int unused1, int unused2, old_sigset_t mask);
#endif
asmlinkage long sys_rt_sigsuspend(sigset_t __user *unewset, size_t sigsetsize);
#ifdef CONFIG_OLD_SIGACTION
asmlinkage long sys_sigaction(int, const struct old_sigaction __user *,
struct old_sigaction __user *);
#endif
#ifndef CONFIG_ODD_RT_SIGACTION
asmlinkage long sys_rt_sigaction(int,
const struct sigaction __user *,
struct sigaction __user *,
size_t);
#endif
asmlinkage long sys_rt_sigprocmask(int how, sigset_t __user *set,
sigset_t __user *oset, size_t sigsetsize);
asmlinkage long sys_rt_sigpending(sigset_t __user *set, size_t sigsetsize);
asmlinkage long sys_rt_sigtimedwait(const sigset_t __user *uthese,
siginfo_t __user *uinfo,
const struct timespec __user *uts,
size_t sigsetsize);
asmlinkage long sys_rt_tgsigqueueinfo(pid_t tgid, pid_t pid, int sig,
siginfo_t __user *uinfo);
asmlinkage long sys_kill(int pid, int sig);
asmlinkage long sys_tgkill(int tgid, int pid, int sig);
asmlinkage long sys_tkill(int pid, int sig);
asmlinkage long sys_rt_sigqueueinfo(int pid, int sig, siginfo_t __user *uinfo);
asmlinkage long sys_sgetmask(void);
asmlinkage long sys_ssetmask(int newmask);
asmlinkage long sys_signal(int sig, __sighandler_t handler);
asmlinkage long sys_pause(void);
asmlinkage long sys_sync(void);
asmlinkage long sys_fsync(unsigned int fd);
asmlinkage long sys_fdatasync(unsigned int fd);
asmlinkage long sys_bdflush(int func, long data);
asmlinkage long sys_mount(char __user *dev_name, char __user *dir_name,
char __user *type, unsigned long flags,
void __user *data);
asmlinkage long sys_umount(char __user *name, int flags);
asmlinkage long sys_oldumount(char __user *name);
asmlinkage long sys_truncate(const char __user *path, long length);
asmlinkage long sys_ftruncate(unsigned int fd, unsigned long length);
asmlinkage long sys_stat(const char __user *filename,
struct __old_kernel_stat __user *statbuf);
asmlinkage long sys_statfs(const char __user * path,
struct statfs __user *buf);
asmlinkage long sys_statfs64(const char __user *path, size_t sz,
struct statfs64 __user *buf);
asmlinkage long sys_fstatfs(unsigned int fd, struct statfs __user *buf);
asmlinkage long sys_fstatfs64(unsigned int fd, size_t sz,
struct statfs64 __user *buf);
asmlinkage long sys_lstat(const char __user *filename,
struct __old_kernel_stat __user *statbuf);
asmlinkage long sys_fstat(unsigned int fd,
struct __old_kernel_stat __user *statbuf);
asmlinkage long sys_newstat(const char __user *filename,
struct stat __user *statbuf);
asmlinkage long sys_newlstat(const char __user *filename,
struct stat __user *statbuf);
asmlinkage long sys_newfstat(unsigned int fd, struct stat __user *statbuf);
asmlinkage long sys_ustat(unsigned dev, struct ustat __user *ubuf);
#if BITS_PER_LONG == 32
asmlinkage long sys_stat64(const char __user *filename,
struct stat64 __user *statbuf);
asmlinkage long sys_fstat64(unsigned long fd, struct stat64 __user *statbuf);
asmlinkage long sys_lstat64(const char __user *filename,
struct stat64 __user *statbuf);
asmlinkage long sys_truncate64(const char __user *path, loff_t length);
asmlinkage long sys_ftruncate64(unsigned int fd, loff_t length);
#endif
asmlinkage long sys_setxattr(const char __user *path, const char __user *name,
const void __user *value, size_t size, int flags);
asmlinkage long sys_lsetxattr(const char __user *path, const char __user *name,
const void __user *value, size_t size, int flags);
asmlinkage long sys_fsetxattr(int fd, const char __user *name,
const void __user *value, size_t size, int flags);
asmlinkage long sys_getxattr(const char __user *path, const char __user *name,
void __user *value, size_t size);
asmlinkage long sys_lgetxattr(const char __user *path, const char __user *name,
void __user *value, size_t size);
asmlinkage long sys_fgetxattr(int fd, const char __user *name,
void __user *value, size_t size);
asmlinkage long sys_listxattr(const char __user *path, char __user *list,
size_t size);
asmlinkage long sys_llistxattr(const char __user *path, char __user *list,
size_t size);
asmlinkage long sys_flistxattr(int fd, char __user *list, size_t size);
asmlinkage long sys_removexattr(const char __user *path,
const char __user *name);
asmlinkage long sys_lremovexattr(const char __user *path,
const char __user *name);
asmlinkage long sys_fremovexattr(int fd, const char __user *name);
asmlinkage long sys_brk(unsigned long brk);
asmlinkage long sys_mprotect(unsigned long start, size_t len,
unsigned long prot);
asmlinkage long sys_mremap(unsigned long addr,
unsigned long old_len, unsigned long new_len,
unsigned long flags, unsigned long new_addr);
asmlinkage long sys_remap_file_pages(unsigned long start, unsigned long size,
unsigned long prot, unsigned long pgoff,
unsigned long flags);
asmlinkage long sys_msync(unsigned long start, size_t len, int flags);
asmlinkage long sys_fadvise64(int fd, loff_t offset, size_t len, int advice);
asmlinkage long sys_fadvise64_64(int fd, loff_t offset, loff_t len, int advice);
asmlinkage long sys_munmap(unsigned long addr, size_t len);
asmlinkage long sys_mlock(unsigned long start, size_t len);
asmlinkage long sys_munlock(unsigned long start, size_t len);
asmlinkage long sys_mlockall(int flags);
asmlinkage long sys_munlockall(void);
asmlinkage long sys_madvise(unsigned long start, size_t len, int behavior);
asmlinkage long sys_mincore(unsigned long start, size_t len,
unsigned char __user * vec);
asmlinkage long sys_pivot_root(const char __user *new_root,
const char __user *put_old);
asmlinkage long sys_chroot(const char __user *filename);
asmlinkage long sys_mknod(const char __user *filename, umode_t mode,
unsigned dev);
asmlinkage long sys_link(const char __user *oldname,
const char __user *newname);
asmlinkage long sys_symlink(const char __user *old, const char __user *new);
asmlinkage long sys_unlink(const char __user *pathname);
asmlinkage long sys_rename(const char __user *oldname,
const char __user *newname);
asmlinkage long sys_chmod(const char __user *filename, umode_t mode);
asmlinkage long sys_fchmod(unsigned int fd, umode_t mode);
asmlinkage long sys_fcntl(unsigned int fd, unsigned int cmd, unsigned long arg);
#if BITS_PER_LONG == 32
asmlinkage long sys_fcntl64(unsigned int fd,
unsigned int cmd, unsigned long arg);
#endif
asmlinkage long sys_pipe(int __user *fildes);
asmlinkage long sys_pipe2(int __user *fildes, int flags);
asmlinkage long sys_dup(unsigned int fildes);
asmlinkage long sys_dup2(unsigned int oldfd, unsigned int newfd);
asmlinkage long sys_dup3(unsigned int oldfd, unsigned int newfd, int flags);
asmlinkage long sys_ioperm(unsigned long from, unsigned long num, int on);
asmlinkage long sys_ioctl(unsigned int fd, unsigned int cmd,
unsigned long arg);
asmlinkage long sys_flock(unsigned int fd, unsigned int cmd);
asmlinkage long sys_io_setup(unsigned nr_reqs, aio_context_t __user *ctx);
asmlinkage long sys_io_destroy(aio_context_t ctx);
asmlinkage long sys_io_getevents(aio_context_t ctx_id,
long min_nr,
long nr,
struct io_event __user *events,
struct timespec __user *timeout);
asmlinkage long sys_io_submit(aio_context_t, long,
struct iocb __user * __user *);
asmlinkage long sys_io_cancel(aio_context_t ctx_id, struct iocb __user *iocb,
struct io_event __user *result);
asmlinkage long sys_sendfile(int out_fd, int in_fd,
off_t __user *offset, size_t count);
asmlinkage long sys_sendfile64(int out_fd, int in_fd,
loff_t __user *offset, size_t count);
asmlinkage long sys_readlink(const char __user *path,
char __user *buf, int bufsiz);
asmlinkage long sys_creat(const char __user *pathname, umode_t mode);
asmlinkage long sys_open(const char __user *filename,
int flags, umode_t mode);
asmlinkage long sys_close(unsigned int fd);
asmlinkage long sys_access(const char __user *filename, int mode);
asmlinkage long sys_vhangup(void);
asmlinkage long sys_chown(const char __user *filename,
uid_t user, gid_t group);
asmlinkage long sys_lchown(const char __user *filename,
uid_t user, gid_t group);
asmlinkage long sys_fchown(unsigned int fd, uid_t user, gid_t group);
#ifdef CONFIG_UID16
asmlinkage long sys_chown16(const char __user *filename,
old_uid_t user, old_gid_t group);
asmlinkage long sys_lchown16(const char __user *filename,
old_uid_t user, old_gid_t group);
asmlinkage long sys_fchown16(unsigned int fd, old_uid_t user, old_gid_t group);
asmlinkage long sys_setregid16(old_gid_t rgid, old_gid_t egid);
asmlinkage long sys_setgid16(old_gid_t gid);
asmlinkage long sys_setreuid16(old_uid_t ruid, old_uid_t euid);
asmlinkage long sys_setuid16(old_uid_t uid);
asmlinkage long sys_setresuid16(old_uid_t ruid, old_uid_t euid, old_uid_t suid);
asmlinkage long sys_getresuid16(old_uid_t __user *ruid,
old_uid_t __user *euid, old_uid_t __user *suid);
asmlinkage long sys_setresgid16(old_gid_t rgid, old_gid_t egid, old_gid_t sgid);
asmlinkage long sys_getresgid16(old_gid_t __user *rgid,
old_gid_t __user *egid, old_gid_t __user *sgid);
asmlinkage long sys_setfsuid16(old_uid_t uid);
asmlinkage long sys_setfsgid16(old_gid_t gid);
asmlinkage long sys_getgroups16(int gidsetsize, old_gid_t __user *grouplist);
asmlinkage long sys_setgroups16(int gidsetsize, old_gid_t __user *grouplist);
asmlinkage long sys_getuid16(void);
asmlinkage long sys_geteuid16(void);
asmlinkage long sys_getgid16(void);
asmlinkage long sys_getegid16(void);
#endif
asmlinkage long sys_utime(char __user *filename,
struct utimbuf __user *times);
asmlinkage long sys_utimes(char __user *filename,
struct timeval __user *utimes);
asmlinkage long sys_lseek(unsigned int fd, off_t offset,
unsigned int whence);
asmlinkage long sys_llseek(unsigned int fd, unsigned long offset_high,
unsigned long offset_low, loff_t __user *result,
unsigned int whence);
asmlinkage long sys_read(unsigned int fd, char __user *buf, size_t count);
asmlinkage long sys_readahead(int fd, loff_t offset, size_t count);
asmlinkage long sys_readv(unsigned long fd,
const struct iovec __user *vec,
unsigned long vlen);
asmlinkage long sys_write(unsigned int fd, const char __user *buf,
size_t count);
asmlinkage long sys_writev(unsigned long fd,
const struct iovec __user *vec,
unsigned long vlen);
asmlinkage long sys_pread64(unsigned int fd, char __user *buf,
size_t count, loff_t pos);
asmlinkage long sys_pwrite64(unsigned int fd, const char __user *buf,
size_t count, loff_t pos);
asmlinkage long sys_preadv(unsigned long fd, const struct iovec __user *vec,
unsigned long vlen, unsigned long pos_l, unsigned long pos_h);
asmlinkage long sys_pwritev(unsigned long fd, const struct iovec __user *vec,
unsigned long vlen, unsigned long pos_l, unsigned long pos_h);
asmlinkage long sys_getcwd(char __user *buf, unsigned long size);
asmlinkage long sys_mkdir(const char __user *pathname, umode_t mode);
asmlinkage long sys_chdir(const char __user *filename);
asmlinkage long sys_fchdir(unsigned int fd);
asmlinkage long sys_rmdir(const char __user *pathname);
asmlinkage long sys_lookup_dcookie(u64 cookie64, char __user *buf, size_t len);
asmlinkage long sys_quotactl(unsigned int cmd, const char __user *special,
qid_t id, void __user *addr);
asmlinkage long sys_getdents(unsigned int fd,
struct linux_dirent __user *dirent,
unsigned int count);
asmlinkage long sys_getdents64(unsigned int fd,
struct linux_dirent64 __user *dirent,
unsigned int count);
asmlinkage long sys_setsockopt(int fd, int level, int optname,
char __user *optval, int optlen);
asmlinkage long sys_getsockopt(int fd, int level, int optname,
char __user *optval, int __user *optlen);
asmlinkage long sys_bind(int, struct sockaddr __user *, int);
asmlinkage long sys_connect(int, struct sockaddr __user *, int);
asmlinkage long sys_accept(int, struct sockaddr __user *, int __user *);
asmlinkage long sys_accept4(int, struct sockaddr __user *, int __user *, int);
asmlinkage long sys_getsockname(int, struct sockaddr __user *, int __user *);
asmlinkage long sys_getpeername(int, struct sockaddr __user *, int __user *);
asmlinkage long sys_send(int, void __user *, size_t, unsigned);
asmlinkage long sys_sendto(int, void __user *, size_t, unsigned,
struct sockaddr __user *, int);
asmlinkage long sys_sendmsg(int fd, struct msghdr __user *msg, unsigned flags);
asmlinkage long sys_sendmmsg(int fd, struct mmsghdr __user *msg,
unsigned int vlen, unsigned flags);
asmlinkage long sys_recv(int, void __user *, size_t, unsigned);
asmlinkage long sys_recvfrom(int, void __user *, size_t, unsigned,
struct sockaddr __user *, int __user *);
asmlinkage long sys_recvmsg(int fd, struct msghdr __user *msg, unsigned flags);
asmlinkage long sys_recvmmsg(int fd, struct mmsghdr __user *msg,
unsigned int vlen, unsigned flags,
struct timespec __user *timeout);
asmlinkage long sys_socket(int, int, int);
asmlinkage long sys_socketpair(int, int, int, int __user *);
asmlinkage long sys_socketcall(int call, unsigned long __user *args);
asmlinkage long sys_listen(int, int);
asmlinkage long sys_poll(struct pollfd __user *ufds, unsigned int nfds,
int timeout);
asmlinkage long sys_select(int n, fd_set __user *inp, fd_set __user *outp,
fd_set __user *exp, struct timeval __user *tvp);
asmlinkage long sys_old_select(struct sel_arg_struct __user *arg);
asmlinkage long sys_epoll_create(int size);
asmlinkage long sys_epoll_create1(int flags);
asmlinkage long sys_epoll_ctl(int epfd, int op, int fd,
struct epoll_event __user *event);
asmlinkage long sys_epoll_wait(int epfd, struct epoll_event __user *events,
int maxevents, int timeout);
asmlinkage long sys_epoll_pwait(int epfd, struct epoll_event __user *events,
int maxevents, int timeout,
const sigset_t __user *sigmask,
size_t sigsetsize);
asmlinkage long sys_gethostname(char __user *name, int len);
asmlinkage long sys_sethostname(char __user *name, int len);
asmlinkage long sys_setdomainname(char __user *name, int len);
asmlinkage long sys_newuname(struct new_utsname __user *name);
asmlinkage long sys_uname(struct old_utsname __user *);
asmlinkage long sys_olduname(struct oldold_utsname __user *);
asmlinkage long sys_getrlimit(unsigned int resource,
struct rlimit __user *rlim);
#if defined(COMPAT_RLIM_OLD_INFINITY) || !(defined(CONFIG_IA64))
asmlinkage long sys_old_getrlimit(unsigned int resource, struct rlimit __user *rlim);
#endif
asmlinkage long sys_setrlimit(unsigned int resource,
struct rlimit __user *rlim);
asmlinkage long sys_prlimit64(pid_t pid, unsigned int resource,
const struct rlimit64 __user *new_rlim,
struct rlimit64 __user *old_rlim);
asmlinkage long sys_getrusage(int who, struct rusage __user *ru);
asmlinkage long sys_umask(int mask);
asmlinkage long sys_msgget(key_t key, int msgflg);
asmlinkage long sys_msgsnd(int msqid, struct msgbuf __user *msgp,
size_t msgsz, int msgflg);
asmlinkage long sys_msgrcv(int msqid, struct msgbuf __user *msgp,
size_t msgsz, long msgtyp, int msgflg);
asmlinkage long sys_msgctl(int msqid, int cmd, struct msqid_ds __user *buf);
asmlinkage long sys_semget(key_t key, int nsems, int semflg);
asmlinkage long sys_semop(int semid, struct sembuf __user *sops,
unsigned nsops);
asmlinkage long sys_semctl(int semid, int semnum, int cmd, unsigned long arg);
asmlinkage long sys_semtimedop(int semid, struct sembuf __user *sops,
unsigned nsops,
const struct timespec __user *timeout);
asmlinkage long sys_shmat(int shmid, char __user *shmaddr, int shmflg);
asmlinkage long sys_shmget(key_t key, size_t size, int flag);
asmlinkage long sys_shmdt(char __user *shmaddr);
asmlinkage long sys_shmctl(int shmid, int cmd, struct shmid_ds __user *buf);
asmlinkage long sys_ipc(unsigned int call, int first, unsigned long second,
unsigned long third, void __user *ptr, long fifth);
asmlinkage long sys_mq_open(const char __user *name, int oflag, umode_t mode, struct mq_attr __user *attr);
asmlinkage long sys_mq_unlink(const char __user *name);
asmlinkage long sys_mq_timedsend(mqd_t mqdes, const char __user *msg_ptr, size_t msg_len, unsigned int msg_prio, const struct timespec __user *abs_timeout);
asmlinkage long sys_mq_timedreceive(mqd_t mqdes, char __user *msg_ptr, size_t msg_len, unsigned int __user *msg_prio, const struct timespec __user *abs_timeout);
asmlinkage long sys_mq_notify(mqd_t mqdes, const struct sigevent __user *notification);
asmlinkage long sys_mq_getsetattr(mqd_t mqdes, const struct mq_attr __user *mqstat, struct mq_attr __user *omqstat);
asmlinkage long sys_pciconfig_iobase(long which, unsigned long bus, unsigned long devfn);
asmlinkage long sys_pciconfig_read(unsigned long bus, unsigned long dfn,
unsigned long off, unsigned long len,
void __user *buf);
asmlinkage long sys_pciconfig_write(unsigned long bus, unsigned long dfn,
unsigned long off, unsigned long len,
void __user *buf);
asmlinkage long sys_prctl(int option, unsigned long arg2, unsigned long arg3,
unsigned long arg4, unsigned long arg5);
asmlinkage long sys_swapon(const char __user *specialfile, int swap_flags);
asmlinkage long sys_swapoff(const char __user *specialfile);
asmlinkage long sys_sysctl(struct __sysctl_args __user *args);
asmlinkage long sys_sysinfo(struct sysinfo __user *info);
asmlinkage long sys_sysfs(int option,
unsigned long arg1, unsigned long arg2);
asmlinkage long sys_syslog(int type, char __user *buf, int len);
asmlinkage long sys_uselib(const char __user *library);
asmlinkage long sys_ni_syscall(void);
asmlinkage long sys_ptrace(long request, long pid, unsigned long addr,
unsigned long data);
asmlinkage long sys_add_key(const char __user *_type,
const char __user *_description,
const void __user *_payload,
size_t plen,
key_serial_t destringid);
asmlinkage long sys_request_key(const char __user *_type,
const char __user *_description,
const char __user *_callout_info,
key_serial_t destringid);
asmlinkage long sys_keyctl(int cmd, unsigned long arg2, unsigned long arg3,
unsigned long arg4, unsigned long arg5);
asmlinkage long sys_ioprio_set(int which, int who, int ioprio);
asmlinkage long sys_ioprio_get(int which, int who);
asmlinkage long sys_set_mempolicy(int mode, unsigned long __user *nmask,
unsigned long maxnode);
asmlinkage long sys_migrate_pages(pid_t pid, unsigned long maxnode,
const unsigned long __user *from,
const unsigned long __user *to);
asmlinkage long sys_move_pages(pid_t pid, unsigned long nr_pages,
const void __user * __user *pages,
const int __user *nodes,
int __user *status,
int flags);
asmlinkage long sys_mbind(unsigned long start, unsigned long len,
unsigned long mode,
unsigned long __user *nmask,
unsigned long maxnode,
unsigned flags);
asmlinkage long sys_get_mempolicy(int __user *policy,
unsigned long __user *nmask,
unsigned long maxnode,
unsigned long addr, unsigned long flags);
asmlinkage long sys_inotify_init(void);
asmlinkage long sys_inotify_init1(int flags);
asmlinkage long sys_inotify_add_watch(int fd, const char __user *path,
u32 mask);
asmlinkage long sys_inotify_rm_watch(int fd, __s32 wd);
asmlinkage long sys_spu_run(int fd, __u32 __user *unpc,
__u32 __user *ustatus);
asmlinkage long sys_spu_create(const char __user *name,
unsigned int flags, umode_t mode, int fd);
asmlinkage long sys_mknodat(int dfd, const char __user * filename, umode_t mode,
unsigned dev);
asmlinkage long sys_mkdirat(int dfd, const char __user * pathname, umode_t mode);
asmlinkage long sys_unlinkat(int dfd, const char __user * pathname, int flag);
asmlinkage long sys_symlinkat(const char __user * oldname,
int newdfd, const char __user * newname);
asmlinkage long sys_linkat(int olddfd, const char __user *oldname,
int newdfd, const char __user *newname, int flags);
asmlinkage long sys_renameat(int olddfd, const char __user * oldname,
int newdfd, const char __user * newname);
asmlinkage long sys_futimesat(int dfd, const char __user *filename,
struct timeval __user *utimes);
asmlinkage long sys_faccessat(int dfd, const char __user *filename, int mode);
asmlinkage long sys_fchmodat(int dfd, const char __user * filename,
umode_t mode);
asmlinkage long sys_fchownat(int dfd, const char __user *filename, uid_t user,
gid_t group, int flag);
asmlinkage long sys_openat(int dfd, const char __user *filename, int flags,
umode_t mode);
asmlinkage long sys_newfstatat(int dfd, const char __user *filename,
struct stat __user *statbuf, int flag);
asmlinkage long sys_fstatat64(int dfd, const char __user *filename,
struct stat64 __user *statbuf, int flag);
asmlinkage long sys_readlinkat(int dfd, const char __user *path, char __user *buf,
int bufsiz);
asmlinkage long sys_utimensat(int dfd, const char __user *filename,
struct timespec __user *utimes, int flags);
asmlinkage long sys_unshare(unsigned long unshare_flags);
asmlinkage long sys_splice(int fd_in, loff_t __user *off_in,
int fd_out, loff_t __user *off_out,
size_t len, unsigned int flags);
asmlinkage long sys_vmsplice(int fd, const struct iovec __user *iov,
unsigned long nr_segs, unsigned int flags);
asmlinkage long sys_tee(int fdin, int fdout, size_t len, unsigned int flags);
asmlinkage long sys_sync_file_range(int fd, loff_t offset, loff_t nbytes,
unsigned int flags);
asmlinkage long sys_sync_file_range2(int fd, unsigned int flags,
loff_t offset, loff_t nbytes);
asmlinkage long sys_get_robust_list(int pid,
struct robust_list_head __user * __user *head_ptr,
size_t __user *len_ptr);
asmlinkage long sys_set_robust_list(struct robust_list_head __user *head,
size_t len);
asmlinkage long sys_getcpu(unsigned __user *cpu, unsigned __user *node, struct getcpu_cache __user *cache);
asmlinkage long sys_signalfd(int ufd, sigset_t __user *user_mask, size_t sizemask);
asmlinkage long sys_signalfd4(int ufd, sigset_t __user *user_mask, size_t sizemask, int flags);
asmlinkage long sys_timerfd_create(int clockid, int flags);
asmlinkage long sys_timerfd_settime(int ufd, int flags,
const struct itimerspec __user *utmr,
struct itimerspec __user *otmr);
asmlinkage long sys_timerfd_gettime(int ufd, struct itimerspec __user *otmr);
asmlinkage long sys_eventfd(unsigned int count);
asmlinkage long sys_eventfd2(unsigned int count, int flags);
asmlinkage long sys_fallocate(int fd, int mode, loff_t offset, loff_t len);
asmlinkage long sys_old_readdir(unsigned int, struct old_linux_dirent __user *, unsigned int);
asmlinkage long sys_pselect6(int, fd_set __user *, fd_set __user *,
fd_set __user *, struct timespec __user *,
void __user *);
asmlinkage long sys_ppoll(struct pollfd __user *, unsigned int,
struct timespec __user *, const sigset_t __user *,
size_t);
asmlinkage long sys_fanotify_init(unsigned int flags, unsigned int event_f_flags);
asmlinkage long sys_fanotify_mark(int fanotify_fd, unsigned int flags,
u64 mask, int fd,
const char __user *pathname);
asmlinkage long sys_syncfs(int fd);
asmlinkage long sys_fork(void);
asmlinkage long sys_vfork(void);
#ifdef CONFIG_CLONE_BACKWARDS
asmlinkage long sys_clone(unsigned long, unsigned long, int __user *, int,
int __user *);
#else
#ifdef CONFIG_CLONE_BACKWARDS3
asmlinkage long sys_clone(unsigned long, unsigned long, int, int __user *,
int __user *, int);
#else
asmlinkage long sys_clone(unsigned long, unsigned long, int __user *,
int __user *, int);
#endif
#endif
asmlinkage long sys_execve(const char __user *filename,
const char __user *const __user *argv,
const char __user *const __user *envp);
asmlinkage long sys_perf_event_open(
struct perf_event_attr __user *attr_uptr,
pid_t pid, int cpu, int group_fd, unsigned long flags);
asmlinkage long sys_mmap_pgoff(unsigned long addr, unsigned long len,
unsigned long prot, unsigned long flags,
unsigned long fd, unsigned long pgoff);
asmlinkage long sys_old_mmap(struct mmap_arg_struct __user *arg);
asmlinkage long sys_name_to_handle_at(int dfd, const char __user *name,
struct file_handle __user *handle,
int __user *mnt_id, int flag);
asmlinkage long sys_open_by_handle_at(int mountdirfd,
struct file_handle __user *handle,
int flags);
asmlinkage long sys_setns(int fd, int nstype);
asmlinkage long sys_process_vm_readv(pid_t pid,
const struct iovec __user *lvec,
unsigned long liovcnt,
const struct iovec __user *rvec,
unsigned long riovcnt,
unsigned long flags);
asmlinkage long sys_process_vm_writev(pid_t pid,
const struct iovec __user *lvec,
unsigned long liovcnt,
const struct iovec __user *rvec,
unsigned long riovcnt,
unsigned long flags);
asmlinkage long sys_kcmp(pid_t pid1, pid_t pid2, int type,
unsigned long idx1, unsigned long idx2);
asmlinkage long sys_finit_module(int fd, const char __user *uargs, int flags);
/* ogh_test */
asmlinkage long sys_ogh_test(void);
asmlinkage long sys_set_timetable(struct timetable * tt, int num);
asmlinkage long sys_check_timetable(struct timetable* tt, int* retval);
#endif
| wurikiji/ttFS | ulinux/linux-3.10.61/include/linux/syscalls.h | C | gpl-2.0 | 37,560 |
/*
* CLabel.java
*
* Copyright 2014 Subhraman Sarkar <subhraman@subhraman-Inspiron-660s>
*
* 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.
*
*
*/
package clz;
import java.awt.Color;
import java.awt.Dimension;
import java.io.IOException;
import java.util.Stack;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.border.LineBorder;
public class CLabel extends JLabel {
private static final long serialVersionUID = 1L;
private Stack<Card> cards = new Stack<Card>();
//public static Card ncrd = new Card("No Card", "/images/NCRD.jpg");
private boolean fliped;
private boolean used;
private boolean upside_down;
private String tooltip =
"<html><body>Click to move and click again on another card to paste.<br/>" +
"Move the mouse wheel to use/unuse.</body></html>";
public CLabel() throws IOException {
//this(ncrd);
//System.out.println("Generated");
super(ImageManipulator.scale(
new ImageIcon(
ImageIO.read(CLabel.class.getResourceAsStream("/images/NCRD.jpg"))), 64, 87));
setPreferredSize(new Dimension(64, 87));
}
public CLabel(Card card1) {
super(ImageManipulator.scale(card1.getImCard(), 64, 87));
cards.add(card1);
fliped = false;
used = false;
setUpsideDown(false);
if (card1.name.equalsIgnoreCase("No Card")) {
this.setToolTipText(tooltip);
} else {
StringBuffer effects = new StringBuffer();
effects.append("<html>");
effects.append("<body>");
effects.append("<h1>" + card1.name + "</h1>");
effects.append("<br/>");
effects.append("<p><b>Energy : </b>" + Card.energyToString(card1.energy) + "</p>");
effects.append("<p><b>Type : </b>" + card1.type + "</p>");
effects.append("<p><b>Subtype : </b>" + card1.subtype + "</p>");
effects.append("<p><b>Power : </b>" + card1.power + "</p>");
effects.append("<p><b>Damage : </b>" + card1.damage + "</p>");
effects.append("<p><b>Effects : </b><br/>");
for (String effect : card1.effects) {
effects.append(effect);
effects.append("<br/>");
}
effects.append("</p>");
effects.append("</body>");
effects.append("</html>");
this.setToolTipText(effects.toString());
// this.setToolTipText(card1.name + ","
// + Card.energyToString(card1.energy) + ","
// + Card.energyToString(card1.eno));
}
setPreferredSize(new Dimension(64, 87));
}
public CLabel(String text) {
super(text);
//cards.add(ncrd);
fliped = false;
used = false;
this.setToolTipText(tooltip);
setPreferredSize(new Dimension(64, 87));
}
public CLabel(Icon image) {
super(ImageManipulator.scale(image, 64, 87));
//cards.add(ncrd);
fliped = false;
used = false;
this.setToolTipText(tooltip);
setPreferredSize(new Dimension(64, 87));
}
public CLabel(String text, int horizontalAlignment) {
super(text, horizontalAlignment);
//cards.add(ncrd);
fliped = false;
used = false;
this.setToolTipText(tooltip);
setPreferredSize(new Dimension(64, 87));
}
public CLabel(Icon image, int horizontalAlignment) {
super(ImageManipulator.scale(image, 64, 87), horizontalAlignment);
// cards.add(ncrd);
fliped = false;
used = false;
this.setToolTipText(tooltip);
setPreferredSize(new Dimension(64, 87));
}
public CLabel(String text, Icon image, int horizontalAlignment) {
super(text, ImageManipulator.scale(image, 64, 87), horizontalAlignment);
// cards.add(ncrd);
fliped = false;
used = false;
this.setToolTipText(tooltip);
setPreferredSize(new Dimension(64, 87));
}
public final boolean isUsed() {
return this.used;
}
public final void setUsed(boolean used) {
this.used = used;
}
public Card getCard() {
if (cards.size() > 0) {
Card card2 = cards.lastElement();
super.setIcon(ImageManipulator.scale(cards.lastElement().getImCard(), 64, 87));
return card2;
} else {
return null;
}
}
public Card grCard() {
if (cards.size() > 0) {
Card card2 = cards.pop();
if (cards.size() > 0) {
super.setIcon(ImageManipulator.scale(cards.lastElement().getImCard(), 64, 87));
} else {
// this.setCard(ncrd);
try {
super.setIcon(
ImageManipulator.scale(
new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/images/NCRD.jpg"))), 64, 87
));
} catch(Exception e) {
// What to do if the image is missing?
System.err.println("Missing Resource!");
}
}
return card2;
} else {
return null; // NULL
}
}
public void setCard(Card card0) {
if (card0 != null) {
cards.add(card0);
super.setIcon(ImageManipulator.scale(card0.getImCard(), 64, 87));
if (card0.name.equalsIgnoreCase("No Card")) {
this.setToolTipText(tooltip);
} else {
this.setToolTipText(
card0.name + "," + Card.energyToString(card0.energy) + "," + Card.energyToString(card0.eno));
}
}
}
public void showFullImage() {
this.setIcon(this.getCard().getImCard());
}
public void showNormalImage() {
this.setIcon(ImageManipulator.scale(this.getCard().getImCard(), 64, 87));
}
public void flip() {
//imCard2 = imCard;
Card card = this.getCard();
if (card.bkCard != null) {
if (fliped) {
this.setIcon(ImageManipulator.scale(card.getImCard(), 64, 87));
fliped = false;
} else {
this.setIcon(ImageManipulator.scale(card.bkCard, 64, 87));
fliped = true;
}
}
}
public void use2() {
setUsed(true);
Card c = this.getCard();
if (c.civility.equalsIgnoreCase("Raenid")) {
this.setBorder(new LineBorder(Color.YELLOW, 2));
} else if (c.civility.equalsIgnoreCase("Asarn")) {
this.setBorder(new LineBorder(Color.RED, 2));
} else if (c.civility.equalsIgnoreCase("Mayarth")) {
this.setBorder(new LineBorder(Color.ORANGE, 2));
} else if (c.civility.equalsIgnoreCase("Zivar")) {
this.setBorder(new LineBorder(Color.BLACK, 2));
} else if (c.civility.equalsIgnoreCase("Niaz")) {
this.setBorder(new LineBorder(Color.BLUE, 2));
} else if (c.civility.equalsIgnoreCase("Kshiti")) {
this.setBorder(new LineBorder(Color.GREEN, 2));
} else {
this.setBorder(new LineBorder(Color.DARK_GRAY, 2));
}
repaint();
}
public void unuse2() {
setUsed(false);
this.setBorder(null);
repaint();
}
public void rot_90() {
setUsed(true);
ImageIcon img = ImageManipulator.scale(this.getCard().getImCard(), 64, 87);
ImageIcon rot_img = ImageManipulator.rotate90(img);
this.setIcon(rot_img);
}
public void rot_180() {
ImageIcon img = ImageManipulator.scale(this.getCard().getImCard(), 64, 87);
if (isUpsideDown()) {
setUpsideDown(false);
} else {
setUpsideDown(true);
img = ImageManipulator.flipVert(img);
}
this.setIcon(img);
}
public void rot_0() {
setUsed(false);
ImageIcon img = ImageManipulator.scale(this.getCard().getImCard(), 64, 87);
// Flipping the image if it was flipped before tapping.
if (isUpsideDown()) {
img = ImageManipulator.flipVert(img);
}
this.setIcon(img);
}
// public void flipBack() {
// setUpsideDown(false);
// setOrig();
// }
//
// public void unuse() {
// setUsed(false);
// if (!isUpsideDown()) {
// setOrig();
// } else {
// ImageIcon img = ImageManipulator.scale(this.getIcon(), 64, 87);
// ImageIcon rot_img = ImageManipulator.flipVert(img);
// this.setIcon(rot_img);
// }
// }
//
public void setOrig() {
this.setIcon(ImageManipulator.scale(this.getCard().getImCard(), 64, 87));
}
public boolean isUpsideDown() {
return upside_down;
}
public void setUpsideDown(boolean upside_down) {
this.upside_down = upside_down;
}
}
| babaissarkar/paladin | clz/CLabel.java | Java | gpl-2.0 | 8,259 |
package sys.vp8;
import sys.vp8.lib.*;
import sys.vp8.lib.Vp8Library.*;
import org.bridj.*;
public class Converter {
// Converts RGB24 data (packed as ARGB ints) to a VPX YUV I420 image
public static void ConvertRGB24ToI420(int[] rgbData, Pointer<vpx_image_t> img) {
int width = img.get().d_w();
int height = img.get().d_h();
Pointer<Byte> imgY = img.get().planes().get(Vp8Library.VPX_PLANE_Y);
Pointer<Byte> imgU = img.get().planes().get(Vp8Library.VPX_PLANE_U);
Pointer<Byte> imgV = img.get().planes().get(Vp8Library.VPX_PLANE_V);
int i1 = 0;
int uvi = 0;
for (int ypos = 0; ypos < height; ypos += 2) {
for (int xpos = 0; xpos < width; xpos += 2) {
int i2 = i1 + 1;
int i3 = width + i1;
int i4 = width + i2;
int rgb1 = rgbData[i1];
int rgb2 = rgbData[i2];
int rgb3 = rgbData[i3];
int rgb4 = rgbData[i4];
int r1 = unpackR(rgb1);
int g1 = unpackG(rgb1);
int b1 = unpackB(rgb1);
int r2 = unpackR(rgb2);
int g2 = unpackG(rgb2);
int b2 = unpackB(rgb2);
int r3 = unpackR(rgb3);
int g3 = unpackG(rgb3);
int b3 = unpackB(rgb3);
int r4 = unpackR(rgb4);
int g4 = unpackG(rgb4);
int b4 = unpackB(rgb4);
imgY.set(i1, (byte) getY(r1, g1, b1));
imgY.set(i2, (byte) getY(r2, g2, b2));
imgY.set(i3, (byte) getY(r3, g3, b3));
imgY.set(i4, (byte) getY(r4, g4, b4));
int u1 = getU(r1, g1, b1);
int u2 = getU(r2, g2, b2);
int u3 = getU(r3, g3, b3);
int u4 = getU(r4, g4, b4);
int v1 = getV(r1, g1, b1);
int v2 = getV(r2, g2, b2);
int v3 = getV(r3, g3, b3);
int v4 = getV(r4, g4, b4);
imgU.set(uvi, (byte) ((u1 + u2 + u3 + u4) / 4));
imgV.set(uvi, (byte) ((v1 + v2 + v3 + v4) / 4));
i1 += 2;
uvi++;
}
i1 += width;
}
}
// Converts a VPX YUV I420 image to RGB24 data (packed as ARGB ints)
public static void ConvertI420ToRGB24(Pointer<vpx_image_t> img, int[] rgbData) {
int width = img.get().d_w();
int height = img.get().d_h();
Pointer<Byte> imgY = img.get().planes().get(Vp8Library.VPX_PLANE_Y);
Pointer<Byte> imgU = img.get().planes().get(Vp8Library.VPX_PLANE_U);
Pointer<Byte> imgV = img.get().planes().get(Vp8Library.VPX_PLANE_V);
int yPadding = img.get().stride().get(Vp8Library.VPX_PLANE_Y) - width;
int uPadding = img.get().stride().get(Vp8Library.VPX_PLANE_U) - (width / 2);
int vPadding = img.get().stride().get(Vp8Library.VPX_PLANE_V) - (width / 2);
int yi = 0;
int ui = 0;
int vi = 0;
int rgbi = 0;
for (int ypos = 0; ypos < height; ypos++) {
for (int xpos = 0; xpos < width; xpos++) {
int y = imgY.get(yi) & 0xFF;
int u = imgU.get(ui) & 0xFF;
int v = imgV.get(vi) & 0xFF;
int r = getR(y, u, v);
int g = getG(y, u, v);
int b = getB(y, u, v);
rgbData[rgbi++] = packRGB(r, g, b);
yi++;
if (xpos % 2 == 1) {
ui++;
vi++;
}
}
yi += yPadding;
if (ypos % 2 == 0) {
ui -= (width / 2);
vi -= (width / 2);
} else {
ui += uPadding;
vi += vPadding;
}
}
}
private static int unpackR(int rgb) {
return (rgb >> 16) & 0xFF;
}
private static int unpackG(int rgb) {
return (rgb >> 8) & 0xFF;
}
private static int unpackB(int rgb) {
return (rgb >> 0) & 0xFF;
}
private static int packRGB(int r, int g, int b) {
return 0xFF000000
| (r & 0xFF) << 16
| (g & 0xFF) << 8
| (b & 0xFF) << 0;
}
private static int getR(int y, int u, int v) {
return clamp(y + (int) (1.402f * (v - 128)));
}
private static int getG(int y, int u, int v) {
return clamp(y - (int) (0.344f * (u - 128) + 0.714f * (v - 128)));
}
private static int getB(int y, int u, int v) {
return clamp(y + (int) (1.772f * (u - 128)));
}
private static int getY(int r, int g, int b) {
return (int) (0.299f * r + 0.587f * g + 0.114f * b);
}
private static int getU(int r, int g, int b) {
return (int) (-0.169f * r - 0.331f * g + 0.499f * b + 128);
}
private static int getV(int r, int g, int b) {
return (int) (0.499f * r - 0.418f * g - 0.0813f * b + 128);
}
private static int clamp(int value) {
return Math.min(Math.max(value, 0), 255);
}
} | Exiliot/video-conference | ClientSystem/src/sys/vp8/Converter.java | Java | gpl-2.0 | 5,166 |
<?php
/**
* XML Sitemap Feed Template for displaying an XML Sitemap feed.
*
* @package XML Sitemap Feed plugin for WordPress
*/
if ( ! defined( 'WPINC' ) ) die;
// do xml tag via echo or SVN parser is going to freak out
echo '<?xml version="1.0" encoding="' . get_bloginfo('charset') . '"?>
'; ?>
<?php xmlsf_xml_stylesheet( 'author' ); ?>
<?php do_action( 'xmlsf_generator' ); ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
<?php do_action( 'xmlsf_urlset', 'home' ); ?>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<?php
$users = get_users( apply_filters( 'get_users_args', array() ) );
foreach ( $users as $user ) {
$url = get_author_posts_url( $user->ID );
// Check if we are dealing with an external URL. This can happen with multi-language plugins where each language has its own domain.
if ( ! xmlsf_is_allowed_domain( $url ) ) continue;
// allow filtering of users
if ( apply_filters( 'xmlsf_skip_user', false, $user ) ) continue;
?>
<url>
<loc><?php echo esc_url( $url ); ?></loc>
<priority><?php echo xmlsf_get_user_priority( $user ); ?></priority>
<?php if ( $lastmod = xmlsf_get_user_modified( $user ) ) { ?>
<lastmod><?php echo $lastmod; ?></lastmod>
<?php }
do_action( 'xmlsf_tags_after', 'author' );
?>
</url>
<?php
do_action( 'xmlsf_url_after', 'author' );
}
?>
</urlset>
<?php xmlsf_usage(); ?>
| RavanH/xml-sitemap-feed | views/feed-sitemap-author.php | PHP | gpl-2.0 | 1,485 |
<?php
namespace Proweb\CommonBundle;
use Proweb\CommonBundle\DependencyInjection\Compiler\MapperCollectionPass;
use Proweb\CommonBundle\DependencyInjection\Compiler\PropelEventDispatcherCompilerPass;
use Proweb\CommonBundle\DependencyInjection\Compiler\PropelQueryAsServiceCompilerPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/**
* @author Marek Kalnik <marekk@theodo.fr>
* @package NosbProwebCommonBundle
*/
class ProwebCommonBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new PropelQueryAsServiceCompilerPass());
$container->addCompilerPass(new MapperCollectionPass());
$container->addCompilerPass(new PropelEventDispatcherCompilerPass());
}
}
| gvandencruche/project_symfony | proweb/src/Proweb/CommonBundle/ProwebCommonBundle.php | PHP | gpl-2.0 | 851 |
<?php
/**
* The loop that displays a single post.
*
* The loop displays the posts and the post content. See
* http://codex.wordpress.org/The_Loop to understand it and
* http://codex.wordpress.org/Template_Tags to understand
* the tags used in it.
*
* This can be overridden in child themes with loop-single.php.
*
* @package WordPress
* @subpackage Twenty_Ten
* @since Twenty Ten 1.2
*/
?>
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<div id="loopsinglecontent">
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h2><a HREF="javascript:javascript:history.go(-1)"><< Back</a>
<h3><?php the_date(); ?></h3>
<h1 class="entry-title"><?php the_title(); ?></h1>
<div class="entry-content">
<?php the_content();?>
<div id="entry-author-info">
Posted by <b><?php the_author(); ?></b>
</div>
<?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'twentyten' ), 'after' => '</div>' ) ); ?>
</div><!-- .entry-content -->
<?php endwhile; // end of the loop. ?>
</div>
</div>
<div id="articlesidebar">
<h2>Recent Articles</h2>
<ul>
<?php query_posts( array(
'posts_per_page' => 10,
'category_name' => Blog,
'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1 ),
));
?>
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<a href="<?php the_permalink() ?>" rel="bookmark">
<li><h1><?php the_date(); ?></h1>
<?php the_title(); ?>
</li></a>
<?php endwhile; ?>
</ul>
<?php get_sidebar();?>
</div>
<?php get_footer(); ?>
<STYLE type="text/css">
#primary {display:inherit !important;}
#article{ margin-bottom:10px !important;
}
</STYLE> | lionellsgithub/underwaterpeoples.com | loop-single.php | PHP | gpl-2.0 | 1,717 |
/*
* Copyright (c) 2020, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted.phases;
import java.util.HashMap;
import java.util.Map;
import org.graalvm.compiler.api.replacements.SnippetReflectionProvider;
import org.graalvm.compiler.nodes.ConstantNode;
import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderContext;
import org.graalvm.compiler.nodes.graphbuilderconf.NodePlugin;
import org.graalvm.nativeimage.impl.clinit.ClassInitializationTracking;
import com.oracle.graal.pointsto.infrastructure.OriginalClassProvider;
import com.oracle.svm.core.RuntimeAssertionsSupport;
import com.oracle.svm.util.ReflectionUtil;
import jdk.vm.ci.meta.ConstantReflectionProvider;
import jdk.vm.ci.meta.JavaKind;
import jdk.vm.ci.meta.MetaAccessProvider;
import jdk.vm.ci.meta.ResolvedJavaField;
import jdk.vm.ci.meta.ResolvedJavaType;
/**
* Early constant folding for well-known static fields. These constant foldings do not require and
* {@link ConstantReflectionProvider}.
*/
public class EarlyConstantFoldLoadFieldPlugin implements NodePlugin {
private final ResolvedJavaField isImageBuildTimeField;
private final SnippetReflectionProvider snippetReflection;
private final Map<ResolvedJavaType, ResolvedJavaType> primitiveTypes;
public EarlyConstantFoldLoadFieldPlugin(MetaAccessProvider metaAccess, SnippetReflectionProvider snippetReflection) {
isImageBuildTimeField = metaAccess.lookupJavaField(ReflectionUtil.lookupField(ClassInitializationTracking.class, "IS_IMAGE_BUILD_TIME"));
this.snippetReflection = snippetReflection;
primitiveTypes = new HashMap<>();
for (JavaKind kind : JavaKind.values()) {
if (kind.toBoxedJavaClass() != null) {
primitiveTypes.put(metaAccess.lookupJavaType(kind.toBoxedJavaClass()), metaAccess.lookupJavaType(kind.toJavaClass()));
}
}
}
@Override
public boolean handleLoadStaticField(GraphBuilderContext b, ResolvedJavaField field) {
if (field.equals(isImageBuildTimeField)) {
/*
* Loads of this field are injected into class initializers to provide stack traces when
* a class is wrongly initialized at image build time.
*/
b.addPush(JavaKind.Boolean, ConstantNode.forBoolean(false));
return true;
} else if (field.isSynthetic() && field.getName().startsWith("$assertionsDisabled")) {
/*
* Intercept assertion status: the value of the field during image generation does not
* matter at all (because it is the hosted assertion status), we instead return the
* appropriate runtime assertion status.
*/
Class<?> javaClass = OriginalClassProvider.getJavaClass(snippetReflection, field.getDeclaringClass());
boolean assertionsEnabled = RuntimeAssertionsSupport.singleton().desiredAssertionStatus(javaClass);
b.addPush(JavaKind.Boolean, ConstantNode.forBoolean(!assertionsEnabled));
return true;
}
/*
* Constant fold e.g. `Integer.TYPE`, which is accessed when using the literal `int.class`
* in Java code.
*/
if (field.getName().equals("TYPE")) {
ResolvedJavaType primitiveType = primitiveTypes.get(field.getDeclaringClass());
if (primitiveType != null) {
b.addPush(JavaKind.Object, ConstantNode.forConstant(b.getConstantReflection().asJavaClass(primitiveType), b.getMetaAccess()));
return true;
}
}
return false;
}
}
| smarr/Truffle | substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/phases/EarlyConstantFoldLoadFieldPlugin.java | Java | gpl-2.0 | 4,777 |
"""In the case that the Setup.py file fails to execute, please manually install the following packages,
or execute the requirements.sh script."""
# Installing Requirements: #
# pip install git+https://github.com/pwaller/pyfiglet #
# pip install colorama #
# pip install termcolor #
# pip install blessings #
from distutils.core import setup
setup(name='DPS East Hackathon Rule booklet.',
version='1.0',
description='DPS East Hackathon Rule booklet.',
author='thel3l',
author_email='i.rithwik@protonmail.com',
url='https://www.github.com/thel3l/hackathon-dpse',
packages=['distutils', 'distutils.command', 'pyfiglet', 'colorama', 'termcolor', 'blessings'],
)
| xxHACKYHACKYXx/hackathon-dpse | Rule booklet in Python/Setup.py | Python | gpl-2.0 | 875 |
/* $Id$ */
/** @file
* VBox Debugger GUI - Console.
*/
/*
* Copyright (C) 2006-2010 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#define LOG_GROUP LOG_GROUP_DBGG
#include "VBoxDbgConsole.h"
#include <QLabel>
#include <QApplication>
#include <QFont>
#include <QLineEdit>
#include <QHBoxLayout>
#include <QAction>
#include <QContextMenuEvent>
#include <VBox/dbg.h>
#include <VBox/vmm/cfgm.h>
#include <VBox/err.h>
#include <iprt/thread.h>
#include <iprt/tcp.h>
#include <VBox/log.h>
#include <iprt/assert.h>
#include <iprt/asm.h>
#include <iprt/alloc.h>
#include <iprt/string.h>
/*
*
* V B o x D b g C o n s o l e O u t p u t
* V B o x D b g C o n s o l e O u t p u t
* V B o x D b g C o n s o l e O u t p u t
*
*
*/
VBoxDbgConsoleOutput::VBoxDbgConsoleOutput(QWidget *pParent/* = NULL*/, const char *pszName/* = NULL*/)
: QTextEdit(pParent), m_uCurLine(0), m_uCurPos(0), m_hGUIThread(RTThreadNativeSelf())
{
setReadOnly(true);
setUndoRedoEnabled(false);
setOverwriteMode(false);
setPlainText("");
setTextInteractionFlags(Qt::TextBrowserInteraction);
setAutoFormatting(QTextEdit::AutoAll);
setTabChangesFocus(true);
setAcceptRichText(false);
#ifdef Q_WS_MAC
QFont Font("Monaco", 10, QFont::Normal, FALSE);
Font.setStyleStrategy(QFont::NoAntialias);
#else
QFont Font = font();
Font.setStyleHint(QFont::TypeWriter);
Font.setFamily("Courier [Monotype]");
#endif
setFont(Font);
/* green on black */
QPalette Pal(palette());
Pal.setColor(QPalette::All, QPalette::Base, QColor(Qt::black));
setPalette(Pal);
setTextColor(QColor(qRgb(0, 0xe0, 0)));
NOREF(pszName);
}
VBoxDbgConsoleOutput::~VBoxDbgConsoleOutput()
{
Assert(m_hGUIThread == RTThreadNativeSelf());
}
void
VBoxDbgConsoleOutput::appendText(const QString &rStr)
{
Assert(m_hGUIThread == RTThreadNativeSelf());
if (rStr.isEmpty() || rStr.isNull() || !rStr.length())
return;
/*
* Insert all in one go and make sure it's visible.
*/
QTextCursor Cursor = textCursor();
if (!Cursor.atEnd())
moveCursor(QTextCursor::End); /* make sure we append the text */
Cursor.insertText(rStr);
ensureCursorVisible();
}
/*
*
* V B o x D b g C o n s o l e I n p u t
* V B o x D b g C o n s o l e I n p u t
* V B o x D b g C o n s o l e I n p u t
*
*
*/
VBoxDbgConsoleInput::VBoxDbgConsoleInput(QWidget *pParent/* = NULL*/, const char *pszName/* = NULL*/)
: QComboBox(pParent), m_iBlankItem(0), m_hGUIThread(RTThreadNativeSelf())
{
insertItem(m_iBlankItem, "");
setEditable(true);
setInsertPolicy(NoInsert);
setAutoCompletion(false);
setMaxCount(50);
const QLineEdit *pEdit = lineEdit();
if (pEdit)
connect(pEdit, SIGNAL(returnPressed()), this, SLOT(returnPressed()));
NOREF(pszName);
}
VBoxDbgConsoleInput::~VBoxDbgConsoleInput()
{
Assert(m_hGUIThread == RTThreadNativeSelf());
}
void
VBoxDbgConsoleInput::setLineEdit(QLineEdit *pEdit)
{
Assert(m_hGUIThread == RTThreadNativeSelf());
QComboBox::setLineEdit(pEdit);
if (lineEdit() == pEdit && pEdit)
connect(pEdit, SIGNAL(returnPressed()), this, SLOT(returnPressed()));
}
void
VBoxDbgConsoleInput::returnPressed()
{
Assert(m_hGUIThread == RTThreadNativeSelf());
/* deal with the current command. */
QString Str = currentText();
emit commandSubmitted(Str);
/* update the history and clear the entry field */
QString PrevStr = m_iBlankItem > 0 ? itemText(m_iBlankItem - 1) : "";
if (PrevStr != Str)
{
setItemText(m_iBlankItem, Str);
if ( m_iBlankItem > 0
&& m_iBlankItem >= maxCount() - 1)
removeItem(m_iBlankItem - maxCount() - 1);
insertItem(++m_iBlankItem, "");
}
clearEditText();
setCurrentIndex(m_iBlankItem);
}
/*
*
* V B o x D b g C o n s o l e
* V B o x D b g C o n s o l e
* V B o x D b g C o n s o l e
*
*
*/
VBoxDbgConsole::VBoxDbgConsole(VBoxDbgGui *a_pDbgGui, QWidget *a_pParent/* = NULL*/)
: VBoxDbgBaseWindow(a_pDbgGui, a_pParent), m_pOutput(NULL), m_pInput(NULL), m_fInputRestoreFocus(false),
m_pszInputBuf(NULL), m_cbInputBuf(0), m_cbInputBufAlloc(0),
m_pszOutputBuf(NULL), m_cbOutputBuf(0), m_cbOutputBufAlloc(0),
m_pTimer(NULL), m_fUpdatePending(false), m_Thread(NIL_RTTHREAD), m_EventSem(NIL_RTSEMEVENT),
m_fTerminate(false), m_fThreadTerminated(false)
{
setWindowTitle("VBoxDbg - Console");
/*
* Create the output text box.
*/
m_pOutput = new VBoxDbgConsoleOutput(this);
/* try figure a suitable size */
QLabel *pLabel = new QLabel( "11111111111111111111111111111111111111111111111111111111111111111111111111111112222222222", this);
pLabel->setFont(m_pOutput->font());
QSize Size = pLabel->sizeHint();
delete pLabel;
Size.setWidth((int)(Size.width() * 1.10));
Size.setHeight(Size.width() / 2);
resize(Size);
/*
* Create the input combo box (with a label).
*/
QHBoxLayout *pLayout = new QHBoxLayout();
//pLayout->setSizeConstraint(QLayout::SetMaximumSize);
pLabel = new QLabel(" Command ");
pLayout->addWidget(pLabel);
pLabel->setMaximumSize(pLabel->sizeHint());
pLabel->setAlignment(Qt::AlignCenter);
m_pInput = new VBoxDbgConsoleInput(NULL);
pLayout->addWidget(m_pInput);
m_pInput->setDuplicatesEnabled(false);
connect(m_pInput, SIGNAL(commandSubmitted(const QString &)), this, SLOT(commandSubmitted(const QString &)));
# if 0//def Q_WS_MAC
pLabel = new QLabel(" ");
pLayout->addWidget(pLabel);
pLabel->setMaximumSize(20, m_pInput->sizeHint().height() + 6);
pLabel->setMinimumSize(20, m_pInput->sizeHint().height() + 6);
# endif
QWidget *pHBox = new QWidget(this);
pHBox->setLayout(pLayout);
m_pInput->setEnabled(false); /* (we'll get a ready notification) */
/*
* Vertical layout box on the whole widget.
*/
QVBoxLayout *pVLayout = new QVBoxLayout();
pVLayout->setContentsMargins(0, 0, 0, 0);
pVLayout->setSpacing(5);
pVLayout->addWidget(m_pOutput);
pVLayout->addWidget(pHBox);
setLayout(pVLayout);
/*
* The tab order is from input to output, not the other way around as it is by default.
*/
setTabOrder(m_pInput, m_pOutput);
/*
* Setup the timer.
*/
m_pTimer = new QTimer(this);
connect(m_pTimer, SIGNAL(timeout()), SLOT(updateOutput()));
/*
* Init the backend structure.
*/
m_Back.Core.pfnInput = backInput;
m_Back.Core.pfnRead = backRead;
m_Back.Core.pfnWrite = backWrite;
m_Back.Core.pfnSetReady = backSetReady;
m_Back.pSelf = this;
/*
* Create the critical section, the event semaphore and the debug console thread.
*/
int rc = RTCritSectInit(&m_Lock);
AssertRC(rc);
rc = RTSemEventCreate(&m_EventSem);
AssertRC(rc);
rc = RTThreadCreate(&m_Thread, backThread, this, 0, RTTHREADTYPE_DEBUGGER, RTTHREADFLAGS_WAITABLE, "VBoxDbgC");
AssertRC(rc);
if (RT_FAILURE(rc))
m_Thread = NIL_RTTHREAD;
/*
* Shortcuts.
*/
m_pFocusToInput = new QAction("", this);
m_pFocusToInput->setShortcut(QKeySequence("Ctrl+L"));
addAction(m_pFocusToInput);
connect(m_pFocusToInput, SIGNAL(triggered(bool)), this, SLOT(actFocusToInput()));
m_pFocusToOutput = new QAction("", this);
m_pFocusToOutput->setShortcut(QKeySequence("Ctrl+O"));
addAction(m_pFocusToOutput);
connect(m_pFocusToOutput, SIGNAL(triggered(bool)), this, SLOT(actFocusToOutput()));
}
VBoxDbgConsole::~VBoxDbgConsole()
{
Assert(isGUIThread());
/*
* Wait for the thread.
*/
ASMAtomicWriteBool(&m_fTerminate, true);
RTSemEventSignal(m_EventSem);
if (m_Thread != NIL_RTTHREAD)
{
int rc = RTThreadWait(m_Thread, 15000, NULL);
AssertRC(rc);
m_Thread = NIL_RTTHREAD;
}
/*
* Free resources.
*/
delete m_pTimer;
m_pTimer = NULL;
RTCritSectDelete(&m_Lock);
RTSemEventDestroy(m_EventSem);
m_EventSem = 0;
m_pOutput = NULL;
m_pInput = NULL;
if (m_pszInputBuf)
{
RTMemFree(m_pszInputBuf);
m_pszInputBuf = NULL;
}
m_cbInputBuf = 0;
m_cbInputBufAlloc = 0;
delete m_pFocusToInput;
m_pFocusToInput = NULL;
delete m_pFocusToOutput;
m_pFocusToOutput = NULL;
}
void
VBoxDbgConsole::commandSubmitted(const QString &rCommand)
{
Assert(isGUIThread());
lock();
RTSemEventSignal(m_EventSem);
QByteArray Utf8Array = rCommand.toUtf8();
const char *psz = Utf8Array.constData();
size_t cb = strlen(psz);
/*
* Make sure we've got space for the input.
*/
if (cb + m_cbInputBuf >= m_cbInputBufAlloc)
{
size_t cbNew = RT_ALIGN_Z(cb + m_cbInputBufAlloc + 1, 128);
void *pv = RTMemRealloc(m_pszInputBuf, cbNew);
if (!pv)
{
unlock();
return;
}
m_pszInputBuf = (char *)pv;
m_cbInputBufAlloc = cbNew;
}
/*
* Add the input and output it.
*/
memcpy(m_pszInputBuf + m_cbInputBuf, psz, cb);
m_cbInputBuf += cb;
m_pszInputBuf[m_cbInputBuf++] = '\n';
m_pOutput->appendText(rCommand + "\n");
m_pOutput->ensureCursorVisible();
m_fInputRestoreFocus = m_pInput->hasFocus(); /* dirty focus hack */
m_pInput->setEnabled(false);
Log(("VBoxDbgConsole::commandSubmitted: %s (input-enabled=%RTbool)\n", psz, m_pInput->isEnabled()));
unlock();
}
void
VBoxDbgConsole::updateOutput()
{
Assert(isGUIThread());
lock();
m_fUpdatePending = false;
if (m_cbOutputBuf)
{
m_pOutput->appendText(QString::fromUtf8((const char *)m_pszOutputBuf, (int)m_cbOutputBuf));
m_cbOutputBuf = 0;
}
unlock();
}
/**
* Lock the object.
*/
void
VBoxDbgConsole::lock()
{
RTCritSectEnter(&m_Lock);
}
/**
* Unlocks the object.
*/
void
VBoxDbgConsole::unlock()
{
RTCritSectLeave(&m_Lock);
}
/**
* Checks if there is input.
*
* @returns true if there is input ready.
* @returns false if there not input ready.
* @param pBack Pointer to VBoxDbgConsole::m_Back.
* @param cMillies Number of milliseconds to wait on input data.
*/
/*static*/ DECLCALLBACK(bool)
VBoxDbgConsole::backInput(PDBGCBACK pBack, uint32_t cMillies)
{
VBoxDbgConsole *pThis = VBOXDBGCONSOLE_FROM_DBGCBACK(pBack);
pThis->lock();
bool fRc = true;
if (!pThis->m_cbInputBuf)
{
/*
* Wait outside the lock for the requested time, then check again.
*/
pThis->unlock();
RTSemEventWait(pThis->m_EventSem, cMillies);
pThis->lock();
fRc = pThis->m_cbInputBuf
|| ASMAtomicUoReadBool(&pThis->m_fTerminate);
}
pThis->unlock();
return fRc;
}
/**
* Read input.
*
* @returns VBox status code.
* @param pBack Pointer to VBoxDbgConsole::m_Back.
* @param pvBuf Where to put the bytes we read.
* @param cbBuf Maximum nymber of bytes to read.
* @param pcbRead Where to store the number of bytes actually read.
* If NULL the entire buffer must be filled for a
* successful return.
*/
/*static*/ DECLCALLBACK(int)
VBoxDbgConsole::backRead(PDBGCBACK pBack, void *pvBuf, size_t cbBuf, size_t *pcbRead)
{
VBoxDbgConsole *pThis = VBOXDBGCONSOLE_FROM_DBGCBACK(pBack);
Assert(pcbRead); /** @todo implement this bit */
if (pcbRead)
*pcbRead = 0;
pThis->lock();
int rc = VINF_SUCCESS;
if (!ASMAtomicUoReadBool(&pThis->m_fTerminate))
{
if (pThis->m_cbInputBuf)
{
const char *psz = pThis->m_pszInputBuf;
size_t cbRead = RT_MIN(pThis->m_cbInputBuf, cbBuf);
memcpy(pvBuf, psz, cbRead);
psz += cbRead;
pThis->m_cbInputBuf -= cbRead;
if (*psz)
memmove(pThis->m_pszInputBuf, psz, pThis->m_cbInputBuf);
pThis->m_pszInputBuf[pThis->m_cbInputBuf] = '\0';
*pcbRead = cbRead;
}
}
else
rc = VERR_GENERAL_FAILURE;
pThis->unlock();
return rc;
}
/**
* Write (output).
*
* @returns VBox status code.
* @param pBack Pointer to VBoxDbgConsole::m_Back.
* @param pvBuf What to write.
* @param cbBuf Number of bytes to write.
* @param pcbWritten Where to store the number of bytes actually written.
* If NULL the entire buffer must be successfully written.
*/
/*static*/ DECLCALLBACK(int)
VBoxDbgConsole::backWrite(PDBGCBACK pBack, const void *pvBuf, size_t cbBuf, size_t *pcbWritten)
{
VBoxDbgConsole *pThis = VBOXDBGCONSOLE_FROM_DBGCBACK(pBack);
int rc = VINF_SUCCESS;
pThis->lock();
if (cbBuf + pThis->m_cbOutputBuf >= pThis->m_cbOutputBufAlloc)
{
size_t cbNew = RT_ALIGN_Z(cbBuf + pThis->m_cbOutputBufAlloc + 1, 1024);
void *pv = RTMemRealloc(pThis->m_pszOutputBuf, cbNew);
if (!pv)
{
pThis->unlock();
if (pcbWritten)
*pcbWritten = 0;
return VERR_NO_MEMORY;
}
pThis->m_pszOutputBuf = (char *)pv;
pThis->m_cbOutputBufAlloc = cbNew;
}
/*
* Add the output.
*/
memcpy(pThis->m_pszOutputBuf + pThis->m_cbOutputBuf, pvBuf, cbBuf);
pThis->m_cbOutputBuf += cbBuf;
pThis->m_pszOutputBuf[pThis->m_cbOutputBuf] = '\0';
if (pcbWritten)
*pcbWritten = cbBuf;
if (ASMAtomicUoReadBool(&pThis->m_fTerminate))
rc = VERR_GENERAL_FAILURE;
/*
* Tell the GUI thread to draw this text.
* We cannot do it from here without frequent crashes.
*/
if (!pThis->m_fUpdatePending)
QApplication::postEvent(pThis, new VBoxDbgConsoleEvent(VBoxDbgConsoleEvent::kUpdate));
pThis->unlock();
return rc;
}
/*static*/ DECLCALLBACK(void)
VBoxDbgConsole::backSetReady(PDBGCBACK pBack, bool fReady)
{
VBoxDbgConsole *pThis = VBOXDBGCONSOLE_FROM_DBGCBACK(pBack);
if (fReady)
QApplication::postEvent(pThis, new VBoxDbgConsoleEvent(VBoxDbgConsoleEvent::kInputEnable));
}
/**
* The Debugger Console Thread
*
* @returns VBox status code (ignored).
* @param Thread The thread handle.
* @param pvUser Pointer to the VBoxDbgConsole object.s
*/
/*static*/ DECLCALLBACK(int)
VBoxDbgConsole::backThread(RTTHREAD Thread, void *pvUser)
{
VBoxDbgConsole *pThis = (VBoxDbgConsole *)pvUser;
LogFlow(("backThread: Thread=%p pvUser=%p\n", (void *)Thread, pvUser));
NOREF(Thread);
/*
* Create and execute the console.
*/
int rc = pThis->dbgcCreate(&pThis->m_Back.Core, 0);
ASMAtomicUoWriteBool(&pThis->m_fThreadTerminated, true);
if (!ASMAtomicUoReadBool(&pThis->m_fTerminate))
QApplication::postEvent(pThis, new VBoxDbgConsoleEvent(rc == VINF_SUCCESS
? VBoxDbgConsoleEvent::kTerminatedUser
: VBoxDbgConsoleEvent::kTerminatedOther));
LogFlow(("backThread: returns %Rrc (m_fTerminate=%RTbool)\n", rc, ASMAtomicUoReadBool(&pThis->m_fTerminate)));
return rc;
}
bool
VBoxDbgConsole::event(QEvent *pGenEvent)
{
Assert(isGUIThread());
if (pGenEvent->type() == (QEvent::Type)VBoxDbgConsoleEvent::kEventNumber)
{
VBoxDbgConsoleEvent *pEvent = (VBoxDbgConsoleEvent *)pGenEvent;
switch (pEvent->command())
{
/* make update pending. */
case VBoxDbgConsoleEvent::kUpdate:
lock();
if (!m_fUpdatePending)
{
m_fUpdatePending = true;
m_pTimer->setSingleShot(true);
m_pTimer->start(10);
}
unlock();
break;
/* Re-enable the input field and restore focus. */
case VBoxDbgConsoleEvent::kInputEnable:
Log(("VBoxDbgConsole: kInputEnable (input-enabled=%RTbool)\n", m_pInput->isEnabled()));
m_pInput->setEnabled(true);
if ( m_fInputRestoreFocus
&& !m_pInput->hasFocus())
m_pInput->setFocus(); /* this is a hack. */
m_fInputRestoreFocus = false;
break;
/* The thread terminated by user command (exit, quit, bye). */
case VBoxDbgConsoleEvent::kTerminatedUser:
Log(("VBoxDbgConsole: kTerminatedUser (input-enabled=%RTbool)\n", m_pInput->isEnabled()));
m_pInput->setEnabled(false);
close();
break;
/* The thread terminated for some unknown reason., disable input */
case VBoxDbgConsoleEvent::kTerminatedOther:
Log(("VBoxDbgConsole: kTerminatedOther (input-enabled=%RTbool)\n", m_pInput->isEnabled()));
m_pInput->setEnabled(false);
break;
/* paranoia */
default:
AssertMsgFailed(("command=%d\n", pEvent->command()));
break;
}
return true;
}
return VBoxDbgBaseWindow::event(pGenEvent);
}
void
VBoxDbgConsole::closeEvent(QCloseEvent *a_pCloseEvt)
{
if (m_fThreadTerminated)
{
a_pCloseEvt->accept();
delete this;
}
}
void
VBoxDbgConsole::actFocusToInput()
{
if (!m_pInput->hasFocus())
m_pInput->setFocus(Qt::ShortcutFocusReason);
}
void
VBoxDbgConsole::actFocusToOutput()
{
if (!m_pOutput->hasFocus())
m_pOutput->setFocus(Qt::ShortcutFocusReason);
}
| dezelin/vbox-haiku | src/VBox/Debugger/VBoxDbgConsole.cpp | C++ | gpl-2.0 | 18,472 |
/* ****************************************************************************
* Start Waterfall series code *
*****************************************************************************/
wrap(axisProto, 'getSeriesExtremes', function (proceed, renew) {
// Run uber method
proceed.call(this, renew);
if (this.isXAxis) {
return;
}
var axis = this,
visitedStacks = [],
resetMinMax = true;
// recalculate extremes for each waterfall stack
each(axis.series, function (series) {
// process only visible, waterfall series, one from each stack
if (!series.visible || !series.stackKey || series.type !== 'waterfall' || HighchartsAdapter.inArray(series.stackKey) !== -1) {
return;
}
// reset previously found dataMin and dataMax, do it only once
if (resetMinMax) {
axis.dataMin = axis.dataMax = null;
resetMinMax = false;
}
var yData = series.processedYData,
yDataLength = yData.length,
seriesDataMin = yData[0],
seriesDataMax = yData[0],
threshold = series.options.threshold,
stacks = axis.stacks,
stackKey = series.stackKey,
negKey = '-' + stackKey,
total,
previous,
key,
i;
// set new stack totals including preceding values, finds new min and max values
for (i = 0; i < yDataLength; i++) {
key = yData[i] < threshold ? negKey : stackKey;
total = stacks[key][i].total;
if (i > threshold) {
total += previous;
stacks[key][i].setTotal(total);
// _cum is used to avoid conflict with Series.translate method
stacks[key][i]._cum = null;
}
// find min / max values
if (total < seriesDataMin) {
seriesDataMin = total;
}
if (total > seriesDataMax) {
seriesDataMax = total;
}
previous = total;
}
// set new extremes
series.dataMin = seriesDataMin;
series.dataMax = seriesDataMax;
axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin, threshold);
axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax, threshold);
// remember series' stack key
visitedStacks.push(series.stackKey);
// Adjust to threshold. This code is duplicated from the parent getSeriesExtremes method.
if (typeof threshold === 'number') {
if (axis.dataMin >= threshold) {
axis.dataMin = threshold;
axis.ignoreMinPadding = true;
} else if (axis.dataMax < threshold) {
axis.dataMax = threshold;
axis.ignoreMaxPadding = true;
}
}
});
});
// 1 - set default options
defaultPlotOptions.waterfall = merge(defaultPlotOptions.column, {
lineWidth: 1,
lineColor: '#333',
dashStyle: 'dot',
borderColor: '#333'
});
// 2 - Create the series object
seriesTypes.waterfall = extendClass(seriesTypes.column, {
type: 'waterfall',
upColorProp: 'fill',
pointArrayMap: ['y', 'low'],
pointValKey: 'y',
/**
* Init waterfall series, force stacking
*/
init: function (chart, options) {
options.stacking = true;
seriesTypes.column.prototype.init.call(this, chart, options);
},
/**
* Translate data points from raw values
*/
translate: function () {
var series = this,
options = series.options,
axis = series.yAxis,
len,
i,
points,
point,
shapeArgs,
sum,
sumStart,
subSum,
subSumStart,
edges,
cumulative,
prevStack,
prevY,
stack,
crispCorr = (options.borderWidth % 2) / 2;
// run column series translate
seriesTypes.column.prototype.translate.apply(this);
points = this.points;
subSumStart = sumStart = points[0];
sum = subSum = points[0].y;
for (i = 1, len = points.length; i < len; i++) {
// cache current point object
point = points[i];
shapeArgs = point.shapeArgs;
// get current and previous stack
stack = series.getStack(i);
prevStack = series.getStack(i - 1);
prevY = series.getStackY(prevStack);
// set new intermediate sum values after reset
if (subSumStart === null) {
subSumStart = point;
subSum = 0;
}
// sum only points with value, not intermediate or total sum
if (point.y && !point.isSum && !point.isIntermediateSum) {
sum += point.y;
subSum += point.y;
}
// calculate sum points
if (point.isSum || point.isIntermediateSum) {
if (point.isIntermediateSum) {
edges = series.getSumEdges(subSumStart, points[i - 1]);
point.y = subSum;
subSumStart = null;
} else {
edges = series.getSumEdges(sumStart, points[i - 1]);
point.y = sum;
}
shapeArgs.y = point.plotY = edges[1];
shapeArgs.height = edges[0] - edges[1];
// calculate other (up or down) points based on y value
} else {
// use "_cum" instead of already calculated "cum" to avoid reverse ordering negative columns
cumulative = stack._cum === null ? prevStack.total : stack._cum;
stack._cum = cumulative + point.y;
if (point.y < 0) {
shapeArgs.y = mathCeil(axis.translate(cumulative, 0, 1)) - crispCorr;
shapeArgs.height = mathCeil(axis.translate(stack._cum, 0, 1) - shapeArgs.y);
} else {
if (prevStack.total + point.y < 0) {
shapeArgs.y = axis.translate(stack._cum, 0, 1);
}
shapeArgs.height = mathFloor(prevY - shapeArgs.y);
}
}
}
},
/**
* Call default processData then override yData to reflect waterfall's extremes on yAxis
*/
processData: function (force) {
Series.prototype.processData.call(this, force);
var series = this,
options = series.options,
yData = series.yData,
length = yData.length,
prev,
curr,
subSum,
sum,
i;
prev = sum = subSum = options.threshold;
for (i = 0; i < length; i++) {
curr = yData[i];
// processed yData only if it's not already processed
if (curr !== null && typeof curr !== 'number') {
if (curr === "sum") {
yData[i] = null;
} else if (curr === "intermediateSum") {
yData[i] = null;
subSum = prev;
} else {
yData[i] = curr[0];// + prev;
}
prev = yData[i];
}
}
},
/**
* Return [y, low] array, if low is not defined, it's replaced with null for further calculations
*/
toYData: function (pt) {
if (pt.isSum) {
return "sum";
} else if (pt.isIntermediateSum) {
return "intermediateSum";
}
return [pt.y];
},
/**
* Postprocess mapping between options and SVG attributes
*/
getAttribs: function () {
seriesTypes.column.prototype.getAttribs.apply(this, arguments);
var series = this,
options = series.options,
stateOptions = options.states,
upColor = options.upColor || series.color,
hoverColor = Highcharts.Color(upColor).brighten(0.1).get(),
seriesDownPointAttr = merge(series.pointAttr),
upColorProp = series.upColorProp;
seriesDownPointAttr[''][upColorProp] = upColor;
seriesDownPointAttr.hover[upColorProp] = stateOptions.hover.upColor || hoverColor;
seriesDownPointAttr.select[upColorProp] = stateOptions.select.upColor || upColor;
each(series.points, function (point) {
if (point.y > 0 && !point.color) {
point.pointAttr = seriesDownPointAttr;
point.color = upColor;
}
});
},
/**
* Draw columns' connector lines
*/
getGraphPath: function () {
var data = this.data,
length = data.length,
lineWidth = this.options.lineWidth + this.options.borderWidth,
normalizer = mathRound(lineWidth) % 2 / 2,
path = [],
M = 'M',
L = 'L',
prevArgs,
pointArgs,
i,
d;
for (i = 1; i < length; i++) {
pointArgs = data[i].shapeArgs;
prevArgs = data[i - 1].shapeArgs;
d = [
M,
prevArgs.x + prevArgs.width, prevArgs.y + normalizer,
L,
pointArgs.x, prevArgs.y + normalizer
];
if (data[i - 1].y < 0) {
d[2] += prevArgs.height;
d[5] += prevArgs.height;
}
path = path.concat(d);
}
return path;
},
getStack: function (i) {
var axis = this.yAxis,
stacks = axis.stacks,
key = this.stackKey;
if (this.processedYData[i] < this.options.threshold) {
key = '-' + key;
}
return stacks[key][i];
},
getStackY: function (stack) {
return mathCeil(this.yAxis.translate(stack.total, null, true));
},
/**
* Return array of top and bottom position for sum column based on given edge points
*/
getSumEdges: function (pointA, pointB) {
var valueA,
valueB,
tmp,
threshold = this.options.threshold;
valueA = pointA.y >= threshold ? pointA.shapeArgs.y + pointA.shapeArgs.height : pointA.shapeArgs.y;
valueB = pointB.y >= threshold ? pointB.shapeArgs.y : pointB.shapeArgs.y + pointB.shapeArgs.height;
if (valueB > valueA) {
tmp = valueA;
valueA = valueB;
valueB = tmp;
}
return [valueA, valueB];
},
drawGraph: Series.prototype.drawGraph
});
/* ****************************************************************************
* End Waterfall series code *
*****************************************************************************/
| wydler/python-piko | piko/static/vendor/highstock/js/parts-more/WaterfallSeries.js | JavaScript | gpl-2.0 | 8,880 |
/*
* include/asm-s390/fcntl.h
*
* S390 version
*
* Derived from "include/asm-i386/fcntl.h"
*/
#ifndef _S390_FCNTL_H
#define _S390_FCNTL_H
/* open/fcntl - O_SYNC is only implemented on blocks devices and on files
located on an ext2 file system */
#define O_ACCMODE 0003
#define O_RDONLY 00
#define O_WRONLY 01
#define O_RDWR 02
#define O_CREAT 0100 /* not fcntl */
#define O_EXCL 0200 /* not fcntl */
#define O_NOCTTY 0400 /* not fcntl */
#define O_TRUNC 01000 /* not fcntl */
#define O_APPEND 02000
#define O_NONBLOCK 04000
#define O_NDELAY O_NONBLOCK
#define O_SYNC 010000
#define FASYNC 020000 /* fcntl, for BSD compatibility */
#define O_DIRECT 040000 /* direct disk access hint - currently ignored */
#define O_LARGEFILE 0100000
#define O_DIRECTORY 0200000 /* must be a directory */
#define O_NOFOLLOW 0400000 /* don't follow links */
#define F_DUPFD 0 /* dup */
#define F_GETFD 1 /* get f_flags */
#define F_SETFD 2 /* set f_flags */
#define F_GETFL 3 /* more flags (cloexec) */
#define F_SETFL 4
#define F_GETLK 5
#define F_SETLK 6
#define F_SETLKW 7
#define F_SETOWN 8 /* for sockets. */
#define F_GETOWN 9 /* for sockets. */
#define F_SETSIG 10 /* for sockets. */
#define F_GETSIG 11 /* for sockets. */
/* for F_[GET|SET]FL */
#define FD_CLOEXEC 1 /* actually anything with low bit set goes */
/* for posix fcntl() and lockf() */
#define F_RDLCK 0
#define F_WRLCK 1
#define F_UNLCK 2
/* for old implementation of bsd flock () */
#define F_EXLCK 4 /* or 3 */
#define F_SHLCK 8 /* or 4 */
/* operations for bsd flock(), also used by the kernel implementation */
#define LOCK_SH 1 /* shared lock */
#define LOCK_EX 2 /* exclusive lock */
#define LOCK_NB 4 /* or'd with one of the above to prevent
blocking */
#define LOCK_UN 8 /* remove lock */
struct flock {
short l_type;
short l_whence;
off_t l_start;
off_t l_len;
pid_t l_pid;
};
#endif
| empeg/empeg-hijack | include/asm-s390/fcntl.h | C | gpl-2.0 | 1,941 |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- template designed by Marco Von Ballmoos -->
<title></title>
<link rel="stylesheet" href="media/stylesheet.css" />
<script src="media/lib/classTree.js"></script>
<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/>
<script language="javascript" type="text/javascript">
var imgPlus = new Image();
var imgMinus = new Image();
imgPlus.src = "media/images/plus.png";
imgMinus.src = "media/images/minus.png";
function showNode(Node){
switch(navigator.family){
case 'nn4':
// Nav 4.x code fork...
var oTable = document.layers["span" + Node];
var oImg = document.layers["img" + Node];
break;
case 'ie4':
// IE 4/5 code fork...
var oTable = document.all["span" + Node];
var oImg = document.all["img" + Node];
break;
case 'gecko':
// Standards Compliant code fork...
var oTable = document.getElementById("span" + Node);
var oImg = document.getElementById("img" + Node);
break;
}
oImg.src = imgMinus.src;
oTable.style.display = "block";
}
function hideNode(Node){
switch(navigator.family){
case 'nn4':
// Nav 4.x code fork...
var oTable = document.layers["span" + Node];
var oImg = document.layers["img" + Node];
break;
case 'ie4':
// IE 4/5 code fork...
var oTable = document.all["span" + Node];
var oImg = document.all["img" + Node];
break;
case 'gecko':
// Standards Compliant code fork...
var oTable = document.getElementById("span" + Node);
var oImg = document.getElementById("img" + Node);
break;
}
oImg.src = imgPlus.src;
oTable.style.display = "none";
}
function nodeIsVisible(Node){
switch(navigator.family){
case 'nn4':
// Nav 4.x code fork...
var oTable = document.layers["span" + Node];
break;
case 'ie4':
// IE 4/5 code fork...
var oTable = document.all["span" + Node];
break;
case 'gecko':
// Standards Compliant code fork...
var oTable = document.getElementById("span" + Node);
break;
}
return (oTable && oTable.style.display == "block");
}
function toggleNodeVisibility(Node){
if (nodeIsVisible(Node)){
hideNode(Node);
}else{
showNode(Node);
}
}
</script>
</head>
<body>
<select class="package-selector" onchange="window.parent.left_bottom.location=this[selectedIndex].value">
<option value="li_default.html">default</option>
<option value="li_akeebabackup.html">akeebabackup</option>
<option value="li_FrameworkOnFramework.html">FrameworkOnFramework</option>
<option value="li_IDNA.html">IDNA</option>
<option value="li_Joomla-Administrator.html">Joomla-Administrator</option>
<option value="li_Joomla-Cli.html">Joomla-Cli</option>
<option value="li_Joomla-Cms.html">Joomla-Cms</option>
<option value="li_Joomla-Compat.html">Joomla-Compat</option>
<option value="li_Joomla-Installation.html">Joomla-Installation</option>
<option value="li_Joomla-Language.html">Joomla-Language</option>
<option selected value="li_Joomla-Legacy.html">Joomla-Legacy</option>
<option value="li_Joomla-Libraries.html">Joomla-Libraries</option>
<option value="li_Joomla-Platform.html">Joomla-Platform</option>
<option value="li_Joomla-Plugin.html">Joomla-Plugin</option>
<option value="li_Joomla-Site.html">Joomla-Site</option>
<option value="li_PHPMailer.html">PHPMailer</option>
<option value="li_SimplePie.html">SimplePie</option>
<option value="li_utf8.html">utf8</option>
</select>
<h3 class="package-title">Joomla-Legacy</h3>
<div class="tree">
<script language="Javascript">
if (document.getElementById) {
var tree = new WebFXTree('<span class="package">Joomla-Legacy</span>');
tree.setBehavior('classic');
tree.openIcon = 'media/images/package.png';
tree.icon = 'media/images/package.png';
var todos = new WebFXTreeItem('To-do List', 'todolist.html');
todos.openIcon = 'media/images/Index.png';
todos.icon = 'media/images/Index.png';
tree.add(todos);
var class_trees = new WebFXTreeItem('Class trees', 'classtrees_Joomla-Legacy.html');
class_trees.openIcon = 'media/images/Index.png';
class_trees.icon = 'media/images/Index.png';
tree.add(class_trees);
var elements = new WebFXTreeItem('Index of elements', 'elementindex_Joomla-Legacy.html');
elements.openIcon = 'media/images/Index.png';
elements.icon = 'media/images/Index.png';
tree.add(elements);
var parent_node;
var subpackagetree = new WebFXTreeItem('<span class="sub-package">Access</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('JRule', 'Joomla-Legacy/Access/JRule.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JRules', 'Joomla-Legacy/Access/JRules.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
var subpackagetree_file = new WebFXTreeItem('File(s)', '');
subpackagetree_file.openIcon = 'media/images/folder.png';
subpackagetree_file.icon = 'media/images/folder.png';
var file = new WebFXTreeItem('rule.php', 'Joomla-Legacy/Access/_libraries---legacy---access---rule.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('rules.php', 'Joomla-Legacy/Access/_libraries---legacy---access---rules.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
subpackagetree.add(subpackagetree_file);
tree.add(subpackagetree);
var subpackagetree = new WebFXTreeItem('<span class="sub-package">Application</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('JApplication', 'Joomla-Legacy/Application/JApplication.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JDaemon', 'Joomla-Legacy/Application/JDaemon.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JWeb', 'Joomla-Legacy/Application/JWeb.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JWebClient', 'Joomla-Legacy/Application/JWebClient.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
var subpackagetree_file = new WebFXTreeItem('File(s)', '');
subpackagetree_file.openIcon = 'media/images/folder.png';
subpackagetree_file.icon = 'media/images/folder.png';
var file = new WebFXTreeItem('application.php', 'Joomla-Legacy/Application/_libraries---legacy---application---application.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('client.php', 'Joomla-Legacy/Application/_libraries---legacy---web---client.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('daemon.php', 'Joomla-Legacy/Application/_libraries---legacy---application---daemon.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('web.php', 'Joomla-Legacy/Application/_libraries---legacy---web---web.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
subpackagetree.add(subpackagetree_file);
tree.add(subpackagetree);
var subpackagetree = new WebFXTreeItem('<span class="sub-package">Base</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('JNode', 'Joomla-Legacy/Base/JNode.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JObservable', 'Joomla-Legacy/Base/JObservable.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JObserver', 'Joomla-Legacy/Base/JObserver.html');
classe.openIcon = 'media/images/AbstractClass.png';
classe.icon = 'media/images/AbstractClass.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JTree', 'Joomla-Legacy/Base/JTree.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
var subpackagetree_file = new WebFXTreeItem('File(s)', '');
subpackagetree_file.openIcon = 'media/images/folder.png';
subpackagetree_file.icon = 'media/images/folder.png';
var file = new WebFXTreeItem('node.php', 'Joomla-Legacy/Base/_libraries---legacy---base---node.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('observable.php', 'Joomla-Legacy/Base/_libraries---legacy---base---observable.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('observer.php', 'Joomla-Legacy/Base/_libraries---legacy---base---observer.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('tree.php', 'Joomla-Legacy/Base/_libraries---legacy---base---tree.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
subpackagetree.add(subpackagetree_file);
tree.add(subpackagetree);
var subpackagetree = new WebFXTreeItem('<span class="sub-package">Categories</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('JCategories', 'Joomla-Legacy/Categories/JCategories.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JCategoryNode', 'Joomla-Legacy/Categories/JCategoryNode.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
var subpackagetree_file = new WebFXTreeItem('File(s)', '');
subpackagetree_file.openIcon = 'media/images/folder.png';
subpackagetree_file.icon = 'media/images/folder.png';
var file = new WebFXTreeItem('categories.php', 'Joomla-Legacy/Categories/_libraries---legacy---categories---categories.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
subpackagetree.add(subpackagetree_file);
tree.add(subpackagetree);
var subpackagetree = new WebFXTreeItem('<span class="sub-package">Controller</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('JControllerAdmin', 'Joomla-Legacy/Controller/JControllerAdmin.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JControllerForm', 'Joomla-Legacy/Controller/JControllerForm.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JControllerLegacy', 'Joomla-Legacy/Controller/JControllerLegacy.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
var subpackagetree_file = new WebFXTreeItem('File(s)', '');
subpackagetree_file.openIcon = 'media/images/folder.png';
subpackagetree_file.icon = 'media/images/folder.png';
var file = new WebFXTreeItem('admin.php', 'Joomla-Legacy/Controller/_libraries---legacy---controller---admin.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('form.php', 'Joomla-Legacy/Controller/_libraries---legacy---controller---form.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('legacy.php', 'Joomla-Legacy/Controller/_libraries---legacy---controller---legacy.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
subpackagetree.add(subpackagetree_file);
tree.add(subpackagetree);
var subpackagetree = new WebFXTreeItem('<span class="sub-package">Database</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('JDatabaseException', 'Joomla-Legacy/Database/JDatabaseException.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JDatabaseMysql', 'Joomla-Legacy/Database/JDatabaseMysql.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JDatabaseMysqli', 'Joomla-Legacy/Database/JDatabaseMysqli.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JDatabaseSqlazure', 'Joomla-Legacy/Database/JDatabaseSqlazure.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JDatabaseSqlsrv', 'Joomla-Legacy/Database/JDatabaseSqlsrv.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
var subpackagetree_file = new WebFXTreeItem('File(s)', '');
subpackagetree_file.openIcon = 'media/images/folder.png';
subpackagetree_file.icon = 'media/images/folder.png';
var file = new WebFXTreeItem('exception.php', 'Joomla-Legacy/Database/_libraries---legacy---database---exception.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('mysql.php', 'Joomla-Legacy/Database/_libraries---legacy---database---mysql.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('mysqli.php', 'Joomla-Legacy/Database/_libraries---legacy---database---mysqli.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('sqlazure.php', 'Joomla-Legacy/Database/_libraries---legacy---database---sqlazure.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('sqlsrv.php', 'Joomla-Legacy/Database/_libraries---legacy---database---sqlsrv.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
subpackagetree.add(subpackagetree_file);
tree.add(subpackagetree);
var subpackagetree = new WebFXTreeItem('<span class="sub-package">Dispatcher</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('JDispatcher', 'Joomla-Legacy/Dispatcher/JDispatcher.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
var subpackagetree_file = new WebFXTreeItem('File(s)', '');
subpackagetree_file.openIcon = 'media/images/folder.png';
subpackagetree_file.icon = 'media/images/folder.png';
var file = new WebFXTreeItem('dispatcher.php', 'Joomla-Legacy/Dispatcher/_libraries---legacy---dispatcher---dispatcher.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
subpackagetree.add(subpackagetree_file);
tree.add(subpackagetree);
var subpackagetree = new WebFXTreeItem('<span class="sub-package">Error</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('JError', 'Joomla-Legacy/Error/JError.html');
classe.openIcon = 'media/images/AbstractClass.png';
classe.icon = 'media/images/AbstractClass.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
var subpackagetree_file = new WebFXTreeItem('File(s)', '');
subpackagetree_file.openIcon = 'media/images/folder.png';
subpackagetree_file.icon = 'media/images/folder.png';
var file = new WebFXTreeItem('error.php', 'Joomla-Legacy/Error/_libraries---legacy---error---error.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
subpackagetree.add(subpackagetree_file);
tree.add(subpackagetree);
var subpackagetree = new WebFXTreeItem('<span class="sub-package">Exception</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('JException', 'Joomla-Legacy/Exception/JException.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
var subpackagetree_file = new WebFXTreeItem('File(s)', '');
subpackagetree_file.openIcon = 'media/images/folder.png';
subpackagetree_file.icon = 'media/images/folder.png';
var file = new WebFXTreeItem('exception.php', 'Joomla-Legacy/Exception/_libraries---legacy---exception---exception.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
subpackagetree.add(subpackagetree_file);
tree.add(subpackagetree);
var subpackagetree = new WebFXTreeItem('<span class="sub-package">Form</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('JFormFieldCategory', 'Joomla-Legacy/Form/JFormFieldCategory.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JFormFieldComponentlayout', 'Joomla-Legacy/Form/JFormFieldComponentlayout.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JFormFieldModulelayout', 'Joomla-Legacy/Form/JFormFieldModulelayout.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
var subpackagetree_file = new WebFXTreeItem('File(s)', '');
subpackagetree_file.openIcon = 'media/images/folder.png';
subpackagetree_file.icon = 'media/images/folder.png';
var file = new WebFXTreeItem('category.php', 'Joomla-Legacy/Form/_libraries---legacy---form---field---category.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('componentlayout.php', 'Joomla-Legacy/Form/_libraries---legacy---form---field---componentlayout.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('modulelayout.php', 'Joomla-Legacy/Form/_libraries---legacy---form---field---modulelayout.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
subpackagetree.add(subpackagetree_file);
tree.add(subpackagetree);
var subpackagetree = new WebFXTreeItem('<span class="sub-package">Library</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('JLibraryHelper', 'Joomla-Legacy/Library/JLibraryHelper.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
var subpackagetree_function = new WebFXTreeItem('Function(s)', '');
subpackagetree_function.openIcon = 'media/images/function_folder.png';
subpackagetree_function.icon = 'media/images/function_folder.png';
var fic = new WebFXTreeItem('getParams', 'Joomla-Legacy/Library/_libraries---cms---library---helper.php.html#functiongetParams');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('isEnabled', 'Joomla-Legacy/Library/_libraries---cms---library---helper.php.html#functionisEnabled');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('saveParams', 'Joomla-Legacy/Library/_libraries---cms---library---helper.php.html#functionsaveParams');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('_load', 'Joomla-Legacy/Library/_libraries---cms---library---helper.php.html#function_load');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
subpackagetree.add(subpackagetree_function);
var subpackagetree_file = new WebFXTreeItem('File(s)', '');
subpackagetree_file.openIcon = 'media/images/folder.png';
subpackagetree_file.icon = 'media/images/folder.png';
var file = new WebFXTreeItem('helper.php', 'Joomla-Legacy/Library/_libraries---cms---library---helper.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
subpackagetree.add(subpackagetree_file);
tree.add(subpackagetree);
var subpackagetree = new WebFXTreeItem('<span class="sub-package">Log</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('LogException', 'Joomla-Legacy/Log/LogException.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
var subpackagetree_file = new WebFXTreeItem('File(s)', '');
subpackagetree_file.openIcon = 'media/images/folder.png';
subpackagetree_file.icon = 'media/images/folder.png';
var file = new WebFXTreeItem('logexception.php', 'Joomla-Legacy/Log/_libraries---legacy---log---logexception.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
subpackagetree.add(subpackagetree_file);
tree.add(subpackagetree);
var subpackagetree = new WebFXTreeItem('<span class="sub-package">Model</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('JModelAdmin', 'Joomla-Legacy/Model/JModelAdmin.html');
classe.openIcon = 'media/images/AbstractClass.png';
classe.icon = 'media/images/AbstractClass.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JModelForm', 'Joomla-Legacy/Model/JModelForm.html');
classe.openIcon = 'media/images/AbstractClass.png';
classe.icon = 'media/images/AbstractClass.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JModelItem', 'Joomla-Legacy/Model/JModelItem.html');
classe.openIcon = 'media/images/AbstractClass.png';
classe.icon = 'media/images/AbstractClass.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JModelLegacy', 'Joomla-Legacy/Model/JModelLegacy.html');
classe.openIcon = 'media/images/AbstractClass.png';
classe.icon = 'media/images/AbstractClass.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JModelList', 'Joomla-Legacy/Model/JModelList.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
var subpackagetree_function = new WebFXTreeItem('Function(s)', '');
subpackagetree_function.openIcon = 'media/images/function_folder.png';
subpackagetree_function.icon = 'media/images/function_folder.png';
var fic = new WebFXTreeItem('batchLanguage', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html#functionbatchLanguage');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('batchMove', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html#functionbatchMove');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('batchTag', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html#functionbatchTag');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('canDelete', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html#functioncanDelete');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('canEditState', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html#functioncanEditState');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('checkCategoryId', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html#functioncheckCategoryId');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('checkin', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html#functioncheckin');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('checkout', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html#functioncheckout');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('createTagsHelper', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html#functioncreateTagsHelper');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('delete', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html#functiondelete');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('generateNewTitle', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html#functiongenerateNewTitle');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('generateTitle', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html#functiongenerateTitle');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('getItem', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html#functiongetItem');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('getReorderConditions', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html#functiongetReorderConditions');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('populateState', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html#functionpopulateState');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('prepareTable', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html#functionprepareTable');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('publish', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html#functionpublish');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('reorder', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html#functionreorder');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('save', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html#functionsave');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
var fic = new WebFXTreeItem('saveorder', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html#functionsaveorder');
fic.openIcon = 'media/images/Function.png';
fic.icon = 'media/images/Function.png';
subpackagetree_function.add(fic);
subpackagetree.add(subpackagetree_function);
var subpackagetree_file = new WebFXTreeItem('File(s)', '');
subpackagetree_file.openIcon = 'media/images/folder.png';
subpackagetree_file.icon = 'media/images/folder.png';
var file = new WebFXTreeItem('admin.php', 'Joomla-Legacy/Model/_libraries---legacy---model---admin.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('form.php', 'Joomla-Legacy/Model/_libraries---legacy---model---form.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('item.php', 'Joomla-Legacy/Model/_libraries---legacy---model---item.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('legacy.php', 'Joomla-Legacy/Model/_libraries---legacy---model---legacy.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('list.php', 'Joomla-Legacy/Model/_libraries---legacy---model---list.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
subpackagetree.add(subpackagetree_file);
tree.add(subpackagetree);
var subpackagetree = new WebFXTreeItem('<span class="sub-package">Request</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('JRequest', 'Joomla-Legacy/Request/JRequest.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
var subpackagetree_file = new WebFXTreeItem('File(s)', '');
subpackagetree_file.openIcon = 'media/images/folder.png';
subpackagetree_file.icon = 'media/images/folder.png';
var file = new WebFXTreeItem('request.php', 'Joomla-Legacy/Request/_libraries---legacy---request---request.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
subpackagetree.add(subpackagetree_file);
tree.add(subpackagetree);
var subpackagetree = new WebFXTreeItem('<span class="sub-package">Response</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('JResponse', 'Joomla-Legacy/Response/JResponse.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
var subpackagetree_file = new WebFXTreeItem('File(s)', '');
subpackagetree_file.openIcon = 'media/images/folder.png';
subpackagetree_file.icon = 'media/images/folder.png';
var file = new WebFXTreeItem('response.php', 'Joomla-Legacy/Response/_libraries---legacy---response---response.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
subpackagetree.add(subpackagetree_file);
tree.add(subpackagetree);
var subpackagetree = new WebFXTreeItem('<span class="sub-package">Simplecrypt</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('JSimplecrypt', 'Joomla-Legacy/Simplecrypt/JSimplecrypt.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
var subpackagetree_file = new WebFXTreeItem('File(s)', '');
subpackagetree_file.openIcon = 'media/images/folder.png';
subpackagetree_file.icon = 'media/images/folder.png';
var file = new WebFXTreeItem('simplecrypt.php', 'Joomla-Legacy/Simplecrypt/_libraries---legacy---simplecrypt---simplecrypt.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
subpackagetree.add(subpackagetree_file);
tree.add(subpackagetree);
var subpackagetree = new WebFXTreeItem('<span class="sub-package">Simplepie</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('JSimplepieFactory', 'Joomla-Legacy/Simplepie/JSimplepieFactory.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
var subpackagetree_file = new WebFXTreeItem('File(s)', '');
subpackagetree_file.openIcon = 'media/images/folder.png';
subpackagetree_file.icon = 'media/images/folder.png';
var file = new WebFXTreeItem('factory.php', 'Joomla-Legacy/Simplepie/_libraries---legacy---simplepie---factory.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
subpackagetree.add(subpackagetree_file);
tree.add(subpackagetree);
var subpackagetree = new WebFXTreeItem('<span class="sub-package">Table</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('JTableCategory', 'Joomla-Legacy/Table/JTableCategory.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JTableContent', 'Joomla-Legacy/Table/JTableContent.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JTableMenu', 'Joomla-Legacy/Table/JTableMenu.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JTableMenuType', 'Joomla-Legacy/Table/JTableMenuType.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JTableModule', 'Joomla-Legacy/Table/JTableModule.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JTableSession', 'Joomla-Legacy/Table/JTableSession.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
var subpackagetree_file = new WebFXTreeItem('File(s)', '');
subpackagetree_file.openIcon = 'media/images/folder.png';
subpackagetree_file.icon = 'media/images/folder.png';
var file = new WebFXTreeItem('category.php', 'Joomla-Legacy/Table/_libraries---legacy---table---category.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('content.php', 'Joomla-Legacy/Table/_libraries---legacy---table---content.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('menu.php', 'Joomla-Legacy/Table/_libraries---legacy---table---menu.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('module.php', 'Joomla-Legacy/Table/_libraries---legacy---table---module.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('session.php', 'Joomla-Legacy/Table/_libraries---legacy---table---session.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('type.php', 'Joomla-Legacy/Table/_libraries---legacy---table---menu---type.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
subpackagetree.add(subpackagetree_file);
tree.add(subpackagetree);
var subpackagetree = new WebFXTreeItem('<span class="sub-package">Utilities</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('JXMLElement', 'Joomla-Legacy/Utilities/JXMLElement.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
var subpackagetree_file = new WebFXTreeItem('File(s)', '');
subpackagetree_file.openIcon = 'media/images/folder.png';
subpackagetree_file.icon = 'media/images/folder.png';
var file = new WebFXTreeItem('xmlelement.php', 'Joomla-Legacy/Utilities/_libraries---legacy---utilities---xmlelement.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
subpackagetree.add(subpackagetree_file);
tree.add(subpackagetree);
var subpackagetree = new WebFXTreeItem('<span class="sub-package">View</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('JViewCategory', 'Joomla-Legacy/View/JViewCategory.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JViewCategoryfeed', 'Joomla-Legacy/View/JViewCategoryfeed.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
var classe = new WebFXTreeItem('JViewLegacy', 'Joomla-Legacy/View/JViewLegacy.html');
classe.openIcon = 'media/images/Class.png';
classe.icon = 'media/images/Class.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
var subpackagetree_file = new WebFXTreeItem('File(s)', '');
subpackagetree_file.openIcon = 'media/images/folder.png';
subpackagetree_file.icon = 'media/images/folder.png';
var file = new WebFXTreeItem('category.php', 'Joomla-Legacy/View/_libraries---legacy---view---category.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('categoryfeed.php', 'Joomla-Legacy/View/_libraries---legacy---view---categoryfeed.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
var file = new WebFXTreeItem('legacy.php', 'Joomla-Legacy/View/_libraries---legacy---view---legacy.php.html');
file.openIcon = 'media/images/Page.png';
file.icon = 'media/images/Page.png';
subpackagetree_file.add(file);
subpackagetree.add(subpackagetree_file);
tree.add(subpackagetree);
var subpackagetree = new WebFXTreeItem('<span class="sub-package">Toolbar</span>', '');
subpackagetree.openIcon = 'media/images/package.png';
subpackagetree.icon = 'media/images/package.png';
var subpackagetree_classe = new WebFXTreeItem('Class(es)', '');
subpackagetree_classe.openIcon = 'media/images/class_folder.png';
subpackagetree_classe.icon = 'media/images/class_folder.png';
var classe = new WebFXTreeItem('JButton', 'Joomla-Legacy/Toolbar/JButton.html');
classe.openIcon = 'media/images/AbstractClass.png';
classe.icon = 'media/images/AbstractClass.png';
subpackagetree_classe.add(classe);
subpackagetree.add(subpackagetree_classe);
tree.add(subpackagetree);
document.write(tree);
}
</script>
</div>
<p class="notes">
Generated by
<a href="http://www.phpdoc.org" target="_blank">phpDocumentor <span class="field">1.4.3</span></a>
</p>
</body>
</html> | asika32764/Joomla-CMS-API-Document | li_Joomla-Legacy.html | HTML | gpl-2.0 | 50,062 |
/**
* MaNGOS is a full featured server for World of Warcraft, supporting
* the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8
*
* Copyright (C) 2005-2019 MaNGOS project <https://getmangos.eu>
*
* 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
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
#ifndef MANGOSSERVER_ITEM_H
#define MANGOSSERVER_ITEM_H
#include "Common/Common.h"
#include "Object.h"
#include "LootMgr.h"
#include "ItemPrototype.h"
struct SpellEntry;
class Bag;
class Field;
class QueryResult;
class Unit;
struct ItemSetEffect
{
uint32 setid;
uint32 item_count;
SpellEntry const* spells[8];
};
// [-ZERO] Need fix, possible uptodate in mangos-0.6
enum InventoryResult
{
EQUIP_ERR_OK = 0,
EQUIP_ERR_CANT_EQUIP_LEVEL_I = 1, // ERR_CANT_EQUIP_LEVEL_I
EQUIP_ERR_CANT_EQUIP_SKILL = 2, // ERR_CANT_EQUIP_SKILL
EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT = 3, // ERR_WRONG_SLOT
EQUIP_ERR_BAG_FULL = 4, // ERR_BAG_FULL
EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG = 5, // ERR_BAG_IN_BAG
EQUIP_ERR_CANT_TRADE_EQUIP_BAGS = 6, // ERR_TRADE_EQUIPPED_BAG
EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE = 7, // ERR_AMMO_ONLY
EQUIP_ERR_NO_REQUIRED_PROFICIENCY = 8, // ERR_PROFICIENCY_NEEDED
EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE = 9, // ERR_NO_SLOT_AVAILABLE
EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM = 10, // ERR_CANT_EQUIP_EVER
EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM2 = 11, // ERR_CANT_EQUIP_EVER
EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE2 = 12, // ERR_NO_SLOT_AVAILABLE
EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED = 13, // ERR_2HANDED_EQUIPPED
EQUIP_ERR_CANT_DUAL_WIELD = 14, // ERR_2HSKILLNOTFOUND
EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG = 15, // ERR_WRONG_BAG_TYPE
EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG2 = 16, // ERR_WRONG_BAG_TYPE
EQUIP_ERR_CANT_CARRY_MORE_OF_THIS = 17, // ERR_ITEM_MAX_COUNT
EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE3 = 18, // ERR_NO_SLOT_AVAILABLE
EQUIP_ERR_ITEM_CANT_STACK = 19, // ERR_CANT_STACK
EQUIP_ERR_ITEM_CANT_BE_EQUIPPED = 20, // ERR_NOT_EQUIPPABLE
EQUIP_ERR_ITEMS_CANT_BE_SWAPPED = 21, // ERR_CANT_SWAP
EQUIP_ERR_SLOT_IS_EMPTY = 22, // ERR_SLOT_EMPTY
EQUIP_ERR_ITEM_NOT_FOUND = 23, // ERR_ITEM_NOT_FOUND
EQUIP_ERR_CANT_DROP_SOULBOUND = 24, // ERR_DROP_BOUND_ITEM
EQUIP_ERR_OUT_OF_RANGE = 25, // ERR_OUT_OF_RANGE
EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT = 26, // ERR_TOO_FEW_TO_SPLIT
EQUIP_ERR_COULDNT_SPLIT_ITEMS = 27, // ERR_SPLIT_FAILED
EQUIP_ERR_MISSING_REAGENT = 28, // ERR_SPELL_FAILED_REAGENTS_GENERIC
EQUIP_ERR_NOT_ENOUGH_MONEY = 29, // ERR_NOT_ENOUGH_MONEY
EQUIP_ERR_NOT_A_BAG = 30, // ERR_NOT_A_BAG
EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS = 31, // ERR_DESTROY_NONEMPTY_BAG
EQUIP_ERR_DONT_OWN_THAT_ITEM = 32, // ERR_NOT_OWNER
EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER = 33, // ERR_ONLY_ONE_QUIVER
EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT = 34, // ERR_NO_BANK_SLOT
EQUIP_ERR_TOO_FAR_AWAY_FROM_BANK = 35, // ERR_NO_BANK_HERE
EQUIP_ERR_ITEM_LOCKED = 36, // ERR_ITEM_LOCKED
EQUIP_ERR_YOU_ARE_STUNNED = 37, // ERR_GENERIC_STUNNED
EQUIP_ERR_YOU_ARE_DEAD = 38, // ERR_PLAYER_DEAD
EQUIP_ERR_CANT_DO_RIGHT_NOW = 39, // ERR_CLIENT_LOCKED_OUT
EQUIP_ERR_INT_BAG_ERROR = 40, // ERR_INTERNAL_BAG_ERROR
EQUIP_ERR_CAN_EQUIP_ONLY1_BOLT = 41, // ERR_ONLY_ONE_BOLT
EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH = 42, // ERR_ONLY_ONE_AMMO
EQUIP_ERR_STACKABLE_CANT_BE_WRAPPED = 43, // ERR_CANT_WRAP_STACKABLE
EQUIP_ERR_EQUIPPED_CANT_BE_WRAPPED = 44, // ERR_CANT_WRAP_EQUIPPED
EQUIP_ERR_WRAPPED_CANT_BE_WRAPPED = 45, // ERR_CANT_WRAP_WRAPPED
EQUIP_ERR_BOUND_CANT_BE_WRAPPED = 46, // ERR_CANT_WRAP_BOUND
EQUIP_ERR_UNIQUE_CANT_BE_WRAPPED = 47, // ERR_CANT_WRAP_UNIQUE
EQUIP_ERR_BAGS_CANT_BE_WRAPPED = 48, // ERR_CANT_WRAP_BAGS
EQUIP_ERR_ALREADY_LOOTED = 49, // ERR_LOOT_GONE
EQUIP_ERR_INVENTORY_FULL = 50, // ERR_INV_FULL
EQUIP_ERR_BANK_FULL = 51, // ERR_BAG_FULL
EQUIP_ERR_ITEM_IS_CURRENTLY_SOLD_OUT = 52, // ERR_VENDOR_SOLD_OUT
EQUIP_ERR_BAG_FULL3 = 53, // ERR_BAG_FULL
EQUIP_ERR_ITEM_NOT_FOUND2 = 54, // ERR_ITEM_NOT_FOUND
EQUIP_ERR_ITEM_CANT_STACK2 = 55, // ERR_CANT_STACK
EQUIP_ERR_BAG_FULL4 = 56, // ERR_BAG_FULL
EQUIP_ERR_ITEM_SOLD_OUT = 57, // ERR_VENDOR_SOLD_OUT
EQUIP_ERR_OBJECT_IS_BUSY = 58, // ERR_OBJECT_IS_BUSY
EQUIP_ERR_NONE = 59, // ERR_CANT_BE_DISENCHANTED
EQUIP_ERR_NOT_IN_COMBAT = 60, // ERR_NOT_IN_COMBAT
EQUIP_ERR_NOT_WHILE_DISARMED = 61, // ERR_NOT_WHILE_DISARMED
EQUIP_ERR_BAG_FULL6 = 62, // ERR_BAG_FULL
EQUIP_ERR_CANT_EQUIP_RANK = 63, // ERR_CANT_EQUIP_RANK
EQUIP_ERR_CANT_EQUIP_REPUTATION = 64, // ERR_CANT_EQUIP_REPUTATION
EQUIP_ERR_TOO_MANY_SPECIAL_BAGS = 65, // ERR_TOO_MANY_SPECIAL_BAGS
EQUIP_ERR_LOOT_CANT_LOOT_THAT_NOW = 66, // ERR_LOOT_CANT_LOOT_THAT_NOW
// any greater values show as "bag full"
};
enum BuyResult
{
BUY_ERR_CANT_FIND_ITEM = 0,
BUY_ERR_ITEM_ALREADY_SOLD = 1,
BUY_ERR_NOT_ENOUGHT_MONEY = 2,
BUY_ERR_SELLER_DONT_LIKE_YOU = 4,
BUY_ERR_DISTANCE_TOO_FAR = 5,
BUY_ERR_ITEM_SOLD_OUT = 7,
BUY_ERR_CANT_CARRY_MORE = 8,
BUY_ERR_RANK_REQUIRE = 11,
BUY_ERR_REPUTATION_REQUIRE = 12
};
enum SellResult
{
SELL_ERR_CANT_FIND_ITEM = 1,
SELL_ERR_CANT_SELL_ITEM = 2, // merchant doesn't like that item
SELL_ERR_CANT_FIND_VENDOR = 3, // merchant doesn't like you
SELL_ERR_YOU_DONT_OWN_THAT_ITEM = 4, // you don't own that item
SELL_ERR_UNK = 5, // nothing appears...
SELL_ERR_ONLY_EMPTY_BAG = 6 // can only do with empty bags
};
// -1 from client enchantment slot number
enum EnchantmentSlot
{
PERM_ENCHANTMENT_SLOT = 0,
TEMP_ENCHANTMENT_SLOT = 1,
MAX_INSPECTED_ENCHANTMENT_SLOT = 2,
PROP_ENCHANTMENT_SLOT_0 = 3, // used with RandomSuffix
PROP_ENCHANTMENT_SLOT_1 = 4, // used with RandomSuffix
PROP_ENCHANTMENT_SLOT_2 = 5, // used with RandomSuffix
PROP_ENCHANTMENT_SLOT_3 = 6,
MAX_ENCHANTMENT_SLOT = 7
};
#define MAX_VISIBLE_ITEM_OFFSET 12
enum EnchantmentOffset
{
ENCHANTMENT_ID_OFFSET = 0,
ENCHANTMENT_DURATION_OFFSET = 1,
ENCHANTMENT_CHARGES_OFFSET = 2
};
#define MAX_ENCHANTMENT_OFFSET 3
enum EnchantmentSlotMask
{
ENCHANTMENT_CAN_SOULBOUND = 0x01,
ENCHANTMENT_UNK1 = 0x02,
ENCHANTMENT_UNK2 = 0x04,
ENCHANTMENT_UNK3 = 0x08
};
enum ItemUpdateState
{
ITEM_UNCHANGED = 0,
ITEM_CHANGED = 1,
ITEM_NEW = 2,
ITEM_REMOVED = 3
};
enum ItemLootUpdateState
{
ITEM_LOOT_NONE = 0, // loot not generated
ITEM_LOOT_TEMPORARY = 1, // generated loot is temporary (will deleted at loot window close)
ITEM_LOOT_UNCHANGED = 2,
ITEM_LOOT_CHANGED = 3,
ITEM_LOOT_NEW = 4,
ITEM_LOOT_REMOVED = 5
};
// masks for ITEM_FIELD_FLAGS field
enum ItemDynFlags
{
ITEM_DYNFLAG_BINDED = 0x00000001, // set in game at binding
ITEM_DYNFLAG_UNK1 = 0x00000002,
ITEM_DYNFLAG_UNLOCKED = 0x00000004, // have meaning only for item with proto->LockId, if not set show as "Locked, req. lockpicking N"
ITEM_DYNFLAG_WRAPPED = 0x00000008, // mark item as wrapped into wrapper container
ITEM_DYNFLAG_UNK4 = 0x00000010, // can't repeat old note: appears red icon (like when item durability==0)
ITEM_DYNFLAG_UNK5 = 0x00000020,
ITEM_DYNFLAG_UNK6 = 0x00000040, // ? old note: usable
ITEM_DYNFLAG_UNK7 = 0x00000080,
ITEM_DYNFLAG_UNK8 = 0x00000100,
ITEM_DYNFLAG_READABLE = 0x00000200, // can be open for read, it or item proto pagetText make show "Right click to read"
ITEM_DYNFLAG_UNK10 = 0x00000400,
ITEM_DYNFLAG_UNK11 = 0x00000800,
ITEM_DYNFLAG_UNK12 = 0x00001000,
ITEM_DYNFLAG_UNK13 = 0x00002000,
ITEM_DYNFLAG_UNK14 = 0x00004000,
ITEM_DYNFLAG_UNK15 = 0x00008000,
ITEM_DYNFLAG_UNK16 = 0x00010000,
ITEM_DYNFLAG_UNK17 = 0x00020000,
};
enum ItemRequiredTargetType
{
ITEM_TARGET_TYPE_CREATURE = 1,
ITEM_TARGET_TYPE_DEAD = 2
};
#define MAX_ITEM_REQ_TARGET_TYPE 2
struct ItemRequiredTarget
{
ItemRequiredTarget(ItemRequiredTargetType uiType, uint32 uiTargetEntry) : m_uiType(uiType), m_uiTargetEntry(uiTargetEntry) {}
ItemRequiredTargetType m_uiType;
uint32 m_uiTargetEntry;
// helpers
bool IsFitToRequirements(Unit* pUnitTarget) const;
};
bool ItemCanGoIntoBag(ItemPrototype const* proto, ItemPrototype const* pBagProto);
class Item : public Object
{
public:
static Item* CreateItem(uint32 item, uint32 count, Player const* player = NULL, uint32 randomPropertyId = 0);
Item* CloneItem(uint32 count, Player const* player = NULL) const;
Item();
~Item();
virtual bool Create(uint32 guidlow, uint32 itemid, Player const* owner);
ItemPrototype const* GetProto() const;
ObjectGuid const& GetOwnerGuid() const { return GetGuidValue(ITEM_FIELD_OWNER); }
void SetOwnerGuid(ObjectGuid guid) { SetGuidValue(ITEM_FIELD_OWNER, guid); }
Player* GetOwner()const;
void SetBinding(bool val) { ApplyModFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_BINDED, val); }
bool IsSoulBound() const { return HasFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_BINDED); }
bool IsBindedNotWith(Player const* player) const;
bool IsBoundByEnchant() const;
virtual void SaveToDB();
virtual bool LoadFromDB(uint32 guidLow, Field* fields, ObjectGuid ownerGuid = ObjectGuid());
virtual void DeleteFromDB();
void DeleteFromInventoryDB();
void LoadLootFromDB(Field* fields);
Bag* ToBag() { if (IsBag()) return reinterpret_cast<Bag*>(this); else return NULL; }
const Bag* ToBag() const { if (IsBag()) return reinterpret_cast<const Bag*>(this); else return NULL; }
bool IsLocked() const { return !HasFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_UNLOCKED); }
bool IsBag() const { return GetProto()->InventoryType == INVTYPE_BAG; }
bool IsNotEmptyBag() const;
bool IsBroken() const { return GetUInt32Value(ITEM_FIELD_MAXDURABILITY) > 0 && GetUInt32Value(ITEM_FIELD_DURABILITY) == 0; }
bool CanBeTraded() const;
void SetInTrade(bool b = true) { mb_in_trade = b; }
bool IsInTrade() const { return mb_in_trade; }
bool IsFitToSpellRequirements(SpellEntry const* spellInfo) const;
bool IsTargetValidForItemUse(Unit* pUnitTarget);
bool IsLimitedToAnotherMapOrZone(uint32 cur_mapId, uint32 cur_zoneId) const;
uint32 GetCount() const { return GetUInt32Value(ITEM_FIELD_STACK_COUNT); }
void SetCount(uint32 value) { SetUInt32Value(ITEM_FIELD_STACK_COUNT, value); }
uint32 GetMaxStackCount() const { return GetProto()->GetMaxStackSize(); }
InventoryResult CanBeMergedPartlyWith(ItemPrototype const* proto) const;
uint8 GetSlot() const {return m_slot;}
Bag* GetContainer() { return m_container; }
uint8 GetBagSlot() const;
void SetSlot(uint8 slot) {m_slot = slot;}
uint16 GetPos() const { return uint16(GetBagSlot()) << 8 | GetSlot(); }
void SetContainer(Bag* container) { m_container = container; }
bool IsInBag() const { return m_container != NULL; }
bool IsEquipped() const;
uint32 GetSkill();
uint32 GetSpell();
// RandomPropertyId (signed but stored as unsigned)
int32 GetItemRandomPropertyId() const { return GetInt32Value(ITEM_FIELD_RANDOM_PROPERTIES_ID); }
uint32 GetItemSuffixFactor() const { return GetUInt32Value(ITEM_FIELD_PROPERTY_SEED); }
void SetItemRandomProperties(int32 randomPropId);
static int32 GenerateItemRandomPropertyId(uint32 item_id);
void SetEnchantment(EnchantmentSlot slot, uint32 id, uint32 duration, uint32 charges);
void SetEnchantmentDuration(EnchantmentSlot slot, uint32 duration);
void SetEnchantmentCharges(EnchantmentSlot slot, uint32 charges);
void ClearEnchantment(EnchantmentSlot slot);
uint32 GetEnchantmentId(EnchantmentSlot slot) const { return GetUInt32Value(ITEM_FIELD_ENCHANTMENT + slot * MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_ID_OFFSET);}
uint32 GetEnchantmentDuration(EnchantmentSlot slot) const { return GetUInt32Value(ITEM_FIELD_ENCHANTMENT + slot * MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_DURATION_OFFSET);}
uint32 GetEnchantmentCharges(EnchantmentSlot slot) const { return GetUInt32Value(ITEM_FIELD_ENCHANTMENT + slot * MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_CHARGES_OFFSET);}
void SendTimeUpdate(Player* owner);
void UpdateDuration(Player* owner, uint32 diff);
// spell charges (signed but stored as unsigned)
int32 GetSpellCharges(uint8 index/*0..5*/ = 0) const { return GetInt32Value(ITEM_FIELD_SPELL_CHARGES + index); }
void SetSpellCharges(uint8 index/*0..5*/, int32 value) { SetInt32Value(ITEM_FIELD_SPELL_CHARGES + index, value); }
Loot loot;
void SetLootState(ItemLootUpdateState state);
bool HasGeneratedLoot() const { return m_lootState != ITEM_LOOT_NONE && m_lootState != ITEM_LOOT_REMOVED; }
bool HasTemporaryLoot() const { return m_lootState == ITEM_LOOT_TEMPORARY; }
bool HasSavedLoot() const { return m_lootState != ITEM_LOOT_NONE && m_lootState != ITEM_LOOT_NEW && m_lootState != ITEM_LOOT_TEMPORARY; }
// Update States
ItemUpdateState GetState() const { return uState; }
void SetState(ItemUpdateState state, Player* forplayer = NULL);
void AddToUpdateQueueOf(Player* player);
void RemoveFromUpdateQueueOf(Player* player);
bool IsInUpdateQueue() const { return uQueuePos != -1; }
uint16 GetQueuePos() const { return uQueuePos; }
void FSetState(ItemUpdateState state) // forced
{
uState = state;
}
bool HasQuest(uint32 quest_id) const override { return GetProto()->StartQuest == quest_id; }
bool HasInvolvedQuest(uint32 /*quest_id*/) const override { return false; }
bool IsPotion() const { return GetProto()->IsPotion(); }
bool IsConjuredConsumable() const { return GetProto()->IsConjuredConsumable(); }
bool IsWeaponVellum() const { return GetProto()->IsWeaponVellum(); }
bool IsArmorVellum() const { return GetProto()->IsArmorVellum(); }
uint32 GetScriptId() const;
void AddToClientUpdateList() override;
void RemoveFromClientUpdateList() override;
void BuildUpdateData(UpdateDataMapType& update_players) override;
private:
uint8 m_slot;
Bag* m_container;
ItemUpdateState uState;
int16 uQueuePos;
bool mb_in_trade; // true if item is currently in trade-window
ItemLootUpdateState m_lootState;
};
#endif
| H0zen/M0-server | src/game/Object/Item.h | C | gpl-2.0 | 18,060 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Modèle;
import Controleur.Controleur;
import java.awt.Color;
import vue.Graphique.BlocCustomGraphique;
/**
* Ce bloc permet de créer son propre code.
* @author tancfire
*/
public class BlocCustom extends Bloc{
String code;
public BlocCustom(String code, Controleur ctrl) {
super(TypeBloc.programmation, Color.PINK, new BlocCustomGraphique(), ctrl);
initialisation(code);
init();
}
public BlocCustom(int id, String code, Controleur ctrl) {
super(id, TypeBloc.programmation, Color.PINK, new BlocCustomGraphique(), ctrl);
initialisation(code);
init();
}
private void initialisation(String code)
{
this.code = code;
}
@Override
public void mettreAjourCode() {
sonCodeDebut = code;
acces.setParametre(id, "String", "code", code);
}
}
| FunLABGIT/FunArduino | src/Modèle/BlocCustom.java | Java | gpl-2.0 | 1,071 |
/*
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/// \addtogroup u2w
/// @{
/// \file
#ifndef _OPCODES_H
#define _OPCODES_H
#include "Common.h"
// Note: this include need for be sure have full definition of class WorldSession
// if this class definition not complite then VS for x64 release use different size for
// struct OpcodeHandler in this header and Opcode.cpp and get totally wrong data from
// table opcodeTable in source when Opcode.h included but WorldSession.h not included
#include "WorldSession.h"
/// List of Opcodes
enum Opcodes
{
MSG_NULL_ACTION = 0x000,
CMSG_BOOTME = 0x001,
CMSG_DBLOOKUP = 0x002,
SMSG_DBLOOKUP = 0x003,
CMSG_QUERY_OBJECT_POSITION = 0x004,
SMSG_QUERY_OBJECT_POSITION = 0x005,
CMSG_QUERY_OBJECT_ROTATION = 0x006,
SMSG_QUERY_OBJECT_ROTATION = 0x007,
CMSG_WORLD_TELEPORT = 0x008,
CMSG_TELEPORT_TO_UNIT = 0x009,
CMSG_ZONE_MAP = 0x00A,
SMSG_ZONE_MAP = 0x00B,
CMSG_DEBUG_CHANGECELLZONE = 0x00C,
CMSG_MOVE_CHARACTER_CHEAT = 0x00D,
SMSG_MOVE_CHARACTER_CHEAT = 0x00E,
CMSG_RECHARGE = 0x00F,
CMSG_LEARN_SPELL = 0x010,
CMSG_CREATEMONSTER = 0x011,
CMSG_DESTROYMONSTER = 0x012,
CMSG_CREATEITEM = 0x013,
CMSG_CREATEGAMEOBJECT = 0x014,
SMSG_CHECK_FOR_BOTS = 0x015,
CMSG_MAKEMONSTERATTACKGUID = 0x016,
CMSG_BOT_DETECTED2 = 0x017,
CMSG_FORCEACTION = 0x018,
CMSG_FORCEACTIONONOTHER = 0x019,
CMSG_FORCEACTIONSHOW = 0x01A,
SMSG_FORCEACTIONSHOW = 0x01B,
CMSG_PETGODMODE = 0x01C,
SMSG_PETGODMODE = 0x01D,
SMSG_REFER_A_FRIEND_EXPIRED = 0x01E,
CMSG_WEATHER_SPEED_CHEAT = 0x01F,
CMSG_UNDRESSPLAYER = 0x020,
CMSG_BEASTMASTER = 0x021,
CMSG_GODMODE = 0x022,
SMSG_GODMODE = 0x023,
CMSG_CHEAT_SETMONEY = 0x024,
CMSG_LEVEL_CHEAT = 0x025,
CMSG_PET_LEVEL_CHEAT = 0x026,
CMSG_SET_WORLDSTATE = 0x027,
CMSG_COOLDOWN_CHEAT = 0x028,
CMSG_USE_SKILL_CHEAT = 0x029,
CMSG_FLAG_QUEST = 0x02A,
CMSG_FLAG_QUEST_FINISH = 0x02B,
CMSG_CLEAR_QUEST = 0x02C,
CMSG_SEND_EVENT = 0x02D,
CMSG_DEBUG_AISTATE = 0x02E,
SMSG_DEBUG_AISTATE = 0x02F,
CMSG_DISABLE_PVP_CHEAT = 0x030,
CMSG_ADVANCE_SPAWN_TIME = 0x031,
SMSG_DESTRUCTIBLE_BUILDING_DAMAGE = 0x032,
CMSG_AUTH_SRP6_BEGIN = 0x033,
CMSG_AUTH_SRP6_PROOF = 0x034,
CMSG_AUTH_SRP6_RECODE = 0x035,
CMSG_CHAR_CREATE = 0x036,
CMSG_CHAR_ENUM = 0x037,
CMSG_CHAR_DELETE = 0x038,
SMSG_AUTH_SRP6_RESPONSE = 0x039,
SMSG_CHAR_CREATE = 0x03A,
SMSG_CHAR_ENUM = 0x03B,
SMSG_CHAR_DELETE = 0x03C,
CMSG_PLAYER_LOGIN = 0x03D,
SMSG_NEW_WORLD = 0x03E,
SMSG_TRANSFER_PENDING = 0x03F,
SMSG_TRANSFER_ABORTED = 0x040,
SMSG_CHARACTER_LOGIN_FAILED = 0x041,
SMSG_LOGIN_SETTIMESPEED = 0x042,
SMSG_GAMETIME_UPDATE = 0x043,
CMSG_GAMETIME_SET = 0x044,
SMSG_GAMETIME_SET = 0x045,
CMSG_GAMESPEED_SET = 0x046,
SMSG_GAMESPEED_SET = 0x047,
CMSG_SERVERTIME = 0x048,
SMSG_SERVERTIME = 0x049,
CMSG_PLAYER_LOGOUT = 0x04A,
CMSG_LOGOUT_REQUEST = 0x04B,
SMSG_LOGOUT_RESPONSE = 0x04C,
SMSG_LOGOUT_COMPLETE = 0x04D,
CMSG_LOGOUT_CANCEL = 0x04E,
SMSG_LOGOUT_CANCEL_ACK = 0x04F,
CMSG_NAME_QUERY = 0x050,
SMSG_NAME_QUERY_RESPONSE = 0x051,
CMSG_PET_NAME_QUERY = 0x052,
SMSG_PET_NAME_QUERY_RESPONSE = 0x053,
CMSG_GUILD_QUERY = 0x054,
SMSG_GUILD_QUERY_RESPONSE = 0x055,
CMSG_ITEM_QUERY_SINGLE = 0x056,
CMSG_ITEM_QUERY_MULTIPLE = 0x057,
SMSG_ITEM_QUERY_SINGLE_RESPONSE = 0x058,
SMSG_ITEM_QUERY_MULTIPLE_RESPONSE = 0x059,
CMSG_PAGE_TEXT_QUERY = 0x05A,
SMSG_PAGE_TEXT_QUERY_RESPONSE = 0x05B,
CMSG_QUEST_QUERY = 0x05C,
SMSG_QUEST_QUERY_RESPONSE = 0x05D,
CMSG_GAMEOBJECT_QUERY = 0x05E,
SMSG_GAMEOBJECT_QUERY_RESPONSE = 0x05F,
CMSG_CREATURE_QUERY = 0x060,
SMSG_CREATURE_QUERY_RESPONSE = 0x061,
CMSG_WHO = 0x062,
SMSG_WHO = 0x063,
CMSG_WHOIS = 0x064,
SMSG_WHOIS = 0x065,
CMSG_CONTACT_LIST = 0x066,
SMSG_CONTACT_LIST = 0x067,
SMSG_FRIEND_STATUS = 0x068,
CMSG_ADD_FRIEND = 0x069,
CMSG_DEL_FRIEND = 0x06A,
CMSG_SET_CONTACT_NOTES = 0x06B,
CMSG_ADD_IGNORE = 0x06C,
CMSG_DEL_IGNORE = 0x06D,
CMSG_GROUP_INVITE = 0x06E,
SMSG_GROUP_INVITE = 0x06F,
CMSG_GROUP_CANCEL = 0x070,
SMSG_GROUP_CANCEL = 0x071,
CMSG_GROUP_ACCEPT = 0x072,
CMSG_GROUP_DECLINE = 0x073,
SMSG_GROUP_DECLINE = 0x074,
CMSG_GROUP_UNINVITE = 0x075,
CMSG_GROUP_UNINVITE_GUID = 0x076,
SMSG_GROUP_UNINVITE = 0x077,
CMSG_GROUP_SET_LEADER = 0x078,
SMSG_GROUP_SET_LEADER = 0x079,
CMSG_LOOT_METHOD = 0x07A,
CMSG_GROUP_DISBAND = 0x07B,
SMSG_GROUP_DESTROYED = 0x07C,
SMSG_GROUP_LIST = 0x07D,
SMSG_PARTY_MEMBER_STATS = 0x07E,
SMSG_PARTY_COMMAND_RESULT = 0x07F,
UMSG_UPDATE_GROUP_MEMBERS = 0x080,
CMSG_GUILD_CREATE = 0x081,
CMSG_GUILD_INVITE = 0x082,
SMSG_GUILD_INVITE = 0x083,
CMSG_GUILD_ACCEPT = 0x084,
CMSG_GUILD_DECLINE = 0x085,
SMSG_GUILD_DECLINE = 0x086,
CMSG_GUILD_INFO = 0x087,
SMSG_GUILD_INFO = 0x088,
CMSG_GUILD_ROSTER = 0x089,
SMSG_GUILD_ROSTER = 0x08A,
CMSG_GUILD_PROMOTE = 0x08B,
CMSG_GUILD_DEMOTE = 0x08C,
CMSG_GUILD_LEAVE = 0x08D,
CMSG_GUILD_REMOVE = 0x08E,
CMSG_GUILD_DISBAND = 0x08F,
CMSG_GUILD_LEADER = 0x090,
CMSG_GUILD_MOTD = 0x091,
SMSG_GUILD_EVENT = 0x092,
SMSG_GUILD_COMMAND_RESULT = 0x093,
UMSG_UPDATE_GUILD = 0x094,
CMSG_MESSAGECHAT = 0x095,
SMSG_MESSAGECHAT = 0x096,
CMSG_JOIN_CHANNEL = 0x097,
CMSG_LEAVE_CHANNEL = 0x098,
SMSG_CHANNEL_NOTIFY = 0x099,
CMSG_CHANNEL_LIST = 0x09A,
SMSG_CHANNEL_LIST = 0x09B,
CMSG_CHANNEL_PASSWORD = 0x09C,
CMSG_CHANNEL_SET_OWNER = 0x09D,
CMSG_CHANNEL_OWNER = 0x09E,
CMSG_CHANNEL_MODERATOR = 0x09F,
CMSG_CHANNEL_UNMODERATOR = 0x0A0,
CMSG_CHANNEL_MUTE = 0x0A1,
CMSG_CHANNEL_UNMUTE = 0x0A2,
CMSG_CHANNEL_INVITE = 0x0A3,
CMSG_CHANNEL_KICK = 0x0A4,
CMSG_CHANNEL_BAN = 0x0A5,
CMSG_CHANNEL_UNBAN = 0x0A6,
CMSG_CHANNEL_ANNOUNCEMENTS = 0x0A7,
CMSG_CHANNEL_MODERATE = 0x0A8,
SMSG_UPDATE_OBJECT = 0x0A9,
SMSG_DESTROY_OBJECT = 0x0AA,
CMSG_USE_ITEM = 0x0AB,
CMSG_OPEN_ITEM = 0x0AC,
CMSG_READ_ITEM = 0x0AD,
SMSG_READ_ITEM_OK = 0x0AE,
SMSG_READ_ITEM_FAILED = 0x0AF,
SMSG_ITEM_COOLDOWN = 0x0B0,
CMSG_GAMEOBJ_USE = 0x0B1,
CMSG_DESTROY_ITEMS = 0x0B2,
SMSG_GAMEOBJECT_CUSTOM_ANIM = 0x0B3,
CMSG_AREATRIGGER = 0x0B4,
MSG_MOVE_START_FORWARD = 0x0B5,
MSG_MOVE_START_BACKWARD = 0x0B6,
MSG_MOVE_STOP = 0x0B7,
MSG_MOVE_START_STRAFE_LEFT = 0x0B8,
MSG_MOVE_START_STRAFE_RIGHT = 0x0B9,
MSG_MOVE_STOP_STRAFE = 0x0BA,
MSG_MOVE_JUMP = 0x0BB,
MSG_MOVE_START_TURN_LEFT = 0x0BC,
MSG_MOVE_START_TURN_RIGHT = 0x0BD,
MSG_MOVE_STOP_TURN = 0x0BE,
MSG_MOVE_START_PITCH_UP = 0x0BF,
MSG_MOVE_START_PITCH_DOWN = 0x0C0,
MSG_MOVE_STOP_PITCH = 0x0C1,
MSG_MOVE_SET_RUN_MODE = 0x0C2,
MSG_MOVE_SET_WALK_MODE = 0x0C3,
MSG_MOVE_TOGGLE_LOGGING = 0x0C4,
MSG_MOVE_TELEPORT = 0x0C5,
MSG_MOVE_TELEPORT_CHEAT = 0x0C6,
MSG_MOVE_TELEPORT_ACK = 0x0C7,
MSG_MOVE_TOGGLE_FALL_LOGGING = 0x0C8,
MSG_MOVE_FALL_LAND = 0x0C9,
MSG_MOVE_START_SWIM = 0x0CA,
MSG_MOVE_STOP_SWIM = 0x0CB,
MSG_MOVE_SET_RUN_SPEED_CHEAT = 0x0CC,
MSG_MOVE_SET_RUN_SPEED = 0x0CD,
MSG_MOVE_SET_RUN_BACK_SPEED_CHEAT = 0x0CE,
MSG_MOVE_SET_RUN_BACK_SPEED = 0x0CF,
MSG_MOVE_SET_WALK_SPEED_CHEAT = 0x0D0,
MSG_MOVE_SET_WALK_SPEED = 0x0D1,
MSG_MOVE_SET_SWIM_SPEED_CHEAT = 0x0D2,
MSG_MOVE_SET_SWIM_SPEED = 0x0D3,
MSG_MOVE_SET_SWIM_BACK_SPEED_CHEAT = 0x0D4,
MSG_MOVE_SET_SWIM_BACK_SPEED = 0x0D5,
MSG_MOVE_SET_ALL_SPEED_CHEAT = 0x0D6,
MSG_MOVE_SET_TURN_RATE_CHEAT = 0x0D7,
MSG_MOVE_SET_TURN_RATE = 0x0D8,
MSG_MOVE_TOGGLE_COLLISION_CHEAT = 0x0D9,
MSG_MOVE_SET_FACING = 0x0DA,
MSG_MOVE_SET_PITCH = 0x0DB,
MSG_MOVE_WORLDPORT_ACK = 0x0DC,
SMSG_MONSTER_MOVE = 0x0DD,
SMSG_MOVE_WATER_WALK = 0x0DE,
SMSG_MOVE_LAND_WALK = 0x0DF,
MSG_MOVE_SET_RAW_POSITION_ACK = 0x0E0,
CMSG_MOVE_SET_RAW_POSITION = 0x0E1,
SMSG_FORCE_RUN_SPEED_CHANGE = 0x0E2,
CMSG_FORCE_RUN_SPEED_CHANGE_ACK = 0x0E3,
SMSG_FORCE_RUN_BACK_SPEED_CHANGE = 0x0E4,
CMSG_FORCE_RUN_BACK_SPEED_CHANGE_ACK = 0x0E5,
SMSG_FORCE_SWIM_SPEED_CHANGE = 0x0E6,
CMSG_FORCE_SWIM_SPEED_CHANGE_ACK = 0x0E7,
SMSG_FORCE_MOVE_ROOT = 0x0E8,
CMSG_FORCE_MOVE_ROOT_ACK = 0x0E9,
SMSG_FORCE_MOVE_UNROOT = 0x0EA,
CMSG_FORCE_MOVE_UNROOT_ACK = 0x0EB,
MSG_MOVE_ROOT = 0x0EC,
MSG_MOVE_UNROOT = 0x0ED,
MSG_MOVE_HEARTBEAT = 0x0EE,
SMSG_MOVE_KNOCK_BACK = 0x0EF,
CMSG_MOVE_KNOCK_BACK_ACK = 0x0F0,
MSG_MOVE_KNOCK_BACK = 0x0F1,
SMSG_MOVE_FEATHER_FALL = 0x0F2,
SMSG_MOVE_NORMAL_FALL = 0x0F3,
SMSG_MOVE_SET_HOVER = 0x0F4,
SMSG_MOVE_UNSET_HOVER = 0x0F5,
CMSG_MOVE_HOVER_ACK = 0x0F6,
MSG_MOVE_HOVER = 0x0F7,
CMSG_TRIGGER_CINEMATIC_CHEAT = 0x0F8,
CMSG_OPENING_CINEMATIC = 0x0F9,
SMSG_TRIGGER_CINEMATIC = 0x0FA,
CMSG_NEXT_CINEMATIC_CAMERA = 0x0FB,
CMSG_COMPLETE_CINEMATIC = 0x0FC,
SMSG_TUTORIAL_FLAGS = 0x0FD,
CMSG_TUTORIAL_FLAG = 0x0FE,
CMSG_TUTORIAL_CLEAR = 0x0FF,
CMSG_TUTORIAL_RESET = 0x100,
CMSG_STANDSTATECHANGE = 0x101,
CMSG_EMOTE = 0x102,
SMSG_EMOTE = 0x103,
CMSG_TEXT_EMOTE = 0x104,
SMSG_TEXT_EMOTE = 0x105,
CMSG_AUTOEQUIP_GROUND_ITEM = 0x106,
CMSG_AUTOSTORE_GROUND_ITEM = 0x107,
CMSG_AUTOSTORE_LOOT_ITEM = 0x108,
CMSG_STORE_LOOT_IN_SLOT = 0x109,
CMSG_AUTOEQUIP_ITEM = 0x10A,
CMSG_AUTOSTORE_BAG_ITEM = 0x10B,
CMSG_SWAP_ITEM = 0x10C,
CMSG_SWAP_INV_ITEM = 0x10D,
CMSG_SPLIT_ITEM = 0x10E,
CMSG_AUTOEQUIP_ITEM_SLOT = 0x10F,
OBSOLETE_DROP_ITEM = 0x110,
CMSG_DESTROYITEM = 0x111,
SMSG_INVENTORY_CHANGE_FAILURE = 0x112,
SMSG_OPEN_CONTAINER = 0x113,
CMSG_INSPECT = 0x114,
SMSG_INSPECT = 0x115,
CMSG_INITIATE_TRADE = 0x116,
CMSG_BEGIN_TRADE = 0x117,
CMSG_BUSY_TRADE = 0x118,
CMSG_IGNORE_TRADE = 0x119,
CMSG_ACCEPT_TRADE = 0x11A,
CMSG_UNACCEPT_TRADE = 0x11B,
CMSG_CANCEL_TRADE = 0x11C,
CMSG_SET_TRADE_ITEM = 0x11D,
CMSG_CLEAR_TRADE_ITEM = 0x11E,
CMSG_SET_TRADE_GOLD = 0x11F,
SMSG_TRADE_STATUS = 0x120,
SMSG_TRADE_STATUS_EXTENDED = 0x121,
SMSG_INITIALIZE_FACTIONS = 0x122,
SMSG_SET_FACTION_VISIBLE = 0x123,
SMSG_SET_FACTION_STANDING = 0x124,
CMSG_SET_FACTION_ATWAR = 0x125,
CMSG_SET_FACTION_CHEAT = 0x126,
SMSG_SET_PROFICIENCY = 0x127,
CMSG_SET_ACTION_BUTTON = 0x128,
SMSG_ACTION_BUTTONS = 0x129,
SMSG_INITIAL_SPELLS = 0x12A,
SMSG_LEARNED_SPELL = 0x12B,
SMSG_SUPERCEDED_SPELL = 0x12C,
CMSG_NEW_SPELL_SLOT = 0x12D,
CMSG_CAST_SPELL = 0x12E,
CMSG_CANCEL_CAST = 0x12F,
SMSG_CAST_FAILED = 0x130,
SMSG_SPELL_START = 0x131,
SMSG_SPELL_GO = 0x132,
SMSG_SPELL_FAILURE = 0x133,
SMSG_SPELL_COOLDOWN = 0x134,
SMSG_COOLDOWN_EVENT = 0x135,
CMSG_CANCEL_AURA = 0x136,
SMSG_EQUIPMENT_SET_SAVED = 0x137,
SMSG_PET_CAST_FAILED = 0x138,
MSG_CHANNEL_START = 0x139,
MSG_CHANNEL_UPDATE = 0x13A,
CMSG_CANCEL_CHANNELLING = 0x13B,
SMSG_AI_REACTION = 0x13C,
CMSG_SET_SELECTION = 0x13D,
CMSG_EQUIPMENT_SET_DELETE = 0x13E,
CMSG_INSTANCE_LOCK_WARNING_RESPONSE = 0x13F,
CMSG_UNUSED2 = 0x140,
CMSG_ATTACKSWING = 0x141,
CMSG_ATTACKSTOP = 0x142,
SMSG_ATTACKSTART = 0x143,
SMSG_ATTACKSTOP = 0x144,
SMSG_ATTACKSWING_NOTINRANGE = 0x145,
SMSG_ATTACKSWING_BADFACING = 0x146,
SMSG_INSTANCE_LOCK_WARNING_QUERY = 0x147,
SMSG_ATTACKSWING_DEADTARGET = 0x148,
SMSG_ATTACKSWING_CANT_ATTACK = 0x149,
SMSG_ATTACKERSTATEUPDATE = 0x14A,
SMSG_BATTLEFIELD_PORT_DENIED = 0x14B,
SMSG_DAMAGE_DONE_OBSOLETE = 0x14C,
SMSG_DAMAGE_TAKEN_OBSOLETE = 0x14D,
SMSG_CANCEL_COMBAT = 0x14E,
SMSG_SPELLBREAKLOG = 0x14F,
SMSG_SPELLHEALLOG = 0x150,
SMSG_SPELLENERGIZELOG = 0x151,
SMSG_BREAK_TARGET = 0x152,
CMSG_SAVE_PLAYER = 0x153,
CMSG_SETDEATHBINDPOINT = 0x154,
SMSG_BINDPOINTUPDATE = 0x155,
CMSG_GETDEATHBINDZONE = 0x156,
SMSG_BINDZONEREPLY = 0x157,
SMSG_PLAYERBOUND = 0x158,
SMSG_CLIENT_CONTROL_UPDATE = 0x159,
CMSG_REPOP_REQUEST = 0x15A,
SMSG_RESURRECT_REQUEST = 0x15B,
CMSG_RESURRECT_RESPONSE = 0x15C,
CMSG_LOOT = 0x15D,
CMSG_LOOT_MONEY = 0x15E,
CMSG_LOOT_RELEASE = 0x15F,
SMSG_LOOT_RESPONSE = 0x160,
SMSG_LOOT_RELEASE_RESPONSE = 0x161,
SMSG_LOOT_REMOVED = 0x162,
SMSG_LOOT_MONEY_NOTIFY = 0x163,
SMSG_LOOT_ITEM_NOTIFY = 0x164,
SMSG_LOOT_CLEAR_MONEY = 0x165,
SMSG_ITEM_PUSH_RESULT = 0x166,
SMSG_DUEL_REQUESTED = 0x167,
SMSG_DUEL_OUTOFBOUNDS = 0x168,
SMSG_DUEL_INBOUNDS = 0x169,
SMSG_DUEL_COMPLETE = 0x16A,
SMSG_DUEL_WINNER = 0x16B,
CMSG_DUEL_ACCEPTED = 0x16C,
CMSG_DUEL_CANCELLED = 0x16D,
SMSG_MOUNTRESULT = 0x16E,
SMSG_DISMOUNTRESULT = 0x16F,
SMSG_PUREMOUNT_CANCELLED_OBSOLETE = 0x170,
CMSG_MOUNTSPECIAL_ANIM = 0x171,
SMSG_MOUNTSPECIAL_ANIM = 0x172,
SMSG_PET_TAME_FAILURE = 0x173,
CMSG_PET_SET_ACTION = 0x174,
CMSG_PET_ACTION = 0x175,
CMSG_PET_ABANDON = 0x176,
CMSG_PET_RENAME = 0x177,
SMSG_PET_NAME_INVALID = 0x178,
SMSG_PET_SPELLS = 0x179,
SMSG_PET_MODE = 0x17A,
CMSG_GOSSIP_HELLO = 0x17B,
CMSG_GOSSIP_SELECT_OPTION = 0x17C,
SMSG_GOSSIP_MESSAGE = 0x17D,
SMSG_GOSSIP_COMPLETE = 0x17E,
CMSG_NPC_TEXT_QUERY = 0x17F,
SMSG_NPC_TEXT_UPDATE = 0x180,
SMSG_NPC_WONT_TALK = 0x181,
CMSG_QUESTGIVER_STATUS_QUERY = 0x182,
SMSG_QUESTGIVER_STATUS = 0x183,
CMSG_QUESTGIVER_HELLO = 0x184,
SMSG_QUESTGIVER_QUEST_LIST = 0x185,
CMSG_QUESTGIVER_QUERY_QUEST = 0x186,
CMSG_QUESTGIVER_QUEST_AUTOLAUNCH = 0x187,
SMSG_QUESTGIVER_QUEST_DETAILS = 0x188,
CMSG_QUESTGIVER_ACCEPT_QUEST = 0x189,
CMSG_QUESTGIVER_COMPLETE_QUEST = 0x18A,
SMSG_QUESTGIVER_REQUEST_ITEMS = 0x18B,
CMSG_QUESTGIVER_REQUEST_REWARD = 0x18C,
SMSG_QUESTGIVER_OFFER_REWARD = 0x18D,
CMSG_QUESTGIVER_CHOOSE_REWARD = 0x18E,
SMSG_QUESTGIVER_QUEST_INVALID = 0x18F,
CMSG_QUESTGIVER_CANCEL = 0x190,
SMSG_QUESTGIVER_QUEST_COMPLETE = 0x191,
SMSG_QUESTGIVER_QUEST_FAILED = 0x192,
CMSG_QUESTLOG_SWAP_QUEST = 0x193,
CMSG_QUESTLOG_REMOVE_QUEST = 0x194,
SMSG_QUESTLOG_FULL = 0x195,
SMSG_QUESTUPDATE_FAILED = 0x196,
SMSG_QUESTUPDATE_FAILEDTIMER = 0x197,
SMSG_QUESTUPDATE_COMPLETE = 0x198,
SMSG_QUESTUPDATE_ADD_KILL = 0x199,
SMSG_QUESTUPDATE_ADD_ITEM = 0x19A,
CMSG_QUEST_CONFIRM_ACCEPT = 0x19B,
SMSG_QUEST_CONFIRM_ACCEPT = 0x19C,
CMSG_PUSHQUESTTOPARTY = 0x19D,
CMSG_LIST_INVENTORY = 0x19E,
SMSG_LIST_INVENTORY = 0x19F,
CMSG_SELL_ITEM = 0x1A0,
SMSG_SELL_ITEM = 0x1A1,
CMSG_BUY_ITEM = 0x1A2,
CMSG_BUY_ITEM_IN_SLOT = 0x1A3,
SMSG_BUY_ITEM = 0x1A4,
SMSG_BUY_FAILED = 0x1A5,
CMSG_TAXICLEARALLNODES = 0x1A6,
CMSG_TAXIENABLEALLNODES = 0x1A7,
CMSG_TAXISHOWNODES = 0x1A8,
SMSG_SHOWTAXINODES = 0x1A9,
CMSG_TAXINODE_STATUS_QUERY = 0x1AA,
SMSG_TAXINODE_STATUS = 0x1AB,
CMSG_TAXIQUERYAVAILABLENODES = 0x1AC,
CMSG_ACTIVATETAXI = 0x1AD,
SMSG_ACTIVATETAXIREPLY = 0x1AE,
SMSG_NEW_TAXI_PATH = 0x1AF,
CMSG_TRAINER_LIST = 0x1B0,
SMSG_TRAINER_LIST = 0x1B1,
CMSG_TRAINER_BUY_SPELL = 0x1B2,
SMSG_TRAINER_BUY_SUCCEEDED = 0x1B3,
SMSG_TRAINER_BUY_FAILED = 0x1B4,
CMSG_BINDER_ACTIVATE = 0x1B5,
SMSG_PLAYERBINDERROR = 0x1B6,
CMSG_BANKER_ACTIVATE = 0x1B7,
SMSG_SHOW_BANK = 0x1B8,
CMSG_BUY_BANK_SLOT = 0x1B9,
SMSG_BUY_BANK_SLOT_RESULT = 0x1BA,
CMSG_PETITION_SHOWLIST = 0x1BB,
SMSG_PETITION_SHOWLIST = 0x1BC,
CMSG_PETITION_BUY = 0x1BD,
CMSG_PETITION_SHOW_SIGNATURES = 0x1BE,
SMSG_PETITION_SHOW_SIGNATURES = 0x1BF,
CMSG_PETITION_SIGN = 0x1C0,
SMSG_PETITION_SIGN_RESULTS = 0x1C1,
MSG_PETITION_DECLINE = 0x1C2,
CMSG_OFFER_PETITION = 0x1C3,
CMSG_TURN_IN_PETITION = 0x1C4,
SMSG_TURN_IN_PETITION_RESULTS = 0x1C5,
CMSG_PETITION_QUERY = 0x1C6,
SMSG_PETITION_QUERY_RESPONSE = 0x1C7,
SMSG_FISH_NOT_HOOKED = 0x1C8,
SMSG_FISH_ESCAPED = 0x1C9,
CMSG_BUG = 0x1CA,
SMSG_NOTIFICATION = 0x1CB,
CMSG_PLAYED_TIME = 0x1CC,
SMSG_PLAYED_TIME = 0x1CD,
CMSG_QUERY_TIME = 0x1CE,
SMSG_QUERY_TIME_RESPONSE = 0x1CF,
SMSG_LOG_XPGAIN = 0x1D0,
SMSG_AURACASTLOG = 0x1D1,
CMSG_RECLAIM_CORPSE = 0x1D2,
CMSG_WRAP_ITEM = 0x1D3,
SMSG_LEVELUP_INFO = 0x1D4,
MSG_MINIMAP_PING = 0x1D5,
SMSG_RESISTLOG = 0x1D6,
SMSG_ENCHANTMENTLOG = 0x1D7,
CMSG_SET_SKILL_CHEAT = 0x1D8,
SMSG_START_MIRROR_TIMER = 0x1D9,
SMSG_PAUSE_MIRROR_TIMER = 0x1DA,
SMSG_STOP_MIRROR_TIMER = 0x1DB,
CMSG_PING = 0x1DC,
SMSG_PONG = 0x1DD,
SMSG_CLEAR_COOLDOWN = 0x1DE,
SMSG_GAMEOBJECT_PAGETEXT = 0x1DF,
CMSG_SETSHEATHED = 0x1E0,
SMSG_COOLDOWN_CHEAT = 0x1E1,
SMSG_SPELL_DELAYED = 0x1E2,
CMSG_QUEST_POI_QUERY = 0x1E3,
SMSG_QUEST_POI_QUERY_RESPONSE = 0x1E4,
CMSG_GHOST = 0x1E5,
CMSG_GM_INVIS = 0x1E6,
SMSG_INVALID_PROMOTION_CODE = 0x1E7,
MSG_GM_BIND_OTHER = 0x1E8,
MSG_GM_SUMMON = 0x1E9,
SMSG_ITEM_TIME_UPDATE = 0x1EA,
SMSG_ITEM_ENCHANT_TIME_UPDATE = 0x1EB,
SMSG_AUTH_CHALLENGE = 0x1EC,
CMSG_AUTH_SESSION = 0x1ED,
SMSG_AUTH_RESPONSE = 0x1EE,
MSG_GM_SHOWLABEL = 0x1EF,
CMSG_PET_CAST_SPELL = 0x1F0,
MSG_SAVE_GUILD_EMBLEM = 0x1F1,
MSG_TABARDVENDOR_ACTIVATE = 0x1F2,
SMSG_PLAY_SPELL_VISUAL = 0x1F3,
CMSG_ZONEUPDATE = 0x1F4,
SMSG_PARTYKILLLOG = 0x1F5,
SMSG_COMPRESSED_UPDATE_OBJECT = 0x1F6,
SMSG_PLAY_SPELL_IMPACT = 0x1F7,
SMSG_EXPLORATION_EXPERIENCE = 0x1F8,
CMSG_GM_SET_SECURITY_GROUP = 0x1F9,
CMSG_GM_NUKE = 0x1FA,
MSG_RANDOM_ROLL = 0x1FB,
SMSG_ENVIRONMENTALDAMAGELOG = 0x1FC,
CMSG_RWHOIS_OBSOLETE = 0x1FD,
SMSG_RWHOIS = 0x1FE,
MSG_LOOKING_FOR_GROUP = 0x1FF,
CMSG_SET_LOOKING_FOR_GROUP = 0x200,
CMSG_UNLEARN_SPELL = 0x201,
CMSG_UNLEARN_SKILL = 0x202,
SMSG_REMOVED_SPELL = 0x203,
CMSG_DECHARGE = 0x204,
CMSG_GMTICKET_CREATE = 0x205,
SMSG_GMTICKET_CREATE = 0x206,
CMSG_GMTICKET_UPDATETEXT = 0x207,
SMSG_GMTICKET_UPDATETEXT = 0x208,
SMSG_ACCOUNT_DATA_TIMES = 0x209,
CMSG_REQUEST_ACCOUNT_DATA = 0x20A,
CMSG_UPDATE_ACCOUNT_DATA = 0x20B,
SMSG_UPDATE_ACCOUNT_DATA = 0x20C,
SMSG_CLEAR_FAR_SIGHT_IMMEDIATE = 0x20D,
SMSG_POWERGAINLOG_OBSOLETE = 0x20E,
CMSG_GM_TEACH = 0x20F,
CMSG_GM_CREATE_ITEM_TARGET = 0x210,
CMSG_GMTICKET_GETTICKET = 0x211,
SMSG_GMTICKET_GETTICKET = 0x212,
CMSG_UNLEARN_TALENTS = 0x213,
SMSG_GAMEOBJECT_SPAWN_ANIM_OBSOLETE = 0x214,
SMSG_GAMEOBJECT_DESPAWN_ANIM = 0x215,
MSG_CORPSE_QUERY = 0x216,
CMSG_GMTICKET_DELETETICKET = 0x217,
SMSG_GMTICKET_DELETETICKET = 0x218,
SMSG_CHAT_WRONG_FACTION = 0x219,
CMSG_GMTICKET_SYSTEMSTATUS = 0x21A,
SMSG_GMTICKET_SYSTEMSTATUS = 0x21B,
CMSG_SPIRIT_HEALER_ACTIVATE = 0x21C,
CMSG_SET_STAT_CHEAT = 0x21D,
SMSG_SET_REST_START_OBSOLETE = 0x21E,
CMSG_SKILL_BUY_STEP = 0x21F,
CMSG_SKILL_BUY_RANK = 0x220,
CMSG_XP_CHEAT = 0x221,
SMSG_SPIRIT_HEALER_CONFIRM = 0x222,
CMSG_CHARACTER_POINT_CHEAT = 0x223,
SMSG_GOSSIP_POI = 0x224,
CMSG_CHAT_IGNORED = 0x225,
CMSG_GM_VISION = 0x226,
CMSG_SERVER_COMMAND = 0x227,
CMSG_GM_SILENCE = 0x228,
CMSG_GM_REVEALTO = 0x229,
CMSG_GM_RESURRECT = 0x22A,
CMSG_GM_SUMMONMOB = 0x22B,
CMSG_GM_MOVECORPSE = 0x22C,
CMSG_GM_FREEZE = 0x22D,
CMSG_GM_UBERINVIS = 0x22E,
CMSG_GM_REQUEST_PLAYER_INFO = 0x22F,
SMSG_GM_PLAYER_INFO = 0x230,
CMSG_GUILD_RANK = 0x231,
CMSG_GUILD_ADD_RANK = 0x232,
CMSG_GUILD_DEL_RANK = 0x233,
CMSG_GUILD_SET_PUBLIC_NOTE = 0x234,
CMSG_GUILD_SET_OFFICER_NOTE = 0x235,
SMSG_LOGIN_VERIFY_WORLD = 0x236,
CMSG_CLEAR_EXPLORATION = 0x237,
CMSG_SEND_MAIL = 0x238,
SMSG_SEND_MAIL_RESULT = 0x239,
CMSG_GET_MAIL_LIST = 0x23A,
SMSG_MAIL_LIST_RESULT = 0x23B,
CMSG_BATTLEFIELD_LIST = 0x23C,
SMSG_BATTLEFIELD_LIST = 0x23D,
CMSG_BATTLEFIELD_JOIN = 0x23E,
SMSG_BATTLEFIELD_WIN_OBSOLETE = 0x23F,
SMSG_BATTLEFIELD_LOSE_OBSOLETE = 0x240,
CMSG_TAXICLEARNODE = 0x241,
CMSG_TAXIENABLENODE = 0x242,
CMSG_ITEM_TEXT_QUERY = 0x243,
SMSG_ITEM_TEXT_QUERY_RESPONSE = 0x244,
CMSG_MAIL_TAKE_MONEY = 0x245,
CMSG_MAIL_TAKE_ITEM = 0x246,
CMSG_MAIL_MARK_AS_READ = 0x247,
CMSG_MAIL_RETURN_TO_SENDER = 0x248,
CMSG_MAIL_DELETE = 0x249,
CMSG_MAIL_CREATE_TEXT_ITEM = 0x24A,
SMSG_SPELLLOGMISS = 0x24B,
SMSG_SPELLLOGEXECUTE = 0x24C,
SMSG_DEBUGAURAPROC = 0x24D,
SMSG_PERIODICAURALOG = 0x24E,
SMSG_SPELLDAMAGESHIELD = 0x24F,
SMSG_SPELLNONMELEEDAMAGELOG = 0x250,
CMSG_LEARN_TALENT = 0x251,
SMSG_RESURRECT_FAILED = 0x252,
CMSG_TOGGLE_PVP = 0x253,
SMSG_ZONE_UNDER_ATTACK = 0x254,
MSG_AUCTION_HELLO = 0x255,
CMSG_AUCTION_SELL_ITEM = 0x256,
CMSG_AUCTION_REMOVE_ITEM = 0x257,
CMSG_AUCTION_LIST_ITEMS = 0x258,
CMSG_AUCTION_LIST_OWNER_ITEMS = 0x259,
CMSG_AUCTION_PLACE_BID = 0x25A,
SMSG_AUCTION_COMMAND_RESULT = 0x25B,
SMSG_AUCTION_LIST_RESULT = 0x25C,
SMSG_AUCTION_OWNER_LIST_RESULT = 0x25D,
SMSG_AUCTION_BIDDER_NOTIFICATION = 0x25E,
SMSG_AUCTION_OWNER_NOTIFICATION = 0x25F,
SMSG_PROCRESIST = 0x260,
SMSG_STANDSTATE_CHANGE_FAILURE_OBSOLETE = 0x261,
SMSG_DISPEL_FAILED = 0x262,
SMSG_SPELLORDAMAGE_IMMUNE = 0x263,
CMSG_AUCTION_LIST_BIDDER_ITEMS = 0x264,
SMSG_AUCTION_BIDDER_LIST_RESULT = 0x265,
SMSG_SET_FLAT_SPELL_MODIFIER = 0x266,
SMSG_SET_PCT_SPELL_MODIFIER = 0x267,
CMSG_SET_AMMO = 0x268,
SMSG_CORPSE_RECLAIM_DELAY = 0x269,
CMSG_SET_ACTIVE_MOVER = 0x26A,
CMSG_PET_CANCEL_AURA = 0x26B,
CMSG_PLAYER_AI_CHEAT = 0x26C,
CMSG_CANCEL_AUTO_REPEAT_SPELL = 0x26D,
MSG_GM_ACCOUNT_ONLINE = 0x26E,
MSG_LIST_STABLED_PETS = 0x26F,
CMSG_STABLE_PET = 0x270,
CMSG_UNSTABLE_PET = 0x271,
CMSG_BUY_STABLE_SLOT = 0x272,
SMSG_STABLE_RESULT = 0x273,
CMSG_STABLE_REVIVE_PET = 0x274,
CMSG_STABLE_SWAP_PET = 0x275,
MSG_QUEST_PUSH_RESULT = 0x276,
SMSG_PLAY_MUSIC = 0x277,
SMSG_PLAY_OBJECT_SOUND = 0x278,
CMSG_REQUEST_PET_INFO = 0x279,
CMSG_FAR_SIGHT = 0x27A,
SMSG_SPELLDISPELLOG = 0x27B,
SMSG_DAMAGE_CALC_LOG = 0x27C,
CMSG_ENABLE_DAMAGE_LOG = 0x27D,
CMSG_GROUP_CHANGE_SUB_GROUP = 0x27E,
CMSG_REQUEST_PARTY_MEMBER_STATS = 0x27F,
CMSG_GROUP_SWAP_SUB_GROUP = 0x280,
CMSG_RESET_FACTION_CHEAT = 0x281,
CMSG_AUTOSTORE_BANK_ITEM = 0x282,
CMSG_AUTOBANK_ITEM = 0x283,
MSG_QUERY_NEXT_MAIL_TIME = 0x284,
SMSG_RECEIVED_MAIL = 0x285,
SMSG_RAID_GROUP_ONLY = 0x286,
CMSG_SET_DURABILITY_CHEAT = 0x287,
CMSG_SET_PVP_RANK_CHEAT = 0x288,
CMSG_ADD_PVP_MEDAL_CHEAT = 0x289,
CMSG_DEL_PVP_MEDAL_CHEAT = 0x28A,
CMSG_SET_PVP_TITLE = 0x28B,
SMSG_PVP_CREDIT = 0x28C,
SMSG_AUCTION_REMOVED_NOTIFICATION = 0x28D,
CMSG_GROUP_RAID_CONVERT = 0x28E,
CMSG_GROUP_ASSISTANT_LEADER = 0x28F,
CMSG_BUYBACK_ITEM = 0x290,
SMSG_SERVER_MESSAGE = 0x291,
CMSG_SET_SAVED_INSTANCE_EXTEND = 0x292, // lua: SetSavedInstanceExtend
SMSG_MEETINGSTONE_LEAVE = 0x293,
CMSG_MEETINGSTONE_CHEAT = 0x294,
SMSG_MEETINGSTONE_SETQUEUE = 0x295,
CMSG_MEETINGSTONE_INFO = 0x296,
SMSG_MEETINGSTONE_COMPLETE = 0x297,
SMSG_MEETINGSTONE_IN_PROGRESS = 0x298,
SMSG_MEETINGSTONE_MEMBER_ADDED = 0x299,
CMSG_GMTICKETSYSTEM_TOGGLE = 0x29A,
CMSG_CANCEL_GROWTH_AURA = 0x29B,
SMSG_CANCEL_AUTO_REPEAT = 0x29C,
SMSG_STANDSTATE_UPDATE = 0x29D,
SMSG_LOOT_ALL_PASSED = 0x29E,
SMSG_LOOT_ROLL_WON = 0x29F,
CMSG_LOOT_ROLL = 0x2A0,
SMSG_LOOT_START_ROLL = 0x2A1,
SMSG_LOOT_ROLL = 0x2A2,
CMSG_LOOT_MASTER_GIVE = 0x2A3,
SMSG_LOOT_MASTER_LIST = 0x2A4,
SMSG_SET_FORCED_REACTIONS = 0x2A5,
SMSG_SPELL_FAILED_OTHER = 0x2A6,
SMSG_GAMEOBJECT_RESET_STATE = 0x2A7,
CMSG_REPAIR_ITEM = 0x2A8,
SMSG_CHAT_PLAYER_NOT_FOUND = 0x2A9,
MSG_TALENT_WIPE_CONFIRM = 0x2AA,
SMSG_SUMMON_REQUEST = 0x2AB,
CMSG_SUMMON_RESPONSE = 0x2AC,
MSG_MOVE_TOGGLE_GRAVITY_CHEAT = 0x2AD,
SMSG_MONSTER_MOVE_TRANSPORT = 0x2AE,
SMSG_PET_BROKEN = 0x2AF,
MSG_MOVE_FEATHER_FALL = 0x2B0,
MSG_MOVE_WATER_WALK = 0x2B1,
CMSG_SERVER_BROADCAST = 0x2B2,
CMSG_SELF_RES = 0x2B3,
SMSG_FEIGN_DEATH_RESISTED = 0x2B4,
CMSG_RUN_SCRIPT = 0x2B5,
SMSG_SCRIPT_MESSAGE = 0x2B6,
SMSG_DUEL_COUNTDOWN = 0x2B7,
SMSG_AREA_TRIGGER_MESSAGE = 0x2B8,
CMSG_SHOWING_HELM = 0x2B9,
CMSG_SHOWING_CLOAK = 0x2BA,
SMSG_MEETINGSTONE_JOINFAILED = 0x2BB,
SMSG_PLAYER_SKINNED = 0x2BC,
SMSG_DURABILITY_DAMAGE_DEATH = 0x2BD,
CMSG_SET_EXPLORATION = 0x2BE,
CMSG_SET_ACTIONBAR_TOGGLES = 0x2BF,
UMSG_DELETE_GUILD_CHARTER = 0x2C0,
MSG_PETITION_RENAME = 0x2C1,
SMSG_INIT_WORLD_STATES = 0x2C2,
SMSG_UPDATE_WORLD_STATE = 0x2C3,
CMSG_ITEM_NAME_QUERY = 0x2C4,
SMSG_ITEM_NAME_QUERY_RESPONSE = 0x2C5,
SMSG_PET_ACTION_FEEDBACK = 0x2C6,
CMSG_CHAR_RENAME = 0x2C7,
SMSG_CHAR_RENAME = 0x2C8,
CMSG_MOVE_SPLINE_DONE = 0x2C9,
CMSG_MOVE_FALL_RESET = 0x2CA,
SMSG_INSTANCE_SAVE_CREATED = 0x2CB,
SMSG_RAID_INSTANCE_INFO = 0x2CC,
CMSG_REQUEST_RAID_INFO = 0x2CD,
CMSG_MOVE_TIME_SKIPPED = 0x2CE,
CMSG_MOVE_FEATHER_FALL_ACK = 0x2CF,
CMSG_MOVE_WATER_WALK_ACK = 0x2D0,
CMSG_MOVE_NOT_ACTIVE_MOVER = 0x2D1,
SMSG_PLAY_SOUND = 0x2D2,
CMSG_BATTLEFIELD_STATUS = 0x2D3,
SMSG_BATTLEFIELD_STATUS = 0x2D4,
CMSG_BATTLEFIELD_PORT = 0x2D5,
MSG_INSPECT_HONOR_STATS = 0x2D6,
CMSG_BATTLEMASTER_HELLO = 0x2D7,
CMSG_MOVE_START_SWIM_CHEAT = 0x2D8,
CMSG_MOVE_STOP_SWIM_CHEAT = 0x2D9,
SMSG_FORCE_WALK_SPEED_CHANGE = 0x2DA,
CMSG_FORCE_WALK_SPEED_CHANGE_ACK = 0x2DB,
SMSG_FORCE_SWIM_BACK_SPEED_CHANGE = 0x2DC,
CMSG_FORCE_SWIM_BACK_SPEED_CHANGE_ACK = 0x2DD,
SMSG_FORCE_TURN_RATE_CHANGE = 0x2DE,
CMSG_FORCE_TURN_RATE_CHANGE_ACK = 0x2DF,
MSG_PVP_LOG_DATA = 0x2E0,
CMSG_LEAVE_BATTLEFIELD = 0x2E1,
CMSG_AREA_SPIRIT_HEALER_QUERY = 0x2E2,
CMSG_AREA_SPIRIT_HEALER_QUEUE = 0x2E3,
SMSG_AREA_SPIRIT_HEALER_TIME = 0x2E4,
CMSG_GM_UNTEACH = 0x2E5,
SMSG_WARDEN_DATA = 0x2E6,
CMSG_WARDEN_DATA = 0x2E7,
SMSG_GROUP_JOINED_BATTLEGROUND = 0x2E8,
MSG_BATTLEGROUND_PLAYER_POSITIONS = 0x2E9,
CMSG_PET_STOP_ATTACK = 0x2EA,
SMSG_BINDER_CONFIRM = 0x2EB,
SMSG_BATTLEGROUND_PLAYER_JOINED = 0x2EC,
SMSG_BATTLEGROUND_PLAYER_LEFT = 0x2ED,
CMSG_BATTLEMASTER_JOIN = 0x2EE,
SMSG_ADDON_INFO = 0x2EF,
CMSG_PET_UNLEARN = 0x2F0,
SMSG_PET_UNLEARN_CONFIRM = 0x2F1,
SMSG_PARTY_MEMBER_STATS_FULL = 0x2F2,
CMSG_PET_SPELL_AUTOCAST = 0x2F3,
SMSG_WEATHER = 0x2F4,
SMSG_PLAY_TIME_WARNING = 0x2F5,
SMSG_MINIGAME_SETUP = 0x2F6,
SMSG_MINIGAME_STATE = 0x2F7,
CMSG_MINIGAME_MOVE = 0x2F8,
SMSG_MINIGAME_MOVE_FAILED = 0x2F9,
SMSG_RAID_INSTANCE_MESSAGE = 0x2FA,
SMSG_COMPRESSED_MOVES = 0x2FB,
CMSG_GUILD_INFO_TEXT = 0x2FC,
SMSG_CHAT_RESTRICTED = 0x2FD,
SMSG_SPLINE_SET_RUN_SPEED = 0x2FE,
SMSG_SPLINE_SET_RUN_BACK_SPEED = 0x2FF,
SMSG_SPLINE_SET_SWIM_SPEED = 0x300,
SMSG_SPLINE_SET_WALK_SPEED = 0x301,
SMSG_SPLINE_SET_SWIM_BACK_SPEED = 0x302,
SMSG_SPLINE_SET_TURN_RATE = 0x303,
SMSG_SPLINE_MOVE_UNROOT = 0x304,
SMSG_SPLINE_MOVE_FEATHER_FALL = 0x305,
SMSG_SPLINE_MOVE_NORMAL_FALL = 0x306,
SMSG_SPLINE_MOVE_SET_HOVER = 0x307,
SMSG_SPLINE_MOVE_UNSET_HOVER = 0x308,
SMSG_SPLINE_MOVE_WATER_WALK = 0x309,
SMSG_SPLINE_MOVE_LAND_WALK = 0x30A,
SMSG_SPLINE_MOVE_START_SWIM = 0x30B,
SMSG_SPLINE_MOVE_STOP_SWIM = 0x30C,
SMSG_SPLINE_MOVE_SET_RUN_MODE = 0x30D,
SMSG_SPLINE_MOVE_SET_WALK_MODE = 0x30E,
CMSG_GM_NUKE_ACCOUNT = 0x30F,
MSG_GM_DESTROY_CORPSE = 0x310,
CMSG_GM_DESTROY_ONLINE_CORPSE = 0x311,
CMSG_ACTIVATETAXIEXPRESS = 0x312,
SMSG_SET_FACTION_ATWAR = 0x313,
SMSG_GAMETIMEBIAS_SET = 0x314,
CMSG_DEBUG_ACTIONS_START = 0x315,
CMSG_DEBUG_ACTIONS_STOP = 0x316,
CMSG_SET_FACTION_INACTIVE = 0x317,
CMSG_SET_WATCHED_FACTION = 0x318,
MSG_MOVE_TIME_SKIPPED = 0x319,
SMSG_SPLINE_MOVE_ROOT = 0x31A,
CMSG_SET_EXPLORATION_ALL = 0x31B,
SMSG_INVALIDATE_PLAYER = 0x31C,
CMSG_RESET_INSTANCES = 0x31D,
SMSG_INSTANCE_RESET = 0x31E,
SMSG_INSTANCE_RESET_FAILED = 0x31F,
SMSG_UPDATE_LAST_INSTANCE = 0x320,
MSG_RAID_TARGET_UPDATE = 0x321,
MSG_RAID_READY_CHECK = 0x322,
CMSG_LUA_USAGE = 0x323,
SMSG_PET_ACTION_SOUND = 0x324,
SMSG_PET_DISMISS_SOUND = 0x325,
SMSG_GHOSTEE_GONE = 0x326,
CMSG_GM_UPDATE_TICKET_STATUS = 0x327,
SMSG_GM_TICKET_STATUS_UPDATE = 0x328,
MSG_SET_DUNGEON_DIFFICULTY = 0x329,
CMSG_GMSURVEY_SUBMIT = 0x32A,
SMSG_UPDATE_INSTANCE_OWNERSHIP = 0x32B,
CMSG_IGNORE_KNOCKBACK_CHEAT = 0x32C,
SMSG_CHAT_PLAYER_AMBIGUOUS = 0x32D,
MSG_DELAY_GHOST_TELEPORT = 0x32E,
SMSG_SPELLINSTAKILLLOG = 0x32F,
SMSG_SPELL_UPDATE_CHAIN_TARGETS = 0x330,
CMSG_CHAT_FILTERED = 0x331,
SMSG_EXPECTED_SPAM_RECORDS = 0x332,
SMSG_SPELLSTEALLOG = 0x333,
CMSG_LOTTERY_QUERY_OBSOLETE = 0x334,
SMSG_LOTTERY_QUERY_RESULT_OBSOLETE = 0x335,
CMSG_BUY_LOTTERY_TICKET_OBSOLETE = 0x336,
SMSG_LOTTERY_RESULT_OBSOLETE = 0x337,
SMSG_CHARACTER_PROFILE = 0x338,
SMSG_CHARACTER_PROFILE_REALM_CONNECTED = 0x339,
SMSG_DEFENSE_MESSAGE = 0x33A,
SMSG_INSTANCE_DIFFICULTY = 0x33B,
MSG_GM_RESETINSTANCELIMIT = 0x33C,
SMSG_MOTD = 0x33D,
SMSG_MOVE_SET_FLIGHT_OBSOLETE = 0x33E,
SMSG_MOVE_UNSET_FLIGHT_OBSOLETE = 0x33F,
CMSG_MOVE_FLIGHT_ACK_OBSOLETE = 0x340,
MSG_MOVE_START_SWIM_CHEAT = 0x341,
MSG_MOVE_STOP_SWIM_CHEAT = 0x342,
SMSG_MOVE_SET_CAN_FLY = 0x343,
SMSG_MOVE_UNSET_CAN_FLY = 0x344,
CMSG_MOVE_SET_CAN_FLY_ACK = 0x345,
CMSG_MOVE_SET_FLY = 0x346,
CMSG_SOCKET_GEMS = 0x347,
CMSG_ARENA_TEAM_CREATE = 0x348,
SMSG_ARENA_TEAM_COMMAND_RESULT = 0x349,
UMSG_UPDATE_ARENA_TEAM_OBSOLETE = 0x34A,
CMSG_ARENA_TEAM_QUERY = 0x34B,
SMSG_ARENA_TEAM_QUERY_RESPONSE = 0x34C,
CMSG_ARENA_TEAM_ROSTER = 0x34D,
SMSG_ARENA_TEAM_ROSTER = 0x34E,
CMSG_ARENA_TEAM_INVITE = 0x34F,
SMSG_ARENA_TEAM_INVITE = 0x350,
CMSG_ARENA_TEAM_ACCEPT = 0x351,
CMSG_ARENA_TEAM_DECLINE = 0x352,
CMSG_ARENA_TEAM_LEAVE = 0x353,
CMSG_ARENA_TEAM_REMOVE = 0x354,
CMSG_ARENA_TEAM_DISBAND = 0x355,
CMSG_ARENA_TEAM_LEADER = 0x356,
SMSG_ARENA_TEAM_EVENT = 0x357,
CMSG_BATTLEMASTER_JOIN_ARENA = 0x358,
MSG_MOVE_START_ASCEND = 0x359,
MSG_MOVE_STOP_ASCEND = 0x35A,
SMSG_ARENA_TEAM_STATS = 0x35B,
CMSG_LFG_SET_AUTOJOIN = 0x35C,
CMSG_LFG_CLEAR_AUTOJOIN = 0x35D,
CMSG_LFM_SET_AUTOFILL = 0x35E,
CMSG_LFM_CLEAR_AUTOFILL = 0x35F,
CMSG_ACCEPT_LFG_MATCH = 0x360,
CMSG_DECLINE_LFG_MATCH = 0x361,
CMSG_CANCEL_PENDING_LFG = 0x362,
CMSG_CLEAR_LOOKING_FOR_GROUP = 0x363,
CMSG_CLEAR_LOOKING_FOR_MORE = 0x364,
CMSG_SET_LOOKING_FOR_MORE = 0x365,
CMSG_SET_LFG_COMMENT = 0x366,
SMSG_LFG_TIMEDOUT = 0x367,
SMSG_LFG_OTHER_TIMEDOUT = 0x368,
SMSG_LFG_AUTOJOIN_FAILED = 0x369,
SMSG_LFG_AUTOJOIN_FAILED_NO_PLAYER = 0x36A,
SMSG_LFG_LEADER_IS_LFM = 0x36B,
SMSG_LFG_UPDATE = 0x36C,
SMSG_LFG_UPDATE_LFM = 0x36D,
SMSG_LFG_UPDATE_LFG = 0x36E,
SMSG_LFG_UPDATE_QUEUED = 0x36F,
SMSG_LFG_PENDING_INVITE = 0x370,
SMSG_LFG_PENDING_MATCH = 0x371,
SMSG_LFG_PENDING_MATCH_DONE = 0x372,
SMSG_TITLE_EARNED = 0x373,
CMSG_SET_TITLE = 0x374,
CMSG_CANCEL_MOUNT_AURA = 0x375,
SMSG_ARENA_ERROR = 0x376,
MSG_INSPECT_ARENA_TEAMS = 0x377,
SMSG_DEATH_RELEASE_LOC = 0x378,
CMSG_CANCEL_TEMP_ENCHANTMENT = 0x379,
SMSG_FORCED_DEATH_UPDATE = 0x37A,
CMSG_CHEAT_SET_HONOR_CURRENCY = 0x37B,
CMSG_CHEAT_SET_ARENA_CURRENCY = 0x37C,
MSG_MOVE_SET_FLIGHT_SPEED_CHEAT = 0x37D,
MSG_MOVE_SET_FLIGHT_SPEED = 0x37E,
MSG_MOVE_SET_FLIGHT_BACK_SPEED_CHEAT = 0x37F,
MSG_MOVE_SET_FLIGHT_BACK_SPEED = 0x380,
SMSG_FORCE_FLIGHT_SPEED_CHANGE = 0x381,
CMSG_FORCE_FLIGHT_SPEED_CHANGE_ACK = 0x382,
SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE = 0x383,
CMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE_ACK = 0x384,
SMSG_SPLINE_SET_FLIGHT_SPEED = 0x385,
SMSG_SPLINE_SET_FLIGHT_BACK_SPEED = 0x386,
CMSG_MAELSTROM_INVALIDATE_CACHE = 0x387,
SMSG_FLIGHT_SPLINE_SYNC = 0x388,
CMSG_SET_TAXI_BENCHMARK_MODE = 0x389,
SMSG_JOINED_BATTLEGROUND_QUEUE = 0x38A,
SMSG_REALM_SPLIT = 0x38B,
CMSG_REALM_SPLIT = 0x38C,
CMSG_MOVE_CHNG_TRANSPORT = 0x38D,
MSG_PARTY_ASSIGNMENT = 0x38E,
SMSG_OFFER_PETITION_ERROR = 0x38F,
SMSG_TIME_SYNC_REQ = 0x390,
CMSG_TIME_SYNC_RESP = 0x391,
CMSG_SEND_LOCAL_EVENT = 0x392,
CMSG_SEND_GENERAL_TRIGGER = 0x393,
CMSG_SEND_COMBAT_TRIGGER = 0x394,
CMSG_MAELSTROM_GM_SENT_MAIL = 0x395,
SMSG_RESET_FAILED_NOTIFY = 0x396,
SMSG_REAL_GROUP_UPDATE = 0x397,
SMSG_LFG_DISABLED = 0x398,
CMSG_ACTIVE_PVP_CHEAT = 0x399,
CMSG_CHEAT_DUMP_ITEMS_DEBUG_ONLY = 0x39A,
SMSG_CHEAT_DUMP_ITEMS_DEBUG_ONLY_RESPONSE = 0x39B,
SMSG_CHEAT_DUMP_ITEMS_DEBUG_ONLY_RESPONSE_WRITE_FILE = 0x39C,
SMSG_UPDATE_COMBO_POINTS = 0x39D,
SMSG_VOICE_SESSION_ROSTER_UPDATE = 0x39E,
SMSG_VOICE_SESSION_LEAVE = 0x39F,
SMSG_VOICE_SESSION_ADJUST_PRIORITY = 0x3A0,
CMSG_VOICE_SET_TALKER_MUTED_REQUEST = 0x3A1,
SMSG_VOICE_SET_TALKER_MUTED = 0x3A2,
SMSG_INIT_EXTRA_AURA_INFO_OBSOLETE = 0x3A3,
SMSG_SET_EXTRA_AURA_INFO_OBSOLETE = 0x3A4,
SMSG_SET_EXTRA_AURA_INFO_NEED_UPDATE_OBSOLETE = 0x3A5,
SMSG_CLEAR_EXTRA_AURA_INFO_OBSOLETE = 0x3A6,
MSG_MOVE_START_DESCEND = 0x3A7,
CMSG_IGNORE_REQUIREMENTS_CHEAT = 0x3A8,
SMSG_IGNORE_REQUIREMENTS_CHEAT = 0x3A9,
SMSG_SPELL_CHANCE_PROC_LOG = 0x3AA,
CMSG_MOVE_SET_RUN_SPEED = 0x3AB,
SMSG_DISMOUNT = 0x3AC,
MSG_MOVE_UPDATE_CAN_FLY = 0x3AD,
MSG_RAID_READY_CHECK_CONFIRM = 0x3AE,
CMSG_VOICE_SESSION_ENABLE = 0x3AF,
SMSG_VOICE_SESSION_ENABLE = 0x3B0,
SMSG_VOICE_PARENTAL_CONTROLS = 0x3B1,
CMSG_GM_WHISPER = 0x3B2,
SMSG_GM_MESSAGECHAT = 0x3B3,
MSG_GM_GEARRATING = 0x3B4,
CMSG_COMMENTATOR_ENABLE = 0x3B5,
SMSG_COMMENTATOR_STATE_CHANGED = 0x3B6,
CMSG_COMMENTATOR_GET_MAP_INFO = 0x3B7,
SMSG_COMMENTATOR_MAP_INFO = 0x3B8,
CMSG_COMMENTATOR_GET_PLAYER_INFO = 0x3B9,
SMSG_COMMENTATOR_GET_PLAYER_INFO = 0x3BA,
SMSG_COMMENTATOR_PLAYER_INFO = 0x3BB,
CMSG_COMMENTATOR_ENTER_INSTANCE = 0x3BC,
CMSG_COMMENTATOR_EXIT_INSTANCE = 0x3BD,
CMSG_COMMENTATOR_INSTANCE_COMMAND = 0x3BE,
SMSG_CLEAR_TARGET = 0x3BF,
CMSG_BOT_DETECTED = 0x3C0,
SMSG_CROSSED_INEBRIATION_THRESHOLD = 0x3C1,
CMSG_CHEAT_PLAYER_LOGIN = 0x3C2,
CMSG_CHEAT_PLAYER_LOOKUP = 0x3C3,
SMSG_CHEAT_PLAYER_LOOKUP = 0x3C4,
SMSG_KICK_REASON = 0x3C5,
MSG_RAID_READY_CHECK_FINISHED = 0x3C6,
CMSG_COMPLAIN = 0x3C7,
SMSG_COMPLAIN_RESULT = 0x3C8,
SMSG_FEATURE_SYSTEM_STATUS = 0x3C9,
CMSG_GM_SHOW_COMPLAINTS = 0x3CA,
CMSG_GM_UNSQUELCH = 0x3CB,
CMSG_CHANNEL_SILENCE_VOICE = 0x3CC,
CMSG_CHANNEL_SILENCE_ALL = 0x3CD,
CMSG_CHANNEL_UNSILENCE_VOICE = 0x3CE,
CMSG_CHANNEL_UNSILENCE_ALL = 0x3CF,
CMSG_TARGET_CAST = 0x3D0,
CMSG_TARGET_SCRIPT_CAST = 0x3D1,
CMSG_CHANNEL_DISPLAY_LIST = 0x3D2,
CMSG_SET_ACTIVE_VOICE_CHANNEL = 0x3D3,
CMSG_GET_CHANNEL_MEMBER_COUNT = 0x3D4,
SMSG_CHANNEL_MEMBER_COUNT = 0x3D5,
CMSG_CHANNEL_VOICE_ON = 0x3D6,
CMSG_CHANNEL_VOICE_OFF = 0x3D7,
CMSG_DEBUG_LIST_TARGETS = 0x3D8,
SMSG_DEBUG_LIST_TARGETS = 0x3D9,
SMSG_AVAILABLE_VOICE_CHANNEL = 0x3DA,
CMSG_ADD_VOICE_IGNORE = 0x3DB,
CMSG_DEL_VOICE_IGNORE = 0x3DC,
CMSG_PARTY_SILENCE = 0x3DD,
CMSG_PARTY_UNSILENCE = 0x3DE,
MSG_NOTIFY_PARTY_SQUELCH = 0x3DF,
SMSG_COMSAT_RECONNECT_TRY = 0x3E0,
SMSG_COMSAT_DISCONNECT = 0x3E1,
SMSG_COMSAT_CONNECT_FAIL = 0x3E2,
SMSG_VOICE_CHAT_STATUS = 0x3E3,
CMSG_REPORT_PVP_AFK = 0x3E4,
SMSG_REPORT_PVP_AFK_RESULT = 0x3E5, // SMSG?
CMSG_GUILD_BANKER_ACTIVATE = 0x3E6,
CMSG_GUILD_BANK_QUERY_TAB = 0x3E7,
SMSG_GUILD_BANK_LIST = 0x3E8,
CMSG_GUILD_BANK_SWAP_ITEMS = 0x3E9,
CMSG_GUILD_BANK_BUY_TAB = 0x3EA,
CMSG_GUILD_BANK_UPDATE_TAB = 0x3EB,
CMSG_GUILD_BANK_DEPOSIT_MONEY = 0x3EC,
CMSG_GUILD_BANK_WITHDRAW_MONEY = 0x3ED,
MSG_GUILD_BANK_LOG_QUERY = 0x3EE,
CMSG_SET_CHANNEL_WATCH = 0x3EF,
SMSG_USERLIST_ADD = 0x3F0,
SMSG_USERLIST_REMOVE = 0x3F1,
SMSG_USERLIST_UPDATE = 0x3F2,
CMSG_CLEAR_CHANNEL_WATCH = 0x3F3,
SMSG_INSPECT_TALENT = 0x3F4,
SMSG_GOGOGO_OBSOLETE = 0x3F5,
SMSG_ECHO_PARTY_SQUELCH = 0x3F6,
CMSG_SET_TITLE_SUFFIX = 0x3F7,
CMSG_SPELLCLICK = 0x3F8,
SMSG_LOOT_LIST = 0x3F9,
CMSG_GM_CHARACTER_RESTORE = 0x3FA,
CMSG_GM_CHARACTER_SAVE = 0x3FB,
SMSG_VOICESESSION_FULL = 0x3FC,
MSG_GUILD_PERMISSIONS = 0x3FD,
MSG_GUILD_BANK_MONEY_WITHDRAWN = 0x3FE,
MSG_GUILD_EVENT_LOG_QUERY = 0x3FF,
CMSG_MAELSTROM_RENAME_GUILD = 0x400,
CMSG_GET_MIRRORIMAGE_DATA = 0x401,
SMSG_MIRRORIMAGE_DATA = 0x402,
SMSG_FORCE_DISPLAY_UPDATE = 0x403,
SMSG_SPELL_CHANCE_RESIST_PUSHBACK = 0x404,
CMSG_IGNORE_DIMINISHING_RETURNS_CHEAT = 0x405,
SMSG_IGNORE_DIMINISHING_RETURNS_CHEAT = 0x406,
CMSG_KEEP_ALIVE = 0x407,
SMSG_RAID_READY_CHECK_ERROR = 0x408,
CMSG_OPT_OUT_OF_LOOT = 0x409,
MSG_QUERY_GUILD_BANK_TEXT = 0x40A,
CMSG_SET_GUILD_BANK_TEXT = 0x40B,
CMSG_SET_GRANTABLE_LEVELS = 0x40C,
CMSG_GRANT_LEVEL = 0x40D,
CMSG_REFER_A_FRIEND = 0x40E,
MSG_GM_CHANGE_ARENA_RATING = 0x40F,
CMSG_DECLINE_CHANNEL_INVITE = 0x410,
SMSG_GROUPACTION_THROTTLED = 0x411, // SMSG?
SMSG_OVERRIDE_LIGHT = 0x412,
SMSG_TOTEM_CREATED = 0x413,
CMSG_TOTEM_DESTROYED = 0x414,
CMSG_EXPIRE_RAID_INSTANCE = 0x415,
CMSG_NO_SPELL_VARIANCE = 0x416,
CMSG_QUESTGIVER_STATUS_MULTIPLE_QUERY = 0x417,
SMSG_QUESTGIVER_STATUS_MULTIPLE = 0x418,
CMSG_SET_PLAYER_DECLINED_NAMES = 0x419,
SMSG_SET_PLAYER_DECLINED_NAMES_RESULT = 0x41A,
CMSG_QUERY_SERVER_BUCK_DATA = 0x41B,
CMSG_CLEAR_SERVER_BUCK_DATA = 0x41C,
SMSG_SERVER_BUCK_DATA = 0x41D,
SMSG_SEND_UNLEARN_SPELLS = 0x41E,
SMSG_PROPOSE_LEVEL_GRANT = 0x41F,
CMSG_ACCEPT_LEVEL_GRANT = 0x420,
SMSG_REFER_A_FRIEND_FAILURE = 0x421,
SMSG_SPLINE_MOVE_SET_FLYING = 0x422,
SMSG_SPLINE_MOVE_UNSET_FLYING = 0x423,
SMSG_SUMMON_CANCEL = 0x424,
CMSG_CHANGE_PERSONAL_ARENA_RATING = 0x425,
CMSG_ALTER_APPEARANCE = 0x426,
SMSG_ENABLE_BARBER_SHOP = 0x427,
SMSG_BARBER_SHOP_RESULT = 0x428,
CMSG_CALENDAR_GET_CALENDAR = 0x429,
CMSG_CALENDAR_GET_EVENT = 0x42A,
CMSG_CALENDAR_GUILD_FILTER = 0x42B,
CMSG_CALENDAR_ARENA_TEAM = 0x42C,
CMSG_CALENDAR_ADD_EVENT = 0x42D,
CMSG_CALENDAR_UPDATE_EVENT = 0x42E,
CMSG_CALENDAR_REMOVE_EVENT = 0x42F,
CMSG_CALENDAR_COPY_EVENT = 0x430,
CMSG_CALENDAR_EVENT_INVITE = 0x431,
CMSG_CALENDAR_EVENT_RSVP = 0x432,
CMSG_CALENDAR_EVENT_REMOVE_INVITE = 0x433,
CMSG_CALENDAR_EVENT_STATUS = 0x434,
CMSG_CALENDAR_EVENT_MODERATOR_STATUS = 0x435,
SMSG_CALENDAR_SEND_CALENDAR = 0x436,
SMSG_CALENDAR_SEND_EVENT = 0x437,
SMSG_CALENDAR_FILTER_GUILD = 0x438,
SMSG_CALENDAR_ARENA_TEAM = 0x439,
SMSG_CALENDAR_EVENT_INVITE = 0x43A,
SMSG_CALENDAR_EVENT_INVITE_REMOVED = 0x43B,
SMSG_CALENDAR_EVENT_STATUS = 0x43C,
SMSG_CALENDAR_COMMAND_RESULT = 0x43D,
SMSG_CALENDAR_RAID_LOCKOUT_ADDED = 0x43E,
SMSG_CALENDAR_RAID_LOCKOUT_REMOVED = 0x43F,
SMSG_CALENDAR_EVENT_INVITE_ALERT = 0x440,
SMSG_CALENDAR_EVENT_INVITE_REMOVED_ALERT = 0x441,
SMSG_CALENDAR_EVENT_INVITE_STATUS_ALERT = 0x442,
SMSG_CALENDAR_EVENT_REMOVED_ALERT = 0x443,
SMSG_CALENDAR_EVENT_UPDATED_ALERT = 0x444,
SMSG_CALENDAR_EVENT_MODERATOR_STATUS_ALERT = 0x445,
CMSG_CALENDAR_COMPLAIN = 0x446,
CMSG_CALENDAR_GET_NUM_PENDING = 0x447,
SMSG_CALENDAR_SEND_NUM_PENDING = 0x448,
CMSG_SAVE_DANCE = 0x449,
SMSG_NOTIFY_DANCE = 0x44A,
CMSG_PLAY_DANCE = 0x44B,
SMSG_PLAY_DANCE = 0x44C,
CMSG_LOAD_DANCES = 0x44D,
CMSG_STOP_DANCE = 0x44E,
SMSG_STOP_DANCE = 0x44F,
CMSG_SYNC_DANCE = 0x450,
CMSG_DANCE_QUERY = 0x451,
SMSG_DANCE_QUERY_RESPONSE = 0x452,
SMSG_INVALIDATE_DANCE = 0x453,
CMSG_DELETE_DANCE = 0x454,
SMSG_LEARNED_DANCE_MOVES = 0x455,
CMSG_LEARN_DANCE_MOVE = 0x456,
CMSG_UNLEARN_DANCE_MOVE = 0x457,
CMSG_SET_RUNE_COUNT = 0x458,
CMSG_SET_RUNE_COOLDOWN = 0x459,
MSG_MOVE_SET_PITCH_RATE_CHEAT = 0x45A,
MSG_MOVE_SET_PITCH_RATE = 0x45B,
SMSG_FORCE_PITCH_RATE_CHANGE = 0x45C,
CMSG_FORCE_PITCH_RATE_CHANGE_ACK = 0x45D,
SMSG_SPLINE_SET_PITCH_RATE = 0x45E,
SMSG_MOVE_ABANDON_TRANSPORT = 0x45F,
MSG_MOVE_ABANDON_TRANSPORT = 0x460,
CMSG_MOVE_ABANDON_TRANSPORT_ACK = 0x461,
CMSG_UPDATE_MISSILE_TRAJECTORY = 0x462,
SMSG_UPDATE_ACCOUNT_DATA_COMPLETE = 0x463,
SMSG_TRIGGER_MOVIE = 0x464,
CMSG_COMPLETE_MOVIE = 0x465,
CMSG_SET_GLYPH_SLOT = 0x466,
CMSG_SET_GLYPH = 0x467,
SMSG_ACHIEVEMENT_EARNED = 0x468,
SMSG_DYNAMIC_DROP_ROLL_RESULT = 0x469,
SMSG_CRITERIA_UPDATE = 0x46A,
CMSG_QUERY_INSPECT_ACHIEVEMENTS = 0x46B,
SMSG_RESPOND_INSPECT_ACHIEVEMENTS = 0x46C,
CMSG_DISMISS_CONTROLLED_VEHICLE = 0x46D,
CMSG_COMPLETE_ACHIEVEMENT_CHEAT = 0x46E,
SMSG_QUESTUPDATE_ADD_PVP_KILL = 0x46F,
CMSG_SET_CRITERIA_CHEAT = 0x470,
SMSG_GROUP_SWAP_FAILED = 0x471,
CMSG_UNITANIMTIER_CHEAT = 0x472,
CMSG_CHAR_CUSTOMIZE = 0x473,
SMSG_CHAR_CUSTOMIZE = 0x474,
SMSG_PET_RENAMEABLE = 0x475,
CMSG_REQUEST_VEHICLE_EXIT = 0x476,
CMSG_REQUEST_VEHICLE_PREV_SEAT = 0x477,
CMSG_REQUEST_VEHICLE_NEXT_SEAT = 0x478,
CMSG_REQUEST_VEHICLE_SWITCH_SEAT = 0x479,
CMSG_PET_LEARN_TALENT = 0x47A,
CMSG_PET_UNLEARN_TALENTS = 0x47B,
SMSG_SET_PHASE_SHIFT = 0x47C,
SMSG_ALL_ACHIEVEMENT_DATA = 0x47D,
CMSG_FORCE_SAY_CHEAT = 0x47E,
SMSG_HEALTH_UPDATE = 0x47F,
SMSG_POWER_UPDATE = 0x480,
CMSG_GAMEOBJ_REPORT_USE = 0x481,
SMSG_HIGHEST_THREAT_UPDATE = 0x482,
SMSG_THREAT_UPDATE = 0x483,
SMSG_THREAT_REMOVE = 0x484,
SMSG_THREAT_CLEAR = 0x485,
SMSG_CONVERT_RUNE = 0x486,
SMSG_RESYNC_RUNES = 0x487,
SMSG_ADD_RUNE_POWER = 0x488,
CMSG_START_QUEST = 0x489,
CMSG_REMOVE_GLYPH = 0x48A,
CMSG_DUMP_OBJECTS = 0x48B,
SMSG_DUMP_OBJECTS_DATA = 0x48C,
CMSG_DISMISS_CRITTER = 0x48D,
SMSG_NOTIFY_DEST_LOC_SPELL_CAST = 0x48E,
CMSG_AUCTION_LIST_PENDING_SALES = 0x48F,
SMSG_AUCTION_LIST_PENDING_SALES = 0x490,
SMSG_MODIFY_COOLDOWN = 0x491,
SMSG_PET_UPDATE_COMBO_POINTS = 0x492,
CMSG_ENABLETAXI = 0x493,
SMSG_PRE_RESURRECT = 0x494,
SMSG_AURA_UPDATE_ALL = 0x495,
SMSG_AURA_UPDATE = 0x496,
CMSG_FLOOD_GRACE_CHEAT = 0x497,
SMSG_SERVER_FIRST_ACHIEVEMENT = 0x498,
SMSG_PET_LEARNED_SPELL = 0x499,
SMSG_PET_REMOVED_SPELL = 0x49A,
CMSG_CHANGE_SEATS_ON_CONTROLLED_VEHICLE = 0x49B,
CMSG_HEARTH_AND_RESURRECT = 0x49C, // not changed in 3.1
SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA = 0x49D, // not changed 9626
SMSG_CRITERIA_DELETED = 0x49E, // not changed 9626
SMSG_ACHIEVEMENT_DELETED = 0x49F, // not changed 9626
CMSG_SERVER_INFO_QUERY = 0x4A0, // not found
SMSG_SERVER_INFO_RESPONSE = 0x4A1, // not found
CMSG_CHECK_LOGIN_CRITERIA = 0x4A2, // not found
SMSG_SERVER_BUCK_DATA_START = 0x4A3, // not found
CMSG_QUERY_VEHICLE_STATUS = 0x4A4, // not found
UMSG_UNKNOWN_1189 = 0x4A5, // not found, old SMSG_PET_GUIDS
SMSG_UNKNOWN_1190 = 0x4A6, // smsg unk, "You can't do that yet"
SMSG_UNKNOWN_1191 = 0x4A7, // smsg guid+uint32 (vehicle)
CMSG_UNKNOWN_1192 = 0x4A8, // cmsg uint64
CMSG_EJECT_PASSENGER = 0x4A9, // cmsg uint64
SMSG_PET_GUIDS = 0x4AA, // shifted+5
SMSG_CLIENTCACHE_VERSION = 0x4AB, // shifted+5
UMSG_UNKNOWN_1196 = 0x4AC, // not found
UMSG_UNKNOWN_1197 = 0x4AD, // not found
UMSG_UNKNOWN_1198 = 0x4AE, // not found
UMSG_UNKNOWN_1199 = 0x4AF, // not found
UMSG_UNKNOWN_1200 = 0x4B0, // not found
UMSG_UNKNOWN_1201 = 0x4B1, // not found
SMSG_UNKNOWN_1202 = 0x4B2, // refund something
CMSG_ITEM_REFUND_INFO_REQUEST = 0x4B3, // refund request?
CMSG_UNKNOWN_1204 = 0x4B4, // lua: ContainerRefundItemPurchase
SMSG_UNKNOWN_1205 = 0x4B5, // refund something
CMSG_CORPSE_MAP_POSITION_QUERY = 0x4B6, // CMSG, uint32
CMSG_CORPSE_MAP_POSITION_QUERY_RESPONSE = 0x4B7, // SMSG, 3*float+float
CMSG_LFG_SET_ROLES = 0x4B8, // CMSG, empty, lua: SetLFGRoles
UMSG_UNKNOWN_1209 = 0x4B9, // not found
CMSG_UNKNOWN_1210 = 0x4BA, // CMSG, uint64, lua: CalendarContextEventSignUp
SMSG_UNKNOWN_1211 = 0x4BB, // SMSG, calendar related
SMSG_EQUIPMENT_SET_LIST = 0x4BC, // SMSG, equipment manager list?
CMSG_EQUIPMENT_SET_SAVE = 0x4BD, // CMSG, lua: SaveEquipmentSet
CMSG_UNKNOWN_1214 = 0x4BE, // CMSG, missle?
SMSG_UNKNOWN_1215 = 0x4BF, // SMSG, uint64, uint8, 3 x float
SMSG_TALENTS_INFO = 0x4C0, // SMSG, talents related
CMSG_LEARN_PREVIEW_TALENTS = 0x4C1, // CMSG, lua: LearnPreviewTalents (for player?)
CMSG_LEARN_PREVIEW_TALENTS_PET = 0x4C2, // CMSG, lua: LearnPreviewTalents (for pet?)
UMSG_UNKNOWN_1219 = 0x4C3, // not found 3.2
UMSG_UNKNOWN_1220 = 0x4C4, // not found 3.2
UMSG_UNKNOWN_1221 = 0x4C5, // not found 3.2
UMSG_UNKNOWN_1222 = 0x4C6, // not found 3.2
SMSG_UNKNOWN_1223 = 0x4C7, // uint64, arena pet? 3.2
SMSG_UNKNOWN_1224 = 0x4C8, // uint32 "Can't modify arena team while queued or in a match." 3.2
UMSG_UNKNOWN_1225 = 0x4C9, // not found 3.2
UMSG_UNKNOWN_1226 = 0x4CA, // not found 3.2
UMSG_UNKNOWN_1227 = 0x4CB, // not found 3.2
UMSG_UNKNOWN_1228 = 0x4CC, // not found 3.2
SMSG_UNKNOWN_1229 = 0x4CD, // SMSG, any opcode?
SMSG_UNKNOWN_1230 = 0x4CE, // SMSG, movement related
CMSG_UNKNOWN_1231_ACK = 0x4CF, // movement related
SMSG_UNKNOWN_1232 = 0x4D0, // SMSG, movement related
CMSG_UNKNOWN_1233_ACK = 0x4D1, // movement related
SMSG_UNKNOWN_1234 = 0x4D2, // SMSG, movement related
SMSG_UNKNOWN_1235 = 0x4D3, // SMSG, movement related
SMSG_UNKNOWN_1236 = 0x4D4, // SMSG, movement related
CMSG_EQUIPMENT_SET_USE = 0x4D5, // CMSG, lua: UseEquipmentSet
SMSG_EQUIPMENT_SET_USE_RESULT = 0x4D6, // SMSG, UseEquipmentSetResult?
UMSG_UNKNOWN_1239 = 0x4D7, // not found 3.2
SMSG_UNKNOWN_1240 = 0x4D8, // SMSG, uint64, string
CMSG_CHAR_FACTION_CHANGE = 0x4D9, // lua: CreateCharacter (PFC client response)
SMSG_CHAR_FACTION_CHANGE = 0x4DA, // response to 1241 (PFC server response)
UMSG_UNKNOWN_1243 = 0x4DB, // not found 3.2
UMSG_UNKNOWN_1244 = 0x4DC, // not found 3.2
UMSG_UNKNOWN_1245 = 0x4DD, // not found 3.2
SMSG_UNKNOWN_1246 = 0x4DE, // uint32, BattlefieldMgrEntryInvite
CMSG_UNKNOWN_1247 = 0x4DF, // lua: BattlefieldMgrEntryInviteResponse
SMSG_UNKNOWN_1248 = 0x4E0, // uint32, uint8, uint8
SMSG_UNKNOWN_1249 = 0x4E1, // uint32 BattlefieldMgrQueueInvite
CMSG_UNKNOWN_1250 = 0x4E2, // lua: BattlefieldMgrQueueInviteResponse
CMSG_UNKNOWN_1251 = 0x4E3, // lua: BattlefieldMgrQueueRequest
SMSG_UNKNOWN_1252 = 0x4E4, // uint32, uint8 queue full/can't join
SMSG_UNKNOWN_1253 = 0x4E5, // uint32 wintergrasp is full, you'll be ejected soon
SMSG_UNKNOWN_1254 = 0x4E6, // uint32, uint32, uint8
CMSG_UNKNOWN_1255 = 0x4E7, // lua: BattlefieldMgrExitRequest
SMSG_UNKNOWN_1256 = 0x4E8, // uint32, uint32
UMSG_UNKNOWN_1257 = 0x4E9, // not found 3.2
UMSG_UNKNOWN_1258 = 0x4EA, // not found 3.2
MSG_SET_RAID_DIFFICULTY = 0x4EB, // lua: SetRaidDifficulty
UMSG_UNKNOWN_1260 = 0x4EC, // not found 3.2
SMSG_TOGGLE_XP_GAIN = 0x4ED, // enable/disable XP gain console message
SMSG_UNKNOWN_1262 = 0x4EE,
SMSG_UNKNOWN_1263 = 0x4EF,
CMSG_UNKNOWN_1264 = 0x4F0, // lua: GMResponseResolve
SMSG_UNKNOWN_1265 = 0x4F1,
UMSG_UNKNOWN_1266 = 0x4F2, // not found 3.2
UMSG_UNKNOWN_1267 = 0x4F3, // not found 3.2
UMSG_UNKNOWN_1268 = 0x4F4, // not found 3.2
UMSG_UNKNOWN_1269 = 0x4F5, // not found 3.2
CMSG_WORLD_STATE_UI_TIMER_UPDATE = 0x4F6,
SMSG_WORLD_STATE_UI_TIMER_UPDATE = 0x4F7,
CMSG_UNKNOWN_1272 = 0x4F8, // called from lua: CreateCharacter, paid race change
NUM_MSG_TYPES = 0x4F9
};
/// Player state
enum SessionStatus
{
STATUS_AUTHED = 0, ///< Player authenticated (_player==NULL, m_playerRecentlyLogout = false or will be reset before handler call, m_GUID have garbage)
STATUS_LOGGEDIN, ///< Player in game (_player!=NULL, m_GUID == _player->GetGUID(), inWorld())
STATUS_TRANSFER, ///< Player transferring to another map (_player!=NULL, m_GUID == _player->GetGUID(), !inWorld())
STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT, ///< _player!= NULL or _player==NULL && m_playerRecentlyLogout, m_GUID store last _player guid)
STATUS_NEVER, ///< Opcode not accepted from client (deprecated or server side only)
STATUS_UNHANDLED ///< We don' handle this opcode yet
};
class WorldPacket;
struct OpcodeHandler
{
char const* name;
SessionStatus status;
void (WorldSession::*handler)(WorldPacket& recvPacket);
};
extern OpcodeHandler opcodeTable[NUM_MSG_TYPES];
/// Lookup opcode name for human understandable logging
inline const char* LookupOpcodeName(uint16 id)
{
if (id >= NUM_MSG_TYPES)
return "Received unknown opcode, it's more than max!";
return opcodeTable[id].name;
}
#endif
/// @}
| kicho/Ebon-Hold-Converted | src/game/Opcodes.h | C | gpl-2.0 | 82,620 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Marsyas: F0Analysis Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">Marsyas
 <span id="projectnumber">0.2</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.1.2 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Data Fields</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespaceMarsyas.html">Marsyas</a></li><li class="navelem"><a class="el" href="classMarsyas_1_1F0Analysis.html">F0Analysis</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">F0Analysis Class Reference<div class="ingroups"><a class="el" href="group__Analysis.html">Analysis</a></div></div> </div>
</div><!--header-->
<div class="contents">
<p>Compute F0s in input spectrum.
<a href="classMarsyas_1_1F0Analysis.html#details">More...</a></p>
<p><code>#include <<a class="el" href="F0Analysis_8h_source.html">F0Analysis.h</a>></code></p>
<p>Inherits <a class="el" href="classMarsyas_1_1MarSystem.html">MarSystem</a>.</p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2><a name="inherited"></a>
Additional Inherited Members</h2></td></tr>
<tr class="inherit_header pub_methods_classMarsyas_1_1MarSystem"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_classMarsyas_1_1MarSystem')"><img src="closed.png" alt="-"/> Public Member Functions inherited from <a class="el" href="classMarsyas_1_1MarSystem.html">MarSystem</a></td></tr>
<tr class="memitem:a63f09b80ca0e7838eb2a771e0372afec inherit pub_methods_classMarsyas_1_1MarSystem"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a63f09b80ca0e7838eb2a771e0372afec"></a>
bool </td><td class="memItemRight" valign="bottom"><a class="el" href="classMarsyas_1_1MarSystem.html#a63f09b80ca0e7838eb2a771e0372afec">linkControl</a> (std::string cname1, std::string cname2, bool update=true)</td></tr>
<tr class="memdesc:a63f09b80ca0e7838eb2a771e0372afec inherit pub_methods_classMarsyas_1_1MarSystem"><td class="mdescLeft"> </td><td class="mdescRight">Link controls. <br/></td></tr>
<tr class="memitem:ae3bf89f6a267e930ec5d3e768ccfad22 inherit pub_methods_classMarsyas_1_1MarSystem"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae3bf89f6a267e930ec5d3e768ccfad22"></a>
virtual std::istream & </td><td class="memItemRight" valign="bottom"><a class="el" href="classMarsyas_1_1MarSystem.html#ae3bf89f6a267e930ec5d3e768ccfad22">put</a> (std::istream &is)</td></tr>
<tr class="memdesc:ae3bf89f6a267e930ec5d3e768ccfad22 inherit pub_methods_classMarsyas_1_1MarSystem"><td class="mdescLeft"> </td><td class="mdescRight">The opposite of toString() and put() above, read in the parameters for a system. <br/></td></tr>
<tr class="memitem:aebbabcf1e6fde50604e431e768c396e7 inherit pub_methods_classMarsyas_1_1MarSystem"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aebbabcf1e6fde50604e431e768c396e7"></a>
virtual std::ostream & </td><td class="memItemRight" valign="bottom"><a class="el" href="classMarsyas_1_1MarSystem.html#aebbabcf1e6fde50604e431e768c396e7">put_html</a> (std::ostream &o)</td></tr>
<tr class="memdesc:aebbabcf1e6fde50604e431e768c396e7 inherit pub_methods_classMarsyas_1_1MarSystem"><td class="mdescLeft"> </td><td class="mdescRight">Output the <a class="el" href="classMarsyas_1_1MarSystem.html" title="MarSystem transforms a realvec.">MarSystem</a> as an HTML document with nested lists. <br/></td></tr>
<tr class="memitem:a866bc69cc6f557ab502d49762105b5ee inherit pub_methods_classMarsyas_1_1MarSystem"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a866bc69cc6f557ab502d49762105b5ee"></a>
void </td><td class="memItemRight" valign="bottom"><a class="el" href="classMarsyas_1_1MarSystem.html#a866bc69cc6f557ab502d49762105b5ee">setMATLABscript</a> (std::string script)</td></tr>
<tr class="memdesc:a866bc69cc6f557ab502d49762105b5ee inherit pub_methods_classMarsyas_1_1MarSystem"><td class="mdescLeft"> </td><td class="mdescRight">MATLAB scripting. <br/></td></tr>
<tr class="memitem:adb901a4b43e2cea8e9b55547365f5caf inherit pub_methods_classMarsyas_1_1MarSystem"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="adb901a4b43e2cea8e9b55547365f5caf"></a>
virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="classMarsyas_1_1MarSystem.html#adb901a4b43e2cea8e9b55547365f5caf">setName</a> (std::string name)</td></tr>
<tr class="memdesc:adb901a4b43e2cea8e9b55547365f5caf inherit pub_methods_classMarsyas_1_1MarSystem"><td class="mdescLeft"> </td><td class="mdescRight">Naming methods. <br/></td></tr>
<tr class="inherit_header pro_methods_classMarsyas_1_1MarSystem"><td colspan="2" onclick="javascript:toggleInherit('pro_methods_classMarsyas_1_1MarSystem')"><img src="closed.png" alt="-"/> Protected Member Functions inherited from <a class="el" href="classMarsyas_1_1MarSystem.html">MarSystem</a></td></tr>
<tr class="memitem:adb485c40cd7759b028209e10661bc58f inherit pro_methods_classMarsyas_1_1MarSystem"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="adb485c40cd7759b028209e10661bc58f"></a>
std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="classMarsyas_1_1MarSystem.html#adb485c40cd7759b028209e10661bc58f">getControlRelativePath</a> (std::string cname) const </td></tr>
<tr class="memdesc:adb485c40cd7759b028209e10661bc58f inherit pro_methods_classMarsyas_1_1MarSystem"><td class="mdescLeft"> </td><td class="mdescRight">control paths <br/></td></tr>
<tr class="memitem:a4614b4feb7f06e8a42d2280934cba880 inherit pro_methods_classMarsyas_1_1MarSystem"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a4614b4feb7f06e8a42d2280934cba880"></a>
<a class="el" href="classMarsyas_1_1MarSystem.html">MarSystem</a> & </td><td class="memItemRight" valign="bottom"><a class="el" href="classMarsyas_1_1MarSystem.html#a4614b4feb7f06e8a42d2280934cba880">operator=</a> (const <a class="el" href="classMarsyas_1_1MarSystem.html">MarSystem</a> &)</td></tr>
<tr class="memdesc:a4614b4feb7f06e8a42d2280934cba880 inherit pro_methods_classMarsyas_1_1MarSystem"><td class="mdescLeft"> </td><td class="mdescRight">Assignment operator (should never be called!) [!]. <br/></td></tr>
<tr class="inherit_header pro_attribs_classMarsyas_1_1MarSystem"><td colspan="2" onclick="javascript:toggleInherit('pro_attribs_classMarsyas_1_1MarSystem')"><img src="closed.png" alt="-"/> Protected Attributes inherited from <a class="el" href="classMarsyas_1_1MarSystem.html">MarSystem</a></td></tr>
<tr class="memitem:abec89a9066105205150c0bb915578f10 inherit pro_attribs_classMarsyas_1_1MarSystem"><td class="memItemLeft" align="right" valign="top">std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="classMarsyas_1_1MarSystem.html#abec89a9066105205150c0bb915578f10">absPath_</a></td></tr>
<tr class="memitem:abe8561cc60ffe3e07225be25849c61aa inherit pro_attribs_classMarsyas_1_1MarSystem"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="abe8561cc60ffe3e07225be25849c61aa"></a>
mrs_natural </td><td class="memItemRight" valign="bottom"><a class="el" href="classMarsyas_1_1MarSystem.html#abe8561cc60ffe3e07225be25849c61aa">c</a></td></tr>
<tr class="memdesc:abe8561cc60ffe3e07225be25849c61aa inherit pro_attribs_classMarsyas_1_1MarSystem"><td class="mdescLeft"> </td><td class="mdescRight">observation and time index //[!] <br/></td></tr>
<tr class="memitem:a56e3cc39df41d7723fe9c427e78d9100 inherit pro_attribs_classMarsyas_1_1MarSystem"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a56e3cc39df41d7723fe9c427e78d9100"></a>
std::map< std::string, <br class="typebreak"/>
MarControlPtr > </td><td class="memItemRight" valign="bottom"><a class="el" href="classMarsyas_1_1MarSystem.html#a56e3cc39df41d7723fe9c427e78d9100">controls_</a></td></tr>
<tr class="memdesc:a56e3cc39df41d7723fe9c427e78d9100 inherit pro_attribs_classMarsyas_1_1MarSystem"><td class="mdescLeft"> </td><td class="mdescRight">Controls. <br/></td></tr>
<tr class="memitem:aca39f88b9c54b9df276d74d82adc9993 inherit pro_attribs_classMarsyas_1_1MarSystem"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aca39f88b9c54b9df276d74d82adc9993"></a>
mrs_natural </td><td class="memItemRight" valign="bottom"><a class="el" href="classMarsyas_1_1MarSystem.html#aca39f88b9c54b9df276d74d82adc9993">count_</a></td></tr>
<tr class="memdesc:aca39f88b9c54b9df276d74d82adc9993 inherit pro_attribs_classMarsyas_1_1MarSystem"><td class="mdescLeft"> </td><td class="mdescRight">scheduling purposes <br/></td></tr>
<tr class="memitem:ac04358674719dc8eaacbe9786f53b8a3 inherit pro_attribs_classMarsyas_1_1MarSystem"><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="classMarsyas_1_1MarSystem.html#ac04358674719dc8eaacbe9786f53b8a3">isUpdating_</a></td></tr>
<tr class="memdesc:ac04358674719dc8eaacbe9786f53b8a3 inherit pro_attribs_classMarsyas_1_1MarSystem"><td class="mdescLeft"> </td><td class="mdescRight">value which is added to inStabilizingDelay to produce onStabilizingDelay. Defaults to 0. <a href="#ac04358674719dc8eaacbe9786f53b8a3"></a><br/></td></tr>
<tr class="memitem:a9f8e8d9c30975788bb7aa6b958a57e76 inherit pro_attribs_classMarsyas_1_1MarSystem"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a9f8e8d9c30975788bb7aa6b958a57e76"></a>
std::vector< <a class="el" href="classMarsyas_1_1MarSystem.html">MarSystem</a> * > </td><td class="memItemRight" valign="bottom"><a class="el" href="classMarsyas_1_1MarSystem.html#a9f8e8d9c30975788bb7aa6b958a57e76">marsystems_</a></td></tr>
<tr class="memdesc:a9f8e8d9c30975788bb7aa6b958a57e76 inherit pro_attribs_classMarsyas_1_1MarSystem"><td class="mdescLeft"> </td><td class="mdescRight">children <br/></td></tr>
<tr class="memitem:a4d739cc5d335052eb9f5b2ca559b81d1 inherit pro_attribs_classMarsyas_1_1MarSystem"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a4d739cc5d335052eb9f5b2ca559b81d1"></a>
std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="classMarsyas_1_1MarSystem.html#a4d739cc5d335052eb9f5b2ca559b81d1">name_</a></td></tr>
<tr class="memdesc:a4d739cc5d335052eb9f5b2ca559b81d1 inherit pro_attribs_classMarsyas_1_1MarSystem"><td class="mdescLeft"> </td><td class="mdescRight">Name of instance. <br/></td></tr>
<tr class="memitem:a57e87c242d81ca70dbe02dd600e35434 inherit pro_attribs_classMarsyas_1_1MarSystem"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a57e87c242d81ca70dbe02dd600e35434"></a>
<a class="el" href="classMarsyas_1_1MarSystem.html">MarSystem</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="classMarsyas_1_1MarSystem.html#a57e87c242d81ca70dbe02dd600e35434">parent_</a></td></tr>
<tr class="memdesc:a57e87c242d81ca70dbe02dd600e35434 inherit pro_attribs_classMarsyas_1_1MarSystem"><td class="mdescLeft"> </td><td class="mdescRight">Parent <a class="el" href="classMarsyas_1_1MarSystem.html" title="MarSystem transforms a realvec.">MarSystem</a> (if in a composite, otherwise it's NULL) <br/></td></tr>
<tr class="memitem:aee2268e08f3b7f390308ac90e9e87e74 inherit pro_attribs_classMarsyas_1_1MarSystem"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aee2268e08f3b7f390308ac90e9e87e74"></a>
std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="classMarsyas_1_1MarSystem.html#aee2268e08f3b7f390308ac90e9e87e74">prefix_</a></td></tr>
<tr class="memdesc:aee2268e08f3b7f390308ac90e9e87e74 inherit pro_attribs_classMarsyas_1_1MarSystem"><td class="mdescLeft"> </td><td class="mdescRight">/type_/name_/ <br/></td></tr>
<tr class="memitem:a82430191e59707c01706b4dcddde965a inherit pro_attribs_classMarsyas_1_1MarSystem"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a82430191e59707c01706b4dcddde965a"></a>
std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="classMarsyas_1_1MarSystem.html#a82430191e59707c01706b4dcddde965a">type_</a></td></tr>
<tr class="memdesc:a82430191e59707c01706b4dcddde965a inherit pro_attribs_classMarsyas_1_1MarSystem"><td class="mdescLeft"> </td><td class="mdescRight">Type of <a class="el" href="classMarsyas_1_1MarSystem.html" title="MarSystem transforms a realvec.">MarSystem</a>. <br/></td></tr>
</table>
<a name="details" id="details"></a><h2>Detailed Description</h2>
<div class="textblock"><p>Compute F0s in input spectrum. </p>
<dl class="section author"><dt>Author</dt><dd>Matthias Varewyck </dd></dl>
<dl class="section date"><dt>Date</dt><dd>20090518</dd></dl>
<p>Controls:</p>
<ul>
<li><b>mrs_natural</b> NrOfHarmonics [rw] : nr. of harmonics taken into account (excl. F0)</li>
<li><b>mrs_real</b> F0Weight [rw] : balance between F0 and higher harmonics</li>
<li><b>mrs_real</b> Attenuation [rw] : attenuation of higher harmonics</li>
<li><b>mrs_real</b> Tolerance_ [rw] : tolerance for harmonics to be assigned to F0</li>
<li><b>mrs_real</b> LowestFo_ [rw] : lowest possible F0</li>
<li><b>mrs_real</b> ChordEvidence_ [r] : evidence that input spectrum includes chord </li>
</ul>
<p>Definition at line <a class="el" href="F0Analysis_8h_source.html#l00041">41</a> of file <a class="el" href="F0Analysis_8h_source.html">F0Analysis.h</a>.</p>
</div><hr/>The documentation for this class was generated from the following files:<ul>
<li>/home/hindle1/src/marsyas/src/marsyas/<a class="el" href="F0Analysis_8h_source.html">F0Analysis.h</a></li>
<li>/home/hindle1/src/marsyas/src/marsyas/<a class="el" href="F0Analysis_8cpp_source.html">F0Analysis.cpp</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Sun Mar 24 2013 13:57:21 for Marsyas by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.1.2
</small></address>
</body>
</html>
| abramhindle/marsyas-fork | doc/out-www/sourceDoc/html/classMarsyas_1_1F0Analysis.html | HTML | gpl-2.0 | 15,782 |
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.truffle.r.library.fastrGrid;
import com.oracle.truffle.r.library.fastrGrid.DisplayList.LGetDisplayListElement;
import com.oracle.truffle.r.library.fastrGrid.DisplayList.LInitDisplayList;
import com.oracle.truffle.r.library.fastrGrid.DisplayList.LSetDisplayListOn;
import com.oracle.truffle.r.library.fastrGrid.PaletteExternals.CPalette;
import com.oracle.truffle.r.library.fastrGrid.PaletteExternals.CPalette2;
import com.oracle.truffle.r.library.fastrGrid.color.Col2RGB;
import com.oracle.truffle.r.library.fastrGrid.color.RGB;
import com.oracle.truffle.r.library.fastrGrid.grDevices.DevCairo;
import com.oracle.truffle.r.library.fastrGrid.grDevices.DevCurr;
import com.oracle.truffle.r.library.fastrGrid.grDevices.DevHoldFlush;
import com.oracle.truffle.r.library.fastrGrid.grDevices.DevOff;
import com.oracle.truffle.r.library.fastrGrid.grDevices.DevSize;
import com.oracle.truffle.r.library.fastrGrid.grDevices.InitWindowedDevice;
import com.oracle.truffle.r.library.fastrGrid.grDevices.SavePlot;
import com.oracle.truffle.r.library.fastrGrid.graphics.CPar;
import com.oracle.truffle.r.nodes.builtin.RExternalBuiltinNode;
import com.oracle.truffle.r.nodes.builtin.RInternalCodeBuiltinNode;
import com.oracle.truffle.r.runtime.RInternalCode;
import com.oracle.truffle.r.runtime.RRuntime;
import com.oracle.truffle.r.runtime.data.RList;
import com.oracle.truffle.r.runtime.data.RNull;
/**
* Implements the lookup for externals replaced by the FastR grid package.
*/
public final class FastRGridExternalLookup {
private FastRGridExternalLookup() {
// only static members
}
public static RExternalBuiltinNode lookupDotExternal(String name) {
switch (name) {
case "devholdflush":
return DevHoldFlush.create();
case "devsize":
return new DevSize();
case "devcur":
return new DevCurr();
case "devoff":
return DevOff.create();
case "PDF":
return new IgnoredGridExternal(RNull.instance);
case "devCairo":
return new DevCairo();
default:
return null;
}
}
public static RExternalBuiltinNode lookupDotExternal2(String name) {
switch (name) {
case "C_par":
return new CPar();
case "savePlot":
return SavePlot.create();
case "X11":
return new InitWindowedDevice();
case "devAskNewPage":
return new IgnoredGridExternal(RRuntime.LOGICAL_FALSE);
default:
return null;
}
}
public static RExternalBuiltinNode lookupDotCall(String name) {
switch (name) {
case "gridDirty":
return new LGridDirty();
case "initGrid":
return LInitGrid.create();
case "newpage":
return new LNewPage();
case "convert":
return LConvert.create();
case "validUnits":
return LValidUnit.create();
case "pretty":
return LPretty.create();
case "stringMetric":
return LStringMetric.create();
// Viewport management
case "upviewport":
return LUpViewPort.create();
case "initViewportStack":
return new LInitViewPortStack();
case "unsetviewport":
return LUnsetViewPort.create();
case "setviewport":
case "downviewport":
case "downvppath":
return getExternalFastRGridBuiltinNode(name);
// Drawing primitives
case "rect":
return LRect.create();
case "lines":
return LLines.create();
case "polygon":
return LPolygon.create();
case "text":
return LText.create();
case "textBounds":
return LTextBounds.create();
case "segments":
return LSegments.create();
case "circle":
return LCircle.create();
case "points":
return LPoints.create();
case "raster":
return LRaster.create();
// Bounds primitive:
case "rectBounds":
return LRectBounds.create();
case "locnBounds":
return LLocnBounds.create();
case "circleBounds":
return LCircleBounds.create();
// Simple grid state access
case "getGPar":
return new GridStateGetNode(GridState::getGpar);
case "setGPar":
return GridStateSetNode.create((state, val) -> state.setGpar((RList) val));
case "getCurrentGrob":
return new GridStateGetNode(GridState::getCurrentGrob);
case "setCurrentGrob":
return GridStateSetNode.create(GridState::setCurrentGrob);
case "currentViewport":
return new GridStateGetNode(GridState::getViewPort);
case "initGPar":
return new LInitGPar();
// Display list stuff
case "getDisplayList":
return new GridStateGetNode(GridState::getDisplayList);
case "setDisplayList":
return GridStateSetNode.create((state, val) -> state.setDisplayList((RList) val));
case "getDLindex":
return new GridStateGetNode(GridState::getDisplayListIndex);
case "setDLindex":
return GridStateSetNode.create((state, val) -> state.setDisplayListIndex(RRuntime.asInteger(val)));
case "setDLelt":
return GridStateSetNode.create(GridState::setDisplayListElement);
case "getDLelt":
return LGetDisplayListElement.create();
case "setDLon":
return LSetDisplayListOn.create();
case "getDLon":
return new GridStateGetNode(state -> RRuntime.asLogical(state.isDisplayListOn()));
case "getEngineDLon":
return new IgnoredGridExternal(RRuntime.LOGICAL_FALSE);
case "initDisplayList":
return new LInitDisplayList();
case "newpagerecording":
return new IgnoredGridExternal(RNull.instance);
// Color conversions
case "col2rgb":
return Col2RGB.create();
case "rgb":
return RGB.create();
case "palette2":
return CPalette2.create();
case "palette":
return CPalette.create();
default:
return null;
}
}
public static RExternalBuiltinNode lookupDotCallGraphics(String name) {
switch (name) {
case "gridDirty":
return new LGridDirty();
case "palette2":
return CPalette2.create();
case "palette":
return CPalette.create();
default:
return null;
}
}
private static RExternalBuiltinNode getExternalFastRGridBuiltinNode(String name) {
return new RInternalCodeBuiltinNode("grid", RInternalCode.loadSourceRelativeTo(LInitGrid.class, "fastrGrid.R"), name);
}
}
| akunft/fastr | com.oracle.truffle.r.library/src/com/oracle/truffle/r/library/fastrGrid/FastRGridExternalLookup.java | Java | gpl-2.0 | 8,532 |
package org.ups.sma.interfaces;
import org.ups.sma.custom.domain.agent.State;
public interface Stateful {
public State getState();
public State getPublicState();
}
| Ornro/SMA | src/org/ups/sma/interfaces/Stateful.java | Java | gpl-2.0 | 168 |
<?php
/**
* WordPress DB Class
*
* Original code from {@link http://php.justinvincent.com Justin Vincent (justin@visunet.ie)}
*
* @package WordPress
* @subpackage Database
* @since 0.71
*/
/**
* @since 0.71
*/
define( 'EZSQL_VERSION', 'WP1.25' );
/**
* @since 0.71
*/
define( 'OBJECT', 'OBJECT' );
define( 'object', 'OBJECT' ); // Back compat.
/**
* @since 2.5.0
*/
define( 'OBJECT_K', 'OBJECT_K' );
/**
* @since 0.71
*/
define( 'ARRAY_A', 'ARRAY_A' );
/**
* @since 0.71
*/
define( 'ARRAY_N', 'ARRAY_N' );
/**
* WordPress Database Access Abstraction Object
*
* It is possible to replace this class with your own
* by setting the $wpdb global variable in wp-content/db.php
* file to your class. The wpdb class will still be included,
* so you can extend it or simply use your own.
*
* @link https://codex.wordpress.org/Function_Reference/wpdb_Class
*
* @package WordPress
* @subpackage Database
* @since 0.71
*/
class wpdb {
/**
* Whether to show SQL/DB errors.
*
* Default behavior is to show errors if both WP_DEBUG and WP_DEBUG_DISPLAY
* evaluated to true.
*
* @since 0.71
* @access private
* @var bool
*/
var $show_errors = false;
/**
* Whether to suppress errors during the DB bootstrapping.
*
* @access private
* @since 2.5.0
* @var bool
*/
var $suppress_errors = false;
/**
* The last error during query.
*
* @since 2.5.0
* @var string
*/
public $last_error = '';
/**
* Amount of queries made
*
* @since 1.2.0
* @access public
* @var int
*/
public $num_queries = 0;
/**
* Count of rows returned by previous query
*
* @since 0.71
* @access public
* @var int
*/
public $num_rows = 0;
/**
* Count of affected rows by previous query
*
* @since 0.71
* @access private
* @var int
*/
var $rows_affected = 0;
/**
* The ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
*
* @since 0.71
* @access public
* @var int
*/
public $insert_id = 0;
/**
* Last query made
*
* @since 0.71
* @access private
* @var array
*/
var $last_query;
/**
* Results of the last query made
*
* @since 0.71
* @access private
* @var array|null
*/
var $last_result;
/**
* MySQL result, which is either a resource or boolean.
*
* @since 0.71
* @access protected
* @var mixed
*/
protected $result;
/**
* Cached column info, for sanity checking data before inserting
*
* @since 4.2.0
* @access protected
* @var array
*/
protected $col_meta = array();
/**
* Calculated character sets on tables
*
* @since 4.2.0
* @access protected
* @var array
*/
protected $table_charset = array();
/**
* Whether text fields in the current query need to be sanity checked.
*
* @since 4.2.0
* @access protected
* @var bool
*/
protected $check_current_query = true;
/**
* Flag to ensure we don't run into recursion problems when checking the collation.
*
* @since 4.2.0
* @access private
* @see wpdb::check_safe_collation()
* @var bool
*/
private $checking_collation = false;
/**
* Saved info on the table column
*
* @since 0.71
* @access protected
* @var array
*/
protected $col_info;
/**
* Saved queries that were executed
*
* @since 1.5.0
* @access private
* @var array
*/
var $queries;
/**
* The number of times to retry reconnecting before dying.
*
* @since 3.9.0
* @access protected
* @see wpdb::check_connection()
* @var int
*/
protected $reconnect_retries = 5;
/**
* WordPress table prefix
*
* You can set this to have multiple WordPress installations
* in a single database. The second reason is for possible
* security precautions.
*
* @since 2.5.0
* @access public
* @var string
*/
public $prefix = '';
/**
* WordPress base table prefix.
*
* @since 3.0.0
* @access public
* @var string
*/
public $base_prefix;
/**
* Whether the database queries are ready to start executing.
*
* @since 2.3.2
* @access private
* @var bool
*/
var $ready = false;
/**
* Blog ID.
*
* @since 3.0.0
* @access public
* @var int
*/
public $blogid = 0;
/**
* Site ID.
*
* @since 3.0.0
* @access public
* @var int
*/
public $siteid = 0;
/**
* List of WordPress per-blog tables
*
* @since 2.5.0
* @access private
* @see wpdb::tables()
* @var array
*/
var $tables = array( 'posts', 'comments', 'links', 'options', 'postmeta',
'terms', 'term_taxonomy', 'term_relationships', 'commentmeta' );
/**
* List of deprecated WordPress tables
*
* categories, post2cat, and link2cat were deprecated in 2.3.0, db version 5539
*
* @since 2.9.0
* @access private
* @see wpdb::tables()
* @var array
*/
var $old_tables = array( 'categories', 'post2cat', 'link2cat' );
/**
* List of WordPress global tables
*
* @since 3.0.0
* @access private
* @see wpdb::tables()
* @var array
*/
var $global_tables = array( 'users', 'usermeta' );
/**
* List of Multisite global tables
*
* @since 3.0.0
* @access private
* @see wpdb::tables()
* @var array
*/
var $ms_global_tables = array( 'blogs', 'signups', 'site', 'sitemeta',
'sitecategories', 'registration_log', 'blog_versions' );
/**
* WordPress Comments table
*
* @since 1.5.0
* @access public
* @var string
*/
public $comments;
/**
* WordPress Comment Metadata table
*
* @since 2.9.0
* @access public
* @var string
*/
public $commentmeta;
/**
* WordPress Links table
*
* @since 1.5.0
* @access public
* @var string
*/
public $links;
/**
* WordPress Options table
*
* @since 1.5.0
* @access public
* @var string
*/
public $options;
/**
* WordPress Post Metadata table
*
* @since 1.5.0
* @access public
* @var string
*/
public $postmeta;
/**
* WordPress Posts table
*
* @since 1.5.0
* @access public
* @var string
*/
public $posts;
/**
* WordPress Terms table
*
* @since 2.3.0
* @access public
* @var string
*/
public $terms;
/**
* WordPress Term Relationships table
*
* @since 2.3.0
* @access public
* @var string
*/
public $term_relationships;
/**
* WordPress Term Taxonomy table
*
* @since 2.3.0
* @access public
* @var string
*/
public $term_taxonomy;
/*
* Global and Multisite tables
*/
/**
* WordPress User Metadata table
*
* @since 2.3.0
* @access public
* @var string
*/
public $usermeta;
/**
* WordPress Users table
*
* @since 1.5.0
* @access public
* @var string
*/
public $users;
/**
* Multisite Blogs table
*
* @since 3.0.0
* @access public
* @var string
*/
public $blogs;
/**
* Multisite Blog Versions table
*
* @since 3.0.0
* @access public
* @var string
*/
public $blog_versions;
/**
* Multisite Registration Log table
*
* @since 3.0.0
* @access public
* @var string
*/
public $registration_log;
/**
* Multisite Signups table
*
* @since 3.0.0
* @access public
* @var string
*/
public $signups;
/**
* Multisite Sites table
*
* @since 3.0.0
* @access public
* @var string
*/
public $site;
/**
* Multisite Sitewide Terms table
*
* @since 3.0.0
* @access public
* @var string
*/
public $sitecategories;
/**
* Multisite Site Metadata table
*
* @since 3.0.0
* @access public
* @var string
*/
public $sitemeta;
/**
* Format specifiers for DB columns. Columns not listed here default to %s. Initialized during WP load.
*
* Keys are column names, values are format types: 'ID' => '%d'
*
* @since 2.8.0
* @see wpdb::prepare()
* @see wpdb::insert()
* @see wpdb::update()
* @see wpdb::delete()
* @see wp_set_wpdb_vars()
* @access public
* @var array
*/
public $field_types = array();
/**
* Database table columns charset
*
* @since 2.2.0
* @access public
* @var string
*/
public $charset;
/**
* Database table columns collate
*
* @since 2.2.0
* @access public
* @var string
*/
public $collate;
/**
* Database Username
*
* @since 2.9.0
* @access protected
* @var string
*/
protected $dbuser;
/**
* Database Password
*
* @since 3.1.0
* @access protected
* @var string
*/
protected $dbpassword;
/**
* Database Name
*
* @since 3.1.0
* @access protected
* @var string
*/
protected $dbname;
/**
* Database Host
*
* @since 3.1.0
* @access protected
* @var string
*/
protected $dbhost;
/**
* Database Handle
*
* @since 0.71
* @access protected
* @var string
*/
protected $dbh;
/**
* A textual description of the last query/get_row/get_var call
*
* @since 3.0.0
* @access public
* @var string
*/
public $func_call;
/**
* Whether MySQL is used as the database engine.
*
* Set in WPDB::db_connect() to true, by default. This is used when checking
* against the required MySQL version for WordPress. Normally, a replacement
* database drop-in (db.php) will skip these checks, but setting this to true
* will force the checks to occur.
*
* @since 3.3.0
* @access public
* @var bool
*/
public $is_mysql = null;
/**
* A list of incompatible SQL modes.
*
* @since 3.9.0
* @access protected
* @var array
*/
protected $incompatible_modes = array( 'NO_ZERO_DATE', 'ONLY_FULL_GROUP_BY',
'STRICT_TRANS_TABLES', 'STRICT_ALL_TABLES', 'TRADITIONAL' );
/**
* Whether to use mysqli over mysql.
*
* @since 3.9.0
* @access private
* @var bool
*/
private $use_mysqli = false;
/**
* Whether we've managed to successfully connect at some point
*
* @since 3.9.0
* @access private
* @var bool
*/
private $has_connected = false;
/**
* Connects to the database server and selects a database
*
* PHP5 style constructor for compatibility with PHP5. Does
* the actual setting up of the class properties and connection
* to the database.
*
* @link https://core.trac.wordpress.org/ticket/3354
* @since 2.0.8
*
* @global string $wp_version
*
* @param string $dbuser MySQL database user
* @param string $dbpassword MySQL database password
* @param string $dbname MySQL database name
* @param string $dbhost MySQL database host
*/
public function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
register_shutdown_function( array( $this, '__destruct' ) );
if ( WP_DEBUG && WP_DEBUG_DISPLAY )
$this->show_errors();
/* Use ext/mysqli if it exists and:
* - WP_USE_EXT_MYSQL is defined as false, or
* - We are a development version of WordPress, or
* - We are running PHP 5.5 or greater, or
* - ext/mysql is not loaded.
*/
if ( function_exists( 'mysqli_connect' ) ) {
if ( defined( 'WP_USE_EXT_MYSQL' ) ) {
$this->use_mysqli = ! WP_USE_EXT_MYSQL;
} elseif ( version_compare( phpversion(), '5.5', '>=' ) || ! function_exists( 'mysql_connect' ) ) {
$this->use_mysqli = true;
} elseif ( false !== strpos( $GLOBALS['wp_version'], '-' ) ) {
$this->use_mysqli = true;
}
}
$this->dbuser = $dbuser;
$this->dbpassword = $dbpassword;
$this->dbname = $dbname;
$this->dbhost = $dbhost;
// wp-config.php creation will manually connect when ready.
if ( defined( 'WP_SETUP_CONFIG' ) ) {
return;
}
$this->db_connect();
}
/**
* PHP5 style destructor and will run when database object is destroyed.
*
* @see wpdb::__construct()
* @since 2.0.8
* @return true
*/
public function __destruct() {
return true;
}
/**
* PHP5 style magic getter, used to lazy-load expensive data.
*
* @since 3.5.0
*
* @param string $name The private member to get, and optionally process
* @return mixed The private member
*/
public function __get( $name ) {
if ( 'col_info' === $name )
$this->load_col_info();
return $this->$name;
}
/**
* Magic function, for backwards compatibility.
*
* @since 3.5.0
*
* @param string $name The private member to set
* @param mixed $value The value to set
*/
public function __set( $name, $value ) {
$protected_members = array(
'col_meta',
'table_charset',
'check_current_query',
);
if ( in_array( $name, $protected_members, true ) ) {
return;
}
$this->$name = $value;
}
/**
* Magic function, for backwards compatibility.
*
* @since 3.5.0
*
* @param string $name The private member to check
*
* @return bool If the member is set or not
*/
public function __isset( $name ) {
return isset( $this->$name );
}
/**
* Magic function, for backwards compatibility.
*
* @since 3.5.0
*
* @param string $name The private member to unset
*/
public function __unset( $name ) {
unset( $this->$name );
}
/**
* Set $this->charset and $this->collate
*
* @since 3.1.0
*/
public function init_charset() {
if ( function_exists('is_multisite') && is_multisite() ) {
$this->charset = 'utf8';
if ( defined( 'DB_COLLATE' ) && DB_COLLATE ) {
$this->collate = DB_COLLATE;
} else {
$this->collate = 'utf8_general_ci';
}
} elseif ( defined( 'DB_COLLATE' ) ) {
$this->collate = DB_COLLATE;
}
if ( defined( 'DB_CHARSET' ) ) {
$this->charset = DB_CHARSET;
}
if ( ( $this->use_mysqli && ! ( $this->dbh instanceof mysqli ) ) || empty( $this->dbh ) ) {
return;
}
if ( 'utf8' === $this->charset && $this->has_cap( 'utf8mb4' ) ) {
$this->charset = 'utf8mb4';
}
if ( 'utf8mb4' === $this->charset && ( ! $this->collate || stripos( $this->collate, 'utf8_' ) === 0 ) ) {
$this->collate = 'utf8mb4_unicode_ci';
}
}
/**
* Sets the connection's character set.
*
* @since 3.1.0
*
* @param resource $dbh The resource given by mysql_connect
* @param string $charset Optional. The character set. Default null.
* @param string $collate Optional. The collation. Default null.
*/
public function set_charset( $dbh, $charset = null, $collate = null ) {
if ( ! isset( $charset ) )
$charset = $this->charset;
if ( ! isset( $collate ) )
$collate = $this->collate;
if ( $this->has_cap( 'collation' ) && ! empty( $charset ) ) {
if ( $this->use_mysqli ) {
if ( function_exists( 'mysqli_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
mysqli_set_charset( $dbh, $charset );
} else {
$query = $this->prepare( 'SET NAMES %s', $charset );
if ( ! empty( $collate ) )
$query .= $this->prepare( ' COLLATE %s', $collate );
mysqli_query( $dbh, $query );
}
} else {
if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
mysql_set_charset( $charset, $dbh );
} else {
$query = $this->prepare( 'SET NAMES %s', $charset );
if ( ! empty( $collate ) )
$query .= $this->prepare( ' COLLATE %s', $collate );
mysql_query( $query, $dbh );
}
}
}
}
/**
* Change the current SQL mode, and ensure its WordPress compatibility.
*
* If no modes are passed, it will ensure the current MySQL server
* modes are compatible.
*
* @since 3.9.0
*
* @param array $modes Optional. A list of SQL modes to set.
*/
public function set_sql_mode( $modes = array() ) {
if ( empty( $modes ) ) {
if ( $this->use_mysqli ) {
$res = mysqli_query( $this->dbh, 'SELECT @@SESSION.sql_mode' );
} else {
$res = mysql_query( 'SELECT @@SESSION.sql_mode', $this->dbh );
}
if ( empty( $res ) ) {
return;
}
if ( $this->use_mysqli ) {
$modes_array = mysqli_fetch_array( $res );
if ( empty( $modes_array[0] ) ) {
return;
}
$modes_str = $modes_array[0];
} else {
$modes_str = mysql_result( $res, 0 );
}
if ( empty( $modes_str ) ) {
return;
}
$modes = explode( ',', $modes_str );
}
$modes = array_change_key_case( $modes, CASE_UPPER );
/**
* Filter the list of incompatible SQL modes to exclude.
*
* @since 3.9.0
*
* @param array $incompatible_modes An array of incompatible modes.
*/
$incompatible_modes = (array) apply_filters( 'incompatible_sql_modes', $this->incompatible_modes );
foreach( $modes as $i => $mode ) {
if ( in_array( $mode, $incompatible_modes ) ) {
unset( $modes[ $i ] );
}
}
$modes_str = implode( ',', $modes );
if ( $this->use_mysqli ) {
mysqli_query( $this->dbh, "SET SESSION sql_mode='$modes_str'" );
} else {
mysql_query( "SET SESSION sql_mode='$modes_str'", $this->dbh );
}
}
/**
* Sets the table prefix for the WordPress tables.
*
* @since 2.5.0
*
* @param string $prefix Alphanumeric name for the new prefix.
* @param bool $set_table_names Optional. Whether the table names, e.g. wpdb::$posts, should be updated or not.
* @return string|WP_Error Old prefix or WP_Error on error
*/
public function set_prefix( $prefix, $set_table_names = true ) {
if ( preg_match( '|[^a-z0-9_]|i', $prefix ) )
return new WP_Error('invalid_db_prefix', 'Invalid database prefix' );
$old_prefix = is_multisite() ? '' : $prefix;
if ( isset( $this->base_prefix ) )
$old_prefix = $this->base_prefix;
$this->base_prefix = $prefix;
if ( $set_table_names ) {
foreach ( $this->tables( 'global' ) as $table => $prefixed_table )
$this->$table = $prefixed_table;
if ( is_multisite() && empty( $this->blogid ) )
return $old_prefix;
$this->prefix = $this->get_blog_prefix();
foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
$this->$table = $prefixed_table;
foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
$this->$table = $prefixed_table;
}
return $old_prefix;
}
/**
* Sets blog id.
*
* @since 3.0.0
* @access public
*
* @param int $blog_id
* @param int $site_id Optional.
* @return int previous blog id
*/
public function set_blog_id( $blog_id, $site_id = 0 ) {
if ( ! empty( $site_id ) )
$this->siteid = $site_id;
$old_blog_id = $this->blogid;
$this->blogid = $blog_id;
$this->prefix = $this->get_blog_prefix();
foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
$this->$table = $prefixed_table;
foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
$this->$table = $prefixed_table;
return $old_blog_id;
}
/**
* Gets blog prefix.
*
* @since 3.0.0
* @param int $blog_id Optional.
* @return string Blog prefix.
*/
public function get_blog_prefix( $blog_id = null ) {
if ( is_multisite() ) {
if ( null === $blog_id )
$blog_id = $this->blogid;
$blog_id = (int) $blog_id;
if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) )
return $this->base_prefix;
else
return $this->base_prefix . $blog_id . '_';
} else {
return $this->base_prefix;
}
}
/**
* Returns an array of WordPress tables.
*
* Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
* override the WordPress users and usermeta tables that would otherwise
* be determined by the prefix.
*
* The scope argument can take one of the following:
*
* 'all' - returns 'all' and 'global' tables. No old tables are returned.
* 'blog' - returns the blog-level tables for the queried blog.
* 'global' - returns the global tables for the installation, returning multisite tables only if running multisite.
* 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
* 'old' - returns tables which are deprecated.
*
* @since 3.0.0
* @uses wpdb::$tables
* @uses wpdb::$old_tables
* @uses wpdb::$global_tables
* @uses wpdb::$ms_global_tables
*
* @param string $scope Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all.
* @param bool $prefix Optional. Whether to include table prefixes. Default true. If blog
* prefix is requested, then the custom users and usermeta tables will be mapped.
* @param int $blog_id Optional. The blog_id to prefix. Defaults to wpdb::$blogid. Used only when prefix is requested.
* @return array Table names. When a prefix is requested, the key is the unprefixed table name.
*/
public function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
switch ( $scope ) {
case 'all' :
$tables = array_merge( $this->global_tables, $this->tables );
if ( is_multisite() )
$tables = array_merge( $tables, $this->ms_global_tables );
break;
case 'blog' :
$tables = $this->tables;
break;
case 'global' :
$tables = $this->global_tables;
if ( is_multisite() )
$tables = array_merge( $tables, $this->ms_global_tables );
break;
case 'ms_global' :
$tables = $this->ms_global_tables;
break;
case 'old' :
$tables = $this->old_tables;
break;
default :
return array();
}
if ( $prefix ) {
if ( ! $blog_id )
$blog_id = $this->blogid;
$blog_prefix = $this->get_blog_prefix( $blog_id );
$base_prefix = $this->base_prefix;
$global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
foreach ( $tables as $k => $table ) {
if ( in_array( $table, $global_tables ) )
$tables[ $table ] = $base_prefix . $table;
else
$tables[ $table ] = $blog_prefix . $table;
unset( $tables[ $k ] );
}
if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) )
$tables['users'] = CUSTOM_USER_TABLE;
if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) )
$tables['usermeta'] = CUSTOM_USER_META_TABLE;
}
return $tables;
}
/**
* Selects a database using the current database connection.
*
* The database name will be changed based on the current database
* connection. On failure, the execution will bail and display an DB error.
*
* @since 0.71
*
* @param string $db MySQL database name
* @param resource|null $dbh Optional link identifier.
*/
public function select( $db, $dbh = null ) {
if ( is_null($dbh) )
$dbh = $this->dbh;
if ( $this->use_mysqli ) {
$success = @mysqli_select_db( $dbh, $db );
} else {
$success = @mysql_select_db( $db, $dbh );
}
if ( ! $success ) {
$this->ready = false;
if ( ! did_action( 'template_redirect' ) ) {
wp_load_translations_early();
$this->bail( sprintf( __( '<h1>Can’t select database</h1>
<p>We were able to connect to the database server (which means your username and password is okay) but not able to select the <code>%1$s</code> database.</p>
<ul>
<li>Are you sure it exists?</li>
<li>Does the user <code>%2$s</code> have permission to use the <code>%1$s</code> database?</li>
<li>On some systems the name of your database is prefixed with your username, so it would be like <code>username_%1$s</code>. Could that be the problem?</li>
</ul>
<p>If you don\'t know how to set up a database you should <strong>contact your host</strong>. If all else fails you may find help at the <a href="https://wordpress.org/support/">WordPress Support Forums</a>.</p>' ), htmlspecialchars( $db, ENT_QUOTES ), htmlspecialchars( $this->dbuser, ENT_QUOTES ) ), 'db_select_fail' );
}
}
}
/**
* Do not use, deprecated.
*
* Use esc_sql() or wpdb::prepare() instead.
*
* @since 2.8.0
* @deprecated 3.6.0
* @see wpdb::prepare
* @see esc_sql()
* @access private
*
* @param string $string
* @return string
*/
function _weak_escape( $string ) {
if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) )
_deprecated_function( __METHOD__, '3.6', 'wpdb::prepare() or esc_sql()' );
return addslashes( $string );
}
/**
* Real escape, using mysqli_real_escape_string() or mysql_real_escape_string()
*
* @see mysqli_real_escape_string()
* @see mysql_real_escape_string()
* @since 2.8.0
* @access private
*
* @param string $string to escape
* @return string escaped
*/
function _real_escape( $string ) {
if ( $this->dbh ) {
if ( $this->use_mysqli ) {
return mysqli_real_escape_string( $this->dbh, $string );
} else {
return mysql_real_escape_string( $string, $this->dbh );
}
}
$class = get_class( $this );
if ( function_exists( '__' ) ) {
_doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), E_USER_NOTICE );
} else {
_doing_it_wrong( $class, sprintf( '%s must set a database connection for use with escaping.', $class ), E_USER_NOTICE );
}
return addslashes( $string );
}
/**
* Escape data. Works on arrays.
*
* @uses wpdb::_real_escape()
* @since 2.8.0
* @access private
*
* @param string|array $data
* @return string|array escaped
*/
function _escape( $data ) {
if ( is_array( $data ) ) {
foreach ( $data as $k => $v ) {
if ( is_array($v) )
$data[$k] = $this->_escape( $v );
else
$data[$k] = $this->_real_escape( $v );
}
} else {
$data = $this->_real_escape( $data );
}
return $data;
}
/**
* Do not use, deprecated.
*
* Use esc_sql() or wpdb::prepare() instead.
*
* @since 0.71
* @deprecated 3.6.0
* @see wpdb::prepare()
* @see esc_sql()
*
* @param mixed $data
* @return mixed
*/
public function escape( $data ) {
if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) )
_deprecated_function( __METHOD__, '3.6', 'wpdb::prepare() or esc_sql()' );
if ( is_array( $data ) ) {
foreach ( $data as $k => $v ) {
if ( is_array( $v ) )
$data[$k] = $this->escape( $v, 'recursive' );
else
$data[$k] = $this->_weak_escape( $v, 'internal' );
}
} else {
$data = $this->_weak_escape( $data, 'internal' );
}
return $data;
}
/**
* Escapes content by reference for insertion into the database, for security
*
* @uses wpdb::_real_escape()
*
* @since 2.3.0
*
* @param string $string to escape
*/
public function escape_by_ref( &$string ) {
if ( ! is_float( $string ) )
$string = $this->_real_escape( $string );
}
/**
* Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
*
* The following directives can be used in the query format string:
* %d (integer)
* %f (float)
* %s (string)
* %% (literal percentage sign - no argument needed)
*
* All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
* Literals (%) as parts of the query must be properly written as %%.
*
* This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
* Does not support sign, padding, alignment, width or precision specifiers.
* Does not support argument numbering/swapping.
*
* May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
*
* Both %d and %s should be left unquoted in the query string.
*
* wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
* wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
*
* @link http://php.net/sprintf Description of syntax.
* @since 2.3.0
*
* @param string $query Query statement with sprintf()-like placeholders
* @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
* {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
* being called like {@link http://php.net/sprintf sprintf()}.
* @param mixed $args,... further variables to substitute into the query's placeholders if being called like
* {@link http://php.net/sprintf sprintf()}.
* @return string|void Sanitized query string, if there is a query to prepare.
*/
public function prepare( $query, $args ) {
if ( is_null( $query ) )
return;
// This is not meant to be foolproof -- but it will catch obviously incorrect usage.
if ( strpos( $query, '%' ) === false ) {
_doing_it_wrong( 'wpdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9' );
}
$args = func_get_args();
array_shift( $args );
// If args were passed as an array (as in vsprintf), move them up
if ( isset( $args[0] ) && is_array($args[0]) )
$args = $args[0];
$query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
$query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
$query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
$query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
array_walk( $args, array( $this, 'escape_by_ref' ) );
return @vsprintf( $query, $args );
}
/**
* First half of escaping for LIKE special characters % and _ before preparing for MySQL.
*
* Use this only before wpdb::prepare() or esc_sql(). Reversing the order is very bad for security.
*
* Example Prepared Statement:
* $wild = '%';
* $find = 'only 43% of planets';
* $like = $wild . $wpdb->esc_like( $find ) . $wild;
* $sql = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_content LIKE %s", $like );
*
* Example Escape Chain:
* $sql = esc_sql( $wpdb->esc_like( $input ) );
*
* @since 4.0.0
* @access public
*
* @param string $text The raw text to be escaped. The input typed by the user should have no
* extra or deleted slashes.
* @return string Text in the form of a LIKE phrase. The output is not SQL safe. Call $wpdb::prepare()
* or real_escape next.
*/
public function esc_like( $text ) {
return addcslashes( $text, '_%\\' );
}
/**
* Print SQL/DB error.
*
* @since 0.71
* @global array $EZSQL_ERROR Stores error information of query and error string
*
* @param string $str The error to display
* @return false|void False if the showing of errors is disabled.
*/
public function print_error( $str = '' ) {
global $EZSQL_ERROR;
if ( !$str ) {
if ( $this->use_mysqli ) {
$str = mysqli_error( $this->dbh );
} else {
$str = mysql_error( $this->dbh );
}
}
$EZSQL_ERROR[] = array( 'query' => $this->last_query, 'error_str' => $str );
if ( $this->suppress_errors )
return false;
wp_load_translations_early();
if ( $caller = $this->get_caller() )
$error_str = sprintf( __( 'WordPress database error %1$s for query %2$s made by %3$s' ), $str, $this->last_query, $caller );
else
$error_str = sprintf( __( 'WordPress database error %1$s for query %2$s' ), $str, $this->last_query );
error_log( $error_str );
// Are we showing errors?
if ( ! $this->show_errors )
return false;
// If there is an error then take note of it
if ( is_multisite() ) {
$msg = sprintf(
"%s [%s]\n%s\n",
__( 'WordPress database error:' ),
$str,
$this->last_query
);
if ( defined( 'ERRORLOGFILE' ) ) {
error_log( $msg, 3, ERRORLOGFILE );
}
if ( defined( 'DIEONDBERROR' ) ) {
wp_die( $msg );
}
} else {
$str = htmlspecialchars( $str, ENT_QUOTES );
$query = htmlspecialchars( $this->last_query, ENT_QUOTES );
printf(
'<div id="error"><p class="wpdberror"><strong>%s</strong> [%s]<br /><code>%s</code></p></div>',
__( 'WordPress database error:' ),
$str,
$query
);
}
}
/**
* Enables showing of database errors.
*
* This function should be used only to enable showing of errors.
* wpdb::hide_errors() should be used instead for hiding of errors. However,
* this function can be used to enable and disable showing of database
* errors.
*
* @since 0.71
* @see wpdb::hide_errors()
*
* @param bool $show Whether to show or hide errors
* @return bool Old value for showing errors.
*/
public function show_errors( $show = true ) {
$errors = $this->show_errors;
$this->show_errors = $show;
return $errors;
}
/**
* Disables showing of database errors.
*
* By default database errors are not shown.
*
* @since 0.71
* @see wpdb::show_errors()
*
* @return bool Whether showing of errors was active
*/
public function hide_errors() {
$show = $this->show_errors;
$this->show_errors = false;
return $show;
}
/**
* Whether to suppress database errors.
*
* By default database errors are suppressed, with a simple
* call to this function they can be enabled.
*
* @since 2.5.0
* @see wpdb::hide_errors()
* @param bool $suppress Optional. New value. Defaults to true.
* @return bool Old value
*/
public function suppress_errors( $suppress = true ) {
$errors = $this->suppress_errors;
$this->suppress_errors = (bool) $suppress;
return $errors;
}
/**
* Kill cached query results.
*
* @since 0.71
*/
public function flush() {
$this->last_result = array();
$this->col_info = null;
$this->last_query = null;
$this->rows_affected = $this->num_rows = 0;
$this->last_error = '';
if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
mysqli_free_result( $this->result );
$this->result = null;
// Sanity check before using the handle
if ( empty( $this->dbh ) || !( $this->dbh instanceof mysqli ) ) {
return;
}
// Clear out any results from a multi-query
while ( mysqli_more_results( $this->dbh ) ) {
mysqli_next_result( $this->dbh );
}
} elseif ( is_resource( $this->result ) ) {
mysql_free_result( $this->result );
}
}
/**
* Connect to and select database.
*
* If $allow_bail is false, the lack of database connection will need
* to be handled manually.
*
* @since 3.0.0
* @since 3.9.0 $allow_bail parameter added.
*
* @param bool $allow_bail Optional. Allows the function to bail. Default true.
* @return bool True with a successful connection, false on failure.
*/
public function db_connect( $allow_bail = true ) {
$this->is_mysql = true;
/*
* Deprecated in 3.9+ when using MySQLi. No equivalent
* $new_link parameter exists for mysqli_* functions.
*/
$new_link = defined( 'MYSQL_NEW_LINK' ) ? MYSQL_NEW_LINK : true;
$client_flags = defined( 'MYSQL_CLIENT_FLAGS' ) ? MYSQL_CLIENT_FLAGS : 0;
if ( $this->use_mysqli ) {
$this->dbh = mysqli_init();
// mysqli_real_connect doesn't support the host param including a port or socket
// like mysql_connect does. This duplicates how mysql_connect detects a port and/or socket file.
$port = null;
$socket = null;
$host = $this->dbhost;
$port_or_socket = strstr( $host, ':' );
if ( ! empty( $port_or_socket ) ) {
$host = substr( $host, 0, strpos( $host, ':' ) );
$port_or_socket = substr( $port_or_socket, 1 );
if ( 0 !== strpos( $port_or_socket, '/' ) ) {
$port = intval( $port_or_socket );
$maybe_socket = strstr( $port_or_socket, ':' );
if ( ! empty( $maybe_socket ) ) {
$socket = substr( $maybe_socket, 1 );
}
} else {
$socket = $port_or_socket;
}
}
if ( WP_DEBUG ) {
mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
} else {
@mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
}
if ( $this->dbh->connect_errno ) {
$this->dbh = null;
/* It's possible ext/mysqli is misconfigured. Fall back to ext/mysql if:
* - We haven't previously connected, and
* - WP_USE_EXT_MYSQL isn't set to false, and
* - ext/mysql is loaded.
*/
$attempt_fallback = true;
if ( $this->has_connected ) {
$attempt_fallback = false;
} elseif ( defined( 'WP_USE_EXT_MYSQL' ) && ! WP_USE_EXT_MYSQL ) {
$attempt_fallback = false;
} elseif ( ! function_exists( 'mysql_connect' ) ) {
$attempt_fallback = false;
}
if ( $attempt_fallback ) {
$this->use_mysqli = false;
$this->db_connect();
}
}
} else {
if ( WP_DEBUG ) {
$this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
} else {
$this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
}
}
if ( ! $this->dbh && $allow_bail ) {
wp_load_translations_early();
// Load custom DB error template, if present.
if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
require_once( WP_CONTENT_DIR . '/db-error.php' );
die();
}
$this->bail( sprintf( __( "
<h1>Error establishing a database connection</h1>
<p>This either means that the username and password information in your <code>wp-config.php</code> file is incorrect or we can't contact the database server at <code>%s</code>. This could mean your host's database server is down.</p>
<ul>
<li>Are you sure you have the correct username and password?</li>
<li>Are you sure that you have typed the correct hostname?</li>
<li>Are you sure that the database server is running?</li>
</ul>
<p>If you're unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href='https://wordpress.org/support/'>WordPress Support Forums</a>.</p>
" ), htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' );
return false;
} elseif ( $this->dbh ) {
if ( ! $this->has_connected ) {
$this->init_charset();
}
$this->has_connected = true;
$this->set_charset( $this->dbh );
$this->ready = true;
$this->set_sql_mode();
$this->select( $this->dbname, $this->dbh );
return true;
}
return false;
}
/**
* Check that the connection to the database is still up. If not, try to reconnect.
*
* If this function is unable to reconnect, it will forcibly die, or if after the
* the template_redirect hook has been fired, return false instead.
*
* If $allow_bail is false, the lack of database connection will need
* to be handled manually.
*
* @since 3.9.0
*
* @param bool $allow_bail Optional. Allows the function to bail. Default true.
* @return bool|void True if the connection is up.
*/
public function check_connection( $allow_bail = true ) {
if ( $this->use_mysqli ) {
if ( @mysqli_ping( $this->dbh ) ) {
return true;
}
} else {
if ( @mysql_ping( $this->dbh ) ) {
return true;
}
}
$error_reporting = false;
// Disable warnings, as we don't want to see a multitude of "unable to connect" messages
if ( WP_DEBUG ) {
$error_reporting = error_reporting();
error_reporting( $error_reporting & ~E_WARNING );
}
for ( $tries = 1; $tries <= $this->reconnect_retries; $tries++ ) {
// On the last try, re-enable warnings. We want to see a single instance of the
// "unable to connect" message on the bail() screen, if it appears.
if ( $this->reconnect_retries === $tries && WP_DEBUG ) {
error_reporting( $error_reporting );
}
if ( $this->db_connect( false ) ) {
if ( $error_reporting ) {
error_reporting( $error_reporting );
}
return true;
}
sleep( 1 );
}
// If template_redirect has already happened, it's too late for wp_die()/dead_db().
// Let's just return and hope for the best.
if ( did_action( 'template_redirect' ) ) {
return false;
}
if ( ! $allow_bail ) {
return false;
}
// We weren't able to reconnect, so we better bail.
$this->bail( sprintf( ( "
<h1>Error reconnecting to the database</h1>
<p>This means that we lost contact with the database server at <code>%s</code>. This could mean your host's database server is down.</p>
<ul>
<li>Are you sure that the database server is running?</li>
<li>Are you sure that the database server is not under particularly heavy load?</li>
</ul>
<p>If you're unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href='https://wordpress.org/support/'>WordPress Support Forums</a>.</p>
" ), htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' );
// Call dead_db() if bail didn't die, because this database is no more. It has ceased to be (at least temporarily).
dead_db();
}
/**
* Perform a MySQL database query, using current database connection.
*
* More information can be found on the codex page.
*
* @since 0.71
*
* @param string $query Database query
* @return int|false Number of rows affected/selected or false on error
*/
public function query( $query ) {
if ( ! $this->ready ) {
$this->check_current_query = true;
return false;
}
/**
* Filter the database query.
*
* Some queries are made before the plugins have been loaded,
* and thus cannot be filtered with this method.
*
* @since 2.1.0
*
* @param string $query Database query.
*/
$query = apply_filters( 'query', $query );
$this->flush();
// Log how the function was called
$this->func_call = "\$db->query(\"$query\")";
// If we're writing to the database, make sure the query will write safely.
if ( $this->check_current_query && ! $this->check_ascii( $query ) ) {
$stripped_query = $this->strip_invalid_text_from_query( $query );
// strip_invalid_text_from_query() can perform queries, so we need
// to flush again, just to make sure everything is clear.
$this->flush();
if ( $stripped_query !== $query ) {
$this->insert_id = 0;
return false;
}
}
$this->check_current_query = true;
// Keep track of the last query for debug..
$this->last_query = $query;
$this->_do_query( $query );
// MySQL server has gone away, try to reconnect
$mysql_errno = 0;
if ( ! empty( $this->dbh ) ) {
if ( $this->use_mysqli ) {
$mysql_errno = mysqli_errno( $this->dbh );
} else {
$mysql_errno = mysql_errno( $this->dbh );
}
}
if ( empty( $this->dbh ) || 2006 == $mysql_errno ) {
if ( $this->check_connection() ) {
$this->_do_query( $query );
} else {
$this->insert_id = 0;
return false;
}
}
// If there is an error then take note of it..
if ( $this->use_mysqli ) {
$this->last_error = mysqli_error( $this->dbh );
} else {
$this->last_error = mysql_error( $this->dbh );
}
if ( $this->last_error ) {
// Clear insert_id on a subsequent failed insert.
if ( $this->insert_id && preg_match( '/^\s*(insert|replace)\s/i', $query ) )
$this->insert_id = 0;
$this->print_error();
return false;
}
if ( preg_match( '/^\s*(create|alter|truncate|drop)\s/i', $query ) ) {
$return_val = $this->result;
} elseif ( preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query ) ) {
if ( $this->use_mysqli ) {
$this->rows_affected = mysqli_affected_rows( $this->dbh );
} else {
$this->rows_affected = mysql_affected_rows( $this->dbh );
}
// Take note of the insert_id
if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
if ( $this->use_mysqli ) {
$this->insert_id = mysqli_insert_id( $this->dbh );
} else {
$this->insert_id = mysql_insert_id( $this->dbh );
}
}
// Return number of rows affected
$return_val = $this->rows_affected;
} else {
$num_rows = 0;
if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
while ( $row = @mysqli_fetch_object( $this->result ) ) {
$this->last_result[$num_rows] = $row;
$num_rows++;
}
} elseif ( is_resource( $this->result ) ) {
while ( $row = @mysql_fetch_object( $this->result ) ) {
$this->last_result[$num_rows] = $row;
$num_rows++;
}
}
// Log number of rows the query returned
// and return number of rows selected
$this->num_rows = $num_rows;
$return_val = $num_rows;
}
return $return_val;
}
/**
* Internal function to perform the mysql_query() call.
*
* @since 3.9.0
*
* @access private
* @see wpdb::query()
*
* @param string $query The query to run.
*/
private function _do_query( $query ) {
if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
$this->timer_start();
}
if ( $this->use_mysqli ) {
$this->result = @mysqli_query( $this->dbh, $query );
} else {
$this->result = @mysql_query( $query, $this->dbh );
}
$this->num_queries++;
if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
$this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
}
}
/**
* Insert a row into a table.
*
* wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
* wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
*
* @since 2.5.0
* @see wpdb::prepare()
* @see wpdb::$field_types
* @see wp_set_wpdb_vars()
*
* @param string $table Table name
* @param array $data Data to insert (in column => value pairs).
* Both $data columns and $data values should be "raw" (neither should be SQL escaped).
* @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
* If string, that format will be used for all of the values in $data.
* A format is one of '%d', '%f', '%s' (integer, float, string).
* If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
* @return int|false The number of rows inserted, or false on error.
*/
public function insert( $table, $data, $format = null ) {
return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
}
/**
* Replace a row into a table.
*
* wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
* wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
*
* @since 3.0.0
* @see wpdb::prepare()
* @see wpdb::$field_types
* @see wp_set_wpdb_vars()
*
* @param string $table Table name
* @param array $data Data to insert (in column => value pairs).
* Both $data columns and $data values should be "raw" (neither should be SQL escaped).
* @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
* If string, that format will be used for all of the values in $data.
* A format is one of '%d', '%f', '%s' (integer, float, string).
* If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
* @return int|false The number of rows affected, or false on error.
*/
public function replace( $table, $data, $format = null ) {
return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
}
/**
* Helper function for insert and replace.
*
* Runs an insert or replace query based on $type argument.
*
* @access private
* @since 3.0.0
* @see wpdb::prepare()
* @see wpdb::$field_types
* @see wp_set_wpdb_vars()
*
* @param string $table Table name
* @param array $data Data to insert (in column => value pairs).
* Both $data columns and $data values should be "raw" (neither should be SQL escaped).
* @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
* If string, that format will be used for all of the values in $data.
* A format is one of '%d', '%f', '%s' (integer, float, string).
* If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
* @param string $type Optional. What type of operation is this? INSERT or REPLACE. Defaults to INSERT.
* @return int|false The number of rows affected, or false on error.
*/
function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
$this->insert_id = 0;
if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) ) {
return false;
}
$data = $this->process_fields( $table, $data, $format );
if ( false === $data ) {
return false;
}
$formats = $values = array();
foreach ( $data as $value ) {
$formats[] = $value['format'];
$values[] = $value['value'];
}
$fields = '`' . implode( '`, `', array_keys( $data ) ) . '`';
$formats = implode( ', ', $formats );
$sql = "$type INTO `$table` ($fields) VALUES ($formats)";
$this->check_current_query = false;
return $this->query( $this->prepare( $sql, $values ) );
}
/**
* Update a row in the table
*
* wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
* wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
*
* @since 2.5.0
* @see wpdb::prepare()
* @see wpdb::$field_types
* @see wp_set_wpdb_vars()
*
* @param string $table Table name
* @param array $data Data to update (in column => value pairs).
* Both $data columns and $data values should be "raw" (neither should be SQL escaped).
* @param array $where A named array of WHERE clauses (in column => value pairs).
* Multiple clauses will be joined with ANDs.
* Both $where columns and $where values should be "raw".
* @param array|string $format Optional. An array of formats to be mapped to each of the values in $data.
* If string, that format will be used for all of the values in $data.
* A format is one of '%d', '%f', '%s' (integer, float, string).
* If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
* @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where.
* If string, that format will be used for all of the items in $where.
* A format is one of '%d', '%f', '%s' (integer, float, string).
* If omitted, all values in $where will be treated as strings.
* @return int|false The number of rows updated, or false on error.
*/
public function update( $table, $data, $where, $format = null, $where_format = null ) {
if ( ! is_array( $data ) || ! is_array( $where ) ) {
return false;
}
$data = $this->process_fields( $table, $data, $format );
if ( false === $data ) {
return false;
}
$where = $this->process_fields( $table, $where, $where_format );
if ( false === $where ) {
return false;
}
$fields = $conditions = $values = array();
foreach ( $data as $field => $value ) {
$fields[] = "`$field` = " . $value['format'];
$values[] = $value['value'];
}
foreach ( $where as $field => $value ) {
$conditions[] = "`$field` = " . $value['format'];
$values[] = $value['value'];
}
$fields = implode( ', ', $fields );
$conditions = implode( ' AND ', $conditions );
$sql = "UPDATE `$table` SET $fields WHERE $conditions";
$this->check_current_query = false;
return $this->query( $this->prepare( $sql, $values ) );
}
/**
* Delete a row in the table
*
* wpdb::delete( 'table', array( 'ID' => 1 ) )
* wpdb::delete( 'table', array( 'ID' => 1 ), array( '%d' ) )
*
* @since 3.4.0
* @see wpdb::prepare()
* @see wpdb::$field_types
* @see wp_set_wpdb_vars()
*
* @param string $table Table name
* @param array $where A named array of WHERE clauses (in column => value pairs).
* Multiple clauses will be joined with ANDs.
* Both $where columns and $where values should be "raw".
* @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where.
* If string, that format will be used for all of the items in $where.
* A format is one of '%d', '%f', '%s' (integer, float, string).
* If omitted, all values in $where will be treated as strings unless otherwise specified in wpdb::$field_types.
* @return int|false The number of rows updated, or false on error.
*/
public function delete( $table, $where, $where_format = null ) {
if ( ! is_array( $where ) ) {
return false;
}
$where = $this->process_fields( $table, $where, $where_format );
if ( false === $where ) {
return false;
}
$conditions = $values = array();
foreach ( $where as $field => $value ) {
$conditions[] = "`$field` = " . $value['format'];
$values[] = $value['value'];
}
$conditions = implode( ' AND ', $conditions );
$sql = "DELETE FROM `$table` WHERE $conditions";
$this->check_current_query = false;
return $this->query( $this->prepare( $sql, $values ) );
}
/**
* Processes arrays of field/value pairs and field formats.
*
* This is a helper method for wpdb's CRUD methods, which take field/value
* pairs for inserts, updates, and where clauses. This method first pairs
* each value with a format. Then it determines the charset of that field,
* using that to determine if any invalid text would be stripped. If text is
* stripped, then field processing is rejected and the query fails.
*
* @since 4.2.0
* @access protected
*
* @param string $table Table name.
* @param array $data Field/value pair.
* @param mixed $format Format for each field.
* @return array|false Returns an array of fields that contain paired values
* and formats. Returns false for invalid values.
*/
protected function process_fields( $table, $data, $format ) {
$data = $this->process_field_formats( $data, $format );
if ( false === $data ) {
return false;
}
$data = $this->process_field_charsets( $data, $table );
if ( false === $data ) {
return false;
}
$data = $this->process_field_lengths( $data, $table );
if ( false === $data ) {
return false;
}
$converted_data = $this->strip_invalid_text( $data );
if ( $data !== $converted_data ) {
return false;
}
return $data;
}
/**
* Prepares arrays of value/format pairs as passed to wpdb CRUD methods.
*
* @since 4.2.0
* @access protected
*
* @param array $data Array of fields to values.
* @param mixed $format Formats to be mapped to the values in $data.
* @return array Array, keyed by field names with values being an array
* of 'value' and 'format' keys.
*/
protected function process_field_formats( $data, $format ) {
$formats = $original_formats = (array) $format;
foreach ( $data as $field => $value ) {
$value = array(
'value' => $value,
'format' => '%s',
);
if ( ! empty( $format ) ) {
$value['format'] = array_shift( $formats );
if ( ! $value['format'] ) {
$value['format'] = reset( $original_formats );
}
} elseif ( isset( $this->field_types[ $field ] ) ) {
$value['format'] = $this->field_types[ $field ];
}
$data[ $field ] = $value;
}
return $data;
}
/**
* Adds field charsets to field/value/format arrays generated by
* the wpdb::process_field_formats() method.
*
* @since 4.2.0
* @access protected
*
* @param array $data As it comes from the wpdb::process_field_formats() method.
* @param string $table Table name.
* @return array|false The same array as $data with additional 'charset' keys.
*/
protected function process_field_charsets( $data, $table ) {
foreach ( $data as $field => $value ) {
if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
// We can skip this field if we know it isn't a string.
// This checks %d/%f versus ! %s because it's sprintf() could take more.
$value['charset'] = false;
} else {
$value['charset'] = $this->get_col_charset( $table, $field );
if ( is_wp_error( $value['charset'] ) ) {
return false;
}
}
$data[ $field ] = $value;
}
return $data;
}
/**
* For string fields, record the maximum string length that field can safely save.
*
* @since 4.2.1
* @access protected
*
* @param array $data As it comes from the wpdb::process_field_charsets() method.
* @param string $table Table name.
* @return array|false The same array as $data with additional 'length' keys, or false if
* any of the values were too long for their corresponding field.
*/
protected function process_field_lengths( $data, $table ) {
foreach ( $data as $field => $value ) {
if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
// We can skip this field if we know it isn't a string.
// This checks %d/%f versus ! %s because it's sprintf() could take more.
$value['length'] = false;
} else {
$value['length'] = $this->get_col_length( $table, $field );
if ( is_wp_error( $value['length'] ) ) {
return false;
}
}
$data[ $field ] = $value;
}
return $data;
}
/**
* Retrieve one variable from the database.
*
* Executes a SQL query and returns the value from the SQL result.
* If the SQL result contains more than one column and/or more than one row, this function returns the value in the column and row specified.
* If $query is null, this function returns the value in the specified column and row from the previous SQL result.
*
* @since 0.71
*
* @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
* @param int $x Optional. Column of value to return. Indexed from 0.
* @param int $y Optional. Row of value to return. Indexed from 0.
* @return string|null Database query result (as string), or null on failure
*/
public function get_var( $query = null, $x = 0, $y = 0 ) {
$this->func_call = "\$db->get_var(\"$query\", $x, $y)";
if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
$this->check_current_query = false;
}
if ( $query ) {
$this->query( $query );
}
// Extract var out of cached results based x,y vals
if ( !empty( $this->last_result[$y] ) ) {
$values = array_values( get_object_vars( $this->last_result[$y] ) );
}
// If there is a value return it else return null
return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;
}
/**
* Retrieve one row from the database.
*
* Executes a SQL query and returns the row from the SQL result.
*
* @since 0.71
*
* @param string|null $query SQL query.
* @param string $output Optional. one of ARRAY_A | ARRAY_N | OBJECT constants.
* Return an associative array (column => value, ...),
* a numerically indexed array (0 => value, ...) or
* an object ( ->column = value ), respectively.
* @param int $y Optional. Row to return. Indexed from 0.
* @return array|object|null|void Database query result in format specified by $output or null on failure
*/
public function get_row( $query = null, $output = OBJECT, $y = 0 ) {
$this->func_call = "\$db->get_row(\"$query\",$output,$y)";
if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
$this->check_current_query = false;
}
if ( $query ) {
$this->query( $query );
} else {
return null;
}
if ( !isset( $this->last_result[$y] ) )
return null;
if ( $output == OBJECT ) {
return $this->last_result[$y] ? $this->last_result[$y] : null;
} elseif ( $output == ARRAY_A ) {
return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null;
} elseif ( $output == ARRAY_N ) {
return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null;
} elseif ( strtoupper( $output ) === OBJECT ) {
// Back compat for OBJECT being previously case insensitive.
return $this->last_result[$y] ? $this->last_result[$y] : null;
} else {
$this->print_error( " \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N" );
}
}
/**
* Retrieve one column from the database.
*
* Executes a SQL query and returns the column from the SQL result.
* If the SQL result contains more than one column, this function returns the column specified.
* If $query is null, this function returns the specified column from the previous SQL result.
*
* @since 0.71
*
* @param string|null $query Optional. SQL query. Defaults to previous query.
* @param int $x Optional. Column to return. Indexed from 0.
* @return array Database query result. Array indexed from 0 by SQL result row number.
*/
public function get_col( $query = null , $x = 0 ) {
if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
$this->check_current_query = false;
}
if ( $query ) {
$this->query( $query );
}
$new_array = array();
// Extract the column values
for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
$new_array[$i] = $this->get_var( null, $x, $i );
}
return $new_array;
}
/**
* Retrieve an entire SQL result set from the database (i.e., many rows)
*
* Executes a SQL query and returns the entire SQL result.
*
* @since 0.71
*
* @param string $query SQL query.
* @param string $output Optional. Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants.
* With one of the first three, return an array of rows indexed from 0 by SQL result row number.
* Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively.
* With OBJECT_K, return an associative array of row objects keyed by the value of each row's first column's value.
* Duplicate keys are discarded.
* @return array|object|null Database query results
*/
public function get_results( $query = null, $output = OBJECT ) {
$this->func_call = "\$db->get_results(\"$query\", $output)";
if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
$this->check_current_query = false;
}
if ( $query ) {
$this->query( $query );
} else {
return null;
}
$new_array = array();
if ( $output == OBJECT ) {
// Return an integer-keyed array of row objects
return $this->last_result;
} elseif ( $output == OBJECT_K ) {
// Return an array of row objects with keys from column 1
// (Duplicates are discarded)
foreach ( $this->last_result as $row ) {
$var_by_ref = get_object_vars( $row );
$key = array_shift( $var_by_ref );
if ( ! isset( $new_array[ $key ] ) )
$new_array[ $key ] = $row;
}
return $new_array;
} elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
// Return an integer-keyed array of...
if ( $this->last_result ) {
foreach( (array) $this->last_result as $row ) {
if ( $output == ARRAY_N ) {
// ...integer-keyed row arrays
$new_array[] = array_values( get_object_vars( $row ) );
} else {
// ...column name-keyed row arrays
$new_array[] = get_object_vars( $row );
}
}
}
return $new_array;
} elseif ( strtoupper( $output ) === OBJECT ) {
// Back compat for OBJECT being previously case insensitive.
return $this->last_result;
}
return null;
}
/**
* Retrieves the character set for the given table.
*
* @since 4.2.0
* @access protected
*
* @param string $table Table name.
* @return string|WP_Error Table character set, WP_Error object if it couldn't be found.
*/
protected function get_table_charset( $table ) {
return 'utf8mb4';
$tablekey = strtolower( $table );
/**
* Filter the table charset value before the DB is checked.
*
* Passing a non-null value to the filter will effectively short-circuit
* checking the DB for the charset, returning that value instead.
*
* @since 4.2.0
*
* @param string $charset The character set to use. Default null.
* @param string $table The name of the table being checked.
*/
$charset = apply_filters( 'pre_get_table_charset', null, $table );
if ( null !== $charset ) {
return $charset;
}
if ( isset( $this->table_charset[ $tablekey ] ) ) {
return $this->table_charset[ $tablekey ];
}
$charsets = $columns = array();
$table_parts = explode( '.', $table );
$table = '`' . implode( '`.`', $table_parts ) . '`';
$results = $this->get_results( "SHOW FULL COLUMNS FROM $table" );
if ( ! $results ) {
return new WP_Error( 'wpdb_get_table_charset_failure' );
}
foreach ( $results as $column ) {
$columns[ strtolower( $column->Field ) ] = $column;
}
$this->col_meta[ $tablekey ] = $columns;
foreach ( $columns as $column ) {
if ( ! empty( $column->Collation ) ) {
list( $charset ) = explode( '_', $column->Collation );
// If the current connection can't support utf8mb4 characters, let's only send 3-byte utf8 characters.
if ( 'utf8mb4' === $charset && ! $this->has_cap( 'utf8mb4' ) ) {
$charset = 'utf8';
}
$charsets[ strtolower( $charset ) ] = true;
}
list( $type ) = explode( '(', $column->Type );
// A binary/blob means the whole query gets treated like this.
if ( in_array( strtoupper( $type ), array( 'BINARY', 'VARBINARY', 'TINYBLOB', 'MEDIUMBLOB', 'BLOB', 'LONGBLOB' ) ) ) {
$this->table_charset[ $tablekey ] = 'binary';
return 'binary';
}
}
// utf8mb3 is an alias for utf8.
if ( isset( $charsets['utf8mb3'] ) ) {
$charsets['utf8'] = true;
unset( $charsets['utf8mb3'] );
}
// Check if we have more than one charset in play.
$count = count( $charsets );
if ( 1 === $count ) {
$charset = key( $charsets );
} elseif ( 0 === $count ) {
// No charsets, assume this table can store whatever.
$charset = false;
} else {
// More than one charset. Remove latin1 if present and recalculate.
unset( $charsets['latin1'] );
$count = count( $charsets );
if ( 1 === $count ) {
// Only one charset (besides latin1).
$charset = key( $charsets );
} elseif ( 2 === $count && isset( $charsets['utf8'], $charsets['utf8mb4'] ) ) {
// Two charsets, but they're utf8 and utf8mb4, use utf8.
$charset = 'utf8';
} else {
// Two mixed character sets. ascii.
$charset = 'ascii';
}
}
$this->table_charset[ $tablekey ] = $charset;
return $charset;
}
/**
* Retrieves the character set for the given column.
*
* @since 4.2.0
* @access public
*
* @param string $table Table name.
* @param string $column Column name.
* @return string|false|WP_Error Column character set as a string. False if the column has no
* character set. WP_Error object if there was an error.
*/
public function get_col_charset( $table, $column ) {
$tablekey = strtolower( $table );
$columnkey = strtolower( $column );
/**
* Filter the column charset value before the DB is checked.
*
* Passing a non-null value to the filter will short-circuit
* checking the DB for the charset, returning that value instead.
*
* @since 4.2.0
*
* @param string $charset The character set to use. Default null.
* @param string $table The name of the table being checked.
* @param string $column The name of the column being checked.
*/
$charset = apply_filters( 'pre_get_col_charset', null, $table, $column );
if ( null !== $charset ) {
return $charset;
}
// Skip this entirely if this isn't a MySQL database.
if ( false === $this->is_mysql ) {
return false;
}
if ( empty( $this->table_charset[ $tablekey ] ) ) {
// This primes column information for us.
$table_charset = $this->get_table_charset( $table );
if ( is_wp_error( $table_charset ) ) {
return $table_charset;
}
}
// If still no column information, return the table charset.
if ( empty( $this->col_meta[ $tablekey ] ) ) {
return $this->table_charset[ $tablekey ];
}
// If this column doesn't exist, return the table charset.
if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
return $this->table_charset[ $tablekey ];
}
// Return false when it's not a string column.
if ( empty( $this->col_meta[ $tablekey ][ $columnkey ]->Collation ) ) {
return false;
}
list( $charset ) = explode( '_', $this->col_meta[ $tablekey ][ $columnkey ]->Collation );
return $charset;
}
/**
* Retrieve the maximum string length allowed in a given column.
* The length may either be specified as a byte length or a character length.
*
* @since 4.2.1
* @access public
*
* @param string $table Table name.
* @param string $column Column name.
* @return array|false|WP_Error array( 'length' => (int), 'type' => 'byte' | 'char' )
* false if the column has no length (for example, numeric column)
* WP_Error object if there was an error.
*/
public function get_col_length( $table, $column ) {
$tablekey = strtolower( $table );
$columnkey = strtolower( $column );
// Skip this entirely if this isn't a MySQL database.
if ( false === $this->is_mysql ) {
return false;
}
if ( empty( $this->col_meta[ $tablekey ] ) ) {
// This primes column information for us.
$table_charset = $this->get_table_charset( $table );
if ( is_wp_error( $table_charset ) ) {
return $table_charset;
}
}
if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
return false;
}
$typeinfo = explode( '(', $this->col_meta[ $tablekey ][ $columnkey ]->Type );
$type = strtolower( $typeinfo[0] );
if ( ! empty( $typeinfo[1] ) ) {
$length = trim( $typeinfo[1], ')' );
} else {
$length = false;
}
switch( $type ) {
case 'char':
case 'varchar':
return array(
'type' => 'char',
'length' => (int) $length,
);
break;
case 'binary':
case 'varbinary':
return array(
'type' => 'byte',
'length' => (int) $length,
);
break;
case 'tinyblob':
case 'tinytext':
return array(
'type' => 'byte',
'length' => 255, // 2^8 - 1
);
break;
case 'blob':
case 'text':
return array(
'type' => 'byte',
'length' => 65535, // 2^16 - 1
);
break;
case 'mediumblob':
case 'mediumtext':
return array(
'type' => 'byte',
'length' => 16777215, // 2^24 - 1
);
break;
case 'longblob':
case 'longtext':
return array(
'type' => 'byte',
'length' => 4294967295, // 2^32 - 1
);
break;
default:
return false;
}
return false;
}
/**
* Check if a string is ASCII.
*
* The negative regex is faster for non-ASCII strings, as it allows
* the search to finish as soon as it encounters a non-ASCII character.
*
* @since 4.2.0
* @access protected
*
* @param string $string String to check.
* @return bool True if ASCII, false if not.
*/
protected function check_ascii( $string ) {
if ( function_exists( 'mb_check_encoding' ) ) {
if ( mb_check_encoding( $string, 'ASCII' ) ) {
return true;
}
} elseif ( ! preg_match( '/[^\x00-\x7F]/', $string ) ) {
return true;
}
return false;
}
/**
* Check if the query is accessing a collation considered safe on the current version of MySQL.
*
* @since 4.2.0
* @access protected
*
* @param string $query The query to check.
* @return bool True if the collation is safe, false if it isn't.
*/
protected function check_safe_collation( $query ) {
if ( $this->checking_collation ) {
return true;
}
// We don't need to check the collation for queries that don't read data.
$query = ltrim( $query, "\r\n\t (" );
if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN|CREATE)\s/i', $query ) ) {
return true;
}
// All-ASCII queries don't need extra checking.
if ( $this->check_ascii( $query ) ) {
return true;
}
$table = $this->get_table_from_query( $query );
if ( ! $table ) {
return false;
}
$this->checking_collation = true;
$collation = $this->get_table_charset( $table );
$this->checking_collation = false;
// Tables with no collation, or latin1 only, don't need extra checking.
if ( false === $collation || 'latin1' === $collation ) {
return true;
}
$table = strtolower( $table );
if ( empty( $this->col_meta[ $table ] ) ) {
return false;
}
// If any of the columns don't have one of these collations, it needs more sanity checking.
foreach( $this->col_meta[ $table ] as $col ) {
if ( empty( $col->Collation ) ) {
continue;
}
if ( ! in_array( $col->Collation, array( 'utf8_general_ci', 'utf8_bin', 'utf8mb4_general_ci', 'utf8mb4_bin' ), true ) ) {
return false;
}
}
return true;
}
/**
* Strips any invalid characters based on value/charset pairs.
*
* @since 4.2.0
* @access protected
*
* @param array $data Array of value arrays. Each value array has the keys
* 'value' and 'charset'. An optional 'ascii' key can be
* set to false to avoid redundant ASCII checks.
* @return array|WP_Error The $data parameter, with invalid characters removed from
* each value. This works as a passthrough: any additional keys
* such as 'field' are retained in each value array. If we cannot
* remove invalid characters, a WP_Error object is returned.
*/
protected function strip_invalid_text( $data ) {
$db_check_string = false;
foreach ( $data as &$value ) {
$charset = $value['charset'];
if ( is_array( $value['length'] ) ) {
$length = $value['length']['length'];
$truncate_by_byte_length = 'byte' === $value['length']['type'];
} else {
$length = false;
// Since we have no length, we'll never truncate.
// Initialize the variable to false. true would take us
// through an unnecessary (for this case) codepath below.
$truncate_by_byte_length = false;
}
// There's no charset to work with.
if ( false === $charset ) {
continue;
}
// Column isn't a string.
if ( ! is_string( $value['value'] ) ) {
continue;
}
$needs_validation = true;
if (
// latin1 can store any byte sequence
'latin1' === $charset
||
// ASCII is always OK.
( ! isset( $value['ascii'] ) && $this->check_ascii( $value['value'] ) )
) {
$truncate_by_byte_length = true;
$needs_validation = false;
}
if ( $truncate_by_byte_length ) {
mbstring_binary_safe_encoding();
if ( false !== $length && strlen( $value['value'] ) > $length ) {
$value['value'] = substr( $value['value'], 0, $length );
}
reset_mbstring_encoding();
if ( ! $needs_validation ) {
continue;
}
}
// utf8 can be handled by regex, which is a bunch faster than a DB lookup.
if ( ( 'utf8' === $charset || 'utf8mb3' === $charset || 'utf8mb4' === $charset ) && function_exists( 'mb_strlen' ) ) {
$regex = '/
(
(?: [\x00-\x7F] # single-byte sequences 0xxxxxxx
| [\xC2-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
| \xE0[\xA0-\xBF][\x80-\xBF] # triple-byte sequences 1110xxxx 10xxxxxx * 2
| [\xE1-\xEC][\x80-\xBF]{2}
| \xED[\x80-\x9F][\x80-\xBF]
| [\xEE-\xEF][\x80-\xBF]{2}';
if ( 'utf8mb4' === $charset ) {
$regex .= '
| \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences 11110xxx 10xxxxxx * 3
| [\xF1-\xF3][\x80-\xBF]{3}
| \xF4[\x80-\x8F][\x80-\xBF]{2}
';
}
$regex .= '){1,40} # ...one or more times
)
| . # anything else
/x';
$value['value'] = preg_replace( $regex, '$1', $value['value'] );
if ( false !== $length && mb_strlen( $value['value'], 'UTF-8' ) > $length ) {
$value['value'] = mb_substr( $value['value'], 0, $length, 'UTF-8' );
}
continue;
}
// We couldn't use any local conversions, send it to the DB.
$value['db'] = $db_check_string = true;
}
unset( $value ); // Remove by reference.
if ( $db_check_string ) {
$queries = array();
foreach ( $data as $col => $value ) {
if ( ! empty( $value['db'] ) ) {
// We're going to need to truncate by characters or bytes, depending on the length value we have.
if ( 'byte' === $value['length']['type'] ) {
// Using binary causes LEFT() to truncate by bytes.
$charset = 'binary';
} else {
$charset = $value['charset'];
}
if ( is_array( $value['length'] ) ) {
$queries[ $col ] = $this->prepare( "CONVERT( LEFT( CONVERT( %s USING $charset ), %.0f ) USING {$this->charset} )", $value['value'], $value['length']['length'] );
} else if ( 'binary' !== $charset ) {
// If we don't have a length, there's no need to convert binary - it will always return the same result.
$queries[ $col ] = $this->prepare( "CONVERT( CONVERT( %s USING $charset ) USING {$this->charset} )", $value['value'] );
}
unset( $data[ $col ]['db'] );
}
}
$sql = array();
foreach ( $queries as $column => $query ) {
if ( ! $query ) {
continue;
}
$sql[] = $query . " AS x_$column";
}
$this->check_current_query = false;
$row = $this->get_row( "SELECT " . implode( ', ', $sql ), ARRAY_A );
if ( ! $row ) {
return new WP_Error( 'wpdb_strip_invalid_text_failure' );
}
foreach ( array_keys( $data ) as $column ) {
if ( isset( $row["x_$column"] ) ) {
$data[ $column ]['value'] = $row["x_$column"];
}
}
}
return $data;
}
/**
* Strips any invalid characters from the query.
*
* @since 4.2.0
* @access protected
*
* @param string $query Query to convert.
* @return string|WP_Error The converted query, or a WP_Error object if the conversion fails.
*/
protected function strip_invalid_text_from_query( $query ) {
// We don't need to check the collation for queries that don't read data.
$trimmed_query = ltrim( $query, "\r\n\t (" );
if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN|CREATE)\s/i', $trimmed_query ) ) {
return $query;
}
$table = $this->get_table_from_query( $query );
if ( $table ) {
$charset = $this->get_table_charset( $table );
if ( is_wp_error( $charset ) ) {
return $charset;
}
// We can't reliably strip text from tables containing binary/blob columns
if ( 'binary' === $charset ) {
return $query;
}
} else {
$charset = $this->charset;
}
$data = array(
'value' => $query,
'charset' => $charset,
'ascii' => false,
'length' => false,
);
$data = $this->strip_invalid_text( array( $data ) );
if ( is_wp_error( $data ) ) {
return $data;
}
return $data[0]['value'];
}
/**
* Strips any invalid characters from the string for a given table and column.
*
* @since 4.2.0
* @access public
*
* @param string $table Table name.
* @param string $column Column name.
* @param string $value The text to check.
* @return string|WP_Error The converted string, or a WP_Error object if the conversion fails.
*/
public function strip_invalid_text_for_column( $table, $column, $value ) {
if ( ! is_string( $value ) ) {
return $value;
}
$charset = $this->get_col_charset( $table, $column );
if ( ! $charset ) {
// Not a string column.
return $value;
} elseif ( is_wp_error( $charset ) ) {
// Bail on real errors.
return $charset;
}
$data = array(
$column => array(
'value' => $value,
'charset' => $charset,
'length' => $this->get_col_length( $table, $column ),
)
);
$data = $this->strip_invalid_text( $data );
if ( is_wp_error( $data ) ) {
return $data;
}
return $data[ $column ]['value'];
}
/**
* Find the first table name referenced in a query.
*
* @since 4.2.0
* @access protected
*
* @param string $query The query to search.
* @return string|false $table The table name found, or false if a table couldn't be found.
*/
protected function get_table_from_query( $query ) {
// Remove characters that can legally trail the table name.
$query = rtrim( $query, ';/-#' );
// Allow (select...) union [...] style queries. Use the first query's table name.
$query = ltrim( $query, "\r\n\t (" );
// Strip everything between parentheses except nested selects.
$query = preg_replace( '/\((?!\s*select)[^(]*?\)/is', '()', $query );
// Quickly match most common queries.
if ( preg_match( '/^\s*(?:'
. 'SELECT.*?\s+FROM'
. '|INSERT(?:\s+LOW_PRIORITY|\s+DELAYED|\s+HIGH_PRIORITY)?(?:\s+IGNORE)?(?:\s+INTO)?'
. '|REPLACE(?:\s+LOW_PRIORITY|\s+DELAYED)?(?:\s+INTO)?'
. '|UPDATE(?:\s+LOW_PRIORITY)?(?:\s+IGNORE)?'
. '|DELETE(?:\s+LOW_PRIORITY|\s+QUICK|\s+IGNORE)*(?:\s+FROM)?'
. ')\s+((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)/is', $query, $maybe ) ) {
return str_replace( '`', '', $maybe[1] );
}
// SHOW TABLE STATUS and SHOW TABLES
if ( preg_match( '/^\s*(?:'
. 'SHOW\s+TABLE\s+STATUS.+(?:LIKE\s+|WHERE\s+Name\s*=\s*)'
. '|SHOW\s+(?:FULL\s+)?TABLES.+(?:LIKE\s+|WHERE\s+Name\s*=\s*)'
. ')\W((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)\W/is', $query, $maybe ) ) {
return str_replace( '`', '', $maybe[1] );
}
// Big pattern for the rest of the table-related queries.
if ( preg_match( '/^\s*(?:'
. '(?:EXPLAIN\s+(?:EXTENDED\s+)?)?SELECT.*?\s+FROM'
. '|DESCRIBE|DESC|EXPLAIN|HANDLER'
. '|(?:LOCK|UNLOCK)\s+TABLE(?:S)?'
. '|(?:RENAME|OPTIMIZE|BACKUP|RESTORE|CHECK|CHECKSUM|ANALYZE|REPAIR).*\s+TABLE'
. '|TRUNCATE(?:\s+TABLE)?'
. '|CREATE(?:\s+TEMPORARY)?\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?'
. '|ALTER(?:\s+IGNORE)?\s+TABLE'
. '|DROP\s+TABLE(?:\s+IF\s+EXISTS)?'
. '|CREATE(?:\s+\w+)?\s+INDEX.*\s+ON'
. '|DROP\s+INDEX.*\s+ON'
. '|LOAD\s+DATA.*INFILE.*INTO\s+TABLE'
. '|(?:GRANT|REVOKE).*ON\s+TABLE'
. '|SHOW\s+(?:.*FROM|.*TABLE)'
. ')\s+\(*\s*((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)\s*\)*/is', $query, $maybe ) ) {
return str_replace( '`', '', $maybe[1] );
}
return false;
}
/**
* Load the column metadata from the last query.
*
* @since 3.5.0
*
* @access protected
*/
protected function load_col_info() {
if ( $this->col_info )
return;
if ( $this->use_mysqli ) {
$num_fields = @mysqli_num_fields( $this->result );
for ( $i = 0; $i < $num_fields; $i++ ) {
$this->col_info[ $i ] = @mysqli_fetch_field( $this->result );
}
} else {
$num_fields = @mysql_num_fields( $this->result );
for ( $i = 0; $i < $num_fields; $i++ ) {
$this->col_info[ $i ] = @mysql_fetch_field( $this->result, $i );
}
}
}
/**
* Retrieve column metadata from the last query.
*
* @since 0.71
*
* @param string $info_type Optional. Type one of name, table, def, max_length, not_null, primary_key, multiple_key, unique_key, numeric, blob, type, unsigned, zerofill
* @param int $col_offset Optional. 0: col name. 1: which table the col's in. 2: col's max length. 3: if the col is numeric. 4: col's type
* @return mixed Column Results
*/
public function get_col_info( $info_type = 'name', $col_offset = -1 ) {
$this->load_col_info();
if ( $this->col_info ) {
if ( $col_offset == -1 ) {
$i = 0;
$new_array = array();
foreach( (array) $this->col_info as $col ) {
$new_array[$i] = $col->{$info_type};
$i++;
}
return $new_array;
} else {
return $this->col_info[$col_offset]->{$info_type};
}
}
}
/**
* Starts the timer, for debugging purposes.
*
* @since 1.5.0
*
* @return true
*/
public function timer_start() {
$this->time_start = microtime( true );
return true;
}
/**
* Stops the debugging timer.
*
* @since 1.5.0
*
* @return float Total time spent on the query, in seconds
*/
public function timer_stop() {
return ( microtime( true ) - $this->time_start );
}
/**
* Wraps errors in a nice header and footer and dies.
*
* Will not die if wpdb::$show_errors is false.
*
* @since 1.5.0
*
* @param string $message The Error message
* @param string $error_code Optional. A Computer readable string to identify the error.
* @return false|void
*/
public function bail( $message, $error_code = '500' ) {
if ( !$this->show_errors ) {
if ( class_exists( 'WP_Error' ) )
$this->error = new WP_Error($error_code, $message);
else
$this->error = $message;
return false;
}
wp_die($message);
}
/**
* Whether MySQL database is at least the required minimum version.
*
* @since 2.5.0
*
* @global string $wp_version
* @global string $required_mysql_version
*
* @return WP_Error|void
*/
public function check_database_version() {
global $wp_version, $required_mysql_version;
// Make sure the server has the required MySQL version
if ( version_compare($this->db_version(), $required_mysql_version, '<') )
return new WP_Error('database_version', sprintf( __( '<strong>ERROR</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ));
}
/**
* Whether the database supports collation.
*
* Called when WordPress is generating the table scheme.
*
* @since 2.5.0
* @deprecated 3.5.0
* @deprecated Use wpdb::has_cap( 'collation' )
*
* @return bool True if collation is supported, false if version does not
*/
public function supports_collation() {
_deprecated_function( __FUNCTION__, '3.5', 'wpdb::has_cap( \'collation\' )' );
return $this->has_cap( 'collation' );
}
/**
* The database character collate.
*
* @since 3.5.0
*
* @return string The database character collate.
*/
public function get_charset_collate() {
$charset_collate = '';
if ( ! empty( $this->charset ) )
$charset_collate = "DEFAULT CHARACTER SET $this->charset";
if ( ! empty( $this->collate ) )
$charset_collate .= " COLLATE $this->collate";
return $charset_collate;
}
/**
* Determine if a database supports a particular feature.
*
* @since 2.7.0
* @since 4.1.0 Support was added for the 'utf8mb4' feature.
*
* @see wpdb::db_version()
*
* @param string $db_cap The feature to check for. Accepts 'collation',
* 'group_concat', 'subqueries', 'set_charset',
* or 'utf8mb4'.
* @return int|false Whether the database feature is supported, false otherwise.
*/
public function has_cap( $db_cap ) {
$version = $this->db_version();
switch ( strtolower( $db_cap ) ) {
case 'collation' : // @since 2.5.0
case 'group_concat' : // @since 2.7.0
case 'subqueries' : // @since 2.7.0
return version_compare( $version, '4.1', '>=' );
case 'set_charset' :
return version_compare( $version, '5.0.7', '>=' );
case 'utf8mb4' : // @since 4.1.0
if ( version_compare( $version, '5.5.3', '<' ) ) {
return false;
}
if ( $this->use_mysqli ) {
$client_version = mysqli_get_client_info();
} else {
$client_version = mysql_get_client_info();
}
/*
* libmysql has supported utf8mb4 since 5.5.3, same as the MySQL server.
* mysqlnd has supported utf8mb4 since 5.0.9.
*/
if ( false !== strpos( $client_version, 'mysqlnd' ) ) {
$client_version = preg_replace( '/^\D+([\d.]+).*/', '$1', $client_version );
return version_compare( $client_version, '5.0.9', '>=' );
} else {
return version_compare( $client_version, '5.5.3', '>=' );
}
}
return false;
}
/**
* Retrieve the name of the function that called wpdb.
*
* Searches up the list of functions until it reaches
* the one that would most logically had called this method.
*
* @since 2.5.0
*
* @return string|array The name of the calling function
*/
public function get_caller() {
return wp_debug_backtrace_summary( __CLASS__ );
}
/**
* The database version number.
*
* @since 2.7.0
*
* @return null|string Null on failure, version number on success.
*/
public function db_version() {
if ( $this->use_mysqli ) {
$server_info = mysqli_get_server_info( $this->dbh );
} else {
$server_info = mysql_get_server_info( $this->dbh );
}
return preg_replace( '/[^0-9.].*/', '', $server_info );
}
}
| hired/wordpress-heroku | wp-includes/wp-db.php | PHP | gpl-2.0 | 88,640 |
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Parser.Enums;
using Parser.FunctionParser;
using Parser.Interface;
using Parser.OperatorTypes;
using Parser.OperatorTypes.BaseTypes.Operator;
namespace TestParser
{
[TestClass]
public class ParserTest
{
public List<IEvaluatable<double>> Ops = new List<IEvaluatable<double>>
{
new Operator<double>("+", 1, Associativity.B, (a, b) => a + b, false),
new Operator<double>("-", 1, Associativity.L, (a, b) => a - b, false),
new Operator<double>("*", 2, Associativity.B, (a, b) => a * b, false),
new Operator<double>("/", 2, Associativity.L, (a, b) => a / b, false)
};
[TestMethod]
public void TestParse()
{
var parser = new SimpleParser(Ops);
var result = parser.Parse("1+2+3");
var expected = 6;
Assert.AreEqual(expected, result);
}
[TestMethod]
public void TestSymbolEval()
{
var parser = new SimpleParser();
var result = parser.Parse("2+x+3", "x", "2");
var expected = 7;
Assert.AreEqual(expected, result);
}
}
}
| Clanrat/BasicParser | Parser/TestParser/ParserTest.cs | C# | gpl-2.0 | 1,271 |
var config = require('../config'),
mongoose = require('mongoose'),
fixtures = require('node-mongoose-fixtures'),
Q = require('q');
// Connect to database
mongoose.connect(config.mongo.uri, config.mongo.options);
var defer = Q.defer();
defer.promise.then(function() {
console.log('Done');
process.exit(0);
});
| board-games-calendar/board-games-calendar | server/fixtures/index.js | JavaScript | gpl-2.0 | 329 |
<!-- Generated by pkgdown: do not edit by hand -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create the Complement Graph of a loon Graph — complement.loongraph • loon</title>
<!-- favicons -->
<link rel="icon" type="image/png" sizes="16x16" href="../favicon-16x16.png">
<link rel="icon" type="image/png" sizes="32x32" href="../favicon-32x32.png">
<link rel="apple-touch-icon" type="image/png" sizes="180x180" href="../apple-touch-icon.png" />
<link rel="apple-touch-icon" type="image/png" sizes="120x120" href="../apple-touch-icon-120x120.png" />
<link rel="apple-touch-icon" type="image/png" sizes="76x76" href="../apple-touch-icon-76x76.png" />
<link rel="apple-touch-icon" type="image/png" sizes="60x60" href="../apple-touch-icon-60x60.png" />
<!-- jquery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha256-916EbMg70RQy9LHiGkXzG8hSg9EdNy97GazNG/aiY1w=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha256-U5ZEeKfGNOja007MMD3YBI0A3OSZOQbeG6z2f2Y0hu8=" crossorigin="anonymous"></script>
<!-- Font Awesome icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.7.1/css/all.min.css" integrity="sha256-nAmazAk6vS34Xqo0BSrTb+abbtFlgsFK7NKSi6o7Y78=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.7.1/css/v4-shims.min.css" integrity="sha256-6qHlizsOWFskGlwVOKuns+D1nB6ssZrHQrNj1wGplHc=" crossorigin="anonymous" />
<!-- clipboard.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.4/clipboard.min.js" integrity="sha256-FiZwavyI2V6+EXO1U+xzLG3IKldpiTFf3153ea9zikQ=" crossorigin="anonymous"></script>
<!-- headroom.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/headroom/0.9.4/headroom.min.js" integrity="sha256-DJFC1kqIhelURkuza0AvYal5RxMtpzLjFhsnVIeuk+U=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/headroom/0.9.4/jQuery.headroom.min.js" integrity="sha256-ZX/yNShbjqsohH1k95liqY9Gd8uOiE1S4vZc+9KQ1K4=" crossorigin="anonymous"></script>
<!-- pkgdown -->
<link href="../pkgdown.css" rel="stylesheet">
<script src="../pkgdown.js"></script>
<meta property="og:title" content="Create the Complement Graph of a loon Graph — complement.loongraph" />
<meta property="og:description" content="Creates a complement graph of a graph" />
<meta property="og:image" content="/logo.png" />
<meta name="twitter:card" content="summary" />
<!-- mathjax -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js" integrity="sha256-nvJJv9wWKEm88qvoQl9ekL2J+k/RWIsaSScxxlsrv8k=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/config/TeX-AMS-MML_HTMLorMML.js" integrity="sha256-84DKXVJXs0/F8OTMzX4UR909+jtl4G7SPypPavF+GfA=" crossorigin="anonymous"></script>
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container template-reference-topic">
<header>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<span class="navbar-brand">
<a class="navbar-link" href="../index.html">loon</a>
<span class="version label label-default" data-toggle="tooltip" data-placement="bottom" title="Released version">1.2.3</span>
</span>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="../articles/introduction.html">Intro</a>
</li>
<li>
<a href="../reference/index.html">Reference</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
Articles
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="../articles/introduction.html">Introduction</a>
</li>
<li>
<a href="../articles/minorities.html">Analysis example</a>
</li>
<li>
<a href="../articles/teaching-example-smoothing.html">Teaching example</a>
</li>
<li>
<a href="../articles/Rmarkdown.html">Using with Rmarkdown</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
Videos
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="https://youtu.be/JFJcg855HcQ">the (not so) humble (interactive) histogram</a>
</li>
<li>
<a href="https://youtu.be/mMJllGOuDLY">3D interactive scatterplots</a>
</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="https://github.com/great-northern-diver/loon">
<span class="fa fa-github fa-lg"></span>
</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
</header>
<div class="row">
<div class="col-md-9 contents">
<div class="page-header">
<h1>Create the Complement Graph of a loon Graph</h1>
<div class="hidden name"><code>complement.loongraph.Rd</code></div>
</div>
<div class="ref-description">
<p>Creates a complement graph of a graph</p>
</div>
<pre class="usage"><span class='co'># S3 method for loongraph</span>
<span class='fu'><a href='complement.html'>complement</a></span>(<span class='no'>x</span>)</pre>
<h2 class="hasAnchor" id="arguments"><a class="anchor" href="#arguments"></a>Arguments</h2>
<table class="ref-arguments">
<colgroup><col class="name" /><col class="desc" /></colgroup>
<tr>
<th>x</th>
<td><p>loongraph object</p></td>
</tr>
</table>
<h2 class="hasAnchor" id="value"><a class="anchor" href="#value"></a>Value</h2>
<p>graph object of class loongraph</p>
<h2 class="hasAnchor" id="details"><a class="anchor" href="#details"></a>Details</h2>
<p>This method is currently only implemented for undirected graphs.</p>
</div>
<div class="col-md-3 hidden-xs hidden-sm" id="sidebar">
<h2>Contents</h2>
<ul class="nav nav-pills nav-stacked">
<li><a href="#arguments">Arguments</a></li>
<li><a href="#value">Value</a></li>
<li><a href="#details">Details</a></li>
</ul>
</div>
</div>
<footer>
<div class="copyright">
<p>Developed by Adrian Waddell, R. Wayne Oldford.</p>
</div>
<div class="pkgdown">
<p>Site built with <a href="https://pkgdown.r-lib.org/">pkgdown</a> 1.4.0.9000.</p>
</div>
</footer>
</div>
</body>
</html>
| waddella/loon | docs/reference/complement.loongraph.html | HTML | gpl-2.0 | 7,547 |
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.6 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2015 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM LocBlock records.
*
* @package CiviCRM_APIv3
*/
/**
* Create or update a LocBlock.
*
* @param array $params
* name/value pairs to insert in new 'LocBlock'
*
* @return array
* API result array.
*/
function civicrm_api3_loc_block_create($params) {
$entities = array();
// Call the appropriate api to create entities if any are passed in the params
// This is basically chaining but in reverse - we create the sub-entities first
// This exists because chainging does not work in reverse, or with keys like 'email_2'
$items = array('address', 'email', 'phone', 'im');
foreach ($items as $item) {
foreach (array('', '_2') as $suf) {
$key = $item . $suf;
if (!empty($params[$key]) && is_array($params[$key])) {
$info = $params[$key];
// If all we get is an id don't bother calling the api
if (count($info) == 1 && !empty($info['id'])) {
$params[$key . '_id'] = $info['id'];
}
// Bother calling the api
else {
$info['version'] = $params['version'];
$info['contact_id'] = CRM_Utils_Array::value('contact_id', $info, 'null');
$result = civicrm_api($item, 'create', $info);
if (!empty($result['is_error'])) {
return $result;
}
$entities[$key] = $result['values'][$result['id']];
$params[$key . '_id'] = $result['id'];
}
}
}
}
$dao = new CRM_Core_DAO_LocBlock();
$dao->copyValues($params);
$dao->save();
if (!empty($dao->id)) {
$values = array($dao->id => $entities);
_civicrm_api3_object_to_array($dao, $values[$dao->id]);
return civicrm_api3_create_success($values, $params, 'LocBlock', 'create', $dao);
}
return civicrm_api3_create_error('Unable to create LocBlock. Please check your params.');
}
/**
* Returns array of loc_blocks matching a set of one or more properties.
*
* @param array $params
* Array of one or more valid property_name=>value pairs. If $params is set.
* as null, all loc_blocks will be returned (default limit is 25)
*
* @return array
* API result array.
*/
function civicrm_api3_loc_block_get($params) {
$options = _civicrm_api3_get_options_from_params($params);
// If a return param has been set then fetch the appropriate fk objects
// This is a helper because api chaining does not work with a key like 'email_2'
if (!empty($options['return'])) {
unset($params['return']);
$values = array();
$items = array('address', 'email', 'phone', 'im');
$returnAll = !empty($options['return']['all']);
foreach (_civicrm_api3_basic_get('CRM_Core_DAO_LocBlock', $params, FALSE) as $val) {
foreach ($items as $item) {
foreach (array('', '_2') as $suf) {
$key = $item . $suf;
if (!empty($val[$key . '_id']) && ($returnAll || !empty($options['return'][$key]))) {
$val[$key] = civicrm_api($item, 'getsingle', array('version' => 3, 'id' => $val[$key . '_id']));
}
}
}
$values[$val['id']] = $val;
}
return civicrm_api3_create_success($values, $params, 'LocBlock', 'get');
}
return _civicrm_api3_basic_get('CRM_Core_DAO_LocBlock', $params);
}
/**
* Delete an existing LocBlock.
*
* @param array $params
* Array containing id of the record to be deleted.
*
* @return array
* API result array.
*/
function civicrm_api3_loc_block_delete($params) {
return _civicrm_api3_basic_delete('CRM_Core_DAO_LocBlock', $params);
}
| acappellamaniac/eva_website | sites/all/modules/civicrm/api/v3/LocBlock.php | PHP | gpl-2.0 | 5,322 |
cmd_drivers/rtc/rtc-core.o := /home/aashir/android/toolchain/linaro/bin/arm-eabi-ld -EL -r -o drivers/rtc/rtc-core.o drivers/rtc/class.o drivers/rtc/interface.o drivers/rtc/rtc-dev.o drivers/rtc/rtc-proc.o drivers/rtc/rtc-sysfs.o
| emwno/android_kernel_U8500 | drivers/rtc/.rtc-core.o.cmd | Batchfile | gpl-2.0 | 234 |
<html dir="LTR">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
<title>IOwlEdgeCollection Interface</title>
<xml>
</xml>
<link rel="stylesheet" type="text/css" href="MSDN.css" />
</head>
<body id="bodyID" class="dtBODY">
<div id="nsbanner">
<div id="bannerrow1">
<table class="bannerparthead" cellspacing="0">
<tr id="hdr">
<td class="runninghead">OwlDotNetApi Documentation</td>
<td class="product">
</td>
</tr>
</table>
</div>
<div id="TitleRow">
<h1 class="dtH1">IOwlEdgeCollection Interface</h1>
</div>
</div>
<div id="nstext">
<p> Represents a collection of objects that implement the IOwlEdge interface. This collection maps edge IDs to objects that implement the IOwlEdgeList interface </p>
<p>For a list of all members of this type, see <a href="OwlDotNetApi.IOwlEdgeCollectionMembers.html">IOwlEdgeCollection Members</a>.</p>
<p>
</p>
<div class="syntax">
<div>public interface IOwlEdgeCollection</div>
</div>
<h4 class="dtH4">Types that implement IOwlEdgeCollection</h4>
<div class="tablediv">
<table class="dtTABLE" cellspacing="0">
<tr valign="top">
<th width="50%">Type</th>
<th width="50%">Description</th>
</tr>
<tr valign="top">
<td width="50%">
<a href="OwlDotNetApi.OwlEdgeCollection.html">OwlEdgeCollection</a>
</td>
<td width="50%"> Represents a collection of edges. This class maps edge IDs to lists of OwlEdge objects </td>
</tr>
</table>
</div>
<h4 class="dtH4">Requirements</h4>
<p>
<b>Namespace: </b>
<a href="OwlDotNetApi.html">OwlDotNetApi</a>
</p>
<p>
<b>Assembly: </b>OwlDotNetApi (in OwlDotNetApi.dll)
</p>
<h4 class="dtH4">See Also</h4>
<p>
<a href="OwlDotNetApi.IOwlEdgeCollectionMembers.html">IOwlEdgeCollection Members</a> | <a href="OwlDotNetApi.html">OwlDotNetApi Namespace</a></p>
<object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
<param name="Keyword" value="IOwlEdgeCollection interface, about IOwlEdgeCollection interface">
</param>
</object>
</div>
</body>
</html> | bpellens/owldotnetapi | source/OwlDotNetApi/doc/owldotnetapi/OwlDotNetApi.IOwlEdgeCollection.html | HTML | gpl-2.0 | 2,559 |
/* OpenCP Module Player
* copyright (c) '05-'10 Stian Skjelstad <stian@nixia.no>
*
* OPL-compatible file type detection routines for the file selector
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "config.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <adplug/adplug.h>
#include <adplug/players.h>
#include <adplug/player.h>
#include "types.h"
extern "C" {
#include "boot/plinkman.h"
#include "filesel/mdb.h"
#include "filesel/pfilesel.h"
#include "stuff/compat.h"
}
static int oplReadMemInfo(struct moduleinfostruct *m, const char *buf, size_t len)
{
CPlayers::const_iterator i;
int j;
char name[13];
strncpy(name, m->name, 12);
name[12]=0;
for(i = CAdPlug::players.begin(); i != CAdPlug::players.end(); i++)
for(j = 0; (*i)->get_extension(j); j++)
{
if(CFileProvider::extension(name, (*i)->get_extension(j)))
{
snprintf(m->comment, sizeof(m->comment), "%s", (*i)->filetype.c_str());
m->modtype=mtOPL;
return 0; /* we are not a dominant plugin */
}
}
return 0;
}
static int oplReadInfo(struct moduleinfostruct *m, FILE *f, const char *buf, size_t len)
{
return oplReadMemInfo(m, buf, len);
}
static void oplEvent(int event)
{
switch (event)
{
case mdbEvInit:
{
CPlayers::const_iterator i;
int j;
const char *s;
char _s[6];
for(i = CAdPlug::players.begin(); i != CAdPlug::players.end(); i++)
for(j = 0; (s=(*i)->get_extension(j)); j++)
{
strncpy(_s, s+1, 5);
_s[5]=0;
strupr(_s);
fsRegisterExt(_s);
}
}
}
}
static struct mdbreadinforegstruct oplReadInfoReg = {oplReadMemInfo, oplReadInfo, oplEvent MDBREADINFOREGSTRUCT_TAIL};
static void __attribute__((constructor))init(void)
{
mdbRegisterReadInfo(&oplReadInfoReg);
}
static void __attribute__((destructor))done(void)
{
mdbUnregisterReadInfo(&oplReadInfoReg);
}
extern "C" {
const char *dllinfo = "";
struct linkinfostruct dllextinfo = {"opltype", "OpenCP OPL Detection (c) 2005-09 Stian Skjelstad", DLLVERSION, 0 LINKINFOSTRUCT_NOEVENTS};
}
| cynthia/ocp-osx | playopl/opltype.cpp | C++ | gpl-2.0 | 2,693 |
/**
* This file is part of Tales of Berseria "Fix".
*
* Tales of Berseria "Fix" is free software : you can redistribute it
* and/or modify it under the terms of the GNU General Public License
* as published by The Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* Tales of Berseria "Fix" 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 Tales of Berseria "Fix".
*
* If not, see <http://www.gnu.org/licenses/>.
*
**/
#include "tls.h"
TBF_TLS*
__stdcall
TBF_GetTLS (void)
{
if (__TBF_TLS_INDEX == -1)
return nullptr;
LPVOID lpvData =
TlsGetValue (__TBF_TLS_INDEX);
if (lpvData == nullptr)
{
lpvData =
(LPVOID)LocalAlloc (LPTR, sizeof TBF_TLS);
if (! TlsSetValue (__TBF_TLS_INDEX, lpvData))
{
LocalFree (lpvData);
return nullptr;
}
}
return (TBF_TLS *)lpvData;
} | Kaldaien/TBF | src/tls.cpp | C++ | gpl-2.0 | 1,157 |
/*
* $Id: gtpca.c 9725 2012-10-02 10:56:51Z andijahja $
*/
/*
* Harbour Project source code:
* Video subsystem for ANSI terminals
*
* Copyright 2000 David G. Holm <dholm@jsd-llc.com>
* www - http://www.harbour-project.org
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA (or visit the web site http://www.gnu.org/).
*
* As a special exception, the Harbour Project gives permission for
* additional uses of the text contained in its release of Harbour.
*
* The exception is that, if you link the Harbour libraries with other
* files to produce an executable, this does not by itself cause the
* resulting executable to be covered by the GNU General Public License.
* Your use of that executable is in no way restricted on account of
* linking the Harbour library code into it.
*
* This exception does not however invalidate any other reasons why
* the executable file might be covered by the GNU General Public License.
*
* This exception applies only to the code released by the Harbour
* Project under the name Harbour. If you copy code from other
* Harbour Project or Free Software Foundation releases into a copy of
* Harbour, as the General Public License permits, the exception does
* not apply to the code that you add in this way. To avoid misleading
* anyone as to the status of such modified files, you must delete
* this exception notice from them.
*
* If you write modifications of your own for Harbour, it is your choice
* whether to permit this exception to apply to your modifications.
* If you do not wish that, delete this exception notice.
*
*/
/*
* This module is partially based on VIDMGR by Andrew Clarke and modified
* for the Harbour project
*/
/* NOTE: User programs should never call this layer directly! */
#define HB_GT_NAME PCA
#include "hbgtcore.h"
#include "hbinit.h"
#include "hbapifs.h"
#include "hbapicdp.h"
#include "hbapiitm.h"
#include "hbdate.h"
#include "hb_io.h"
#include "inkey.ch"
#include <ctype.h>
#include <string.h>
#if defined( HB_OS_UNIX ) || defined( __DJGPP__ )
#include <unistd.h> /* read() function requires it */
#include <termios.h>
#include <sys/ioctl.h>
#include <signal.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#else
# if defined( HB_WIN32_IO )
# include <windows.h>
# endif
# if ( defined( _MSC_VER ) || defined( __WATCOMC__ ) ) && ! defined( HB_OS_WIN_CE )
# include <conio.h>
# endif
#endif
static int s_GtId;
static HB_GT_FUNCS SuperTable;
#define HB_GTSUPER ( &SuperTable )
#define HB_GTID_PTR ( &s_GtId )
static const BYTE s_szBell[] = { HB_CHAR_BEL, 0 };
static const int s_AnsiColors[] = { 0, 4, 2, 6, 1, 5, 3, 7 };
static HB_FHANDLE s_hFilenoStdin;
static HB_FHANDLE s_hFilenoStdout;
static HB_FHANDLE s_hFilenoStderr;
static int s_iRow;
static int s_iCol;
static int s_iLineBufSize = 0;
static BYTE * s_sLineBuf;
static BYTE * s_szCrLf;
static HB_SIZE s_ulCrLf;
static int s_iCurrentSGR, s_iFgColor, s_iBgColor, s_iBold, s_iBlink, s_iAM;
static int s_iCursorStyle;
static BOOL s_bStdinConsole;
static BOOL s_bStdoutConsole;
static BOOL s_bStderrConsole;
static BOOL s_fDispTrans;
static PHB_CODEPAGE s_cdpTerm;
static PHB_CODEPAGE s_cdpHost;
static BYTE s_keyTransTbl[ 256 ];
static int s_iOutBufSize = 0;
static int s_iOutBufIndex = 0;
static BYTE * s_sOutBuf;
#if defined( HB_OS_UNIX ) || defined( __DJGPP__ )
static volatile BOOL s_fRestTTY = FALSE;
static struct termios s_saved_TIO, s_curr_TIO;
#if defined( SIGTTOU )
static void sig_handler( int iSigNo )
{
switch( iSigNo )
{
#ifdef SIGCHLD
case SIGCHLD:
{
int e = errno, stat;
pid_t pid;
do
{
pid = waitpid( -1, &stat, WNOHANG );
}
while( pid > 0 );
errno = e;
break;
}
#endif
#ifdef SIGWINCH
case SIGWINCH:
/* s_WinSizeChangeFlag = TRUE; */
break;
#endif
#ifdef SIGINT
case SIGINT:
/* s_InetrruptFlag = TRUE; */
break;
#endif
#ifdef SIGQUIT
case SIGQUIT:
/* s_BreakFlag = TRUE; */
break;
#endif
#ifdef SIGTSTP
case SIGTSTP:
/* s_DebugFlag = TRUE; */
break;
#endif
#ifdef SIGTTOU
case SIGTTOU:
s_fRestTTY = FALSE;
break;
#endif
}
}
#endif
#endif
static void hb_gt_pca_termFlush( void )
{
if( s_iOutBufIndex > 0 )
{
hb_fsWriteLarge( s_hFilenoStdout, s_sOutBuf, s_iOutBufIndex );
s_iOutBufIndex = 0;
}
}
static void hb_gt_pca_termOut( const BYTE * pStr, int iLen )
{
if( s_iOutBufSize )
{
int i;
while( iLen > 0 )
{
if( s_iOutBufSize == s_iOutBufIndex )
hb_gt_pca_termFlush();
i = s_iOutBufSize - s_iOutBufIndex;
if( i > iLen )
i = iLen;
memcpy( s_sOutBuf + s_iOutBufIndex, pStr, i );
pStr += i;
s_iOutBufIndex += i;
iLen -= i;
}
}
}
static void hb_gt_pca_AnsiSetAutoMargin( int iAM )
{
HB_TRACE( HB_TR_DEBUG, ( "hb_gt_pca_AnsiSetAutoMargin(%d)", iAM ) );
if( iAM != s_iAM )
{
/*
* disabled until I'll find good PC-ANSI terminal documentation with
* detail Auto Margin and Auto Line Wrapping description, [druzus]
*/
#if 0
if( iAM != 0 )
hb_gt_pca_termOut( ( BYTE * ) "\x1B[=7h", 5 );
else
hb_gt_pca_termOut( ( BYTE * ) "\x1B[=7l", 5 );
#endif
s_iAM = iAM;
}
}
static void hb_gt_pca_AnsiGetCurPos( int * iRow, int * iCol )
{
static BOOL s_fIsAnswer = TRUE;
HB_TRACE( HB_TR_DEBUG, ( "hb_gt_pca_AnsiGetCurPos(%p, %p)", iRow, iCol ) );
if( s_fIsAnswer && s_bStdinConsole && s_bStdoutConsole )
{
hb_gt_pca_termOut( ( BYTE * ) "\x1B[6n", 4 );
hb_gt_pca_termFlush();
#if defined( HB_OS_UNIX ) || defined( __DJGPP__ )
{
char rdbuf[ 64 ];
int i, n, y, x;
struct timeval tv;
fd_set rdfds;
FD_ZERO( &rdfds );
FD_SET( s_hFilenoStdin, &rdfds );
tv.tv_sec = 2;
tv.tv_usec = 0;
*iRow = *iCol = -1;
n = 0;
s_fIsAnswer = FALSE;
while( select( s_hFilenoStdin + 1, &rdfds, NULL, NULL, &tv ) > 0 )
{
i = read( s_hFilenoStdin, rdbuf + n, sizeof( rdbuf ) - 1 - n );
if( i <= 0 )
break;
n += i;
if( n >= 6 )
{
rdbuf[ n ] = '\0';
if( sscanf( rdbuf, "\033[%d;%dR", &y, &x ) == 2 )
{
*iRow = y;
*iCol = x;
s_fIsAnswer = TRUE;
break;
}
}
}
if( ! s_fIsAnswer )
*iRow = *iCol = -1;
}
#else
{
USHORT ch, value = 0, index = 0;
do
{
ch = ( USHORT ) getc( stdin );
if( HB_ISDIGIT( ch ) )
{
value = ( value * 10 ) + ( ch - '0' );
}
else if( ch == ';' )
{
*iRow = value - 1;
value = 0;
}
}
while( ch != 'R' && index < 10 );
*iCol = value - 1;
s_fIsAnswer = ch == 'R' && *iCol != -1 && *iRow != -1;
}
#endif
}
}
static void hb_gt_pca_AnsiSetCursorPos( int iRow, int iCol )
{
HB_TRACE( HB_TR_DEBUG, ( "hb_gt_pca_AnsiSetCursorPos(%d, %d)", iRow, iCol ) );
if( s_iRow != iRow || s_iCol != iCol )
{
char buff[ 16 ];
hb_snprintf( buff, sizeof( buff ), "\x1B[%d;%dH", iRow + 1, iCol + 1 );
hb_gt_pca_termOut( ( BYTE * ) buff, ( int ) strlen( buff ) );
s_iRow = iRow;
s_iCol = iCol;
}
}
static void hb_gt_pca_AnsiSetCursorStyle( int iStyle )
{
HB_TRACE( HB_TR_DEBUG, ( "hb_gt_pca_AnsiSetCursorStyle(%d)", iStyle ) );
if( s_iCursorStyle != iStyle )
{
hb_gt_pca_termOut( ( BYTE * ) ( iStyle == SC_NONE ? "\x1B[?25l" :
"\x1B[?25h" ), 6 );
s_iCursorStyle = iStyle;
}
}
static void hb_gt_pca_AnsiSetAttributes( int iAttr )
{
HB_TRACE( HB_TR_DEBUG, ( "hb_gt_pca_AnsiSetAttributes(%d)", iAttr ) );
if( s_iCurrentSGR != iAttr )
{
int i, bg, fg, bold, blink;
BYTE buff[ 16 ];
i = 2;
buff[ 0 ] = 0x1b;
buff[ 1 ] = '[';
bg = s_AnsiColors[ ( iAttr >> 4 ) & 0x07 ];
fg = s_AnsiColors[ iAttr & 0x07 ];
bold = iAttr & 0x08 ? 1 : 0;
blink = iAttr & 0x80 ? 1 : 0;
if( s_iCurrentSGR == -1 )
{
buff[ i++ ] = '0';
buff[ i++ ] = ';';
if( bold )
{
buff[ i++ ] = '1';
buff[ i++ ] = ';';
}
if( blink )
{
buff[ i++ ] = '5';
buff[ i++ ] = ';';
}
buff[ i++ ] = '3';
buff[ i++ ] = '0' + ( BYTE ) fg;
buff[ i++ ] = ';';
buff[ i++ ] = '4';
buff[ i++ ] = '0' + ( BYTE ) bg;
buff[ i++ ] = 'm';
s_iBold = bold;
s_iBlink = blink;
s_iFgColor = fg;
s_iBgColor = bg;
}
else
{
if( s_iBold != bold )
{
if( ! bold )
buff[ i++ ] = '2';
buff[ i++ ] = '1';
buff[ i++ ] = ';';
s_iBold = bold;
}
if( s_iBlink != blink )
{
if( ! blink )
buff[ i++ ] = '2';
buff[ i++ ] = '5';
buff[ i++ ] = ';';
s_iBlink = blink;
}
if( s_iFgColor != fg )
{
buff[ i++ ] = '3';
buff[ i++ ] = '0' + ( BYTE ) fg;
buff[ i++ ] = ';';
s_iFgColor = fg;
}
if( s_iBgColor != bg )
{
buff[ i++ ] = '4';
buff[ i++ ] = '0' + ( BYTE ) bg;
buff[ i++ ] = ';';
s_iBgColor = bg;
}
buff[ i - 1 ] = 'm';
}
s_iCurrentSGR = iAttr;
if( i > 2 )
{
hb_gt_pca_termOut( buff, i );
}
}
}
static void hb_gt_pca_AnsiInit( void )
{
s_iCurrentSGR = s_iRow = s_iCol = s_iCursorStyle = s_iAM = -1;
}
static void hb_gt_pca_AnsiPutStr( int iRow, int iCol, BYTE bAttr, BYTE * pStr, int iLen )
{
HB_TRACE( HB_TR_DEBUG, ( "hb_gt_pca_AnsiPutStr(%d,%d,%hu,%p,%d)", iRow, iCol, bAttr, pStr, iLen ) );
hb_gt_pca_AnsiSetAttributes( bAttr );
hb_gt_pca_AnsiSetCursorPos( iRow, iCol );
hb_gt_pca_AnsiSetAutoMargin( 0 );
hb_gt_pca_termOut( pStr, iLen );
s_iCol += iLen;
}
static void hb_gt_pca_setKeyTrans( char * pSrcChars, char * pDstChars )
{
int i;
for( i = 0; i < 256; ++i )
s_keyTransTbl[ i ] = ( BYTE ) i;
if( pSrcChars && pDstChars )
{
BYTE c;
for( i = 0; i < 256 && ( c = ( BYTE ) pSrcChars[ i ] ) != 0; ++i )
s_keyTransTbl[ c ] = ( BYTE ) pDstChars[ i ];
}
}
static void hb_gt_pca_Init( PHB_GT pGT, HB_FHANDLE hFilenoStdin, HB_FHANDLE hFilenoStdout, HB_FHANDLE hFilenoStderr )
{
int iRows = 25, iCols = 80;
HB_TRACE( HB_TR_DEBUG, ( "hb_gt_pca_Init(%p,%p,%p,%p)", pGT, ( void * ) ( HB_PTRDIFF ) hFilenoStdin, ( void * ) ( HB_PTRDIFF ) hFilenoStdout, ( void * ) ( HB_PTRDIFF ) hFilenoStderr ) );
s_hFilenoStdin = hFilenoStdin;
s_hFilenoStdout = hFilenoStdout;
s_hFilenoStderr = hFilenoStderr;
s_bStdinConsole = hb_fsIsDevice( s_hFilenoStdin );
s_bStdoutConsole = hb_fsIsDevice( s_hFilenoStdout );
s_bStderrConsole = hb_fsIsDevice( s_hFilenoStderr );
s_cdpTerm = s_cdpHost = NULL;
s_fDispTrans = FALSE;
hb_gt_pca_setKeyTrans( NULL, NULL );
s_szCrLf = ( BYTE * ) hb_conNewLine();
s_ulCrLf = strlen( ( char * ) s_szCrLf );
hb_fsSetDevMode( s_hFilenoStdout, FD_BINARY );
HB_GTSUPER_INIT( pGT, hFilenoStdin, hFilenoStdout, hFilenoStderr );
/* SA_NOCLDSTOP in #if is a hack to detect POSIX compatible environment */
#if ( defined( HB_OS_UNIX ) || defined( __DJGPP__ ) ) && \
defined( SA_NOCLDSTOP )
s_fRestTTY = FALSE;
if( s_bStdinConsole )
{
#if defined( SIGTTOU )
struct sigaction act, old;
/* if( s_saved_TIO.c_lflag & TOSTOP ) != 0 */
sigaction( SIGTTOU, NULL, &old );
memcpy( &act, &old, sizeof( struct sigaction ) );
act.sa_handler = sig_handler;
/* do not use SA_RESTART - new Linux kernels will repeat the operation */
#if defined( SA_ONESHOT )
act.sa_flags = SA_ONESHOT;
#elif defined( SA_RESETHAND )
act.sa_flags = SA_RESETHAND;
#else
act.sa_flags = 0;
#endif
sigaction( SIGTTOU, &act, 0 );
#endif
s_fRestTTY = TRUE;
tcgetattr( hFilenoStdin, &s_saved_TIO );
memcpy( &s_curr_TIO, &s_saved_TIO, sizeof( struct termios ) );
/* atexit( restore_input_mode ); */
s_curr_TIO.c_lflag &= ~( ICANON | ECHO );
s_curr_TIO.c_iflag &= ~ICRNL;
s_curr_TIO.c_cc[ VMIN ] = 0;
s_curr_TIO.c_cc[ VTIME ] = 0;
tcsetattr( hFilenoStdin, TCSAFLUSH, &s_curr_TIO );
#if defined( SIGTTOU )
act.sa_handler = SIG_DFL;
sigaction( SIGTTOU, &old, NULL );
#endif
}
#ifdef TIOCGWINSZ
if( s_bStdoutConsole )
{
struct winsize win;
if( ioctl( hFilenoStdout, TIOCGWINSZ, ( char * ) &win ) != -1 )
{
iRows = win.ws_row;
iCols = win.ws_col;
}
}
#endif
#endif
if( s_iOutBufSize == 0 )
{
s_iOutBufIndex = 0;
s_iOutBufSize = 16384;
s_sOutBuf = ( BYTE * ) hb_xgrab( s_iOutBufSize );
}
HB_GTSELF_RESIZE( pGT, iRows, iCols );
HB_GTSELF_SETFLAG( pGT, HB_GTI_STDOUTCON, s_bStdoutConsole );
HB_GTSELF_SETFLAG( pGT, HB_GTI_STDERRCON, s_bStderrConsole );
hb_gt_pca_AnsiInit();
hb_gt_pca_AnsiGetCurPos( &s_iRow, &s_iCol );
}
static void hb_gt_pca_Exit( PHB_GT pGT )
{
HB_TRACE( HB_TR_DEBUG, ( "hb_gt_pca_Exit(%p)", pGT ) );
HB_GTSELF_REFRESH( pGT );
/* set default color */
hb_gt_pca_AnsiSetAttributes( 0x07 );
hb_gt_pca_AnsiSetCursorStyle( SC_NORMAL );
hb_gt_pca_AnsiSetAutoMargin( 1 );
hb_gt_pca_termFlush();
HB_GTSUPER_EXIT( pGT );
#if defined( HB_OS_UNIX ) || defined( __DJGPP__ )
if( s_fRestTTY )
tcsetattr( s_hFilenoStdin, TCSANOW, &s_saved_TIO );
#endif
if( s_iLineBufSize > 0 )
{
hb_xfree( s_sLineBuf );
s_iLineBufSize = 0;
}
if( s_iOutBufSize > 0 )
{
hb_xfree( s_sOutBuf );
s_iOutBufSize = s_iOutBufIndex = 0;
}
s_bStdinConsole = s_bStdoutConsole = s_bStderrConsole = FALSE;
}
static int hb_gt_pca_ReadKey( PHB_GT pGT, int iEventMask )
{
int ch = 0;
HB_TRACE( HB_TR_DEBUG, ( "hb_gt_pca_ReadKey(%p,%d)", pGT, iEventMask ) );
HB_SYMBOL_UNUSED( pGT );
HB_SYMBOL_UNUSED( iEventMask );
#if defined( HB_OS_OS2_GCC )
/* Read from the keyboard with no echo, no wait, and no SIGSEV on Ctrl-C */
ch = _read_kbd( 0, 0, 0 );
if( ch == 0 )
{
/* It's a function key lead-in, so read the function key scan code */
ch = _read_kbd( 0, 0, 0 );
if( ch != -1 )
ch += 256; /* If it's really a scan code, offset it */
}
/* _read_kbd() returns -1 for no key, the switch statement will handle
this. */
ch = hb_gt_dos_keyCodeTranslate( ch );
if( ch > 0 && ch <= 255 )
ch = s_keyTransTbl[ ch ];
#elif defined( HB_OS_UNIX ) || defined( __DJGPP__ )
{
struct timeval tv;
fd_set rfds;
tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO( &rfds );
FD_SET( s_hFilenoStdin, &rfds );
if( select( s_hFilenoStdin + 1, &rfds, NULL, NULL, &tv ) > 0 )
{
BYTE bChar;
if( hb_fsRead( s_hFilenoStdin, &bChar, 1 ) == 1 )
ch = s_keyTransTbl[ bChar ];
}
}
#elif defined( _MSC_VER ) && ! defined( HB_OS_WIN_CE )
if( s_bStdinConsole )
{
if( _kbhit() )
{
ch = _getch();
if( ( ch == 0 || ch == 224 ) && _kbhit() )
{
/* It was a function key lead-in code, so read the actual
function key and then offset it by 256 */
ch = _getch() + 256;
}
ch = hb_gt_dos_keyCodeTranslate( ch );
if( ch > 0 && ch <= 255 )
ch = s_keyTransTbl[ ch ];
}
}
else if( ! _eof( ( int ) s_hFilenoStdin ) )
{
BYTE bChar;
if( _read( ( int ) s_hFilenoStdin, &bChar, 1 ) == 1 )
ch = s_keyTransTbl[ bChar ];
}
#elif defined( HB_WIN32_IO )
if( ! s_bStdinConsole ||
WaitForSingleObject( ( HANDLE ) hb_fsGetOsHandle( s_hFilenoStdin ), 0 ) == 0x0000 )
{
BYTE bChar;
if( hb_fsRead( s_hFilenoStdin, &bChar, 1 ) == 1 )
ch = s_keyTransTbl[ bChar ];
}
#elif defined( __WATCOMC__ )
if( s_bStdinConsole )
{
if( kbhit() )
{
ch = getch();
if( ( ch == 0 || ch == 224 ) && kbhit() )
{
/* It was a function key lead-in code, so read the actual
function key and then offset it by 256 */
ch = getch() + 256;
}
ch = hb_gt_dos_keyCodeTranslate( ch );
if( ch > 0 && ch <= 255 )
ch = s_keyTransTbl[ ch ];
}
}
else if( ! eof( s_hFilenoStdin ) )
{
BYTE bChar;
if( read( s_hFilenoStdin, &bChar, 1 ) == 1 )
ch = s_keyTransTbl[ bChar ];
}
#else
{
int TODO; /* TODO: */
}
#endif
return ch;
}
static void hb_gt_pca_Tone( PHB_GT pGT, double dFrequency, double dDuration )
{
static double dLastSeconds = 0;
double dCurrentSeconds;
HB_TRACE( HB_TR_DEBUG, ( "hb_gt_pca_Tone(%p, %lf, %lf)", pGT, dFrequency, dDuration ) );
HB_SYMBOL_UNUSED( pGT );
/* Output an ASCII BEL character to cause a sound */
/* but throttle to max once per second, in case of sound */
/* effects prgs calling lots of short tone sequences in */
/* succession leading to BEL hell on the terminal */
dCurrentSeconds = hb_dateSeconds();
if( dCurrentSeconds < dLastSeconds || dCurrentSeconds - dLastSeconds > 0.5 )
{
hb_gt_pca_termOut( s_szBell, 1 );
dLastSeconds = dCurrentSeconds;
hb_gt_pca_termFlush();
}
HB_SYMBOL_UNUSED( dFrequency );
/* convert Clipper (DOS) timer tick units to seconds ( x / 18.2 ) */
hb_idleSleep( dDuration / 18.2 );
}
static void hb_gt_pca_Bell( PHB_GT pGT )
{
HB_TRACE( HB_TR_DEBUG, ( "hb_gt_pca_Bell(%p)", pGT ) );
HB_SYMBOL_UNUSED( pGT );
hb_gt_pca_termOut( s_szBell, 1 );
hb_gt_pca_termFlush();
}
static const char * hb_gt_pca_Version( PHB_GT pGT, int iType )
{
HB_TRACE( HB_TR_DEBUG, ( "hb_gt_pca_Version(%p,%d)", pGT, iType ) );
HB_SYMBOL_UNUSED( pGT );
if( iType == 0 )
return HB_GT_DRVNAME( HB_GT_NAME );
return "Harbour Terminal: PC ANSI";
}
static BOOL hb_gt_pca_Suspend( PHB_GT pGT )
{
HB_TRACE( HB_TR_DEBUG, ( "hb_gt_pca_Suspend(%p)", pGT ) );
HB_SYMBOL_UNUSED( pGT );
#if defined( HB_OS_UNIX ) || defined( __DJGPP__ )
if( s_fRestTTY )
{
tcsetattr( s_hFilenoStdin, TCSANOW, &s_saved_TIO );
}
#endif
/* Enable line wrap when cursor set after last column */
hb_gt_pca_AnsiSetAutoMargin( 1 );
return TRUE;
}
static BOOL hb_gt_pca_Resume( PHB_GT pGT )
{
HB_TRACE( HB_TR_DEBUG, ( "hb_gt_pca_Resume(%p)", pGT ) );
HB_SYMBOL_UNUSED( pGT );
#if defined( HB_OS_UNIX ) || defined( __DJGPP__ )
if( s_fRestTTY )
{
tcsetattr( s_hFilenoStdin, TCSANOW, &s_curr_TIO );
}
#endif
hb_gt_pca_AnsiInit();
return TRUE;
}
static BOOL hb_gt_pca_SetDispCP( PHB_GT pGT, const char * pszTermCDP, const char * pszHostCDP, BOOL fBox )
{
HB_TRACE( HB_TR_DEBUG, ( "hb_gt_pca_SetDispCP(%p,%s,%s,%d)", pGT, pszTermCDP, pszHostCDP, ( int ) fBox ) );
HB_GTSUPER_SETDISPCP( pGT, pszTermCDP, pszHostCDP, fBox );
#ifndef HB_CDP_SUPPORT_OFF
if( ! pszHostCDP )
pszHostCDP = hb_cdpID();
if( ! pszTermCDP )
pszTermCDP = pszHostCDP;
if( pszTermCDP && pszHostCDP )
{
s_cdpTerm = hb_cdpFind( pszTermCDP );
s_cdpHost = hb_cdpFind( pszHostCDP );
s_fDispTrans = s_cdpTerm && s_cdpHost && s_cdpTerm != s_cdpHost;
return TRUE;
}
#endif
return FALSE;
}
static BOOL hb_gt_pca_SetKeyCP( PHB_GT pGT, const char * pszTermCDP, const char * pszHostCDP )
{
HB_TRACE( HB_TR_DEBUG, ( "hb_gt_pca_SetKeyCP(%p,%s,%s)", pGT, pszTermCDP, pszHostCDP ) );
HB_GTSUPER_SETKEYCP( pGT, pszTermCDP, pszHostCDP );
#ifndef HB_CDP_SUPPORT_OFF
if( ! pszHostCDP )
pszHostCDP = hb_cdpID();
if( ! pszTermCDP )
pszTermCDP = pszHostCDP;
if( pszTermCDP && pszHostCDP )
{
PHB_CODEPAGE cdpTerm = hb_cdpFind( pszTermCDP ),
cdpHost = hb_cdpFind( pszHostCDP );
if( cdpTerm && cdpHost && cdpTerm != cdpHost &&
cdpTerm->nChars && cdpTerm->nChars == cdpHost->nChars )
{
char * pszHostLetters = ( char * ) hb_xgrab( cdpHost->nChars * 2 + 1 );
char * pszTermLetters = ( char * ) hb_xgrab( cdpTerm->nChars * 2 + 1 );
hb_strncpy( pszHostLetters, cdpHost->CharsUpper, cdpHost->nChars * 2 );
hb_strncat( pszHostLetters, cdpHost->CharsLower, cdpHost->nChars * 2 );
hb_strncpy( pszTermLetters, cdpTerm->CharsUpper, cdpTerm->nChars * 2 );
hb_strncat( pszTermLetters, cdpTerm->CharsLower, cdpTerm->nChars * 2 );
hb_gt_pca_setKeyTrans( pszTermLetters, pszHostLetters );
hb_xfree( pszHostLetters );
hb_xfree( pszTermLetters );
}
else
hb_gt_pca_setKeyTrans( NULL, NULL );
return TRUE;
}
#endif
return TRUE;
}
static void hb_gt_pca_Redraw( PHB_GT pGT, int iRow, int iCol, int iSize )
{
BYTE bColor, bAttr;
USHORT usChar;
int iLen = 0, iColor = 0;
HB_TRACE( HB_TR_DEBUG, ( "hb_gt_pca_Redraw(%p,%d,%d,%d)", pGT, iRow, iCol, iSize ) );
while( iSize-- )
{
if( ! HB_GTSELF_GETSCRCHAR( pGT, iRow, iCol + iLen, &bColor, &bAttr, &usChar ) )
break;
if( iLen == 0 )
iColor = bColor;
else if( iColor != bColor )
{
#ifndef HB_CDP_SUPPORT_OFF
if( s_fDispTrans )
hb_cdpnTranslate( ( char * ) s_sLineBuf, s_cdpHost, s_cdpTerm, iLen );
#endif
hb_gt_pca_AnsiPutStr( iRow, iCol, ( BYTE ) iColor, s_sLineBuf, iLen );
iCol += iLen;
iLen = 0;
iColor = bColor;
}
if( usChar < 32 || usChar == 127 )
usChar = '.';
s_sLineBuf[ iLen++ ] = ( BYTE ) usChar;
}
if( iLen )
{
#ifndef HB_CDP_SUPPORT_OFF
if( s_fDispTrans )
hb_cdpnTranslate( ( char * ) s_sLineBuf, s_cdpHost, s_cdpTerm, iLen );
#endif
hb_gt_pca_AnsiPutStr( iRow, iCol, ( BYTE ) iColor, s_sLineBuf, iLen );
}
}
static void hb_gt_pca_Refresh( PHB_GT pGT )
{
int iWidth, iHeight, iRow, iCol, iStyle;
HB_TRACE( HB_TR_DEBUG, ( "hb_gt_pca_Refresh(%p)", pGT ) );
HB_GTSELF_GETSIZE( pGT, &iHeight, &iWidth );
if( s_iLineBufSize == 0 )
{
s_sLineBuf = ( BYTE * ) hb_xgrab( iWidth );
s_iLineBufSize = iWidth;
}
else if( s_iLineBufSize != iWidth )
{
s_sLineBuf = ( BYTE * ) hb_xrealloc( s_sLineBuf, iWidth );
s_iLineBufSize = iWidth;
}
HB_GTSUPER_REFRESH( pGT );
HB_GTSELF_GETSCRCURSOR( pGT, &iRow, &iCol, &iStyle );
if( iStyle != SC_NONE )
{
if( iRow >= 0 && iCol >= 0 && iRow < iHeight && iCol < iWidth )
hb_gt_pca_AnsiSetCursorPos( iRow, iCol );
else
iStyle = SC_NONE;
}
hb_gt_pca_AnsiSetCursorStyle( iStyle );
hb_gt_pca_termFlush();
}
static BOOL hb_gt_pca_Info( PHB_GT pGT, int iType, PHB_GT_INFO pInfo )
{
HB_TRACE( HB_TR_DEBUG, ( "hb_gt_pca_Info(%p,%d,%p)", pGT, iType, pInfo ) );
switch( iType )
{
case HB_GTI_FULLSCREEN:
case HB_GTI_KBDSUPPORT:
pInfo->pResult = hb_itemPutL( pInfo->pResult, TRUE );
break;
default:
return HB_GTSUPER_INFO( pGT, iType, pInfo );
}
return TRUE;
}
static BOOL hb_gt_FuncInit( PHB_GT_FUNCS pFuncTable )
{
HB_TRACE( HB_TR_DEBUG, ( "hb_gt_FuncInit(%p)", pFuncTable ) );
pFuncTable->Init = hb_gt_pca_Init;
pFuncTable->Exit = hb_gt_pca_Exit;
pFuncTable->Redraw = hb_gt_pca_Redraw;
pFuncTable->Refresh = hb_gt_pca_Refresh;
pFuncTable->Version = hb_gt_pca_Version;
pFuncTable->Suspend = hb_gt_pca_Suspend;
pFuncTable->Resume = hb_gt_pca_Resume;
pFuncTable->SetDispCP = hb_gt_pca_SetDispCP;
pFuncTable->SetKeyCP = hb_gt_pca_SetKeyCP;
pFuncTable->Tone = hb_gt_pca_Tone;
pFuncTable->Bell = hb_gt_pca_Bell;
pFuncTable->Info = hb_gt_pca_Info;
pFuncTable->ReadKey = hb_gt_pca_ReadKey;
return TRUE;
}
/* ********************************************************************** */
static const HB_GT_INIT gtInit = { HB_GT_DRVNAME( HB_GT_NAME ),
hb_gt_FuncInit,
HB_GTSUPER,
HB_GTID_PTR };
HB_GT_ANNOUNCE( HB_GT_NAME )
HB_CALL_ON_STARTUP_BEGIN( _hb_startup_gt_Init_ )
hb_gtRegister( >Init );
HB_CALL_ON_STARTUP_END( _hb_startup_gt_Init_ )
#if defined( HB_PRAGMA_STARTUP )
#pragma startup _hb_startup_gt_Init_
#elif defined( HB_DATASEG_STARTUP )
#define HB_DATASEG_BODY HB_DATASEG_FUNC( _hb_startup_gt_Init_ )
#include "hbiniseg.h"
#endif
/* *********************************************************************** */
| xharbour/core | source/rtl/gtpca/gtpca.c | C | gpl-2.0 | 26,464 |
# -*- coding: utf-8 -*-
#
# This tool helps you rebase your package to the latest version
# Copyright (C) 2013-2019 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Authors: Petr Hráček <phracek@redhat.com>
# Tomáš Hozza <thozza@redhat.com>
# Nikola Forró <nforro@redhat.com>
# František Nečas <fifinecas@seznam.cz>
import logging
from typing import cast
from rebasehelper.logger import CustomLogger
logger: CustomLogger = cast(CustomLogger, logging.getLogger(__name__))
class InputHelper:
"""Class for command line interaction with the user."""
@staticmethod
def strtobool(message):
"""Converts a user message to a corresponding truth value.
This method is a replacement for deprecated strtobool from distutils,
its behaviour remains the same.
Args:
message (str): Message to evaluate.
Returns:
bool: True on 'y', 'yes', 't', 'true', 'on' and '1'.
False on 'n', 'no', 'f', 'false', 'off' and '0'.
Raises:
ValueError: On any other value.
"""
message = message.lower()
if message in ('y', 'yes', 't', 'true', 'on', '1'):
return True
elif message in ('n', 'no', 'f', 'false', 'off', '0'):
return False
raise ValueError('No conversion to truth value for "{}"'.format(message))
@classmethod
def get_message(cls, message, default_yes=True, any_input=False):
"""Prompts a user with yes/no message and gets the response.
Args:
message (str): Prompt string.
default_yes (bool): If the default value should be YES.
any_input (bool): Whether to return default value regardless of input.
Returns:
bool: True or False, based on user's input.
"""
if default_yes:
choice = '[Y/n]'
else:
choice = '[y/N]'
if any_input:
msg = '{0} '.format(message)
else:
msg = '{0} {1}? '.format(message, choice)
while True:
user_input = input(msg).lower()
if not user_input or any_input:
return True if default_yes else False
try:
user_input = cls.strtobool(user_input)
except ValueError:
logger.error('You have to type y(es) or n(o).')
continue
if any_input:
return True
else:
return bool(user_input)
| rebase-helper/rebase-helper | rebasehelper/helpers/input_helper.py | Python | gpl-2.0 | 3,222 |
<ul class="nav nav-tabs nav-small border-bottom-0">
<li class="nav-item mr-2 text-dark">
<a {%
if select in ['overview', 'commits', 'tree', 'tags', 'branches', 'forks'] %}class="nav-link active" {%
else %}class="nav-link" {%
endif %}href="{{ url_for(
'ui_ns.view_repo',
repo=repo.name,
username=username,
namespace=repo.namespace) }}">
<i class="fa fa-code fa-fw text-muted"></i>
<span class="d-none d-md-inline">Source</span>
</a>
</li>
{% if config['DOC_APP_URL'] and repo and repo.settings.get('project_documentation', True) %}
<li class="nav-item mr-2 text-dark" >
<a {%
if select == 'docs' %}class="active nav-link" {%
else %}class="nav-link" {%
endif %}href="{{ url_for(
'ui_ns.view_docs',
repo=repo.name,
username=username,
namespace=repo.namespace) }}">
<i class="fa fa-book fa-fw text-muted"></i>
<span class="d-none d-md-inline">Docs</span>
</a>
</li>
{% endif %}
{% if repo.namespace in ['rpms', 'container', 'modules'] %}
<li class="nav-item mr-2 text-dark">
{% if repo.namespace == 'rpms' %}
<a class="nav-link" href="https://bugzilla.redhat.com/buglist.cgi?bug_status=NEW&bug_status=ASSIGNED&classification=Fedora&product=Fedora&component={{ repo.name }}">
{% elif repo.namespace == 'container' %}
<a class="nav-link" href="https://bugzilla.redhat.com/buglist.cgi?bug_status=NEW&bug_status=ASSIGNED&classification=Fedora&product=Fedora Container Images&component={{ repo.name }}">
{% elif repo.namespace == 'modules' %}
<a class="nav-link" href="https://bugzilla.redhat.com/buglist.cgi?bug_status=NEW&bug_status=ASSIGNED&classification=Fedora&product=Fedora Modules&component={{ repo.name }}">
{% endif %}
<i class="fa fa-fw text-muted fa-exclamation-circle"></i>
<span class="d-none d-md-inline">Issues </span>
<span class="fa fa-external-link"></span>
</a>
</li>
{% elif g.issues_enabled %}
<li class="nav-item mr-2 text-dark">
<a {%
if select == 'issues' %}class="active nav-link" {%
else %}class="nav-link" {%
endif %}href="{{ url_for(
'ui_ns.view_issues',
repo=repo.name,
username=username,
namespace=repo.namespace) }}">
<i class="fa fa-fw text-muted fa-exclamation-circle"></i>
<span class="d-none d-md-inline">Issues </span>
<span class="badge badge-secondary py-0 d-none d-md-inline">
{{ repo.open_tickets if g.repo_committer else repo.open_tickets_public }}
</span>
</a>
</li>
{% endif %}
{% if repo and repo.settings.get('pull_requests', True) %}
<li class="nav-item mr-2 text-dark">
<a {%
if select == 'requests' %}class="active nav-link" {%
else %}class="nav-link" {%
endif %}href="{{ url_for(
'ui_ns.request_pulls',
repo=repo.name,
username=username,
namespace=repo.namespace) }}">
<i class="fa fa-fw text-muted fa-arrow-circle-down"></i>
<span class="d-none d-md-inline">Pull Requests </span>
<span class="badge badge-secondary py-0 d-none d-md-inline">
{{ repo.open_requests }}
</span>
</a>
</li>
{% endif %}
{% if g.issues_enabled and repo.milestones %}
<li class="nav-item mr-2 text-dark">
<a {%
if select == 'roadmap' %}class="active nav-link" {%
else %}class="nav-link" {%
endif %} href="{{ url_for(
'ui_ns.view_roadmap',
repo=repo.name,
username=username,
namespace=repo.namespace) }}"
class="btn btn-outline-dark btn-sm">
<i class="fa fa-fw text-muted fa-map-signs"></i>
<span class="d-none d-md-inline">Roadmap </span>
</a>
</li>
{% endif %}
<li class="nav-item mr-2 text-dark">
<a {%
if select == 'stats' %}class="active nav-link" {%
else %}class="nav-link" {%
endif %}href="{{ url_for(
'ui_ns.view_stats',
repo=repo.name,
username=username,
namespace=repo.namespace) }}">
<i class="fa fa-line-chart fa-fw text-muted"></i>
<span class="d-none d-md-inline">Stats</span>
</a>
</li>
{% if g.authenticated %}
{% if g.repo_admin %}
<li class="nav-item mr-2 text-dark">
<a title="Settings" {%
if select == 'settings' %}class="active nav-link" {%
else %}class="nav-link" {%
endif %}href="{{ url_for(
'ui_ns.view_settings',
repo=repo.name,
username=username,
namespace=repo.namespace) }}">
<i class="fa fa-cogs fa-fw text-muted"></i>
<span class="d-none d-md-inline">Settings</span>
</a>
</li>
{% endif %}
{% endif %}
{% if endpoint == 'view_docs' %}
<li class="nav-item pull-xs-right">
<a class="nav-link" href="{{ config['DOC_APP_URL'] + url_for(
'ui_ns.view_repo',
repo=repo.namespace + '.' + repo.name if repo.namespace else repo.name,
username=username,
filename=filename)
}}" target="_blank" title="Open to a new tab" rel="noopener noreferrer">
<span class="fa fa-external-link"></span>
</a>
</li>
{% endif %}
</ul>
| pypingou/pagure | pagure/themes/srcfpo/templates/repo_master_navbar.html | HTML | gpl-2.0 | 5,543 |
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2008 Louis Pasteur University / Telecom Bretagne
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Angelos Chatzipapas <Angelos.CHATZIPAPAS@enst-bretagne.fr> /
* <chatzipa@ceid.upatras.gr>
*/
#include "ns3/log.h"
//#include "ns3/ipv6.h"
#include "ns3/ipv6-address.h"
#include "ns3/node.h"
#include "ns3/mac48-address.h"
NS_LOG_COMPONENT_DEFINE ("TestIpv6");
using namespace ns3;
int
main (int argc, char *argv[])
{
LogComponentEnable ("TestIpv6", LOG_LEVEL_ALL);
NS_LOG_INFO ("Test Ipv6");
Mac48Address m_addresses[10];
m_addresses[0]=("00:00:00:00:00:01");
m_addresses[1]=("00:00:00:00:00:02");
m_addresses[2]=("00:00:00:00:00:03");
m_addresses[3]=("00:00:00:00:00:04");
m_addresses[4]=("00:00:00:00:00:05");
m_addresses[5]=("00:00:00:00:00:06");
m_addresses[6]=("00:00:00:00:00:07");
m_addresses[7]=("00:00:00:00:00:08");
m_addresses[8]=("00:00:00:00:00:09");
m_addresses[9]=("00:00:00:00:00:10");
Ipv6Address prefix1 ("2001:1::");
NS_LOG_INFO ("prefix = " << prefix1);
for (uint32_t i = 0; i < 10 ; ++i)
{
NS_LOG_INFO ("address = " <<m_addresses[i]);
Ipv6Address ipv6address=Ipv6Address::MakeAutoconfiguredAddress(m_addresses[i], prefix1);
NS_LOG_INFO ("address = " <<ipv6address);
}
Ipv6Address prefix2 ("2002:1:1::");
NS_LOG_INFO ("prefix = " << prefix2);
for (uint32_t i = 0; i < 10 ; ++i)
{
Ipv6Address ipv6address=Ipv6Address::MakeAutoconfiguredAddress(m_addresses[i], prefix2);
NS_LOG_INFO ("address = " <<ipv6address);
}
}
| AliZafar120/NetworkStimulatorSPl3 | examples/test-ipv6.cc | C++ | gpl-2.0 | 2,235 |
import Ember from 'ember';
export default Ember.Route.extend({
/**
* Instance of the posts service.
*
* @property postsService
* @type {Ember.Service}
*/
postsService: Ember.inject.service('posts'),
/**
* Instance of the tags service.
*
* @property tagsService
* @type {Ember.Service}
*/
tagsService: Ember.inject.service('tags'),
/**
* Instance of the types service.
*
* @property typesService
* @type {Ember.Service}
*/
typesService: Ember.inject.service('types'),
/**
* Instance of the images service.
*
* @property imagesService
* @type {Ember.Service}
*/
imagesService: Ember.inject.service('images'),
/**
* Instance of the alerts service.
*
* @property alertsService
* @type {Ember.Service}
*/
alertsService: Ember.inject.service('alerts'),
beforeModel() {
// Preload images tags and types
let promises = [
this.get('tagsService').getAll(),
this.get('typesService').getAll(),
this.get('imagesService').getAll()
];
return Ember.RSVP.all(promises);
},
model() {
return {
post: this.get('postsService').createNew()
};
},
actions: {
/**
* View specified post page.
*
* @method viewPost
* @return {Void}
*/
viewPost(id) {
this.get('alertsService').success('Your post has been saved');
this.transitionTo('post', { postId: id });
}
}
});
| WattyRev/wattyrev | wattyrev-admin/app/routes/new-post.js | JavaScript | gpl-2.0 | 1,623 |
<?php
add_action( 'pending_to_publish', 'clpr_handle_moderated_transaction' );
add_action( 'appthemes_transaction_completed', 'clpr_handle_transaction_completed' );
add_action( 'appthemes_transaction_activated', 'clpr_handle_coupon_listing' );
function clpr_handle_transaction_completed( $order ) {
global $clpr_options;
$coupon_id = _clpr_get_order_coupon_id( $order );
$coupon_url = get_permalink( $coupon_id );
$order_url = get_permalink( $order->get_id() );
if ( ! $clpr_options->coupons_require_moderation ) {
$order->activate();
if ( ! is_admin() )
clpr_js_redirect( $coupon_url );
return;
} else {
clpr_update_post_status( $coupon_id, 'pending' );
if ( ! is_admin() )
clpr_js_redirect( $order_url );
return;
}
}
function clpr_handle_moderated_transaction( $post ) {
if ( $post->post_type != APP_POST_TYPE )
return;
$orders_post = _appthemes_orders_get_connected( $post->ID );
if ( ! $orders_post->posts ){
return;
}
$order = appthemes_get_order( $orders_post->post->ID );
if ( ! $order || $order->get_status() !== APPTHEMES_ORDER_COMPLETED )
return;
add_action( 'save_post', 'clpr_activate_moderated_transaction', 11 );
}
function clpr_activate_moderated_transaction( $post_id ) {
$orders_post = _appthemes_orders_get_connected( $post_id );
if ( ! $orders_post->posts ) {
return;
}
$order = appthemes_get_order( $orders_post->post->ID );
if ( ! $order || $order->get_status() !== APPTHEMES_ORDER_COMPLETED )
return;
$order->activate();
}
function clpr_handle_coupon_listing( $order ) {
foreach( $order->get_items( CLPR_COUPON_LISTING_TYPE ) as $item ) {
clpr_update_post_status( $item['post_id'], 'publish' );
}
}
function _clpr_get_order_coupon_id( $order ) {
$item = $order->get_item();
return $item['post_id'];
}
function clpr_js_redirect( $url, $message = '' ) {
if ( empty( $message ) )
$message = __( 'Continue', APP_TD );
echo html( 'a', array( 'href' => $url ), $message );
echo html( 'script', 'location.href="' . $url . '"' );
}
function clpr_payments_is_enabled() {
global $clpr_options;
if ( ! current_theme_supports( 'app-payments' ) || ! current_theme_supports( 'app-price-format' ) )
return false;
if ( ! $clpr_options->charge_coupons || ! is_numeric( $clpr_options->coupon_price ) )
return false;
return true;
}
function clpr_have_pending_payment( $post_id ) {
if ( ! clpr_payments_is_enabled() )
return false;
$orders_post = _appthemes_orders_get_connected( $post_id );
if ( ! $orders_post->posts )
return false;
$order = appthemes_get_order( $orders_post->post->ID );
if ( ! $order || ! in_array( $order->get_status(), array( APPTHEMES_ORDER_PENDING, APPTHEMES_ORDER_FAILED ) ) )
return false;
return true;
}
function clpr_get_order_permalink( $post_id ) {
if ( ! clpr_payments_is_enabled() )
return;
$orders_post = _appthemes_orders_get_connected( $post_id );
if ( ! $orders_post->posts )
return;
$order = appthemes_get_order( $orders_post->post->ID );
if ( ! $order )
return;
return get_permalink( $order->get_id() );
}
function clpr_get_order_gateway_name( $order ) {
if ( ! clpr_payments_is_enabled() )
return;
$gateway_id = $order->get_gateway();
if ( ! empty( $gateway_id ) ) {
$gateway = APP_Gateway_Registry::get_gateway( $gateway_id );
if ( $gateway ) {
$gateway_name = $gateway->display_name( 'admin' );
} else {
$gateway_name = __( 'Unknown', APP_TD );
}
} else {
$gateway_name = __( 'Undecided', APP_TD );
}
return $gateway_name;
}
function clpr_display_ordered_items( $order ) {
if ( ! clpr_payments_is_enabled() )
return;
$items = $order->get_items();
foreach( $items as $item ) {
if ( ! APP_Item_Registry::is_registered( $item['type'] ) ) {
$item_title = __( 'Unknown', APP_TD );
} else {
$item_title = APP_Item_Registry::get_title( $item['type'] );
}
echo html( 'div', $item_title );
}
}
| FelixNong1990/coupon | wp-content/themes/clipper/includes/payments.php | PHP | gpl-2.0 | 3,911 |
/*
** Authored by Timothy Gerard Endres
** <mailto:time@gjt.org> <http://www.trustice.com>
**
** This work has been placed into the public domain.
** You may use this work in any way and for any purpose you wish.
**
** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND,
** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR
** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY
** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR
** REDISTRIBUTION OF THIS SOFTWARE.
**
*/
package com.ice.tar;
import java.io.*;
/**
* The TarBuffer class implements the tar archive concept
* of a buffered input stream. This concept goes back to the
* days of blocked tape drives and special io devices. In the
* Java universe, the only real function that this class
* performs is to ensure that files have the correct "block"
* size, or other tars will complain.
* <p>
* You should never have a need to access this class directly.
* TarBuffers are created by Tar IO Streams.
*
* @version $Revision: 1.10 $
* @author Timothy Gerard Endres,
* <a href="mailto:time@gjt.org">time@trustice.com</a>.
* @see TarArchive
*/
public
class TarBuffer
extends Object
{
public static final int DEFAULT_RCDSIZE = ( 512 );
public static final int DEFAULT_BLKSIZE = ( DEFAULT_RCDSIZE * 20 );
private InputStream inStream;
private OutputStream outStream;
private byte[] blockBuffer;
private int currBlkIdx;
private int currRecIdx;
private int blockSize;
private int recordSize;
private int recsPerBlock;
private boolean debug;
public
TarBuffer( InputStream inStream )
{
this( inStream, TarBuffer.DEFAULT_BLKSIZE );
}
public
TarBuffer( InputStream inStream, int blockSize )
{
this( inStream, blockSize, TarBuffer.DEFAULT_RCDSIZE );
}
public
TarBuffer( InputStream inStream, int blockSize, int recordSize )
{
this.inStream = inStream;
this.outStream = null;
this.initialize( blockSize, recordSize );
}
public
TarBuffer( OutputStream outStream )
{
this( outStream, TarBuffer.DEFAULT_BLKSIZE );
}
public
TarBuffer( OutputStream outStream, int blockSize )
{
this( outStream, blockSize, TarBuffer.DEFAULT_RCDSIZE );
}
public
TarBuffer( OutputStream outStream, int blockSize, int recordSize )
{
this.inStream = null;
this.outStream = outStream;
this.initialize( blockSize, recordSize );
}
/**
* Initialization common to all constructors.
*/
private void
initialize( int blockSize, int recordSize )
{
this.debug = false;
this.blockSize = blockSize;
this.recordSize = recordSize;
this.recsPerBlock = ( this.blockSize / this.recordSize );
this.blockBuffer = new byte[ this.blockSize ];
if ( this.inStream != null )
{
this.currBlkIdx = -1;
this.currRecIdx = this.recsPerBlock;
}
else
{
this.currBlkIdx = 0;
this.currRecIdx = 0;
}
}
/**
* Get the TAR Buffer's block size. Blocks consist of multiple records.
*/
public int
getBlockSize()
{
return this.blockSize;
}
/**
* Get the TAR Buffer's record size.
*/
public int
getRecordSize()
{
return this.recordSize;
}
/**
* Set the debugging flag for the buffer.
*
* @param debug If true, print debugging output.
*/
public void
setDebug( boolean debug )
{
this.debug = debug;
}
/**
* Determine if an archive record indicate End of Archive. End of
* archive is indicated by a record that consists entirely of null bytes.
*
* @param record The record data to check.
*/
public boolean
isEOFRecord( byte[] record )
{
for ( int i = 0, sz = this.getRecordSize() ; i < sz ; ++i )
if ( record[i] != 0 )
return false;
return true;
}
/**
* Skip over a record on the input stream.
*/
public void
skipRecord()
throws IOException
{
if ( this.debug )
{
System.err.println
( "SkipRecord: recIdx = " + this.currRecIdx
+ " blkIdx = " + this.currBlkIdx );
}
if ( this.inStream == null )
throw new IOException
( "reading (via skip) from an output buffer" );
if ( this.currRecIdx >= this.recsPerBlock )
{
if ( ! this.readBlock() )
return; // UNDONE
}
this.currRecIdx++;
}
/**
* Read a record from the input stream and return the data.
*
* @return The record data.
*/
public byte[]
readRecord()
throws IOException
{
if ( this.debug )
{
System.err.println
( "ReadRecord: recIdx = " + this.currRecIdx
+ " blkIdx = " + this.currBlkIdx );
}
if ( this.inStream == null )
throw new IOException
( "reading from an output buffer" );
if ( this.currRecIdx >= this.recsPerBlock )
{
if ( ! this.readBlock() )
return null;
}
byte[] result = new byte[ this.recordSize ];
System.arraycopy(
this.blockBuffer, (this.currRecIdx * this.recordSize),
result, 0, this.recordSize );
this.currRecIdx++;
return result;
}
/**
* @return false if End-Of-File, else true
*/
private boolean
readBlock()
throws IOException
{
if ( this.debug )
{
System.err.println
( "ReadBlock: blkIdx = " + this.currBlkIdx );
}
if ( this.inStream == null )
throw new IOException
( "reading from an output buffer" );
this.currRecIdx = 0;
int offset = 0;
int bytesNeeded = this.blockSize;
for ( ; bytesNeeded > 0 ; )
{
long numBytes =
this.inStream.read
( this.blockBuffer, offset, bytesNeeded );
//
// NOTE
// We have fit EOF, and the block is not full!
//
// This is a broken archive. It does not follow the standard
// blocking algorithm. However, because we are generous, and
// it requires little effort, we will simply ignore the error
// and continue as if the entire block were read. This does
// not appear to break anything upstream. We used to return
// false in this case.
//
// Thanks to 'Yohann.Roussel@alcatel.fr' for this fix.
//
if ( numBytes == -1 )
break;
offset += numBytes;
bytesNeeded -= numBytes;
if ( numBytes != this.blockSize )
{
if ( this.debug )
{
System.err.println
( "ReadBlock: INCOMPLETE READ " + numBytes
+ " of " + this.blockSize + " bytes read." );
}
}
}
this.currBlkIdx++;
return true;
}
/**
* Get the current block number, zero based.
*
* @return The current zero based block number.
*/
public int
getCurrentBlockNum()
{
return this.currBlkIdx;
}
/**
* Get the current record number, within the current block, zero based.
* Thus, current offset = (currentBlockNum * recsPerBlk) + currentRecNum.
*
* @return The current zero based record number.
*/
public int
getCurrentRecordNum()
{
return this.currRecIdx - 1;
}
/**
* Write an archive record to the archive.
*
* @param record The record data to write to the archive.
*/
public void
writeRecord( byte[] record )
throws IOException
{
if ( this.debug )
{
System.err.println
( "WriteRecord: recIdx = " + this.currRecIdx
+ " blkIdx = " + this.currBlkIdx );
}
if ( this.outStream == null )
throw new IOException
( "writing to an input buffer" );
if ( record.length != this.recordSize )
throw new IOException
( "record to write has length '" + record.length
+ "' which is not the record size of '"
+ this.recordSize + "'" );
if ( this.currRecIdx >= this.recsPerBlock )
{
this.writeBlock();
}
System.arraycopy(
record, 0,
this.blockBuffer, (this.currRecIdx * this.recordSize),
this.recordSize );
this.currRecIdx++;
}
/**
* Write an archive record to the archive, where the record may be
* inside of a larger array buffer. The buffer must be "offset plus
* record size" long.
*
* @param buf The buffer containing the record data to write.
* @param offset The offset of the record data within buf.
*/
public void
writeRecord( byte[] buf, int offset )
throws IOException
{
if ( this.debug )
{
System.err.println
( "WriteRecord: recIdx = " + this.currRecIdx
+ " blkIdx = " + this.currBlkIdx );
}
if ( this.outStream == null )
throw new IOException
( "writing to an input buffer" );
if ( (offset + this.recordSize) > buf.length )
throw new IOException
( "record has length '" + buf.length
+ "' with offset '" + offset
+ "' which is less than the record size of '"
+ this.recordSize + "'" );
if ( this.currRecIdx >= this.recsPerBlock )
{
this.writeBlock();
}
System.arraycopy(
buf, offset,
this.blockBuffer, (this.currRecIdx * this.recordSize),
this.recordSize );
this.currRecIdx++;
}
/**
* Write a TarBuffer block to the archive.
*/
private void
writeBlock()
throws IOException
{
if ( this.debug )
{
System.err.println
( "WriteBlock: blkIdx = " + this.currBlkIdx );
}
if ( this.outStream == null )
throw new IOException
( "writing to an input buffer" );
this.outStream.write( this.blockBuffer, 0, this.blockSize );
this.outStream.flush();
this.currRecIdx = 0;
this.currBlkIdx++;
}
/**
* Flush the current data block if it has any data in it.
*/
private void
flushBlock()
throws IOException
{
if ( this.debug )
{
System.err.println( "TarBuffer.flushBlock() called." );
}
if ( this.outStream == null )
throw new IOException
( "writing to an input buffer" );
// Thanks to 'Todd Kofford <tkofford@bigfoot.com>' for this patch.
// Use a buffer initialized with 0s to initialize everything in the
// blockBuffer after the last current, complete record. This prevents
// any previous data that might have previously existed in the
// blockBuffer from being written to the file.
if ( this.currRecIdx > 0 )
{
int offset = this.currRecIdx * this.recordSize;
byte[] zeroBuffer = new byte[ this.blockSize - offset ];
System.arraycopy
( zeroBuffer, 0, this.blockBuffer, offset, zeroBuffer.length );
this.writeBlock();
}
}
/**
* Close the TarBuffer. If this is an output buffer, also flush the
* current block before closing.
*/
public void
close()
throws IOException
{
if ( this.debug )
{
System.err.println( "TarBuffer.closeBuffer()." );
}
if ( this.outStream != null )
{
this.flushBlock();
if ( this.outStream != System.out
&& this.outStream != System.err )
{
this.outStream.close();
this.outStream = null;
}
}
else if ( this.inStream != null )
{
if ( this.inStream != System.in )
{
this.inStream.close();
this.inStream = null;
}
}
}
}
| pltxtra/libvuknob | src_jar/com/ice/tar/TarBuffer.java | Java | gpl-2.0 | 10,583 |
//
// BRWallet.h
// BreadWallet
//
// Created by Aaron Voisine on 5/12/13.
// Copyright (c) 2013 Aaron Voisine <voisine@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "BRKeySequence.h"
#define BRWalletBalanceChangedNotification @"BRWalletBalanceChangedNotification"
@class BRTransaction;
@interface BRWallet : NSObject
@property (nonatomic, readonly) uint64_t balance;
@property (nonatomic, readonly) NSString *receiveAddress; // returns the first unused external address
@property (nonatomic, readonly) NSString *changeAddress; // returns the first unused internal address
@property (nonatomic, readonly) NSSet *addresses; // all previously generated internal and external addresses
@property (nonatomic, readonly) NSArray *unspentOutputs; // NSData objects containing serialized UTXOs
@property (nonatomic, readonly) NSArray *recentTransactions; // BRTransaction objects sorted by date, most recent first
- (instancetype)initWithContext:(NSManagedObjectContext *)context sequence:(id<BRKeySequence>)sequence
seed:(NSData *(^)())seed;
// true if the address is known to belong to the wallet
- (BOOL)containsAddress:(NSString *)address;
// Wallets are composed of chains of addresses. Each chain is traversed until a gap of a certain number of addresses is
// found that haven't been used in any transactions. This method returns an array of <gapLimit> unused addresses
// following the last used address in the chain. The internal chain is used for change addresses and the external chain
// for receive addresses.
- (NSArray *)addressesWithGapLimit:(NSUInteger)gapLimit internal:(BOOL)internal;
// returns an unsigned transaction that sends the specified amount from the wallet to the given address
- (BRTransaction *)transactionFor:(uint64_t)amount to:(NSString *)address withFee:(BOOL)fee;
// returns an unsigned transaction that sends the specified amounts from the wallet to the specified output scripts
- (BRTransaction *)transactionForAmounts:(NSArray *)amounts toOutputScripts:(NSArray *)scripts withFee:(BOOL)fee;
// sign any inputs in the given transaction that can be signed using private keys from the wallet
- (BOOL)signTransaction:(BRTransaction *)transaction;
// true if the given transaction is associated with the wallet (even if it hasn't been registered), false otherwise
- (BOOL)containsTransaction:(BRTransaction *)transaction;
// adds a transaction to the wallet, or returns false if it isn't associated with the wallet
- (BOOL)registerTransaction:(BRTransaction *)transaction;
// removes a transaction from the wallet along with any transactions that depend on its outputs
- (void)removeTransaction:(NSData *)txHash;
// true if the given transaction has been added to the wallet
- (BOOL)transactionIsRegistered:(NSData *)txHash;
// true if no previous wallet transaction spends any of the given transaction's inputs, and no input tx is invalid
- (BOOL)transactionIsValid:(BRTransaction *)transaction;
// returns true if transaction won't be valid by blockHeight + 1 or within the next 10 minutes
- (BOOL)transactionIsPending:(BRTransaction *)transaction atBlockHeight:(uint32_t)blockHeight;
// set the block heights for the given transactions
- (void)setBlockHeight:(int32_t)height forTxHashes:(NSArray *)txHashes;
// returns the amount received to the wallet by the transaction (total outputs to change and/or recieve addresses)
- (uint64_t)amountReceivedFromTransaction:(BRTransaction *)transaction;
// retuns the amount sent from the wallet by the trasaction (total wallet outputs consumed, change and fee included)
- (uint64_t)amountSentByTransaction:(BRTransaction *)transaction;
// returns the fee for the given transaction if all its inputs are from wallet transactions, UINT64_MAX otherwise
- (uint64_t)feeForTransaction:(BRTransaction *)transaction;
// returns the first non-change output address for sends, first input address for receives, or nil if unkown
- (NSString *)addressForTransaction:(BRTransaction *)transaction;
// historical wallet balance after the given transaction, or current balance if transaction is not registered in wallet
- (uint64_t)balanceAfterTransaction:(BRTransaction *)transaction;
// returns the block height after which the transaction is likely to be processed without including a fee
- (uint32_t)blockHeightUntilFree:(BRTransaction *)transaction;
@end | bsimic0001/AegisWalletIOS | Aegis Bitcoin Wallet/Aegis Bitcoin Wallet/BRWallet.h | C | gpl-2.0 | 5,442 |
{
base: 'az_circle_counter',
name: Drupal.t('Circle counter'),
icon: 'et et-icon-speedometer',
// description: Drupal.t('Infographic Counter'),
params: [{
type: 'colorpicker',
heading: Drupal.t('Foreground color'),
param_name: 'fgcolor',
value: '#333333',
}, {
type: 'colorpicker',
heading: Drupal.t('Background color'),
param_name: 'bgcolor',
value: '#999999',
}, {
type: 'colorpicker',
heading: Drupal.t('Fill'),
param_name: 'fill',
}, {
type: 'checkbox',
heading: Drupal.t('Half Circle'),
param_name: 'type',
value: {
'half': Drupal.t("Yes"),
},
}, {
type: 'bootstrap_slider',
heading: Drupal.t('Dimension'),
param_name: 'dimension',
max: '500',
value: '250',
}, {
type: 'textfield',
heading: Drupal.t('Text'),
param_name: 'text',
tab: Drupal.t('Circle content'),
}, {
type: 'bootstrap_slider',
heading: Drupal.t('Font size'),
param_name: 'fontsize',
max: '100',
value: '16',
formatter: true,
tab: Drupal.t('Circle content'),
}, {
type: 'textfield',
heading: Drupal.t('Info'),
param_name: 'info',
tab: Drupal.t('Circle content'),
}, {
type: 'bootstrap_slider',
heading: Drupal.t('Width'),
param_name: 'width',
max: '100',
value: '5',
}, {
type: 'bootstrap_slider',
heading: Drupal.t('Percent'),
param_name: 'percent',
max: '100',
value: '50',
}, {
type: 'dropdown',
heading: Drupal.t('Border style'),
param_name: 'border',
value: {
'default': Drupal.t('Default'),
'inline': Drupal.t('Inline'),
'outline': Drupal.t('Outline'),
},
}, {
type: 'icon',
heading: Drupal.t('Icon'),
param_name: 'icon',
tab: Drupal.t('Icon'),
}, {
type: 'bootstrap_slider',
heading: Drupal.t('Icon size'),
param_name: 'icon_size',
max: '100',
description: Drupal.t('Will set the font size of the icon.'),
value: '16',
tab: Drupal.t('Icon'),
}, {
type: 'colorpicker',
heading: Drupal.t('Icon color'),
param_name: 'icon_color',
description: Drupal.t('Will set the font color of the icon.'),
tab: Drupal.t('Icon'),
}, ],
show_settings_on_create: true,
frontend_render: true,
showed: function($) {
this.baseclass.prototype.showed.apply(this, arguments);
var icon_set = this.attrs['icon'].charAt(0);
switch (icon_set) {
case 'e':
this.add_css('vendor/et-line-font/et-line-font.css', 'ETLineFont' in $.fn, function() {});
break;
case 'f':
this.add_css('vendor/font-awesome/css/font-awesome.min.css', 'fontAwesome' in $.fn, function() {});
break;
case 'p':
this.add_css('vendor/pe-icon-7-stroke/css/pe-icon-7-stroke.css', 'PELineFont' in $.fn, function() {});
break;
default:
break;
}
var element = this;
this.add_css('vendor/jquery.circliful/css/jquery.circliful.css', 'circliful' in $.fn, function() {});
this.add_js_list({
paths: ['vendor/jquery.circliful/js/jquery.circliful.min.js',
'vendor/jquery.waypoints/lib/jquery.waypoints.min.js'
],
loaded: 'waypoint' in $.fn && 'circliful' in $.fn,
callback: function() {
$(element.dom_element).waypoint(function(direction) {
$(element.dom_element).find('#' + element.id).once().circliful();
}, {
offset: '100%',
handler: function(direction) {
this.destroy()
},
});
$(document).trigger('scroll');
}
});
},
render: function($) {
if (this.attrs['icon']) {
var circliful_icon = '" data-icon=" ' + this.attrs['icon'] + '" data-iconsize="' + this.attrs[
'icon_size'] + '" data-iconcolor="' + this.attrs['icon_color'];
}
else {
var circliful_icon = '';
}
this.dom_element = $('<div class="az-element az-circle-counter ' + this.attrs['el_class'] + '" style="' +
this.attrs['style'] + '"><div id="' + this.id + '" data-dimension="' + this.attrs['dimension'] +
'" data-text="' + this.attrs['text'] + '" data-info="' + this.attrs['info'] + '" data-width="' + this
.attrs['width'] + '" data-fontsize="' + this.attrs['fontsize'] + '" data-type="' + this.attrs['type'] +
'" data-percent="' + this.attrs['percent'] + '" data-fgcolor="' + this.attrs['fgcolor'] +
'" data-bgcolor="' + this.attrs['bgcolor'] + '" data-fill="' + this.attrs['fill'] + '" data-border="' +
this.attrs['border'] + circliful_icon + '"></div></div>');
this.baseclass.prototype.render.apply(this, arguments);
},
},
| eggla/LA-glazed | profiles/cms/modules/sooperthemes_premium/glazed_builder/glazed_builder/build/glazed-elements/elements/az_circle_counter.js | JavaScript | gpl-2.0 | 5,094 |
package marc.scp.sshutils;
import com.jcraft.jsch.Logger;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.nio.charset.Charset;
public class ConnectionInfo implements Logger
{
static java.util.Hashtable name=new java.util.Hashtable();
static
{
name.put(new Integer(DEBUG), "DEBUG: ");
name.put(new Integer(INFO), "INFO: ");
name.put(new Integer(WARN), "WARN: ");
name.put(new Integer(ERROR), "ERROR: ");
name.put(new Integer(FATAL), "FATAL: ");
}
public boolean isEnabled(int level)
{
return true;
}
public void log(int level, String message)
{
System.err.print(name.get(new Integer(level)));
System.err.println(message);
}
}
| marcb1/droid-ssh | scp/src/main/java/marc/scp/sshutils/ConnectionInfo.java | Java | gpl-2.0 | 769 |
using System;
using System.Linq;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
using Windows.Storage;
namespace WuaFaceAppChristmas.Lib
{
public class CameraActions
{
public static async Task<StorageFile> TakeWebCamPictureAndReturnFile(bool takeSilentPicture)
{
StorageFile file;
if (takeSilentPicture)
{
var takePhotoManager = new MediaCapture();
await takePhotoManager.InitializeAsync();
var imgFormat = ImageEncodingProperties.CreateJpeg();
file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("CameraPhoto.jpg", CreationCollisionOption.ReplaceExisting);
await takePhotoManager.CapturePhotoToStorageFileAsync(imgFormat, file);
}
else
{
var dialog = new CameraCaptureUI();
dialog.PhotoSettings.AllowCropping = false;
dialog.PhotoSettings.MaxResolution = CameraCaptureUIMaxPhotoResolution.HighestAvailable;
file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
}
return file;
}
public static async Task<DeviceInformation> FindCameraDeviceByPanelAsync(Panel desiredPanel)
{
// Get available devices for capturing pictures
var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
// Get the desired camera by panel
DeviceInformation desiredDevice = allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == desiredPanel);
// If there is no device mounted on the desired panel, return the first device found
return desiredDevice ?? allVideoDevices.FirstOrDefault();
}
}
}
| elbruno/Blog | 20160105 UWP Windows 10 Face Detection Christmas sample/WuaFaceAppChristmas/Lib/CameraActions.cs | C# | gpl-2.0 | 1,928 |
<?php
/**
* @package HikaShop for Joomla!
* @version 2.6.4
* @author hikashop.com
* @copyright (C) 2010-2016 HIKARI SOFTWARE. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die('Restricted access');
?><div class="iframedoc" id="iframedoc"></div>
<form action="index.php?option=<?php echo HIKASHOP_COMPONENT ?>&ctrl=zone" method="post" name="adminForm" id="adminForm" enctype="multipart/form-data">
<?php if(!HIKASHOP_BACK_RESPONSIVE) { ?>
<div id="hikashop_zone_form">
<table style="width:100%" class="table">
<tr>
<td valign="top" width="350">
<?php } else { ?>
<div id="hikashop_zone_form" class="row-fluid">
<div class="span4 hikaspanleft">
<?php } ?>
<fieldset class="adminform" id="htmlfieldset">
<legend><?php echo JText::_( 'ZONE_INFORMATION' ); ?></legend>
<?php
$this->setLayout('information');
echo $this->loadTemplate();
?>
</fieldset>
<?php if(!HIKASHOP_BACK_RESPONSIVE) { ?>
</td>
<td valign="top">
<?php } else { ?>
</div>
<div class="span8">
<?php } ?>
<fieldset class="adminform" id="htmlfieldset">
<legend><?php echo JText::_( 'SUBZONES' ); ?></legend>
<?php if(empty($this->element->zone_namekey)){
echo JText::_( 'SUBZONES_CHOOSER_DISABLED' );
}else{
$this->setLayout('childlisting');
echo $this->loadTemplate();
} ?>
</fieldset>
<?php if(!HIKASHOP_BACK_RESPONSIVE) { ?>
</td>
</tr>
</table>
</div>
<?php } else { ?>
</div>
</div>
<?php } ?>
<div class="clr"></div>
<input type="hidden" name="cid[]" value="<?php echo @$this->element->zone_id; ?>" />
<input type="hidden" name="option" value="<?php echo HIKASHOP_COMPONENT; ?>" />
<input type="hidden" name="task" value="" />
<input type="hidden" name="ctrl" value="zone" />
<?php echo JHTML::_( 'form.token' ); ?>
</form>
| khuongdang/dongtrungtruongsinh | administrator/components/com_hikashop/views/zone/tmpl/form.php | PHP | gpl-2.0 | 1,970 |
#parser_testing.py
import os, sys, re, StringIO
sys.path.append('/Users/Jason/Dropbox/JournalMap/scripts/GeoParsers')
#from jmap_geoparser_re import *
from jmap_geoparser import *
#def test_parsing():
test = "blah blah blah 45º 23' 12'', 123º 23' 56'' and blah blah blah 32º21'59''N, 115º 23' 14''W blah blah blah"
coords = coordinateParser.searchString(test)
for coord in coords:
assert coordinate(coord).calcDD(), "Coordinate Transform Error for "+str(coord)
test = "45.234º, 123.43º"
assert coordinate(coordinateParser.parseString(test)).calcDD() == {'latitude': 45.234, 'longitude': 123.43}
test = "-45º 23' 12'', -123º 23' 56''"
assert coordinate(coordinateParser.parseString(test)).calcDD() == {'latitude': -45.38667, 'longitude': 123.39889}
test = "32º21'59''N, 115º 23' 14''W"
assert coordinate(coordinateParser.parseString(test)).calcDD() == {'latitude': 32.36639, 'longitude': -115.38722}
test = "12 43 56 North, 23 56 12 East"
assert coordinate(coordinateParser.parseString(test)).calcDD() == {'latitude': 12.73222, 'longitude': 23.93667}
test = "52 15 10N, 0 01 54W"
assert coordinate(coordinateParser.parseString(test)).calcDD() == {'latitude': 52.25278, 'longitude': -0.03167}
test = "52 35 31N, 1 28 05E"
assert coordinate(coordinateParser.parseString(test)).calcDD() == {'latitude': 52.59194, 'longitude': 1.46806}
test = "30° 47' N, 34° 46' E"
assert coordinate(coordinateParser.parseString(test)).calcDD() == {'latitude': 30.78333, 'longitude': 34.76667}
'''
test = "AT; 1 spm, CN 3-41, 21°00′ N, 112°30′ E"
for result, start, end in coordinateParser.scanString(test):
assert coordinate(result).calcDD() == {'latitude': 21.0, 'longitude': 112.5}
test = '27°43.886, 34°15.663'
assert coordinate(coordinateParser.parseString(test)).calcDD() == {'latitude': 27.73143, 'longitude': 34.26105}
test = '49°17’13”N, 13°40’18”E'
assert coordinate(coordinateParser.parseString(test)).calcDD() == {'latitude': 49.28694, 'longitude': 13.67167}
test = '45.9215º; -76.6219º'
assert coordinate(coordinateParser.parseString(test)).calcDD() == {'latitude': -45.9215, 'longitude': 76.6219}
test = "latitude 32°47′47″ S and longitude 26°50′56″ E"
assert coordinate(coordinateParser.parseString(test)).calcDD() == {'latitude': -32.79639, 'longitude': 26.84889}
test = "N15°46′ W87°00'"
assert coordinate(coordinateParser.parseString(test)).calcDD() == {'latitude': 15.76667, 'longitude': -87.0}
test = "latitude of 35°13', longitude of 4°11'"
assert coordinate(coordinateParser.parseString(test)).calcDD() == {'latitude': 35.21667, 'longitude': 4.18333}
test = "expects to find coordinates: 52 degrees, 42 minutes north, 124 degrees, 50 minutes west"
assert coordinate(coordinateParser.parseString(test)).calcDD() == {'latitude': 52.7, 'longitude': -124.83333}
# Should return an exception, but instead calculates latitude as 6º 10'
#test = "expects to find coordinates: 5°70'N, 73°46'W" # Minutes greater than 60
#test = "expects not to find: 4.5–5.0 "
''' | JournalMap/GeoParsers | pyparser_geoparser_testing.py | Python | gpl-2.0 | 3,064 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 21 15:53:15 2016
@author: agiovann
"""
from __future__ import division
from __future__ import print_function
#%%
from builtins import zip
from builtins import str
from builtins import map
from builtins import range
from past.utils import old_div
import cv2
try:
cv2.setNumThreads(1)
except:
print('Open CV is naturally single threaded')
try:
if __IPYTHON__:
print((1))
# this is used for debugging purposes only. allows to reload classes when changed
get_ipython().magic('load_ext autoreload')
get_ipython().magic('autoreload 2')
except NameError:
print('Not launched under iPython')
import caiman as cm
import numpy as np
import time
import pylab as pl
import psutil
import sys
import os
from ipyparallel import Client
from skimage.external.tifffile import TiffFile
# , motion_correction_piecewise
from caiman.motion_correction import tile_and_correct
#%% in parallel
def tile_and_correct_wrapper(params):
from skimage.external.tifffile import imread
import numpy as np
import cv2
try:
cv2.setNumThreads(1)
except:
1 # 'Open CV is naturally single threaded'
from caiman.motion_correction import tile_and_correct
img_name, out_fname, idxs, shape_mov, template, strides, overlaps, max_shifts,\
add_to_movie, max_deviation_rigid, upsample_factor_grid, newoverlaps, newstrides, shifts_opencv = params
imgs = imread(img_name, key=idxs)
mc = np.zeros(imgs.shape, dtype=np.float32)
shift_info = []
for count, img in enumerate(imgs):
if count % 10 == 0:
print(count)
mc[count], total_shift, start_step, xy_grid = tile_and_correct(img, template, strides, overlaps, max_shifts, add_to_movie=add_to_movie, newoverlaps=newoverlaps, newstrides=newstrides,
upsample_factor_grid=upsample_factor_grid, upsample_factor_fft=10, show_movie=False, max_deviation_rigid=max_deviation_rigid, shifts_opencv=shifts_opencv)
shift_info.append([total_shift, start_step, xy_grid])
if out_fname is not None:
outv = np.memmap(out_fname, mode='r+', dtype=np.float32,
shape=shape_mov, order='F')
outv[:, idxs] = np.reshape(
mc.astype(np.float32), (len(imgs), -1), order='F').T
return shift_info, idxs, np.nanmean(mc, 0)
#%%
def motion_correction_piecewise(fname, splits, strides, overlaps, add_to_movie=0, template=None, max_shifts=(12, 12), max_deviation_rigid=3, newoverlaps=None, newstrides=None,
upsample_factor_grid=4, order='F', dview=None, save_movie=True, base_name='none', num_splits=None, shifts_opencv=False):
'''
'''
with TiffFile(fname) as tf:
d1, d2 = tf[0].shape
T = len(tf)
if type(splits) is int:
idxs = np.array_split(list(range(T)), splits)
else:
idxs = splits
save_movie = False
if template is None:
raise Exception('Not implemented')
shape_mov = (d1 * d2, T)
dims = d1, d2
if num_splits is not None:
idxs = np.array(idxs)[np.random.randint(0, len(idxs), num_splits)]
save_movie = False
print('**** MOVIE NOT SAVED BECAUSE num_splits is not None ****')
if save_movie:
if base_name is None:
base_name = fname[:-4]
fname_tot = base_name + '_d1_' + str(dims[0]) + '_d2_' + str(dims[1]) + '_d3_' + str(
1 if len(dims) == 2 else dims[2]) + '_order_' + str(order) + '_frames_' + str(T) + '_.mmap'
fname_tot = os.path.join(os.path.split(fname)[0], fname_tot)
np.memmap(fname_tot, mode='w+', dtype=np.float32,
shape=shape_mov, order=order)
else:
fname_tot = None
pars = []
for idx in idxs:
pars.append([fname, fname_tot, idx, shape_mov, template, strides, overlaps, max_shifts, np.array(
add_to_movie, dtype=np.float32), max_deviation_rigid, upsample_factor_grid, newoverlaps, newstrides, shifts_opencv])
t1 = time.time()
if dview is not None:
res = dview.map_sync(tile_and_correct_wrapper, pars)
else:
res = list(map(tile_and_correct_wrapper, pars))
print((time.time() - t1))
return fname_tot, res
#%%
# backend='SLURM'
backend = 'local'
if backend == 'SLURM':
n_processes = np.int(os.environ.get('SLURM_NPROCS'))
else:
# roughly number of cores on your machine minus 1
n_processes = np.maximum(np.int(psutil.cpu_count()), 1)
print(('using ' + str(n_processes) + ' processes'))
#%% start cluster for efficient computation
single_thread = False
if single_thread:
dview = None
else:
try:
c.close()
except:
print('C was not existing, creating one')
print("Stopping cluster to avoid unnencessary use of memory....")
sys.stdout.flush()
if backend == 'SLURM':
try:
cm.stop_server(is_slurm=True)
except:
print('Nothing to stop')
slurm_script = '/mnt/xfs1/home/agiovann/SOFTWARE/Constrained_NMF/SLURM/slurmStart.sh'
cm.start_server(slurm_script=slurm_script)
pdir, profile = os.environ['IPPPDIR'], os.environ['IPPPROFILE']
c = Client(ipython_dir=pdir, profile=profile)
else:
cm.stop_server()
cm.start_server()
c = Client()
print(('Using ' + str(len(c)) + ' processes'))
dview = c[:len(c)]
#%% set parameters and create template by rigid motion correction
t1 = time.time()
#fname = 'k56_20160608_RSM_125um_41mW_zoom2p2_00001_00034.tif'
#fname = 'Sue_1000.tif'
fname = 'Sue_2000.tif'
max_shifts = (12, 12)
# splits = 56 # for parallelization split the movies in num_splits chuncks across time
#num_splits_to_process = 28
#fname = 'M_FLUO_t_1000.tif'
#max_shifts = (10,10)
splits = 56 # for parallelization split the movies in num_splits chuncks across time
num_splits_to_process = 28
#fname = 'M_FLUO_4.tif'
m = cm.load(fname, subindices=slice(0, 500, None))
template = cm.motion_correction.bin_median(m[100:400].copy().motion_correct(
max_shifts[0], max_shifts[1], template=None)[0])
print(time.time() - t1)
#%
# pl.imshow(template)
#%
shifts_opencv = False
new_templ = template
add_to_movie = -np.min(template)
save_movie = False
num_iter = 1
for iter_ in range(num_iter):
print(iter_)
old_templ = new_templ.copy()
if iter_ == num_iter - 1:
save_movie = True
print('saving!')
num_splits_to_process = None
# templ_to_save = old_templ
fname_tot, res = motion_correction_piecewise(fname, splits, None, None,
add_to_movie=add_to_movie, template=old_templ, max_shifts=max_shifts, max_deviation_rigid=0,
newoverlaps=None, newstrides=None,
upsample_factor_grid=4, order='F', dview=dview, save_movie=save_movie, base_name=fname[:-4] + '_rig_', num_splits=num_splits_to_process, shifts_opencv=shifts_opencv)
new_templ = np.nanmedian(np.dstack([r[-1] for r in res]), -1)
print((old_div(np.linalg.norm(new_templ - old_templ), np.linalg.norm(old_templ))))
t2 = time.time() - t1
print(t2)
pl.imshow(new_templ, cmap='gray', vmax=np.percentile(new_templ, 95))
#%%
import scipy
np.save(fname[:-4] + '_templ_rigid.npy', new_templ)
#scipy.io.savemat('/mnt/xfs1/home/agiovann/dropbox/Python_progress/' + str(np.shape(m)[-1])+'_templ_rigid.mat',{'template':new_templ})
#%%
template = new_templ
#%%
mr = cm.load(fname_tot)
#%% online does not seem to work!
#overlaps = (16,16)
# if template.shape == (512,512):
# strides = (128,128)# 512 512
# #strides = (48,48)# 128 64
# elif template.shape == (64,128):
# strides = (48,48)# 512 512
# else:
# raise Exception('Unknown size, set manually')
#upsample_factor_grid = 4
#
#T = m.shape[0]
#idxs_outer = np.array_split(range(T),T/1000)
# for iddx in idxs_outer:
# num_fr = len(iddx)
# splits = np.array_split(iddx,num_fr/n_processes)
# print (splits[0][0]),(splits[-1][-1])
# fname_tot, res = motion_correction_piecewise(fname,splits, strides, overlaps,\
# add_to_movie=add_to_movie, template = template, max_shifts = (12,12),max_deviation_rigid = 3,\
# upsample_factor_grid = upsample_factor_grid,dview = dview)
#%%
# for 512 512 this seems good
t1 = time.time()
if template.shape == (512, 512):
strides = (128, 128) # 512 512
overlaps = (32, 32)
# strides = (16,16)# 512 512
newoverlaps = None
newstrides = None
# strides = (48,48)# 128 64
elif template.shape == (64, 128):
strides = (32, 32)
overlaps = (16, 16)
newoverlaps = None
newstrides = None
else:
raise Exception('Unknown size, set manually')
splits = 56
num_splits_to_process = 28
upsample_factor_grid = 4
max_deviation_rigid = 3
new_templ = template
add_to_movie = -np.min(m)
num_iter = 2
save_movie = False
for iter_ in range(num_iter):
print(iter_)
old_templ = new_templ.copy()
if iter_ == num_iter - 1:
save_movie = True
num_splits_to_process = None
print('saving!')
fname_tot, res = motion_correction_piecewise(fname, splits, strides, overlaps,
add_to_movie=add_to_movie, template=old_templ, max_shifts=max_shifts, max_deviation_rigid=max_deviation_rigid,
newoverlaps=newoverlaps, newstrides=newstrides,
upsample_factor_grid=upsample_factor_grid, order='F', dview=dview, save_movie=save_movie, base_name=fname[:-4] + '_els_opencv_', num_splits=num_splits_to_process, shifts_opencv=shifts_opencv)
new_templ = np.nanmedian(np.dstack([r[-1] for r in res]), -1)
# print((old_div(np.linalg.norm(new_templ-old_templ),np.linalg.norm(old_templ))))
# pl.imshow(new_templ,cmap = 'gray',vmax = np.percentile(new_templ,99))
# pl.pause(.1)
t2 = time.time() - t1
print(t2)
mc = cm.load(fname_tot)
#%%
pl.imshow(new_templ, cmap='gray', vmax=np.percentile(new_templ, 95))
#%%
np.save(fname[:-4] + '_templ_pw_rigid.npy', new_templ)
#scipy.io.savemat('/mnt/xfs1/home/agiovann/dropbox/Python_progress/' + str(np.shape(m)[-1])+'_templ_pw_rigid.mat',{'template':templ_to_save})
#%%
#%%
def compute_metrics_motion_correction(fname, final_size_x, final_size_y, swap_dim, pyr_scale=.5, levels=3, winsize=100, iterations=15, poly_n=5, poly_sigma=1.2 / 5, flags=0,
play_flow=False, resize_fact_flow=.2, template=None):
# cv2.OPTFLOW_FARNEBACK_GAUSSIAN
import scipy
vmin, vmax = -1, 1
m = cm.load(fname)
max_shft_x = np.int(np.ceil((np.shape(m)[1] - final_size_x) / 2))
max_shft_y = np.int(np.ceil((np.shape(m)[2] - final_size_y) / 2))
max_shft_x_1 = - ((np.shape(m)[1] - max_shft_x) - (final_size_x))
max_shft_y_1 = - ((np.shape(m)[2] - max_shft_y) - (final_size_y))
if max_shft_x_1 == 0:
max_shft_x_1 = None
if max_shft_y_1 == 0:
max_shft_y_1 = None
# print ([max_shft_x,max_shft_x_1,max_shft_y,max_shft_y_1])
m = m[:, max_shft_x:max_shft_x_1, max_shft_y:max_shft_y_1]
print('Local correlations..')
img_corr = m.local_correlations(eight_neighbours=True, swap_dim=swap_dim)
print(m.shape)
if template is None:
tmpl = cm.motion_correction.bin_median(m)
else:
tmpl = template
# tmpl = tmpl[max_shft_x:-max_shft_x,max_shft_y:-max_shft_y]
print('Compute Smoothness.. ')
smoothness = np.sqrt(
np.sum(np.sum(np.array(np.gradient(np.mean(m, 0)))**2, 0)))
smoothness_corr = np.sqrt(
np.sum(np.sum(np.array(np.gradient(img_corr))**2, 0)))
print('Compute correlations.. ')
correlations = []
count = 0
for fr in m:
if count % 100 == 0:
print(count)
count += 1
correlations.append(scipy.stats.pearsonr(
fr.flatten(), tmpl.flatten())[0])
print('Compute optical flow .. ')
m = m.resize(1, 1, resize_fact_flow)
norms = []
flows = []
count = 0
for fr in m:
if count % 100 == 0:
print(count)
count += 1
flow = cv2.calcOpticalFlowFarneback(
tmpl, fr, None, pyr_scale, levels, winsize, iterations, poly_n, poly_sigma, flags)
if play_flow:
pl.subplot(1, 3, 1)
pl.cla()
pl.imshow(fr, vmin=0, vmax=300, cmap='gray')
pl.title('movie')
pl.subplot(1, 3, 3)
pl.cla()
pl.imshow(flow[:, :, 1], vmin=vmin, vmax=vmax)
pl.title('y_flow')
pl.subplot(1, 3, 2)
pl.cla()
pl.imshow(flow[:, :, 0], vmin=vmin, vmax=vmax)
pl.title('x_flow')
pl.pause(.05)
n = np.linalg.norm(flow)
flows.append(flow)
norms.append(n)
np.savez(fname[:-4] + '_metrics', flows=flows, norms=norms, correlations=correlations,
smoothness=smoothness, tmpl=tmpl, smoothness_corr=smoothness_corr, img_corr=img_corr)
return tmpl, correlations, flows, norms, smoothness
#%% run comparisons MLK
m_res = glob.glob('MKL*hdf5')
final_size = (512 - 24, 512 - 24)
winsize = 100
swap_dim = False
resize_fact_flow = .2
for mv in m_res:
tmpl, correlations, flows_orig, norms, smoothness = compute_metrics_motion_correction(
mv, final_size[0], final_size[1], swap_dim, winsize=winsize, play_flow=False, resize_fact_flow=resize_fact_flow)
#%% run comparisons NORMCORRE
m_fluos = glob.glob('M_FLUO*.mmap') + glob.glob('M_FLUO*.tif')
final_size = (64 - 20, 128 - 20)
winsize = 32
resize_fact_flow = 1
for mv in m_fluos:
tmpl, correlations, flows_orig, norms, smoothness = compute_metrics_motion_correction(
mv, final_size[0], final_size[1], winsize=winsize, play_flow=False, resize_fact_flow=resize_fact_flow)
#% run comparisons resonant
m_res = glob.glob('Sue*mmap') + glob.glob('Sue*.tif')
final_size = (512 - 24, 512 - 24)
winsize = 100
swap_dim = False
resize_fact_flow = .2
for mv in m_res:
tmpl, correlations, flows_orig, norms, smoothness = compute_metrics_motion_correction(
mv, final_size[0], final_size[1], swap_dim, winsize=winsize, play_flow=False, resize_fact_flow=resize_fact_flow)
#%% run comparisons SIMA
m_fluos = glob.glob('plane*.tif') + glob.glob('row*.tif')
final_size = (64 - 20, 128 - 20)
winsize = 32
resize_fact_flow = 1
for mv in m_fluos:
tmpl, correlations, flows_orig, norms, smoothness = compute_metrics_motion_correction(
mv, final_size[0], final_size[1], winsize=winsize, play_flow=False, resize_fact_flow=resize_fact_flow)
#% run comparisons resonant
m_res = glob.glob('Sue*.tif')
final_size = (512 - 24, 512 - 24)
winsize = 100
resize_fact_flow = .2
for mv in m_res:
tmpl, correlations, flows_orig, norms, smoothness = compute_metrics_motion_correction(
mv, final_size[0], final_size[1], winsize=winsize, play_flow=False, resize_fact_flow=resize_fact_flow)
#%% run comparisons SUITE2P
for mvs in glob.glob('Sue*2000*16*.mat'):
print(mvs)
cm.movie(scipy.io.loadmat(mvs)['data'].transpose(
[2, 0, 1])).save(mvs[:-3] + '.hdf5')
#%%
m_fluos = glob.glob('M_FLUO*.hdf5')
final_size = (64 - 20, 128 - 20)
winsize = 32
resize_fact_flow = 1
for mv in m_fluos:
tmpl, correlations, flows_orig, norms, smoothness = compute_metrics_motion_correction(
mv, final_size[0], final_size[1], winsize=winsize, play_flow=False, resize_fact_flow=resize_fact_flow)
#% run comparisons resonant
m_res = glob.glob('Sue_2000*16*.hdf5')
final_size = (512 - 24, 512 - 24)
winsize = 100
resize_fact_flow = .2
for mv in m_res:
tmpl, correlations, flows_orig, norms, smoothness = compute_metrics_motion_correction(
mv, final_size[0], final_size[1], winsize=winsize, play_flow=False, resize_fact_flow=resize_fact_flow)
#%% plot the results
files_img = [u'/mnt/xfs1/home/agiovann/DataForPublications/Piecewise-Rigid-Analysis-paper/NORM_CORRE_OPENCV/Sue_2000_els_opencv__d1_512_d2_512_d3_1_order_F_frames_2000_._metrics.npz',
u'/mnt/xfs1/home/agiovann/DataForPublications/Piecewise-Rigid-Analysis-paper/NORMCORRE_EFF/Sue_2000_els__d1_512_d2_512_d3_1_order_F_frames_2000_._metrics.npz',
# u'/mnt/xfs1/home/agiovann/DataForPublications/Piecewise-Rigid-Analysis-paper/MLK/Sue_2000_MLK_metrics.npz',
# u'/mnt/xfs1/home/agiovann/DataForPublications/Piecewise-Rigid-Analysis-paper/SIMA_RESULTS/Sue_1000_T.tifrow1_example_sima_Trow1_example_sima_metrics.npz',
# u'/mnt/xfs1/home/agiovann/DataForPublications/Piecewise-Rigid-Analysis-paper/SUITE_2P_RES/Sue_2000_t_NB_16.._metrics.npz',
u'/mnt/xfs1/home/agiovann/DataForPublications/Piecewise-Rigid-Analysis-paper/MLK/MKL16T._metrics.npz']
# for fl in glob.glob('*.npz'):
for fl in files_img:
with np.load(fl) as ld:
print(ld.keys())
pl.figure()
print(fl + ':' + str(np.mean(ld['norms'])) + '+/-' + str(np.std(ld['norms'])) + ' ; ' + str(np.mean(ld['correlations'])
) + '+/-' + str(np.std(ld['correlations'])) + ' ; ' + str(ld['smoothness']) + ' ; ' + str(ld['smoothness_corr']))
pl.subplot(1, 2, 1)
try:
mean_img = np.mean(cm.load(fl[:-12] + 'mmap'), 0)[12:-12, 12:-12]
except:
try:
mean_img = np.mean(
cm.load(fl[:-12] + '.tif'), 0)[12:-12, 12:-12]
except:
mean_img = np.mean(
cm.load(fl[:-12] + 'hdf5'), 0)[12:-12, 12:-12]
# lq,hq = np.nanpercentile(mean_img,[.1,99.9])
lq, hq = 13.3, 318.01
pl.imshow(mean_img, vmin=lq, vmax=hq)
pl.colorbar()
# pl.plot(ld['correlations'])
pl.subplot(1, 2, 2)
pl.imshow(ld['img_corr'], vmin=0, vmax=.5)
pl.colorbar()
#%%
for fl in glob.glob('Mf*.npz'):
with np.load(fl) as ld:
print(ld.keys())
pl.figure()
print(fl + ':' + str(np.mean(ld['norms'])) + '+/-' + str(np.std(ld['norms'])) + ' ; ' + str(np.mean(ld['correlations'])
) + '+/-' + str(np.std(ld['correlations'])) + ' ; ' + str(ld['smoothness']) + ' ; ' + str(ld['smoothness_corr']))
#%%
#%
#total_shifts = []
#start_steps = []
#xy_grids = []
#mc = np.zeros(m.shape)
# for count,img in enumerate(np.array(m)):
# if count % 10 == 0:
# print(count)
# mc[count],total_shift,start_step,xy_grid = tile_and_correct(img, template, strides, overlaps,(12,12), newoverlaps = None, \
# newstrides = newstrides, upsample_factor_grid=upsample_factor_grid,\
# upsample_factor_fft=10,show_movie=False,max_deviation_rigid=2,add_to_movie=add_to_movie)
#
# total_shifts.append(total_shift)
# start_steps.append(start_step)
# xy_grids.append(xy_grid)
#mc = cm.load('M_FLUO_4_d1_64_d2_128_d3_1_order_F_frames_4620_.mmap')
#mc = cm.load('M_FLUO_t_d1_64_d2_128_d3_1_order_F_frames_6764_.mmap')
#%%
mc.resize(1, 1, .1).play(gain=10., fr=30, offset=100, magnification=1.)
#%%
m.resize(1, 1, .2).play(gain=10, fr=30, offset=0, magnification=1.)
#%%
cm.concatenate([mr.resize(1, 1, .5), mc.resize(1, 1, .5)], axis=1).play(
gain=10, fr=100, offset=300, magnification=1.)
#%%
import h5py
with h5py.File('sueann_pw_rigid_movie.mat') as f:
mef = np.array(f['M2'])
mef = cm.movie(mef.transpose([0, 2, 1]))
#%%
cm.concatenate([mef.resize(1, 1, .15), mc.resize(1, 1, .15)], axis=1).play(
gain=30, fr=40, offset=300, magnification=1.)
#%%
(mef - mc).resize(1, 1, .1).play(gain=50, fr=20, offset=0, magnification=1.)
#%%
(mc - mef).resize(1, 1, .1).play(gain=50, fr=20, offset=0, magnification=1.)
#%%
T, d1, d2 = np.shape(m)
shape_mov = (d1 * d2, m.shape[0])
Y = np.memmap('M_FLUO_4_d1_64_d2_128_d3_1_order_F_frames_4620_.mmap',
mode='r', dtype=np.float32, shape=shape_mov, order='F')
mc = cm.movie(np.reshape(Y, (d2, d1, T), order='F').transpose([2, 1, 0]))
mc.resize(1, 1, .25).play(gain=10., fr=50)
#%%
total_shifts = [r[0][0][0] for r in res]
pl.plot(np.reshape(np.array(total_shifts), (len(total_shifts), -1)))
#%%
#m_raw = cm.motion_correction.bin_median(m,exclude_nans=True)
#m_rig = cm.motion_correction.bin_median(mr,exclude_nans=True)
#m_el = cm.motion_correction.bin_median(mc,exclude_nans=True)
m_raw = np.nanmean(m, 0)
m_rig = np.nanmean(mr, 0)
m_el = np.nanmean(mc, 0)
m_ef = np.nanmean(mef, 0)
#%%
import scipy
r_raw = []
r_rig = []
r_el = []
r_ef = []
max_shft_x, max_shft_y = max_shifts
for fr_id in range(m.shape[0]):
fr = m[fr_id].copy()[max_shft_x:-max_shft_x, max_shft_y:-max_shft_y]
templ_ = m_raw.copy()[max_shft_x:-max_shft_x, max_shft_y:-max_shft_y]
r_raw.append(scipy.stats.pearsonr(fr.flatten(), templ_.flatten())[0])
fr = mr[fr_id].copy()[max_shft_x:-max_shft_x, max_shft_y:-max_shft_y]
templ_ = m_rig.copy()[max_shft_x:-max_shft_x, max_shft_y:-max_shft_y]
r_rig.append(scipy.stats.pearsonr(fr.flatten(), templ_.flatten())[0])
fr = mc[fr_id].copy()[max_shft_x:-max_shft_x, max_shft_y:-max_shft_y]
templ_ = m_el.copy()[max_shft_x:-max_shft_x, max_shft_y:-max_shft_y]
r_el.append(scipy.stats.pearsonr(fr.flatten(), templ_.flatten())[0])
if 1:
fr = mef[fr_id].copy()[max_shft_x:-max_shft_x, max_shft_y:-max_shft_y]
templ_ = m_ef.copy()[max_shft_x:-max_shft_x, max_shft_y:-max_shft_y]
r_ef.append(scipy.stats.pearsonr(fr.flatten(), templ_.flatten())[0])
r_raw = np.array(r_raw)
r_rig = np.array(r_rig)
r_el = np.array(r_el)
r_ef = np.array(r_ef)
#%%
#r_ef = scipy.io.loadmat('sueann.mat')['cM2'].squeeze()
#r_efr = scipy.io.loadmat('sueann.mat')['cY'].squeeze()
# pl.close()
#%%
pl.plot(r_raw)
pl.plot(r_rig)
pl.plot(r_el)
# pl.plot(r_ef)
#%%
pl.scatter(r_el, r_ef)
pl.plot([0, 1], [0, 1], 'r--')
#%%
pl.plot(old_div((r_ef - r_el), np.abs(r_el)))
#%%
import pylab as pl
vmax = -100
max_shft = 3
#%
pl.subplot(3, 3, 1)
pl.imshow(np.nanmean(m, 0)[max_shft:-max_shft, max_shft:-
max_shft], cmap='gray', vmax=vmax, interpolation='none')
pl.title('raw')
pl.axis('off')
pl.xlim([0, 100])
pl.ylim([220, 320])
pl.axis('off')
pl.subplot(3, 3, 2)
pl.title('rigid mean')
pl.imshow(np.nanmean(mr, 0)[max_shft:-max_shft, max_shft:-
max_shft], cmap='gray', vmax=vmax, interpolation='none')
pl.xlim([0, 100])
pl.ylim([220, 320])
pl.axis('off')
pl.subplot(3, 3, 3)
pl.imshow(np.nanmean(mc, 0)[max_shft:-max_shft, max_shft:-
max_shft], cmap='gray', vmax=vmax, interpolation='none')
pl.title('pw-rigid mean')
pl.axis('off')
pl.xlim([0, 100])
pl.ylim([220, 320])
pl.axis('off')
pl.subplot(3, 3, 5)
pl.scatter(r_raw, r_rig)
pl.plot([0, 1], [0, 1], 'r--')
pl.xlabel('raw')
pl.ylabel('rigid')
pl.xlim([0, 1])
pl.ylim([0, 1])
pl.subplot(3, 3, 6)
pl.scatter(r_rig, r_el)
pl.plot([0, 1], [0, 1], 'r--')
pl.ylabel('pw-rigid')
pl.xlabel('rigid')
pl.xlim([0, 1])
pl.ylim([0, 1])
if 0:
pl.subplot(2, 3, 3)
pl.scatter(r_el, r_ef)
pl.plot([0, 1], [0, 1], 'r--')
pl.ylabel('pw-rigid')
pl.xlabel('pw-rigid eft')
pl.xlim([0, 1])
pl.ylim([0, 1])
pl.subplot(2, 3, 6)
pl.imshow(np.nanmean(mef, 0)[max_shft:-max_shft, max_shft:-
max_shft], cmap='gray', vmax=vmax, interpolation='none')
pl.title('pw-rigid eft mean')
pl.axis('off')
#%%
pl.plot(r_ef)
#%%
mc = cm.movie(mc)
mc[np.isnan(mc)] = 0
#%% play movie
(mc + add_to_movie).resize(1, 1, .25).play(gain=10., fr=50)
#%% compute correlation images
ccimage = m.local_correlations(eight_neighbours=True, swap_dim=False)
ccimage_rig = mr.local_correlations(eight_neighbours=True, swap_dim=False)
ccimage_els = mc.local_correlations(eight_neighbours=True, swap_dim=False)
ccimage_ef = mef.local_correlations(eight_neighbours=True, swap_dim=False)
#%% check correlation images
pl.subplot(2, 2, 1)
pl.imshow(ccimage, vmin=0, vmax=0.4, interpolation='none')
pl.subplot(2, 2, 2)
pl.imshow(ccimage_rig, vmin=0, vmax=0.4, interpolation='none')
pl.subplot(2, 2, 3)
pl.imshow(ccimage_els, vmin=0, vmax=0.4, interpolation='none')
pl.subplot(2, 2, 4)
pl.imshow(ccimage_ef, vmin=0, vmax=0.4, interpolation='none')
#%%
all_mags = []
all_mags_eig = []
for chunk in res:
for frame in chunk[0]:
shifts, pos, init = frame
x_sh = np.zeros(np.add(init[-1], 1))
y_sh = np.zeros(np.add(init[-1], 1))
for nt, sh in zip(init, shifts):
x_sh[nt] = sh[0]
y_sh[nt] = sh[1]
jac_xx = x_sh[1:, :] - x_sh[:-1, :]
jac_yx = y_sh[1:, :] - y_sh[:-1, :]
jac_xy = x_sh[:, 1:] - x_sh[:, :-1]
jac_yy = y_sh[:, 1:] - y_sh[:, :-1]
mag_norm = np.sqrt(jac_xx[:, :-1]**2 + jac_yx[:, :-1]
** 2 + jac_xy[:-1, :]**2 + jac_yy[:-1, :]**2)
all_mags.append(mag_norm)
# pl.cla()
# pl.imshow(mag_norm,vmin=0,vmax =1,interpolation = 'none')
# pl.pause(.1)
#%%
mam = cm.movie(np.dstack(all_mags)).transpose([2, 0, 1])
#mam.play(magnification=10,gain = 5.)
#%%
pl.imshow(np.max(mam, 0), interpolation='none')
#%%
m = cm.load('rig_sue__d1_512_d2_512_d3_1_order_F_frames_3000_.mmap')
m1 = cm.load('els_sue__d1_512_d2_512_d3_1_order_F_frames_3000_.mmap')
m0 = cm.load('k56_20160608_RSM_125um_41mW_zoom2p2_00001_00034.tif')
tmpl = cm.motion_correction.bin_median(m)
tmpl1 = cm.motion_correction.bin_median(m1)
tmpl0 = cm.motion_correction.bin_median(m0)
#%%
vmin, vmax = -1, 1
count = 0
pyr_scale = .5
levels = 3
winsize = 100
iterations = 15
poly_n = 5
poly_sigma = old_div(1.2, 5)
flags = 0 # cv2.OPTFLOW_FARNEBACK_GAUSSIAN
norms = []
flows = []
for fr, fr1, fr0 in zip(m.resize(1, 1, .2), m1.resize(1, 1, .2), m0.resize(1, 1, .2)):
count += 1
print(count)
flow1 = cv2.calcOpticalFlowFarneback(tmpl1[max_shft_x:-max_shft_x, max_shft_y:-max_shft_y], fr1[max_shft_x:-
max_shft_x, max_shft_y:-max_shft_y], None, pyr_scale, levels, winsize, iterations, poly_n, poly_sigma, flags)
flow = cv2.calcOpticalFlowFarneback(tmpl[max_shft_x:-max_shft_x, max_shft_y:-max_shft_y], fr[max_shft_x:-
max_shft_x, max_shft_y:-max_shft_y], None, pyr_scale, levels, winsize, iterations, poly_n, poly_sigma, flags)
flow0 = cv2.calcOpticalFlowFarneback(tmpl0[max_shft_x:-max_shft_x, max_shft_y:-max_shft_y], fr0[max_shft_x:-
max_shft_x, max_shft_y:-max_shft_y], None, pyr_scale, levels, winsize, iterations, poly_n, poly_sigma, flags)
#
# pl.subplot(2,3,1)
# pl.cla()
# pl.imshow(flow1[:,:,1],vmin=vmin,vmax=vmax)
# pl.subplot(2,3,2)
# pl.cla()
# pl.imshow(flow[:,:,1],vmin=vmin,vmax=vmax)
# pl.subplot(2,3,3)
# pl.cla()
# pl.imshow(flow0[:,:,1],vmin=vmin,vmax=vmax)
#
# pl.subplot(2,3,4)
# pl.cla()
# pl.imshow(flow1[:,:,0],vmin=vmin,vmax=vmax)
# pl.subplot(2,3,5)
# pl.cla()
# pl.imshow(flow[:,:,0],vmin=vmin,vmax=vmax)
# pl.subplot(2,3,6)
# pl.cla()
# pl.imshow(flow0[:,:,0],vmin=vmin,vmax=vmax)
# pl.pause(.1)
n1, n, n0 = np.linalg.norm(flow1), np.linalg.norm(
flow), np.linalg.norm(flow0)
flows.append([flow1, flow, flow0])
norms.append([n1, n, n0])
#%%
flm1_x = cm.movie(np.dstack([fl[0][:, :, 0]
for fl in flows])).transpose([2, 0, 1])
flm_x = cm.movie(np.dstack([fl[1][:, :, 0]
for fl in flows])).transpose([2, 0, 1])
flm0_x = cm.movie(np.dstack([fl[2][:, :, 0]
for fl in flows])).transpose([2, 0, 1])
flm1_y = cm.movie(np.dstack([fl[0][:, :, 1]
for fl in flows])).transpose([2, 0, 1])
flm_y = cm.movie(np.dstack([fl[1][:, :, 1]
for fl in flows])).transpose([2, 0, 1])
flm0_y = cm.movie(np.dstack([fl[2][:, :, 1]
for fl in flows])).transpose([2, 0, 1])
#%%
pl.figure()
pl.subplot(2, 1, 1)
pl.plot(norms)
pl.subplot(2, 1, 2)
pl.plot(np.arange(0, 3000 * .2, 0.2), r_el)
pl.plot(np.arange(0, 3000 * .2, 0.2), r_rig)
pl.plot(np.arange(0, 3000 * .2, 0.2), r_raw)
#%%
#%% compare to optical flow
pl.figure()
vmin = -.5
vmax = .5
cmap = 'hot'
pl.subplot(2, 3, 1)
pl.imshow(np.mean(np.abs(flm1_x), 0), vmin=vmin, vmax=vmax, cmap=cmap)
pl.title('PW-RIGID')
pl.ylabel('optical flow x')
pl.colorbar()
pl.subplot(2, 3, 2)
pl.title('RIGID')
pl.imshow(np.mean(np.abs(flm_x), 0), vmin=vmin, vmax=vmax, cmap=cmap)
pl.colorbar()
pl.subplot(2, 3, 3)
pl.imshow(np.mean(np.abs(flm0_x), 0), vmin=vmin * 4, vmax=vmax * 4, cmap=cmap)
pl.title('RAW')
pl.colorbar()
pl.subplot(2, 3, 4)
pl.imshow(np.mean(np.abs(flm1_y), 0), vmin=vmin, vmax=vmax, cmap=cmap)
pl.ylabel('optical flow y')
pl.colorbar()
pl.subplot(2, 3, 5)
pl.imshow(np.mean(np.abs(flm_y), 0), vmin=vmin, vmax=vmax, cmap=cmap)
pl.colorbar()
pl.subplot(2, 3, 6)
pl.imshow(np.mean(np.abs(flm0_y), 0), vmin=vmin * 4, vmax=vmax * 4, cmap=cmap)
pl.colorbar()
#%%
fl_rig = [n[1] / 1000 for n in norms]
fl_raw = [n[2] / 1000 for n in norms]
fl_el = [n[0] / 1000 for n in norms]
#%%
font = {'family': 'Myriad Pro',
'weight': 'regular',
'size': 15}
pl.rc('font', **font)
vmax = -100
max_shft = 3
pl.subplot(4, 3, 1)
pl.imshow(np.nanmean(m, 0)[max_shft:-max_shft, max_shft:-
max_shft], cmap='gray', vmax=vmax, interpolation='none')
pl.title('raw')
pl.axis('off')
pl.xlim([0, 100])
pl.ylim([220, 320])
pl.axis('off')
pl.subplot(4, 3, 2)
pl.title('rigid mean')
pl.imshow(np.nanmean(mr, 0)[max_shft:-max_shft, max_shft:-
max_shft], cmap='gray', vmax=vmax, interpolation='none')
pl.xlim([0, 100])
pl.ylim([220, 320])
pl.axis('off')
pl.subplot(4, 3, 3)
pl.imshow(np.nanmean(mc, 0)[max_shft:-max_shft, max_shft:-
max_shft], cmap='gray', vmax=vmax, interpolation='none')
pl.title('pw-rigid mean')
pl.axis('off')
pl.xlim([0, 100])
pl.ylim([220, 320])
pl.axis('off')
pl.subplot(4, 3, 5)
pl.scatter(r_raw, r_rig, s=50, c='red')
pl.axis('tight')
pl.plot([0, 1], [0, 1], 'k--')
pl.xlabel('raw')
pl.ylabel('rigid')
pl.xlim([0.2, .45])
pl.ylim([.2, .45])
pl.locator_params(nbins=4)
pl.subplot(4, 3, 6)
pl.scatter(r_rig, r_el, s=50, c='red')
pl.plot([0, 1], [0, 1], 'k--')
pl.ylabel('pw-rigid')
pl.xlabel('rigid')
pl.xlim([0.3, .45])
pl.ylim([.3, .45])
pl.locator_params(nbins=4)
pl.subplot(4, 3, 4)
pl.plot(np.arange(0, 3000 * .2, 0.2), r_el)
pl.plot(np.arange(0, 3000 * .2, 0.2), r_rig)
pl.plot(np.arange(0, 3000 * .2, 0.2), r_raw)
pl.xlim([220, 320])
pl.ylabel('correlation')
pl.locator_params(nbins=4)
pl.subplot(4, 3, 7)
pl.plot(norms)
pl.xlim([220, 320])
pl.ylabel('norm of optical flow')
pl.xlabel('frames')
pl.locator_params(nbins=4)
pl.subplot(4, 3, 8)
pl.scatter(fl_raw, fl_rig, s=50, c='red')
pl.axis('tight')
pl.plot([0, 3000], [0, 3000], 'k--')
pl.xlabel('raw')
pl.ylabel('rigid')
pl.xlim([0, 3])
pl.ylim([0, 3])
pl.locator_params(nbins=4)
pl.subplot(4, 3, 9)
pl.scatter(fl_rig, fl_el, s=50, c='red')
pl.plot([0, 1000], [0, 1000], 'k--')
pl.ylabel('pw-rigid')
pl.xlabel('rigid')
pl.xlim([0, 1])
pl.ylim([0, 1])
pl.locator_params(nbins=4)
ofl_mod_rig = np.mean(np.sqrt(flm_x**2 + flm_y**2), 0)
ofl_mod_el = np.mean(np.sqrt(flm1_x**2 + flm1_y**2), 0)
pl.subplot(4, 3, 10)
pl.imshow(ofl_mod_el, cmap='hot', vmin=0, vmax=1, interpolation='none')
pl.axis('off')
pl.colorbar()
pl.subplot(4, 3, 11)
pl.imshow(ofl_mod_rig, cmap='hot', vmin=0, vmax=1, interpolation='none')
pl.axis('off')
# pl.xlim([0,100])
# pl.ylim([220,320])
pl.axis('off')
pl.subplot(4, 3, 12)
pl.imshow(ofl_mod_el, cmap='hot', vmin=0, vmax=1, interpolation='none')
pl.axis('off')
# pl.xlim([0,100])
# pl.ylim([220,320])
pl.axis('off')
# font = {'family' : 'Myriad Pro',
# 'weight' : 'regular',
# 'size' : 15}
#
#pl.rc('font', **font)
pl.rcParams['pdf.fonttype'] = 42
#%% test against SIMA
import sima
import sima.motion
from sima.motion import HiddenMarkov2D
#fname_gr = 'M_FLUO_t.tif'
#fname_gr = 'Sue_1000.tif'
#fname_gr = 'Sue_2000.tif'
fname_gr = 'Sue_1000_T.tif'
fname_gr = 'Sue_1000_T.tifrow1_example_sima_T.tif'
sequences = [sima.Sequence.create('TIFF', fname_gr)]
dataset = sima.ImagingDataset(sequences, fname_gr)
#%%
import time
t1 = time.time()
granularity = 'row'
gran_n = 1
mc_approach = sima.motion.HiddenMarkov2D(granularity=(
granularity, gran_n), max_displacement=max_shifts, verbose=True, n_processes=14)
new_dataset = mc_approach.correct(dataset, None)
t2 = time.time() - t1
print(t2)
#%
new_dataset.export_frames(
[[[fname_gr[:-4] + granularity + str(gran_n) + '_example_sima.tif']]], fmt='TIFF16')
#%%
m_s = cm.load(granularity + str(gran_n) + '_example_sima.tif')
m_s_row = cm.load('example_sima.tif')
#%%
def compute_jacobians(res):
all_mags = []
all_mags_eig = []
for chunk in res:
for frame in chunk[0]:
shifts, pos, init = frame
x_sh = np.zeros(np.add(init[-1], 1))
y_sh = np.zeros(np.add(init[-1], 1))
for nt, sh in zip(init, shifts):
x_sh[nt] = sh[0]
y_sh[nt] = sh[1]
jac_xx = x_sh[1:, :] - x_sh[:-1, :]
jac_yx = y_sh[1:, :] - y_sh[:-1, :]
jac_xy = x_sh[:, 1:] - x_sh[:, :-1]
jac_yy = y_sh[:, 1:] - y_sh[:, :-1]
mag_norm = np.sqrt(
jac_xx[:, :-1]**2 + jac_yx[:, :-1]**2 + jac_xy[:-1, :]**2 + jac_yy[:-1, :]**2)
for a, b, c, d in zip(jac_xx, jac_xy, jac_yy, jac_yy):
jc = np.array([[a, b], [c, d]])
w, vl, vr = scipy.linalg.eig(jc)
lsl
all_mags_eig.append(mag_eig)
all_mags.append(mag_norm)
# %%
#m = cm.load('M_FLUO_t_1000.tif')
#tmpl, correlations, flows_rig, norms = compute_metrics_motion_correction('M_FLUO_t_1000_rig__d1_64_d2_128_d3_1_order_F_frames_1000_.mmap',10,10,winsize=32, play_flow=False, resize_fact_flow=1)
#tmpl, correlations, flows_els, norms = compute_metrics_motion_correction('M_FLUO_t_1000_els__d1_64_d2_128_d3_1_order_F_frames_1000_.mmap',10,10,winsize=32, play_flow=False, resize_fact_flow=1)
#tmpl, correlations, flows_orig, norms = compute_metrics_motion_correction('M_FLUO_t_1000.tif',10,10,winsize=32, play_flow=False, resize_fact_flow=1)
#mfl_orig = cm.movie(np.concatenate([np.sqrt(np.sum(ff**2,-1))[np.newaxis,:,:] for ff in flows_orig],axis=0))
#mfl_rig = cm.movie(np.concatenate([np.sqrt(np.sum(ff**2,-1))[np.newaxis,:,:] for ff in flows_rig],axis=0))
#mfl_els = cm.movie(np.concatenate([np.sqrt(np.sum(ff**2,-1))[np.newaxis,:,:] for ff in flows_els],axis=0))
# %%
#cm.concatenate([mfl_orig/5.,mfl_rig,mfl_els],axis = 1).zproject(vmax = .5)
# %%
#cm.concatenate([m[:,10:-10,10:-10]/500,mfl_orig,mfl_rig,mfl_els],axis = 1).play(magnification = 5,gain = 5)
#%% TEST OPT FLOW
nmf = 'M_FLUO_t_shifted_flow.tif'
m = cm.load('M_FLUO_t_1000_els__d1_64_d2_128_d3_1_order_F_frames_1000_.mmap')
#shfts = [(a,b) for a,b in zip(np.random.randint(-2,3,m.shape[0]),np.random.randint(-2,3,m.shape[0]))]
shfts = [(a, b) for a, b in zip(np.random.randn(
m.shape[0]), np.random.randn(m.shape[0]))]
msh = m.copy().apply_shifts(shfts)
msh[:, 10:-10, 10:-10].save(nmf)
template = np.nanmean(m[:, 10:-10, 10:-10], 0)
tmpl, correlations, flows_orig, norms, smoothness = compute_metrics_motion_correction(
'M_FLUO_t_shifted_flow.tif', template.shape[0], template.shape[1], winsize=32, play_flow=False, resize_fact_flow=1, template=template)
with np.load('M_FLUO_t_shifted_flow_metrics.npz') as ld:
flows = ld['flows']
ff_1 = [np.nanmean(f[:, :, 1]) for f in flows]
ff_0 = [np.nanmean(f[:, :, 0]) for f in flows]
pl.subplot(2, 1, 1)
pl.plot(np.array(shfts)[:, 1])
pl.plot(np.array(ff_0))
pl.legend(['shifts', 'optical flow'])
pl.xlim([400, 600])
pl.ylabel('x shifts')
pl.subplot(2, 1, 2)
pl.plot(np.array(shfts)[:, 0])
pl.plot(np.array(ff_1))
pl.xlim([400, 600])
pl.xlabel('frames (15 Hz)')
pl.ylabel('y shifts')
| agiovann/Constrained_NMF | use_cases/motion_correction_paper/demo_motion_correction_nonrigid.py | Python | gpl-2.0 | 36,419 |
/*huawei kernel driver for apds993x*/
/*
* apds993x.c - Linux kernel modules for ambient light + proximity sensor
*
* Copyright (C) 2012 Lee Kai Koon <kai-koon.lee@avagotech.com>
* Copyright (C) 2012 Avago Technologies
* Copyright (C) 2013 LGE Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/mutex.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/input.h>
#include <linux/ioctl.h>
#include <linux/miscdevice.h>
#include <linux/uaccess.h>
#include <linux/i2c/apds993x_ls.h>
#include <linux/regulator/consumer.h>
#include <linux/of_gpio.h>
#include <linux/sensors.h>
#include <linux/wakelock.h>
#ifdef CONFIG_HUAWEI_HW_DEV_DCT
#include <linux/hw_dev_dec.h>
#endif
#include <linux/dsm_pub.h>
#include <misc/app_info.h>
#include <linux/debugfs.h>
static int origin_prox = 822;
#define APDS993X_DRV_NAME "apds993x"
#define DRIVER_VERSION "1.0.0"
#define APDS993X_REG_LEN 0x1a
/* Register Value define : CONTROL */
#define SENSORS_I2C_SCL 909
#define SENSORS_I2C_SDA 908
#define APDS993X_I2C_RETRY_COUNT 3 /* Number of times to retry i2c */
/*wait more time to try read or write to avoid potencial risk*/
#define APDS993X_I2C_RETRY_TIMEOUT 3 /* Timeout between retry (miliseconds) */
#define APDS993X_I2C_BYTE 0
#define APDS993X_I2C_WORD 1
/*APDS993X_SUSPEND_ON:suspend already but not resume,phone is sleeping or suspending*/
/*APDS993X_SUSPEND_OFF:resume already,phone is awake*/
#define APDS993X_SUSPEND_ON 1
#define APDS993X_SUSPEND_OFF 0
#define APDS993X_ERROR_HAPPEN 1
#define APDS993X_ERROR_NOTHAPPEN 0
/*keep 400ms wakeup after the ps report the far or near state*/
#define PS_WAKEUP_TIME 400
/*it is like min_proximity_value in 8x12 and 8930,to adjust the dynamic proximity ditance*/
static int apds993x_ps_init_threshold = 960;
/*remove to .h file*/
/*we use different GA for A,D and C light,so there are three GAs*/
/*pwave and pwindow are for pls to realize the adaptive algorithm*/
static int IAC_last = 0;
/*delete it,we use data->enable to save enable state*/
/*delete the wakelock,so system can sleep when the device is in the calling*/
/*als parameters,it is different for every devices*/
static uint32_t apds993x_a_ga = 200;
static uint32_t apds993x_c_ga = 400;
static uint32_t apds993x_d_ga = 300;
/*pls parameters,it is still different for every devices*/
static uint32_t apds993x_pwave_value = 100;
static uint32_t apds993x_pwindow_value = 200;
static int apds993x_suspend_flag = APDS993X_SUSPEND_OFF;
static int apds993x_error_flag = APDS993X_ERROR_NOTHAPPEN;
extern bool power_key_ps ; //the value is true means powerkey is pressed, false means not pressed
/*dynamic debug mask to control log print,you can echo value to apds993x_debug to control*/
static int apds993x_debug_mask= 0;
module_param_named(apds993x_debug, apds993x_debug_mask, int, S_IRUGO | S_IWUSR | S_IWGRP);
module_param_named(apds993x_pwindow, apds993x_pwindow_value, int, S_IRUGO | S_IWUSR | S_IWGRP);
module_param_named(apds993x_pwave, apds993x_pwave_value, int, S_IRUGO | S_IWUSR | S_IWGRP);
module_param_named(a_ga, apds993x_a_ga, int, S_IRUGO | S_IWUSR | S_IWGRP);
module_param_named(c_ga, apds993x_c_ga, int, S_IRUGO | S_IWUSR | S_IWGRP);
module_param_named(d_ga, apds993x_d_ga, int, S_IRUGO | S_IWUSR | S_IWGRP);
#define APDS993X_ERR(x...) do {\
if (apds993x_debug_mask >=0) \
printk(KERN_ERR x);\
} while (0)
/*KERNEL_HWFLOW is for radar using to control all the log of devices*/
#define APDS993X_INFO(x...) do {\
if ((apds993x_debug_mask >=0)) \
printk(KERN_ERR x);\
} while (0)
#define APDS993X_FLOW(x...) do {\
if (KERNEL_HWFLOW && (apds993x_debug_mask >=1)) \
printk(KERN_ERR x);\
} while (0)
/*
* Structs
*/
struct ls_test_excep{
int i2c_scl_val; /* when i2c transfer err, read the gpio value*/
int i2c_sda_val;
int vdd_mv;
int vdd_status;
int vio_mv;
int vio_status;
int i2c_err_num;
int excep_num;
};
struct apds993x_data {
struct i2c_client *client;
/*to protect the i2c read and write operation*/
struct mutex update_lock;
/*to protect only one thread to control the device register*/
struct mutex single_lock;
struct work_struct dwork; /* for PS interrupt */
struct work_struct als_dwork; /* for ALS polling */
struct delayed_work powerkey_work;
struct input_dev *input_dev_als;
struct input_dev *input_dev_ps;
/* regulator data */
bool power_on;
struct regulator *vdd;
struct regulator *vio;
/* pinctrl data*/
struct pinctrl *pinctrl;
struct pinctrl_state *pin_default;
/*sensor class for als and ps*/
struct sensors_classdev als_cdev;
struct sensors_classdev ps_cdev;
struct apds993x_platform_data *platform_data;
/*for capture the i2c and other errors*/
struct ls_test_excep ls_test_exception;
int irq;
/*hrtimer is removed from platform struct to here*/
struct hrtimer timer;
/*wake lock for not losing ps event reporting*/
struct wake_lock ps_report_wk;
unsigned int enable;
unsigned int atime;
unsigned int ptime;
unsigned int wtime;
unsigned int ailt;
unsigned int aiht;
unsigned int pilt;
unsigned int piht;
unsigned int pers;
unsigned int config;
unsigned int ppcount;
unsigned int control;
/* control flag from HAL */
unsigned int enable_ps_sensor;
unsigned int enable_als_sensor;
/*to record the open or close state of als before suspend*/
unsigned int enable_als_state;
/*delete it,we use data->ps_detection to save ps close or far state*/
/* PS parameters */
unsigned int ps_min_threshold; /*it is the min_proximity_value */
unsigned int ps_detection; /* 5 = near-to-far; 0 = far-to-near */
unsigned int ps_data;/* to store PS data,it is pdata */
/* ALS parameters */
unsigned int als_threshold_l; /* low threshold */
unsigned int als_threshold_h; /* high threshold */
unsigned int als_data; /* to store ALS data from CH0 or CH1*/
int als_prev_lux; /* to store previous lux value */
unsigned int als_poll_delay; /* needed for light sensor polling : micro-second (us) */
bool device_exist;
};
static struct sensors_classdev sensors_light_cdev = {
.name = "apds9930-light",
.vendor = "avago",
.version = 1,
.handle = SENSORS_LIGHT_HANDLE,
.type = SENSOR_TYPE_LIGHT,
.max_range = "10000",
.resolution = "0.0125",
.sensor_power = "0.20",
.min_delay = 1000, /* in microseconds */
.fifo_reserved_event_count = 0,
.fifo_max_event_count = 0,
.enabled = 0,
.delay_msec = 100,
.sensors_enable = NULL,
.sensors_poll_delay = NULL,
};
static struct sensors_classdev sensors_proximity_cdev = {
.name = "apds9930-proximity",
.vendor = "avago",
.version = 1,
.handle = SENSORS_PROXIMITY_HANDLE,
.type = SENSOR_TYPE_PROXIMITY,
.max_range = "1",
.resolution = "1.0",
.sensor_power = "3",
.min_delay = 0, /* in microseconds */
.fifo_reserved_event_count = 0,
.fifo_max_event_count = 0,
.enabled = 0,
.delay_msec = 100,
.sensors_enable = NULL,
.sensors_poll_delay = NULL,
};
static struct dsm_client *apds993x_lps_dclient = NULL;
/* dsm client for lp-sensor */
static struct dsm_dev dsm_lps_apds = {
.name = CLIENT_NAME_LPS_APDS, // dsm client name
.fops = NULL, // options
.buff_size = DSM_SENSOR_BUF_MAX, // buffer size
};
static int apds_dsm_init(struct apds993x_data *data)
{
apds993x_lps_dclient = dsm_register_client(&dsm_lps_apds);
if (!apds993x_lps_dclient) {
APDS993X_ERR("%s@%d register dsm apds993x_lps_dclient failed!\n",__func__,__LINE__);
return -ENOMEM;
}
apds993x_lps_dclient->driver_data = data;
return 0;
}
static void apds_dsm_exit(void)
{
dsm_unregister_client(apds993x_lps_dclient,&dsm_lps_apds);
}
static int apds_dsm_report_i2c(struct apds993x_data *data)
{
struct ls_test_excep *excep = &data->ls_test_exception;
ssize_t size = 0;
ssize_t total_size = 0;
if(dsm_client_ocuppy(apds993x_lps_dclient))
{
/* buffer is busy */
APDS993X_ERR("%s: buffer is busy!", __func__);
return -EBUSY;
}
size = dsm_client_record(apds993x_lps_dclient,
"i2c_scl_val=%d,i2c_sda_val=%d,vdd = %d, vdd_status = %d\n"
"vio=%d, vio_status=%d, excep_num=%d, i2c_err_num=%d\n"
,excep->i2c_scl_val,excep->i2c_sda_val,excep->vdd_mv,excep->vdd_status
,excep->vio_mv,excep->vio_status,excep->excep_num,excep->i2c_err_num);
/*if device is not probe successfully or client is null, don't notify dsm work func*/
if(data->device_exist == false || apds993x_lps_dclient == NULL){
return -ENODEV;
}
dsm_client_notify(apds993x_lps_dclient, DSM_LPS_I2C_ERROR);
total_size += size;
return total_size;
}
/*
* Global data
*/
/*delete two global data to avoid potencial risks*/
/* Proximity sensor use this work queue to report data */
static struct workqueue_struct *apds993x_workqueue = NULL;
/*changeable als gain and ADC time,we don't use*/
/* ALS tuning,they are used to calculate lux*/
static int apds993x_coe_b = 2117;
static int apds993x_coe_c = 76;
static int apds993x_coe_d = 78;
static int apds993x_coe_e = 217;
static int apds993x_coe_f = 50;
static int cur_pthreshold_h=0;
static int cur_pthreshold_l=0;
static int far_init=549;
static int near_init=550;
/*
* Management functions,they are used to set registers in booting and enable
*/
/*init the register of device function for probe and every time the chip is powered on*/
static int apds993x_init_client(struct i2c_client *client);
/*
* if i2c transfer error, we check sda/scl value and regulator's value
*/
static int apds_dump_i2c_exception_status(struct apds993x_data *data)
{
int ret = 0;
/* print pm status and i2c gpio status*/
struct ls_test_excep *excep = &data->ls_test_exception;
if (data->vdd == NULL) {
return -ENXIO;
}
if (data->vio == NULL) {
return -ENXIO;
}
/* read i2c_sda i2c_scl gpio value*/
mutex_lock(&data->update_lock);
excep->i2c_scl_val = gpio_get_value(SENSORS_I2C_SCL);
excep->i2c_sda_val = gpio_get_value(SENSORS_I2C_SDA);
mutex_unlock(&data->update_lock);
/* get regulator's status*/
excep->vdd_status = regulator_is_enabled(data->vdd);
if(excep->vdd_status < 0){
APDS993X_ERR("%s,line %d:regulator_is_enabled vdd failed\n",__func__,__LINE__);
}
excep->vio_status = regulator_is_enabled(data->vio);
if(excep->vio_status < 0){
APDS993X_ERR("%s,line %d:regulator_is_enabled vio failed\n",__func__,__LINE__);
}
/* get regulator's value*/
excep->vdd_mv = regulator_get_voltage(data->vdd)/1000;
if(excep->vdd_mv < 0){
APDS993X_ERR("%s,line %d:regulator_get_voltage vdd failed\n",__func__,__LINE__);
}
excep->vio_mv = regulator_get_voltage(data->vio)/1000;
if(excep->vio_mv < 0){
APDS993X_ERR("%s,line %d:regulator_get_voltage vio failed\n",__func__,__LINE__);
}
/* report i2c err info */
ret = apds_dsm_report_i2c(data);
APDS993X_INFO("%s,line %d:i2c_scl_val=%d,i2c_sda_val=%d,vdd = %d, vdd_status = %d\n"
"vio=%d, vio_status=%d, excep_num=%d, i2c_err_num=%d",__func__,__LINE__
,excep->i2c_scl_val,excep->i2c_sda_val,excep->vdd_mv,excep->vdd_status
,excep->vio_mv,excep->vio_status,excep->excep_num,excep->i2c_err_num);
excep->i2c_err_num = 0;
return ret;
}
static int apds993x_set_command(struct i2c_client *client, int command)
{
struct apds993x_data *data = i2c_get_clientdata(client);
int ret;
int clearInt;
int loop;
if (command == 0)
clearInt = CMD_CLR_PS_INT;
else if (command == 1)
clearInt = CMD_CLR_ALS_INT;
else
clearInt = CMD_CLR_PS_ALS_INT;
loop = APDS993X_I2C_RETRY_COUNT;
/*we give three times to repeat the i2c operation if i2c errors happen*/
while(loop){
mutex_lock(&data->update_lock);
ret = i2c_smbus_write_byte(client, clearInt);
mutex_unlock(&data->update_lock);
if(ret < 0){
loop--;
mdelay(APDS993X_I2C_RETRY_TIMEOUT);
}
else
break;
}
/*after three times,we print the register and regulator value*/
if(loop == 0){
data->ls_test_exception.i2c_err_num = ret;
APDS993X_ERR("%s,line %d:attention: i2c write err = %d\n",__func__,__LINE__,ret);
apds_dump_i2c_exception_status(data);
}
APDS993X_FLOW("%s,line %d:command = %d\n",__func__,__LINE__,command);
return ret;
}
/*we use the unified the function for i2c write and read operation*/
static int apds993x_i2c_write(struct i2c_client*client, u8 reg, u16 value,bool flag)
{
int err,loop;
struct apds993x_data *data = i2c_get_clientdata(client);
loop = APDS993X_I2C_RETRY_COUNT;
/*we give three times to repeat the i2c operation if i2c errors happen*/
while(loop) {
mutex_lock(&data->update_lock);
/*0 is i2c_smbus_write_byte_data,1 is i2c_smbus_write_word_data*/
if(flag == APDS993X_I2C_BYTE)
{
err = i2c_smbus_write_byte_data(client, CMD_BYTE|reg, (u8)value);
}
else if(flag == APDS993X_I2C_WORD)
{
err = i2c_smbus_write_word_data(client, CMD_WORD|reg, value);
}
else
{
APDS993X_ERR("%s,line %d:attention: i2c write wrong flag\n",__func__,__LINE__);
mutex_unlock(&data->update_lock);
return -EINVAL;
}
mutex_unlock(&data->update_lock);
if(err < 0){
loop--;
mdelay(APDS993X_I2C_RETRY_TIMEOUT);
}
else
break;
}
/*after three times,we print the register and regulator value*/
if(loop == 0){
data->ls_test_exception.i2c_err_num = err;
APDS993X_ERR("%s,line %d:attention:i2c write err = %d\n",__func__,__LINE__,err);
apds_dump_i2c_exception_status(data);
}
return err;
}
static int apds993x_i2c_read(struct i2c_client*client, u8 reg,bool flag)
{
int err,loop;
struct apds993x_data *data = i2c_get_clientdata(client);
loop = APDS993X_I2C_RETRY_COUNT;
/*we give three times to repeat the i2c operation if i2c errors happen*/
while(loop) {
mutex_lock(&data->update_lock);
/*0 is i2c_smbus_read_byte_data,1 is i2c_smbus_read_word_data*/
if(flag == APDS993X_I2C_BYTE)
{
err = i2c_smbus_read_byte_data(client, CMD_BYTE|reg);
}
else if(flag == APDS993X_I2C_WORD)
{
err = i2c_smbus_read_word_data(client, CMD_WORD|reg);
}
else
{
APDS993X_ERR("%s,line %d:attention: i2c read wrong flag\n",__func__,__LINE__);
mutex_unlock(&data->update_lock);
return -EINVAL;
}
mutex_unlock(&data->update_lock);
if(err < 0){
loop--;
mdelay(APDS993X_I2C_RETRY_TIMEOUT);
}
else
break;
}
/*after three times,we print the register and regulator value*/
if(loop == 0){
data->ls_test_exception.i2c_err_num = err;
APDS993X_ERR("%s,line %d:attention: i2c read err = %d,reg=0x%x\n",__func__,__LINE__,err,reg);
apds_dump_i2c_exception_status(data);
}
return err;
}
/*
* print the registers value with proper format
*/
static int dump_reg_buf(struct apds993x_data *data,char *buf, int size,int enable)
{
int i=0;
mutex_lock(&data->update_lock);
if(enable)
printk("[enable]");
else
printk("[disable]");
printk(" reg_buf= ");
for(i = 0;i < size; i++){
printk("0x%2x ",buf[i]);
}
mutex_unlock(&data->update_lock);
printk("\n");
return 0;
}
static int apds933x_regs_debug_print(struct apds993x_data *data,int enable)
{
int i=0;
char reg_buf[APDS993X_REG_LEN];
struct i2c_client *client = data->client;
struct apds993x_platform_data *pdata = data->platform_data;
/* read registers[0x0~0x1a] value*/
for(i = 0; i < APDS993X_REG_LEN; i++ )
{
reg_buf[i] = apds993x_i2c_read(client,i,APDS993X_I2C_BYTE);
if(reg_buf[i] <0){
APDS993X_ERR("%s,line %d:read %d reg failed\n",__func__,__LINE__,i);
return reg_buf[i] ;
}
}
/* print the registers[0x0~0x1a] value in proper format*/
dump_reg_buf(data,reg_buf,APDS993X_REG_LEN,enable);
/* print some important parameters*/
APDS993X_INFO("parameters: a=%d, c=%d, d=%d,e=%d,f=%d\n",
pdata->ga_a_value,pdata->ga_c_value,pdata->ga_d_value,pdata->ga_e_value,pdata->ga_f_value);
return 0;
}
static int apds993x_set_enable(struct i2c_client *client, int enable)
{
int ret;
ret = apds993x_i2c_write(client, APDS993X_ENABLE_REG, enable,APDS993X_I2C_BYTE);
if (ret < 0){
APDS993X_ERR("%s,line %d:i2c error,enable = %d\n",__func__,__LINE__,enable);
return ret;
}
/*remove it,we have save the value of enable in another way*/
APDS993X_FLOW("%s,line %d:apds993x enable = %d\n",__func__,__LINE__,enable);
return ret;
}
static int apds993x_set_atime(struct i2c_client *client, int atime)
{
struct apds993x_data *data = i2c_get_clientdata(client);
int ret;
ret = apds993x_i2c_write(client,APDS993X_ATIME_REG, atime,APDS993X_I2C_BYTE);
if (ret < 0){
APDS993X_ERR("%s,line %d:i2c error,atime = %d\n",__func__,__LINE__,atime);
return ret;
}
data->atime = atime;
APDS993X_FLOW("%s,line %d:apds993x atime = %d\n",__func__,__LINE__,atime);
return ret;
}
static int apds993x_set_ptime(struct i2c_client *client, int ptime)
{
struct apds993x_data *data = i2c_get_clientdata(client);
int ret;
ret = apds993x_i2c_write(client,APDS993X_PTIME_REG, ptime,APDS993X_I2C_BYTE);
if (ret < 0){
APDS993X_ERR("%s,line %d:i2c error,ptime = %d\n",__func__,__LINE__,ptime);
return ret;
}
data->ptime = ptime;
APDS993X_FLOW("%s,line %d:apds993x ptime = %d\n",__func__,__LINE__,ptime);
return ret;
}
static int apds993x_set_wtime(struct i2c_client *client, int wtime)
{
struct apds993x_data *data = i2c_get_clientdata(client);
int ret;
ret = apds993x_i2c_write(client,APDS993X_WTIME_REG, wtime,APDS993X_I2C_BYTE);
if (ret < 0){
APDS993X_ERR("%s,line %d:i2c error,wtime = %d\n",__func__,__LINE__,wtime);
return ret;
}
data->wtime = wtime;
APDS993X_FLOW("%s,line %d:apds993x wtime = %d\n",__func__,__LINE__,wtime);
return ret;
}
static int apds993x_set_pilt(struct i2c_client *client, int threshold)
{
struct apds993x_data *data = i2c_get_clientdata(client);
int ret;
ret = apds993x_i2c_write(client,APDS993X_PILTL_REG, threshold,APDS993X_I2C_WORD);
if (ret < 0){
APDS993X_ERR("%s,line %d:i2c error,threshold = %d\n",__func__,__LINE__,threshold);
return ret;
}
data->pilt = threshold;
APDS993X_INFO("%s,line %d:set apds993x pilt =%d\n", __func__, __LINE__,threshold);
return ret;
}
static int apds993x_set_piht(struct i2c_client *client, int threshold)
{
struct apds993x_data *data = i2c_get_clientdata(client);
int ret;
ret = apds993x_i2c_write(client,APDS993X_PIHTL_REG, threshold,APDS993X_I2C_WORD);
if (ret < 0){
APDS993X_ERR("%s,line %d:i2c error,threshold = %d\n",__func__,__LINE__,threshold);
return ret;
}
data->piht = threshold;
APDS993X_INFO("%s,line %d:set apds993x piht =%d\n", __func__,__LINE__,threshold);
return ret;
}
static int apds993x_set_pers(struct i2c_client *client, int pers)
{
struct apds993x_data *data = i2c_get_clientdata(client);
int ret;
ret = apds993x_i2c_write(client,APDS993X_PERS_REG, pers,APDS993X_I2C_BYTE);
if (ret < 0){
APDS993X_ERR("%s,line %d:i2c error,pers = %d\n",__func__,__LINE__,pers);
return ret;
}
data->pers = pers;
APDS993X_FLOW("%s,line %d:apds993x pers = %d\n",__func__,__LINE__,pers);
return ret;
}
static int apds993x_set_config(struct i2c_client *client, int config)
{
struct apds993x_data *data = i2c_get_clientdata(client);
int ret;
ret = apds993x_i2c_write(client,APDS993X_CONFIG_REG, config,APDS993X_I2C_BYTE);
if (ret < 0){
APDS993X_ERR("%s,line %d:i2c error,config = %d\n",__func__,__LINE__,config);
return ret;
}
data->config = config;
APDS993X_FLOW("%s,line %d:apds993x config = %d\n",__func__,__LINE__,config);
return ret;
}
static int apds993x_set_ppcount(struct i2c_client *client, int ppcount)
{
struct apds993x_data *data = i2c_get_clientdata(client);
int ret;
ret = apds993x_i2c_write(client,APDS993X_PPCOUNT_REG, ppcount,APDS993X_I2C_BYTE);
if (ret < 0){
APDS993X_ERR("%s,line %d:i2c error,ppcount = %d\n",__func__,__LINE__,ppcount);
return ret;
}
data->ppcount = ppcount;
APDS993X_FLOW("%s,line %d:apds993x ppcount = %d\n",__func__,__LINE__,ppcount);
return ret;
}
static int apds993x_set_control(struct i2c_client *client, int control)
{
struct apds993x_data *data = i2c_get_clientdata(client);
int ret;
ret = apds993x_i2c_write(client,APDS993X_CONTROL_REG, control,APDS993X_I2C_BYTE);
if (ret < 0){
APDS993X_ERR("%s,line %d:i2c error,control = %d\n",__func__,__LINE__,control);
return ret;
}
data->control = control;
APDS993X_FLOW("%s,line %d:apds993x control = %d\n",__func__,__LINE__,control);
return ret;
}
static int LuxCalculation(struct i2c_client *client, int ch0data, int ch1data)
{
int luxValue=0;
int IAC1=0;
int IAC2=0;
int IAC=0;
if (ch0data >= APDS993X_CDATA_MAX || ch1data >= APDS993X_CDATA_MAX)
{
luxValue = APDS993X_LUX_MAX;
return luxValue;
}
/* re-adjust COE_B to avoid 2 decimal point */
IAC1 = (ch0data - (apds993x_coe_b* ch1data) / 1000);
/* re-adjust COE_C and COE_D to void 2 decimal point */
IAC2 = ((apds993x_coe_c * ch0data) / 1000 -(apds993x_coe_d * ch1data) / 1000);
if (IAC1 > IAC2)
{
IAC = IAC1;
}
else if (IAC1 <= IAC2)
{
IAC = IAC2;
}
else
{
IAC = 0;
}
if(IAC < 0)
{
IAC =IAC_last;
}
else
{
IAC_last = IAC;
}
/*In different color temprature light,we use different GA to calculate lux*/
/*A light*/
if(ch0data < apds993x_coe_e*ch1data/100)
{
luxValue = (IAC*apds993x_a_ga*APDS993X_DF)/100;
}
/*D light*/
else if((ch0data >= apds993x_coe_e*ch1data/100) && (ch0data <= apds993x_coe_f*ch1data/10))
{
luxValue = (IAC*apds993x_d_ga*APDS993X_DF)/100;
}
/*C light*/
else
{
luxValue = (IAC*apds993x_c_ga*APDS993X_DF)/100;
}
/*we use 100ms adc time,so the corresponding again is 1x*/
luxValue /= (272*(256-APDS993X_100MS_ADC_TIME)*APDS993X_AGAIN_1X_LUXCALCULATION/100);
APDS993X_FLOW("%s,line %d:ch0 = %d,ch1=%d,lux = %d\n",__func__,__LINE__,ch0data,ch1data,luxValue);
return (luxValue);
}
static void apds993x_dump_register(struct i2c_client *client,int status,int enable)
{
int wtime,ptime,atime,ppcount,control,config,pers;
wtime = apds993x_i2c_read(client, APDS993X_WTIME_REG,APDS993X_I2C_BYTE);
ptime= apds993x_i2c_read(client, APDS993X_PTIME_REG,APDS993X_I2C_BYTE);
atime =apds993x_i2c_read(client, APDS993X_ATIME_REG,APDS993X_I2C_BYTE);
ppcount=apds993x_i2c_read(client, APDS993X_PPCOUNT_REG,APDS993X_I2C_BYTE);
control=apds993x_i2c_read(client, APDS993X_CONTROL_REG,APDS993X_I2C_BYTE);
config = apds993x_i2c_read(client, APDS993X_CONFIG_REG,APDS993X_I2C_BYTE);
pers= apds993x_i2c_read(client, APDS993X_PERS_REG,APDS993X_I2C_BYTE);
APDS993X_INFO("%s,line %d:status = 0x%x,enable=0x%x,wtime=0x%x\n",__func__,__LINE__,status,enable,wtime);
APDS993X_INFO("%s,line %d:ptime = 0x%x,atime=0x%x,ppcount=0x%x\n",__func__,__LINE__,ptime,atime,ppcount);
APDS993X_INFO("%s,line %d:control = 0x%x,config=0x%x,pers=0x%x\n",__func__,__LINE__,control,config,pers);
}
static void apds993x_ps_report_event(struct i2c_client *client)
{
struct apds993x_data *data = i2c_get_clientdata(client);
int ret;
ret = apds993x_i2c_read(client, APDS993X_PDATAL_REG,APDS993X_I2C_WORD);
if( ret < 0 )
{
/* the number "200" is a value to make sure there is a valid value */
data->ps_data = 200 ;
APDS993X_ERR("%s, line %d: pdate<0, reset to %d\n", __func__, __LINE__, data->ps_data);
}else{
data->ps_data = ret ;
}
/*remove to interrupt function to avoid phone suspend and pls work still running*/
APDS993X_FLOW("%s,line %d:apds9930 ps_data=%d,ps_min_threshold=%d\n",__func__,__LINE__,data->ps_data,data->ps_min_threshold);
if ((data->ps_data + apds993x_pwave_value) < (data->ps_min_threshold))
{
data->ps_min_threshold = data->ps_data + apds993x_pwave_value;
ret = apds993x_i2c_write(client,APDS993X_PILTL_REG,data->ps_min_threshold,APDS993X_I2C_WORD);
ret += apds993x_i2c_write(client,APDS993X_PIHTL_REG,data->ps_min_threshold + apds993x_pwindow_value,APDS993X_I2C_WORD);
if (ret < 0)
{
APDS993X_ERR("%s,line %d:data->pilt = %d,data->piht=%d, i2c wrong\n",__func__,__LINE__,data->pilt,data->piht);
goto exit;
}
data->pilt = data->ps_min_threshold;
data->piht = data->ps_min_threshold + apds993x_pwindow_value;
APDS993X_INFO("%s,line %d:change threshoid,data->ps_data =%d,data->pilt=%d,data->piht=%d,\n", __func__,__LINE__,data->ps_data, data->pilt, data->piht);
if(data->pilt != cur_pthreshold_l || data->piht != cur_pthreshold_h)
{
cur_pthreshold_h = data->piht;
cur_pthreshold_l = data->pilt;
APDS993X_FLOW("%s,line %d:data->ps_data=%d data->pilt=%d data->piht=%d\n", __func__, __LINE__, data->ps_data, data->pilt, data->piht);
}
}
if (data->ps_data >= data->piht) {
/* far-to-near detected */
data->ps_detection = APDS993X_CLOSE_FLAG;
/* FAR-to-NEAR detection */
input_report_abs(data->input_dev_ps, ABS_DISTANCE, APDS993X_CLOSE_FLAG);
input_sync(data->input_dev_ps);
APDS993X_INFO("%s,line %d:PROXIMITY close event, data->ps_data =%d,data->pilt=%d,data->piht=%d,\n", __func__,__LINE__,data->ps_data, data->pilt, data->piht);
ret = apds993x_i2c_write(client,APDS993X_PILTL_REG,data->ps_min_threshold,APDS993X_I2C_WORD);
ret += apds993x_i2c_write(client,APDS993X_PIHTL_REG, (APDS993X_PROX_MAX_ADC_VALUE + 1),APDS993X_I2C_WORD);
if (ret < 0){
APDS993X_ERR("%s,line %d:data->pilt = %d,data->piht=%d, i2c wrong\n",__func__,__LINE__,data->pilt,data->piht);
goto exit;
}
data->pilt = data->ps_min_threshold;
data->piht = APDS993X_PROX_MAX_ADC_VALUE + 1;
APDS993X_INFO("%s,line %d:change threshoid,data->ps_data =%d,data->pilt=%d,data->piht=%d,\n", __func__,__LINE__,data->ps_data, data->pilt, data->piht);
if(data->pilt != cur_pthreshold_l || data->piht != cur_pthreshold_h)
{
cur_pthreshold_h = data->piht;
cur_pthreshold_l = data->pilt;
APDS993X_FLOW("%s,line %d:data->ps_data=%d data->pilt=%d data->piht=%d\n", __func__, __LINE__, data->ps_data, data->pilt, data->piht);
}
} else if ((data->ps_data <= data->pilt)) {
/* near-to-far detected */
data->ps_detection = APDS993X_FAR_FLAG;
/* NEAR-to-FAR detection */
input_report_abs(data->input_dev_ps, ABS_DISTANCE, APDS993X_FAR_FLAG);
input_sync(data->input_dev_ps);
APDS993X_INFO("%s,line %d:PROXIMITY far event, data->ps_data=%d,data->pilt=%d,data->piht=%d,\n", __func__,__LINE__,data->ps_data, data->pilt, data->piht);
ret = apds993x_i2c_write(client,APDS993X_PIHTL_REG,
data->ps_min_threshold + apds993x_pwindow_value,APDS993X_I2C_WORD);
ret += apds993x_i2c_write(client,APDS993X_PILTL_REG,0,APDS993X_I2C_WORD);
if (ret < 0){
APDS993X_ERR("%s,line %d:data->pilt = %d,data->piht=%d, i2c wrong\n",__func__,__LINE__,data->pilt,data->piht);
goto exit;
}
data->piht = data->ps_min_threshold + apds993x_pwindow_value;
data->pilt = 0;
APDS993X_INFO("%s,line %d:change threshoid,data->ps_data =%d,data->pilt=%d,data->piht=%d,\n", __func__,__LINE__,data->ps_data, data->pilt, data->piht);
if(data->pilt != cur_pthreshold_l || data->piht != cur_pthreshold_h)
{
cur_pthreshold_h = data->piht;
cur_pthreshold_l = data->pilt;
APDS993X_FLOW("%s:data->ps_data=%d data->pilt=%d data->piht=%d\n", __func__, data->ps_data, data->pilt, data->piht);
}
}
else{
APDS993X_ERR("%s,line %d:data->ps_data=%d,data->pilt = %d,data->piht=%d,wrong interrupts\n",__func__,__LINE__,data->ps_data, data->pilt,data->piht);
}
return ;
exit:
/*if i2c error happens,we report far event*/
if(data->ps_detection == APDS993X_CLOSE_FLAG)
{
input_report_abs(data->input_dev_ps, ABS_DISTANCE, APDS993X_FAR_FLAG);
input_sync(data->input_dev_ps);
data->ps_detection= APDS993X_FAR_FLAG;
APDS993X_ERR("%s:i2c error happens, report far event, data->ps_data:%d\n", __func__,data->ps_data);
return ;
}
}
/* delete apds993x_reschedule_work, we use queue_work to replase queue_delayed_work, because flush_delayed_work
may cause system stop work */
/* ALS polling routine */
static void apds993x_als_polling_work_handler(struct work_struct *work)
{
struct apds993x_data *data = container_of(work, struct apds993x_data,als_dwork);
struct i2c_client *client=data->client;
int ch0data, ch1data, pdata;
int luxValue=0;
unsigned char lux_is_valid=1;
ch0data = apds993x_i2c_read(client,
APDS993X_CH0DATAL_REG,APDS993X_I2C_WORD);
ch1data = apds993x_i2c_read(client,
APDS993X_CH1DATAL_REG,APDS993X_I2C_WORD);
pdata = apds993x_i2c_read(client,
APDS993X_PDATAL_REG,APDS993X_I2C_WORD);
if(ch0data < 0 || ch1data < 0 || pdata < 0)
{
/* don't report, this is invalid lux value */
lux_is_valid = 0;
luxValue = data->als_prev_lux;
}
else
{
luxValue = LuxCalculation(client, ch0data, ch1data);
}
if (luxValue >= 0)
{
luxValue = luxValue < APDS993X_LUX_MAX? luxValue : APDS993X_LUX_MAX;
data->als_prev_lux = luxValue;
}
else
{
/* don't report, this is invalid lux value */
lux_is_valid = 0;
luxValue = data->als_prev_lux;
}
/*remove it because we use other judge method to decide if pls close event is triggered by sunlight*/
if (lux_is_valid) {
/* report the lux level */
input_report_abs(data->input_dev_als, ABS_MISC, luxValue);
input_sync(data->input_dev_als);
APDS993X_FLOW("%s,line %d:apds9930 lux=%d\n",__func__,__LINE__,luxValue);
}
/* restart timer */
/* start a work after 200ms */
if (0 != hrtimer_start(&data->timer,
ktime_set(0, data->als_poll_delay * 1000000), HRTIMER_MODE_REL) )
{
APDS993X_ERR("%s: hrtimer_start fail! nsec=%d\n", __func__, data->als_poll_delay);
}
}
/*****************************************************************
Parameters : timer
Return : HRTIMER_NORESTART
Description : hrtimer_start call back function,
use to report als data
*****************************************************************/
static enum hrtimer_restart apds993x_als_timer_func(struct hrtimer *timer)
{
struct apds993x_data* data = container_of(timer,struct apds993x_data,timer);
queue_work(apds993x_workqueue, &data->als_dwork);
return HRTIMER_NORESTART;
}
/* PS interrupt routine */
static void apds993x_work_handler(struct work_struct *work)
{
struct apds993x_data *data = container_of(work, struct apds993x_data, dwork);
struct i2c_client *client=data->client;
int status;
int enable;
int ret;
int pdata;
int ps_saturation_flag;/*1:pls current is over by strong sunlight*/
mutex_lock(&data->single_lock);
pdata = apds993x_i2c_read(client, APDS993X_PDATAL_REG,APDS993X_I2C_WORD);
status = apds993x_i2c_read(client, APDS993X_STATUS_REG,APDS993X_I2C_BYTE);
enable = apds993x_i2c_read(client, APDS993X_ENABLE_REG,APDS993X_I2C_BYTE);
if((apds993x_debug_mask > 1)||(pdata == APDS993X_PROX_MAX_ADC_VALUE + 1))
{
apds993x_dump_register(client,status,enable);
}
/* disable 993x's ADC first */
ret = apds993x_i2c_write(client, APDS993X_ENABLE_REG, 0x01,APDS993X_I2C_BYTE);
if (ret < 0){
APDS993X_ERR("%s,line %d:I2c write error happens\n",__func__,__LINE__);
/*if the I2C error happens,firstly we check if suspend is already used.*/
apds993x_error_flag = APDS993X_ERROR_HAPPEN;
if(APDS993X_SUSPEND_ON == apds993x_suspend_flag)
{
/*report the opposite pls event to wake up phone,at least we hope so*/
if(APDS993X_CLOSE_FLAG == data->ps_detection)
{
input_report_abs(data->input_dev_ps, ABS_DISTANCE, APDS993X_FAR_FLAG);
input_sync(data->input_dev_ps);
APDS993X_ERR("%s,%d:i2c error happens, report far event\n", __func__,__LINE__);
}
else if(APDS993X_FAR_FLAG == data->ps_detection)
{
input_report_abs(data->input_dev_ps, ABS_DISTANCE, APDS993X_CLOSE_FLAG);
input_sync(data->input_dev_ps);
APDS993X_ERR("%s,%d:i2c error happens, report near event\n", __func__,__LINE__);
}
else
{
/*this condition hardly happens*/
APDS993X_ERR("%s,%d:i2c error happens, data->ps_detection = %d is wrong\n", __func__,__LINE__,data->ps_detection);
}
}
mutex_unlock(&data->single_lock);
return ;
}
if ((status & enable & 0x20) == 0x20) {
/* only PS is interrupted */
APDS993X_FLOW("%s,line %d:only PLS is detected.\n",__func__,__LINE__);
/* check if this is triggered by background ambient noise */
ps_saturation_flag = status & 0x40;
APDS993X_FLOW("%s,line %d:apds993x_ps_report_event, ps_saturation_flag:%d\n", __func__,__LINE__,ps_saturation_flag);
/*In the case of ambient light never turned on, ch0data=0*/
/*if strong sunlight trigger PS close event,ps_saturation_flag =1 not 0*/
if (ps_saturation_flag == APDS993X_SATURATION_NOT_OVER)
{
apds993x_ps_report_event(client);
}
else
{
if (data->ps_detection == APDS993X_CLOSE_FLAG)
apds993x_ps_report_event(client);
else
APDS993X_INFO("%s: background ambient noise\n",__func__);
}
} else{
APDS993X_ERR("%s,line %d:wrong interrupts,APDS993X_STATUS_REG is 0X%x\n",__func__,__LINE__,status);
}
/* 0 = CMD_CLR_PS_INT */
apds993x_set_command(client, 0);
ret = apds993x_i2c_write(client,APDS993X_ENABLE_REG, data->enable,APDS993X_I2C_BYTE);
mutex_unlock(&data->single_lock);
if (ret < 0)
{
APDS993X_ERR("%s,%d:i2c error happens, als and pls disabled,data->enable = %d\n", __func__,__LINE__,data->enable);
return ;
}
if (data->irq)
{
enable_irq(data->irq);
}
}
/* assume this is ISR */
static irqreturn_t apds993x_interrupt(int vec, void *info)
{
struct i2c_client *client=(struct i2c_client *)info;
struct apds993x_data *data = i2c_get_clientdata(client);
/*in 400ms,system keeps in wakeup state to avoid the sleeling system lose the pls event*/
APDS993X_FLOW("%s,line %d:interrupt is coming.\n",__func__,__LINE__);
disable_irq_nosync(data->irq);
wake_lock_timeout(&data->ps_report_wk, PS_WAKEUP_TIME);
/* and ps data report function to workqueue */
queue_work(apds993x_workqueue, &data->dwork);
return IRQ_HANDLED;
}
/*
* IOCTL support
*/
static int apds993x_enable_als_sensor(struct i2c_client *client, int val)
{
struct apds993x_data *data = i2c_get_clientdata(client);
struct apds993x_platform_data *pdata = data->platform_data;
int ret;
/*Not in use power_value*/
APDS993X_FLOW("%s,line %d:enable als val=%d\n",__func__,__LINE__,val);
/*Not in use power_value*/
mutex_lock(&data->single_lock);
if (val == 1) {
/* turn on light sensor */
if (data->enable_als_sensor == 0) {
if(data->enable_ps_sensor == 0){
/* Power on and initalize the device */
if (pdata->power_on)
pdata->power_on(true,data);
ret = apds993x_init_client(client);
if (ret) {
APDS993X_ERR("%s:line:%d,Failed to init apds993x\n", __func__, __LINE__);
mutex_unlock(&data->single_lock);
return ret;
}
}
data->enable_als_sensor = 1;
data->enable = (data->enable)|0x03;
apds993x_set_enable(client, data->enable);
APDS993X_INFO("%s: line:%d enable als sensor,data->enable=0x%x\n", __func__, __LINE__, data->enable);
/* enable als sensor, start data report hrtimer */
ret = hrtimer_start(&data->timer, ktime_set(0, data->als_poll_delay * 1000000), HRTIMER_MODE_REL);
if (ret != 0) {
APDS993X_ERR("%s: hrtimer_start fail! nsec=%d\n", __func__, data->als_poll_delay);
}
}
} else {
/*
* turn off light sensor
* what if the p sensor is active?
*/
if(data->enable_als_sensor == 1)
{
data->enable_als_sensor = 0;
if(data->enable_ps_sensor ==1)
{
data->enable = (data->enable)&0xfd;
apds993x_set_enable(client, data->enable);
}
else
{
data->enable = 0x00;
apds993x_set_enable(client, data->enable);
}
APDS993X_INFO("%s: line:%d,disable als sensor,data->enable = 0x%x\n", __func__, __LINE__,data->enable);
/* disable als sensor, cancne data report hrtimer */
hrtimer_cancel(&data->timer);
cancel_work_sync(&data->als_dwork);
}
}
/* Vote off regulators if both light and prox sensor are off */
if ((data->enable_als_sensor == 0) &&(data->enable_ps_sensor == 0) &&(pdata->power_on)){
pdata->power_on(false,data);
}
mutex_unlock(&data->single_lock);
APDS993X_FLOW("%s: line:%d,enable als sensor success\n", __func__, __LINE__);
return 0;
}
static int apds993x_open_ps_sensor(struct apds993x_data *data, struct i2c_client *client)
{
int ret = 0;
/* turn on p sensor */
if (data->enable_ps_sensor==0) {
if(data->enable_als_sensor == 0){
/* Power on and initalize the device */
if (data->platform_data->power_on)
data->platform_data->power_on(true,data);
ret = apds993x_init_client(client);
if (ret) {
APDS993X_ERR("%s:line:%d,Failed to init apds993x\n", __func__, __LINE__);
return ret;
}
}
data->enable_ps_sensor= 1;
/*initialize the ps_min_threshold,to update data->piht and data->pilt*/
data->ps_min_threshold = origin_prox;
APDS993X_FLOW("%s,line %d:change threshoid,data->ps_min_threshold =%d\n",__func__,__LINE__,data->ps_min_threshold);
ret = apds993x_i2c_write(client,APDS993X_PILTL_REG,far_init,APDS993X_I2C_WORD);
ret += apds993x_i2c_write(client,APDS993X_PIHTL_REG,near_init,APDS993X_I2C_WORD);
if (ret < 0)
return ret;
APDS993X_INFO("%s,line %d:change threshoid,data->ps_data =%d,data->pilt=%d,data->piht=%d,\n", __func__,__LINE__,data->ps_data, data->pilt, data->piht);
/*we use our own calibration algorithm,more details of the algorithm you can check apds993x_ps_report_event*/
if (data->irq)
{
enable_irq(data->irq);
/*set the property of pls irq,so the pls irq can wake up the sleeping system */
irq_set_irq_wake(data->irq, 1);
}
data->enable = (data->enable) |0x25;
apds993x_set_enable(client, data->enable);
APDS993X_INFO("%s: line:%d,enable pls sensor.data->enable = 0x%x\n", __func__, __LINE__,data->enable);
/* 0 is close, 1 is far */
input_report_abs(data->input_dev_ps, ABS_DISTANCE, APDS993X_FAR_FLAG);
input_sync(data->input_dev_ps);
APDS993X_INFO("%s,line %d:input_report_abs report ABS_DISTANCE, far event, data->ps_data:%d\n", __func__,__LINE__,data->ps_data);
/* move this codes befor apds993x_set_enable*/
}
return ret;
}
static int apds993x_enable_ps_sensor(struct i2c_client *client,unsigned int val)
{
struct apds993x_data *data = i2c_get_clientdata(client);
int ret;
/*Not in use power_value*/
APDS993X_FLOW("%s,line %d:val=%d\n",__func__,__LINE__,val);
if ((val != 0) && (val != 1)) {
APDS993X_ERR("%s: invalid value=%d\n", __func__, val);
return -EINVAL;
}
/*Not in use power_value*/
if (val == 1) {
mutex_lock(&data->single_lock);
ret = apds993x_open_ps_sensor(data, client);
mutex_unlock(&data->single_lock);
if(ret)
{
APDS993X_ERR("%s,line %d:read power_value failed,open ps fail\n",__func__,__LINE__);
return ret;
}
power_key_ps = false;
schedule_delayed_work(&data->powerkey_work, msecs_to_jiffies(100));
} else {
/*
* turn off p sensor - kk 25 Apr 2011
* we can't turn off the entire sensor,
* the light sensor may be needed by HAL
*/
if (data->enable_ps_sensor==1) {
mutex_lock(&data->single_lock);
data->enable_ps_sensor = 0;
if(data->enable_als_sensor ==1)
{
data->enable = (data->enable)&0xcb;
apds993x_set_enable(client, data->enable);
}
else
{
data->enable= 0x00;
apds993x_set_enable(client, data->enable);
}
mutex_unlock(&data->single_lock);
APDS993X_INFO("%s: line:%d,disable pls sensor,data->enable = 0x%x\n", __func__, __LINE__,data->enable);
cancel_work_sync(&data->dwork);
cancel_delayed_work(&data->powerkey_work);
if (data->irq)
{
/*when close the pls,make the wakeup property diabled*/
irq_set_irq_wake(data->irq, 0);
disable_irq(data->irq);
}
}
}
/* Vote off regulators if both light and prox sensor are off */
if ((data->enable_als_sensor == 0) &&(data->enable_ps_sensor == 0) &&(data->platform_data->power_on)){
data->platform_data->power_on(false,data);
}
return 0;
}
/*
* SysFS support
*/
static int apds993x_als_set_enable(struct sensors_classdev *sensors_cdev,
unsigned int enable)
{
int ret = 0;
static int als_enalbe_count=0;
struct apds993x_data *data = container_of(sensors_cdev,struct apds993x_data, als_cdev);
if ((enable != 0) && (enable != 1)) {
APDS993X_ERR("%s: invalid value(%d)\n", __func__, enable);
return -EINVAL;
}
APDS993X_FLOW("%s,line %d:apds9930 als enable=%d\n",__func__,__LINE__,enable);
/*for debug and print registers value when enable/disable the als every time*/
if(enable == 0)
{
if(apds993x_debug_mask >= 1){
APDS993X_FLOW("attention:before als_disable %d times\n", als_enalbe_count);
apds933x_regs_debug_print(data,enable);
}
apds993x_enable_als_sensor(data->client, enable);
}else{
apds993x_enable_als_sensor(data->client, enable);
if(apds993x_debug_mask >= 1){
APDS993X_FLOW("attention: after als_enable %d times\n",++als_enalbe_count);
apds933x_regs_debug_print(data,enable);
}
}
return ret;
}
static int apds993x_ps_set_enable(struct sensors_classdev *sensors_cdev,
unsigned int enable)
{
struct apds993x_data *data = container_of(sensors_cdev,
struct apds993x_data, ps_cdev);
if ((enable != 0) && (enable != 1)) {
APDS993X_ERR("%s: invalid value(%d)\n", __func__, enable);
return -EINVAL;
}
APDS993X_FLOW("%s,line %d:apds9930 enable ps value=(%d)\n",__func__,__LINE__, enable);
return apds993x_enable_ps_sensor(data->client, enable);
}
/*use this function to reset the poll_delay time(ms),val is the time parameter*/
static int apds993x_set_als_poll_delay(struct i2c_client *client,
unsigned int val)
{
struct apds993x_data *data = i2c_get_clientdata(client);
int ret;
int atime_index;
/* minimum 10ms */
if (val < 10)
val = 10;
data->als_poll_delay = 200;
/*atime value,0xDB is 100.64ms;0xED is 51.68ms;0xF6 is 27.2ms*/
atime_index = APDS993X_100MS_ADC_TIME;
ret = apds993x_set_atime(client, atime_index);
if (ret >= 0) {
APDS993X_INFO("%s,line %d:poll delay %d, atime_index %d",__func__,__LINE__,
data->als_poll_delay, atime_index);
} else {
APDS993X_ERR("%s,line %d:SET ATIME FAIL,poll delay %d, atime_index %d",__func__,__LINE__,
data->als_poll_delay, atime_index);
return ret;
}
/*
* If work is already scheduled then subsequent schedules will not
* change the scheduled time that's why we have to cancel it first.
*/
hrtimer_cancel(&data->timer);
cancel_work_sync(&data->als_dwork);
ret = hrtimer_start(&data->timer, ktime_set(0, data->als_poll_delay * 1000000), HRTIMER_MODE_REL);
if (ret != 0) {
APDS993X_ERR("%s,line%d: hrtimer_start fail! nsec=%d\n", __func__, __LINE__,data->als_poll_delay);
return ret;
}
return 0;
}
static int apds993x_als_poll_delay(struct sensors_classdev *sensors_cdev,
unsigned int delay_msec)
{
struct apds993x_data *data = container_of(sensors_cdev,
struct apds993x_data, als_cdev);
apds993x_set_als_poll_delay(data->client, delay_msec);
return 0;
}
static ssize_t apds993x_show_ch0data(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
int ch0data;
ch0data = apds993x_i2c_read(client,APDS993X_CH0DATAL_REG,APDS993X_I2C_WORD);
return snprintf(buf,32,"%d\n", ch0data);
}
static DEVICE_ATTR(ch0data, S_IRUGO, apds993x_show_ch0data, NULL);
static ssize_t apds993x_show_ch1data(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
int ch1data;
ch1data = apds993x_i2c_read(client,APDS993X_CH1DATAL_REG,APDS993X_I2C_WORD);
return snprintf(buf,32, "%d\n", ch1data);
}
static DEVICE_ATTR(ch1data, S_IRUGO, apds993x_show_ch1data, NULL);
static ssize_t apds993x_show_pdata(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
int pdata;
pdata = apds993x_i2c_read(client, APDS993X_PDATAL_REG,APDS993X_I2C_WORD);
if(pdata <0){
APDS993X_ERR("%s,line %d:read pdata failed\n",__func__,__LINE__);
}
return snprintf(buf,32, "%d\n", pdata);
}
static DEVICE_ATTR(pdata, S_IRUGO, apds993x_show_pdata, NULL);
/*
* set the register's value from userspace
* Usage: echo "0x08|0x12" > dump_reg
* "reg_address|reg_value"
*/
static ssize_t apds993x_write_reg(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct apds993x_data *data = i2c_get_clientdata(client);
int val_len_max = 4;
char* input_str =NULL;
char reg_addr_str[10]={'\0'};
char reg_val_str[10]={'\0'};
long reg_addr,reg_val;
int addr_lenth=0,value_lenth=0,buf_len=0,ret = -1;
char* strtok=NULL;
buf_len = strlen(buf);
input_str = kzalloc(buf_len, GFP_KERNEL);
if (!input_str)
{
pr_err("%s:kmalloc fail!\n",__func__);
return -ENOMEM;
}
mutex_lock(&data->update_lock);
snprintf(input_str, 10,"%s", buf);
/*Split the string when encounter "|", for example "0x08|0x12" will be splited "0x18" "0x12" */
strtok=strsep(&input_str, "|");
if(strtok!=NULL)
{
addr_lenth = strlen(strtok);
memcpy(reg_addr_str,strtok,((addr_lenth > (val_len_max))?(val_len_max):addr_lenth));
}
else
{
pr_err("%s: buf name Invalid:%s", __func__,buf);
goto parse_fail_exit;
}
strtok=strsep(&input_str, "|");
if(strtok!=NULL)
{
value_lenth = strlen(strtok);
memcpy(reg_val_str,strtok,((value_lenth > (val_len_max))?(val_len_max):value_lenth));
}
else
{
pr_err("%s: buf value Invalid:%s", __func__,buf);
goto parse_fail_exit;
}
/* transform string to long int */
ret = kstrtol(reg_addr_str,16,®_addr);
if(ret)
goto parse_fail_exit;
ret = kstrtol(reg_val_str,16,®_val);
if(ret)
goto parse_fail_exit;
/* write the parsed value in the register*/
ret = apds993x_i2c_write(client,(char)reg_addr,(char)reg_val,APDS993X_I2C_BYTE);
if (ret < 0){
goto parse_fail_exit;
}
mutex_unlock(&data->update_lock);
return count;
parse_fail_exit:
mutex_unlock(&data->update_lock);
if (input_str)
kfree(input_str);
return ret;
}
/*
* show all registers' value to userspace
*/
static ssize_t apds993x_print_reg_buf(struct device *dev,
struct device_attribute *attr, char *buf)
{
int i;
char reg[APDS993X_REG_LEN];
struct i2c_client *client = to_i2c_client(dev);
/* read all register value and print to user*/
for(i = 0; i < APDS993X_REG_LEN; i++ )
{
reg[i] = apds993x_i2c_read(client,i,APDS993X_I2C_BYTE);
if(reg[i] <0){
APDS993X_ERR("%s,line %d:read %d reg failed\n",__func__,__LINE__,i);
return reg[i] ;
}
}
return snprintf(buf,512,"reg[0x0~0x8]=0x%2x, 0x%2x, 0x%2x, 0x%2x, 0x%2x, 0x%2x, 0x%2x, 0x%2x, 0x%2x\n"
"reg[0x09~0x11]0x%2x, 0x%2x, 0x%2x, 0x%2x, 0x%2x, 0x%2x, 0x%2x, 0x%2x, 0x%2x\n"
"reg[0x12~0x19]0x%2x, 0x%2x, 0x%2x, 0x%2x, 0x%2x, 0x%2x, 0x%2x, 0x%2x\n",
reg[0x00],reg[0x01],reg[0x02],reg[0x03],reg[0x04],reg[0x05],reg[0x06],reg[0x07],reg[0x08],
reg[0x09],reg[0x0a],reg[0x0b],reg[0x0c],reg[0x0d],reg[0x0e],reg[0x0f],reg[0x10],reg[0x11],
reg[0x12],reg[0x13],reg[0x14],reg[0x15],reg[0x16],reg[0x17],reg[0x18],reg[0x19]);
}
static DEVICE_ATTR(dump_reg ,S_IRUGO|S_IWUSR|S_IWGRP, apds993x_print_reg_buf, apds993x_write_reg);
/*
* test data or i2c error interface for device monitor
*/
static ssize_t apds993x_sysfs_dsm_test(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct apds993x_data *data = i2c_get_clientdata(client);
long mode;
int ret = 0;
if (strict_strtol(buf, 10, &mode))
return -EINVAL;
if(mode > 0)
ret = apds_dump_i2c_exception_status(data);
return ret;
}
static DEVICE_ATTR(dsm_excep,S_IWUSR|S_IWGRP, NULL, apds993x_sysfs_dsm_test);
static struct attribute *apds993x_attributes[] = {
&dev_attr_ch0data.attr,
&dev_attr_ch1data.attr,
&dev_attr_pdata.attr,
&dev_attr_dump_reg.attr,
&dev_attr_dsm_excep.attr,
NULL
};
static const struct attribute_group apds993x_attr_group = {
.attrs = apds993x_attributes,
};
/*
* Initialization function
*/
static int apds993x_read_device_id(struct i2c_client *client)
{
int id;
int err;
id = apds993x_i2c_read(client, APDS993X_ID_REG,APDS993X_I2C_BYTE);
if (id == 0x30) {
APDS993X_INFO("%s: APDS9931\n", __func__);
err = app_info_set("LP-Sensor", "APS9931/TMD27723T");
if (err < 0)/*failed to add app_info*/
{
APDS993X_ERR("%s %d:failed to add app_info\n", __func__, __LINE__);
}
} else if (id == 0x39) {
APDS993X_INFO("%s: APDS9930\n", __func__);
err = app_info_set("LP-Sensor", "APS9930/TMD27723T");
if (err < 0)/*failed to add app_info*/
{
APDS993X_ERR("%s %d:failed to add app_info\n", __func__, __LINE__);
}
} else {
APDS993X_INFO("%s: Neither APDS9931 nor APDS9930\n", __func__);
return -ENODEV;
}
return 0;
}
static int apds993x_init_client(struct i2c_client *client)
{
struct apds993x_data *data = i2c_get_clientdata(client);
int err;
data->enable = 0x00;
err = apds993x_set_enable(client, data->enable);
if (err < 0)
{
APDS993X_ERR("%s,line%d:apds993x_set_enable FAIL ",__func__,__LINE__);
return err;
}
/* 100.64ms ALS integration time */
err = apds993x_set_atime(client,APDS993X_100MS_ADC_TIME);
if (err < 0)
{
APDS993X_ERR("%s,line%d:apds993x_set_atime FAIL ",__func__,__LINE__);
return err;
}
/* 2.72ms Prox integration time */
err = apds993x_set_ptime(client, 0xFF);
if (err < 0)
{
APDS993X_ERR("%s,line%d:apds993x_set_ptime FAIL ",__func__,__LINE__);
return err;
}
/* 2.72ms Wait time the value is 0xff,the value is changeable*/
err = apds993x_set_wtime(client, 0xb6);
if (err < 0)
{
APDS993X_ERR("%s,line%d:apds993x_set_wtime FAIL ",__func__,__LINE__);
return err;
}
err = apds993x_set_ppcount(client, 0xC);
if (err < 0)
{
APDS993X_ERR("%s,line%d:apds993x_set_ppcount FAIL ",__func__,__LINE__);
return err;
}
/* no long wait */
err = apds993x_set_config(client, 0);
if (err < 0)
{
APDS993X_ERR("%s,line%d:apds993x_set_config FAIL ",__func__,__LINE__);
return err;
}
err = apds993x_set_control(client,
APDS993X_PDRVIE_50MA |
APDS993X_PRX_IR_DIOD |
APDS993X_PGAIN_1X|APDS993X_AGAIN_1X);
if (err < 0)
{
APDS993X_ERR("%s,line%d:apds993x_set_control FAIL ",__func__,__LINE__);
return err;
}
/* init threshold for proximity */
err = apds993x_set_pilt(client, apds993x_ps_init_threshold-1);
if (err < 0)
{
APDS993X_ERR("%s,line%d:apds993x_set_pilt FAIL ",__func__,__LINE__);
return err;
}
err = apds993x_set_piht(client, apds993x_ps_init_threshold);
if (err < 0)
{
APDS993X_ERR("%s,line%d:apds993x_set_piht FAIL ",__func__,__LINE__);
return err;
}
data->ps_detection = APDS993X_FAR_FLAG; /* initial value = far*/
/* 2 consecutive Interrupt persistence */
err = apds993x_set_pers(client, APDS993X_PPERS_1|APDS993X_APERS_2);
if (err < 0)
{
APDS993X_ERR("%s,line%d:apds993x_set_pers FAIL ",__func__,__LINE__);
return err;
}
/* sensor is in disabled mode but all the configurations are preset */
return 0;
}
/*qualcom updated the regulator configure functions and we add them all*/
static int sensor_regulator_configure(struct apds993x_data *data, bool on)
{
int rc;
if (!on) {
if (regulator_count_voltages(data->vdd) > 0)
regulator_set_voltage(data->vdd, 0,
APDS993X_VDD_MAX_UV);
regulator_put(data->vdd);
if (regulator_count_voltages(data->vio) > 0)
regulator_set_voltage(data->vio, 0,
APDS993X_VIO_MAX_UV);
regulator_put(data->vio);
} else {
data->vdd = regulator_get(&data->client->dev, "vdd");
if (IS_ERR(data->vdd)) {
rc = PTR_ERR(data->vdd);
APDS993X_ERR("%s,line%d:Regulator get failed vdd rc=%d\n",__func__,__LINE__, rc);
return rc;
}
if (regulator_count_voltages(data->vdd) > 0) {
rc = regulator_set_voltage(data->vdd,
APDS993X_VDD_MIN_UV, APDS993X_VDD_MAX_UV);
if (rc) {
APDS993X_ERR("%s,line%d:Regulator set failed vdd rc=%d\n",__func__,__LINE__,rc);
goto reg_vdd_put;
}
}
data->vio = regulator_get(&data->client->dev, "vio");
if (IS_ERR(data->vio)) {
rc = PTR_ERR(data->vio);
APDS993X_ERR("%s,line%d:Regulator get failed vio rc=%d\n",__func__,__LINE__, rc);
goto reg_vdd_set;
}
if (regulator_count_voltages(data->vio) > 0) {
rc = regulator_set_voltage(data->vio,
APDS993X_VIO_MIN_UV, APDS993X_VIO_MAX_UV);
if (rc) {
APDS993X_ERR("%s,line%d:Regulator set failed vio rc=%d\n",__func__,__LINE__, rc);
goto reg_vio_put;
}
}
}
return 0;
reg_vio_put:
regulator_put(data->vio);
reg_vdd_set:
if (regulator_count_voltages(data->vdd) > 0)
regulator_set_voltage(data->vdd, 0, APDS993X_VDD_MAX_UV);
reg_vdd_put:
regulator_put(data->vdd);
return rc;
}
/*In suspend and resume function,we only control the als,leave pls alone*/
static int apds993x_suspend(struct i2c_client *client, pm_message_t mesg)
{
struct apds993x_data *data = i2c_get_clientdata(client);
int rc;
APDS993X_INFO("%s,line%d:APDS993X SUSPEND\n",__func__,__LINE__);
/*hrtimer and work will canceled at apds993x_enable_als_sensor*/
/*
* Save sensor state and disable them,
* this is to ensure internal state flags are set correctly.
* device will power off after both sensors are disabled.
* P sensor will not be disabled because it is a wakeup sensor.
*/
data->enable_als_state = data->enable_als_sensor;
apds993x_suspend_flag = APDS993X_SUSPEND_ON;
if(data->enable_als_sensor){
APDS993X_INFO("%s,line%d:APDS993X SUSPEND and disable als\n",__func__,__LINE__);
rc = apds993x_enable_als_sensor(data->client, 0);
if (rc){
APDS993X_ERR("%s,line%d:Disable light sensor fail! rc=%d\n",__func__,__LINE__, rc);
}
}
return 0;
}
static int apds993x_resume(struct i2c_client *client)
{
struct apds993x_data *data = i2c_get_clientdata(client);
int ret = 0;
apds993x_suspend_flag = APDS993X_SUSPEND_OFF;
APDS993X_INFO("%s,line%d:APDS993X RESUME\n",__func__,__LINE__);
if(APDS993X_ERROR_HAPPEN == apds993x_error_flag)
{
/* 0 = CMD_CLR_PS_INT */
apds993x_set_command(client, 0);
if (data->irq)
{
enable_irq(data->irq);
}
apds993x_error_flag = APDS993X_ERROR_NOTHAPPEN;
}
if (data->enable_als_state) {
ret = apds993x_enable_als_sensor(data->client, 1);
if (ret){
APDS993X_ERR("%s,line%d:Disable light sensor fail! rc=%d\n",__func__,__LINE__, ret);
}
}
return 0;
}
/*pamameter subfunction of probe to reduce the complexity of probe function*/
static int apds993x_sensorclass_init(struct apds993x_data *data,struct i2c_client* client)
{
int err;
/* Register to sensors class */
data->als_cdev = sensors_light_cdev;
data->als_cdev.sensors_enable = apds993x_als_set_enable;
data->als_cdev.sensors_poll_delay = apds993x_als_poll_delay;
data->ps_cdev = sensors_proximity_cdev;
data->ps_cdev.sensors_enable = apds993x_ps_set_enable;
data->ps_cdev.sensors_poll_delay = NULL;
err = sensors_classdev_register(&client->dev, &data->als_cdev);
if (err) {
APDS993X_ERR("%s: Unable to register to sensors class: %d\n",__func__, err);
goto exit;
}
err = sensors_classdev_register(&client->dev, &data->ps_cdev);
if (err) {
APDS993X_ERR("%s: Unable to register to sensors class: %d\n",__func__, err);
goto exit_unregister_als_class;
}
goto exit;
exit_unregister_als_class:
sensors_classdev_unregister(&data->als_cdev);
exit:
return err;
}
static void apds993x_parameter_init(struct apds993x_data *data)
{
/* Set the default parameters */
apds993x_a_ga= data->platform_data->ga_a_value;
apds993x_c_ga= data->platform_data->ga_c_value;
apds993x_d_ga= data->platform_data->ga_d_value;
apds993x_pwave_value= data->platform_data->pwave;
apds993x_pwindow_value= data->platform_data->pwindow;
apds993x_coe_e = data->platform_data->ga_e_value;
apds993x_coe_f = data->platform_data->ga_f_value;
apds993x_coe_b = data->platform_data->als_B;
apds993x_coe_c = data->platform_data->als_C;
apds993x_coe_d = data->platform_data->als_D;
data->enable = 0x00; /* default mode is standard */
data->ps_min_threshold = origin_prox;
APDS993X_FLOW("%s:set origin_prox to data->ps_min_threshold=%d\n", __func__, data->ps_min_threshold);
data->enable_als_sensor = 0; // default to 0
data->enable_ps_sensor = 0; // default to 0
data->als_poll_delay = 200; // default to 200ms
data->als_prev_lux = 300;
}
/*input init subfunction of probe to reduce the complexity of probe function*/
static int apds993x_input_init(struct apds993x_data *data)
{
int err = 0;
/* Register to Input Device */
data->input_dev_als = input_allocate_device();
if (!data->input_dev_als) {
err = -ENOMEM;
APDS993X_ERR("%s: Failed to allocate input device als\n", __func__);
goto exit;
}
data->input_dev_ps = input_allocate_device();
if (!data->input_dev_ps) {
err = -ENOMEM;
input_free_device(data->input_dev_als);
APDS993X_ERR("%s: Failed to allocate input device ps\n", __func__);
goto exit;
}
set_bit(EV_ABS, data->input_dev_als->evbit);
set_bit(EV_ABS, data->input_dev_ps->evbit);
input_set_abs_params(data->input_dev_als, ABS_MISC, 0, 10000, 0, 0);
input_set_abs_params(data->input_dev_ps, ABS_DISTANCE, 0, 5, 0, 0);
data->input_dev_als->name = "light";
data->input_dev_ps->name = "proximity";
err = input_register_device(data->input_dev_als);
if (err) {
err = -ENOMEM;
input_free_device(data->input_dev_als);
input_free_device(data->input_dev_ps);
APDS993X_ERR("%s: Unable to register input device als: %s\n",
__func__, data->input_dev_als->name);
goto exit;
}
err = input_register_device(data->input_dev_ps);
if (err) {
err = -ENOMEM;
APDS993X_ERR("%s: Unable to register input device ps: %s\n",
__func__, data->input_dev_ps->name);
goto unregister_als;
}
goto exit;
unregister_als:
input_unregister_device(data->input_dev_als);
input_free_device(data->input_dev_ps);
exit:
return err;
}
/*irq request subfunction of probe to reduce the complexity of probe function*/
static int apds993x_irq_init(struct apds993x_data *data,struct i2c_client *client)
{
int ret = 0;
if (data->platform_data->irq_gpio)
{
ret = gpio_request(data->platform_data->irq_gpio,"aps9930_irq_gpio");
if (ret)
{
APDS993X_ERR("%s, line %d:unable to request gpio [%d]\n", __func__, __LINE__,data->platform_data->irq_gpio);
return ret;
}
else
{
ret = gpio_direction_input(data->platform_data->irq_gpio);
if(ret)
{
APDS993X_ERR("%s, line %d: Failed to set gpio %d direction\n", __func__, __LINE__,data->platform_data->irq_gpio);
return ret;
}
}
}
client->irq = gpio_to_irq(data->platform_data->irq_gpio);
if (client->irq < 0) {
ret = -EINVAL;
APDS993X_ERR("%s, line %d:gpio_to_irq FAIL! IRQ=%d\n", __func__, __LINE__,data->platform_data->irq_gpio);
return ret;
}
data->irq = client->irq;
if (client->irq)
{
if (request_irq(data->irq, apds993x_interrupt,IRQF_TRIGGER_FALLING|IRQF_ONESHOT|IRQF_NO_SUSPEND, APDS993X_DRV_NAME, (void *)client) >= 0)
{
APDS993X_FLOW("%s, line %d:Received IRQ!\n", __func__, __LINE__);
disable_irq(data->irq);
}
else
{
APDS993X_ERR("%s, line %d:Failed to request IRQ!\n", __func__, __LINE__);
ret = -EINVAL;
return ret;
}
}
return ret;
}
static int sensor_regulator_power_on(struct apds993x_data *data, bool on)
{
int rc = 0;
if (!on) {
rc = regulator_disable(data->vdd);
if (rc) {
APDS993X_ERR("%s: Regulator vdd disable failed rc=%d\n", __func__, rc);
return rc;
}
rc = regulator_disable(data->vio);
if (rc) {
APDS993X_ERR("%s: Regulator vdd disable failed rc=%d\n", __func__, rc);
rc = regulator_enable(data->vdd);
APDS993X_ERR("%s:Regulator vio re-enabled rc=%d\n",__func__, rc);
/*
* Successfully re-enable regulator.
* Enter poweron delay and returns error.
*/
if (!rc) {
rc = -EBUSY;
goto enable_delay;
}
}
return rc;
} else {
rc = regulator_enable(data->vdd);
if (rc) {
APDS993X_ERR("%s:Regulator vdd enable failed rc=%d\n",__func__, rc);
return rc;
}
rc = regulator_enable(data->vio);
if (rc) {
APDS993X_ERR("%s:Regulator vio enable failed rc=%d\n", __func__,rc);
rc = regulator_disable(data->vdd);
return rc;
}
}
enable_delay:
msleep(130);
APDS993X_FLOW("%s:Sensor regulator power on =%d\n",__func__, on);
return rc;
}
static int sensor_platform_hw_power_on(bool on,struct apds993x_data *data)
{
int err = 0;
if (data->power_on != on) {
if (!IS_ERR_OR_NULL(data->pinctrl)) {
if (on)
/*after poweron,set the INT pin the default state*/
err = pinctrl_select_state(data->pinctrl,
data->pin_default);
if (err)
APDS993X_ERR("%s,line%d:Can't select pinctrl state\n", __func__, __LINE__);
}
err = sensor_regulator_power_on(data, on);
if (err)
APDS993X_ERR("%s,line%d:Can't configure regulator!\n", __func__, __LINE__);
else
data->power_on = on;
}
return err;
}
static int sensor_platform_hw_init(struct apds993x_data *data)
{
int error;
error = sensor_regulator_configure(data, true);
if (error < 0) {
APDS993X_ERR("%s,line %d:unable to configure regulator\n",__func__,__LINE__);
return error;
}
return 0;
}
static void sensor_platform_hw_exit(struct apds993x_data *data)
{
int error;
error = sensor_regulator_configure(data, false);
if (error < 0) {
APDS993X_ERR("%s,line %d:unable to configure regulator\n",__func__,__LINE__);
}
/*remove to the error handler program in probe because the gpio is not requested.*/
}
static int apds993x_pinctrl_init(struct apds993x_data *data)
{
struct i2c_client *client = data->client;
data->pinctrl = devm_pinctrl_get(&client->dev);
if (IS_ERR_OR_NULL(data->pinctrl)) {
APDS993X_ERR("%s,line %d:Failed to get pinctrl\n",__func__,__LINE__);
return PTR_ERR(data->pinctrl);
}
/*we have not set the sleep state of INT pin*/
data->pin_default =
pinctrl_lookup_state(data->pinctrl, "default");
if (IS_ERR_OR_NULL(data->pin_default)) {
APDS993X_ERR("%s,line %d:Failed to look up default state\n",__func__,__LINE__);
return PTR_ERR(data->pin_default);
}
return 0;
}
static int sensor_parse_dt(struct device *dev,
struct apds993x_platform_data *pdata)
{
struct device_node *np = dev->of_node;
unsigned int tmp;
int rc = 0;
/* set functions of platform data */
pdata->init = sensor_platform_hw_init;
pdata->exit = sensor_platform_hw_exit;
pdata->power_on = sensor_platform_hw_power_on;
/* irq gpio */
rc = of_get_named_gpio_flags(dev->of_node,
"avago,irq-gpio", 0, NULL);
if (rc < 0) {
APDS993X_ERR("%s,line %d:Unable to read irq gpio\n",__func__,__LINE__);
return rc;
}
pdata->irq_gpio = rc;
rc = of_property_read_u32(np, "avago,ga_a_value", &tmp);
if (rc) {
APDS993X_ERR("%s,line %d:Unable to read ga_a_value\n",__func__,__LINE__);
return rc;
}
pdata ->ga_a_value= tmp;
rc = of_property_read_u32(np, "avago,ga_c_value", &tmp);
if (rc) {
APDS993X_ERR("%s,line %d:Unable to read ga_c_value\n",__func__,__LINE__);
return rc;
}
pdata ->ga_c_value= tmp;
rc = of_property_read_u32(np, "avago,ga_d_value", &tmp);
if (rc) {
APDS993X_ERR("%s,line %d:Unable to read ga_d_value\n",__func__,__LINE__);
return rc;
}
pdata ->ga_d_value= tmp;
rc = of_property_read_u32(np, "avago,wave", &tmp);
if (rc) {
APDS993X_ERR("%s,line %d:Unable to read pwave_value\n",__func__,__LINE__);
return rc;
}
pdata ->pwave= tmp;
rc = of_property_read_u32(np, "avago,window", &tmp);
if (rc) {
APDS993X_ERR("%s,line %d:Unable to read pwindow_value\n",__func__,__LINE__);
return rc;
}
pdata ->pwindow= tmp;
rc = of_property_read_u32(np, "avago,ga_e_value", &tmp);
if (rc) {
APDS993X_ERR("%s,line %d:Unable to read ga_e_value\n",__func__,__LINE__);
return rc;
}
pdata ->ga_e_value= tmp;
rc = of_property_read_u32(np, "avago,ga_f_value", &tmp);
if (rc) {
APDS993X_ERR("%s,line %d:Unable to read ga_f_value\n",__func__,__LINE__);
return rc;
}
pdata ->ga_f_value= tmp;
rc = of_property_read_u32(np, "avago,als_B", &tmp);
if (rc) {
APDS993X_ERR("%s,line %d:Unable to read als_B\n",__func__,__LINE__);
return rc;
}
pdata ->als_B= tmp;
rc = of_property_read_u32(np, "avago,als_C", &tmp);
if (rc) {
APDS993X_ERR("%s,line %d:Unable to read als_C\n",__func__,__LINE__);
return rc;
}
pdata ->als_C= tmp;
rc = of_property_read_u32(np, "avago,als_D", &tmp);
if (rc) {
APDS993X_ERR("%s,line %d:Unable to read als_D\n",__func__,__LINE__);
return rc;
}
pdata ->als_D= tmp;
return 0;
}
/*************************************************
Function: debug_log_set
Description: this func is to set the value to control log enable or disable
Input: data:address of register
val:to control log enable or disable
Output: none
Return: 0
*************************************************/
static int debug_log_set(void *data, u64 val)
{
apds993x_debug_mask = (val >= 1) ? (int)val : 1;
return 0;
}
/*************************************************
Function: debug_log_get
Description: this func is to get the value of control log enable or disable
Input: data:address of register
Output: *val:to control log enable or disable
Return: 0
*************************************************/
static int debug_log_get(void *data, u64 *val)
{
*val = (u64)apds993x_debug_mask;
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(debug_mask_fops, debug_log_get, debug_log_set, "%llu\n");
static void apds993x_powerkey_screen_handler(struct work_struct *work)
{
struct apds993x_data *data = container_of((struct delayed_work *)work, struct apds993x_data, powerkey_work);
if(power_key_ps)
{
APDS993X_INFO("%s : power_key_ps (%d) press\n",__func__, power_key_ps);
power_key_ps=false;
input_report_abs(data->input_dev_ps, ABS_DISTANCE, APDS993X_FAR_FLAG);
input_sync(data->input_dev_ps);
}
schedule_delayed_work(&data->powerkey_work, msecs_to_jiffies(500));
}
/*
* I2C init/probing/exit functions
*/
static struct i2c_driver apds993x_driver;
static int apds993x_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent);
struct apds993x_data *data;
struct apds993x_platform_data *pdata;
int err = 0;
struct dentry *dentry_proximitylog = NULL;
struct dentry *dentry_file = NULL;
APDS993X_INFO("%s,line %d:PROBE START.\n",__func__,__LINE__);
if (client->dev.of_node) {
pdata = devm_kzalloc(&client->dev,
sizeof(struct apds993x_platform_data),
GFP_KERNEL);
if (!pdata) {
APDS993X_ERR("%s,line %d:Failed to allocate memory\n",__func__,__LINE__);
err =-ENOMEM;
goto exit;
}
client->dev.platform_data = pdata;
err = sensor_parse_dt(&client->dev, pdata);
if (err) {
APDS993X_ERR("%s: sensor_parse_dt() err\n", __func__);
goto exit_parse_dt;
}
} else {
pdata = client->dev.platform_data;
if (!pdata) {
APDS993X_ERR("%s,line %d:No platform data\n",__func__,__LINE__);
err = -ENODEV;
goto exit;
}
}
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE)) {
APDS993X_ERR("%s,line %d:Failed to i2c_check_functionality\n",__func__,__LINE__);
err = -EIO;
goto exit_parse_dt;
}
data = kzalloc(sizeof(struct apds993x_data), GFP_KERNEL);
if (!data) {
APDS993X_ERR("%s,line %d:Failed to allocate memory\n",__func__,__LINE__);
err = -ENOMEM;
goto exit_parse_dt;
}
data->platform_data = pdata;
data->client = client;
data->device_exist = false;
/* h/w initialization */
if (pdata->init)
err = pdata->init(data);
if (pdata->power_on)
err = pdata->power_on(true,data);
err = apds_dsm_init(data);
if(err < 0)
goto exit_uninit;
i2c_set_clientdata(client, data);
apds993x_parameter_init(data);
/* initialize pinctrl */
err = apds993x_pinctrl_init(data);
if (err) {
APDS993X_ERR("%s,line %d:Can't initialize pinctrl\n",__func__,__LINE__);
goto exit_unregister_dsm;
}
err = pinctrl_select_state(data->pinctrl, data->pin_default);
if (err) {
APDS993X_ERR("%s,line %d:Can't select pinctrl default state\n",__func__,__LINE__);
goto exit_unregister_dsm;
}
mutex_init(&data->update_lock);
mutex_init(&data->single_lock);
INIT_WORK(&data->dwork, apds993x_work_handler);
INIT_WORK(&data->als_dwork, apds993x_als_polling_work_handler);
INIT_DELAYED_WORK(&data->powerkey_work, apds993x_powerkey_screen_handler);
/* Initialize the APDS993X chip and judge who am i*/
err = apds993x_read_device_id(client);
if (err) {
APDS993X_ERR("%s: Failed to read apds993x\n", __func__);
goto exit_unregister_dsm;
}
err = apds993x_init_client(client);
if (err) {
APDS993X_ERR("%s: Failed to init apds993x\n", __func__);
goto exit_unregister_dsm;
}
err = apds993x_input_init(data);
if(err)
goto exit_unregister_dsm;
/* Register sysfs hooks */
err = sysfs_create_group(&client->dev.kobj, &apds993x_attr_group);
if (err)
goto exit_unregister_dev_ps;
wake_lock_init(&data->ps_report_wk, WAKE_LOCK_SUSPEND, "psensor_wakelock");
err=apds993x_irq_init(data,client);
if(err)
goto exit_remove_sysfs_group;
device_init_wakeup(&(client->dev), true);
err = apds993x_sensorclass_init(data,client);
if (err) {
APDS993X_ERR("%s: Unable to register to sensors class: %d\n",
__func__, err);
goto exit_free_irq;
}
apds993x_workqueue = create_workqueue("apds993x_work_queue");
if (!apds993x_workqueue)
{
APDS993X_ERR("%s: Create ps_workqueue fail.\n", __func__);
goto exit_unregister_sensorclass;
}
/* init hrtimer and call back function */
hrtimer_init(&data->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
data->timer.function = apds993x_als_timer_func;
set_sensors_list(L_SENSOR + P_SENSOR);
#ifdef CONFIG_HUAWEI_HW_DEV_DCT
set_hw_dev_flag(DEV_I2C_APS);
set_hw_dev_flag(DEV_I2C_L_SENSOR);
#endif
err = set_sensor_input(PS, data->input_dev_ps->dev.kobj.name);
if (err) {
APDS993X_ERR("%s set_sensor_input PS failed\n", __func__);
}
err = set_sensor_input(ALS, data->input_dev_als->dev.kobj.name);
if (err) {
APDS993X_ERR("%s set_sensor_input ALS failed\n", __func__);
}
/* create directory "hw_apds993x_log" */
dentry_proximitylog = debugfs_create_dir("hw_apds993x_log", NULL);
if(dentry_proximitylog)
{
/* create file named debug_mask at /sys/kernel/debug/hw_Proximity_log */
dentry_file = debugfs_create_file("debug_mask", 0664, dentry_proximitylog, NULL, &debug_mask_fops);
if (!dentry_file)
{
APDS993X_ERR("%s %d:Create log file error! \n", __func__, __LINE__);
debugfs_remove(dentry_file);
}
}
else
{
APDS993X_ERR("%s %d:Create log director error! \n", __func__, __LINE__);
}
if (pdata->power_on)
err = pdata->power_on(false,data);
APDS993X_INFO("%s: Support ver. %s enabled\n", __func__, DRIVER_VERSION);
data->device_exist = true;
return 0;
/* delete this,use one work queue*/
exit_unregister_sensorclass:
sensors_classdev_unregister(&data->als_cdev);
sensors_classdev_unregister(&data->ps_cdev);
exit_free_irq:
if (gpio_is_valid(data->platform_data->irq_gpio))
gpio_free(data->platform_data->irq_gpio);
free_irq(data->irq, client);
exit_remove_sysfs_group:
wake_lock_destroy(&data->ps_report_wk);
sysfs_remove_group(&client->dev.kobj, &apds993x_attr_group);
exit_unregister_dev_ps:
input_unregister_device(data->input_dev_ps);
input_unregister_device(data->input_dev_als);
exit_unregister_dsm:
apds_dsm_exit();
exit_uninit:
if (pdata->power_on)
pdata->power_on(false,data);
if (pdata->exit)
pdata->exit(data);
kfree(data);
exit_parse_dt:
/*remove it,because devm_kzalloc will release the memory automatically
if don't remove,there will be null pointer which lead to booting crush*/
exit:
return err;
}
static int apds993x_remove(struct i2c_client *client)
{
struct apds993x_data *data = i2c_get_clientdata(client);
struct apds993x_platform_data *pdata = data->platform_data;
/* Power down the device */
data->enable = 0x00;
apds993x_set_enable(client, data->enable);
wake_lock_destroy(&data->ps_report_wk);
sysfs_remove_group(&client->dev.kobj, &apds993x_attr_group);
input_unregister_device(data->input_dev_ps);
input_unregister_device(data->input_dev_als);
free_irq(client->irq, data);
hrtimer_cancel(&data->timer);
apds_dsm_exit();
if (pdata->power_on)
pdata->power_on(false,data);
if (pdata->exit)
pdata->exit(data);
kfree(data);
return 0;
}
static const struct i2c_device_id apds993x_id[] = {
{ "apds993x", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, apds993x_id);
static struct of_device_id apds993X_match_table[] = {
{ .compatible = "avago,apds9930",},
{ },
};
static struct i2c_driver apds993x_driver = {
.driver = {
.name = APDS993X_DRV_NAME,
.owner = THIS_MODULE,
.of_match_table = apds993X_match_table,
},
.probe = apds993x_probe,
.remove = apds993x_remove,
.suspend = apds993x_suspend,
.resume = apds993x_resume,
.id_table = apds993x_id,
};
static int __init apds993x_init(void)
{
return i2c_add_driver(&apds993x_driver);
}
static void __exit apds993x_exit(void)
{
/* destroy als and ps work queue */
if (apds993x_workqueue) {
destroy_workqueue(apds993x_workqueue);
apds993x_workqueue = NULL;
}
i2c_del_driver(&apds993x_driver);
}
MODULE_DESCRIPTION("APDS993X ambient light + proximity sensor driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRIVER_VERSION);
module_init(apds993x_init);
module_exit(apds993x_exit);
| qltsar/g620s | drivers/input/misc/apds993x_ls.c | C | gpl-2.0 | 73,166 |
/*****************************************************************************
*
* DOWNTIME.H - Header file for scheduled downtime functions
*
* Copyright (c) 2001-2009 Ethan Galstad (egalstad@nagios.org)
* Copyright (c) 2009-2011 Nagios Core Development Team and Community Contributors
* Copyright (c) 2009-2011 Icinga Development Team (http://www.icinga.org)
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
#ifndef _DOWNTIME_H
#define _DOWNTIME_H
#include "config.h"
#include "common.h"
#include "objects.h"
#ifdef __cplusplus
extern "C" {
#endif
/* SCHEDULED_DOWNTIME_ENTRY structure */
typedef struct scheduled_downtime_struct{
int type;
char *host_name;
char *service_description;
time_t entry_time;
time_t start_time;
time_t end_time;
int fixed;
unsigned long triggered_by;
unsigned long duration;
unsigned long downtime_id;
char *author;
char *comment;
int is_in_effect;
#ifdef NSCORE
unsigned long comment_id;
int start_flex_downtime;
int incremented_pending_downtime;
#endif
struct scheduled_downtime_struct *next;
}scheduled_downtime;
#ifdef NSCORE
int initialize_downtime_data(char *); /* initializes scheduled downtime data */
int cleanup_downtime_data(char *); /* cleans up scheduled downtime data */
int add_new_downtime(int,char *,char *,time_t,char *,char *,time_t,time_t,int,unsigned long,unsigned long,unsigned long *,int);
int add_new_host_downtime(char *,time_t,char *,char *,time_t,time_t,int,unsigned long,unsigned long,unsigned long *,int);
int add_new_service_downtime(char *,char *,time_t,char *,char *,time_t,time_t,int,unsigned long,unsigned long,unsigned long *,int);
int delete_host_downtime(unsigned long);
int delete_service_downtime(unsigned long);
int delete_downtime(int,unsigned long);
int schedule_downtime(int,char *,char *,time_t,char *,char *,time_t,time_t,int,unsigned long,unsigned long,unsigned long *);
int unschedule_downtime(int,unsigned long);
int register_downtime(int,unsigned long);
int handle_scheduled_downtime(scheduled_downtime *);
int handle_scheduled_downtime_by_id(unsigned long);
int check_pending_flex_host_downtime(host *);
int check_pending_flex_service_downtime(service *);
int check_for_expired_downtime(void);
#endif
int add_host_downtime(char *,time_t,char *,char *,time_t,time_t,int,unsigned long,unsigned long,unsigned long,int);
int add_service_downtime(char *,char *,time_t,char *,char *,time_t,time_t,int,unsigned long,unsigned long,unsigned long,int);
/* If you are going to be adding a lot of downtime in sequence, set
defer_downtime_sorting to 1 before you start and then call
sort_downtime afterwards. Things will go MUCH faster. */
extern int defer_downtime_sorting;
int add_downtime(int,char *,char *,time_t,char *,char *,time_t,time_t,int,unsigned long,unsigned long,unsigned long,int);
int sort_downtime(void);
scheduled_downtime *find_downtime(int,unsigned long);
scheduled_downtime *find_host_downtime(unsigned long);
scheduled_downtime *find_service_downtime(unsigned long);
scheduled_downtime *find_downtime_by_similar_content(int,char *,char *,char *,char *,time_t,time_t,int,unsigned long);
void free_downtime_data(void); /* frees memory allocated to scheduled downtime list */
int delete_downtime_by_hostname_service_description_start_time_comment(char *,char *,time_t,char *);
#ifdef __cplusplus
}
#endif
#endif
| formorer/icinga-core | include/downtime.h | C | gpl-2.0 | 4,141 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.